Coverage Report

Created: 2025-09-05 06:52

/src/serenity/Userland/Libraries/LibCompress/PackBitsDecoder.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org>
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#include "PackBitsDecoder.h"
8
#include <AK/MemoryStream.h>
9
10
namespace Compress::PackBits {
11
12
ErrorOr<ByteBuffer> decode_all(ReadonlyBytes bytes, Optional<u64> expected_output_size, CompatibilityMode mode)
13
962
{
14
    // This implementation uses unsigned values for the selector, as described in the PDF spec.
15
    // Note that this remains compatible with other implementations based on signed numbers.
16
17
962
    auto memory_stream = make<FixedMemoryStream>(bytes);
18
19
962
    ByteBuffer decoded_bytes;
20
21
962
    if (expected_output_size.has_value())
22
416
        TRY(decoded_bytes.try_ensure_capacity(*expected_output_size));
23
24
1.17M
    while (memory_stream->remaining() > 0 && decoded_bytes.size() < expected_output_size.value_or(NumericLimits<u64>::max())) {
25
1.17M
        auto const length = TRY(memory_stream->read_value<u8>());
26
27
1.17M
        if (length < 128) {
28
1.10M
            for (u8 i = 0; i <= length; ++i)
29
970k
                TRY(decoded_bytes.try_append(TRY(memory_stream->read_value<u8>())));
30
1.03M
        } else if (length > 128) {
31
1.03M
            auto const next_byte = TRY(memory_stream->read_value<u8>());
32
33
90.9M
            for (u8 i = 0; i < 257 - length; ++i)
34
89.9M
                TRY(decoded_bytes.try_append(next_byte));
35
1.03M
        } else {
36
885
            VERIFY(length == 128);
37
885
            if (mode == CompatibilityMode::PDF)
38
0
                break;
39
885
        }
40
1.17M
    }
41
42
863
    return decoded_bytes;
43
962
}
44
45
}