C/C++ API Reference
Loading...
Searching...
No Matches
limited_stream.h
1// Copyright 2025 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 "pw_status/try.h"
17#include "pw_stream/stream.h"
18
19namespace pw::stream {
20
22
28 public:
36 : writer_(writer), limit_(limit) {}
37
39 size_t limit() const { return limit_; }
40
45 void set_limit(size_t limit) { limit_ = limit; }
46
48 size_t bytes_written() const { return written_; }
49
50 private:
51 Writer& writer_;
52 size_t limit_;
53 size_t written_ = 0;
54
57 size_t remain() const {
58 if (limit() == kUnlimited) {
59 return kUnlimited;
60 }
61 if (written_ > limit_) {
62 return 0;
63 }
64 return limit_ - written_;
65 }
66
67 Status DoWrite(ConstByteSpan data) override {
68 // Write all or nothing.
69 if (data.size() > remain()) {
70 return Status::OutOfRange();
71 }
72 PW_TRY(writer_.Write(data));
73 written_ += data.size();
74 return OkStatus();
75 }
76
77 size_t ConservativeLimit(LimitType limit_type) const override {
78 switch (limit_type) {
79 case LimitType::kRead:
80 return 0;
81 case LimitType::kWrite:
82 return std::min(remain(), writer_.ConservativeWriteLimit());
83 }
84 }
85};
86
88
89} // namespace pw::stream
Definition: status.h:86
Definition: limited_stream.h:27
void set_limit(size_t limit)
Definition: limited_stream.h:45
size_t limit() const
Returns the current limit of this writer.
Definition: limited_stream.h:39
size_t bytes_written() const
Returns the number of bytes written to the stream.
Definition: limited_stream.h:48
Status DoWrite(ConstByteSpan data) override
Virtual Write() function implemented by derived classes.
Definition: limited_stream.h:67
size_t ConservativeLimit(LimitType limit_type) const override
Definition: limited_stream.h:77
LimitedStreamWriter(Writer &writer, size_t limit=kUnlimited)
Definition: limited_stream.h:35
Definition: stream.h:504
static constexpr size_t kUnlimited
Value returned from read/write limit if unlimited.
Definition: stream.h:66
Status Write(ConstByteSpan data)
Definition: stream.h:192
size_t ConservativeWriteLimit() const
Definition: stream.h:254
Definition: stream.h:440
constexpr Status OkStatus()
Definition: status.h:235