Skip to content

Instantly share code, notes, and snippets.

@gmbeard
Created November 8, 2017 08:49
Show Gist options
  • Save gmbeard/7ac7167bfea6e5ededdc8559dd65b5e7 to your computer and use it in GitHub Desktop.
Save gmbeard/7ac7167bfea6e5ededdc8559dd65b5e7 to your computer and use it in GitHub Desktop.
use std::ops::Deref;
pub trait Crypto {
type Output;
type Error;
fn encrypt(&mut self) -> Result<Self::Output, Self::Error>;
}
impl<'a, T: Crypto> Crypto for &'a mut T {
type Output = T::Output;
type Error = T::Error;
fn encrypt(&mut self) -> Result<Self::Output, Self::Error> {
T::encrypt(*self)
}
}
pub struct Rot13(Vec<u8>);
impl Rot13 {
pub fn new<'a, I>(i: I) -> Rot13
where I: IntoIterator<Item=&'a u8>
{
Rot13(i.into_iter().map(|b| *b).collect())
}
}
fn rot13_byte(val: u8, start_from: u8) -> u8 {
start_from + ((val - start_from) + 13) % 26
}
impl Crypto for Rot13 {
type Output = ();
type Error = ();
fn encrypt(&mut self) -> Result<Self::Output, Self::Error> {
for b in self.0.iter_mut() {
match *b {
b'A'...b'Z' => *b = rot13_byte(*b, b'A'),
b'a'...b'z' => *b = rot13_byte(*b, b'a'),
_ => *b = *b
}
}
Ok(())
}
}
impl Deref for Rot13 {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub fn encrypt_with<C: Crypto>(mut c: C) -> Result<C::Output, C::Error> {
c.encrypt()
}
@gmbeard
Copy link
Author

gmbeard commented Nov 8, 2017

Generating asm for the above results in https://gist.github.com/gmbeard/48ce5280ecb63f8e475722228ee2e296

Applying this diff seems to defeat vectorization...

@@ -40,7 +40,7 @@
             match *b {
                 b'A'...b'Z' => *b = rot13_byte(*b, b'A'),
                 b'a'...b'z' => *b = rot13_byte(*b, b'a'),
-                _ => *b = *b
+                _ => {}
             }
         }

... and results in https://gist.github.com/gmbeard/b0de6903bb6f5dd6c34c4d7b8fb8a9e7

I'm compiling asm output with...

rustc --crate-type lib --cfg release --emit=asm -C opt-level=3 rust-asm-difference.rs

rustc versions...

rustc 1.21.0 (3b72af97e 2017-10-09)
rustc 1.22.0-nightly (b633341c4 2017-10-20)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment