Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright (c) 2020, Andreas Kling <kling@serenityos.org> |
3 | | * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org> |
4 | | * |
5 | | * SPDX-License-Identifier: BSD-2-Clause |
6 | | */ |
7 | | |
8 | | #include <AK/Hex.h> |
9 | | #include <AK/StringBuilder.h> |
10 | | #include <AK/Types.h> |
11 | | #include <AK/Vector.h> |
12 | | |
13 | | namespace AK { |
14 | | |
15 | | ErrorOr<ByteBuffer> decode_hex(StringView input) |
16 | 0 | { |
17 | 0 | if ((input.length() % 2) != 0) |
18 | 0 | return Error::from_string_view_or_print_error_and_return_errno("Hex string was not an even length"sv, EINVAL); |
19 | | |
20 | 0 | auto output = TRY(ByteBuffer::create_zeroed(input.length() / 2)); |
21 | | |
22 | 0 | for (size_t i = 0; i < input.length() / 2; ++i) { |
23 | 0 | auto const c1 = decode_hex_digit(input[i * 2]); |
24 | 0 | if (c1 >= 16) |
25 | 0 | return Error::from_string_view_or_print_error_and_return_errno("Hex string contains invalid digit"sv, EINVAL); |
26 | | |
27 | 0 | auto const c2 = decode_hex_digit(input[i * 2 + 1]); |
28 | 0 | if (c2 >= 16) |
29 | 0 | return Error::from_string_view_or_print_error_and_return_errno("Hex string contains invalid digit"sv, EINVAL); |
30 | | |
31 | 0 | output[i] = (c1 << 4) + c2; |
32 | 0 | } |
33 | | |
34 | 0 | return { move(output) }; |
35 | 0 | } |
36 | | |
37 | | #ifdef KERNEL |
38 | | ErrorOr<NonnullOwnPtr<Kernel::KString>> encode_hex(ReadonlyBytes const input) |
39 | | { |
40 | | StringBuilder output(input.size() * 2); |
41 | | |
42 | | for (auto ch : input) |
43 | | TRY(output.try_appendff("{:02x}", ch)); |
44 | | |
45 | | return Kernel::KString::try_create(output.string_view()); |
46 | | } |
47 | | #else |
48 | | ByteString encode_hex(ReadonlyBytes const input) |
49 | 0 | { |
50 | 0 | StringBuilder output(input.size() * 2); |
51 | |
|
52 | 0 | for (auto ch : input) |
53 | 0 | output.appendff("{:02x}", ch); |
54 | |
|
55 | 0 | return output.to_byte_string(); |
56 | 0 | } |
57 | | #endif |
58 | | |
59 | | } |