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