summaryrefslogtreecommitdiff
path: root/Tests/AK/TestMemoryStream.cpp
blob: b335609b8654738316fff778bec440bf3a19c64a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
 * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/MemoryStream.h>
#include <AK/String.h>
#include <LibTest/TestCase.h>

TEST_CASE(allocating_memory_stream_empty)
{
    AllocatingMemoryStream stream;

    EXPECT_EQ(stream.used_buffer_size(), 0ul);

    {
        Array<u8, 32> array;
        auto read_bytes = MUST(stream.read(array));
        EXPECT_EQ(read_bytes.size(), 0ul);
    }

    {
        auto offset = MUST(stream.offset_of("test"sv.bytes()));
        EXPECT(!offset.has_value());
    }
}

TEST_CASE(allocating_memory_stream_offset_of)
{
    AllocatingMemoryStream stream;
    MUST(stream.write_entire_buffer("Well Hello Friends! :^)"sv.bytes()));

    {
        auto offset = MUST(stream.offset_of(" "sv.bytes()));
        EXPECT(offset.has_value());
        EXPECT_EQ(offset.value(), 4ul);
    }

    {
        auto offset = MUST(stream.offset_of("W"sv.bytes()));
        EXPECT(offset.has_value());
        EXPECT_EQ(offset.value(), 0ul);
    }

    {
        auto offset = MUST(stream.offset_of(")"sv.bytes()));
        EXPECT(offset.has_value());
        EXPECT_EQ(offset.value(), 22ul);
    }

    {
        auto offset = MUST(stream.offset_of("-"sv.bytes()));
        EXPECT(!offset.has_value());
    }

    MUST(stream.discard(1));

    {
        auto offset = MUST(stream.offset_of("W"sv.bytes()));
        EXPECT(!offset.has_value());
    }

    {
        auto offset = MUST(stream.offset_of("e"sv.bytes()));
        EXPECT(offset.has_value());
        EXPECT_EQ(offset.value(), 0ul);
    }
}

TEST_CASE(allocating_memory_stream_offset_of_oob)
{
    AllocatingMemoryStream stream;
    // NOTE: This test is to make sure that offset_of() doesn't read past the end of the "initialized" data.
    //       So we have to assume some things about the behaviour of this class:
    //       - The chunk size is 4096 bytes.
    //       - A chunk is moved to the end when it's fully read from
    //       - A free chunk is used as-is, no new ones are allocated if one exists.

    // First, fill exactly one chunk.
    for (size_t i = 0; i < 256; ++i)
        MUST(stream.write_entire_buffer("AAAAAAAAAAAAAAAA"sv.bytes()));

    // Then discard it all.
    MUST(stream.discard(4096));
    // Now we can write into this chunk again, knowing that it's initialized to all 'A's.
    MUST(stream.write_entire_buffer("Well Hello Friends! :^)"sv.bytes()));

    {
        auto offset = MUST(stream.offset_of("A"sv.bytes()));
        EXPECT(!offset.has_value());
    }
}