2020-12-12 22:35:14 +00:00
|
|
|
/*
|
2024-10-04 11:19:50 +00:00
|
|
|
* Copyright (c) 2020, Andreas Kling <andreas@ladybird.org>
|
2022-01-20 17:01:39 +00:00
|
|
|
* Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
|
2020-12-12 22:35:14 +00:00
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-12-12 22:35:14 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <AK/Hex.h>
|
|
|
|
#include <AK/StringBuilder.h>
|
|
|
|
#include <AK/Types.h>
|
|
|
|
#include <AK/Vector.h>
|
|
|
|
|
|
|
|
namespace AK {
|
|
|
|
|
2022-01-20 17:01:39 +00:00
|
|
|
ErrorOr<ByteBuffer> decode_hex(StringView input)
|
2020-12-12 22:35:14 +00:00
|
|
|
{
|
|
|
|
if ((input.length() % 2) != 0)
|
2023-02-04 12:18:36 +00:00
|
|
|
return Error::from_string_view_or_print_error_and_return_errno("Hex string was not an even length"sv, EINVAL);
|
2020-12-12 22:35:14 +00:00
|
|
|
|
2022-01-20 17:01:39 +00:00
|
|
|
auto output = TRY(ByteBuffer::create_zeroed(input.length() / 2));
|
2020-12-12 22:35:14 +00:00
|
|
|
|
2021-04-18 17:12:03 +00:00
|
|
|
for (size_t i = 0; i < input.length() / 2; ++i) {
|
2022-04-01 17:58:27 +00:00
|
|
|
auto const c1 = decode_hex_digit(input[i * 2]);
|
2020-12-12 22:35:14 +00:00
|
|
|
if (c1 >= 16)
|
2023-02-04 12:18:36 +00:00
|
|
|
return Error::from_string_view_or_print_error_and_return_errno("Hex string contains invalid digit"sv, EINVAL);
|
2020-12-12 22:35:14 +00:00
|
|
|
|
2022-04-01 17:58:27 +00:00
|
|
|
auto const c2 = decode_hex_digit(input[i * 2 + 1]);
|
2020-12-12 22:35:14 +00:00
|
|
|
if (c2 >= 16)
|
2023-02-04 12:18:36 +00:00
|
|
|
return Error::from_string_view_or_print_error_and_return_errno("Hex string contains invalid digit"sv, EINVAL);
|
2020-12-12 22:35:14 +00:00
|
|
|
|
|
|
|
output[i] = (c1 << 4) + c2;
|
|
|
|
}
|
|
|
|
|
2022-01-20 17:01:39 +00:00
|
|
|
return { move(output) };
|
2020-12-12 22:35:14 +00:00
|
|
|
}
|
|
|
|
|
2024-04-18 19:32:56 +00:00
|
|
|
ByteString encode_hex(ReadonlyBytes const input)
|
2020-12-12 22:35:14 +00:00
|
|
|
{
|
|
|
|
StringBuilder output(input.size() * 2);
|
|
|
|
|
|
|
|
for (auto ch : input)
|
2021-02-09 15:08:11 +00:00
|
|
|
output.appendff("{:02x}", ch);
|
2020-12-12 22:35:14 +00:00
|
|
|
|
2023-12-16 14:19:34 +00:00
|
|
|
return output.to_byte_string();
|
2020-12-12 22:35:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|