From 3219ce3d61f42dfcbeb0483a24539cd7b8f4723b Mon Sep 17 00:00:00 2001 From: Idan Horowitz Date: Tue, 15 Feb 2022 23:25:25 +0200 Subject: [PATCH] AK: Return KString instead of String from encode_hex in the Kernel This let's us propagate allocation errors from this API. --- AK/Hex.cpp | 12 ++++++++++++ AK/Hex.h | 11 ++++++++++- AK/UUID.cpp | 15 ++++++++++----- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/AK/Hex.cpp b/AK/Hex.cpp index ca354779689..dfd0d410ef6 100644 --- a/AK/Hex.cpp +++ b/AK/Hex.cpp @@ -35,6 +35,17 @@ ErrorOr decode_hex(StringView input) return { move(output) }; } +#ifdef KERNEL +ErrorOr> encode_hex(const ReadonlyBytes input) +{ + StringBuilder output(input.size() * 2); + + for (auto ch : input) + TRY(output.try_appendff("{:02x}", ch)); + + return Kernel::KString::try_create(output.string_view()); +} +#else String encode_hex(const ReadonlyBytes input) { StringBuilder output(input.size() * 2); @@ -44,5 +55,6 @@ String encode_hex(const ReadonlyBytes input) return output.build(); } +#endif } diff --git a/AK/Hex.h b/AK/Hex.h index ba21c3a7619..b421e9ac259 100644 --- a/AK/Hex.h +++ b/AK/Hex.h @@ -8,9 +8,14 @@ #include #include -#include #include +#ifdef KERNEL +# include +#else +# include +#endif + namespace AK { constexpr u8 decode_hex_digit(char digit) @@ -26,7 +31,11 @@ constexpr u8 decode_hex_digit(char digit) ErrorOr decode_hex(StringView); +#ifdef KERNEL +ErrorOr> encode_hex(ReadonlyBytes); +#else String encode_hex(ReadonlyBytes); +#endif } diff --git a/AK/UUID.cpp b/AK/UUID.cpp index 8353c49c1ec..c04f10cd888 100644 --- a/AK/UUID.cpp +++ b/AK/UUID.cpp @@ -80,15 +80,20 @@ UUID::UUID(StringView uuid_string_view, Endianness endianness) ErrorOr> UUID::to_string() const { StringBuilder builder(36); - TRY(builder.try_append(encode_hex(m_uuid_buffer.span().trim(4)).view())); + auto nibble0 = TRY(encode_hex(m_uuid_buffer.span().trim(4))); + TRY(builder.try_append(nibble0->view())); TRY(builder.try_append('-')); - TRY(builder.try_append(encode_hex(m_uuid_buffer.span().slice(4).trim(2)).view())); + auto nibble1 = TRY(encode_hex(m_uuid_buffer.span().slice(4).trim(2))); + TRY(builder.try_append(nibble1->view())); TRY(builder.try_append('-')); - TRY(builder.try_append(encode_hex(m_uuid_buffer.span().slice(6).trim(2)).view())); + auto nibble2 = TRY(encode_hex(m_uuid_buffer.span().slice(6).trim(2))); + TRY(builder.try_append(nibble2->view())); TRY(builder.try_append('-')); - TRY(builder.try_append(encode_hex(m_uuid_buffer.span().slice(8).trim(2)).view())); + auto nibble3 = TRY(encode_hex(m_uuid_buffer.span().slice(8).trim(2))); + TRY(builder.try_append(nibble3->view())); TRY(builder.try_append('-')); - TRY(builder.try_append(encode_hex(m_uuid_buffer.span().slice(10).trim(6)).view())); + auto nibble4 = TRY(encode_hex(m_uuid_buffer.span().slice(10).trim(6))); + TRY(builder.try_append(nibble4->view())); return Kernel::KString::try_create(builder.string_view()); } #else