1 // Copyright 2024 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <cstddef> 17 18 #include "pw_multibuf/multibuf.h" 19 #include "pw_stream/stream.h" 20 21 namespace pw::multibuf { 22 23 /// A readable, writable, and seekable ``Stream`` implementation backed by a 24 /// ``MultiBuf``. 25 class Stream : public stream::SeekableReaderWriter { 26 public: Stream(MultiBuf & multibuf)27 Stream(MultiBuf& multibuf) 28 : multibuf_(multibuf), 29 iterator_(multibuf_.begin()), 30 multibuf_offset_(0) {} 31 32 /// Returns the ``MultiBuf`` backing this stream. multibuf()33 constexpr const MultiBuf& multibuf() const { return multibuf_; } 34 35 private: 36 Status DoWrite(ConstByteSpan data) override; 37 38 StatusWithSize DoRead(ByteSpan destination) override; 39 40 /// Seeks the writer's cursor position within the multibuf. Only forward 41 /// seeking is permitted; attempting to seek backwards will result in an 42 /// `OUT_OF_RANGE`. This operation is `O(multibuf().Chunks().size())`. 43 Status DoSeek(ptrdiff_t offset, Whence origin) override; 44 DoTell()45 size_t DoTell() override { return multibuf_offset_; } 46 ConservativeLimit(LimitType)47 size_t ConservativeLimit(LimitType) const override { 48 return multibuf_.size() - multibuf_offset_; 49 } 50 51 MultiBuf& multibuf_; 52 MultiBuf::iterator iterator_; 53 size_t multibuf_offset_; 54 }; 55 56 } // namespace pw::multibuf 57