Serenity Operating System
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
13namespace AK {
14
15ErrorOr<ByteBuffer> decode_hex(StringView input)
16{
17 if ((input.length() % 2) != 0)
18 return Error::from_string_view_or_print_error_and_return_errno("Hex string was not an even length"sv, EINVAL);
19
20 auto output = TRY(ByteBuffer::create_zeroed(input.length() / 2));
21
22 for (size_t i = 0; i < input.length() / 2; ++i) {
23 auto const c1 = decode_hex_digit(input[i * 2]);
24 if (c1 >= 16)
25 return Error::from_string_view_or_print_error_and_return_errno("Hex string contains invalid digit"sv, EINVAL);
26
27 auto const c2 = decode_hex_digit(input[i * 2 + 1]);
28 if (c2 >= 16)
29 return Error::from_string_view_or_print_error_and_return_errno("Hex string contains invalid digit"sv, EINVAL);
30
31 output[i] = (c1 << 4) + c2;
32 }
33
34 return { move(output) };
35}
36
37#ifdef KERNEL
38ErrorOr<NonnullOwnPtr<Kernel::KString>> encode_hex(const ReadonlyBytes 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
48DeprecatedString encode_hex(const ReadonlyBytes input)
49{
50 StringBuilder output(input.size() * 2);
51
52 for (auto ch : input)
53 output.appendff("{:02x}", ch);
54
55 return output.to_deprecated_string();
56}
57#endif
58
59}