Prathmesh Prabhu | 28b4a3b | 2014-03-28 11:52:09 -0700 | [diff] [blame] | 1 | // Copyright (c) 2014 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "shill/protobuf_lite_streams.h" |
| 6 | |
| 7 | #include <fcntl.h> |
| 8 | #include <sys/types.h> |
| 9 | |
Ben Chan | 11c213f | 2014-09-05 08:21:06 -0700 | [diff] [blame] | 10 | #include <base/files/file_util.h> |
Prathmesh Prabhu | 28b4a3b | 2014-03-28 11:52:09 -0700 | [diff] [blame] | 11 | #include <base/posix/eintr_wrapper.h> |
| 12 | |
| 13 | using google::protobuf::io::CopyingInputStream; |
| 14 | using google::protobuf::io::CopyingInputStreamAdaptor; |
| 15 | using std::string; |
| 16 | |
| 17 | namespace shill { |
| 18 | |
| 19 | CopyingInputStreamAdaptor *protobuf_lite_file_input_stream( |
| 20 | const string &file_path) { |
| 21 | int fd = HANDLE_EINTR(open(file_path.c_str(), O_RDONLY)); |
| 22 | if (fd == -1) { |
| 23 | PLOG(ERROR) << __func__ << ": " |
| 24 | << "Could not load protobuf file [" << file_path << "] "; |
Ben Chan | cc225ef | 2014-09-30 13:26:51 -0700 | [diff] [blame] | 25 | return nullptr; |
Prathmesh Prabhu | 28b4a3b | 2014-03-28 11:52:09 -0700 | [diff] [blame] | 26 | } |
| 27 | |
| 28 | auto *file_stream(new ProtobufLiteCopyingFileInputStream(fd)); |
| 29 | auto *adaptor(new CopyingInputStreamAdaptor( |
| 30 | static_cast<CopyingInputStream*>(file_stream))); |
| 31 | // Pass ownership of |file_stream|. |
| 32 | adaptor->SetOwnsCopyingStream(true); |
| 33 | return adaptor; |
| 34 | } |
| 35 | |
| 36 | |
| 37 | ProtobufLiteCopyingFileInputStream::ProtobufLiteCopyingFileInputStream(int fd) |
| 38 | : fd_(fd), |
Ben Chan | 6fbf64f | 2014-05-21 18:07:01 -0700 | [diff] [blame] | 39 | scoped_fd_closer_(fd_), |
Prathmesh Prabhu | 28b4a3b | 2014-03-28 11:52:09 -0700 | [diff] [blame] | 40 | previous_seek_failed_(false) {} |
| 41 | |
| 42 | ProtobufLiteCopyingFileInputStream::~ProtobufLiteCopyingFileInputStream() {} |
| 43 | |
| 44 | int ProtobufLiteCopyingFileInputStream::Read(void *buffer, int size) { |
| 45 | return HANDLE_EINTR(read(fd_, buffer, size)); |
| 46 | } |
| 47 | |
| 48 | int ProtobufLiteCopyingFileInputStream::Skip(int count) { |
| 49 | if (!previous_seek_failed_ && |
| 50 | lseek(fd_, count, SEEK_CUR) != static_cast<off_t>(-1)) { |
| 51 | // seek succeeded. |
| 52 | return count; |
| 53 | } |
| 54 | // Let's not attempt to seek again later. |
| 55 | previous_seek_failed_ = true; |
| 56 | return CopyingInputStream::Skip(count); |
| 57 | } |
| 58 | |
| 59 | } // namespace shill |