Brian Silverman | f51499a | 2020-09-21 12:49:08 -0700 | [diff] [blame^] | 1 | #include "aos/events/logging/buffer_encoder.h" |
| 2 | |
| 3 | #include <fcntl.h> |
| 4 | #include <sys/stat.h> |
| 5 | #include <sys/types.h> |
| 6 | |
| 7 | #include "glog/logging.h" |
| 8 | |
| 9 | namespace aos::logger { |
| 10 | |
| 11 | void DummyEncoder::Encode(flatbuffers::DetachedBuffer &&in) { |
| 12 | CHECK(in.data()) << ": Encode called with nullptr."; |
| 13 | |
| 14 | total_bytes_ += in.size(); |
| 15 | queue_.emplace_back(std::move(in)); |
| 16 | } |
| 17 | |
| 18 | void DummyEncoder::Clear(const int n) { |
| 19 | CHECK_GE(n, 0); |
| 20 | CHECK_LE(static_cast<size_t>(n), queue_size()); |
| 21 | queue_.erase(queue_.begin(), queue_.begin() + n); |
| 22 | } |
| 23 | |
| 24 | std::vector<absl::Span<const uint8_t>> DummyEncoder::queue() const { |
| 25 | std::vector<absl::Span<const uint8_t>> queue; |
| 26 | queue.reserve(queue_.size()); |
| 27 | for (const auto &buffer : queue_) { |
| 28 | queue.emplace_back(buffer.data(), buffer.size()); |
| 29 | } |
| 30 | return queue; |
| 31 | } |
| 32 | |
| 33 | size_t DummyEncoder::queued_bytes() const { |
| 34 | size_t bytes = 0; |
| 35 | for (const auto &buffer : queue_) { |
| 36 | bytes += buffer.size(); |
| 37 | } |
| 38 | return bytes; |
| 39 | } |
| 40 | |
| 41 | DummyDecoder::DummyDecoder(std::string_view filename) |
| 42 | : fd_(open(std::string(filename).c_str(), O_RDONLY | O_CLOEXEC)) { |
| 43 | PCHECK(fd_ != -1) << ": Failed to open " << filename; |
| 44 | } |
| 45 | |
| 46 | DummyDecoder::~DummyDecoder() { |
| 47 | int status = close(fd_); |
| 48 | if (status != 0) { |
| 49 | PLOG(ERROR) << "DummyDecoder: Failed to close file"; |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | size_t DummyDecoder::Read(uint8_t *begin, uint8_t *end) { |
| 54 | if (end_of_file_) { |
| 55 | return 0; |
| 56 | } |
| 57 | const ssize_t count = read(fd_, begin, end - begin); |
| 58 | PCHECK(count >= 0) << ": Failed to read from file"; |
| 59 | if (count == 0) { |
| 60 | end_of_file_ = true; |
| 61 | } |
| 62 | return static_cast<size_t>(count); |
| 63 | } |
| 64 | |
| 65 | } // namespace aos::logger |