-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make an initial version of the Endian trait and its custom derive
- Loading branch information
myrrlyn
committed
Aug 20, 2017
0 parents
commit 18c1201
Showing
11 changed files
with
457 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
/target/ | ||
**/*.rs.bk | ||
Cargo.lock |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
[package] | ||
name = "endian_trait" | ||
version = "0.1.0" | ||
authors = [ | ||
"myrrlyn <myrrlyn@outlook.com>", | ||
] | ||
license = "MIT" | ||
description = "A trait for Endianness conversions that can be implemented on most types" | ||
|
||
[dependencies] | ||
endian_trait_derive = { path = "endian_trait_derive", version = "0.1" } | ||
|
||
[workspace] | ||
endian_trait_derive = { path = "endian_trait_derive" } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2017 myrrlyn | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
# Endian Trait | ||
|
||
This library provides a trait called `Endian` that requires four methods for | ||
converting to/from big/little endian orders. | ||
|
||
This trait is implemented on the integer primitives `{i,u}{8,16,32,64,size}`. | ||
|
||
Any item where an endian conversion makes sense can implement this trait, and | ||
items composed of all `Endian` items can themselves be `Endian` | ||
|
||
An associated crate, `endian_trait_derive`, provides a custom derive. | ||
|
||
This will work on structs of integer primitives, and nested structs where inner | ||
structs are themselves `Endian`. | ||
|
||
This does ***NOT*** work on tuple structs, or on enums with specified `repr` | ||
layouts. | ||
|
||
I would like to expand this crate to include these types, but at the moment I am | ||
struggling to make the derivation macro support these types. | ||
|
||
```rust | ||
extern crate endian_trait; | ||
#[macro_use] | ||
extern crate endian_trait_derive; | ||
|
||
#[derive(Endian)] | ||
struct Example { | ||
a: u64, | ||
b: i32, | ||
c: u16, | ||
d: u8, | ||
} | ||
|
||
#[derive(Endian)] | ||
struct Nested { | ||
a: Example, | ||
b: u8, | ||
} | ||
|
||
#[test] | ||
fn flip_it() { | ||
let e = Example { | ||
a: 0x0123456789abcdef, | ||
b: 0x01234567, | ||
c: 0x89ab, | ||
d: 0xcd, | ||
}; | ||
|
||
// I'm assuming you're on x86, a little-endian chip. | ||
let Example { | ||
a, | ||
b, | ||
c, | ||
d, | ||
} = e.to_be(); | ||
|
||
assert_eq!(a, 0xefcdab8967452301); | ||
assert_eq!(b, 0x67452301); | ||
assert_eq!(c, 0xab89); | ||
assert_eq!(d, 0xcd); | ||
|
||
let n = Nested { | ||
a: Example { | ||
a: a, | ||
b: b, | ||
c: c, | ||
d: d, | ||
}, | ||
b: 0xef, | ||
}; | ||
|
||
assert_eq!(n.to_be().b == 0xef); | ||
} | ||
``` | ||
|
||
The use case for this library is for assisting with flipping complex data | ||
structures when they move across the network boundary. Here's an example | ||
demonstrating the (relative) ease of moving a (relatively) complex structure | ||
across a network boundary. | ||
|
||
```rust | ||
extern crate endian_trait; | ||
#[macro_use] | ||
extern crate endian_trait_derive; | ||
|
||
use std::convert::{From,To}; | ||
|
||
#[derive(Endian)] | ||
struct ComplexData { | ||
a: ChildStruct, | ||
b: ChildStruct, | ||
} | ||
#[derive(Endian)] | ||
struct ChildStruct { | ||
a: u32, | ||
b: u16, | ||
} | ||
|
||
impl From<[u8; 12]> for ComplexData { | ||
fn from(src: [u8; 12]) -> Self { | ||
use std::mem::transmute; | ||
unsafe { | ||
ComplexData { | ||
a: ChildStruct { | ||
a: transmute(src[.. 4]), | ||
b: transmute(src[4 .. 6]), | ||
}, | ||
b: ChildStruct { | ||
a: transmute(src[6 .. 10]), | ||
b: transmute(src[10 ..]), | ||
}, | ||
}.from_be() | ||
} | ||
} | ||
} | ||
impl To<[u8; 12]> for ComplexData { | ||
fn to(self) -> [u8; 12] { | ||
use std::mem::transmute; | ||
unsafe { | ||
let s = self.to_be(); | ||
let out: [u8; 12]; | ||
out[.. 4] = transmute(self.a.a); | ||
out[4 .. 6] = transmute(self.a.b); | ||
out[6 .. 10] = transmute(self.b.a); | ||
out[10 ..] = transmute(self.b.b); | ||
} | ||
} | ||
} | ||
``` | ||
|
||
Now the conversion methods that switch between the structure and a byte | ||
representation automatically perform endian conversion as well. You may want to | ||
keep endianness separate, and only do so at the network (so that you can | ||
serialize to bytes for non-network transmission, for example), in which case you | ||
would remove the Endian trait calls from the conversion traits, and do so at the | ||
appropriate call site, like so: | ||
|
||
```rust | ||
let s = ComplexData { /* ... */ }; | ||
let outbound: [u8; 12] = s.to_be().into(); | ||
let inbound: [u8; 12] = read_from_network(); | ||
let r: ComplexData = inbound.into().from_be(); | ||
``` |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
[package] | ||
name = "endian_trait_derive" | ||
version = "0.1.0" | ||
authors = [ | ||
"myrrlyn <myrrlyn@outlook.com>", | ||
] | ||
license = "MIT" | ||
description = "A custom derive for the Endian trait" | ||
|
||
[lib] | ||
proc-macro = true | ||
|
||
[dependencies] | ||
quote = "0.3" | ||
syn = "0.11" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2017 myrrlyn | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# Endian Trait Derivation | ||
|
||
This provides a custom derive for the Endian trait on structs. | ||
|
||
It currently only works on normal structs with named fields. It does not work on | ||
tuple structs or enums. I would like to expand it to reach these before I | ||
consider this ready for a 1.0 release. | ||
|
||
```rust | ||
extern crate endian_trait; | ||
#[macro_use] | ||
extern crate endian_trait_derive; | ||
|
||
#[derive(Endian)] | ||
struct Example { | ||
a: i32, | ||
// others | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
extern crate proc_macro; | ||
extern crate syn; | ||
#[macro_use] | ||
extern crate quote; | ||
|
||
use proc_macro::TokenStream; | ||
use quote::Tokens; | ||
use syn::{ | ||
Body, | ||
DeriveInput, | ||
VariantData, | ||
}; | ||
|
||
#[proc_macro_derive(Endian)] | ||
pub fn endian_trait(source: TokenStream) -> TokenStream { | ||
let s = source.to_string(); | ||
let ast = syn::parse_derive_input(&s).unwrap(); | ||
let imp = impl_endian(&ast); | ||
imp.parse().unwrap() | ||
} | ||
|
||
fn impl_endian(ast: &DeriveInput) -> Tokens { | ||
let name = &ast.ident; | ||
match &ast.body { | ||
&Body::Enum(ref _variants) => { | ||
unimplemented!(); | ||
}, | ||
&Body::Struct(VariantData::Struct(ref fields)) => { | ||
// I know that this is a named-field struct, so unwrap is fine. | ||
let names: Vec<_> = fields.iter().map(|f| match f.ident { | ||
Some(ref n) => n, | ||
None => panic!(), | ||
}).collect(); | ||
let (nl, nr) = (&names, &names); | ||
quote! { | ||
impl Endian for #name { | ||
fn from_be(self) -> Self { Self { | ||
#( #nl: Endian::from_be(self.#nr), )* | ||
} } | ||
fn from_le(self) -> Self { Self { | ||
#( #nl: Endian::from_le(self.#nr), )* | ||
} } | ||
fn to_be(self) -> Self { Self { | ||
#( #nl: Endian::to_be(self.#nr), )* | ||
} } | ||
fn to_le(self) -> Self { Self { | ||
#( #nl: Endian::to_le(self.#nr), )* | ||
} } | ||
} | ||
} | ||
}, | ||
&Body::Struct(VariantData::Tuple(ref _fields)) => { | ||
unimplemented!(); | ||
}, | ||
&Body::Struct(VariantData::Unit) => { | ||
panic!("You can't implement Endian conversions on a ZST"); | ||
}, | ||
} | ||
} |
Oops, something went wrong.