AK: Allow ConstrainedStream to discard bytes until the limit

This commit is contained in:
Lucas CHOLLET
2025-03-19 13:30:25 -04:00
committed by Tim Schumacher
parent abffc2723a
commit ce71f54d8e
3 changed files with 38 additions and 1 deletions

View File

@@ -29,7 +29,7 @@ ErrorOr<Bytes> ConstrainedStream::read_some(Bytes bytes)
ErrorOr<void> ConstrainedStream::discard(size_t discarded_bytes)
{
if (discarded_bytes >= m_limit)
if (discarded_bytes > m_limit)
return Error::from_string_literal("Trying to discard more bytes than allowed");
// Note: This will remove more bytes from the limit than intended if a failing discard yields partial results.

View File

@@ -21,6 +21,7 @@ set(AK_TEST_SOURCES
TestCircularDeque.cpp
TestCircularQueue.cpp
TestComplex.cpp
TestConstrainedStream.cpp
TestCoroutine.cpp
TestDisjointChunks.cpp
TestDistinctNumeric.cpp

View File

@@ -0,0 +1,36 @@
/*
* Copyright (c) 2025, Lucas Chollet <lucas.chollet@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibTest/TestCase.h>
#include <AK/Array.h>
#include <AK/ConstrainedStream.h>
#include <AK/MemoryStream.h>
static Array<u8, 4> base_data { 1, 2, 3, 4 };
TEST_CASE(basic_constraint)
{
auto memory_stream = make<FixedMemoryStream>(base_data.span());
ConstrainedStream constrained_stream { move(memory_stream), 2 };
Array<u8, 2> read;
TRY_OR_FAIL(constrained_stream.read_until_filled(read));
EXPECT_EQ(read.span(), base_data.span().trim(2));
EXPECT(constrained_stream.read_until_filled(read).is_error());
}
TEST_CASE(discard_until_constraint)
{
auto memory_stream = make<FixedMemoryStream>(base_data.span());
ConstrainedStream constrained_stream { move(memory_stream), 3 };
Array<u8, 2> read;
TRY_OR_FAIL(constrained_stream.read_until_filled(read));
EXPECT_EQ(read.span(), base_data.span().trim(2));
EXPECT(!constrained_stream.discard(1).is_error());
EXPECT(constrained_stream.discard(1).is_error());
}