<commit_before>use std::str;

use nom::{IResult, multispace, eof, alphanumeric, space, not_line_ending};
use nom::IResult::*;

use std::io::prelude::*;
use std::fs::File;
use std::collections::HashMap;

named!(quoted_string <&str>,
  chain!(
    tag!("\"")              ~
    qs: map_res!(
      take_until!("\""),
      str::from_utf8)     ~
    tag!("\"")              ,
  || { qs }
  )
);

named!(input_kind <&[u8], &str>, map_res!(alphanumeric, str::from_utf8));

named!(blanks,
    chain!(
        many0!(alt!(multispace | comment | eol | eof)),
        || { &b""[..] }));

named!(comment,
    chain!(
        tag!("#") ~
        not_line_ending? ~
        alt!(eol | eof),
        || { &b""[..] }));

named!(eol,
    alt!(tag!("\r\n") | tag!("\n") | tag!("\u{2028}") | tag!("\u{2029}")));

named!(key_value    <&[u8],(&str,&str)>,
  chain!(
    key: map_res!(alphanumeric, str::from_utf8) ~
      space?                            ~
      tag!("=")                         ~
      space?                            ~
    val: alt!(
      quoted_string |
      map_res!(
        take_until_either!("\n\r#"),
        str::from_utf8
      )
      )                                    ~
      blanks                               ,
    ||{(key, val)}
  )
);

named!(keys_and_values_aggregator<&[u8], Vec<(&str,&str)> >,
 chain!(
     tag!("{")      ~
     blanks     ~
     kva: many0!(key_value) ~
     blanks    ~
     tag!("}"),
 || {kva} )
);

fn keys_and_values(input:&[u8]) -> IResult<&[u8], HashMap<String, String> > {
  let mut h: HashMap<String, String> = HashMap::new();

  match keys_and_values_aggregator(input) {
    IResult::Done(i, tuple_vec) => {
      for &(k,v) in tuple_vec.iter() {
        h.insert(k.to_owned(), v.to_owned());
      }
      IResult::Done(i, h)
    },
    IResult::Incomplete(a)     => IResult::Incomplete(a),
    IResult::Error(a)          => IResult::Error(a)
  }
}

named!(input_and_params <&[u8], (String, Option<HashMap<String,String>>)>,
  chain!(
    blanks                     ~
    ik: input_kind                  ~
    blanks                     ~
    kv: keys_and_values?            ~
    blanks                     ,
    || { (ik.to_owned(), kv) }
  )
);

named!(inputs <&[u8], Vec<(String, Option<HashMap<String,String>>)> >,
  chain!(
    tag!("input")                    ~
    blanks                      ~
    tag!("{")                        ~
    blanks                      ~
    ins: many0!(input_and_params) ~
    blanks                      ~
    tag!("}")                        ~
    blanks                      ,
    || { (ins) }
  )
);

pub fn read_config_file(filename: &str) -> Result<Vec<(String,  Option<HashMap<String,String>>)>, String> {
  println!("Reading config file.");
  let mut f = File::open(filename).unwrap();
  let mut s = String::new();

  match f.read_to_string(&mut s) {
    Ok(_) => {
      let source = s.into_bytes();
      match inputs(&source) {
        Done(_, configuration) => Ok(configuration),
        Error(e) => {
          Err(format!("Parse error: {:?}", e))
        },
        Incomplete(e) => {
          Err(format!("Incomplete content -> await: {:?}", e))
        }
      }
    },
    Err(e) => Err(format!("Read error: {:?}", e))
  }
}

#[test]
fn test_config_parser() {
  match read_config_file("files/test_config.conf") {
    Ok(conf) => {
      // Some({"path": "some literal string", "pipo": "12"})), (Stdin, Some({"tag": "stdin"}))]
      assert_eq!(conf.len(), 2);
      assert_eq!(conf[0].0, "file");
      let mut file_conf = HashMap::new();
      file_conf.insert("path".to_owned(), "some literal string".to_owned());
      file_conf.insert("pipo".to_owned(), "12".to_owned());
      assert_eq!(conf[0].1, Some(file_conf) );

      assert_eq!(conf[1].0, "stdin");
      let mut stdin_conf = HashMap::new();
      stdin_conf.insert("tag".to_owned(), "stdin".to_owned());
      assert_eq!(conf[1].1, Some(stdin_conf) );

    },
    Err(e) => assert!(false, format!("Unable to parse configuration file: {}", e))
  }
}
<commit_msg>Reindent to please my mind<commit_after>use std::str;

use nom::{IResult, multispace, eof, alphanumeric, space, not_line_ending};
use nom::IResult::*;

use std::io::prelude::*;
use std::fs::File;
use std::collections::HashMap;

named!(quoted_string <&str>,
  chain!(
    tag!("\"")              ~
    qs: map_res!(
      take_until!("\""),
      str::from_utf8)       ~
    tag!("\"")              ,
  || { qs }
  )
);

named!(input_kind <&[u8], &str>, map_res!(alphanumeric, str::from_utf8));

named!(blanks,
    chain!(
        many0!(alt!(multispace | comment | eol | eof)),
        || { &b""[..] }));

named!(comment,
    chain!(
        tag!("#")           ~
        not_line_ending?    ~
        alt!(eol | eof)     ,
        || { &b""[..] }));

named!(eol,
    alt!(tag!("\r\n") | tag!("\n") | tag!("\u{2028}") | tag!("\u{2029}")));

named!(key_value    <&[u8],(&str,&str)>,
  chain!(
    key: map_res!(alphanumeric, str::from_utf8) ~
      space?                            ~
      tag!("=")                         ~
      space?                            ~
    val: alt!(
      quoted_string |
      map_res!(
        take_until_either!("\n\r#"),
        str::from_utf8
      )
      )                                    ~
      blanks                               ,
    ||{(key, val)}
  )
);

named!(keys_and_values_aggregator<&[u8], Vec<(&str,&str)> >,
 chain!(
     tag!("{")                ~
     blanks                   ~
     kva: many0!(key_value)   ~
     blanks                   ~
     tag!("}")                ,
 || {kva} )
);

fn keys_and_values(input:&[u8]) -> IResult<&[u8], HashMap<String, String> > {
  let mut h: HashMap<String, String> = HashMap::new();

  match keys_and_values_aggregator(input) {
    IResult::Done(i, tuple_vec) => {
      for &(k,v) in tuple_vec.iter() {
        h.insert(k.to_owned(), v.to_owned());
      }
      IResult::Done(i, h)
    },
    IResult::Incomplete(a)     => IResult::Incomplete(a),
    IResult::Error(a)          => IResult::Error(a)
  }
}

named!(input_and_params <&[u8], (String, Option<HashMap<String,String>>)>,
  chain!(
    blanks                          ~
    ik: input_kind                  ~
    blanks                          ~
    kv: keys_and_values?            ~
    blanks                          ,
    || { (ik.to_lowercase(), kv) }
  )
);

named!(inputs <&[u8], Vec<(String, Option<HashMap<String,String>>)> >,
  chain!(
    tag!("input")                     ~
    blanks                            ~
    tag!("{")                         ~
    blanks                            ~
    ins: many0!(input_and_params)     ~
    blanks                            ~
    tag!("}")                         ~
    blanks                            ,
    || { (ins) }
  )
);

pub fn read_config_file(filename: &str) -> Result<Vec<(String,  Option<HashMap<String,String>>)>, String> {
  println!("Reading config file.");
  let mut f = File::open(filename).unwrap();
  let mut s = String::new();

  match f.read_to_string(&mut s) {
    Ok(_) => {
      let source = s.into_bytes();
      match inputs(&source) {
        Done(_, configuration) => Ok(configuration),
        Error(e) => {
          Err(format!("Parse error: {:?}", e))
        },
        Incomplete(e) => {
          Err(format!("Incomplete content -> await: {:?}", e))
        }
      }
    },
    Err(e) => Err(format!("Read error: {:?}", e))
  }
}

#[test]
fn test_config_parser() {
  match read_config_file("files/test_config.conf") {
    Ok(conf) => {
      // Some({"path": "some literal string", "pipo": "12"})), (Stdin, Some({"tag": "stdin"}))]
      assert_eq!(conf.len(), 2);
      assert_eq!(conf[0].0, "file");
      let mut file_conf = HashMap::new();
      file_conf.insert("path".to_owned(), "some literal string".to_owned());
      file_conf.insert("pipo".to_owned(), "12".to_owned());
      assert_eq!(conf[0].1, Some(file_conf) );

      assert_eq!(conf[1].0, "stdin");
      let mut stdin_conf = HashMap::new();
      stdin_conf.insert("tag".to_owned(), "stdin".to_owned());
      assert_eq!(conf[1].1, Some(stdin_conf) );

    },
    Err(e) => assert!(false, format!("Unable to parse configuration file: {}", e))
  }
}
<|endoftext|>


<commit_before>use super::cpuid;
use phf;

pub mod intel;

use core::fmt::{Write, Result, Error};
use core::str;

const MODEL_LEN: usize = 20;

#[derive(Default)]
struct ModelWriter {
    buffer: [u8; MODEL_LEN],
    index: usize
}

impl ModelWriter {
    fn as_str(&self) -> &str {
        str::from_utf8(&self.buffer[..self.index]).unwrap()
    }
}

impl Write for ModelWriter {
    fn write_str(&mut self, s: &str) -> Result {
        // TODO: There exists probably a more efficient way of doing this:
        for c in s.chars() {
            if self.index >= self.buffer.len() {
                return Err(Error)
            }
            self.buffer[self.index] = c as u8;
            self.index += 1;
        }
        Ok(())
    }
}

/// Return performance counter description for the running micro-architecture.
pub fn available_counters() -> Option<&'static phf::Map<&'static str, intel::description::IntelPerformanceCounterDescription>> {

    let cpuid = cpuid::CpuId::new();

    cpuid.get_vendor_info().map_or(None, |vf| {
        cpuid.get_feature_info().map_or(None, |fi| {
            let vendor = vf.as_string();
            let (family, extended_model, model) = (fi.family_id(), fi.extended_model_id(), fi.model_id());

            let mut writer: ModelWriter = Default::default();
            // Should work as long as it fits in MODEL_LEN bytes:
            write!(writer, "{}-{}-{:X}{:X}", vendor, family, extended_model, model).unwrap();
            let key = writer.as_str();

            intel::counters::COUNTER_MAP.get(key)
        })
    })
}
<commit_msg>Expose uncore counter, avoid code duplication.<commit_after>use super::cpuid;
use phf;

use core::fmt::{Write, Result, Error};
use core::str;

pub mod intel;

const MODEL_LEN: usize = 20;

#[derive(Default)]
struct ModelWriter {
    buffer: [u8; MODEL_LEN],
    index: usize
}

impl ModelWriter {
    fn as_str(&self) -> &str {
        str::from_utf8(&self.buffer[..self.index]).unwrap()
    }
}

impl Write for ModelWriter {
    fn write_str(&mut self, s: &str) -> Result {
        // TODO: There exists probably a more efficient way of doing this:
        for c in s.chars() {
            if self.index >= self.buffer.len() {
                return Err(Error)
            }
            self.buffer[self.index] = c as u8;
            self.index += 1;
        }
        Ok(())
    }
}

// Format must be a string literal
macro_rules! get_counters {
    ($format:expr) => ({
        let cpuid = cpuid::CpuId::new();

        cpuid.get_vendor_info().map_or(None, |vf| {
            cpuid.get_feature_info().map_or(None, |fi| {
                let vendor = vf.as_string();
                let (family, extended_model, model) = (fi.family_id(), fi.extended_model_id(), fi.model_id());

                let mut writer: ModelWriter = Default::default();
                // Should work as long as it fits in MODEL_LEN bytes:
                write!(writer, $format, vendor, family, extended_model, model).unwrap();
                let key = writer.as_str();

                intel::counters::COUNTER_MAP.get(key)
            })
        })
    });
}

/// Return all core performance counters for the running micro-architecture.
pub fn core_counters() -> Option<&'static phf::Map<&'static str, intel::description::IntelPerformanceCounterDescription>> {
    get_counters!("{}-{}-{:X}{:X}-core")
}

/// Return all uncore performance counters for the running micro-architecture.
pub fn uncore_counters() -> Option<&'static phf::Map<&'static str, intel::description::IntelPerformanceCounterDescription>> {
    get_counters!("{}-{}-{:X}{:X}-uncore")
}
<|endoftext|>


<commit_before>use super::scheduler::*;

use std::sync::Arc;
use futures::sync::oneshot;
use futures::future::Future;

///
/// A data storage structure used to govern synchronous and asynchronous access to an underlying object.
///
#[derive(Debug)]
pub struct Desync<T: Send> {
    /// Queue used for scheduling runtime for this object
    queue:  Arc<JobQueue>,

    /// Data for this object. Boxed so the pointer remains the same through the lifetime of the object.
    data:   Box<T>
}

// Rust actually derives this anyway at the moment
unsafe impl<T: Send> Send for Desync<T> {}

// True iff queue: Sync
unsafe impl<T: Send> Sync for Desync<T> {}

///
/// Used for passing the data pointer through to the queue
///
/// 'Safe' because the queue is synchronised during drop, so we can never use the pointer
/// if the object does not exist.
///
struct DataRef<T: Send>(*const T);
unsafe impl<T: Send> Send for DataRef<T> {}

// TODO: we can change DataRef to Shared (https://doc.rust-lang.org/std/ptr/struct.Shared.html in the future)

// TODO: T does not need to be static as we know that its lifetime is at least the lifetime of Desync<T> and hence the queue
impl<T: 'static+Send> Desync<T> {
    ///
    /// Creates a new Desync object
    ///
    pub fn new(data: T) -> Desync<T> {
        let queue = queue();

        Desync {
            queue:  queue,
            data:   Box::new(data)
        }
    }

    ///
    /// Performs an operation asynchronously on this item. This function will return
    /// immediately and the job will happen on a separate thread at some time in the
    /// future (generally fairly soon).
    ///
    /// Jobs are always performed in the order that they are queued and are always
    /// performed synchronously with respect to this object.
    ///
    pub fn async<TFn>(&self, job: TFn)
    where TFn: 'static+Send+FnOnce(&mut T) -> () {
        unsafe {
            // As drop() is the last thing called, we know that this object will still exist at the point where
            let data = DataRef(&*self.data);

            async(&self.queue, move || {
                let data = data.0 as *mut T;
                job(&mut *data);
            })
        }
    }

    ///
    /// Performs an operation synchronously on this item. This will be queued with any other
    /// jobs that this item may be performing, and this function will not return until the
    /// job is complete and the result is available.
    ///
    pub fn sync<TFn, Result>(&self, job: TFn) -> Result
    where TFn: Send+FnOnce(&mut T) -> Result, Result: Send {
        let result = unsafe {
            // As drop() is the last thing called, we know that this object will still exist at the point where
            let data = DataRef(&*self.data);

            sync(&self.queue, move || {
                let data = data.0 as *mut T;
                job(&mut *data)
            })
        };

        result
    }

    ///
    /// Performs an operation asynchronously on this thread, returning the result via a future.
    ///
    pub fn future<TFn, Item: 'static+Send>(&self, job: TFn) -> Box<Future<Item=Item, Error=oneshot::Canceled>>
    where TFn: 'static+Send+FnOnce(&mut T) -> Item {
        let (send, receive) = oneshot::channel();

        self.async(|data| {
            let result = job(data);

            if let Err(e) = send.send(result) {
                panic!(e);
            }
        });

        Box::new(receive)
    }
}

impl<T: Send> Drop for Desync<T> {
    fn drop(&mut self) {
        // Ensure that everything on the queue has committed by queueing a last synchronous event
        // (Not synchronising the queue would make this unsafe as we would hold on to a pointer to
        // the internal data structure)
        sync(&self.queue, || {});
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::thread::*;
    use std::time::*;
    use super::super::scheduler::test::timeout;

    #[derive(Debug)]
    struct TestData {
        val: u32
    }

    #[test]
    fn can_retrieve_data_synchronously() {
        let desynced = Desync::new(TestData { val: 0 });

        assert!(desynced.sync(|data| data.val) == 0);
    }

    #[test]
    fn can_update_data_asynchronously() {
        let desynced = Desync::new(TestData { val: 0 });

        desynced.async(|data| {
            sleep(Duration::from_millis(100));
            data.val = 42;
        });

        assert!(desynced.sync(|data| data.val) == 42);
    }

    #[test]
    fn can_update_data_asynchronously_1000_times() {
        for _i in 0..1000 {
            timeout(|| {
                let desynced = Desync::new(TestData { val: 0 });

                desynced.async(|data| {
                    data.val = 42;
                });
                desynced.async(|data| {
                    data.val = 43;
                });

                assert!(desynced.sync(|data| data.val) == 43);
            }, 500);
        }
    }

    #[test]
    fn can_update_data_with_future() {
        timeout(|| {
            use futures::executor;

            let desynced = Desync::new(TestData { val: 0 });

            desynced.async(|data| {
                sleep(Duration::from_millis(100));
                data.val = 42;
            });

            let mut future = executor::spawn(desynced.future(|data| {
                data.val
            }));

            assert!(future.wait_future().unwrap() == 42);
        }, 500);
    }

    #[test]
    fn can_update_data_with_future_1000_times() {
        // Seems to timeout fairly reliably after signalling the future
        use futures::executor;

        for _i in 0..1000 {
            timeout(|| {
                let desynced = Desync::new(TestData { val: 0 });

                desynced.async(|data| {
                    sleep(Duration::from_millis(1));
                    data.val = 42;
                });

                let mut future = executor::spawn(desynced.future(|data| data.val));

                assert!(future.wait_future().unwrap() == 42);
            }, 500);
        }
    }

    #[test]
    fn dropping_while_running_isnt_obviously_bad() {
        let desynced = Desync::new(TestData { val: 0 });

        desynced.async(|data| {
            sleep(Duration::from_millis(100));
            data.val = 42;
        });
        desynced.async(|data| {
            sleep(Duration::from_millis(100));
            data.val = 42;
        });
    }
}
<commit_msg>Remove sleep from futures test.<commit_after>use super::scheduler::*;

use std::sync::Arc;
use futures::sync::oneshot;
use futures::future::Future;

///
/// A data storage structure used to govern synchronous and asynchronous access to an underlying object.
///
#[derive(Debug)]
pub struct Desync<T: Send> {
    /// Queue used for scheduling runtime for this object
    queue:  Arc<JobQueue>,

    /// Data for this object. Boxed so the pointer remains the same through the lifetime of the object.
    data:   Box<T>
}

// Rust actually derives this anyway at the moment
unsafe impl<T: Send> Send for Desync<T> {}

// True iff queue: Sync
unsafe impl<T: Send> Sync for Desync<T> {}

///
/// Used for passing the data pointer through to the queue
///
/// 'Safe' because the queue is synchronised during drop, so we can never use the pointer
/// if the object does not exist.
///
struct DataRef<T: Send>(*const T);
unsafe impl<T: Send> Send for DataRef<T> {}

// TODO: we can change DataRef to Shared (https://doc.rust-lang.org/std/ptr/struct.Shared.html in the future)

// TODO: T does not need to be static as we know that its lifetime is at least the lifetime of Desync<T> and hence the queue
impl<T: 'static+Send> Desync<T> {
    ///
    /// Creates a new Desync object
    ///
    pub fn new(data: T) -> Desync<T> {
        let queue = queue();

        Desync {
            queue:  queue,
            data:   Box::new(data)
        }
    }

    ///
    /// Performs an operation asynchronously on this item. This function will return
    /// immediately and the job will happen on a separate thread at some time in the
    /// future (generally fairly soon).
    ///
    /// Jobs are always performed in the order that they are queued and are always
    /// performed synchronously with respect to this object.
    ///
    pub fn async<TFn>(&self, job: TFn)
    where TFn: 'static+Send+FnOnce(&mut T) -> () {
        unsafe {
            // As drop() is the last thing called, we know that this object will still exist at the point where
            let data = DataRef(&*self.data);

            async(&self.queue, move || {
                let data = data.0 as *mut T;
                job(&mut *data);
            })
        }
    }

    ///
    /// Performs an operation synchronously on this item. This will be queued with any other
    /// jobs that this item may be performing, and this function will not return until the
    /// job is complete and the result is available.
    ///
    pub fn sync<TFn, Result>(&self, job: TFn) -> Result
    where TFn: Send+FnOnce(&mut T) -> Result, Result: Send {
        let result = unsafe {
            // As drop() is the last thing called, we know that this object will still exist at the point where
            let data = DataRef(&*self.data);

            sync(&self.queue, move || {
                let data = data.0 as *mut T;
                job(&mut *data)
            })
        };

        result
    }

    ///
    /// Performs an operation asynchronously on this thread, returning the result via a future.
    ///
    pub fn future<TFn, Item: 'static+Send>(&self, job: TFn) -> Box<Future<Item=Item, Error=oneshot::Canceled>>
    where TFn: 'static+Send+FnOnce(&mut T) -> Item {
        let (send, receive) = oneshot::channel();

        self.async(|data| {
            let result = job(data);

            if let Err(e) = send.send(result) {
                panic!(e);
            }
        });

        Box::new(receive)
    }
}

impl<T: Send> Drop for Desync<T> {
    fn drop(&mut self) {
        // Ensure that everything on the queue has committed by queueing a last synchronous event
        // (Not synchronising the queue would make this unsafe as we would hold on to a pointer to
        // the internal data structure)
        sync(&self.queue, || {});
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::thread::*;
    use std::time::*;
    use super::super::scheduler::test::timeout;

    #[derive(Debug)]
    struct TestData {
        val: u32
    }

    #[test]
    fn can_retrieve_data_synchronously() {
        let desynced = Desync::new(TestData { val: 0 });

        assert!(desynced.sync(|data| data.val) == 0);
    }

    #[test]
    fn can_update_data_asynchronously() {
        let desynced = Desync::new(TestData { val: 0 });

        desynced.async(|data| {
            sleep(Duration::from_millis(100));
            data.val = 42;
        });

        assert!(desynced.sync(|data| data.val) == 42);
    }

    #[test]
    fn can_update_data_asynchronously_1000_times() {
        for _i in 0..1000 {
            timeout(|| {
                let desynced = Desync::new(TestData { val: 0 });

                desynced.async(|data| {
                    data.val = 42;
                });
                desynced.async(|data| {
                    data.val = 43;
                });

                assert!(desynced.sync(|data| data.val) == 43);
            }, 500);
        }
    }

    #[test]
    fn can_update_data_with_future() {
        timeout(|| {
            use futures::executor;

            let desynced = Desync::new(TestData { val: 0 });

            desynced.async(|data| {
                sleep(Duration::from_millis(100));
                data.val = 42;
            });

            let mut future = executor::spawn(desynced.future(|data| {
                data.val
            }));

            assert!(future.wait_future().unwrap() == 42);
        }, 500);
    }

    #[test]
    fn can_update_data_with_future_1000_times() {
        // Seems to timeout fairly reliably after signalling the future
        use futures::executor;

        for _i in 0..1000 {
            timeout(|| {
                let desynced = Desync::new(TestData { val: 0 });

                desynced.async(|data| {
                    data.val = 42;
                });
                desynced.async(|data| {
                    data.val = 43;
                });

                let mut future = executor::spawn(desynced.future(|data| data.val));

                assert!(future.wait_future().unwrap() == 43);
            }, 500);
        }
    }

    #[test]
    fn dropping_while_running_isnt_obviously_bad() {
        let desynced = Desync::new(TestData { val: 0 });

        desynced.async(|data| {
            sleep(Duration::from_millis(100));
            data.val = 42;
        });
        desynced.async(|data| {
            sleep(Duration::from_millis(100));
            data.val = 42;
        });
    }
}
<|endoftext|>


<commit_before>use reflector::Reflector;
use rotor::Rotor;

#[derive(Clone, Debug)]
pub struct Enigma {
    slow: Rotor,
    mid: Rotor,
    fast: Rotor,
    reflector: Reflector,
}

impl Enigma {
    /// Creates a new `Enigma`, where `slow`, `mid`, and `fast` are integers
    /// ranging from 1-8 (corresponding to rotors I through VIII of the real
    /// Enigma machine), and `reflector` is one of `'A'`, `'B'`, or `'C'`.
    pub fn new(slow: usize, mid: usize, fast: usize, reflector: char) -> Enigma {
        let reflector = (reflector as usize) - 65;

        Enigma {
            slow: ROTORS[slow - 1].clone(),
            mid: ROTORS[mid - 1].clone(),
            fast: ROTORS[fast - 1].clone(),
            reflector: REFLECTORS[reflector].clone(),
        }
    }

    /// Advances the `fast` rotor of the `Enigma`, and also advances
    /// the `mid` and `slow` rotors if appropriate.
    pub fn advance(&mut self) {
        if self.fast.advance() {
            if self.mid.advance() {
                self.slow.advance();
            }
        }
    }
}

lazy_static! {
    static ref ROTORS: Vec<Rotor> = vec![
        Rotor::new("EKMFLGDQVZNTOWYHXUSPAIBRCJ", "Q"),
        Rotor::new("AJDKSIRUXBLHWTMCQGZNPYFVOE", "E"),
        Rotor::new("BDFHJLCPRTXVZNYEIWGAKMUSQO", "V"),
        Rotor::new("ESOVPZJAYQUIRHXLNFTGKDCMWB", "J"),
        Rotor::new("VZBRGITYUPSDNHLXAWMJQOFECK", "Z"),
        Rotor::new("JPGVOUMFYQBENHZRDKASXLICTW", "ZM"),
        Rotor::new("NZJHGRCXMYSWBOUFAIVLPEKQDT", "ZM"),
        Rotor::new("FKQHTLXOCBJSPDZRAMEWNIUYGV", "ZM"),
    ];

    static ref REFLECTORS: Vec<Reflector> = vec![
        Reflector::new("EJMZALYXVBWFCRQUONTSPIKHGD"),
        Reflector::new("YRUHQSLDPXNGOKMIEBFZCWVJAT"),
        Reflector::new("FVPJIAOYEDRZXWGCTKUQSBNMHL"),
    ];
}

#[cfg(test)]
mod tests {
    use super::Enigma;

    #[test]
    fn advance_enigma() {
        let mut enigma = Enigma::new(1, 2, 3, 'B');
        enigma.advance();
    }
}
<commit_msg>Implement Enigma encryption methods<commit_after>use reflector::Reflector;
use rotor::Rotor;

#[derive(Clone, Debug)]
pub struct Enigma {
    slow: Rotor,
    mid: Rotor,
    fast: Rotor,
    reflector: Reflector,
}

impl Enigma {
    /// Creates a new `Enigma`, where `slow`, `mid`, and `fast` are integers
    /// ranging from 1-8 (corresponding to rotors I through VIII of the real
    /// Enigma machine), and `reflector` is one of `'A'`, `'B'`, or `'C'`.
    pub fn new(slow: usize, mid: usize, fast: usize, reflector: char) -> Enigma {
        let reflector = (reflector as usize) - 65;

        Enigma {
            slow: ROTORS[slow - 1].clone(),
            mid: ROTORS[mid - 1].clone(),
            fast: ROTORS[fast - 1].clone(),
            reflector: REFLECTORS[reflector].clone(),
        }
    }

    /// Encrypts an entire message, advancing the rotors of the machine
    /// after each alphabetic character is encrypted.
    pub fn encrypt(&mut self, msg: &str) -> String {
        msg.chars().map(|c| self.encrypt_char(c)).collect()
    }

    /// Returns the substitution of a character, and advances
    /// the rotors if the input character was alphabetic.
    pub fn encrypt_char(&mut self, c: char) -> char {
        let encrypted_char = self.substitute(c);

        if c.is_alphabetic() {
            self.advance();
        }

        encrypted_char
    }

    /// Returns the substitution of a character, which is determined
    /// by passing the character in sequence through rotors from
    /// `fast` to `slow`, through the reflector, then inverted
    /// through the rotors from `slow` to `fast`.
    fn substitute(&self, c: char) -> char {
        if !c.is_alphabetic() {
            return c;
        }

        let c = self.slow.substitute(self.mid.substitute(self.fast.substitute(c)));
        let c = self.reflector.reflect(c);
        self.fast.invert(self.mid.invert(self.slow.invert(c)))
    }

    /// Advances the `fast` rotor, and also advances the
    /// `mid` and `slow` rotors if appropriate.
    fn advance(&mut self) {
        if self.fast.advance() {
            if self.mid.advance() {
                self.slow.advance();
            }
        }
    }
}

lazy_static! {
    static ref ROTORS: Vec<Rotor> = vec![
        Rotor::new("EKMFLGDQVZNTOWYHXUSPAIBRCJ", "Q"),
        Rotor::new("AJDKSIRUXBLHWTMCQGZNPYFVOE", "E"),
        Rotor::new("BDFHJLCPRTXVZNYEIWGAKMUSQO", "V"),
        Rotor::new("ESOVPZJAYQUIRHXLNFTGKDCMWB", "J"),
        Rotor::new("VZBRGITYUPSDNHLXAWMJQOFECK", "Z"),
        Rotor::new("JPGVOUMFYQBENHZRDKASXLICTW", "ZM"),
        Rotor::new("NZJHGRCXMYSWBOUFAIVLPEKQDT", "ZM"),
        Rotor::new("FKQHTLXOCBJSPDZRAMEWNIUYGV", "ZM"),
    ];

    static ref REFLECTORS: Vec<Reflector> = vec![
        Reflector::new("EJMZALYXVBWFCRQUONTSPIKHGD"),
        Reflector::new("YRUHQSLDPXNGOKMIEBFZCWVJAT"),
        Reflector::new("FVPJIAOYEDRZXWGCTKUQSBNMHL"),
    ];
}

#[cfg(test)]
mod tests {
    use super::Enigma;

    #[test]
    fn symmetrical_behaviour() {
        let msg = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";

        let mut enigma = Enigma::new(1, 2, 3, 'B');
        let ciphertext = enigma.encrypt(msg);

        // Reset the machine to its original state
        let mut enigma = Enigma::new(1, 2, 3, 'B');
        let plaintext = enigma.encrypt(&ciphertext);

        assert_eq!(plaintext, msg);
    }
}
<|endoftext|>


<commit_before>
//! Entity identifier and manager types.

use std::collections::Bitv;
use uuid::Uuid;

use Components;

/// Dual identifier for an entity.
///
/// The first element (uint) is the entity's index, used to locate components.
/// This value can be recycled, so the second element (Uuid) is used as an identifier.
#[stable]
#[deriving(Clone, Eq, PartialEq, Show)]
pub struct Entity(uint, Uuid);

#[stable]
impl Entity
{
    pub fn nil() -> Entity
    {
        Entity(0, Uuid::nil())
    }

    /// Returns the entity's index.
    #[inline]
    pub fn get_index(&self) -> uint
    {
        let &Entity(i, _) = self;
        i
    }

    /// Returns the entity's unique identifier.
    #[inline]
    pub fn get_id(&self) -> Uuid
    {
        let &Entity(_, id) = self;
        id
    }
}

impl Deref<uint> for Entity
{
    #[inline]
    fn deref(&self) -> &uint
    {
        let &Entity(ref i, _) = self;
        i
    }
}

pub trait EntityBuilder
{
    fn build(&mut self, &mut Components, Entity);
}

impl<'a> EntityBuilder for |&mut Components, Entity|: 'a
{
    fn build(&mut self, c: &mut Components, e: Entity)
    {
        (*self)(c, e);
    }
}

impl EntityBuilder for () { fn build(&mut self, _: &mut Components, _: Entity) {} }

pub trait EntityModifier
{
    fn modify(&mut self, &mut Components, Entity);
}

impl<'a> EntityModifier for |&mut Components, Entity|: 'a
{
    fn modify(&mut self, c: &mut Components, e: Entity)
    {
        (*self)(c, e);
    }
}

impl EntityModifier for () { fn modify(&mut self, _: &mut Components, _: Entity) {} }

/// Handles creation, activation, and validating of entities.
#[doc(hidden)]
pub struct EntityManager
{
    ids: IdPool,
    entities: Vec<Entity>,
    enabled: Bitv,
}

impl EntityManager
{
    /// Returns a new `EntityManager`
    pub fn new() -> EntityManager
    {
        EntityManager
        {
            ids: IdPool::new(),
            entities: Vec::new(),
            enabled: Bitv::new(),
        }
    }

    /// Creates a new `Entity`, assigning it the first available identifier.
    pub fn create_entity(&mut self) -> Entity
    {
        let ret = Entity(self.ids.get_id(), Uuid::new_v4());
        if *ret >= self.entities.len()
        {
            let diff = *ret - self.entities.len();
            self.entities.grow(diff+1, Entity(0, Uuid::nil()));
        }
        self.entities[mut][*ret] = ret;

        if *ret >= self.enabled.len()
        {
            let diff = *ret - self.enabled.len();
            self.enabled.grow(diff+1, false);
        }
        self.enabled.set(*ret, true);
        ret
    }

    /// Returns true if an entity is valid (not removed from the manager).
    #[inline]
    pub fn is_valid(&self, entity: &Entity) -> bool
    {
        &self.entities[**entity] == entity && self.enabled[**entity]
    }

    /// Deletes an entity from the manager.
    pub fn delete_entity(&mut self, entity: &Entity)
    {
        self.entities[mut][**entity] = Entity(0, Uuid::nil());
        self.enabled.set(**entity, false);
        self.ids.return_id(**entity);
    }
}

struct IdPool
{
    recycled: Vec<uint>,
    next_id: uint,
}

impl IdPool
{
    pub fn new() -> IdPool
    {
        IdPool
        {
            recycled: Vec::new(),
            next_id: 1u,
        }
    }

    pub fn get_id(&mut self) -> uint
    {
        match self.recycled.pop()
        {
            Some(id) => id,
            None => {
                self.next_id += 1;
                self.next_id - 1
            }
        }
    }

    pub fn return_id(&mut self, id: uint)
    {
        self.recycled.push(id);
    }
}
<commit_msg>Make EntityBuilder and EntityBuilder require static lifetime<commit_after>
//! Entity identifier and manager types.

use std::collections::Bitv;
use uuid::Uuid;

use Components;

/// Dual identifier for an entity.
///
/// The first element (uint) is the entity's index, used to locate components.
/// This value can be recycled, so the second element (Uuid) is used as an identifier.
#[stable]
#[deriving(Clone, Eq, PartialEq, Show)]
pub struct Entity(uint, Uuid);

#[stable]
impl Entity
{
    pub fn nil() -> Entity
    {
        Entity(0, Uuid::nil())
    }

    /// Returns the entity's index.
    #[inline]
    pub fn get_index(&self) -> uint
    {
        let &Entity(i, _) = self;
        i
    }

    /// Returns the entity's unique identifier.
    #[inline]
    pub fn get_id(&self) -> Uuid
    {
        let &Entity(_, id) = self;
        id
    }
}

impl Deref<uint> for Entity
{
    #[inline]
    fn deref(&self) -> &uint
    {
        let &Entity(ref i, _) = self;
        i
    }
}

pub trait EntityBuilder: 'static
{
    fn build(&mut self, &mut Components, Entity);
}

impl EntityBuilder for |&mut Components, Entity|: 'static
{
    fn build(&mut self, c: &mut Components, e: Entity)
    {
        (*self)(c, e);
    }
}

impl EntityBuilder for () { fn build(&mut self, _: &mut Components, _: Entity) {} }

pub trait EntityModifier: 'static
{
    fn modify(&mut self, &mut Components, Entity);
}

impl EntityModifier for |&mut Components, Entity|: 'static
{
    fn modify(&mut self, c: &mut Components, e: Entity)
    {
        (*self)(c, e);
    }
}

impl EntityModifier for () { fn modify(&mut self, _: &mut Components, _: Entity) {} }

/// Handles creation, activation, and validating of entities.
#[doc(hidden)]
pub struct EntityManager
{
    ids: IdPool,
    entities: Vec<Entity>,
    enabled: Bitv,
}

impl EntityManager
{
    /// Returns a new `EntityManager`
    pub fn new() -> EntityManager
    {
        EntityManager
        {
            ids: IdPool::new(),
            entities: Vec::new(),
            enabled: Bitv::new(),
        }
    }

    /// Creates a new `Entity`, assigning it the first available identifier.
    pub fn create_entity(&mut self) -> Entity
    {
        let ret = Entity(self.ids.get_id(), Uuid::new_v4());
        if *ret >= self.entities.len()
        {
            let diff = *ret - self.entities.len();
            self.entities.grow(diff+1, Entity(0, Uuid::nil()));
        }
        self.entities[mut][*ret] = ret;

        if *ret >= self.enabled.len()
        {
            let diff = *ret - self.enabled.len();
            self.enabled.grow(diff+1, false);
        }
        self.enabled.set(*ret, true);
        ret
    }

    /// Returns true if an entity is valid (not removed from the manager).
    #[inline]
    pub fn is_valid(&self, entity: &Entity) -> bool
    {
        &self.entities[**entity] == entity && self.enabled[**entity]
    }

    /// Deletes an entity from the manager.
    pub fn delete_entity(&mut self, entity: &Entity)
    {
        self.entities[mut][**entity] = Entity(0, Uuid::nil());
        self.enabled.set(**entity, false);
        self.ids.return_id(**entity);
    }
}

struct IdPool
{
    recycled: Vec<uint>,
    next_id: uint,
}

impl IdPool
{
    pub fn new() -> IdPool
    {
        IdPool
        {
            recycled: Vec::new(),
            next_id: 1u,
        }
    }

    pub fn get_id(&mut self) -> uint
    {
        match self.recycled.pop()
        {
            Some(id) => id,
            None => {
                self.next_id += 1;
                self.next_id - 1
            }
        }
    }

    pub fn return_id(&mut self, id: uint)
    {
        self.recycled.push(id);
    }
}
<|endoftext|>


<commit_before>/* Copyright 2016 Torbjørn Birch Moltu
 *
 * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
 * http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
 * http://opensource.org/licenses/MIT>, at your option. This file may not be
 * copied, modified, or distributed except according to those terms.
 */

//! Boilerplatey error enums

extern crate std;
use std::fmt::{self,Display,Formatter};
use std::error::Error;

/// Reasons why `Utf8Char::from_str()` failed.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum FromStrError {
    /// `Utf8Char` cannot store more than a single codepoint.
    SeveralCodePoints,
    /// `Utf8Char` cannot be empty.
    Empty,
}
use self::FromStrError::*;
impl Error for FromStrError {
    fn description(&self) -> &'static str {match *self {
        SeveralCodePoints => "has more than one codepoint",
        Empty => "is empty",
    }}
}
impl Display for FromStrError {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why an `u32` is not a valid UTF codepoint.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidCodePoint {
    /// It's reserved for UTF-16 surrogate pairs.
    Utf16Reserved,
    /// It's higher than the highest codepoint of 0x10ffff.
    TooHigh,
}
use self::InvalidCodePoint::*;
impl InvalidCodePoint {
    /// Get the range of values for which this error would be given.
    pub fn error_range(self) -> (u32,u32) {match self {
        Utf16Reserved => (0xd8_00, 0xdf_ff),
        TooHigh => (0x00_10_ff_ff, 0xff_ff_ff_ff),
    }}
}
impl Error for InvalidCodePoint {
    fn description(&self) -> &'static str {match *self {
        Utf16Reserved => "is reserved for utf-16 surrogate pairs",
        TooHigh => "is higher than the highest codepoint of 0x10ffff",
    }}
}
impl Display for InvalidCodePoint {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a byte is not the start of a UTF-8 codepoint.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8FirstByte {
    /// Sequences cannot be longer than 4 bytes. Is given for bytes >= 240.
    TooLongSeqence,
    /// This byte belongs to a previous seqence. Is given for values between 128 and 192 (exclusive).
    ContinuationByte,
}
use self::InvalidUtf8FirstByte::*;
impl Error for InvalidUtf8FirstByte {
    fn description(&self) -> &'static str {match *self {
        TooLongSeqence => "is greater than 239 (UTF-8 seqences cannot be longer than four bytes)",
        ContinuationByte => "is a continuation of a previous sequence",
    }}
}
impl Display for InvalidUtf8FirstByte {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a byte sequence is not valid UTF-8, excluding invalid codepoint.
/// In sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8 {
    /// Something is certainly wrong with the first byte.
    FirstByte(InvalidUtf8FirstByte),
    /// One of the continuation bytes doesnt fit the pattern 0b10xx_xxxx.
    NotAContinuationByte(usize),
    /// There are too many leading zeros; it could be a byte shorter.
    OverLong,
}
use self::InvalidUtf8::*;
impl Error for InvalidUtf8 {
    fn description(&self) -> &'static str {match *self {
        FirstByte(TooLongSeqence) => "the first byte is greater than 239 (UTF-8 seqences cannot be longer than four bytes)",
        FirstByte(ContinuationByte) => "the first byte is a continuation of a previous sequence",
        OverLong => "the seqence contains too many zeros and could be shorter",
        NotAContinuationByte(_) => "the sequence is too short",
    }}
    /// When `Some` is returned, the `Error` is a `InvalidUtf8FirstByte`.
    fn cause(&self) -> Option<&Error> {match *self {
        FirstByte(ref cause) => Some(cause),
        _ => None,
    }}
}
impl Display for InvalidUtf8 {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a byte array is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Array {
    /// Something is certainly wrong with the first byte.
    Utf8(InvalidUtf8),
    /// The encoded codepoint is invalid:
    CodePoint(InvalidCodePoint),
}
impl Error for InvalidUtf8Array {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf8Array::Utf8(_) => "the seqence is invalid UTF-8",
        InvalidUtf8Array::CodePoint(_) => "the encoded codepoint is invalid",
    }}
    /// Always returns `Some`.
    fn cause(&self) -> Option<&Error> {match *self {
        InvalidUtf8Array::Utf8(ref u) => Some(u),
        InvalidUtf8Array::CodePoint(ref c) => Some(c),
    }}
}
impl Display for InvalidUtf8Array {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}: {}", self.description(), self.cause().unwrap().description())
    }
}

/// Reasons why a byte slice is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Slice {
    /// Something is certainly wrong with the first byte.
    Utf8(InvalidUtf8),
    /// The encoded codepoint is invalid:
    CodePoint(InvalidCodePoint),
    /// The slice is too short; n bytes was required.
    TooShort(usize),
}
impl Error for InvalidUtf8Slice {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf8Slice::Utf8(_) => "the seqence is invalid UTF-8",
        InvalidUtf8Slice::CodePoint(_) => "the encoded codepoint is invalid",
        InvalidUtf8Slice::TooShort(0) => "the slice is empty",
        InvalidUtf8Slice::TooShort(_) => "the slice is shorter than the seqence",
    }}
    fn cause(&self) -> Option<&Error> {match *self {
        InvalidUtf8Slice::Utf8(ref u) => Some(u),
        InvalidUtf8Slice::CodePoint(ref c) => Some(c),
        InvalidUtf8Slice::TooShort(_) => None,
    }}
}
impl Display for InvalidUtf8Slice {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        match self.cause() {
            Some(d) => write!(fmtr, "{}: {}", self.description(), d),
            None    => write!(fmtr, "{}", self.description()),
        }
    }
}

/// Reasons why one or two `u16`s are not valid UTF-16, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf16Tuple {
    /// The first unit is a trailing/low surrogate, which is never valid.
    ///
    /// Note that the value of a low surrogate is actually higher than a high surrogate.
    FirstIsTrailingSurrogate,
    /// You provided a second unit, but the first one stands on its own.
    SuperfluousSecond,
    /// The first and only unit requires a second unit.
    MissingSecond,
    /// The first unit requires a second unit, but it's not a trailing/low surrogate.
    ///
    /// Note that the value of a low surrogate is actually higher than a high surrogate.
    InvalidSecond,
}
impl Error for InvalidUtf16Tuple {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf16Tuple::FirstIsTrailingSurrogate => "the first unit is a trailing / low surrogate, which is never valid",
        InvalidUtf16Tuple::SuperfluousSecond => "the second unit is superfluous",
        InvalidUtf16Tuple::MissingSecond => "the first unit requires a second unit",
        InvalidUtf16Tuple::InvalidSecond => "the required second unit is not a trailing / low surrogate",
    }}
}
impl Display for InvalidUtf16Tuple {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a slice of `u16`s doesn't start with valid UTF-16.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf16Slice {
    /// The slice is empty.
    EmptySlice,
    /// The first unit is a low surrogate.
    FirstLowSurrogate,
    /// The first and only unit requires a second unit.
    MissingSecond,
    /// The first unit requires a second one, but it's not a low surrogate.
    SecondNotLowSurrogate,
}
impl Error for InvalidUtf16Slice {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf16Slice::EmptySlice => "the slice is empty",
        InvalidUtf16Slice::FirstLowSurrogate => "the first unit is a low surrogate",
        InvalidUtf16Slice::MissingSecond => "the first and only unit requires a second one",
        InvalidUtf16Slice::SecondNotLowSurrogate => "the required second unit is not a low surrogate",
    }}
}
impl Display for InvalidUtf16Slice {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}
<commit_msg>Fix a single lowercase "utf-16"<commit_after>/* Copyright 2016 Torbjørn Birch Moltu
 *
 * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
 * http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
 * http://opensource.org/licenses/MIT>, at your option. This file may not be
 * copied, modified, or distributed except according to those terms.
 */

//! Boilerplatey error enums

extern crate std;
use std::fmt::{self,Display,Formatter};
use std::error::Error;

/// Reasons why `Utf8Char::from_str()` failed.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum FromStrError {
    /// `Utf8Char` cannot store more than a single codepoint.
    SeveralCodePoints,
    /// `Utf8Char` cannot be empty.
    Empty,
}
use self::FromStrError::*;
impl Error for FromStrError {
    fn description(&self) -> &'static str {match *self {
        SeveralCodePoints => "has more than one codepoint",
        Empty => "is empty",
    }}
}
impl Display for FromStrError {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why an `u32` is not a valid UTF codepoint.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidCodePoint {
    /// It's reserved for UTF-16 surrogate pairs.
    Utf16Reserved,
    /// It's higher than the highest codepoint of 0x10ffff.
    TooHigh,
}
use self::InvalidCodePoint::*;
impl InvalidCodePoint {
    /// Get the range of values for which this error would be given.
    pub fn error_range(self) -> (u32,u32) {match self {
        Utf16Reserved => (0xd8_00, 0xdf_ff),
        TooHigh => (0x00_10_ff_ff, 0xff_ff_ff_ff),
    }}
}
impl Error for InvalidCodePoint {
    fn description(&self) -> &'static str {match *self {
        Utf16Reserved => "is reserved for UTF-16 surrogate pairs",
        TooHigh => "is higher than the highest codepoint of 0x10ffff",
    }}
}
impl Display for InvalidCodePoint {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a byte is not the start of a UTF-8 codepoint.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8FirstByte {
    /// Sequences cannot be longer than 4 bytes. Is given for bytes >= 240.
    TooLongSeqence,
    /// This byte belongs to a previous seqence. Is given for values between 128 and 192 (exclusive).
    ContinuationByte,
}
use self::InvalidUtf8FirstByte::*;
impl Error for InvalidUtf8FirstByte {
    fn description(&self) -> &'static str {match *self {
        TooLongSeqence => "is greater than 239 (UTF-8 seqences cannot be longer than four bytes)",
        ContinuationByte => "is a continuation of a previous sequence",
    }}
}
impl Display for InvalidUtf8FirstByte {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a byte sequence is not valid UTF-8, excluding invalid codepoint.
/// In sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8 {
    /// Something is certainly wrong with the first byte.
    FirstByte(InvalidUtf8FirstByte),
    /// One of the continuation bytes doesnt fit the pattern 0b10xx_xxxx.
    NotAContinuationByte(usize),
    /// There are too many leading zeros; it could be a byte shorter.
    OverLong,
}
use self::InvalidUtf8::*;
impl Error for InvalidUtf8 {
    fn description(&self) -> &'static str {match *self {
        FirstByte(TooLongSeqence) => "the first byte is greater than 239 (UTF-8 seqences cannot be longer than four bytes)",
        FirstByte(ContinuationByte) => "the first byte is a continuation of a previous sequence",
        OverLong => "the seqence contains too many zeros and could be shorter",
        NotAContinuationByte(_) => "the sequence is too short",
    }}
    /// When `Some` is returned, the `Error` is a `InvalidUtf8FirstByte`.
    fn cause(&self) -> Option<&Error> {match *self {
        FirstByte(ref cause) => Some(cause),
        _ => None,
    }}
}
impl Display for InvalidUtf8 {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a byte array is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Array {
    /// Something is certainly wrong with the first byte.
    Utf8(InvalidUtf8),
    /// The encoded codepoint is invalid:
    CodePoint(InvalidCodePoint),
}
impl Error for InvalidUtf8Array {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf8Array::Utf8(_) => "the seqence is invalid UTF-8",
        InvalidUtf8Array::CodePoint(_) => "the encoded codepoint is invalid",
    }}
    /// Always returns `Some`.
    fn cause(&self) -> Option<&Error> {match *self {
        InvalidUtf8Array::Utf8(ref u) => Some(u),
        InvalidUtf8Array::CodePoint(ref c) => Some(c),
    }}
}
impl Display for InvalidUtf8Array {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}: {}", self.description(), self.cause().unwrap().description())
    }
}

/// Reasons why a byte slice is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Slice {
    /// Something is certainly wrong with the first byte.
    Utf8(InvalidUtf8),
    /// The encoded codepoint is invalid:
    CodePoint(InvalidCodePoint),
    /// The slice is too short; n bytes was required.
    TooShort(usize),
}
impl Error for InvalidUtf8Slice {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf8Slice::Utf8(_) => "the seqence is invalid UTF-8",
        InvalidUtf8Slice::CodePoint(_) => "the encoded codepoint is invalid",
        InvalidUtf8Slice::TooShort(0) => "the slice is empty",
        InvalidUtf8Slice::TooShort(_) => "the slice is shorter than the seqence",
    }}
    fn cause(&self) -> Option<&Error> {match *self {
        InvalidUtf8Slice::Utf8(ref u) => Some(u),
        InvalidUtf8Slice::CodePoint(ref c) => Some(c),
        InvalidUtf8Slice::TooShort(_) => None,
    }}
}
impl Display for InvalidUtf8Slice {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        match self.cause() {
            Some(d) => write!(fmtr, "{}: {}", self.description(), d),
            None    => write!(fmtr, "{}", self.description()),
        }
    }
}

/// Reasons why one or two `u16`s are not valid UTF-16, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf16Tuple {
    /// The first unit is a trailing/low surrogate, which is never valid.
    ///
    /// Note that the value of a low surrogate is actually higher than a high surrogate.
    FirstIsTrailingSurrogate,
    /// You provided a second unit, but the first one stands on its own.
    SuperfluousSecond,
    /// The first and only unit requires a second unit.
    MissingSecond,
    /// The first unit requires a second unit, but it's not a trailing/low surrogate.
    ///
    /// Note that the value of a low surrogate is actually higher than a high surrogate.
    InvalidSecond,
}
impl Error for InvalidUtf16Tuple {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf16Tuple::FirstIsTrailingSurrogate => "the first unit is a trailing / low surrogate, which is never valid",
        InvalidUtf16Tuple::SuperfluousSecond => "the second unit is superfluous",
        InvalidUtf16Tuple::MissingSecond => "the first unit requires a second unit",
        InvalidUtf16Tuple::InvalidSecond => "the required second unit is not a trailing / low surrogate",
    }}
}
impl Display for InvalidUtf16Tuple {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}

/// Reasons why a slice of `u16`s doesn't start with valid UTF-16.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf16Slice {
    /// The slice is empty.
    EmptySlice,
    /// The first unit is a low surrogate.
    FirstLowSurrogate,
    /// The first and only unit requires a second unit.
    MissingSecond,
    /// The first unit requires a second one, but it's not a low surrogate.
    SecondNotLowSurrogate,
}
impl Error for InvalidUtf16Slice {
    fn description(&self) -> &'static str {match *self {
        InvalidUtf16Slice::EmptySlice => "the slice is empty",
        InvalidUtf16Slice::FirstLowSurrogate => "the first unit is a low surrogate",
        InvalidUtf16Slice::MissingSecond => "the first and only unit requires a second one",
        InvalidUtf16Slice::SecondNotLowSurrogate => "the required second unit is not a low surrogate",
    }}
}
impl Display for InvalidUtf16Slice {
    fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
        write!(fmtr, "{}", self.description())
    }
}
<|endoftext|>


<commit_before>//! `errors` - error-chain generated `Error` types.

use void::Void;

error_chain! {
    types { Error, ErrorKind, ResultExt, Result; }

    links {
        Rados(::rad::Error, ::rad::ErrorKind);
    }

    foreign_links {
        Bincode(::bincode::Error);
        Nul(::std::ffi::NulError);
        Io(::std::io::Error);
        TomlSer(::toml::ser::Error);
        TomlDe(::toml::de::Error);
    }

    errors {
        Impossible(never: Void) {
            description("This error can never occur.")
            display("This error can literally never happen.")
        }
    }
}
<commit_msg>Remove unused  error.<commit_after>//! # `errors` - error-chain generated `Error` types.

use void::Void;

error_chain! {
    types { Error, ErrorKind, ResultExt, Result; }

    links {
        Rados(::rad::Error, ::rad::ErrorKind);
    }

    foreign_links {
        Bincode(::bincode::Error);
        Nul(::std::ffi::NulError);
        Io(::std::io::Error);
        TomlSer(::toml::ser::Error);
        TomlDe(::toml::de::Error);
    }

    errors {}
}
<|endoftext|>


<commit_before>/// Exports a given list of functions to a Erlang module.
///
/// This should be called exactly once in every NIF library. It will wrap and export the given rust
/// functions into the Erlang module.
///
/// The first argument is a string specifying what Erlang/Elixir module you want the function
/// exported into. In Erlang this will simply be the atom you named your module. In Elixir, all
/// modules are prefixed with `Elixir.<module path>`
///
/// The second argument is a list of 3-tuples. Each tuple contains information on a single exported
/// NIF function. The first tuple item is the name you want to export the function into, the second
/// is the arity (number of arguments) of the exported function. The third argument is a
/// indentifier of a rust function. This is where your actual NIF will be implemented.
///
/// The third argument is an `Option<fn(env: &NifEnv, load_info: NifTerm) -> bool>`. If this is
/// `Some`, the function will execute when the NIF is first loaded by the BEAM.
#[macro_export]
macro_rules! rustler_export_nifs {
    ($name:expr, [$( $exported_nif:tt ),*], $on_load:expr) => {
        static mut NIF_ENTRY: Option<$crate::codegen_runtime::DEF_NIF_ENTRY> = None;

        #[no_mangle]
        pub extern "C" fn nif_init() -> *const $crate::codegen_runtime::DEF_NIF_ENTRY {
            // TODO: If a NIF ever gets unloaded, there will be a memory leak! Fix this!
            // TODO: If an unwrap ever happens, we will unwind right into C! Fix this!

            extern "C" fn nif_load(
                env: $crate::codegen_runtime::NIF_ENV,
                _priv_data: *mut *mut $crate::codegen_runtime::c_void,
                load_info: $crate::codegen_runtime::NIF_TERM)
                -> $crate::codegen_runtime::c_int {
                    $crate::codegen_runtime::handle_nif_init_call($on_load, env, load_info)
                }

            let fun_entries = [
                $(rustler_export_nifs!(internal, $exported_nif)),*
            ];
            let fun_entries_len = fun_entries.len();
            let fun_entries_ptr = Box::into_raw(Box::new(fun_entries));

            let entry = $crate::codegen_runtime::DEF_NIF_ENTRY {
                major: $crate::codegen_runtime::NIF_MAJOR_VERSION,
                minor: $crate::codegen_runtime::NIF_MINOR_VERSION,
                name: ::std::ffi::CString::new($name).unwrap().into_raw() as *const u8,
                num_of_funcs: fun_entries_len as $crate::codegen_runtime::c_int,
                funcs: fun_entries_ptr as *const $crate::codegen_runtime::DEF_NIF_FUNC,
                load: Some(nif_load),
                reload: None,
                upgrade: None,
                unload: None,
                vm_variant: b"beam.vanilla\x00" as *const u8,
                options: 0,
            };
            unsafe { NIF_ENTRY = Some(entry) };

            unsafe { NIF_ENTRY.as_ref().unwrap() }
        }
    };

    (internal, ($nif_name:expr, $nif_arity:expr, $nif_fun:path)) => {
        rustler_export_nifs!(internal, ($nif_name, $nif_arity, $nif_fun, $crate::schedule::NifScheduleFlags::Normal))
    };
    (internal, ($nif_name:expr, $nif_arity:expr, $nif_fun:path, $nif_flag:expr)) => {
        $crate::codegen_runtime::DEF_NIF_FUNC {
            name: ::std::ffi::CString::new($nif_name).unwrap().into_raw() as *const u8,
            arity: $nif_arity,
            function: {
                extern "C" fn nif_func(
                    env: $crate::codegen_runtime::NIF_ENV,
                    argc: $crate::codegen_runtime::c_int,
                    argv: *const $crate::codegen_runtime::NIF_TERM)
                    -> $crate::codegen_runtime::NIF_TERM {
                    $crate::codegen_runtime::handle_nif_call($nif_fun, $nif_arity, env, argc, argv)
                }
                nif_func
            },
            flags: $nif_flag as u32,
        }
    };
}
<commit_msg>Use const strings and arrays in the export macro. Fixes #53.<commit_after>/// Exports a given list of functions to a Erlang module.
///
/// This should be called exactly once in every NIF library. It will wrap and export the given rust
/// functions into the Erlang module.
///
/// The first argument is a string specifying what Erlang/Elixir module you want the function
/// exported into. In Erlang this will simply be the atom you named your module. In Elixir, all
/// modules are prefixed with `Elixir.<module path>`
///
/// The second argument is a list of 3-tuples. Each tuple contains information on a single exported
/// NIF function. The first tuple item is the name you want to export the function into, the second
/// is the arity (number of arguments) of the exported function. The third argument is a
/// indentifier of a rust function. This is where your actual NIF will be implemented.
///
/// The third argument is an `Option<fn(env: &NifEnv, load_info: NifTerm) -> bool>`. If this is
/// `Some`, the function will execute when the NIF is first loaded by the BEAM.
#[macro_export]
macro_rules! rustler_export_nifs {
    ($name:expr, [$( $exported_nif:tt ),*], $on_load:expr) => {
        static mut NIF_ENTRY: Option<$crate::codegen_runtime::DEF_NIF_ENTRY> = None;

        #[no_mangle]
        pub extern "C" fn nif_init() -> *const $crate::codegen_runtime::DEF_NIF_ENTRY {
            // TODO: If an unwrap ever happens, we will unwind right into C! Fix this!

            extern "C" fn nif_load(
                env: $crate::codegen_runtime::NIF_ENV,
                _priv_data: *mut *mut $crate::codegen_runtime::c_void,
                load_info: $crate::codegen_runtime::NIF_TERM)
                -> $crate::codegen_runtime::c_int {
                    $crate::codegen_runtime::handle_nif_init_call($on_load, env, load_info)
                }

            const FUN_ENTRIES: &'static [$crate::codegen_runtime::DEF_NIF_FUNC] = &[
                $(rustler_export_nifs!(internal, $exported_nif)),*
            ];

            let entry = $crate::codegen_runtime::DEF_NIF_ENTRY {
                major: $crate::codegen_runtime::NIF_MAJOR_VERSION,
                minor: $crate::codegen_runtime::NIF_MINOR_VERSION,
                name: concat!($name, "\x00") as *const str as *const u8,
                num_of_funcs: FUN_ENTRIES.len() as $crate::codegen_runtime::c_int,
                funcs: FUN_ENTRIES.as_ptr(),
                load: Some(nif_load),
                reload: None,
                upgrade: None,
                unload: None,
                vm_variant: b"beam.vanilla\x00".as_ptr(),
                options: 0,
            };
            unsafe { NIF_ENTRY = Some(entry) };

            unsafe { NIF_ENTRY.as_ref().unwrap() }
        }
    };

    (internal, ($nif_name:expr, $nif_arity:expr, $nif_fun:path)) => {
        rustler_export_nifs!(internal, ($nif_name, $nif_arity, $nif_fun, $crate::schedule::NifScheduleFlags::Normal))
    };
    (internal, ($nif_name:expr, $nif_arity:expr, $nif_fun:path, $nif_flag:expr)) => {
        $crate::codegen_runtime::DEF_NIF_FUNC {
            name: concat!($nif_name, "\x00") as *const str as *const u8,
            arity: $nif_arity,
            function: {
                extern "C" fn nif_func(
                    env: $crate::codegen_runtime::NIF_ENV,
                    argc: $crate::codegen_runtime::c_int,
                    argv: *const $crate::codegen_runtime::NIF_TERM)
                    -> $crate::codegen_runtime::NIF_TERM {
                    $crate::codegen_runtime::handle_nif_call($nif_fun, $nif_arity, env, argc, argv)
                }
                nif_func
            },
            flags: $nif_flag as u32,
        }
    };
}
<|endoftext|>


<commit_before>extern crate num_cpus;

use std;
use std::thread;
use std::sync::mpsc;

static THREAD_THRESHOLD: usize = 255;

pub fn prime_filter(iter_size: usize) -> Vec<bool>{
    if iter_size<100{
        slow_prime_filter(iter_size)
    }else{
        prime_filter_section(0, iter_size)
    }
}

fn case_1(y_sq: usize, iter_size: usize)
    -> Vec<usize> {
    //n_1 = 4x^2 + y^2 === 1 (mod 4)
    let (mut n_1, mut to_next_n_1) = (y_sq, 4);    let mut ret_stack: Vec<usize> = Vec::new();
    loop{
        n_1 += to_next_n_1;
        to_next_n_1 += 8;
        match n_1%60{
            _ if n_1 >= iter_size => break,
            1 | 13 | 17 | 29 | 37 | 41 | 49 | 53 => (),
            _ => continue,
        };

        // println!("1: {}", n_1);
        ret_stack.push(n_1);
    };
    ret_stack
}
fn case_2(y_sq: usize, iter_size: usize)
    -> Vec<usize> {
    //n_2 = 3x^2 + y^2 === 1 (mod 6)
    let (mut n_2, mut to_next_n_2) = (y_sq, 3);
    let mut ret_stack: Vec<usize> = Vec::new();
    loop {
        n_2 += to_next_n_2;
        to_next_n_2 += 6;
        match n_2%60{
            _ if n_2 >= iter_size => break,
            7 | 19 | 31 | 43 => (),
            _ => continue,
        };
        // println!("2: {}", n_2);
        ret_stack.push(n_2);
    };
    ret_stack
}
fn case_3(y_sq: usize, to_next_y_sq: usize, iter_size: usize)
    -> Vec<usize> {
    //n_3 = 3x^2 - y^2 === 11 (mod 12)
    let (mut n_3, mut to_next_n_3) = (2*y_sq, 3*to_next_y_sq);
    let mut ret_stack: Vec<usize> = Vec::new();
    loop {
        n_3 += to_next_n_3;
        to_next_n_3 += 6;
        match n_3%60{
            _ if n_3 >= iter_size => break,
            11 | 23 | 47 | 59 => (),
            _ => continue,
        };
        // println!("3: {}", n_3);
        ret_stack.push(n_3);
    };
    ret_stack
}

fn prime_filter_section(min:usize, max: usize) -> Vec<bool>{
    //Sieve of Atkin
    let num_cpus = num_cpus::get();
    assert!(min<max);
    let mut prime_filter = vec![false; max-min];
    if (min <= 2) & (max > 2) {prime_filter[2-min] = true;}
    if (min <= 3) & (max > 3) {prime_filter[3-min] = true;}
    if (min <= 5) & (max > 5) {prime_filter[5-min] = true;}

    let (mut y_sq, mut to_next_y_sq) = match min {
        0|1 => (1, 3),
        _ => (min*min, 2*min + 1),
    };
    let mut spawned_threads = 0;
    let (tx, rx) = mpsc::channel();
    while y_sq<max {
        if y_sq%2 == 1 {
            spawned_threads += 1;
            let (y_sq, tx) = (y_sq, tx.clone());
            thread::spawn(move || {
                tx.send(case_1(y_sq, max)).unwrap();
            });
        };
        if y_sq%3 == 1 {

            spawned_threads += 1;
            let (y_sq, to_next_y_sq, tx1) = (y_sq, to_next_y_sq, tx.clone());
            thread::spawn(move || {
                tx1.send(case_2(y_sq, max)).unwrap();
            });
            if y_sq*2<max{
                spawned_threads += 1;
                let tx2 = tx.clone();
                thread::spawn(move || {
                    tx2.send(case_3(y_sq, to_next_y_sq, max)).unwrap();
                });
            }
        };
        while{ //Do-while
            y_sq += to_next_y_sq;
            to_next_y_sq += 2;
            y_sq%6 == 0
        } {};
        if spawned_threads >= THREAD_THRESHOLD{
            // let prev_spawned_threads = spawned_threads;
            while spawned_threads > num_cpus{
                for mes in rx.try_iter(){
                    spawned_threads -= 1;
                    for flip_i in mes{
                        prime_filter[flip_i - min] ^= true;
                    }
                }
            }
            // let despawned_threads = prev_spawned_threads - spawned_threads;
            // println!("despawned_threads: {}", despawned_threads);
        };
    };

    while spawned_threads!=0{
        for mes in rx.try_iter(){
            spawned_threads -= 1;
            for flip_i in mes{
                prime_filter[flip_i - min] ^= true;
            }
        }
    };
    //Eliminate non-squarefree numbers
    let mut n_sq = 49; // 7^2
    let mut next_n_sq = 32; //9^2 - 7^2, skip even numbers.
    while n_sq < max {
        let mut non_sq_free = n_sq;
        while non_sq_free < max {
            if non_sq_free >= min {
                prime_filter[non_sq_free - min] = false;
            }
            while{ //Do-while
                non_sq_free += n_sq + n_sq;
                (non_sq_free%3==0) | (non_sq_free%5==0)
            } {};
        };
        while{ //Do-while
            n_sq += next_n_sq;
            next_n_sq += 8;
            (n_sq%3==0) | (n_sq%5 == 0)
        } {};
    }
    prime_filter
}
#[cfg(test)]
pub fn old_prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    slow_prime_filter(iter_size)
}

fn slow_prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    if iter_size < 5 {
         let mut ret = vec![false, false, true, true];
         ret.truncate(iter_size);
         return ret
     }
    let mut prime_filter = vec![true; iter_size];
    prime_filter[0] = false;
    prime_filter[1] = false;
    let mut cur_num = 2;
    'outer: loop{
        for i in (cur_num+1)..iter_size{
            if 0 == i%cur_num { prime_filter[i] = false; }
        }
        cur_num += 1;
        while !prime_filter[cur_num]{
            if cur_num*cur_num > iter_size {
                break 'outer
            }
            cur_num += 1;
        }
    };
    prime_filter
}
<commit_msg>Using a static core multiplier instead of threshold<commit_after>extern crate num_cpus;

use std;
use std::thread;
use std::sync::mpsc;

static CORE_MUL_THRESHOLD: usize = 8;

pub fn prime_filter(iter_size: usize) -> Vec<bool>{
    if iter_size<100{
        slow_prime_filter(iter_size)
    }else{
        prime_filter_section(0, iter_size)
    }
}

fn case_1(y_sq: usize, iter_size: usize)
    -> Vec<usize> {
    //n_1 = 4x^2 + y^2 === 1 (mod 4)
    let (mut n_1, mut to_next_n_1) = (y_sq, 4);    let mut ret_stack: Vec<usize> = Vec::new();
    loop{
        n_1 += to_next_n_1;
        to_next_n_1 += 8;
        match n_1%60{
            _ if n_1 >= iter_size => break,
            1 | 13 | 17 | 29 | 37 | 41 | 49 | 53 => (),
            _ => continue,
        };

        // println!("1: {}", n_1);
        ret_stack.push(n_1);
    };
    ret_stack
}
fn case_2(y_sq: usize, iter_size: usize)
    -> Vec<usize> {
    //n_2 = 3x^2 + y^2 === 1 (mod 6)
    let (mut n_2, mut to_next_n_2) = (y_sq, 3);
    let mut ret_stack: Vec<usize> = Vec::new();
    loop {
        n_2 += to_next_n_2;
        to_next_n_2 += 6;
        match n_2%60{
            _ if n_2 >= iter_size => break,
            7 | 19 | 31 | 43 => (),
            _ => continue,
        };
        // println!("2: {}", n_2);
        ret_stack.push(n_2);
    };
    ret_stack
}
fn case_3(y_sq: usize, to_next_y_sq: usize, iter_size: usize)
    -> Vec<usize> {
    //n_3 = 3x^2 - y^2 === 11 (mod 12)
    let (mut n_3, mut to_next_n_3) = (2*y_sq, 3*to_next_y_sq);
    let mut ret_stack: Vec<usize> = Vec::new();
    loop {
        n_3 += to_next_n_3;
        to_next_n_3 += 6;
        match n_3%60{
            _ if n_3 >= iter_size => break,
            11 | 23 | 47 | 59 => (),
            _ => continue,
        };
        // println!("3: {}", n_3);
        ret_stack.push(n_3);
    };
    ret_stack
}

fn prime_filter_section(min:usize, max: usize) -> Vec<bool>{
    //Sieve of Atkin
    let num_cpus = num_cpus::get();
    let thread_threshold = num_cpus*CORE_MUL_THRESHOLD;
    assert!(min<max);
    let mut prime_filter = vec![false; max-min];
    if (min <= 2) & (max > 2) {prime_filter[2-min] = true;}
    if (min <= 3) & (max > 3) {prime_filter[3-min] = true;}
    if (min <= 5) & (max > 5) {prime_filter[5-min] = true;}

    let (mut y_sq, mut to_next_y_sq) = match min {
        0|1 => (1, 3),
        _ => (min*min, 2*min + 1),
    };
    let mut spawned_threads = 0;
    let (tx, rx) = mpsc::channel();
    while y_sq<max {
        if y_sq%2 == 1 {
            spawned_threads += 1;
            let (y_sq, tx) = (y_sq, tx.clone());
            thread::spawn(move || {
                tx.send(case_1(y_sq, max)).unwrap();
            });
        };
        if y_sq%3 == 1 {

            spawned_threads += 1;
            let (y_sq, to_next_y_sq, tx1) = (y_sq, to_next_y_sq, tx.clone());
            thread::spawn(move || {
                tx1.send(case_2(y_sq, max)).unwrap();
            });
            if y_sq*2<max{
                spawned_threads += 1;
                let tx2 = tx.clone();
                thread::spawn(move || {
                    tx2.send(case_3(y_sq, to_next_y_sq, max)).unwrap();
                });
            }
        };
        while{ //Do-while
            y_sq += to_next_y_sq;
            to_next_y_sq += 2;
            y_sq%6 == 0
        } {};
        if spawned_threads >= thread_threshold{
            // let prev_spawned_threads = spawned_threads;
            while spawned_threads > num_cpus{
                for mes in rx.try_iter(){
                    spawned_threads -= 1;
                    for flip_i in mes{
                        prime_filter[flip_i - min] ^= true;
                    }
                }
            }
            // let despawned_threads = prev_spawned_threads - spawned_threads;
            // println!("despawned_threads: {}", despawned_threads);
        };
    };

    while spawned_threads!=0{
        for mes in rx.try_iter(){
            spawned_threads -= 1;
            for flip_i in mes{
                prime_filter[flip_i - min] ^= true;
            }
        }
    };
    //Eliminate non-squarefree numbers
    let mut n_sq = 49; // 7^2
    let mut next_n_sq = 32; //9^2 - 7^2, skip even numbers.
    while n_sq < max {
        let mut non_sq_free = n_sq;
        while non_sq_free < max {
            if non_sq_free >= min {
                prime_filter[non_sq_free - min] = false;
            }
            while{ //Do-while
                non_sq_free += n_sq + n_sq;
                (non_sq_free%3==0) | (non_sq_free%5==0)
            } {};
        };
        while{ //Do-while
            n_sq += next_n_sq;
            next_n_sq += 8;
            (n_sq%3==0) | (n_sq%5 == 0)
        } {};
    }
    prime_filter
}
#[cfg(test)]
pub fn old_prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    slow_prime_filter(iter_size)
}

fn slow_prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    if iter_size < 5 {
         let mut ret = vec![false, false, true, true];
         ret.truncate(iter_size);
         return ret
     }
    let mut prime_filter = vec![true; iter_size];
    prime_filter[0] = false;
    prime_filter[1] = false;
    let mut cur_num = 2;
    'outer: loop{
        for i in (cur_num+1)..iter_size{
            if 0 == i%cur_num { prime_filter[i] = false; }
        }
        cur_num += 1;
        while !prime_filter[cur_num]{
            if cur_num*cur_num > iter_size {
                break 'outer
            }
            cur_num += 1;
        }
    };
    prime_filter
}
<|endoftext|>


<commit_before>extern crate chrono;
extern crate fuse;
extern crate libc;
extern crate regex;
extern crate rustc_serialize;
extern crate time;
extern crate users;

mod constants;
mod filesystem;
mod flags;
mod helpers;
mod inode;
mod ops;

pub use self::constants::*;
pub use self::filesystem::*;
pub use self::flags::*;
pub use self::helpers::*;
pub use self::inode::*;
pub use self::ops::*;
<commit_msg>Include gooddata_fs::fs::items module<commit_after>extern crate chrono;
extern crate fuse;
extern crate libc;
extern crate regex;
extern crate rustc_serialize;
extern crate time;
extern crate users;

mod constants;
mod filesystem;
mod flags;
mod helpers;
mod inode;
mod items;
mod ops;

pub use self::constants::*;
pub use self::filesystem::*;
pub use self::flags::*;
pub use self::helpers::*;
pub use self::inode::*;
pub use self::items::*;
pub use self::ops::*;
<|endoftext|>


<commit_before>// Format validated types representing lexical tokens defined in
// RFC 5322 (as well as some referred from RFC 5234)
// in order to support SMTP (RFC 5321)

// Macro for defining sequences of characters within a character class
macro_rules! def_cclass {
    ( $typ:ident, $test:ident) => {
        #[derive(Debug, Clone, PartialEq)]
        pub struct $typ(pub Vec<u8>);
        impl Parsable for $typ {
            fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
                let mut pos: usize = 0;
                let mut output: Vec<u8> = Vec::new();
                while pos < input.len() && $test(input[pos]) {
                    output.push(input[pos]);
                    pos += 1;
                }
                if output.len() > 0 {
                    Ok( ($typ(output), &input[pos..]) )
                }
                else {
                    if pos >= input.len() { Err( ParseError::Eof ) }
                    else { Err( ParseError::NotFound ) }
                }
            }
        }
        impl Streamable for $typ {
            fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
                Ok(try!(w.write(&self.0[..])))
            }
        }
    };
}

// Macro for assigning the returned remaining input of a parse function to an existing
// variable
macro_rules! parse {
    ($pth:ident, $rem:ident) => {
        {
            $pth::parse($rem).map(|(value, r)| { $rem = r; value })
        }
    };
}

macro_rules! req {
    ($rem:ident, $bytes:expr, $input:ident) => {
        let len: usize = $bytes.len();
        if $rem.len() < len {
            return Err(ParseError::Eof);
        }
        if &$rem[0..len] != $bytes {
            return Err(ParseError::Expected($bytes.to_vec()));
        }
        $rem = &$rem[len..];
    };
}

pub mod error;
pub use self::error::ParseError;
pub mod types;
pub mod headers;

use std::io::Write;
use std::io::Error as IoError;
use self::headers::{Return, Received};
use self::headers::{ResentDate, ResentFrom, ResentSender, ResentTo, ResentCc, ResentBcc,
                    ResentMessageId};

pub trait Parsable: Sized {
    /// Parse the object off of the beginning of the `input`.  If found, returns Some object,
    /// and a slice containing the remainer of the input.
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError>;
}

pub trait Streamable {
    /// Serializes and sends the content out to `w`, returning the number of bytes written.
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError>;
}

// 3.6.7
// trace           =   [return]
//                     1*received
#[derive(Debug, Clone, PartialEq)]
pub struct Trace {
    return_path: Option<Return>,
    received: Vec<Received>
}
impl Parsable for Trace {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        let maybe_return = parse!(Return, rem).ok();
        let mut received: Vec<Received> = Vec::new();
        while let Ok(r) = parse!(Received, rem) {
            received.push(r);
        }
        if received.len() < 1 { return Err(ParseError::NotFound); }
        Ok((Trace {
            return_path: maybe_return,
            received: received,
        }, rem))
    }
}
impl Streamable for Trace {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref rp) = self.return_path {
            count += try!(rp.stream(w));
        }
        for r in &self.received {
            count += try!(r.stream(w));
        }
        Ok(count)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum ResentField {
    Date(ResentDate),
    From(ResentFrom),
    Sender(ResentSender),
    To(ResentTo),
    Cc(ResentCc),
    Bcc(ResentBcc),
    MessageId(ResentMessageId),
}
impl Parsable for ResentField {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        if let Ok(x) = parse!(ResentDate, rem) {
            return Ok((ResentField::Date(x), rem));
        }
        if let Ok(x) = parse!(ResentFrom, rem) {
            return Ok((ResentField::From(x), rem));
        }
        if let Ok(x) = parse!(ResentSender, rem) {
            return Ok((ResentField::Sender(x), rem));
        }
        if let Ok(x) = parse!(ResentTo, rem) {
            return Ok((ResentField::To(x), rem));
        }
        if let Ok(x) = parse!(ResentCc, rem) {
            return Ok((ResentField::Cc(x), rem));
        }
        if let Ok(x) = parse!(ResentBcc, rem) {
            return Ok((ResentField::Bcc(x), rem));
        }
        if let Ok(x) = parse!(ResentMessageId, rem) {
            return Ok((ResentField::MessageId(x), rem));
        }
        Err(ParseError::NotFound)
    }
}
impl Streamable for ResentField {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            ResentField::Date(ref x) => x.stream(w),
            ResentField::From(ref x) => x.stream(w),
            ResentField::Sender(ref x) => x.stream(w),
            ResentField::To(ref x) => x.stream(w),
            ResentField::Cc(ref x) => x.stream(w),
            ResentField::Bcc(ref x) => x.stream(w),
            ResentField::MessageId(ref x) => x.stream(w),
        }
    }
}
<commit_msg>rfc5322: Field enum<commit_after>// Format validated types representing lexical tokens defined in
// RFC 5322 (as well as some referred from RFC 5234)
// in order to support SMTP (RFC 5321)

// Macro for defining sequences of characters within a character class
macro_rules! def_cclass {
    ( $typ:ident, $test:ident) => {
        #[derive(Debug, Clone, PartialEq)]
        pub struct $typ(pub Vec<u8>);
        impl Parsable for $typ {
            fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
                let mut pos: usize = 0;
                let mut output: Vec<u8> = Vec::new();
                while pos < input.len() && $test(input[pos]) {
                    output.push(input[pos]);
                    pos += 1;
                }
                if output.len() > 0 {
                    Ok( ($typ(output), &input[pos..]) )
                }
                else {
                    if pos >= input.len() { Err( ParseError::Eof ) }
                    else { Err( ParseError::NotFound ) }
                }
            }
        }
        impl Streamable for $typ {
            fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
                Ok(try!(w.write(&self.0[..])))
            }
        }
    };
}

// Macro for assigning the returned remaining input of a parse function to an existing
// variable
macro_rules! parse {
    ($pth:ident, $rem:ident) => {
        {
            $pth::parse($rem).map(|(value, r)| { $rem = r; value })
        }
    };
}

macro_rules! req {
    ($rem:ident, $bytes:expr, $input:ident) => {
        let len: usize = $bytes.len();
        if $rem.len() < len {
            return Err(ParseError::Eof);
        }
        if &$rem[0..len] != $bytes {
            return Err(ParseError::Expected($bytes.to_vec()));
        }
        $rem = &$rem[len..];
    };
}

pub mod error;
pub use self::error::ParseError;
pub mod types;
pub mod headers;

use std::io::Write;
use std::io::Error as IoError;
use self::headers::{Return, Received};
use self::headers::{ResentDate, ResentFrom, ResentSender, ResentTo, ResentCc, ResentBcc,
                    ResentMessageId};
use self::headers::{OrigDate, From, Sender, ReplyTo, To, Cc, Bcc, MessageId, InReplyTo,
                    References, Subject, Comments, Keywords, OptionalField};

pub trait Parsable: Sized {
    /// Parse the object off of the beginning of the `input`.  If found, returns Some object,
    /// and a slice containing the remainer of the input.
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError>;
}

pub trait Streamable {
    /// Serializes and sends the content out to `w`, returning the number of bytes written.
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError>;
}

// 3.6.7
// trace           =   [return]
//                     1*received
#[derive(Debug, Clone, PartialEq)]
pub struct Trace {
    return_path: Option<Return>,
    received: Vec<Received>
}
impl Parsable for Trace {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        let maybe_return = parse!(Return, rem).ok();
        let mut received: Vec<Received> = Vec::new();
        while let Ok(r) = parse!(Received, rem) {
            received.push(r);
        }
        if received.len() < 1 { return Err(ParseError::NotFound); }
        Ok((Trace {
            return_path: maybe_return,
            received: received,
        }, rem))
    }
}
impl Streamable for Trace {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref rp) = self.return_path {
            count += try!(rp.stream(w));
        }
        for r in &self.received {
            count += try!(r.stream(w));
        }
        Ok(count)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum ResentField {
    Date(ResentDate),
    From(ResentFrom),
    Sender(ResentSender),
    To(ResentTo),
    Cc(ResentCc),
    Bcc(ResentBcc),
    MessageId(ResentMessageId),
}
impl Parsable for ResentField {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        if let Ok(x) = parse!(ResentDate, rem) {
            return Ok((ResentField::Date(x), rem));
        }
        if let Ok(x) = parse!(ResentFrom, rem) {
            return Ok((ResentField::From(x), rem));
        }
        if let Ok(x) = parse!(ResentSender, rem) {
            return Ok((ResentField::Sender(x), rem));
        }
        if let Ok(x) = parse!(ResentTo, rem) {
            return Ok((ResentField::To(x), rem));
        }
        if let Ok(x) = parse!(ResentCc, rem) {
            return Ok((ResentField::Cc(x), rem));
        }
        if let Ok(x) = parse!(ResentBcc, rem) {
            return Ok((ResentField::Bcc(x), rem));
        }
        if let Ok(x) = parse!(ResentMessageId, rem) {
            return Ok((ResentField::MessageId(x), rem));
        }
        Err(ParseError::NotFound)
    }
}
impl Streamable for ResentField {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            ResentField::Date(ref x) => x.stream(w),
            ResentField::From(ref x) => x.stream(w),
            ResentField::Sender(ref x) => x.stream(w),
            ResentField::To(ref x) => x.stream(w),
            ResentField::Cc(ref x) => x.stream(w),
            ResentField::Bcc(ref x) => x.stream(w),
            ResentField::MessageId(ref x) => x.stream(w),
        }
    }
}

// 3.6
// a sub part of the Fields definition
#[derive(Debug, Clone, PartialEq)]
pub enum Field {
    OrigDate(OrigDate),
    From(From),
    Sender(Sender),
    ReplyTo(ReplyTo),
    To(To),
    Cc(Cc),
    Bcc(Bcc),
    MessageId(MessageId),
    InReplyTo(InReplyTo),
    References(References),
    Subject(Subject),
    Comments(Comments),
    Keywords(Keywords),
    OptionalField(OptionalField),
}
impl Parsable for Field {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        if let Ok(x) = parse!(OrigDate, rem) {
            return Ok((Field::OrigDate(x), rem));
        }
        if let Ok(x) = parse!(From, rem) {
            return Ok((Field::From(x), rem));
        }
        if let Ok(x) = parse!(Sender, rem) {
            return Ok((Field::Sender(x), rem));
        }
        if let Ok(x) = parse!(ReplyTo, rem) {
            return Ok((Field::ReplyTo(x), rem));
        }
        if let Ok(x) = parse!(To, rem) {
            return Ok((Field::To(x), rem));
        }
        if let Ok(x) = parse!(Cc, rem) {
            return Ok((Field::Cc(x), rem));
        }
        if let Ok(x) = parse!(Bcc, rem) {
            return Ok((Field::Bcc(x), rem));
        }
        if let Ok(x) = parse!(MessageId, rem) {
            return Ok((Field::MessageId(x), rem));
        }
        if let Ok(x) = parse!(InReplyTo, rem) {
            return Ok((Field::InReplyTo(x), rem));
        }
        if let Ok(x) = parse!(References, rem) {
            return Ok((Field::References(x), rem));
        }
        if let Ok(x) = parse!(Subject, rem) {
            return Ok((Field::Subject(x), rem));
        }
        if let Ok(x) = parse!(Comments, rem) {
            return Ok((Field::Comments(x), rem));
        }
        if let Ok(x) = parse!(Keywords, rem) {
            return Ok((Field::Keywords(x), rem));
        }
        if let Ok(x) = parse!(OptionalField, rem) {
            return Ok((Field::OptionalField(x), rem));
        }
        Err(ParseError::NotFound)
    }
}
impl Streamable for Field {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            Field::OrigDate(ref x) => x.stream(w),
            Field::From(ref x) => x.stream(w),
            Field::Sender(ref x) => x.stream(w),
            Field::ReplyTo(ref x) => x.stream(w),
            Field::To(ref x) => x.stream(w),
            Field::Cc(ref x) => x.stream(w),
            Field::Bcc(ref x) => x.stream(w),
            Field::MessageId(ref x) => x.stream(w),
            Field::InReplyTo(ref x) => x.stream(w),
            Field::References(ref x) => x.stream(w),
            Field::Subject(ref x) => x.stream(w),
            Field::Comments(ref x) => x.stream(w),
            Field::Keywords(ref x) => x.stream(w),
            Field::OptionalField(ref x) => x.stream(w),
        }
    }
}
<|endoftext|>