1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 // Adapters for using SharedFD as std::istream and std::ostream. 18 19 #ifndef CUTTLEFISH_COMMON_COMMON_LIBS_FS_SHARED_FD_STREAM_H_ 20 #define CUTTLEFISH_COMMON_COMMON_LIBS_FS_SHARED_FD_STREAM_H_ 21 22 #include <cstdio> 23 #include <istream> 24 #include <memory> 25 #include <ostream> 26 #include <streambuf> 27 28 #include "common/libs/fs/shared_fd.h" 29 30 namespace cuttlefish { 31 32 class SharedFDStreambuf : public std::streambuf { 33 public: 34 SharedFDStreambuf(SharedFD shared_fd); 35 36 private: 37 // Reading characters from the SharedFD. 38 int underflow() override; 39 std::streamsize xsgetn(char* dest, std::streamsize count) override; 40 41 // Write characters to the SharedFD. 42 int overflow(int c) override; 43 std::streamsize xsputn(const char* source, std::streamsize count) override; 44 45 int pbackfail(int c) override; 46 47 private: 48 SharedFD shared_fd_; 49 50 static constexpr const ptrdiff_t kUngetSize = 128; 51 static constexpr const ptrdiff_t kBufferSize = 4096 + kUngetSize; 52 std::unique_ptr<char[]> read_buffer_ = nullptr; 53 }; 54 55 class SharedFDIstream : public std::istream { 56 public: 57 SharedFDIstream(SharedFD shared_fd); 58 59 private: 60 SharedFDStreambuf buf_; 61 }; 62 63 class SharedFDOstream : public std::ostream { 64 public: 65 SharedFDOstream(SharedFD shared_fd); 66 67 private: 68 SharedFDStreambuf buf_; 69 }; 70 71 } // namespace cuttlefish 72 73 #endif