From ce42fa971b38d77026cde7532a373a83ca1083d4 Mon Sep 17 00:00:00 2001 From: Brisk Date: Tue, 11 Feb 2025 09:58:06 +0100 Subject: [PATCH] Use std::byte for Bytes type --- examples/showcase/src/ShowcaseComponent.cpp | 2 +- include/brisk/core/BasicTypes.hpp | 31 +++++---- include/brisk/core/Bytes.hpp | 9 +-- include/brisk/core/Cryptography.hpp | 6 +- include/brisk/core/Json.hpp | 4 +- include/brisk/core/Resources.hpp | 22 ++++--- include/brisk/core/Stream.hpp | 68 +++++++++++--------- include/brisk/graphics/internal/Sprites.hpp | 12 ++-- src/core/Bytes.cpp | 18 +++--- src/core/Bytes_test.cpp | 26 +++++--- src/core/Catch2Utils.hpp | 4 +- src/core/Compression_Brotli.cpp | 27 ++++---- src/core/Compression_GZip.cpp | 21 +++--- src/core/Compression_LZ4.cpp | 27 ++++---- src/core/Cryptography.cpp | 19 +++--- src/core/IO.cpp | 10 +-- src/core/IO_Windows.cpp | 4 +- src/core/Json.cpp | 15 +++-- src/core/Json_test.cpp | 23 +++---- src/core/Stream.cpp | 26 ++++---- src/core/Stream_test.cpp | 4 +- src/graphics/Fonts.cpp | 2 +- src/graphics/Html.cpp | 16 ++--- src/graphics/ImageFormats_bmp.cpp | 6 +- src/graphics/ImageFormats_jpeg.cpp | 11 ++-- src/graphics/ImageFormats_png.cpp | 2 +- src/graphics/ImageFormats_webp.cpp | 10 +-- src/graphics/Renderer_test.cpp | 2 +- src/graphics/WebGPURenderer/RenderDevice.cpp | 6 +- src/network/Fetch.cpp | 4 +- src/window/KeyCodes_Windows.cpp | 3 +- src/window/PlatformWindow_Darwin.mm | 2 +- src/window/PlatformWindow_Linux.cpp | 2 +- 33 files changed, 236 insertions(+), 208 deletions(-) diff --git a/examples/showcase/src/ShowcaseComponent.cpp b/examples/showcase/src/ShowcaseComponent.cpp index dbe24f0..8c84fa6 100644 --- a/examples/showcase/src/ShowcaseComponent.cpp +++ b/examples/showcase/src/ShowcaseComponent.cpp @@ -171,7 +171,7 @@ void ShowcaseComponent::configureWindow(RC window) { } void ShowcaseComponent::saveScreenshot(RC image) { - std::vector bytes = pngEncode(image); + Bytes bytes = pngEncode(image); if (auto file = showSaveDialog({ FileDialogFilter{ "*.png", "PNG image"_tr } }, defaultFolder(DefaultFolder::Pictures))) { if (auto s = writeBytes(*file, bytes)) { diff --git a/include/brisk/core/BasicTypes.hpp b/include/brisk/core/BasicTypes.hpp index 98af964..3a3049f 100644 --- a/include/brisk/core/BasicTypes.hpp +++ b/include/brisk/core/BasicTypes.hpp @@ -39,6 +39,10 @@ namespace Brisk { using namespace std::literals::string_view_literals; using namespace std::literals::string_literals; +constexpr std::byte operator""_b(unsigned long long n) { + return static_cast(n); +} + /** * @brief Creates a `std::span` representing a view over a single mutable element. * @@ -73,25 +77,20 @@ std::span one(const T& value) noexcept { return std::span{ &value, 1 }; } -/** - * @brief Type alias for a single byte (8-bit unsigned integer). - */ -using byte = uint8_t; - /** * @brief Type alias for a vector of bytes. */ -using Bytes = std::vector; +using Bytes = std::vector; /** * @brief Type alias for a non-modifiable view of a sequence of bytes. */ -using BytesView = std::span; +using BytesView = std::span; /** * @brief Type alias for a modifiable view of a sequence of bytes. */ -using BytesMutableView = std::span; +using BytesMutableView = std::span; #ifdef BRISK_USE_CHAR8_T /** @@ -233,7 +232,7 @@ template inline BytesView asBytesView(const Type& value) requires simpleMemoryRepresentation { - return BytesView(reinterpret_cast(std::addressof(value)), sizeof(Type)); + return BytesView(reinterpret_cast(std::addressof(value)), sizeof(Type)); } /** @@ -249,7 +248,7 @@ inline BytesView toBytesView(Container&& cont) requires std::is_constructible_v, Container&> { std::span sp(cont); - return BytesView(reinterpret_cast(sp.data()), sp.size_bytes()); + return BytesView(reinterpret_cast(sp.data()), sp.size_bytes()); } /** @@ -260,7 +259,7 @@ inline BytesView toBytesView(Container&& cont) */ template inline BytesView toBytesView(const char (&str)[N]) { - return BytesView(reinterpret_cast(str), N - 1); + return BytesView(reinterpret_cast(str), N - 1); } /** @@ -271,7 +270,7 @@ inline BytesView toBytesView(const char (&str)[N]) { */ template inline BytesView toBytesView(const char8_t (&str)[N]) { - return BytesView(reinterpret_cast(str), N - 1); + return BytesView(reinterpret_cast(str), N - 1); } /** @@ -282,7 +281,7 @@ inline BytesView toBytesView(const char8_t (&str)[N]) { */ template inline BytesView toBytesView(const char16_t (&str)[N]) { - return BytesView(reinterpret_cast(str), (N - 1) * sizeof(char16_t)); + return BytesView(reinterpret_cast(str), (N - 1) * sizeof(char16_t)); } /** @@ -293,7 +292,7 @@ inline BytesView toBytesView(const char16_t (&str)[N]) { */ template inline BytesView toBytesView(const char32_t (&str)[N]) { - return BytesView(reinterpret_cast(str), (N - 1) * sizeof(char32_t)); + return BytesView(reinterpret_cast(str), (N - 1) * sizeof(char32_t)); } /** @@ -304,7 +303,7 @@ inline BytesView toBytesView(const char32_t (&str)[N]) { */ template inline BytesView toBytesView(const wchar_t (&str)[N]) { - return BytesView(reinterpret_cast(str), (N - 1) * sizeof(wchar_t)); + return BytesView(reinterpret_cast(str), (N - 1) * sizeof(wchar_t)); } /** @@ -320,7 +319,7 @@ inline BytesMutableView toBytesMutableView(Container&& cont) requires requires { std::span{ cont }; } { std::span sp(cont); - return BytesMutableView(reinterpret_cast(sp.data()), sp.size_bytes()); + return BytesMutableView(reinterpret_cast(sp.data()), sp.size_bytes()); } /** diff --git a/include/brisk/core/Bytes.hpp b/include/brisk/core/Bytes.hpp index 0ff28c2..6cf0f10 100644 --- a/include/brisk/core/Bytes.hpp +++ b/include/brisk/core/Bytes.hpp @@ -29,8 +29,6 @@ namespace Brisk { -using Bytes = std::vector; - /// @brief Converts string in Hex format to span of bytes /// @returns number of bytes written or SIZE_MAX in case of error [[nodiscard]] size_t fromHex(BytesMutableView data, std::string_view encoded); @@ -49,8 +47,7 @@ using Bytes = std::vector; /// @brief Converts span of bytes to string in Base64 format /// @returns number of characters written or SIZE_MAX in case of error -[[nodiscard]] size_t toBase64(std::span encoded, BytesView data, bool urlSafe = false, - bool pad = true); +[[nodiscard]] size_t toBase64(std::span encoded, BytesView data, bool urlSafe = false, bool pad = true); [[nodiscard]] optional fromBase64(std::string_view encoded, bool urlSafe = false, bool strict = false); [[nodiscard]] std::string toBase64(BytesView data, bool urlSafe = false, bool pad = true); @@ -236,7 +233,7 @@ struct FixedBytes { return Brisk::toBase64({ data(), size() }, urlSafe, pad); } - using value_type = uint8_t; + using value_type = std::byte; using size_type = size_t; using pointer = value_type*; using const_pointer = const value_type*; @@ -279,7 +276,7 @@ struct FixedBytes { return data() + size(); } - uint8_t m_data[Size]; + value_type m_data[Size]; }; template diff --git a/include/brisk/core/Cryptography.hpp b/include/brisk/core/Cryptography.hpp index 2fc304b..d5eec75 100644 --- a/include/brisk/core/Cryptography.hpp +++ b/include/brisk/core/Cryptography.hpp @@ -292,10 +292,14 @@ struct Hasher { * @param size The number of bytes to write. * @return True if the write operation was successful, otherwise false. */ - bool write(const uint8_t* data, size_t size) { + bool write(const std::byte* data, size_t size) { return write({ data, size }); } + bool write(const uint8_t* data, size_t size) { + return write(reinterpret_cast(data), size); + } + /** The hashing method used by this hasher. */ HashMethod method; diff --git a/include/brisk/core/Json.hpp b/include/brisk/core/Json.hpp index 882dcd9..dd7ad02 100644 --- a/include/brisk/core/Json.hpp +++ b/include/brisk/core/Json.hpp @@ -517,7 +517,7 @@ struct Json : protected JsonVariant { * @brief Converts the current Json object to a MessagePack byte array. * @return A vector of bytes representing the MessagePack format. */ - std::vector toMsgPack() const; + Bytes toMsgPack() const; /** * @brief Parses a MessagePack byte array and returns a Json object. @@ -933,7 +933,7 @@ inline bool fromJson(const Json& b, std::set& v) { template inline bool toJson(Json& b, const std::vector& v) { if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) { - b = toHex(v); + b = toHex(toBytesView(v)); return true; } else { JsonArray a(v.size()); diff --git a/include/brisk/core/Resources.hpp b/include/brisk/core/Resources.hpp index c5875a0..06bbcea 100644 --- a/include/brisk/core/Resources.hpp +++ b/include/brisk/core/Resources.hpp @@ -46,21 +46,22 @@ inline bool resourceExists(std::string_view name) { return rsrc && *rsrc->size > 0; } -inline std::vector loadResource(std::string_view name, bool emptyOk = false) { +inline Bytes loadResource(std::string_view name, bool emptyOk = false) { const Internal::ResourceEntry* rsrc = Internal::lookupResource(name); if ((!rsrc || *rsrc->size == 0) && emptyOk) { return {}; } BRISK_ASSERT(rsrc); if (rsrc->compression == Internal::ResourceCompression::None) { - return std::vector(rsrc->data, rsrc->data + *rsrc->size); + return Bytes((const std::byte*)rsrc->data, (const std::byte*)rsrc->data + *rsrc->size); } - return compressionDecode(static_cast(rsrc->compression), - std::span(rsrc->data, rsrc->data + *rsrc->size)); + return compressionDecode( + static_cast(rsrc->compression), + BytesView((const std::byte*)rsrc->data, (const std::byte*)rsrc->data + *rsrc->size)); } -inline const std::vector& loadResourceCached(std::string name, bool emptyOk = false) { - static std::map> cache; +inline const Bytes& loadResourceCached(std::string name, bool emptyOk = false) { + static std::map cache; auto data = loadResource(name, emptyOk); auto it = cache.insert_or_assign(std::move(name), std::move(data)); return it.first->second; @@ -73,11 +74,12 @@ inline std::string loadResourceText(std::string_view name, bool emptyOk = false) } BRISK_ASSERT(rsrc); if (rsrc->compression == Internal::ResourceCompression::None) { - return std::string(rsrc->data, rsrc->data + *rsrc->size); + return std::string((const char*)rsrc->data, (const char*)rsrc->data + *rsrc->size); } - auto bytes = compressionDecode(static_cast(rsrc->compression), - std::span(rsrc->data, rsrc->data + *rsrc->size)); - return std::string(bytes.data(), bytes.data() + bytes.size()); + auto bytes = compressionDecode( + static_cast(rsrc->compression), + BytesView((const std::byte*)rsrc->data, (const std::byte*)rsrc->data + *rsrc->size)); + return std::string((const char*)bytes.data(), (const char*)bytes.data() + bytes.size()); } inline const std::string& loadResourceTextCached(std::string name, bool emptyOk = false) { diff --git a/include/brisk/core/Stream.hpp b/include/brisk/core/Stream.hpp index 284d1a6..988452e 100644 --- a/include/brisk/core/Stream.hpp +++ b/include/brisk/core/Stream.hpp @@ -196,7 +196,7 @@ class Stream { * @brief Retrieves the capabilities of the stream. * @return StreamCapabilities A bitmask representing the capabilities of the stream. */ - [[nodiscard]] virtual StreamCapabilities caps() const noexcept = 0; + [[nodiscard]] virtual StreamCapabilities caps() const noexcept = 0; /** * @brief Reads up to `size` bytes from the stream into the provided buffer. @@ -218,7 +218,11 @@ class Stream { * - If EOF is reached, the function returns the number of bytes read before EOF. * - If EOF is reached before any bytes are read, `Transferred::Eof` is returned. */ - [[nodiscard]] virtual Transferred read(uint8_t* data, size_t size) = 0; + [[nodiscard]] virtual Transferred read(std::byte* data, size_t size) = 0; + + [[nodiscard]] virtual Transferred read(uint8_t* data, size_t size) { + return read(reinterpret_cast(data), size); + } /** * @brief Writes up to `size` bytes from the provided buffer to the stream. @@ -236,7 +240,11 @@ class Stream { * - If any error occurs during the `WriteFile` call or no bytes are written, the function * returns `Transferred::Error`. */ - [[nodiscard]] virtual Transferred write(const uint8_t* data, size_t size) = 0; + [[nodiscard]] virtual Transferred write(const std::byte* data, size_t size) = 0; + + [[nodiscard]] virtual Transferred write(uint8_t* data, size_t size) { + return write(reinterpret_cast(data), size); + } /** * @brief Flushes the stream, ensuring that all buffered data is written to the underlying storage. @@ -320,18 +328,18 @@ class Stream { } /** - * @brief Reads data into a `std::span` buffer. - * @param data A `std::span` representing the buffer to read into. + * @brief Reads data into a `std::span` buffer. + * @param data A `std::span` representing the buffer to read into. * @return Transferred The result of the read operation. */ - [[nodiscard]] Transferred read(std::span data) { + [[nodiscard]] Transferred read(std::span data) { return read(data.data(), data.size()); } /** * @brief Reads data from the stream until the end is reached or an error occurs. * - * The `readUntilEnd` function reads data in chunks into a `std::vector` from the stream. It + * The `readUntilEnd` function reads data in chunks into a `std::vector` from the stream. It * continues reading until EOF is encountered or an error occurs. If an error occurs before all requested * data is read and `incompleteOk` is set to `false`, the function returns `std::nullopt` to indicate that * the read operation failed. @@ -339,11 +347,11 @@ class Stream { * @param incompleteOk If set to `true`, allows returning partial data if error occurs before the buffer * is completely filled. * - * @return std::optional> - * - A `std::vector` containing the data read from the stream if successful. + * @return std::optional> + * - A `std::vector` containing the data read from the stream if successful. * - `std::nullopt` if an error occurs and `incompleteOk` is `false`. */ - optional> readUntilEnd(bool incompleteOk = false); + optional> readUntilEnd(bool incompleteOk = false); /** * @brief Writes all data from the given span to the stream. @@ -351,10 +359,10 @@ class Stream { * The `writeAll` function attempts to write the entire range of data specified by `data` to the * stream. It ensures that the number of bytes written matches the size of the `data` span. * - * @param data A `std::span` containing the data to be written. + * @param data A `std::span` containing the data to be written. * @return bool True if the entire data was written successfully; otherwise, false. */ - [[nodiscard]] bool writeAll(std::span data); + [[nodiscard]] bool writeAll(std::span data); /** * @brief Writes the contents of a `string_view` to the stream. @@ -382,7 +390,7 @@ class SequentialReader : public Stream { StreamCapabilities caps() const noexcept override; - Transferred write(const uint8_t* data, size_t size) final; + Transferred write(const std::byte* data, size_t size) final; bool seek(intmax_t position, SeekOrigin origin = SeekOrigin::Beginning) override; @@ -408,7 +416,7 @@ class SequentialWriter : public Stream { StreamCapabilities caps() const noexcept override; - Transferred read(uint8_t* data, size_t size) final; + Transferred read(std::byte* data, size_t size) final; bool seek(intmax_t position, SeekOrigin origin = SeekOrigin::Beginning) override; @@ -454,7 +462,7 @@ class Writer : public SequentialWriter { /** * @class MemoryStream * @brief In-memory stream with full read/write capabilities. - * Internally stores data as a `std::vector` and grows as new data is written to the stream. + * Internally stores data as a `Bytes` and grows as new data is written to the stream. * * Supports all stream operations, including read, write, seek, and size queries. */ @@ -468,15 +476,15 @@ class MemoryStream : public Stream { /** * @brief Constructs a `MemoryStream` with the given initial data. - * @param data A `std::vector` containing the initial data for the stream. + * @param data A `std::vector` containing the initial data for the stream. */ - MemoryStream(std::vector data); + MemoryStream(std::vector data); [[nodiscard]] StreamCapabilities caps() const noexcept override; - [[nodiscard]] Transferred read(uint8_t* data, size_t size) override; + [[nodiscard]] Transferred read(std::byte* data, size_t size) override; - [[nodiscard]] Transferred write(const uint8_t* data, size_t size) override; + [[nodiscard]] Transferred write(const std::byte* data, size_t size) override; [[nodiscard]] bool flush() override; @@ -490,18 +498,18 @@ class MemoryStream : public Stream { /** * @brief Returns a const reference to the internal data buffer. - * @return A constant reference to the `std::vector` holding the stream's data. + * @return A constant reference to the `std::vector` holding the stream's data. */ - const std::vector& data() const; + const std::vector& data() const; /** * @brief Returns a non-const reference to the internal data buffer. - * @return A non-constant reference to the `std::vector` holding the stream's data. + * @return A non-constant reference to the `std::vector` holding the stream's data. */ - std::vector& data(); + std::vector& data(); private: - std::vector m_data; + std::vector m_data; uintmax_t m_position = 0; }; @@ -532,19 +540,19 @@ class SpanStream : public Stream { } } - [[nodiscard]] Transferred read(uint8_t* data, size_t size) override { + [[nodiscard]] Transferred read(std::byte* data, size_t size) override { if (size == 0) return Transferred::Error; size_t trSize = std::min(size, static_cast(m_data.size_bytes() - m_bytePosition)); if (trSize == 0) { return Transferred::Eof; } - memcpy(data, reinterpret_cast(m_data.data()) + m_bytePosition, trSize); + memcpy(data, reinterpret_cast(m_data.data()) + m_bytePosition, trSize); m_bytePosition += trSize; return trSize; } - [[nodiscard]] Transferred write(const uint8_t* data, size_t size) override { + [[nodiscard]] Transferred write(const std::byte* data, size_t size) override { if constexpr (readOnly) { throwException(ENotImplemented("write called for read-only SpanStream")); } else { @@ -552,7 +560,7 @@ class SpanStream : public Stream { return Transferred::Error; size = std::min(static_cast(m_data.size_bytes() - m_bytePosition), size); if (size) { - memcpy(reinterpret_cast(m_data.data()) + m_bytePosition, data, size); + memcpy(reinterpret_cast(m_data.data()) + m_bytePosition, data, size); m_bytePosition += size; } return size; @@ -616,7 +624,7 @@ class SpanStream : public Stream { uintmax_t m_bytePosition = 0; }; -using ByteMutableViewStream = SpanStream; -using ByteViewStream = SpanStream; +using ByteMutableViewStream = SpanStream; +using ByteViewStream = SpanStream; } // namespace Brisk diff --git a/include/brisk/graphics/internal/Sprites.hpp b/include/brisk/graphics/internal/Sprites.hpp index cb8a748..03607c2 100644 --- a/include/brisk/graphics/internal/Sprites.hpp +++ b/include/brisk/graphics/internal/Sprites.hpp @@ -12,12 +12,12 @@ struct SpriteResource { uint64_t id; Size size; - uint8_t* data() noexcept { - return std::launder(reinterpret_cast(this)) + sizeof(SpriteResource); + std::byte* data() noexcept { + return std::launder(reinterpret_cast(this)) + sizeof(SpriteResource); } - const uint8_t* data() const noexcept { - return std::launder(reinterpret_cast(this)) + sizeof(SpriteResource); + const std::byte* data() const noexcept { + return std::launder(reinterpret_cast(this)) + sizeof(SpriteResource); } BytesView bytes() const noexcept { @@ -30,10 +30,10 @@ struct SpriteResource { }; inline RC makeSprite(Size size) { - uint8_t* ptr = (uint8_t*)::malloc(sizeof(SpriteResource) + size.area()); + std::byte* ptr = (std::byte*)::malloc(sizeof(SpriteResource) + size.area()); SpriteResource* sprite = new (ptr) SpriteResource{ autoincremented(), size }; return std::shared_ptr(sprite, [](SpriteResource* ptr) { - ::free(reinterpret_cast(ptr)); + ::free(reinterpret_cast(ptr)); }); } diff --git a/src/core/Bytes.cpp b/src/core/Bytes.cpp index 54381cb..76a6f70 100644 --- a/src/core/Bytes.cpp +++ b/src/core/Bytes.cpp @@ -54,7 +54,7 @@ struct Hex { uint8_t h2 = hashmap[n2]; if (h1 == 0xff || h2 == 0xff) return SIZE_MAX; - data[i] = (h1 << 4) | h2; + data[i] = std::byte((h1 << 4) | h2); } return encoded.size() / 2; } @@ -65,7 +65,7 @@ struct Hex { } std::string_view alphabet = Hex::alphabet[upperCase]; for (size_t i = 0; i < data.size(); i++) { - uint8_t b = data[i]; + uint8_t b = uint8_t(data[i]); encoded[i * 2] = alphabet[(b >> 4) & 0x0f]; encoded[i * 2 + 1] = alphabet[b & 0x0f]; } @@ -126,7 +126,7 @@ struct Base64 { static size_t decode(BytesMutableView data, std::string_view encoded, bool urlSafe, bool strict) { const uint8_t* hashmap = Base64::hashmap[urlSafe]; - uint8_t* out = data.data(); + std::byte* out = data.data(); int g = 0; size_t y = 0; size_t z = 0; @@ -158,9 +158,9 @@ struct Base64 { if (++y == 4) { if (z + 3 > data.size()) return SIZE_MAX; - *out++ = (uint8_t)((t >> 16) & 255); - *out++ = (uint8_t)((t >> 8) & 255); - *out++ = (uint8_t)(t & 255); + *out++ = (std::byte)((t >> 16) & 255); + *out++ = (std::byte)((t >> 8) & 255); + *out++ = (std::byte)(t & 255); y = t = 0; } } @@ -174,9 +174,9 @@ struct Base64 { if (z + y - 1 > data.size()) return SIZE_MAX; if (y >= 2) - *out++ = (uint8_t)((t >> 16) & 255); + *out++ = (std::byte)((t >> 16) & 255); if (y == 3) - *out++ = (uint8_t)((t >> 8) & 255); + *out++ = (std::byte)((t >> 8) & 255); } return out - data.data(); @@ -189,7 +189,7 @@ struct Base64 { std::string_view alphabet = Base64::alphabet[urlSafe]; char* out = encoded.data(); - const uint8_t* in = data.data(); + const uint8_t* in = reinterpret_cast(data.data()); size_t round = data.size() / 3 * 3; for (size_t i = 0; i < round; i += 3) { *out++ = alphabet[(in[0] >> 2) & 0x3F]; diff --git a/src/core/Bytes_test.cpp b/src/core/Bytes_test.cpp index fc24d09..43ddac4 100644 --- a/src/core/Bytes_test.cpp +++ b/src/core/Bytes_test.cpp @@ -48,19 +48,23 @@ TEST_CASE("Convert uint32 vector to hex") { } TEST_CASE("Convert Bytes to uppercase hex representation") { - CHECK(toHex(Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }) == "0123456789ABCDEF"); + CHECK(toHex(Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }) == + "0123456789ABCDEF"); } TEST_CASE("Convert Bytes to lowercase hex representation") { - CHECK(toHex(Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }, false) == "0123456789abcdef"); + CHECK(toHex(Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }, false) == + "0123456789abcdef"); } TEST_CASE("Convert uppercase hex string to Bytes") { - CHECK(fromHex("0123456789ABCDEF") == Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }); + CHECK(fromHex("0123456789ABCDEF") == + Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }); } TEST_CASE("Convert lowercase hex string to Bytes") { - CHECK(fromHex("0123456789abcdef") == Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }); + CHECK(fromHex("0123456789abcdef") == + Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }); } TEST_CASE("Convert empty Bytes to Base64 representation") { @@ -80,7 +84,7 @@ TEST_CASE("Handle invalid Base64 input: '@'") { } TEST_CASE("Convert Base64 string with newlines to Bytes") { - CHECK(fromBase64("AAA\r\nAAA", false, false) == Bytes{ 0, 0, 0, 0 }); + CHECK(fromBase64("AAA\r\nAAA", false, false) == Bytes{ 0_b, 0_b, 0_b, 0_b }); } TEST_CASE("Invalid Base64 string with newlines returns nullopt") { @@ -97,19 +101,23 @@ TEST_CASE("Convert uint32 vector to Base64 with URL safe flag") { } TEST_CASE("Convert Bytes to Base64") { - CHECK(toBase64(Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }) == "ASNFZ4mrze8="); + CHECK(toBase64(Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }) == + "ASNFZ4mrze8="); } TEST_CASE("Convert Bytes to Base64 without padding") { - CHECK(toBase64(Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }, false) == "ASNFZ4mrze8="); + CHECK(toBase64(Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }, false) == + "ASNFZ4mrze8="); } TEST_CASE("Convert valid Base64 string to Bytes") { - CHECK(fromBase64("ASNFZ4mrze8=", false, true) == Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }); + CHECK(fromBase64("ASNFZ4mrze8=", false, true) == + Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }); } TEST_CASE("Duplicate check for valid Base64 string conversion") { - CHECK(fromBase64("ASNFZ4mrze8=", false, true) == Bytes{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }); + CHECK(fromBase64("ASNFZ4mrze8=", false, true) == + Bytes{ 0x01_b, 0x23_b, 0x45_b, 0x67_b, 0x89_b, 0xAB_b, 0xCD_b, 0xEF_b }); } TEST_CASE("Convert string of length 3 to CC") { diff --git a/src/core/Catch2Utils.hpp b/src/core/Catch2Utils.hpp index e43ec02..4a1f25c 100644 --- a/src/core/Catch2Utils.hpp +++ b/src/core/Catch2Utils.hpp @@ -78,8 +78,8 @@ struct StringMaker> { }; template <> -struct StringMaker> { - static std::string convert(const std::vector& value) { +struct StringMaker> { + static std::string convert(const std::vector& value) { return Brisk::toHex(value); } }; diff --git a/src/core/Compression_Brotli.cpp b/src/core/Compression_Brotli.cpp index 4888aa9..6401759 100644 --- a/src/core/Compression_Brotli.cpp +++ b/src/core/Compression_Brotli.cpp @@ -41,21 +41,21 @@ struct BrotliEncoderDeleter { class BrotliDecoder : public SequentialReader { public: explicit BrotliDecoder(RC reader) : reader(std::move(reader)) { - buffer.reset(new uint8_t[compressionBatchSize]); + buffer.reset(new std::byte[compressionBatchSize]); bufferUsed = 0; state.reset(BrotliDecoderCreateInstance(nullptr, nullptr, nullptr)); } - [[nodiscard]] Transferred read(uint8_t* data, size_t size) final { + [[nodiscard]] Transferred read(std::byte* data, size_t size) final { if (finished) return Transferred::Eof; size_t available_out = size; - uint8_t* next_out = data; + uint8_t* next_out = reinterpret_cast(data); size_t available_in; const uint8_t* next_in; do { - next_in = buffer.get(); + next_in = (const uint8_t*)buffer.get(); if (bufferUsed < compressionBatchSize) { Transferred sz = reader->read(buffer.get() + bufferUsed, compressionBatchSize - bufferUsed); if (sz.isError()) { @@ -97,7 +97,7 @@ class BrotliDecoder : public SequentialReader { private: RC reader; std::unique_ptr state; - std::unique_ptr buffer; + std::unique_ptr buffer; size_t bufferUsed = 0; bool finished = false; }; @@ -115,21 +115,21 @@ static_assert(brotliQuality(CompressionLevel::Normal) == (BROTLI_MAX_QUALITY + B class BrotliEncoder final : public SequentialWriter { public: explicit BrotliEncoder(RC writer, CompressionLevel level) : writer(std::move(writer)) { - buffer.reset(new uint8_t[compressionBatchSize]); + buffer.reset(new std::byte[compressionBatchSize]); state.reset(BrotliEncoderCreateInstance(nullptr, nullptr, nullptr)); BrotliEncoderSetParameter(state.get(), BROTLI_PARAM_QUALITY, brotliQuality(level)); BrotliEncoderSetParameter(state.get(), BROTLI_PARAM_LGWIN, brotliLgWin); } - [[nodiscard]] Transferred write(const uint8_t* data, size_t size) final { + [[nodiscard]] Transferred write(const std::byte* data, size_t size) final { if (size == 0) return 0; - const uint8_t* next_in = data; + const uint8_t* next_in = reinterpret_cast(data); size_t available_in = size; while (available_in > 0) { size_t available_out = compressionBatchSize; - uint8_t* next_out = buffer.get(); + uint8_t* next_out = (uint8_t*)buffer.get(); if (!BrotliEncoderCompressStream(state.get(), BROTLI_OPERATION_PROCESS, &available_in, &next_in, &available_out, &next_out, nullptr)) { return Transferred::Error; @@ -150,7 +150,7 @@ class BrotliEncoder final : public SequentialWriter { size_t avail_in = 0; while (!BrotliEncoderIsFinished(state.get())) { size_t avail_out = compressionBatchSize; - uint8_t* next_out = buffer.get(); + uint8_t* next_out = (uint8_t*)buffer.get(); if (!BrotliEncoderCompressStream(state.get(), BROTLI_OPERATION_FINISH, &avail_in, &next_in, &avail_out, &next_out, nullptr)) { return false; @@ -171,7 +171,7 @@ class BrotliEncoder final : public SequentialWriter { private: RC writer; std::unique_ptr state; - std::unique_ptr buffer; + std::unique_ptr buffer; }; RC brotliDecoder(RC reader) { @@ -191,7 +191,7 @@ Bytes brotliEncode(BytesView data, CompressionLevel level) { result.resize(sz); size_t encoded_size = result.size(); while (!BrotliEncoderCompress(q, brotliLgWin, BrotliEncoderMode::BROTLI_MODE_GENERIC, data.size(), - data.data(), &encoded_size, result.data())) { + (const uint8_t*)data.data(), &encoded_size, (uint8_t*)result.data())) { if (encoded_size == 0) return {}; result.resize(result.size() * 2); @@ -205,7 +205,8 @@ Bytes brotliDecode(BytesView data) { Bytes result; result.resize(data.size() * 3); size_t decoded_size = result.size(); - while (!BrotliDecoderDecompress(data.size(), data.data(), &decoded_size, result.data())) { + while (!BrotliDecoderDecompress(data.size(), (const uint8_t*)data.data(), &decoded_size, + (uint8_t*)result.data())) { if (decoded_size == 0) return {}; result.resize(result.size() * 2); diff --git a/src/core/Compression_GZip.cpp b/src/core/Compression_GZip.cpp index eba23b8..79f2e85 100644 --- a/src/core/Compression_GZip.cpp +++ b/src/core/Compression_GZip.cpp @@ -31,7 +31,7 @@ using Internal::compressionBatchSize; class ZLibDecoder : public SequentialReader { public: explicit ZLibDecoder(RC reader) : reader(std::move(reader)) { - buffer.reset(new uint8_t[compressionBatchSize]); + buffer.reset(new std::byte[compressionBatchSize]); bufferUsed = 0; strm.zalloc = Z_NULL; @@ -41,13 +41,13 @@ class ZLibDecoder : public SequentialReader { inflateInit2(&strm, MAX_WBITS | ACCEPT_GZIP_OR_ZLIB_HEADER); } - [[nodiscard]] Transferred read(uint8_t* data, size_t size) final { + [[nodiscard]] Transferred read(std::byte* data, size_t size) final { if (finished) return Transferred::Eof; strm.avail_out = size; strm.next_out = (Bytef*)data; do { - strm.next_in = buffer.get(); + strm.next_in = (Bytef*)buffer.get(); if (bufferUsed < compressionBatchSize) { Transferred sz = reader->read(buffer.get() + bufferUsed, compressionBatchSize - bufferUsed); if (sz.isError()) @@ -93,7 +93,7 @@ class ZLibDecoder : public SequentialReader { private: RC reader; z_stream strm{}; - std::unique_ptr buffer; + std::unique_ptr buffer; size_t bufferUsed = 0; bool finished = false; }; @@ -102,7 +102,7 @@ class ZLibEncoder final : public SequentialWriter { public: explicit ZLibEncoder(RC writer, CompressionLevel level, bool gzip = false) : writer(std::move(writer)) { - buffer.reset(new uint8_t[compressionBatchSize]); + buffer.reset(new std::byte[compressionBatchSize]); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; @@ -132,7 +132,7 @@ class ZLibEncoder final : public SequentialWriter { return compressionBatchSize; } - [[nodiscard]] Transferred write(const uint8_t* data, size_t size) final { + [[nodiscard]] Transferred write(const std::byte* data, size_t size) final { if (size == 0) return 0; strm.avail_in = (uInt)size; @@ -163,7 +163,7 @@ class ZLibEncoder final : public SequentialWriter { private: RC writer; z_stream strm{}; - std::unique_ptr buffer; + std::unique_ptr buffer; }; RC gzipDecoder(RC reader) { @@ -276,8 +276,8 @@ Bytes zlibEncode2(BytesView data, CompressionLevel level, bool gzip) { size_t sz = compressBound(data.size()); result.resize(sz); unsigned long destLen = result.size(); - while (int e = zlibCompress(result.data(), &destLen, data.data(), data.size(), static_cast(level), - gzip)) { + while (int e = zlibCompress((uint8_t*)result.data(), &destLen, (const uint8_t*)data.data(), data.size(), + static_cast(level), gzip)) { if (e != Z_BUF_ERROR) return {}; result.resize(result.size() * 2); @@ -300,7 +300,8 @@ Bytes zlibDecode(BytesView data) { size_t sz = data.size() * 4; result.resize(sz); unsigned long destLen = result.size(); - while (int e = zlibUncompress(result.data(), &destLen, data.data(), data.size())) { + while (int e = + zlibUncompress((uint8_t*)result.data(), &destLen, (const uint8_t*)data.data(), data.size())) { if (e != Z_BUF_ERROR) return {}; result.resize(result.size() * 2); diff --git a/src/core/Compression_LZ4.cpp b/src/core/Compression_LZ4.cpp index aebddf2..622dc30 100644 --- a/src/core/Compression_LZ4.cpp +++ b/src/core/Compression_LZ4.cpp @@ -12,7 +12,7 @@ using Internal::compressionBatchSize; class LZ4Decoder : public SequentialReader { public: explicit LZ4Decoder(RC reader) : reader(std::move(reader)) { - buffer.reset(new uint8_t[compressionBatchSize]); + buffer.reset(new std::byte[compressionBatchSize]); bufferSize = bufferConsumed = 0; LZ4F_errorCode_t result = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); if (LZ4F_isError(result)) { @@ -21,14 +21,14 @@ class LZ4Decoder : public SequentialReader { } } - [[nodiscard]] Transferred read(uint8_t* data, size_t size) final { + [[nodiscard]] Transferred read(std::byte* data, size_t size) final { if (!dctx) return Transferred::Error; if (finished) return Transferred::Eof; size_t available_out = size; - uint8_t* next_out = data; + uint8_t* next_out = (uint8_t*)data; size_t in_size; const uint8_t* next_in; @@ -42,7 +42,7 @@ class LZ4Decoder : public SequentialReader { } in_size = bufferSize - bufferConsumed; - next_in = buffer.get() + bufferConsumed; + next_in = (uint8_t*)buffer.get() + bufferConsumed; size_t next_out_size = available_out; size_t result = LZ4F_decompress(dctx, next_out, &next_out_size, next_in, &in_size, nullptr); @@ -86,7 +86,7 @@ class LZ4Decoder : public SequentialReader { private: RC reader; LZ4F_dctx* dctx = nullptr; - std::unique_ptr buffer; + std::unique_ptr buffer; size_t bufferSize = 0; size_t bufferConsumed = 0; bool finished = false; @@ -112,12 +112,13 @@ class LZ4Encoder final : public SequentialWriter { preferences.compressionLevel = lz4Level(level); bufferSize = LZ4F_compressBound(compressionBatchSize, &preferences); - buffer.reset(new uint8_t[bufferSize]); + buffer.reset(new std::byte[bufferSize]); } bool writeHeader() { - uint8_t headerData[LZ4F_HEADER_SIZE_MAX]; - size_t headerSize = LZ4F_compressBegin(cctx, headerData, std::size(headerData), &preferences); + std::byte headerData[LZ4F_HEADER_SIZE_MAX]; + size_t headerSize = + LZ4F_compressBegin(cctx, (uint8_t*)headerData, std::size(headerData), &preferences); if (LZ4F_isError(headerSize)) { LOG_ERROR(lz4, "LZ4F_compressBegin failed: {}", LZ4F_getErrorName(headerSize)); return false; @@ -125,7 +126,7 @@ class LZ4Encoder final : public SequentialWriter { return this->writer->write(headerData, headerSize) == headerSize; } - [[nodiscard]] Transferred write(const uint8_t* data, size_t size) final { + [[nodiscard]] Transferred write(const std::byte* data, size_t size) final { if (!headerWritten) { if (!writeHeader()) return Transferred::Error; @@ -136,12 +137,12 @@ class LZ4Encoder final : public SequentialWriter { return Transferred::Error; } - const uint8_t* next_in = data; + const uint8_t* next_in = (const uint8_t*)data; size_t available_in = size; while (available_in > 0) { size_t available_out = bufferSize; - uint8_t* next_out = buffer.get(); + uint8_t* next_out = (uint8_t*)buffer.get(); size_t result = LZ4F_compressUpdate(cctx, next_out, available_out, next_in, std::min(available_in, compressionBatchSize), nullptr); @@ -173,7 +174,7 @@ class LZ4Encoder final : public SequentialWriter { } size_t available_out = bufferSize; - uint8_t* next_out = buffer.get(); + uint8_t* next_out = (uint8_t*)buffer.get(); size_t result = LZ4F_compressEnd(cctx, next_out, available_out, nullptr); if (LZ4F_isError(result)) { @@ -203,7 +204,7 @@ class LZ4Encoder final : public SequentialWriter { bool headerWritten = false; LZ4F_cctx* cctx = nullptr; LZ4F_preferences_t preferences{}; - std::unique_ptr buffer; + std::unique_ptr buffer; size_t bufferSize{}; }; diff --git a/src/core/Cryptography.cpp b/src/core/Cryptography.cpp index 78706b0..333efb1 100644 --- a/src/core/Cryptography.cpp +++ b/src/core/Cryptography.cpp @@ -43,7 +43,7 @@ class RandomReader : public SequentialReader { public: RandomReader() = default; - Transferred read(uint8_t* data, size_t size) final { + Transferred read(std::byte* data, size_t size) final { return cryptoRandomInplaceSafe(BytesMutableView{ data, size }); } }; @@ -77,8 +77,8 @@ static void hashTo(HashMethod method, BytesView data, BytesMutableView hash) { const HashFunctions& desc = hashFunctions(method); hash_state state; desc.init(&state); - desc.process(&state, data.data(), data.size()); - desc.done(&state, hash.data()); + desc.process(&state, (const uint8_t*)data.data(), data.size()); + desc.done(&state, (uint8_t*)hash.data()); } template @@ -162,11 +162,11 @@ class HashStream final : public SequentialWriter { } } - Transferred write(const uint8_t* data, size_t size) final { + Transferred write(const std::byte* data, size_t size) final { if (failed || flushed) return Transferred::Error; - if (desc.process(&state, data, size) != CRYPT_OK) { + if (desc.process(&state, (const uint8_t*)data, size) != CRYPT_OK) { failed = true; return Transferred::Error; } @@ -187,9 +187,9 @@ class HashStream final : public SequentialWriter { } if (failed) { - std::fill(hash.begin(), hash.end(), 0); + std::fill(hash.begin(), hash.end(), 0_b); } else { - desc.done(&state, hash.data()); + desc.done(&state, (uint8_t*)hash.data()); } flushed = true; @@ -243,11 +243,12 @@ Hasher::Hasher(HashMethod method) noexcept : method(method) { bool Hasher::finish(BytesMutableView bytes) { auto desc = hashFunctions(method); BRISK_ASSERT(bytes.size() == desc.hashsize); - return desc.done(reinterpret_cast(state.data()), bytes.data()) == CRYPT_OK; + return desc.done(reinterpret_cast(state.data()), (uint8_t*)bytes.data()) == CRYPT_OK; } bool Hasher::write(BytesView data) { auto desc = hashFunctions(method); - return desc.process(reinterpret_cast(state.data()), data.data(), data.size()) == CRYPT_OK; + return desc.process(reinterpret_cast(state.data()), (const uint8_t*)data.data(), + data.size()) == CRYPT_OK; } } // namespace Brisk diff --git a/src/core/IO.cpp b/src/core/IO.cpp index 4e22ebc..361d5bc 100644 --- a/src/core/IO.cpp +++ b/src/core/IO.cpp @@ -144,7 +144,7 @@ class FileStream final : public Stream { return IO_TELL_64(m_file); } - [[nodiscard]] Transferred read(uint8_t* data, size_t size) final { + [[nodiscard]] Transferred read(std::byte* data, size_t size) final { if (!m_file || ferror(m_file)) return Transferred::Error; if (feof(m_file)) @@ -152,7 +152,7 @@ class FileStream final : public Stream { return fread(data, 1, size, m_file); } - [[nodiscard]] Transferred write(const uint8_t* data, size_t size) final { + [[nodiscard]] Transferred write(const std::byte* data, size_t size) final { if (!m_file || ferror(m_file)) return Transferred::Error; return fwrite(data, 1, size, m_file); @@ -201,7 +201,7 @@ expected, IOError> openFileForWriting(const fs::path& filePath, bool optional writeFromReader(RC dest, RC src, size_t bufSize) { uintmax_t transferred = 0; - auto buf = std::unique_ptr(new uint8_t[bufSize]); + auto buf = std::unique_ptr(new std::byte[bufSize]); Transferred rd; while ((rd = src->read(buf.get(), bufSize))) { if (dest->write(buf.get(), rd.bytes()) != rd.bytes()) @@ -228,9 +228,9 @@ expected readBytes(const fs::path& file_name) { expected readUtf8(const fs::path& file_name, bool removeBOM) { return readBytes(file_name).map([removeBOM](const Bytes& b) { if (removeBOM) - return std::string(utf8SkipBom(std::string(b.begin(), b.end()))); + return std::string(utf8SkipBom(std::string((const char*)b.data(), b.size()))); else - return std::string(b.begin(), b.end()); + return std::string((const char*)b.data(), b.size()); }); } diff --git a/src/core/IO_Windows.cpp b/src/core/IO_Windows.cpp index 991d07f..3fa68da 100644 --- a/src/core/IO_Windows.cpp +++ b/src/core/IO_Windows.cpp @@ -115,7 +115,7 @@ class Win32HandleStream final : public Stream { return result.QuadPart; } - [[nodiscard]] Transferred read(uint8_t* data, size_t size) final { + [[nodiscard]] Transferred read(std::byte* data, size_t size) final { if (!m_handle) return Transferred::Error; @@ -140,7 +140,7 @@ class Win32HandleStream final : public Stream { return size; } - [[nodiscard]] Transferred write(const uint8_t* data, size_t size) final { + [[nodiscard]] Transferred write(const std::byte* data, size_t size) final { if (!m_handle) return Transferred::Error; diff --git a/src/core/Json.cpp b/src/core/Json.cpp index 1563c87..3044576 100644 --- a/src/core/Json.cpp +++ b/src/core/Json.cpp @@ -379,15 +379,18 @@ struct Visitor : public BaseReaderHandler, Visitor> { bool keyMode = false; }; -struct byte_stream { +namespace { + +struct ByteStream { Bytes data; void write(const char* buf, size_t len) { - data.insert(data.end(), buf, buf + len); + data.insert(data.end(), (const std::byte*)buf, (const std::byte*)buf + len); } }; +} // namespace -void writeMsgpack(msgpack::packer& w, const Json& b) { +void writeMsgpack(msgpack::packer& w, const Json& b) { switch (b.type()) { case JsonType::Array: { const auto& arr = b.access(); @@ -472,9 +475,9 @@ optional Json::fromJson(const std::string& s) { return visitor.back(); } -std::vector Json::toMsgPack() const { - byte_stream bs; - msgpack::packer pack(bs); +Bytes Json::toMsgPack() const { + ByteStream bs; + msgpack::packer pack(bs); writeMsgpack(pack, *this); diff --git a/src/core/Json_test.cpp b/src/core/Json_test.cpp index fcecf8b..02525ad 100644 --- a/src/core/Json_test.cpp +++ b/src/core/Json_test.cpp @@ -231,18 +231,19 @@ TEST_CASE("get bool") { } TEST_CASE("toMsgPack") { - CHECK(Json(true).toMsgPack() == Bytes{ 0xC3 }); - CHECK(Json(false).toMsgPack() == Bytes{ 0xC2 }); - CHECK(Json(nullptr).toMsgPack() == Bytes{ 0xC0 }); - CHECK(Json(1).toMsgPack() == Bytes{ 0x01 }); - CHECK(Json(32).toMsgPack() == Bytes{ 0x20 }); - CHECK(Json(1024).toMsgPack() == Bytes{ 0xCD, 0x04, 0x00 }); - CHECK(Json(1048768).toMsgPack() == Bytes{ 0xCE, 0x00, 0x10, 0x00, 0xC0 }); - CHECK(Json(1073741824).toMsgPack() == Bytes{ 0xCE, 0x40, 0x00, 0x00, 0x00 }); - CHECK(Json(JsonArray{ 1, 2, 3, 4 }).toMsgPack() == Bytes{ 0x94, 0x01, 0x02, 0x03, 0x04 }); - CHECK(Json("abc").toMsgPack() == Bytes{ 0xA3, 0x61, 0x62, 0x63 }); + CHECK(Json(true).toMsgPack() == Bytes{ 0xC3_b }); + CHECK(Json(false).toMsgPack() == Bytes{ 0xC2_b }); + CHECK(Json(nullptr).toMsgPack() == Bytes{ 0xC0_b }); + CHECK(Json(1).toMsgPack() == Bytes{ 0x01_b }); + CHECK(Json(32).toMsgPack() == Bytes{ 0x20_b }); + CHECK(Json(1024).toMsgPack() == Bytes{ 0xCD_b, 0x04_b, 0x00_b }); + CHECK(Json(1048768).toMsgPack() == Bytes{ 0xCE_b, 0x00_b, 0x10_b, 0x00_b, 0xC0_b }); + CHECK(Json(1073741824).toMsgPack() == Bytes{ 0xCE_b, 0x40_b, 0x00_b, 0x00_b, 0x00_b }); + CHECK(Json(JsonArray{ 1, 2, 3, 4 }).toMsgPack() == Bytes{ 0x94_b, 0x01_b, 0x02_b, 0x03_b, 0x04_b }); + CHECK(Json("abc").toMsgPack() == Bytes{ 0xA3_b, 0x61_b, 0x62_b, 0x63_b }); CHECK(Json(JsonObject{ { "a", 1 }, { "b", 0.5f } }).toMsgPack() == - Bytes{ 0x82, 0xA1, 0x61, 0x01, 0xA1, 0x62, 0xCB, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); + Bytes{ 0x82_b, 0xA1_b, 0x61_b, 0x01_b, 0xA1_b, 0x62_b, 0xCB_b, 0x3F_b, 0xE0_b, 0x00_b, 0x00_b, + 0x00_b, 0x00_b, 0x00_b, 0x00_b }); CHECK(BytesView(Json(JsonObject{ { "compact", true }, { "schema", 0 } }).toMsgPack()) == toBytesView("\x82\xA7" diff --git a/src/core/Stream.cpp b/src/core/Stream.cpp index 7cee9ff..7eb6aab 100644 --- a/src/core/Stream.cpp +++ b/src/core/Stream.cpp @@ -31,10 +31,10 @@ Transferred& Transferred::operator+=(Transferred other) noexcept { return *this; } -optional> Stream::readUntilEnd(bool incompleteOk) { +optional> Stream::readUntilEnd(bool incompleteOk) { constexpr size_t SIZE = 16384; - std::vector data; - uint8_t buf[SIZE]; + std::vector data; + std::byte buf[SIZE]; Transferred r; while ((r = read(buf, SIZE))) { @@ -46,10 +46,10 @@ optional> Stream::readUntilEnd(bool incompleteOk) { } Transferred Stream::write(std::string_view data) { - return write(reinterpret_cast(data.data()), data.size()); + return write(reinterpret_cast(data.data()), data.size()); } -bool Stream::writeAll(std::span data) { +bool Stream::writeAll(std::span data) { return write(data.data(), data.size()) == data.size(); } @@ -73,7 +73,7 @@ bool SequentialReader::seek(intmax_t position, SeekOrigin origin) { throwException(ENotImplemented("seek called for SequentialReader")); } -Transferred SequentialReader::write(const uint8_t* data, size_t size) { +Transferred SequentialReader::write(const std::byte* data, size_t size) { throwException(ENotImplemented("write called for SequentialReader")); } @@ -86,7 +86,7 @@ StreamCapabilities MemoryStream::caps() const noexcept { StreamCapabilities::CanFlush | StreamCapabilities::CanTruncate | StreamCapabilities::HasSize; } -Transferred MemoryStream::read(uint8_t* data, size_t size) { +Transferred MemoryStream::read(std::byte* data, size_t size) { if (size == 0) return Transferred::Error; size_t trSize = std::min(size, static_cast(m_data.size() - m_position)); @@ -98,7 +98,7 @@ Transferred MemoryStream::read(uint8_t* data, size_t size) { return trSize; } -Transferred MemoryStream::write(const uint8_t* data, size_t size) { +Transferred MemoryStream::write(const std::byte* data, size_t size) { if (size == 0) return Transferred::Error; if (m_data.size() < m_position + size) @@ -112,16 +112,16 @@ bool MemoryStream::flush() { return true; } -std::vector& MemoryStream::data() { +std::vector& MemoryStream::data() { return m_data; } -const std::vector& MemoryStream::data() const { +const std::vector& MemoryStream::data() const { return m_data; } bool MemoryStream::truncate() { - m_data.resize(m_position, uint8_t{}); + m_data.resize(m_position, std::byte{}); return true; } @@ -169,7 +169,7 @@ bool SequentialWriter::seek(intmax_t position, SeekOrigin origin) { throwException(ENotImplemented("seek called for SequentialWriter")); } -Transferred SequentialWriter::read(uint8_t* data, size_t size) { +Transferred SequentialWriter::read(std::byte* data, size_t size) { throwException(ENotImplemented("read called for SequentialWriter")); } @@ -177,7 +177,7 @@ StreamCapabilities SequentialWriter::caps() const noexcept { return StreamCapabilities::CanWrite | StreamCapabilities::CanFlush; } -MemoryStream::MemoryStream(std::vector data) : m_data(std::move(data)) {} +MemoryStream::MemoryStream(std::vector data) : m_data(std::move(data)) {} MemoryStream::MemoryStream() {} diff --git a/src/core/Stream_test.cpp b/src/core/Stream_test.cpp index d3ff57f..2aae7bf 100644 --- a/src/core/Stream_test.cpp +++ b/src/core/Stream_test.cpp @@ -26,7 +26,7 @@ namespace Brisk { static std::string_view pangram = "The quick brown fox jumps over the lazy dog"; -static uint8_t buf[1024]; +static std::byte buf[1024]; TEST_CASE("MemoryStream") { RC m = rcnew MemoryStream(); @@ -46,7 +46,7 @@ TEST_CASE("MemoryStream") { CHECK(m->read(buf, 100) == Transferred::Eof); CHECK(m->readUntilEnd() == Bytes{}); CHECK(m->seek(0) == true); - CHECK(m->readUntilEnd(true) == Bytes{ 'a', 'b', 'c', 'd', 'e', 'f' }); + CHECK(m->readUntilEnd(true) == toBytes(std::vector{ 'a', 'b', 'c', 'd', 'e', 'f' })); } } diff --git a/src/graphics/Fonts.cpp b/src/graphics/Fonts.cpp index c369ac7..30bf7ca 100644 --- a/src/graphics/Fonts.cpp +++ b/src/graphics/Fonts.cpp @@ -1220,7 +1220,7 @@ void FontManager::testRender(RC image, const PreparedText& prepared, Poin int32_t xx = std::lround(origin.x + (g.pos + run.position).x + data->offset_x + x); if (xx < 0 || xx >= w.width()) continue; - uint8_t value = v[x + y * data->size.width]; + uint8_t value = static_cast(v[x + y * data->size.width]); if (flags && TestRenderFlags::Fade) value /= 2; if (flags && TestRenderFlags::GlyphBounds) diff --git a/src/graphics/Html.cpp b/src/graphics/Html.cpp index 14d8854..00da65c 100644 --- a/src/graphics/Html.cpp +++ b/src/graphics/Html.cpp @@ -400,29 +400,29 @@ std::string_view htmlDecodeChar(std::string_view name) { std::optional parseHtmlColor(std::string_view colorText) { if (colorText.starts_with('#')) { if (colorText.size() == 1 + 6) { // RRGGBB - uint8_t rgb[3]; + std::byte rgb[3]; if (fromHex(rgb, colorText.substr(1)) != 3) return std::nullopt; - return Color(rgb[0], rgb[1], rgb[2]); + return Color(uint8_t(rgb[0]), uint8_t(rgb[1]), uint8_t(rgb[2])); } else if (colorText.size() == 1 + 8) { // RRGGBBAA - uint8_t rgba[4]; + std::byte rgba[4]; if (fromHex(rgba, colorText.substr(1)) != 4) return std::nullopt; - return Color(rgba[0], rgba[1], rgba[2], rgba[3]); + return Color(uint8_t(rgba[0]), uint8_t(rgba[1]), uint8_t(rgba[2]), uint8_t(rgba[3])); } else if (colorText.size() == 1 + 3) { // RGB const char expanded[6] = { colorText[1], colorText[1], colorText[2], colorText[2], colorText[3], colorText[3] }; - uint8_t rgb[3]; + std::byte rgb[3]; if (fromHex(rgb, std::string_view(std::data(expanded), std::size(expanded))) != 3) return std::nullopt; - return Color(rgb[0], rgb[1], rgb[2]); + return Color(uint8_t(rgb[0]), uint8_t(rgb[1]), uint8_t(rgb[2])); } else if (colorText.size() == 1 + 4) { // RGBA const char expanded[8] = { colorText[1], colorText[1], colorText[2], colorText[2], colorText[3], colorText[3], colorText[4], colorText[4] }; - uint8_t rgba[4]; + std::byte rgba[4]; if (fromHex(rgba, std::string_view(std::data(expanded), std::size(expanded))) != 4) return std::nullopt; - return Color(rgba[0], rgba[1], rgba[2], rgba[3]); + return Color(uint8_t(rgba[0]), uint8_t(rgba[1]), uint8_t(rgba[2]), uint8_t(rgba[3])); } else { return std::nullopt; } diff --git a/src/graphics/ImageFormats_bmp.cpp b/src/graphics/ImageFormats_bmp.cpp index 2f725a1..e0d5853 100644 --- a/src/graphics/ImageFormats_bmp.cpp +++ b/src/graphics/ImageFormats_bmp.cpp @@ -43,7 +43,7 @@ namespace Brisk { static void stbi_write(void* context, void* data, int size) { MemoryStream& result = *reinterpret_cast(context); - std::ignore = result.write((const uint8_t*)data, size); + std::ignore = result.write((const std::byte*)data, size); } Bytes bmpEncode(RC image) { @@ -77,7 +77,7 @@ static expected, ImageIOError> stbiDecode(BytesView bytes, ImageFormat PixelFormat pixelFormat = toPixelFormat(format); int width, height, comp; std::unique_ptr mem( - stbi_load_from_memory(bytes.data(), bytes.size(), &width, &height, &comp, + stbi_load_from_memory((const uint8_t*)bytes.data(), bytes.size(), &width, &height, &comp, pixelFormat == PixelFormat::Unknown ? 0 : pixelComponents(pixelFormat))); if (!mem) return unexpected(ImageIOError::CodecError); @@ -90,7 +90,7 @@ static expected, ImageIOError> stbiDecode(BytesView bytes, ImageFormat return unexpected(ImageIOError::InvalidFormat); RC image = rcnew Image(Size{ width, height }, imageFormat(PixelType::U8Gamma, fmt)); auto w = image->mapWrite(); - w.readFrom(BytesView{ mem.get(), size_t(width * height * comp) }); + w.readFrom(BytesView{ (const std::byte*)mem.get(), size_t(width * height * comp) }); return image; } diff --git a/src/graphics/ImageFormats_jpeg.cpp b/src/graphics/ImageFormats_jpeg.cpp index 1087dc5..573b35a 100644 --- a/src/graphics/ImageFormats_jpeg.cpp +++ b/src/graphics/ImageFormats_jpeg.cpp @@ -55,7 +55,7 @@ Bytes jpegEncode(RC image, optional quality, optionalmapRead(); Bytes result(tjBufSize(r.width(), r.height(), toJPGSS(ss.value_or(defaultColorSubsampling)))); - uint8_t* resultData = result.data(); + uint8_t* resultData = (uint8_t*)result.data(); unsigned long resultSize = result.size(); if (tjCompress2(jpeg, r.data(), r.width(), r.byteStride(), r.height(), toJPGFormat(image->pixelFormat()), @@ -84,8 +84,8 @@ expected, ImageIOError> jpegDecode(BytesView bytes, ImageFormat format Size size; int jpegSS; - if (tjDecompressHeader2(jpeg, const_cast(bytes.data()), bytes.size(), &size.width, &size.height, - &jpegSS) != 0) { + if (tjDecompressHeader2(jpeg, reinterpret_cast(const_cast(bytes.data())), + bytes.size(), &size.width, &size.height, &jpegSS) != 0) { return unexpected(ImageIOError::CodecError); } if (pixelFormat == PixelFormat::Unknown) { @@ -96,8 +96,9 @@ expected, ImageIOError> jpegDecode(BytesView bytes, ImageFormat format auto w = image->mapWrite(); - if (tjDecompress2(jpeg, const_cast(bytes.data()), bytes.size(), w.data(), w.width(), - w.byteStride(), w.height(), toJPGFormat(pixelFormat), TJFLAG_ACCURATEDCT) != 0) { + if (tjDecompress2(jpeg, reinterpret_cast(const_cast(bytes.data())), bytes.size(), + w.data(), w.width(), w.byteStride(), w.height(), toJPGFormat(pixelFormat), + TJFLAG_ACCURATEDCT) != 0) { return unexpected(ImageIOError::CodecError); } diff --git a/src/graphics/ImageFormats_png.cpp b/src/graphics/ImageFormats_png.cpp index 61782fe..5bc019b 100644 --- a/src/graphics/ImageFormats_png.cpp +++ b/src/graphics/ImageFormats_png.cpp @@ -62,7 +62,7 @@ Bytes pngEncode(RC image) { pngimage.width = image->width(); pngimage.height = image->height(); pngimage.format = toPNGFormat(image->pixelFormat()); - Bytes b(PNG_IMAGE_PNG_SIZE_MAX(pngimage), 0); + Bytes b(PNG_IMAGE_PNG_SIZE_MAX(pngimage), 0_b); png_alloc_size_t pngbytes = b.size(); SCOPE_EXIT { diff --git a/src/graphics/ImageFormats_webp.cpp b/src/graphics/ImageFormats_webp.cpp index 180116d..0771554 100644 --- a/src/graphics/ImageFormats_webp.cpp +++ b/src/graphics/ImageFormats_webp.cpp @@ -104,16 +104,16 @@ struct webp_deleter { std::unique_ptr pixels; switch (toPixelFormat(format)) { case PixelFormat::RGBA: - pixels.reset(WebPDecodeRGBA(bytes.data(), bytes.size(), &width, &height)); + pixels.reset(WebPDecodeRGBA((const uint8_t*)bytes.data(), bytes.size(), &width, &height)); break; case PixelFormat::RGB: - pixels.reset(WebPDecodeRGB(bytes.data(), bytes.size(), &width, &height)); + pixels.reset(WebPDecodeRGB((const uint8_t*)bytes.data(), bytes.size(), &width, &height)); break; case PixelFormat::BGRA: - pixels.reset(WebPDecodeBGRA(bytes.data(), bytes.size(), &width, &height)); + pixels.reset(WebPDecodeBGRA((const uint8_t*)bytes.data(), bytes.size(), &width, &height)); break; case PixelFormat::BGR: - pixels.reset(WebPDecodeBGR(bytes.data(), bytes.size(), &width, &height)); + pixels.reset(WebPDecodeBGR((const uint8_t*)bytes.data(), bytes.size(), &width, &height)); break; default: return unexpected(ImageIOError::InvalidFormat); @@ -122,7 +122,7 @@ struct webp_deleter { return unexpected(ImageIOError::InvalidFormat); RC img = rcnew Image(Size{ width, height }, format); auto wr = img->mapWrite(); - wr.readFrom({ pixels.get(), size_t(width * height * 4) }); + wr.readFrom({ (const std::byte*)pixels.get(), size_t(width * height * 4) }); return img; } diff --git a/src/graphics/Renderer_test.cpp b/src/graphics/Renderer_test.cpp index d1f6cde..76bdee9 100644 --- a/src/graphics/Renderer_test.cpp +++ b/src/graphics/Renderer_test.cpp @@ -494,7 +494,7 @@ TEST_CASE("Canvas::drawColorMask", "[gpu]") { pixels[(y * size.width + x) * 4 + 3] = alpha; } } - auto sprite = makeSprite(Size{ size.width * 4, size.height }, pixels); + auto sprite = makeSprite(Size{ size.width * 4, size.height }, toBytesView(pixels)); canvas.drawColorMask({ std::move(sprite) }, one(GeometryGlyph{ { { 1, 1 }, size }, diff --git a/src/graphics/WebGPURenderer/RenderDevice.cpp b/src/graphics/WebGPURenderer/RenderDevice.cpp index 48684cf..21592e6 100644 --- a/src/graphics/WebGPURenderer/RenderDevice.cpp +++ b/src/graphics/WebGPURenderer/RenderDevice.cpp @@ -39,7 +39,7 @@ static fs::path cacheFolder() { } static size_t loadCached(const void* key, size_t keySize, void* value, size_t valueSize, void* userdata) { - BytesView keyBytes(reinterpret_cast(key), keySize); + BytesView keyBytes(reinterpret_cast(key), keySize); auto hash = sha256(keyBytes); auto valueBytes = readBytes(cacheFolder() / toHex(hash)); if (!valueBytes) { @@ -53,8 +53,8 @@ static size_t loadCached(const void* key, size_t keySize, void* value, size_t va static void storeCached(const void* key, size_t keySize, const void* value, size_t valueSize, void* userdata) { - BytesView keyBytes(reinterpret_cast(key), keySize); - BytesView valueBytes(reinterpret_cast(value), valueSize); + BytesView keyBytes(reinterpret_cast(key), keySize); + BytesView valueBytes(reinterpret_cast(value), valueSize); auto hash = sha256(keyBytes); std::ignore = writeBytes(cacheFolder() / toHex(hash), valueBytes); } diff --git a/src/network/Fetch.cpp b/src/network/Fetch.cpp index c5cd44c..6a53fbf 100644 --- a/src/network/Fetch.cpp +++ b/src/network/Fetch.cpp @@ -34,12 +34,12 @@ void setupCURLE(void* c) { static size_t curlWriter(void* ptr, size_t size, size_t nmemb, Stream* stream) { size_t totalSize = size * nmemb; - return stream->write((const uint8_t*)ptr, totalSize).bytes(); + return stream->write((const std::byte*)ptr, totalSize).bytes(); } static size_t curlReader(void* ptr, size_t size, size_t nmemb, Stream* stream) { size_t totalSize = size * nmemb; - return stream->read((uint8_t*)ptr, totalSize).bytes(); + return stream->read((std::byte*)ptr, totalSize).bytes(); } static size_t curlHeaderWriter(char* ptr, size_t size, size_t nmemb, std::string* headers) { diff --git a/src/window/KeyCodes_Windows.cpp b/src/window/KeyCodes_Windows.cpp index ca78dbd..8e35ae6 100644 --- a/src/window/KeyCodes_Windows.cpp +++ b/src/window/KeyCodes_Windows.cpp @@ -166,7 +166,8 @@ KeyCode scanCodeToKeyCode(int scanCode) { } int keyCodeToScanCode(KeyCode keyCode) { - if (keyCode < KeyCode(0) || keyCode > KeyCode::Last) // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange) + if (keyCode < KeyCode(0) || // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange) + keyCode > KeyCode::Last) return -1; return keyCodeToScanCodeTable[+keyCode]; } diff --git a/src/window/PlatformWindow_Darwin.mm b/src/window/PlatformWindow_Darwin.mm index 2f412b5..b5007dd 100644 --- a/src/window/PlatformWindow_Darwin.mm +++ b/src/window/PlatformWindow_Darwin.mm @@ -160,7 +160,7 @@ - (void)applicationDidFinishLaunching:(NSNotification*)notification { if (rep == nil) return nullptr; - image.writeTo(BytesMutableView([rep bitmapData], image.byteSize())); + image.writeTo(BytesMutableView(reinterpret_cast([rep bitmapData]), image.byteSize())); NSSize dipSize = NSMakeSize(std::round(image.width() / scale), std::round(image.height() / scale)); NSPoint dipHot = NSMakePoint(std::round(xhot / scale), std::round(yhot / scale)); diff --git a/src/window/PlatformWindow_Linux.cpp b/src/window/PlatformWindow_Linux.cpp index dc8096a..1d40586 100644 --- a/src/window/PlatformWindow_Linux.cpp +++ b/src/window/PlatformWindow_Linux.cpp @@ -262,7 +262,7 @@ RC PlatformCursors::cursorFromImage(const RC& image, Point auto rd = image->mapRead(); img.width = rd.width(); img.height = rd.height(); - std::vector data; + Bytes data; if (rd.byteStride() == rd.width() * 4) { img.pixels = (unsigned char*)rd.data(); } else {