Coverage Report

Created: 2026-07-25 07:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/AK/ConstrainedStream.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
3
 * Copyright (c) 2023, Tim Schumacher <timschumi@gmx.de>
4
 *
5
 * SPDX-License-Identifier: BSD-2-Clause
6
 */
7
8
#include <AK/ConstrainedStream.h>
9
10
namespace AK {
11
12
ConstrainedStream::ConstrainedStream(MaybeOwned<Stream> stream, u64 limit)
13
30.9k
    : m_stream(move(stream))
14
30.9k
    , m_limit(limit)
15
30.9k
{
16
30.9k
}
17
18
ErrorOr<Bytes> ConstrainedStream::read_some(Bytes bytes)
19
28.2M
{
20
28.2M
    if (bytes.size() >= m_limit)
21
14.1k
        bytes = bytes.trim(m_limit);
22
23
28.2M
    auto result = TRY(m_stream->read_some(bytes));
24
25
28.2M
    m_limit -= result.size();
26
27
28.2M
    return result;
28
28.2M
}
29
30
ErrorOr<void> ConstrainedStream::discard(size_t discarded_bytes)
31
22.0k
{
32
22.0k
    if (discarded_bytes > m_limit)
33
67
        return Error::from_string_literal("Trying to discard more bytes than allowed");
34
35
    // Note: This will remove more bytes from the limit than intended if a failing discard yields partial results.
36
    //       However, stopping early is most likely better than running over the end of the stream.
37
21.9k
    m_limit -= discarded_bytes;
38
21.9k
    TRY(m_stream->discard(discarded_bytes));
39
40
21.8k
    return {};
41
21.9k
}
42
43
ErrorOr<size_t> ConstrainedStream::write_some(ReadonlyBytes)
44
0
{
45
0
    return Error::from_errno(EBADF);
46
0
}
47
48
bool ConstrainedStream::is_eof() const
49
45.2M
{
50
45.2M
    return m_limit == 0 || m_stream->is_eof();
51
45.2M
}
52
53
bool ConstrainedStream::is_open() const
54
0
{
55
0
    return m_stream->is_open();
56
0
}
57
58
void ConstrainedStream::close()
59
0
{
60
0
}
61
62
}