Skip to content

Instantly share code, notes, and snippets.

@jfager
Last active June 16, 2019 17:36
Show Gist options
  • Save jfager/5936197 to your computer and use it in GitHub Desktop.
Save jfager/5936197 to your computer and use it in GitHub Desktop.
Fun w/ rust macros - easily impl traits for fixed-length vectors.
extern mod std;
struct Foo([u8,..2]);
struct Bar([u8,..4]);
macro_rules! fixed_iter_bytes(
($t:ty) => (
impl IterBytes for $t {
fn iter_bytes(&self, lsb0: bool, f: std::to_bytes::Cb) -> bool {
self.as_slice().iter_bytes(lsb0, f)
}
}
);
)
macro_rules! fixed_eq(
($t:ty) => (
impl Eq for $t {
fn eq(&self, other: &$t) -> bool {
self.as_slice().eq(&other.as_slice())
}
}
);
)
macro_rules! fixed_ord(
($t:ty) => (
impl Ord for $t {
fn lt(&self, other: &$t) -> bool {
self.as_slice().lt(&other.as_slice())
}
}
);
)
macro_rules! fixed_clone(
($t:ident, $arrt: ty, $len:expr) => (
impl Clone for $t {
fn clone(&self) -> $t {
let mut new_vec: [$arrt, ..$len] = [0, .. $len];
for new_vec.mut_iter().zip((**self).iter()).advance |(x,y)| { *x = y.clone(); }
$t(new_vec)
}
}
);
)
fixed_iter_bytes!(Foo)
fixed_eq!(Foo)
fixed_ord!(Foo)
fixed_clone!(Foo, u8, 2)
fixed_iter_bytes!(Bar)
fixed_eq!(Bar)
fixed_ord!(Bar)
fixed_clone!(Bar, u8, 4)
#[deriving(IterBytes, Eq, Ord, Clone)]
struct Baz {
x: u8,
y: Foo,
z: Bar
}
fn main() {
let b = Baz { x: 1u8, y: Foo([1u8,2u8]), z: Bar([1u8,2u8,3u8,4u8]) };
std::io::println(fmt!("%?", b));
std::io::println(fmt!("%?", b.clone()));
}
pub use self::generated::*;
macro_rules! fixed_vec_type(
($t:ident, $arrt: ty, $len:expr) => (mod generated {
extern mod std;
pub struct $t([$arrt,..$len]);
impl IterBytes for $t {
fn iter_bytes(&self, lsb0: bool, f: std::to_bytes::Cb) -> bool {
self.as_slice().iter_bytes(lsb0, f)
}
}
impl Eq for $t {
fn eq(&self, other: &$t) -> bool {
self.as_slice().eq(&other.as_slice())
}
}
impl Ord for $t {
fn lt(&self, other: &$t) -> bool {
self.as_slice().lt(&other.as_slice())
}
}
impl Clone for $t {
fn clone(&self) -> $t {
let mut new_vec: [$arrt, ..$len] = [0, .. $len];
for new_vec.mut_iter().zip((**self).iter()).advance |(x,y)| { *x = y.clone(); }
$t(new_vec)
}
}
});
)
fixed_vec_type!(Foo, u8, 2)
#[deriving(IterBytes, Eq, Ord, Clone)]
struct Baz {
x: u8,
y: Foo
}
fn main() {
let b = Baz { x: 1u8,
y: Foo([1u8,2u8]) };
std::io::println(fmt!("%?", b));
std::io::println(fmt!("%?", b.clone()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment