1 // Copyright 2020 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_bytes/span.h" 19 #include "pw_polyfill/language_feature_macros.h" 20 #include "pw_span/span.h" 21 #include "pw_status/status.h" 22 #include "pw_status/status_with_size.h" 23 #include "pw_stream/stream.h" 24 25 namespace pw::stream { 26 27 // Stream that silently drops written data and returns nothing on reads, similar 28 // to /dev/null. 29 class NullStream final : public SeekableReaderWriter { 30 public: 31 // Gives access to a global NullStream instance. It is not necessary to have 32 // multiple NullStream instances since they have no state and do nothing. Instance()33 static NullStream& Instance() { 34 PW_CONSTINIT static NullStream stream; 35 return stream; 36 } 37 38 private: DoWrite(ConstByteSpan)39 Status DoWrite(ConstByteSpan) final { return OkStatus(); } DoRead(ByteSpan)40 StatusWithSize DoRead(ByteSpan) final { return StatusWithSize::OutOfRange(); } DoSeek(ptrdiff_t,Whence)41 Status DoSeek(ptrdiff_t, Whence) final { return OkStatus(); } 42 }; 43 44 // Same as NullStream, but tracks the number of bytes written. 45 class CountingNullStream final : public SeekableReaderWriter { 46 public: CountingNullStream()47 constexpr CountingNullStream() : bytes_written_(0) {} 48 bytes_written()49 size_t bytes_written() const { return bytes_written_; } 50 51 private: DoWrite(ConstByteSpan data)52 Status DoWrite(ConstByteSpan data) final { 53 bytes_written_ += data.size(); 54 return OkStatus(); 55 } 56 DoRead(ByteSpan)57 StatusWithSize DoRead(ByteSpan) final { return StatusWithSize::OutOfRange(); } DoSeek(ptrdiff_t,Whence)58 Status DoSeek(ptrdiff_t, Whence) final { return OkStatus(); } 59 60 size_t bytes_written_; 61 }; 62 63 } // namespace pw::stream 64