Serenity Operating System
at master 93 lines 2.6 kB view raw
1/* 2 * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/MemoryStream.h> 8#include <AK/String.h> 9#include <LibTest/TestCase.h> 10 11TEST_CASE(allocating_memory_stream_empty) 12{ 13 AllocatingMemoryStream stream; 14 15 EXPECT_EQ(stream.used_buffer_size(), 0ul); 16 17 { 18 Array<u8, 32> array; 19 auto read_bytes = MUST(stream.read_some(array)); 20 EXPECT_EQ(read_bytes.size(), 0ul); 21 } 22 23 { 24 auto offset = MUST(stream.offset_of("test"sv.bytes())); 25 EXPECT(!offset.has_value()); 26 } 27} 28 29TEST_CASE(allocating_memory_stream_offset_of) 30{ 31 AllocatingMemoryStream stream; 32 MUST(stream.write_until_depleted("Well Hello Friends! :^)"sv.bytes())); 33 34 { 35 auto offset = MUST(stream.offset_of(" "sv.bytes())); 36 EXPECT(offset.has_value()); 37 EXPECT_EQ(offset.value(), 4ul); 38 } 39 40 { 41 auto offset = MUST(stream.offset_of("W"sv.bytes())); 42 EXPECT(offset.has_value()); 43 EXPECT_EQ(offset.value(), 0ul); 44 } 45 46 { 47 auto offset = MUST(stream.offset_of(")"sv.bytes())); 48 EXPECT(offset.has_value()); 49 EXPECT_EQ(offset.value(), 22ul); 50 } 51 52 { 53 auto offset = MUST(stream.offset_of("-"sv.bytes())); 54 EXPECT(!offset.has_value()); 55 } 56 57 MUST(stream.discard(1)); 58 59 { 60 auto offset = MUST(stream.offset_of("W"sv.bytes())); 61 EXPECT(!offset.has_value()); 62 } 63 64 { 65 auto offset = MUST(stream.offset_of("e"sv.bytes())); 66 EXPECT(offset.has_value()); 67 EXPECT_EQ(offset.value(), 0ul); 68 } 69} 70 71TEST_CASE(allocating_memory_stream_offset_of_oob) 72{ 73 AllocatingMemoryStream stream; 74 // NOTE: This test is to make sure that offset_of() doesn't read past the end of the "initialized" data. 75 // So we have to assume some things about the behaviour of this class: 76 // - The chunk size is 4096 bytes. 77 // - A chunk is moved to the end when it's fully read from 78 // - A free chunk is used as-is, no new ones are allocated if one exists. 79 80 // First, fill exactly one chunk. 81 for (size_t i = 0; i < 256; ++i) 82 MUST(stream.write_until_depleted("AAAAAAAAAAAAAAAA"sv.bytes())); 83 84 // Then discard it all. 85 MUST(stream.discard(4096)); 86 // Now we can write into this chunk again, knowing that it's initialized to all 'A's. 87 MUST(stream.write_until_depleted("Well Hello Friends! :^)"sv.bytes())); 88 89 { 90 auto offset = MUST(stream.offset_of("A"sv.bytes())); 91 EXPECT(!offset.has_value()); 92 } 93}