• About TC
  • Affiliate Disclaimer
  • Privacy Policy
  • TOS
  • Contact
Monday, June 16, 2025
Techcratic
  • TC
  • AI
    Artificial Intelligence

    Amazon Nova Lite enables Bito to offer a free tier option for its AI-powered code reviews

    Artificial Intelligence

    Bridging the Gap: New Datasets Push Recommender Research Toward Real-World Scale

    Artificial Intelligence

    7 Python Errors That Are Actually Features

    Artificial Intelligence

    10 Awesome OCR Models for 2025

    Artificial Intelligence

    5 Error Handling Patterns in Python (Beyond Try-Except)

    Artificial Intelligence

    Top 5 Alternative Data Career Paths and How to Learn Them for Free

    Artificial Intelligence

    Implementing Machine Learning Pipelines with Apache Spark

    Artificial Intelligence

    Learn Power BI for Free This Week

    Artificial Intelligence

    Build GraphRAG applications using Amazon Bedrock Knowledge Bases

  • Crypto
    Report: Justin Sun’s Tron Aims for Nasdaq Listing in High-Stakes Merger Deal

    Report: Justin Sun’s Tron Aims for Nasdaq Listing in High-Stakes Merger Deal

    Best Presales to Buy Today – Which Coins Are Poised for a Breakout?

    2025’s Breakout Meme Coin? Why Everyone’s Rushing to Get a Piece of $AKE

    Metaplanet Acquires Additional 1,112 Bitcoin, Total Holdings Reach 10,000 BTC

    Metaplanet Acquires Additional 1,112 Bitcoin, Total Holdings Reach 10,000 BTC

    Crypto to “Become Part of All Sectors” Under Trump: Kevin O’Leary

    Metaplanet Issues Fresh $210M Bonds to Evo Fund

    Bitcoin Going to $1M: Saylor’s Call Revives Interest in Adam Back’s 21M BTC Order

    Bitcoin Going to $1M: Saylor’s Call Revives Interest in Adam Back’s 21M BTC Order

    Bitcoin Eyes $30T Treasury Store of Value Market, Says Bitwise CEO

    Bitcoin Eyes $30T Treasury Store of Value Market, Says Bitwise CEO

    ZKJ Token Plummets More Than 60% in Flash Crash Amid Rug-Pull Allegations

    ZKJ Token Plummets More Than 60% in Flash Crash Amid Rug-Pull Allegations

    Bitcoin Holding $105K During War Is Bullish for Crypto

    Bitcoin Holding $105K During War Is Bullish for Crypto

    Saylor Signals Another Bitcoin Buy—Orange Dots Strike Again

    Saylor Signals Another Bitcoin Buy—Orange Dots Strike Again

  • Cybersecurity
    Cybersecurity

    AI Agents Run on Secret Accounts — Learn How to Secure Them in This Webinar

    Cybersecurity

    How to Address the Expanding Security Risk

    Cybersecurity

    ConnectWise to Rotate ScreenConnect Code Signing Certificates Due to Security Risks

    Cybersecurity

    5 Lessons from River Island

    Cybersecurity

    INTERPOL Dismantles 20,000+ Malicious IPs Linked to 69 Malware Variants in Operation Secure

    Cybersecurity

    SinoTrack GPS Devices Vulnerable to Remote Vehicle Control via Default Passwords

    Cybersecurity

    Researchers Uncover 20+ Configuration Risks, Including Five CVEs, in Salesforce Industry Cloud

    Cybersecurity

    Adobe Releases Patch Fixing 254 Vulnerabilities, Closing High-Severity Security Gaps

    Cybersecurity

    Researcher Found Flaw to Discover Phone Numbers Linked to Any Google Account

  • Deals
    Lexar 128GB (2-PK) Professional SILVER PRO SD Card, UHS-II, C10, U3, V60, Full HD, 4K,…

    Lexar 128GB (2-PK) Professional SILVER PRO SD Card, UHS-II, C10, U3, V60, Full HD, 4K,…

    SABRENT 2.5 Inch SATA to USB 3.0 Tool Free External Hard Drive Enclosure [Optimized for…

    SABRENT 2.5 Inch SATA to USB 3.0 Tool Free External Hard Drive Enclosure [Optimized for…

    B221000 Black Toner Cartridge B/MB2236 Replacement for Lexmark B221000 Toner Cartridge…

    B221000 Black Toner Cartridge B/MB2236 Replacement for Lexmark B221000 Toner Cartridge…

    Lexar 1TB Professional Go Portable SSD w/Hub, Supports Apple 4K 60fps ProRes, Up to…

    Lexar 1TB Professional Go Portable SSD w/Hub, Supports Apple 4K 60fps ProRes, Up to…

    Kingston NV3 1TB M.2 2280 NVMe SSD | PCIe 4.0 Gen 4×4 | Up to 6000 MB/s | SNV3S/1000G

    Kingston NV3 1TB M.2 2280 NVMe SSD | PCIe 4.0 Gen 4×4 | Up to 6000 MB/s | SNV3S/1000G

    Intel Core Ultra 7 Desktop Processor 265K – 20 cores (8 P-cores + 12 E-cores) up to 5.5…

    Intel Core Ultra 7 Desktop Processor 265K – 20 cores (8 P-cores + 12 E-cores) up to 5.5…

    Hitachi FIJ0038 Fuel Injector

    Hitachi FIJ0038 Fuel Injector

    EVGA Supernova 1300 P+, 80+ Platinum 1300W, Fully Modular, 10 Year Warranty, Includes…

    EVGA Supernova 1300 P+, 80+ Platinum 1300W, Fully Modular, 10 Year Warranty, Includes…

    Logitech G502 X Plus Wireless Gaming Mouse – LIGHTSPEED Optical, LIGHTFORCE Switches,…

    Logitech G502 X Plus Wireless Gaming Mouse – LIGHTSPEED Optical, LIGHTFORCE Switches,…

  • Gaming
    Fortnite CHAPTER 6 SEASON 3 – Trailer

    Fortnite CHAPTER 6 SEASON 3 – Trailer

    Minions Paradise – Gameplay Walkthrough Part 1 – Level 1-3 (iOS, Android)

    Minions Paradise – Gameplay Walkthrough Part 1 – Level 1-3 (iOS, Android)

    The new Windows 11 Insider release has a weird bug where it plays the Windows Vista start-up music instead of the current one

    The new Windows 11 Insider release has a weird bug where it plays the Windows Vista start-up music instead of the current one

    Flip 7 Review – Is It The Greatest Card Game of All Time?

    Flip 7 Review – Is It The Greatest Card Game of All Time?

    NEW GAME TRAILERS 2021 |PART 1| |FOR THE LOVE OF GAMING|

    NEW GAME TRAILERS 2021 |PART 1| |FOR THE LOVE OF GAMING|

    WWE 2K25 Review – Two Steps Forward, One Step Back

    WWE 2K25 Review – Two Steps Forward, One Step Back

    Honest Game Trailers | WoW: Wrath of the Lich King

    Honest Game Trailers | WoW: Wrath of the Lich King

    Hello Neighbor – Finland Story | Full Game Walkthrough

    Hello Neighbor – Finland Story | Full Game Walkthrough

    Elden Ring NIGHTREIGN Early Reviews Say It All….

    Elden Ring NIGHTREIGN Early Reviews Say It All….

  • Tesla
    Winch Stopper,Winch Accessories,Car Accessories Winch Cable Stopper,Rubber Winch…

    Winch Stopper,Winch Accessories,Car Accessories Winch Cable Stopper,Rubber Winch…

    LUCKEASY 2PCS Storage Box Compatible with Tesla Cybertruck 2024 2023 Center Console…

    LUCKEASY 2PCS Storage Box Compatible with Tesla Cybertruck 2024 2023 Center Console…

    Tesla on ‘self-driving’ gets stuck on train track and hit by train

    Tesla on ‘self-driving’ gets stuck on train track and hit by train

    Level 1/2 Tesla Charger – 16A 3.84KW Mobile EV Charging with 240V NEMA 6-20 Plug, 5-15…

    Level 1/2 Tesla Charger – 16A 3.84KW Mobile EV Charging with 240V NEMA 6-20 Plug, 5-15…

    Upgrade fit Tesla Model Y (2019-2023) Center Console Wireless Charger Mat – Silicone…

    Upgrade fit Tesla Model Y (2019-2023) Center Console Wireless Charger Mat – Silicone…

    Torx Plus Socket, 5-External Torx Socket 1/4″ Dr 10EPR Compatible With Tesla Model 3…

    Torx Plus Socket, 5-External Torx Socket 1/4″ Dr 10EPR Compatible With Tesla Model 3…

    Car Seat Organizers,Multi-functional Back Seat Protectors, Storage Pouches, and Tray…

    Car Seat Organizers,Multi-functional Back Seat Protectors, Storage Pouches, and Tray…

    AOHI USB C Car Charger, PD 45W&QC 30W 2 Port Type-C Fast Charging Car Charger Lighter…

    AOHI USB C Car Charger, PD 45W&QC 30W 2 Port Type-C Fast Charging Car Charger Lighter…

    Roof Sunshades for Tesla Model 3 2025, Upgraded 3.0 Sunroof Shade Sunshade Roof Sun…

    Roof Sunshades for Tesla Model 3 2025, Upgraded 3.0 Sunroof Shade Sunshade Roof Sun…

  • UFO
    I SHREDDED Alien's Belongings in VR! – Blinnk and the Vacuum of Space VR

    I SHREDDED Alien's Belongings in VR! – Blinnk and the Vacuum of Space VR

    Mind Blowing Encounters with Spiritual Beings and Astral Realms – With Erik Unger P-2

    Mind Blowing Encounters with Spiritual Beings and Astral Realms – With Erik Unger P-2

    Katie’s Bumpers Frequent Flyer UFO Yellow – FF7YEL

    Katie’s Bumpers Frequent Flyer UFO Yellow – FF7YEL

    Did Ancient astronauts visit Earth?? new evidence fuels extraterrestrial Theories! #viral #history

    Did Ancient astronauts visit Earth?? new evidence fuels extraterrestrial Theories! #viral #history

    INFUNLY 4pcs Solar System Patches Iron on Sequin Planet Embroidery Patch Rainbow UFO Patch Space Sew on Patch Spacecraft Patch Celestial Applique for DIY Clothing Jeans Bags Jacket Backpack Hat

    INFUNLY 4pcs Solar System Patches Iron on Sequin Planet Embroidery Patch Rainbow UFO Patch Space Sew on Patch Spacecraft Patch Celestial Applique for DIY Clothing Jeans Bags Jacket Backpack Hat

    UFO Cover Up – They Want You Confused About the Truth!

    UFO Cover Up – They Want You Confused About the Truth!

    Nitro Green for Men – 3.4 oz EDP Spray

    Nitro Green for Men – 3.4 oz EDP Spray

    Argentinian Town Has One Of The Best Documented Mass UFO Sightings | The Unexplained Files

    Football Fan Patch Trucker Hat – Netted Snapback Baseball Cap with Team Design for Men & Women

    Football Fan Patch Trucker Hat – Netted Snapback Baseball Cap with Team Design for Men & Women

No Result
View All Result
  • TC
  • AI
    Artificial Intelligence

    Amazon Nova Lite enables Bito to offer a free tier option for its AI-powered code reviews

    Artificial Intelligence

    Bridging the Gap: New Datasets Push Recommender Research Toward Real-World Scale

    Artificial Intelligence

    7 Python Errors That Are Actually Features

    Artificial Intelligence

    10 Awesome OCR Models for 2025

    Artificial Intelligence

    5 Error Handling Patterns in Python (Beyond Try-Except)

    Artificial Intelligence

    Top 5 Alternative Data Career Paths and How to Learn Them for Free

    Artificial Intelligence

    Implementing Machine Learning Pipelines with Apache Spark

    Artificial Intelligence

    Learn Power BI for Free This Week

    Artificial Intelligence

    Build GraphRAG applications using Amazon Bedrock Knowledge Bases

  • Crypto
    Report: Justin Sun’s Tron Aims for Nasdaq Listing in High-Stakes Merger Deal

    Report: Justin Sun’s Tron Aims for Nasdaq Listing in High-Stakes Merger Deal

    Best Presales to Buy Today – Which Coins Are Poised for a Breakout?

    2025’s Breakout Meme Coin? Why Everyone’s Rushing to Get a Piece of $AKE

    Metaplanet Acquires Additional 1,112 Bitcoin, Total Holdings Reach 10,000 BTC

    Metaplanet Acquires Additional 1,112 Bitcoin, Total Holdings Reach 10,000 BTC

    Crypto to “Become Part of All Sectors” Under Trump: Kevin O’Leary

    Metaplanet Issues Fresh $210M Bonds to Evo Fund

    Bitcoin Going to $1M: Saylor’s Call Revives Interest in Adam Back’s 21M BTC Order

    Bitcoin Going to $1M: Saylor’s Call Revives Interest in Adam Back’s 21M BTC Order

    Bitcoin Eyes $30T Treasury Store of Value Market, Says Bitwise CEO

    Bitcoin Eyes $30T Treasury Store of Value Market, Says Bitwise CEO

    ZKJ Token Plummets More Than 60% in Flash Crash Amid Rug-Pull Allegations

    ZKJ Token Plummets More Than 60% in Flash Crash Amid Rug-Pull Allegations

    Bitcoin Holding $105K During War Is Bullish for Crypto

    Bitcoin Holding $105K During War Is Bullish for Crypto

    Saylor Signals Another Bitcoin Buy—Orange Dots Strike Again

    Saylor Signals Another Bitcoin Buy—Orange Dots Strike Again

  • Cybersecurity
    Cybersecurity

    AI Agents Run on Secret Accounts — Learn How to Secure Them in This Webinar

    Cybersecurity

    How to Address the Expanding Security Risk

    Cybersecurity

    ConnectWise to Rotate ScreenConnect Code Signing Certificates Due to Security Risks

    Cybersecurity

    5 Lessons from River Island

    Cybersecurity

    INTERPOL Dismantles 20,000+ Malicious IPs Linked to 69 Malware Variants in Operation Secure

    Cybersecurity

    SinoTrack GPS Devices Vulnerable to Remote Vehicle Control via Default Passwords

    Cybersecurity

    Researchers Uncover 20+ Configuration Risks, Including Five CVEs, in Salesforce Industry Cloud

    Cybersecurity

    Adobe Releases Patch Fixing 254 Vulnerabilities, Closing High-Severity Security Gaps

    Cybersecurity

    Researcher Found Flaw to Discover Phone Numbers Linked to Any Google Account

  • Deals
    Lexar 128GB (2-PK) Professional SILVER PRO SD Card, UHS-II, C10, U3, V60, Full HD, 4K,…

    Lexar 128GB (2-PK) Professional SILVER PRO SD Card, UHS-II, C10, U3, V60, Full HD, 4K,…

    SABRENT 2.5 Inch SATA to USB 3.0 Tool Free External Hard Drive Enclosure [Optimized for…

    SABRENT 2.5 Inch SATA to USB 3.0 Tool Free External Hard Drive Enclosure [Optimized for…

    B221000 Black Toner Cartridge B/MB2236 Replacement for Lexmark B221000 Toner Cartridge…

    B221000 Black Toner Cartridge B/MB2236 Replacement for Lexmark B221000 Toner Cartridge…

    Lexar 1TB Professional Go Portable SSD w/Hub, Supports Apple 4K 60fps ProRes, Up to…

    Lexar 1TB Professional Go Portable SSD w/Hub, Supports Apple 4K 60fps ProRes, Up to…

    Kingston NV3 1TB M.2 2280 NVMe SSD | PCIe 4.0 Gen 4×4 | Up to 6000 MB/s | SNV3S/1000G

    Kingston NV3 1TB M.2 2280 NVMe SSD | PCIe 4.0 Gen 4×4 | Up to 6000 MB/s | SNV3S/1000G

    Intel Core Ultra 7 Desktop Processor 265K – 20 cores (8 P-cores + 12 E-cores) up to 5.5…

    Intel Core Ultra 7 Desktop Processor 265K – 20 cores (8 P-cores + 12 E-cores) up to 5.5…

    Hitachi FIJ0038 Fuel Injector

    Hitachi FIJ0038 Fuel Injector

    EVGA Supernova 1300 P+, 80+ Platinum 1300W, Fully Modular, 10 Year Warranty, Includes…

    EVGA Supernova 1300 P+, 80+ Platinum 1300W, Fully Modular, 10 Year Warranty, Includes…

    Logitech G502 X Plus Wireless Gaming Mouse – LIGHTSPEED Optical, LIGHTFORCE Switches,…

    Logitech G502 X Plus Wireless Gaming Mouse – LIGHTSPEED Optical, LIGHTFORCE Switches,…

  • Gaming
    Fortnite CHAPTER 6 SEASON 3 – Trailer

    Fortnite CHAPTER 6 SEASON 3 – Trailer

    Minions Paradise – Gameplay Walkthrough Part 1 – Level 1-3 (iOS, Android)

    Minions Paradise – Gameplay Walkthrough Part 1 – Level 1-3 (iOS, Android)

    The new Windows 11 Insider release has a weird bug where it plays the Windows Vista start-up music instead of the current one

    The new Windows 11 Insider release has a weird bug where it plays the Windows Vista start-up music instead of the current one

    Flip 7 Review – Is It The Greatest Card Game of All Time?

    Flip 7 Review – Is It The Greatest Card Game of All Time?

    NEW GAME TRAILERS 2021 |PART 1| |FOR THE LOVE OF GAMING|

    NEW GAME TRAILERS 2021 |PART 1| |FOR THE LOVE OF GAMING|

    WWE 2K25 Review – Two Steps Forward, One Step Back

    WWE 2K25 Review – Two Steps Forward, One Step Back

    Honest Game Trailers | WoW: Wrath of the Lich King

    Honest Game Trailers | WoW: Wrath of the Lich King

    Hello Neighbor – Finland Story | Full Game Walkthrough

    Hello Neighbor – Finland Story | Full Game Walkthrough

    Elden Ring NIGHTREIGN Early Reviews Say It All….

    Elden Ring NIGHTREIGN Early Reviews Say It All….

  • Tesla
    Winch Stopper,Winch Accessories,Car Accessories Winch Cable Stopper,Rubber Winch…

    Winch Stopper,Winch Accessories,Car Accessories Winch Cable Stopper,Rubber Winch…

    LUCKEASY 2PCS Storage Box Compatible with Tesla Cybertruck 2024 2023 Center Console…

    LUCKEASY 2PCS Storage Box Compatible with Tesla Cybertruck 2024 2023 Center Console…

    Tesla on ‘self-driving’ gets stuck on train track and hit by train

    Tesla on ‘self-driving’ gets stuck on train track and hit by train

    Level 1/2 Tesla Charger – 16A 3.84KW Mobile EV Charging with 240V NEMA 6-20 Plug, 5-15…

    Level 1/2 Tesla Charger – 16A 3.84KW Mobile EV Charging with 240V NEMA 6-20 Plug, 5-15…

    Upgrade fit Tesla Model Y (2019-2023) Center Console Wireless Charger Mat – Silicone…

    Upgrade fit Tesla Model Y (2019-2023) Center Console Wireless Charger Mat – Silicone…

    Torx Plus Socket, 5-External Torx Socket 1/4″ Dr 10EPR Compatible With Tesla Model 3…

    Torx Plus Socket, 5-External Torx Socket 1/4″ Dr 10EPR Compatible With Tesla Model 3…

    Car Seat Organizers,Multi-functional Back Seat Protectors, Storage Pouches, and Tray…

    Car Seat Organizers,Multi-functional Back Seat Protectors, Storage Pouches, and Tray…

    AOHI USB C Car Charger, PD 45W&QC 30W 2 Port Type-C Fast Charging Car Charger Lighter…

    AOHI USB C Car Charger, PD 45W&QC 30W 2 Port Type-C Fast Charging Car Charger Lighter…

    Roof Sunshades for Tesla Model 3 2025, Upgraded 3.0 Sunroof Shade Sunshade Roof Sun…

    Roof Sunshades for Tesla Model 3 2025, Upgraded 3.0 Sunroof Shade Sunshade Roof Sun…

  • UFO
    I SHREDDED Alien's Belongings in VR! – Blinnk and the Vacuum of Space VR

    I SHREDDED Alien's Belongings in VR! – Blinnk and the Vacuum of Space VR

    Mind Blowing Encounters with Spiritual Beings and Astral Realms – With Erik Unger P-2

    Mind Blowing Encounters with Spiritual Beings and Astral Realms – With Erik Unger P-2

    Katie’s Bumpers Frequent Flyer UFO Yellow – FF7YEL

    Katie’s Bumpers Frequent Flyer UFO Yellow – FF7YEL

    Did Ancient astronauts visit Earth?? new evidence fuels extraterrestrial Theories! #viral #history

    Did Ancient astronauts visit Earth?? new evidence fuels extraterrestrial Theories! #viral #history

    INFUNLY 4pcs Solar System Patches Iron on Sequin Planet Embroidery Patch Rainbow UFO Patch Space Sew on Patch Spacecraft Patch Celestial Applique for DIY Clothing Jeans Bags Jacket Backpack Hat

    INFUNLY 4pcs Solar System Patches Iron on Sequin Planet Embroidery Patch Rainbow UFO Patch Space Sew on Patch Spacecraft Patch Celestial Applique for DIY Clothing Jeans Bags Jacket Backpack Hat

    UFO Cover Up – They Want You Confused About the Truth!

    UFO Cover Up – They Want You Confused About the Truth!

    Nitro Green for Men – 3.4 oz EDP Spray

    Nitro Green for Men – 3.4 oz EDP Spray

    Argentinian Town Has One Of The Best Documented Mass UFO Sightings | The Unexplained Files

    Football Fan Patch Trucker Hat – Netted Snapback Baseball Cap with Team Design for Men & Women

    Football Fan Patch Trucker Hat – Netted Snapback Baseball Cap with Team Design for Men & Women

No Result
View All Result
Techcratic
No Result
View All Result
Home Hacker News

EmberEmu/Hexi: Header-only, lightweight C++ library for binary streaming. Network data handling made easy peasy!

Hacker News by Hacker News
March 28, 2025
in Hacker News
Reading Time: 17 mins read
121 9
A A
0

2025-03-28 13:37:00
github.com

Hexi, Easy Peasy Binary Streaming




Hexi is a lightweight, header-only C++23 library for safely handling binary data from arbitrary sources (but primarily network data). It sits somewhere between manually memcpying bytes from network buffers and full-blown serialisation libraries.

The design goals are ease of use, safety when dealing with untrusted data, a reasonable level of flexibility, and keeping overhead to a minimum.

What Hexi doesn’t offer: versioning, conversion between different formats, handling of text-based formats, unloading the dishwasher.

Getting started

Incorporating Hexi into your project is simple! The easiest way is to simply copy hexi.h from single_include into your own project. If you’d rather only include what you use, you can add include to your include paths or incorporate it into your own CMake project with target_link_library. To build the unit tests, run CMake with ENABLE_TESTING.

Here’s what some libraries might call a very simple motivating example:

#include hexi.h>
#include array>
#include vector>
#include cstddef>

struct UserPacket {
    uint64_t user_id;
    uint64_t timestamp;
    std::arrayuint8_t, 16> ipv6;
};

auto deserialise(std::spanconst char> network_buffer) {
    hexi::buffer_adaptor adaptor(network_buffer); // wrap the buffer
    hexi::binary_stream stream(adaptor);          // create a binary stream
    
    // deserialise!
    UserPacket packet;
    stream >> packet;
    return packet;
}

auto serialise(const UserPacket& packet) {
    std::vectoruint8_t> buffer;
    hexi::buffer_adaptor adaptor(buffer); // wrap the buffer
    hexi::binary_stream stream(adaptor);  // create a binary stream
    
    // serialise!
    stream return buffer;
}

By default, Hexi will try to serialise basic structures such as our UserPacket if they meet requirements for being safe to directly copy the bytes. Now, for reasons of portability, it’s not recommended that you do things this way unless you’re positive that the data layout is identical on the system that wrote the data. Not to worry, this is easily solved. Plus, we didn’t do any error handling. All in good time.

Remember these two classes, if nothing else!

The two classes you’ll primarily deal with are buffer_adaptor and binary_stream.

binary_stream takes a container as its argument and is used to do the reading and writing. It doesn’t know much about the details of the underlying container.

To support containers that weren’t written to be used with Hexi, buffer_adaptor is used as a wrapper that binary_stream can interface with. As with binary_stream, it also provides read and write operations but at a lower level.

buffer_adaptor can wrap any contiguous container or view that provides data and size member functions and optionally resize() for write support. From the standard library, that means the following can be used out of the box:

Plenty of non-standard library containers will work out of the box, too, as long as they provide a vaguely similar API.

The container’s value type must be a byte type (e.g. char, std::byte, uint8_t). std::as_bytes can be used as a workaround if this poses a problem.

Hexi supports custom containers, including non-contiguous containers. In fact, there’s a non-contiguous container included in the library. You simply need to provide a few functions such as read and size to allow the binary_stream class to be able to use it.

static_buffer.h provides a simple example of a custom container that can be used directly with binary_stream.

As mentioned, Hexi is intended to be safe to use even when dealing with untrusted data. An example might be network messages that have been manipulated to try to trick your code into reading out of bounds.

binary_stream performs bounds checking to ensure that it will never read more data than the buffer has available and optionally allows you to specify an upper bound on the amount of data to read. This can be useful when you have multiple messages in a buffer and want to limit the deserialisation from potentially eating into the next.

buffer_t buffer;
// ... read data
hexi::binary_stream stream(buffer, 32); // will never read more than 32 bytes

Errors happen, it's up to you to handle 'em

The default error handling mechanism is exceptions. Upon encountering a problem with reading data, an exception derived from hexi::exception will be thrown. These are:

  • hexi::buffer_underrun – attempt to read out of bounds
  • hexi::stream_read_limit – attempt to read more than the imposed limit

Exceptions from binary_stream can be disabled by specifying no_throw as a template argument, as shown:

hexi::binary_stream stream(...);

While this prevents binary_stream itself from throwing, it does not prevent propagation of exceptions from lower levels. For example, a wrapped std::vector could still throw std::bad_alloc if allocation fails when writing to it.

Regardless of the error handling mechanism you use, the state of a binary_stream can be checked as follows:

hexi::binary_stream stream(...);
// ... assume an error happens

// simplest way to check whether any errors have occurred
if (!stream) {
    // handle error
}

// or we can get the state
if (auto state = stream.state(); state != hexi::stream_state::ok) {
    // handle error
}

Writing portable code is easy peasy

In the first example, reading our UserPacket would only work as expected if the program that wrote the data laid everything out in the same way as our own program.
This might not be the case for reasons of architecture differences, compiler flags, etc.

Here’s the same example but doing it portably.

#include hexi.h>
#include span>
#include string>
#include vector>
#include cstddef>
#include cstdint>

struct UserPacket {
    uint64_t user_id;
    std::string username;
    uint64_t timestamp;
    uint8_t has_optional_field;
    uint32_t optional_field;  // pretend this is big endian in the protocol

    // deserialise
    auto& operator>>(auto& stream) {
        stream >> user_id >> username >> timestamp >> has_optional_field;

        if (has_optional_field) {
            stream >> optional_field;
            hexi::endian::big_to_native_inplace(optional_field);
        }

        // we can manually trigger an error if something went wrong
        // stream.set_error_state();
        return stream;
    }

    // serialise
    auto& operatorauto& stream) const {
        stream if (has_optional_field) {
            stream hexi::endian::native_to_big(optional_field);
        }

        return stream;
    }
};

// pretend we're reading network data
void read() {
    std::vectorchar> buffer;
    const auto bytes_read = socket.read(buffer);

    // ... logic for determing packet type, etc

    bool result {};

    switch (packet_type) {
        case packet_type::user_packet:
            result = handle_user_packet(buffer);
            break;
    }

    // ... handle result
}

auto handle_user_packet(std::spanconst char> buffer) {
    hexi::buffer_adaptor adaptor(buffer);
    hexi::binary_stream stream(adaptor);

    UserPacket packet;
    stream >> packet;

    if (stream) {
        // ... do something with the packet
        return true;
    } else {
        return false;
    }
}

Because binary_stream is a template, it’s easiest to allow the compiler to perform type deduction magic.

If you want the function bodies to be in a source file, it’s recommended that you provide your own using alias for your binary_stream type.
The alternative is to use the polymorphic equivalents, pmc::buffer_adaptor and pmc::binary_stream, which allow you to change the underlying buffer type at runtime but at the cost of virtual call overhead and lacking some functionality that doesn’t mesh well with polymorphism.

How you structure your code is up to you, this is just one way of doing it.

Uh, one more thing...

When using binary_stream, strings are always treated as null-terminated. Writing a char*, std::string_view or std::string will always write a terminating byte to the stream. If you require otherwise, use one of the put functions.

Likewise, reading to std::string assumes the buffer contains a null-terminator. If it does not, an empty string will be returned. If you know the length of the string or need to support a custom terminating/sentinel value, use get() and find_first_of().

What else is in the box?

Here’s a very quick rundown on some of the included extras.

  • hexi::file_buffer
    • For dealing with binary files. Simples.
  • hexi::static_buffer
    • Fixed-size networking buffer for when you know the upper bound on the amount of data you’ll need to send or receive in one go. Essentially a wrapper around std::array but with added state tracking. Handy if you need to deserialise in multiple steps (read packet header, dispatch, read packet body).
  • hexi::dynamic_buffer
    • Resizeable buffer for when you want to deal with occasional large read/writes without having to allocate the space up front. Internally, it adds additional allocations to accomodate extra data rather than requesting a larger allocation and copying data as std::vector would. It reuses allocated blocks where possible and has support for Asio (Boost or standalone). Effectively, it’s a linked list buffer.
  • hexi::tls_block_allocator
    • Allows many instances of dynamic_buffer to share a larger pool of pre-allocated memory, with each thread having its own pool. This is useful when you have many network sockets to handle and want to avoid the general purpose allocator. The caveat is that a deallocation must be made by the same thread that made the allocation, thus limiting access to the buffer to a single thread (with some exceptions).
  • hexi::endian
    • Provides functionality for handling endianness of integral types.

Before we wrap up, look at these tidbits...

We’re at the end of the overview, but there’s more to discover if you decide to give Hexi a shot. Here’s a selection of tasty morsels:

  • binary_stream allows you to perform write seeking within the stream, when the underlying buffer supports it. This is nice if, for example, you need to update a message header with information that you might not know until the rest of the message has been written; checksums, sizes, etc.
  • binary_stream provides overloaded put and get member functions, which allow for fine-grained control, such as reading/writing a specific number of bytes.
  • binary_stream allows for writing to std::string_view and std::span with view() and span() as long as the underlying container is contiguous. This allows you to create views into the buffer’s data, providing a fast, zero-copy way to read strings and arrays from the stream. If you do this, you should avoid writing to the same buffer while holding views to the data.
  • buffer_adaptor provides a template option, space_optimise. This is enabled by default and allows it to avoid resizing containers in cases where all data has been read by the stream. Disabling it allows for preserving data even after having been read. This option is only relevant in scenarios where a single buffer is being both written to and read from.
  • buffer_adaptor provides find_first_of, making it easy to find a specific sentinel value within your buffer.

To learn more, check out the examples in docs/examples!

Thanks for listening! Now go unload the dis[C Make Lists](include/CMakeLists.txt)hwasher.

Source Link


Keep your files stored safely and securely with the SanDisk 2TB Extreme Portable SSD. With over 69,505 ratings and an impressive 4.6 out of 5 stars, this product has been purchased over 8K+ times in the past month. At only $129.99, this Amazon’s Choice product is a must-have for secure file storage.

Help keep private content private with the included password protection featuring 256-bit AES hardware encryption. Order now for just $129.99 on Amazon!


Start your free Amazon Prime trial
today and unlock unlimited streaming and more!

Help Power Techcratic’s Future – Scan To Support

If Techcratic’s content and insights have helped you, consider giving back by supporting the platform with crypto. Every contribution makes a difference, whether it’s for high-quality content, server maintenance, or future updates. Techcratic is constantly evolving, and your support helps drive that progress.

As a solo operator who wears all the hats, creating content, managing the tech, and running the site, your support allows me to stay focused on delivering valuable resources. Your support keeps everything running smoothly and enables me to continue creating the content you love. I’m deeply grateful for your support, it truly means the world to me! Thank you!

BITCOIN

Bitcoin Logo

Bitcoin QR Code

bc1qlszw7elx2qahjwvaryh0tkgg8y68enw30gpvge

Scan the QR code with your crypto wallet app

DOGECOIN

Dogecoin Logo

Dogecoin QR Code

D64GwvvYQxFXYyan3oQCrmWfidf6T3JpBA

Scan the QR code with your crypto wallet app

ETHEREUM

Ethereum Logo

Ethereum QR Code

0xe9BC980DF3d985730dA827996B43E4A62CCBAA7a

Scan the QR code with your crypto wallet app

Please read the Privacy and Security Disclaimer on how Techcratic handles your support.

Disclaimer: As an Amazon Associate, Techcratic may earn from qualifying purchases.

Tags: Hacker News
Previous Post

No cash? No Problem! DoorDash-Klarna partnership lets you pay for takeout in installments

Next Post

What’s The Difference Between These Crossovers?

Hacker News

Hacker News

Stay updated with Hacker News, where technology meets entrepreneurial spirit. Get the latest on tech trends, startup news, and discussions from the tech community. Read the latest updates here at Techcratic.

Related Posts

ccbikai/ssh-ai-chat: Chat with AI over SSH.
Hacker News

ccbikai/ssh-ai-chat: Chat with AI over SSH.

June 16, 2025
1.3k
rorosen/zeekstd: Rust implementation of the Zstandard Seekable Format
Hacker News

rorosen/zeekstd: Rust implementation of the Zstandard Seekable Format

June 16, 2025
1.3k
Solving LinkedIn Queens with APL
Hacker News

Solving LinkedIn Queens with APL

June 16, 2025
1.3k
KAIST NEWS CENTER
Hacker News

KAIST NEWS CENTER

June 15, 2025
1.3k
How fast can the RPython GC allocate?
Hacker News

How fast can the RPython GC allocate?

June 15, 2025
1.3k
Biofuels Policy, a Mainstay of American Agriculture, Has Been a Failure for the Climate, a New Report Claims
Hacker News

Biofuels Policy, a Mainstay of American Agriculture, Has Been a Failure for the Climate, a New Report Claims

June 15, 2025
1.3k
SakanaAI/text-to-lora: Hypernetworks that adapt LLMs for specific benchmark tasks using only textual task description as the input
Hacker News

SakanaAI/text-to-lora: Hypernetworks that adapt LLMs for specific benchmark tasks using only textual task description as the input

June 15, 2025
1.3k
tanelp/tiny-diffusion: A minimal PyTorch implementation of probabilistic diffusion models for 2D datasets.
Hacker News

tanelp/tiny-diffusion: A minimal PyTorch implementation of probabilistic diffusion models for 2D datasets.

June 15, 2025
1.3k
Load More
Next Post
What’s The Difference Between These Crossovers?

What's The Difference Between These Crossovers?

The Pixel 9a launches on April 10 in the US

The Pixel 9a launches on April 10 in the US

A secret weapon in your war against jumping, nipping and chewing

A secret weapon in your war against jumping, nipping and chewing

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Your Tech Resources

  • 30 Second Tech ™
  • AI
  • App Zone ™
  • Apple
  • Ars Technica
  • CNET
  • ComputerWorld
  • Crypto News
  • Cybersecurity
  • Endgadget
  • Forbes
  • Fossbytes
  • Gaming
  • GeekWire
  • Gizmodo
  • Google News
  • Hacker News
  • Harvard Tech
  • I Like Cats ™
  • I Like Dogs ™
  • LifeHacker
  • MacRumors
  • Macworld
  • Mashable
  • Microsoft
  • MIT Tech
  • PC World
  • Photofocus
  • Physics
  • Random Tech
  • Retro Rewind ™
  • Robot Report
  • SiliconANGLE
  • SlashGear
  • Smartphone
  • StackSocial
  • Tech Art
  • Tech Careers
  • Tech Deals
  • Techcratic ™
  • TechCrunch
  • Techdirt
  • TechRepublic
  • Techs Got To Eat ™
  • TechSpot
  • Tesla
  • The Verge
  • TNW
  • Trusted Reviews
  • UFO
  • VentureBeat
  • Visual Capitalist
  • Wired
  • ZDNet

Tech News

  • 30 Second Tech ™
  • AI
  • Apple Insider
  • Ars Technica
  • CNET
  • ComputerWorld
  • Crypto News
  • Cybersecurity
  • Endgadget
  • ExtremeTech
  • Fossbytes
  • Gaming
  • GeekWire
  • Gizmodo

Tech News

  • Harvard Tech
  • MacRumors
  • Macworld
  • Mashable
  • Microsoft
  • MIT Tech
  • Physics
  • PC World
  • Random Tech
  • Retro Rewind ™
  • SiliconANGLE
  • SlashGear
  • Smartphone
  • StackSocial
  • Tech Careers

Tech News​

  • Tech Art
  • TechCrunch
  • Techdirt
  • TechRepublic
  • Techs Got To Eat ™
  • TechSpot
  • Tesla
  • The Verge
  • TNW
  • Trusted Reviews
  • UFO
  • VentureBeat
  • Visual Capitalist
  • Wired
  • ZDNet

Site Links

  • About Techcratic
  • Affiliate Disclaimer
  • Affiliate Link Policy
  • Contact Techcratic
  • Dealors Discount Store
  • Privacy and Security Disclaimer
  • Privacy Policy
  • RSS Feed
  • Site Map
  • Support Techcratic
  • Techcratic
  • Tech Deals
  • TOS
  • 𝕏
Click For A Secret Deal

Techcratic – Your All In One Tech Hub © 2020 – 2025
All Rights Reserved
∞

No Result
View All Result
  • 30 Second Tech ™
  • AI
  • App Zone ™
  • Apple
  • Ars Technica
  • CNET
  • Crypto News
  • Cybersecurity
  • Endgadget
  • Gaming
  • I Like Cats ™
  • I Like Dogs ™
  • MacRumors
  • Macworld
  • Tech Deals
  • Techcratic ™
  • Techs Got To Eat ™
  • Tesla
  • UFO
  • Wired