Code Monkey home page Code Monkey logo

endian_codec's Introduction

crates.io Documentation CI master derive: crates.io

endian_codec

This crate helps serialize types as bytes and deserialize from bytes with a special byte order. This crate can be used in no_std environment and has no external dependencies.

If you are looking for a small universal binary (de)serializer that works with serde, look at bincode.

Main features:

  • A clean way to convert structures to bytes( with bytes order) and back
  • Derive
  • no_std
  • no external dependencies

Examples

use endian_codec::{PackedSize, EncodeLE, DecodeLE};
// If you look at this structure without checking the documentation, you know it works with
// little-endian notation
#[derive(Debug, PartialEq, Eq, PackedSize, EncodeLE, DecodeLE)]
struct Version {
  major: u16,
  minor: u16,
  patch: u16
}

let mut buf = [0; Version::PACKED_LEN]; // From PackedSize
let test = Version { major: 0, minor: 21, patch: 37 };
// if you work with big- and little-endians, you will not mix them accidentally
test.encode_as_le_bytes(&mut buf);
let test_from_b = Version::decode_from_le_bytes(&buf);
assert_eq!(test, test_from_b);

There can be also a situation when you are forced to work with mixed-endians in one struct.

use endian_codec::{PackedSize, EncodeME};
// even if you only use derive EncodeME, you also need to have required traits in the scope.
use endian_codec::{EncodeLE, EncodeBE}; // for #[endian = "le/be"]

#[derive(PackedSize, EncodeME)]
// You work with a very old system and there are mixed-endians
// There will be only one format "le" or "little" in the next minor version.
struct Request {
  #[endian = "le"]
  cmd: u16,
  #[endian = "little"] // or #[endian = "le"]
  value: i64,
  #[endian = "big"] // or #[endian = "be"]
  timestamp: i128,
}

let mut buf = [0; Request::PACKED_LEN];
let req = Request {
  cmd: 0x44,
  value: 74,
  timestamp: 0xFFFF_FFFF_0000_0000,
};
// here we see me (mixed-endian), just look at the struct definition for details
req.encode_as_me_bytes(&mut buf);

Why another crate to handle endianess?

  • Easy byteorder-encoding structs with multiple fields and consistent encoding
  • Learning how to create custom derives
  • Making a clean API and auto document code.

There are a few other crates that do a similar things:

  • byteorder - Library for reading/writing numbers in big-endian and little-endian.
  • bytes - Buf and BufMut traits that have methods to put and get primitives in the desired endian format.
  • packed_struct - Safe struct (un-) packing with bit-level control.
  • simple_endian - Instead of providing functions that convert - create types that store. variables in the desired endian format.
  • struct_deser - Inspiration for this crate.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

This project try follow rules:

This README was generated with cargo-readme from template

endian_codec's People

Contributors

adriaenxo avatar wucke13 avatar xoac avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

wucke13 mbyzhang

endian_codec's Issues

Derives for enums

It'd be nice if this crate supported enums too. Suggested API:

`#[derive(DecodeME)]`
#[endian_codec(tag_repr = "u16", endian = "le")] // tag will be treated as u16 and matched against the enum variants
enum Message {
    #[endian_codec(tag = 42)]
    Foo(FooStruct),
    #[endian_codec(tag = 47)]
    Bar(BarStruct),
}

I may write the PR if I need it, but don't expect it any time soon (probably not this year).

Document error handling

The slices given to encoding can have the wrong size. Judging from the signature (and the implementation from copy_from_bytes), panicing on a mismatch is the expected behavior, but that should be explicit. (A future version that utilizes const generics might even be able to make that a build time error).

Support for arbitrary sized byte array

Hi!

First of, thanks for the lib, I'm doing some PoC network protocols and by far it's solving the headache of OS endianness. My question is how can I support arbitrary sized byte array?

For example:

#[derive(PackedSize, EncodeBE, DecodeBE)]
pub struct Chat {
    group: [u8; 32],
    msg_size: u32,
    msg: [u8; 256],
}

msg should be max 256 bytes, the actual size is msg_size. Any idea how to overcome this? Or should I manually handle the data coming from the network?

Using short or long for with attribute #[endian = "..."]

When working with MixedEndian(Des)/(S)erializer is possible to use types that doesn't implement this trait for field. You just need to add #[endian] attribute. This is just to decide use a long or short form.

#[derive(EndianSize, MixedEndianSerialize)]
struct A {
  #[endian = "little"]
  a: i32,
  #[endian = "le"]
  b: i32,
}

I feel better with long form.

Rename crate

I am not quite sure name of this crate is correct. The same suggest it works with serde but it doesn't.

It transform rust types as little or big endiannes.

Any suggestions are welcome.

Add a README file

It'd be convenient for the library to have a README (commonly a README.md) file that gives a brief outline of the crate's purpose and links to repository (not everyone will be reading it on github), crates.io page and documentation.

If you dislike writing that manually, cargo readme can assist.

Add packed_struct to list of similar crates

As far as I understand this crate does not only deal with endianess but also with packing and unpacking structs. To me it looks like Rust has quite a weak spot in this domain, because there is really not one widely used/well maintained crate for (de)serializing structs to a custom byte format. Having one more mentioned in your list will hopefully spare some time for someone in the future.

https://crates.io/crates/packed_struct

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.