<commit_before>use regex::Regex;

static IGNORE_WHITESPACE: &'static str = r"\s*";
static ANY_WHITESPACE: &'static str = r"\s+";
static FIELD_TYPE: &'static str = r"([a-zA-Z0-9_/]+)";
static FIELD_NAME: &'static str = r"([a-zA-Z][a-zA-Z0-9_]*)";
static EMPTY_BRACKETS: &'static str = r"\[\s*\]";
static NUMBER_BRACKETS: &'static str = r"\[\s*([0-9]+)\s*\]";

fn match_field(data: &str) -> Option<FieldLine> {
    lazy_static! {
        static ref MATCHER: String = format!("^{}{}{}$", FIELD_TYPE, ANY_WHITESPACE, FIELD_NAME);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some(FieldLine {
        field_type: captures.get(1).unwrap().as_str().into(),
        field_name: captures.get(2).unwrap().as_str().into(),
    })
}

fn match_vector_field(data: &str) -> Option<FieldLine> {
    lazy_static! {
        static ref MATCHER: String = format!(
            "^{}{}{}{}{}$", FIELD_TYPE, IGNORE_WHITESPACE, EMPTY_BRACKETS, ANY_WHITESPACE,
            FIELD_NAME);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some(FieldLine {
        field_type: captures.get(1).unwrap().as_str().into(),
        field_name: captures.get(2).unwrap().as_str().into(),
    })
}

fn match_array_field(data: &str) -> Option<(FieldLine, usize)> {
    lazy_static! {
        static ref MATCHER: String = format!(
            "^{}{}{}{}{}$", FIELD_TYPE, IGNORE_WHITESPACE, NUMBER_BRACKETS, ANY_WHITESPACE,
            FIELD_NAME);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some((FieldLine {
              field_type: captures.get(1).unwrap().as_str().into(),
              field_name: captures.get(3).unwrap().as_str().into(),
          },
          captures.get(2).unwrap().as_str().parse().unwrap()))
}

fn match_const_string(data: &str) -> Option<(FieldLine, String)> {
    lazy_static! {
        static ref MATCHER: String = format!(
            r"^(string){}{}{}={}(.*)$", ANY_WHITESPACE, FIELD_NAME, IGNORE_WHITESPACE,
            IGNORE_WHITESPACE);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some((FieldLine {
              field_type: captures.get(1).unwrap().as_str().into(),
              field_name: captures.get(2).unwrap().as_str().into(),
          },
          captures.get(3).unwrap().as_str().into()))
}

fn match_const_numeric(data: &str) -> Option<(FieldLine, String)> {
    lazy_static! {
        static ref MATCHER: String = format!(
            r"^{}{}{}{}={}(-?[0-9]+)$", FIELD_TYPE, ANY_WHITESPACE, FIELD_NAME,
            IGNORE_WHITESPACE, IGNORE_WHITESPACE);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some((FieldLine {
              field_type: captures.get(1).unwrap().as_str().into(),
              field_name: captures.get(2).unwrap().as_str().into(),
          },
          captures.get(3).unwrap().as_str().into()))
}

fn match_line(data: &str) -> Result<Option<FieldInfo>, ()> {
    if let Some((info, data)) = match_const_string(data.trim()) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Const(data),
        }));
    }
    let data = data.splitn(2, '#').next().unwrap().trim();
    if data == "" {
        return Ok(None);
    }
    if let Some(info) = match_field(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Unit,
        }));
    }
    if let Some(info) = match_vector_field(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Vector,
        }));
    }
    if let Some((info, count)) = match_array_field(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Array(count),
        }));
    }
    if let Some((info, data)) = match_const_numeric(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Const(data),
        }));
    }
    Err(())
}

#[inline]
fn match_lines(data: &str) -> Result<Vec<FieldInfo>, ()> {
    let lines: Result<Vec<Option<_>>, ()> = data.split('\n').map(match_line).collect();
    Ok(lines?.into_iter().filter_map(|v| v).collect())
}

#[derive(Debug,PartialEq)]
struct FieldLine {
    field_type: String,
    field_name: String,
}

#[derive(Debug,PartialEq)]
enum FieldCase {
    Unit,
    Vector,
    Array(usize),
    Const(String),
}

#[derive(Debug,PartialEq)]
struct FieldInfo {
    datatype: String,
    name: String,
    case: FieldCase,
}

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

    #[test]
    fn match_field_matches_legal_field() {
        assert_eq!(FieldLine {
                       field_type: "geom_msgs/Twist".into(),
                       field_name: "myname".into(),
                   },
                   match_field("geom_msgs/Twist   myname").unwrap());
    }

    #[test]
    fn match_vector_field_matches_legal_field() {
        assert_eq!(FieldLine {
                       field_type: "geom_msgs/Twist".into(),
                       field_name: "myname".into(),
                   },
                   match_vector_field("geom_msgs/Twist [  ]   myname").unwrap());
    }

    #[test]
    fn match_array_field_matches_legal_field() {
        assert_eq!((FieldLine {
                        field_type: "geom_msgs/Twist".into(),
                        field_name: "myname".into(),
                    },
                    127),
                   match_array_field("geom_msgs/Twist   [   127 ]   myname").unwrap());
    }

    #[test]
    fn match_const_string_matches_legal_field() {
        assert_eq!((FieldLine {
                        field_type: "string".into(),
                        field_name: "myname".into(),
                    },
                    "this is # data".into()),
                   match_const_string("string   myname  =  this is # data").unwrap());
    }

    #[test]
    fn match_const_numeric_matches_legal_field() {
        assert_eq!((FieldLine {
                        field_type: "mytype".into(),
                        field_name: "myname".into(),
                    },
                    "-444".into()),
                   match_const_numeric("mytype   myname  =  -444").unwrap());
    }

    #[test]
    fn match_line_works_on_legal_data() {
        assert!(match_line("#just a comment").unwrap().is_none());
        assert!(match_line("#  YOLO !   ").unwrap().is_none());
        assert!(match_line("      ").unwrap().is_none());

        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Unit,
                   },
                   match_line("  geom_msgs/Twist   myname    # this clearly should succeed")
                       .unwrap()
                       .unwrap());

        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Vector,
                   },
                   match_line("  geom_msgs/Twist [  ]   myname  # ...").unwrap().unwrap());

        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Array(127),
                   },
                   match_line("  geom_msgs/Twist   [   127 ]   myname# comment").unwrap().unwrap());
        assert_eq!(FieldInfo {
                       datatype: "string".into(),
                       name: "myname".into(),
                       case: FieldCase::Const("this is # data".into()),
                   },
                   match_line("  string  myname =   this is # data  ").unwrap().unwrap());
        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Const("-444".into()),
                   },
                   match_line("  geom_msgs/Twist  myname =   -444 # data  ").unwrap().unwrap());
    }

    #[test]
    fn match_lines_parses_real_message() {
        let data = match_lines(include_str!("TwistWithCovariance.msg")).unwrap();
        assert_eq!(vec![FieldInfo {
                            datatype: "Twist".into(),
                            name: "twist".into(),
                            case: FieldCase::Unit,
                        },
                        FieldInfo {
                            datatype: "float64".into(),
                            name: "covariance".into(),
                            case: FieldCase::Array(36),
                        }],
                   data);
    }
}
<commit_msg>Extract members from message data<commit_after>use regex::Regex;

static IGNORE_WHITESPACE: &'static str = r"\s*";
static ANY_WHITESPACE: &'static str = r"\s+";
static FIELD_TYPE: &'static str = r"([a-zA-Z0-9_/]+)";
static FIELD_NAME: &'static str = r"([a-zA-Z][a-zA-Z0-9_]*)";
static EMPTY_BRACKETS: &'static str = r"\[\s*\]";
static NUMBER_BRACKETS: &'static str = r"\[\s*([0-9]+)\s*\]";

fn match_field(data: &str) -> Option<FieldLine> {
    lazy_static! {
        static ref MATCHER: String = format!("^{}{}{}$", FIELD_TYPE, ANY_WHITESPACE, FIELD_NAME);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some(FieldLine {
        field_type: captures.get(1).unwrap().as_str().into(),
        field_name: captures.get(2).unwrap().as_str().into(),
    })
}

fn match_vector_field(data: &str) -> Option<FieldLine> {
    lazy_static! {
        static ref MATCHER: String = format!(
            "^{}{}{}{}{}$", FIELD_TYPE, IGNORE_WHITESPACE, EMPTY_BRACKETS, ANY_WHITESPACE,
            FIELD_NAME);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some(FieldLine {
        field_type: captures.get(1).unwrap().as_str().into(),
        field_name: captures.get(2).unwrap().as_str().into(),
    })
}

fn match_array_field(data: &str) -> Option<(FieldLine, usize)> {
    lazy_static! {
        static ref MATCHER: String = format!(
            "^{}{}{}{}{}$", FIELD_TYPE, IGNORE_WHITESPACE, NUMBER_BRACKETS, ANY_WHITESPACE,
            FIELD_NAME);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some((FieldLine {
              field_type: captures.get(1).unwrap().as_str().into(),
              field_name: captures.get(3).unwrap().as_str().into(),
          },
          captures.get(2).unwrap().as_str().parse().unwrap()))
}

fn match_const_string(data: &str) -> Option<(FieldLine, String)> {
    lazy_static! {
        static ref MATCHER: String = format!(
            r"^(string){}{}{}={}(.*)$", ANY_WHITESPACE, FIELD_NAME, IGNORE_WHITESPACE,
            IGNORE_WHITESPACE);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some((FieldLine {
              field_type: captures.get(1).unwrap().as_str().into(),
              field_name: captures.get(2).unwrap().as_str().into(),
          },
          captures.get(3).unwrap().as_str().into()))
}

fn match_const_numeric(data: &str) -> Option<(FieldLine, String)> {
    lazy_static! {
        static ref MATCHER: String = format!(
            r"^{}{}{}{}={}(-?[0-9]+)$", FIELD_TYPE, ANY_WHITESPACE, FIELD_NAME,
            IGNORE_WHITESPACE, IGNORE_WHITESPACE);
        static ref RE: Regex = Regex::new(&MATCHER).unwrap();
    }
    let captures = match RE.captures(data) {
        Some(v) => v,
        None => return None,
    };
    Some((FieldLine {
              field_type: captures.get(1).unwrap().as_str().into(),
              field_name: captures.get(2).unwrap().as_str().into(),
          },
          captures.get(3).unwrap().as_str().into()))
}

fn match_line(data: &str) -> Result<Option<FieldInfo>, ()> {
    if let Some((info, data)) = match_const_string(data.trim()) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Const(data),
        }));
    }
    let data = data.splitn(2, '#').next().unwrap().trim();
    if data == "" {
        return Ok(None);
    }
    if let Some(info) = match_field(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Unit,
        }));
    }
    if let Some(info) = match_vector_field(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Vector,
        }));
    }
    if let Some((info, count)) = match_array_field(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Array(count),
        }));
    }
    if let Some((info, data)) = match_const_numeric(data) {
        return Ok(Some(FieldInfo {
            datatype: info.field_type,
            name: info.field_name,
            case: FieldCase::Const(data),
        }));
    }
    Err(())
}

#[inline]
fn match_lines(data: &str) -> Result<Vec<FieldInfo>, ()> {
    let lines: Result<Vec<Option<_>>, ()> = data.split('\n').map(match_line).collect();
    Ok(lines?.into_iter().filter_map(|v| v).collect())
}

#[derive(Debug,PartialEq)]
struct FieldLine {
    field_type: String,
    field_name: String,
}

#[derive(Debug,PartialEq)]
enum FieldCase {
    Unit,
    Vector,
    Array(usize),
    Const(String),
}

#[derive(Clone,Debug,PartialEq)]
enum MemberCase {
    Unit,
    Vector,
    Array(usize),
}

impl<'a> From<&'a FieldCase> for MemberCase {
    fn from(case: &'a FieldCase) -> MemberCase {
        match *case {
            FieldCase::Unit => MemberCase::Unit,
            FieldCase::Vector => MemberCase::Vector,
            FieldCase::Array(v) => MemberCase::Array(v),
            _ => panic!("Conversion not supported"),
        }
    }
}

#[derive(Debug,PartialEq)]
struct FieldInfo {
    datatype: String,
    name: String,
    case: FieldCase,
}

#[derive(Debug,PartialEq)]
enum DataType {
    Bool,
    I8,
    I16,
    I32,
    I64,
    U8,
    U16,
    U32,
    U64,
    F32,
    F64,
    String,
    Time,
    Duration,
    LocalStruct(String),
    RemoteStruct(String, String),
}

#[derive(Debug,PartialEq)]
struct MemberInfo {
    datatype: DataType,
    name: String,
    case: MemberCase,
}

fn parse_members(fields: &[FieldInfo]) -> Result<Vec<MemberInfo>, ()> {
    fields.iter()
        .map(|v| {
            Ok(MemberInfo {
                datatype: parse_datatype(&v.datatype).ok_or(())?,
                name: v.name.clone(),
                case: MemberCase::from(&v.case),
            })
        })
        .collect()
}

fn parse_datatype(datatype: &str) -> Option<DataType> {
    match datatype {
        "bool" => Some(DataType::Bool),
        "int8" => Some(DataType::I8),
        "int16" => Some(DataType::I16),
        "int32" => Some(DataType::I32),
        "int64" => Some(DataType::I64),
        "uint8" => Some(DataType::U8),
        "uint16" => Some(DataType::U16),
        "uint32" => Some(DataType::U32),
        "uint64" => Some(DataType::U64),
        "float32" => Some(DataType::F32),
        "float64" => Some(DataType::F64),
        "string" => Some(DataType::String),
        "time" => Some(DataType::Time),
        "duration" => Some(DataType::Duration),
        _ => {
            let parts = datatype.split('/').collect::<Vec<_>>();
            if parts.iter().any(|v| v.len() == 0) {
                return None;
            }
            match parts.len() {
                2 => Some(DataType::RemoteStruct(parts[0].to_owned(), parts[1].to_owned())),
                1 => Some(DataType::LocalStruct(parts[0].to_owned())),
                _ => None,
            }
        }
    }
}

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

    #[test]
    fn match_field_matches_legal_field() {
        assert_eq!(FieldLine {
                       field_type: "geom_msgs/Twist".into(),
                       field_name: "myname".into(),
                   },
                   match_field("geom_msgs/Twist   myname").unwrap());
    }

    #[test]
    fn match_vector_field_matches_legal_field() {
        assert_eq!(FieldLine {
                       field_type: "geom_msgs/Twist".into(),
                       field_name: "myname".into(),
                   },
                   match_vector_field("geom_msgs/Twist [  ]   myname").unwrap());
    }

    #[test]
    fn match_array_field_matches_legal_field() {
        assert_eq!((FieldLine {
                        field_type: "geom_msgs/Twist".into(),
                        field_name: "myname".into(),
                    },
                    127),
                   match_array_field("geom_msgs/Twist   [   127 ]   myname").unwrap());
    }

    #[test]
    fn match_const_string_matches_legal_field() {
        assert_eq!((FieldLine {
                        field_type: "string".into(),
                        field_name: "myname".into(),
                    },
                    "this is # data".into()),
                   match_const_string("string   myname  =  this is # data").unwrap());
    }

    #[test]
    fn match_const_numeric_matches_legal_field() {
        assert_eq!((FieldLine {
                        field_type: "mytype".into(),
                        field_name: "myname".into(),
                    },
                    "-444".into()),
                   match_const_numeric("mytype   myname  =  -444").unwrap());
    }

    #[test]
    fn match_line_works_on_legal_data() {
        assert!(match_line("#just a comment").unwrap().is_none());
        assert!(match_line("#  YOLO !   ").unwrap().is_none());
        assert!(match_line("      ").unwrap().is_none());

        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Unit,
                   },
                   match_line("  geom_msgs/Twist   myname    # this clearly should succeed")
                       .unwrap()
                       .unwrap());

        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Vector,
                   },
                   match_line("  geom_msgs/Twist [  ]   myname  # ...").unwrap().unwrap());

        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Array(127),
                   },
                   match_line("  geom_msgs/Twist   [   127 ]   myname# comment").unwrap().unwrap());
        assert_eq!(FieldInfo {
                       datatype: "string".into(),
                       name: "myname".into(),
                       case: FieldCase::Const("this is # data".into()),
                   },
                   match_line("  string  myname =   this is # data  ").unwrap().unwrap());
        assert_eq!(FieldInfo {
                       datatype: "geom_msgs/Twist".into(),
                       name: "myname".into(),
                       case: FieldCase::Const("-444".into()),
                   },
                   match_line("  geom_msgs/Twist  myname =   -444 # data  ").unwrap().unwrap());
    }

    #[test]
    fn match_lines_parses_real_message() {
        let data = match_lines(include_str!("TwistWithCovariance.msg")).unwrap();
        assert_eq!(vec![FieldInfo {
                            datatype: "Twist".into(),
                            name: "twist".into(),
                            case: FieldCase::Unit,
                        },
                        FieldInfo {
                            datatype: "float64".into(),
                            name: "covariance".into(),
                            case: FieldCase::Array(36),
                        }],
                   data);
    }

    #[test]
    fn parse_members_parses_real_message() {
        let data = parse_members(&match_lines(include_str!("TwistWithCovariance.msg")).unwrap())
            .unwrap();
        assert_eq!(vec![MemberInfo {
                            datatype: DataType::LocalStruct("Twist".into()),
                            name: "twist".into(),
                            case: MemberCase::Unit,
                        },
                        MemberInfo {
                            datatype: DataType::F64,
                            name: "covariance".into(),
                            case: MemberCase::Array(36),
                        }],
                   data);
    }
}
<|endoftext|>


<commit_before>use std::{mem, slice, str};

use cassandra_sys::CASS_OK;
use cassandra_sys::cass_true;
use cassandra_sys::cass_false;

// use cassandra_sys::CassIteratorType as _CassIteratorType;
use cassandra_sys::CassIterator as _CassIterator;
// use cassandra_sys::cass_iterator_type;
use cassandra_sys::cass_iterator_free;
use cassandra_sys::cass_iterator_get_function_meta;
use cassandra_sys::cass_iterator_get_keyspace_meta;
use cassandra_sys::cass_iterator_get_map_key;
use cassandra_sys::cass_iterator_get_map_value;
use cassandra_sys::cass_iterator_get_meta_field_name;
use cassandra_sys::cass_iterator_get_meta_field_value;
use cassandra_sys::cass_iterator_get_table_meta;
use cassandra_sys::cass_iterator_get_column_meta;
use cassandra_sys::cass_iterator_get_user_type;
use cassandra_sys::cass_iterator_get_value;
use cassandra_sys::cass_iterator_next;
use cassandra::value::Value;
use cassandra::field::Field;
use cassandra::data_type::ConstDataType;
use cassandra::schema::keyspace_meta::KeyspaceMeta;
use cassandra::schema::table_meta::TableMeta;
use cassandra::schema::function_meta::FunctionMeta;
use cassandra::schema::column_meta::ColumnMeta;
use cassandra::schema::aggregate_meta::AggregateMeta;
use cassandra_sys::cass_iterator_get_aggregate_meta;
use cassandra::util::Protected;

///Iterates over the  aggregate metadata entries(??)
pub struct AggregateIterator(*mut _CassIterator);

impl Drop for AggregateIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for AggregateIterator {
    type Item = AggregateMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => {
                    let field_value = cass_iterator_get_aggregate_meta(self.0);
                    Some(AggregateMeta::build(field_value))
                }
            }
        }
    }
}

///Iterater over the fields of a UDT
pub struct UserTypeIterator(*mut _CassIterator);

impl Drop for UserTypeIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for UserTypeIterator {
    type Item = ConstDataType;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(ConstDataType(cass_iterator_get_user_type(self.0))),
            }
        }
    }
}

impl UserTypeIterator {
    //    pub fn get_field_name(&mut self)-> Value {unsafe{
    //
    //        Value::new(cass_iterator_get_user_type_field_name(self.0))
    //    }}
}

///Iterater over the  function metadata entries(??)
pub struct FunctionIterator(*mut _CassIterator);

impl Iterator for FunctionIterator {
    type Item = FunctionMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(FunctionMeta::build(cass_iterator_get_function_meta(self.0))),
            }
        }
    }
}

///Iterater over the table's metadata entries(??)
pub struct TableIterator(*mut _CassIterator);

impl Iterator for TableIterator {
    type Item = TableMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(TableMeta::build(cass_iterator_get_table_meta(self.0))),
            }
        }
    }
}

///Iterater over the keyspace's metadata entries(??)
pub struct KeyspaceIterator(*mut _CassIterator);

impl Iterator for KeyspaceIterator {
    type Item = KeyspaceMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(KeyspaceMeta::build(cass_iterator_get_keyspace_meta(self.0))),
            }
        }
    }
}

///Iterater over the columns's metadata entries(??)
pub struct ColumnIterator(*mut _CassIterator);

impl Iterator for ColumnIterator {
    type Item = ColumnMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(ColumnMeta::build(cass_iterator_get_column_meta(self.0))),
            }
        }
    }
}

///Iterater over the field's metadata entries(??)
pub struct FieldIterator(*mut _CassIterator);

impl Iterator for FieldIterator {
    type Item = Field;
    #[allow(cast_possible_truncation)]
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => {
                    let mut name = mem::zeroed();
                    let mut name_length = mem::zeroed();
                    match cass_iterator_get_meta_field_name(self.0, &mut name, &mut name_length) {
                        CASS_OK => {
                            let slice = slice::from_raw_parts(name as *const u8, name_length as usize);
                            Some(Field {
                                name: str::from_utf8(slice).expect("must be utf8").to_owned(),
                                value: Value::build(cass_iterator_get_meta_field_value(self.0)),
                            })
                        }
                        err => panic!("FIXME: no error handling. Err {:?}", err),
                    }
                }
            }
        }
    }
}

// pub struct CassIteratorType(_CassIteratorType);

// impl CassIteratorType {
//    pub fn new(_type: _CassIteratorType) -> Self { CassIteratorType(_type) }
// }

// impl Protected<*mut _Batch> for CassIterator {
//    fn inner(&self) -> *mut _CassIterator {
//        self.0
//    }
//    fn build(inner: *mut _CassIterator) -> Self {
//        CassIterator(inner)
//    }
// }

impl Protected<*mut _CassIterator> for UserTypeIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        UserTypeIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for AggregateIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        AggregateIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for FunctionIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        FunctionIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for KeyspaceIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        KeyspaceIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for FieldIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        FieldIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for ColumnIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        ColumnIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for TableIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        TableIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for MapIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        MapIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for SetIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        SetIterator(inner)
    }
}

///Iterater over the set's metadata entries(??)
pub struct SetIterator(*mut _CassIterator);

// impl<'a> Display for &'a SetIterator {
//    fn fmt(&self, f:&mut Formatter) -> fmt::Result {
//        for item in self {
//            try!(write!(f, "{}\t", item));
//        }
//        Ok(())
//    }
// }

impl Drop for SetIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for SetIterator {
    type Item = Value;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_value()),
            }
        }
    }
}

impl SetIterator {
    fn get_value(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_value(self.0)) }
    }
}

///An iterator over the k/v pair in the map
pub struct MapIterator(*mut _CassIterator);

impl MapIterator {
    fn get_key(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_map_key(self.0)) }
    }
    fn get_value(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_map_value(self.0)) }
    }

    ///Gets the next k/v pair in the map
    pub fn get_pair(&mut self) -> (Value, Value) {
        (self.get_key(), self.get_value())
    }
}

///An iterator over the elements of a Cassandra tuple
pub struct TupleIterator(pub *mut _CassIterator);

impl Drop for TupleIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for TupleIterator {
    type Item = Value;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_value()),
            }
        }
    }
}

impl TupleIterator {
    fn get_value(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_value(self.0)) }
    }
}

impl Drop for MapIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for MapIterator {
    type Item = (Value,Value);
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_pair()),
            }
        }
    }
}
<commit_msg>Derive debug for iterator<commit_after>use std::{mem, slice, str};

use cassandra_sys::CASS_OK;
use cassandra_sys::cass_true;
use cassandra_sys::cass_false;

// use cassandra_sys::CassIteratorType as _CassIteratorType;
use cassandra_sys::CassIterator as _CassIterator;
// use cassandra_sys::cass_iterator_type;
use cassandra_sys::cass_iterator_free;
use cassandra_sys::cass_iterator_get_function_meta;
use cassandra_sys::cass_iterator_get_keyspace_meta;
use cassandra_sys::cass_iterator_get_map_key;
use cassandra_sys::cass_iterator_get_map_value;
use cassandra_sys::cass_iterator_get_meta_field_name;
use cassandra_sys::cass_iterator_get_meta_field_value;
use cassandra_sys::cass_iterator_get_table_meta;
use cassandra_sys::cass_iterator_get_column_meta;
use cassandra_sys::cass_iterator_get_user_type;
use cassandra_sys::cass_iterator_get_value;
use cassandra_sys::cass_iterator_next;
use cassandra::value::Value;
use cassandra::field::Field;
use cassandra::data_type::ConstDataType;
use cassandra::schema::keyspace_meta::KeyspaceMeta;
use cassandra::schema::table_meta::TableMeta;
use cassandra::schema::function_meta::FunctionMeta;
use cassandra::schema::column_meta::ColumnMeta;
use cassandra::schema::aggregate_meta::AggregateMeta;
use cassandra_sys::cass_iterator_get_aggregate_meta;
use cassandra::util::Protected;

///Iterates over the  aggregate metadata entries(??)
#[derive(Debug)]
pub struct AggregateIterator(*mut _CassIterator);

impl Drop for AggregateIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for AggregateIterator {
    type Item = AggregateMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => {
                    let field_value = cass_iterator_get_aggregate_meta(self.0);
                    Some(AggregateMeta::build(field_value))
                }
            }
        }
    }
}

///Iterater over the fields of a UDT
#[derive(Debug)]
pub struct UserTypeIterator(*mut _CassIterator);

impl Drop for UserTypeIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for UserTypeIterator {
    type Item = ConstDataType;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(ConstDataType(cass_iterator_get_user_type(self.0))),
            }
        }
    }
}

impl UserTypeIterator {
    //    pub fn get_field_name(&mut self)-> Value {unsafe{
    //
    //        Value::new(cass_iterator_get_user_type_field_name(self.0))
    //    }}
}

///Iterater over the  function metadata entries(??)
#[derive(Debug)]
pub struct FunctionIterator(*mut _CassIterator);

impl Iterator for FunctionIterator {
    type Item = FunctionMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(FunctionMeta::build(cass_iterator_get_function_meta(self.0))),
            }
        }
    }
}

///Iterater over the table's metadata entries(??)
#[derive(Debug)]
pub struct TableIterator(*mut _CassIterator);

impl Iterator for TableIterator {
    type Item = TableMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(TableMeta::build(cass_iterator_get_table_meta(self.0))),
            }
        }
    }
}

///Iterater over the keyspace's metadata entries(??)
#[derive(Debug)]
pub struct KeyspaceIterator(*mut _CassIterator);

impl Iterator for KeyspaceIterator {
    type Item = KeyspaceMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(KeyspaceMeta::build(cass_iterator_get_keyspace_meta(self.0))),
            }
        }
    }
}

///Iterater over the columns's metadata entries(??)
#[derive(Debug)]
pub struct ColumnIterator(*mut _CassIterator);

impl Iterator for ColumnIterator {
    type Item = ColumnMeta;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(ColumnMeta::build(cass_iterator_get_column_meta(self.0))),
            }
        }
    }
}

///Iterater over the field's metadata entries(??)
#[derive(Debug)]
pub struct FieldIterator(*mut _CassIterator);

impl Iterator for FieldIterator {
    type Item = Field;
    #[allow(cast_possible_truncation)]
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => {
                    let mut name = mem::zeroed();
                    let mut name_length = mem::zeroed();
                    match cass_iterator_get_meta_field_name(self.0, &mut name, &mut name_length) {
                        CASS_OK => {
                            let slice = slice::from_raw_parts(name as *const u8, name_length as usize);
                            Some(Field {
                                name: str::from_utf8(slice).expect("must be utf8").to_owned(),
                                value: Value::build(cass_iterator_get_meta_field_value(self.0)),
                            })
                        }
                        err => panic!("FIXME: no error handling. Err {:?}", err),
                    }
                }
            }
        }
    }
}

// pub struct CassIteratorType(_CassIteratorType);

// impl CassIteratorType {
//    pub fn new(_type: _CassIteratorType) -> Self { CassIteratorType(_type) }
// }

// impl Protected<*mut _Batch> for CassIterator {
//    fn inner(&self) -> *mut _CassIterator {
//        self.0
//    }
//    fn build(inner: *mut _CassIterator) -> Self {
//        CassIterator(inner)
//    }
// }

impl Protected<*mut _CassIterator> for UserTypeIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        UserTypeIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for AggregateIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        AggregateIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for FunctionIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        FunctionIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for KeyspaceIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        KeyspaceIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for FieldIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        FieldIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for ColumnIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        ColumnIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for TableIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        TableIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for MapIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        MapIterator(inner)
    }
}

impl Protected<*mut _CassIterator> for SetIterator {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
    fn build(inner: *mut _CassIterator) -> Self {
        SetIterator(inner)
    }
}

///Iterater over the set's metadata entries(??)
#[derive(Debug)]
pub struct SetIterator(*mut _CassIterator);

// impl<'a> Display for &'a SetIterator {
//    fn fmt(&self, f:&mut Formatter) -> fmt::Result {
//        for item in self {
//            try!(write!(f, "{}\t", item));
//        }
//        Ok(())
//    }
// }

impl Drop for SetIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for SetIterator {
    type Item = Value;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_value()),
            }
        }
    }
}

impl SetIterator {
    fn get_value(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_value(self.0)) }
    }
}

///An iterator over the k/v pair in the map
#[derive(Debug)]
pub struct MapIterator(*mut _CassIterator);

impl MapIterator {
    fn get_key(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_map_key(self.0)) }
    }
    fn get_value(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_map_value(self.0)) }
    }

    ///Gets the next k/v pair in the map
    pub fn get_pair(&mut self) -> (Value, Value) {
        (self.get_key(), self.get_value())
    }
}

///An iterator over the elements of a Cassandra tuple
#[derive(Debug)]
pub struct TupleIterator(pub *mut _CassIterator);

impl Drop for TupleIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for TupleIterator {
    type Item = Value;
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_value()),
            }
        }
    }
}

impl TupleIterator {
    fn get_value(&mut self) -> Value {
        unsafe { Value::build(cass_iterator_get_value(self.0)) }
    }
}

impl Drop for MapIterator {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl Iterator for MapIterator {
    type Item = (Value,Value);
    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_pair()),
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate libc;
extern crate term_input;
extern crate termbox_simple;
extern crate time;
extern crate tiny;

use term_input::{Input, Event};

use std::mem;

use tiny::tui::{TUI, TUIRet, MsgTarget};

fn loop_() -> Option<String> {
    let mut tui = TUI::new();
    tui.new_server_tab("debug");

    let mut fd_set : libc::fd_set = unsafe { mem::zeroed() };
    unsafe { libc::FD_SET(libc::STDIN_FILENO, &mut fd_set); }
    let nfds = libc::STDIN_FILENO + 1;

    let mut input = Input::new();
    let mut ev_buffer : Vec<Event> = Vec::new();

    loop {
        tui.draw();

        let mut fd_set_ = fd_set.clone();
        let ret = unsafe {
            libc::select(nfds,
                         &mut fd_set_,           // read fds
                         std::ptr::null_mut(),   // write fds
                         std::ptr::null_mut(),   // error fds
                         std::ptr::null_mut())   // timeval
        };

        if unsafe { ret == -1 || libc::FD_ISSET(0, &mut fd_set_) } {
            input.read_input_events(&mut ev_buffer);
            for ev in ev_buffer.drain(0..) {
                match tui.handle_input_event(ev) {
                    TUIRet::Input { msg, .. } => {
                        tui.add_msg(&msg.into_iter().collect::<String>(),
                                    &time::now(),
                                    &MsgTarget::Server { serv_name: "debug" });
                    },
                    TUIRet::Abort => {
                        return None;
                    },
                    _ => {}
                }
            }
        }
    }
}

fn main() {
    loop_().map(|err| println!("{}", err));
}
<commit_msg>Port msg_area_example to ev_loop<commit_after>extern crate ev_loop;
extern crate libc;
extern crate term_input;
extern crate termbox_simple;
extern crate time;
extern crate tiny;

use ev_loop::{EvLoop, READ_EV};
use term_input::{Input, Event};
use tiny::tui::{TUI, TUIRet, MsgTarget};

fn main() {
    let mut tui = TUI::new();
    tui.new_server_tab("debug");
    tui.draw();

    let mut ev_loop: EvLoop<TUI> = EvLoop::new();

    {
        let mut ev_buffer: Vec<Event> = Vec::new();
        let mut input = Input::new();
        ev_loop.add_fd(libc::STDIN_FILENO, READ_EV, Box::new(move |_, ctrl, tui| {
            input.read_input_events(&mut ev_buffer);
            for ev in ev_buffer.drain(0..) {
                match tui.handle_input_event(ev) {
                    TUIRet::Input { msg, .. } => {
                        tui.add_msg(&msg.into_iter().collect::<String>(),
                                    &time::now(),
                                    &MsgTarget::Server { serv_name: "debug" });
                    },
                    TUIRet::Abort => {
                        ctrl.stop();
                    },
                    _ => {}
                }
            }
            tui.draw();
        }));
    }

    ev_loop.run(tui);
}
<|endoftext|>


<commit_before>use std;
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)
    }
}
pub fn prime_filter_section(min:usize, max: usize) -> Vec<bool>{
    //Sieve of Atkin
    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) = (1, 3);
    while y_sq<max {
        if y_sq%2 == 1 {
            //n_1 = 4x^2 + y^2 === 1 (mod 4)
            let (mut n_1, mut to_next_n_1) = (y_sq, 4);
            loop{
                n_1 += to_next_n_1;
                to_next_n_1 += 8;
                match n_1%60{
                    _ if n_1 < min => continue,
                    _ if n_1 >= max => break,
                    1 | 13 | 17 | 29 | 37 | 41 | 49 | 53 => (),
                    _ => continue,
                };

                // println!("1: {}", n_1);
                prime_filter[n_1 - min] ^= true;
            };
        };
        if y_sq%3 == 1 {
            //n_2 = 3x^2 + y^2 === 1 (mod 6)
            let (mut n_2, mut to_next_n_2) = (y_sq, 3);
            loop {
                n_2 += to_next_n_2;
                to_next_n_2 += 6;
                match n_2%60{
                    _ if n_2 < min => continue,
                    _ if n_2 >= max => break,
                    7 | 19 | 31 | 43 => (),
                    _ => continue,
                };
                // println!("2: {}", n_2);
                prime_filter[n_2 - min] ^= true;
            };
            //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);
            loop {
                n_3 += to_next_n_3;
                to_next_n_3 += 6;
                match n_3%60{
                    _ if n_3 < min => continue,
                    _ if n_3 >= max => break,
                    11 | 23 | 47 | 59 => (),
                    _ => continue,
                };
                // println!("3: {}", n_3);
                prime_filter[n_3 - min] ^= true;
            };
        };
        while{ //Do-while
            y_sq += to_next_y_sq;
            to_next_y_sq += 2;
            y_sq%6 == 0
        } {};
    };
    //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>Added macros, improved case 3<commit_after>use std;

macro_rules! if_any_divides {
     ( $( $div:tt ),* | $n:ident $if_b:block ) => { if $(($n % $div == 0))|* $if_b};
}
macro_rules! if_sm_prime_divides{
    ( $n:ident $if_b:block ) => {if_any_divides!(
    2, 3, 5, 7, 11, 13,
    17, 19, 23, 29, 31,
    37, 41, 43, 47, 53,
    59, 61, 67, 71, 73,
    79, 83, 89, 97, 101,
    103, 107, 109, 113, 127,
    131, 137, 139, 149, 151,
    157, 163, 167, 173, 179,
    181, 191, 193, 197, 199 | $n $if_b)};
}
macro_rules! set_true_if_in_range{
    ( $( $i:tt ),* => $filter:ident + $offset:expr, $min:expr, $max:expr) => {
        $(if ($min <= $i) & ($max > $i) {$filter[$i-$offset] = true;})*
    };
    ( $( $i:tt ),* => $filter:ident, $min:expr, $max:expr) => {
        $(if ($min <= $i) & ($max > $i) {$filter[$i] = true;})*
    };
}
macro_rules! set_sm_primes_true {
    ($filter:expr, $min:expr, $max:expr) => {
        set_true_if_in_range!(
        2, 3, 5, 7, 11, 13,
        17, 19, 23, 29, 31,
        37, 41, 43, 47, 53,
        59, 61, 67, 71, 73,
        79, 83, 89, 97, 101,
        103, 107, 109, 113, 127,
        131, 137, 139, 149, 151,
        157, 163, 167, 173, 179,
        181, 191, 193, 197, 199 => $filter + $min, $min, $max)
    };
}

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)
    }
}
pub fn prime_filter_section(min:usize, max: usize) -> Vec<bool>{
    //Sieve of Atkin
    assert!(min<max);
    let mut prime_filter = vec![false; max-min];

    set_true_if_in_range!(2, 3, 5 => prime_filter + min, min, max);
    //Macro equivilent:
    // 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) = (1, 3);

    while y_sq<max {
        if y_sq%2 == 1 {
            //CASE 1
            //n_1 = 4x^2 + y^2 === 1 (mod 4)
            let (mut n_1, mut to_next_n_1) = (y_sq, 4);
            loop{
                n_1 += to_next_n_1;
                to_next_n_1 += 8;
                match n_1%60{
                    _ if n_1 < min => continue,
                    _ if n_1 >= max => break,
                    1 | 13 | 17 | 29 | 37 | 41 | 49 | 53 => (),
                    _ => continue,
                };
                prime_filter[n_1 - min] ^= true;
            };
        };
        if y_sq%3 == 1 {
            //CASE 2
            //n_2 = 3x^2 + y^2 === 1 (mod 6)
            let (mut n_2, mut to_next_n_2) = (y_sq, 3);
            loop {
                n_2 += to_next_n_2;
                to_next_n_2 += 6;
                match n_2%60{
                    _ if n_2 < min => continue,
                    _ if n_2 >= max => break,
                    7 | 19 | 31 | 43 => (),
                    _ => continue,
                };

                prime_filter[n_2 - min] ^= true;
            };
            //CASE 3
            //n_3 = 3x^2 - y^2 === 11 (mod 12)
            //Initially, we set x = y+1 -> n_3 = 3(y+1)^2 - y^2 = 2*y^2 + 6*y + 3
            //Amd then hop x by 2 each iteration.
            let (mut n_3, mut to_next_n_3) = (2*y_sq+3*to_next_y_sq, 6*to_next_y_sq+18);
            loop {
                match n_3%60{
                    _ if n_3 < min => (),
                    _ if n_3 >= max => break,
                    11 | 23 | 47 | 59 => {prime_filter[n_3 - min] ^= true;},
                    _ => (),
                };
                n_3 += to_next_n_3;
                to_next_n_3 += 24;
            };
        };
        while{ //Do-while
            y_sq += to_next_y_sq;
            to_next_y_sq += 2;
            y_sq%6 == 0
        } {};
    };

    //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>//! Takes 2 audio inputs and outputs them to 2 audio outputs.
//! All JACK notifications are also printed out.
extern crate jack;
use jack::prelude as j;
use std::io;

struct Notifications;

impl j::NotificationHandler for Notifications {
    fn thread_init(&self, _: &j::Client) {
        println!("JACK: thread init");
    }

    fn shutdown(&mut self, status: j::ClientStatus, reason: &str) {
        println!("JACK: shutdown with status {:?} because \"{}\"",
                 status,
                 reason);
    }

    fn freewheel(&mut self, _: &j::Client, is_enabled: bool) {
        println!("JACK: freewheel mode is {}",
                 if is_enabled { "on" } else { "of" });
    }

    fn buffer_size(&mut self, _: &j::Client, sz: j::JackFrames) -> j::JackControl {
        println!("JACK: buffer size changed to {}", sz);
        j::JackControl::Continue
    }

    fn sample_rate(&mut self, _: &j::Client, srate: j::JackFrames) -> j::JackControl {
        println!("JACK: sample rate changed to {}", srate);
        j::JackControl::Continue
    }

    fn client_registration(&mut self, _: &j::Client, name: &str, is_reg: bool) {
        println!("JACK: {} client with name \"{}\"",
                 if is_reg { "registered" } else { "unregistered" },
                 name);
    }

    fn port_registration(&mut self, _: &j::Client, port_id: j::JackPortId, is_reg: bool) {
        println!("JACK: {} port with id {}",
                 if is_reg { "registered" } else { "unregistered" },
                 port_id);
    }

    fn port_rename(&mut self,
                   _: &j::Client,
                   port_id: j::JackPortId,
                   old_name: &str,
                   new_name: &str)
                   -> j::JackControl {
        println!("JACK: port with id {} renamed from {} to {}",
                 port_id,
                 old_name,
                 new_name);
        j::JackControl::Continue
    }

    fn ports_connected(&mut self,
                       _: &j::Client,
                       port_id_a: j::JackPortId,
                       port_id_b: j::JackPortId,
                       are_connected: bool) {
        println!("JACK: ports with id {} and {} are {}",
                 port_id_a,
                 port_id_b,
                 if are_connected {
                     "connected"
                 } else {
                     "disconnected"
                 });
    }

    fn graph_reorder(&mut self, _: &j::Client) -> j::JackControl {
        println!("JACK: graph reordered");
        j::JackControl::Continue
    }

    fn xrun(&mut self, _: &j::Client) -> j::JackControl {
        println!("JACK: xrun occurred");
        j::JackControl::Continue
    }

    fn latency(&mut self, _: &j::Client, mode: j::LatencyType) {
        println!("JACK: {} latency has changed",
                 match mode {
                     j::LatencyType::Capture => "capture",
                     j::LatencyType::Playback => "playback",
                 });
    }
}

fn main() {
    // Create client
    let (client, _status) = j::Client::new("rust_jack_simple", j::client_options::NO_START_SERVER)
        .unwrap();

    // Register ports. They will be used in a callback that will be
    // called when new data is available.
    let in_a = client.register_port("rust_in_l", j::AudioInSpec::default()).unwrap();
    let in_b = client.register_port("rust_in_r", j::AudioInSpec::default()).unwrap();
    let mut out_a = client.register_port("rust_out_l", j::AudioOutSpec::default()).unwrap();
    let mut out_b = client.register_port("rust_out_r", j::AudioOutSpec::default()).unwrap();
    let process_callback = move |_: &j::Client, ps: &j::ProcessScope| -> j::JackControl {
        let mut out_a_p = j::AudioOutPort::new(&mut out_a, ps);
        let mut out_b_p = j::AudioOutPort::new(&mut out_b, ps);
        let in_a_p = j::AudioInPort::new(&in_a, ps);
        let in_b_p = j::AudioInPort::new(&in_b, ps);
        out_a_p.clone_from_slice(&in_a_p);
        out_b_p.clone_from_slice(&in_b_p);
        j::JackControl::Continue
    };
    let process = j::ClosureProcessHandler::new(process_callback);

    // Activate the client, which starts the processing.
    let active_client = j::AsyncClient::new(client, Notifications, process).unwrap();

    // Wait for user input to quit
    println!("Press enter/return to quit...");
    let mut user_input = String::new();
    io::stdin().read_line(&mut user_input).ok();

    active_client.deactivate().unwrap();
}
<commit_msg>of -> off typo<commit_after>//! Takes 2 audio inputs and outputs them to 2 audio outputs.
//! All JACK notifications are also printed out.
extern crate jack;
use jack::prelude as j;
use std::io;

struct Notifications;

impl j::NotificationHandler for Notifications {
    fn thread_init(&self, _: &j::Client) {
        println!("JACK: thread init");
    }

    fn shutdown(&mut self, status: j::ClientStatus, reason: &str) {
        println!("JACK: shutdown with status {:?} because \"{}\"",
                 status,
                 reason);
    }

    fn freewheel(&mut self, _: &j::Client, is_enabled: bool) {
        println!("JACK: freewheel mode is {}",
                 if is_enabled { "on" } else { "off" });
    }

    fn buffer_size(&mut self, _: &j::Client, sz: j::JackFrames) -> j::JackControl {
        println!("JACK: buffer size changed to {}", sz);
        j::JackControl::Continue
    }

    fn sample_rate(&mut self, _: &j::Client, srate: j::JackFrames) -> j::JackControl {
        println!("JACK: sample rate changed to {}", srate);
        j::JackControl::Continue
    }

    fn client_registration(&mut self, _: &j::Client, name: &str, is_reg: bool) {
        println!("JACK: {} client with name \"{}\"",
                 if is_reg { "registered" } else { "unregistered" },
                 name);
    }

    fn port_registration(&mut self, _: &j::Client, port_id: j::JackPortId, is_reg: bool) {
        println!("JACK: {} port with id {}",
                 if is_reg { "registered" } else { "unregistered" },
                 port_id);
    }

    fn port_rename(&mut self,
                   _: &j::Client,
                   port_id: j::JackPortId,
                   old_name: &str,
                   new_name: &str)
                   -> j::JackControl {
        println!("JACK: port with id {} renamed from {} to {}",
                 port_id,
                 old_name,
                 new_name);
        j::JackControl::Continue
    }

    fn ports_connected(&mut self,
                       _: &j::Client,
                       port_id_a: j::JackPortId,
                       port_id_b: j::JackPortId,
                       are_connected: bool) {
        println!("JACK: ports with id {} and {} are {}",
                 port_id_a,
                 port_id_b,
                 if are_connected {
                     "connected"
                 } else {
                     "disconnected"
                 });
    }

    fn graph_reorder(&mut self, _: &j::Client) -> j::JackControl {
        println!("JACK: graph reordered");
        j::JackControl::Continue
    }

    fn xrun(&mut self, _: &j::Client) -> j::JackControl {
        println!("JACK: xrun occurred");
        j::JackControl::Continue
    }

    fn latency(&mut self, _: &j::Client, mode: j::LatencyType) {
        println!("JACK: {} latency has changed",
                 match mode {
                     j::LatencyType::Capture => "capture",
                     j::LatencyType::Playback => "playback",
                 });
    }
}

fn main() {
    // Create client
    let (client, _status) = j::Client::new("rust_jack_simple", j::client_options::NO_START_SERVER)
        .unwrap();

    // Register ports. They will be used in a callback that will be
    // called when new data is available.
    let in_a = client.register_port("rust_in_l", j::AudioInSpec::default()).unwrap();
    let in_b = client.register_port("rust_in_r", j::AudioInSpec::default()).unwrap();
    let mut out_a = client.register_port("rust_out_l", j::AudioOutSpec::default()).unwrap();
    let mut out_b = client.register_port("rust_out_r", j::AudioOutSpec::default()).unwrap();
    let process_callback = move |_: &j::Client, ps: &j::ProcessScope| -> j::JackControl {
        let mut out_a_p = j::AudioOutPort::new(&mut out_a, ps);
        let mut out_b_p = j::AudioOutPort::new(&mut out_b, ps);
        let in_a_p = j::AudioInPort::new(&in_a, ps);
        let in_b_p = j::AudioInPort::new(&in_b, ps);
        out_a_p.clone_from_slice(&in_a_p);
        out_b_p.clone_from_slice(&in_b_p);
        j::JackControl::Continue
    };
    let process = j::ClosureProcessHandler::new(process_callback);

    // Activate the client, which starts the processing.
    let active_client = j::AsyncClient::new(client, Notifications, process).unwrap();

    // Wait for user input to quit
    println!("Press enter/return to quit...");
    let mut user_input = String::new();
    io::stdin().read_line(&mut user_input).ok();

    active_client.deactivate().unwrap();
}
<|endoftext|>


<commit_before>use std::sync::{Arc, Mutex};
use std::marker::PhantomData;

use rotor::{Notifier, GenericScope};

trait ReadFuture<T> {
    fn ready(&self) -> bool;
    fn take(&mut self) -> Option<T>;
}

pub struct Future<T>(Arc<Mutex<ReadFuture<T>>>);

pub struct FutureImpl<I, O, F: FnOnce(I) -> O>{
    output: Option<O>,
    convert: Option<F>,
    notifier: Notifier,
    phantom: PhantomData<*const I>,
}

impl<I, O, F:FnOnce(I) -> O> FutureImpl<I, O, F> {
    pub fn new(fun: F, notify: Notifier) -> FutureImpl<I, O, F> {
        FutureImpl {
            output: None,
            convert: Some(fun),
            notifier: notify,
            phantom: PhantomData,
        }
    }
    pub fn put(&mut self, t: O) {
        self.output = Some(t);
        self.notifier.wakeup().expect("wakeup of state machine");
    }
    pub fn convert(&mut self) -> F {
        self.convert.take().unwrap()
    }
}

impl<I, O, F:FnOnce(I) -> O> ReadFuture<O> for FutureImpl<I, O, F> {
    fn ready(&self) -> bool {
        self.output.is_some()
    }
    fn take(&mut self) -> Option<O> {
        self.output.take()
    }
}

impl<T: Sized> Future<T> {
    pub fn is_done(&self) -> bool {
        self.0.lock().expect("future can be locked").ready()
    }
    pub fn consume(self) -> Result<T, Self> {
        match self.0.lock().expect("future can be locked").take() {
            Some(x) => return Ok(x),
            None => {}
        }
        Err(self)
    }
}

pub fn new<I, O: 'static, F:FnOnce(I) -> O + 'static, S: GenericScope>(scope: &mut S, fun: F)
    -> Arc<Mutex<FutureImpl<I, O, F>>>
{
    Arc::new(Mutex::new(FutureImpl::new(fun, scope.notifier())))
}

#[cfg(test)]
mod test {
    extern crate rotor_test;
    use std::sync::{Arc, Mutex};

    use std::str::FromStr;
    use super::{new, FutureImpl, Future};

    trait ParseStr {
        fn put_str(&mut self, &str);
    }
    struct Port(Arc<Mutex<ParseStr>>);

    impl<'a, O, F: FnOnce(&str) -> O> ParseStr for FutureImpl<&'a str, O, F> {
        fn put_str(&mut self, val: &str) {
            let converted = self.convert()(val);
            self.put(converted);
        }
    }

    impl Port {
        fn put(self, val: &str) {
            self.0.lock().expect("port locked").put_str(val)
        }
    }

    #[test]
    fn test_int() {
        let mut lp = rotor_test::MockLoop::new(());
        let ref mut scope = lp.scope(1);
        let arc = new(scope, |x: &str| x.parse().unwrap());
        let future: Future<u64> = Future(arc.clone());
        let value: String = String::from("10");
        Port(arc).put(&value[..]);
        assert_eq!(future.consume().unwrap_or(9999), 10);
    }

}
<commit_msg>More enhancements to the Future interface<commit_after>use std::fmt;
use std::sync::{Arc, Mutex};
use std::marker::PhantomData;

use rotor::{Notifier, GenericScope};

trait ReadFuture<T> {
    fn ready(&self) -> bool;
    fn take(&mut self) -> Option<T>;
    /// Only for debug trait
    fn peek(&self) -> Option<&T>;
}

pub trait MakeFuture<T> {
    fn make_future(self) -> Future<T>;
}

pub trait GetNotifier {
    fn get_notifier(self) -> Notifier;
}

impl<'a, T: GenericScope> GetNotifier for &'a mut T {
    fn get_notifier(self) -> Notifier {
        self.notifier()
    }
}
impl GetNotifier for Notifier {
    fn get_notifier(self) -> Notifier {
        return self;
    }
}

pub struct Future<T>(Arc<Mutex<ReadFuture<T>>>);

pub struct FutureImpl<I, O, F: FnOnce(I) -> O>{
    output: Option<O>,
    convert: Option<F>,
    notifier: Notifier,
    phantom: PhantomData<*const I>,
}

impl<I, O, F> MakeFuture<O> for Arc<Mutex<FutureImpl<I, O, F>>>
    where I: 'static, O: 'static, F: FnOnce(I) -> O + 'static
{
    fn make_future(self) -> Future<O> {
        Future(self)
    }
}

impl<I, O, F:FnOnce(I) -> O> FutureImpl<I, O, F> {
    pub fn new(fun: F, notify: Notifier) -> FutureImpl<I, O, F> {
        FutureImpl {
            output: None,
            convert: Some(fun),
            notifier: notify,
            phantom: PhantomData,
        }
    }
    pub fn put(&mut self, t: O) {
        self.output = Some(t);
        self.notifier.wakeup().expect("wakeup of state machine");
    }
    pub fn convert(&mut self) -> F {
        self.convert.take().unwrap()
    }
}

impl<I, O, F:FnOnce(I) -> O> ReadFuture<O> for FutureImpl<I, O, F> {
    fn ready(&self) -> bool {
        self.output.is_some()
    }
    fn take(&mut self) -> Option<O> {
        self.output.take()
    }
    fn peek(&self) -> Option<&O> {
        self.output.as_ref()
    }
}

impl<T: Sized> Future<T> {
    pub fn is_done(&self) -> bool {
        self.0.lock().expect("future can be locked").ready()
    }
    pub fn consume(self) -> Result<T, Self> {
        match self.0.lock().expect("future can be locked").take() {
            Some(x) => return Ok(x),
            None => {}
        }
        Err(self)
    }
}

pub fn new<I, O, F, N>(notifier: N, fun: F)
    -> Arc<Mutex<FutureImpl<I, O, F>>>
    where O: 'static, F: FnOnce(I) -> O + 'static, N: GetNotifier
{
    Arc::new(Mutex::new(FutureImpl::new(fun, notifier.get_notifier())))
}

impl<T: fmt::Debug> fmt::Debug for Future<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.0.lock() {
            Ok(locked) => match locked.peek() {
                Some(value) => write!(fmt, "Future({:?})", value),
                None => write!(fmt, "Future(<Waiting>)"),
            },
            Err(_) => write!(fmt, "Future(<Poisoned>)"),
        }
    }
}

#[cfg(test)]
mod test {
    extern crate rotor_test;
    use std::sync::{Arc, Mutex};

    use super::{new, FutureImpl, Future, MakeFuture};

    trait ParseStr {
        fn put_str(&mut self, &str);
    }
    struct Port(Arc<Mutex<ParseStr>>);

    impl<'a, O, F: FnOnce(&str) -> O> ParseStr for FutureImpl<&'a str, O, F> {
        fn put_str(&mut self, val: &str) {
            let converted = self.convert()(val);
            self.put(converted);
        }
    }

    impl Port {
        fn put(self, val: &str) {
            self.0.lock().expect("port locked").put_str(val)
        }
    }

    #[test]
    fn test_int() {
        let mut lp = rotor_test::MockLoop::new(());
        let ref mut scope = lp.scope(1);
        let arc = new(scope, |x: &str| x.parse().unwrap());
        let future: Future<u64> = arc.clone().make_future();
        let value: String = String::from("10");
        Port(arc).put(&value[..]);
        assert_eq!(future.consume().unwrap(), 10);
    }

}
<|endoftext|>


<commit_before>use std::error::Error;
use std::path::Path;

extern crate walkdir;

use walkdir::{DirEntry, WalkDir};

fn is_not_hidden(entry: &DirEntry) -> bool {
    entry
         .file_name()
         .to_str()
         .map(|s| entry.depth() == 0 || !s.starts_with("."))
         .unwrap_or(false)
}

pub fn traverse(path: &Path) -> Result<(), Box<dyn Error>> {
    for entry in WalkDir::new(path)
            .follow_links(true)
            .into_iter()
            .filter_entry(|e| is_not_hidden(e))
            .filter_map(|e| e.ok()) {
        let f_name = entry.file_name().to_string_lossy();

        if f_name.ends_with(".rs") {
            println!("{}", entry.path().display());
        }
    }

    Ok(())
}<commit_msg>traverse now creates hidden .reqtangle dir if not exists<commit_after>use std::error::Error;
use std::path::Path;
use std::fs;

extern crate walkdir;

use walkdir::{DirEntry, WalkDir};

fn is_not_hidden(entry: &DirEntry) -> bool {
    entry
         .file_name()
         .to_str()
         .map(|s| entry.depth() == 0 || !s.starts_with("."))
         .unwrap_or(false)
}

pub fn traverse(path: &Path) -> Result<(), Box<dyn Error>> {
    if !Path::new(".reqtangle").exists() {
        fs::create_dir(".reqtangle")?;
    }

    for entry in WalkDir::new(path)
            .follow_links(true)
            .into_iter()
            .filter_entry(|e| is_not_hidden(e))
            .filter_map(|e| e.ok()) {
        let f_name = entry.file_name().to_string_lossy();

        if f_name.ends_with(".rs") {
            println!("{}", entry.path().display());
        }
    }

    Ok(())
}<|endoftext|>


<commit_before>use regex::{Captures, Regex};

const LANGUAGE_SEP_END : &'static str = "\" -->";
const LANGUAGE_BLOCK_BEGIN : &'static str = "|[<!-- language=\"";
const LANGUAGE_BLOCK_END : &'static str = "\n]|";

pub fn reformat_doc(input: &str) -> String {
    let out = code_blocks_transformation(input);
    replace_c_types(&out)
}

fn code_blocks_transformation(input: &str) -> String {
    let mut out = String::new();

    for entry in input.split(LANGUAGE_BLOCK_BEGIN) {
        if out.is_empty() {
            out.push_str(entry);
            continue;
        }
        out.push_str("```");
        let entry = get_language(entry, &mut out);
        out.push_str(&format!("{}", entry.replace(LANGUAGE_BLOCK_END, "\n```")))
    }
    out
}

fn get_language<'a>(entry: &'a str, out: &mut String) -> &'a str {
    if let Some(pos) = entry.find(LANGUAGE_SEP_END) {
        out.push_str(&entry[0..pos]);
        &entry[(pos + LANGUAGE_SEP_END.len())..]
    } else {
        out.push_str("\n");
        entry
    }
}

fn replace_c_types(entry: &str) -> String {
    if let Ok(reg) = Regex::new(r"Gtk[\w]*") {
        let mut out = vec!();

        for (num, part) in entry.split("```").into_iter().enumerate() {
            out.push(
                if num & 1 == 0 {
                    reg.replace_all(part, |caps: &Captures| {
                        match caps.at(0) {
                            Some(s) => format!("`{}`", &s[4..]),
                            None => String::new(),
                        }
                    })
                } else {
                    part.to_owned()
                }
            );
        }
        out.join("```")
    } else {
        entry.to_owned()
    }
}
<commit_msg>Global doc formatting improvement and add support for "@"<commit_after>use regex::{Captures, Regex};

const LANGUAGE_SEP_BEGIN : &'static str = "<!-- language=\"";
const LANGUAGE_SEP_END : &'static str = "\" -->";
const LANGUAGE_BLOCK_BEGIN : &'static str = "|[";
const LANGUAGE_BLOCK_END : &'static str = "\n]|";

lazy_static! {
    static ref REG : Regex = Regex::new(r"#?(G[dt]k)([\w]*)").unwrap();
    static ref REG2 : Regex = Regex::new(r"@(\w*)").unwrap();
}

pub fn reformat_doc(input: &str) -> String {
    code_blocks_transformation(input)
}

fn try_split<'a>(src: &'a str, needle: &str) -> (&'a str, Option<&'a str>) {
    match src.find(needle) {
        Some(pos) => (&src[..pos], Some(&src[pos + needle.len()..])),
        None => (src, None),
    }
}

fn code_blocks_transformation(mut input: &str) -> String {
    let mut out = String::new();

    loop {
        input = match try_split(input, LANGUAGE_BLOCK_BEGIN) {
            (before, Some(after)) => {
                out.push_str(&replace_c_types(before));
                if let (before, Some(after)) = try_split(get_language(after, &mut out),
                                                         LANGUAGE_BLOCK_END) {
                    out.push_str(before);
                    out.push_str("\n```");
                    after
                } else {
                    after
                }
            }
            (before, None) => {
                out.push_str(&replace_c_types(before));
                return out
            }
        };
    }
}

fn get_language<'a>(entry: &'a str, out: &mut String) -> &'a str {
    if let Some(pos) = entry.find(LANGUAGE_SEP_BEGIN) {
        let entry = &entry[pos + LANGUAGE_SEP_BEGIN.len()..];
        if let Some(pos) = entry.find(LANGUAGE_SEP_END) {
            out.push_str(&format!("```{}", &entry[0..pos]));
            return &entry[(pos + LANGUAGE_SEP_END.len())..]
        }
    }
    out.push_str("```");
    entry
}

fn replace_c_types(entry: &str) -> String {
    let out = &REG.replace_all(entry, |caps: &Captures| {
        format!("`{}::{}`", &caps[1].to_lowercase(), &caps[2])
    });
    REG2.replace_all(out, "`$1`")
}
<|endoftext|>


<commit_before>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.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.

use {LinkerFlavor, PanicStrategy};
use target::{Target, TargetOptions, TargetResult};

pub fn target() -> TargetResult {
    Ok(Target {
        llvm_target: "msp430-none-elf".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "16".to_string(),
        target_c_int_width: "16".to_string(),
        data_layout: "e-m:e-p:16:16-i32:16-i64:16-f32:16-f64:16-a:8-n8:16-S16".to_string(),
        arch: "msp430".to_string(),
        target_os: "none".to_string(),
        target_env: "".to_string(),
        target_vendor: "".to_string(),
        linker_flavor: LinkerFlavor::Gcc,

        options: TargetOptions {
            executables: true,

            // The LLVM backend currently can't generate object files. To
            // workaround this LLVM generates assembly files which then we feed
            // to gcc to get object files. For this reason we have a hard
            // dependency on this specific gcc.
            asm_args: vec!["-mcpu=msp430".to_string()],
            linker: "msp430-elf-gcc".to_string(),
            no_integrated_as: true,

            // There are no atomic instructions available in the MSP430
            // instruction set
            max_atomic_width: Some(0),

            // Because these devices have very little resources having an
            // unwinder is too onerous so we default to "abort" because the
            // "unwind" strategy is very rare.
            panic_strategy: PanicStrategy::Abort,

            // Similarly, one almost always never wants to use relocatable
            // code because of the extra costs it involves.
            relocation_model: "static".to_string(),

            // Right now we invoke an external assembler and this isn't
            // compatible with multiple codegen units, and plus we probably
            // don't want to invoke that many gcc instances.
            default_codegen_units: Some(1),

            .. Default::default( )
        }
    })
}
<commit_msg>[MSP430] Don't enable trap_unreachable option by default on msp.<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.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.

use {LinkerFlavor, PanicStrategy};
use target::{Target, TargetOptions, TargetResult};

pub fn target() -> TargetResult {
    Ok(Target {
        llvm_target: "msp430-none-elf".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "16".to_string(),
        target_c_int_width: "16".to_string(),
        data_layout: "e-m:e-p:16:16-i32:16-i64:16-f32:16-f64:16-a:8-n8:16-S16".to_string(),
        arch: "msp430".to_string(),
        target_os: "none".to_string(),
        target_env: "".to_string(),
        target_vendor: "".to_string(),
        linker_flavor: LinkerFlavor::Gcc,

        options: TargetOptions {
            executables: true,

            // The LLVM backend currently can't generate object files. To
            // workaround this LLVM generates assembly files which then we feed
            // to gcc to get object files. For this reason we have a hard
            // dependency on this specific gcc.
            asm_args: vec!["-mcpu=msp430".to_string()],
            linker: "msp430-elf-gcc".to_string(),
            no_integrated_as: true,

            // There are no atomic instructions available in the MSP430
            // instruction set
            max_atomic_width: Some(0),

            // Because these devices have very little resources having an
            // unwinder is too onerous so we default to "abort" because the
            // "unwind" strategy is very rare.
            panic_strategy: PanicStrategy::Abort,

            // Similarly, one almost always never wants to use relocatable
            // code because of the extra costs it involves.
            relocation_model: "static".to_string(),

            // Right now we invoke an external assembler and this isn't
            // compatible with multiple codegen units, and plus we probably
            // don't want to invoke that many gcc instances.
            default_codegen_units: Some(1),

            // Since MSP430 doesn't meaningfully support faulting on illegal
            // instructions, LLVM generates a call to abort() function instead
            // of a trap instruction. Such calls are 4 bytes long, and that is
            // too much overhead for such small target.
            trap_unreachable: false,

            .. Default::default( )
        }
    })
}
<|endoftext|>


<commit_before>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.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.

use rustc::traits::{
    Clause,
    Clauses,
    DomainGoal,
    FromEnv,
    Goal,
    ProgramClause,
    Environment,
};
use rustc::ty::{TyCtxt, Ty};
use rustc_data_structures::fx::FxHashSet;

struct ClauseVisitor<'set, 'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    round: &'set mut FxHashSet<Clause<'tcx>>,
}

impl ClauseVisitor<'set, 'a, 'tcx> {
    fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, round: &'set mut FxHashSet<Clause<'tcx>>) -> Self {
        ClauseVisitor {
            tcx,
            round,
        }
    }

    fn visit_ty(&mut self, _ty: Ty<'tcx>) {

    }

    fn visit_from_env(&mut self, from_env: FromEnv<'tcx>) {
        match from_env {
            FromEnv::Trait(predicate) => {
                self.round.extend(
                    self.tcx.program_clauses_for(predicate.def_id())
                        .iter()
                        .cloned()
                );
            }

            FromEnv::Ty(ty) => self.visit_ty(ty),
        }
    }

    fn visit_domain_goal(&mut self, domain_goal: DomainGoal<'tcx>) {
        if let DomainGoal::FromEnv(from_env) = domain_goal {
            self.visit_from_env(from_env);
        }
    }

    fn visit_goal(&mut self, goal: Goal<'tcx>) {
        match goal {
            Goal::Implies(clauses, goal) => {
                for clause in clauses {
                    self.visit_clause(*clause);
                }
                self.visit_goal(*goal);
            }

            Goal::And(goal1, goal2) => {
                self.visit_goal(*goal1);
                self.visit_goal(*goal2);
            }

            Goal::Not(goal) => self.visit_goal(*goal),
            Goal::DomainGoal(domain_goal) => self.visit_domain_goal(domain_goal),
            Goal::Quantified(_, goal) => self.visit_goal(**goal.skip_binder()),
            Goal::CannotProve => (),
        }
    }

    fn visit_program_clause(&mut self, clause: ProgramClause<'tcx>) {
        self.visit_domain_goal(clause.goal);
        for goal in clause.hypotheses {
            self.visit_goal(*goal);
        }
    }

    fn visit_clause(&mut self, clause: Clause<'tcx>) {
        match clause {
            Clause::Implies(clause) => self.visit_program_clause(clause),
            Clause::ForAll(clause) => self.visit_program_clause(*clause.skip_binder()),
        }
    }
}

crate fn program_clauses_for_env<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    environment: Environment<'tcx>,
) -> Clauses<'tcx> {
    debug!("program_clauses_for_env(environment={:?})", environment);

    let mut last_round = FxHashSet();
    {
        let mut visitor = ClauseVisitor::new(tcx, &mut last_round);
        for clause in environment.clauses {
            visitor.visit_clause(*clause);
        }
    }

    let mut closure = last_round.clone();
    let mut next_round = FxHashSet();
    while !last_round.is_empty() {
        let mut visitor = ClauseVisitor::new(tcx, &mut next_round);
        for clause in last_round {
            visitor.visit_clause(clause);
        }
        last_round = next_round.drain()
            .filter(|&clause| closure.insert(clause))
            .collect();
    }

    debug!("program_clauses_for_env: closure = {:#?}", closure);

    return tcx.mk_clauses(
        closure.into_iter()
    );
}
<commit_msg>Visit tys in `program_clauses_for_env`<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.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.

use rustc::traits::{
    Clause,
    Clauses,
    DomainGoal,
    FromEnv,
    ProgramClause,
    Environment,
};
use rustc::ty::{self, TyCtxt, Ty};
use rustc_data_structures::fx::FxHashSet;

struct ClauseVisitor<'set, 'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    round: &'set mut FxHashSet<Clause<'tcx>>,
}

impl ClauseVisitor<'set, 'a, 'tcx> {
    fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, round: &'set mut FxHashSet<Clause<'tcx>>) -> Self {
        ClauseVisitor {
            tcx,
            round,
        }
    }

    fn visit_ty(&mut self, ty: Ty<'tcx>) {
        match ty.sty {
            ty::Projection(data) => {
                self.round.extend(
                    self.tcx.program_clauses_for(data.item_def_id)
                        .iter()
                        .cloned()
                );
            }

            // forall<'a, T> { `Outlives(T, 'a) :- FromEnv(&'a T)` }
            ty::Ref(_region, _sub_ty, ..) => {
                // FIXME: we need bound tys in order to write the above rule
            }

            ty::Dynamic(..) => {
                // FIXME: trait object rules are not yet implemented
            }

            ty::Adt(def, ..) => {
                self.round.extend(
                    self.tcx.program_clauses_for(def.did)
                        .iter()
                        .cloned()
                );
            }

            ty::Foreign(def_id) |
            ty::FnDef(def_id, ..) |
            ty::Closure(def_id, ..) |
            ty::Generator(def_id, ..) |
            ty::Opaque(def_id, ..) => {
                self.round.extend(
                    self.tcx.program_clauses_for(def_id)
                        .iter()
                        .cloned()
                );
            }

            ty::Bool |
            ty::Char |
            ty::Int(..) |
            ty::Uint(..) |
            ty::Float(..) |
            ty::Str |
            ty::Array(..) |
            ty::Slice(..) |
            ty::RawPtr(..) |
            ty::FnPtr(..) |
            ty::Never |
            ty::Tuple(..) |
            ty::GeneratorWitness(..) |
            ty::UnnormalizedProjection(..) |
            ty::Param(..) |
            ty::Infer(..) |
            ty::Error => (),
        }
    }

    fn visit_from_env(&mut self, from_env: FromEnv<'tcx>) {
        match from_env {
            FromEnv::Trait(predicate) => {
                self.round.extend(
                    self.tcx.program_clauses_for(predicate.def_id())
                        .iter()
                        .cloned()
                );
            }

            FromEnv::Ty(ty) => self.visit_ty(ty),
        }
    }

    fn visit_domain_goal(&mut self, domain_goal: DomainGoal<'tcx>) {
        // The only domain goals we can find in an environment are:
        // * `DomainGoal::Holds(..)`
        // * `DomainGoal::FromEnv(..)`
        // The former do not lead to any implied bounds. So we only need
        // to visit the latter.
        if let DomainGoal::FromEnv(from_env) = domain_goal {
            self.visit_from_env(from_env);
        }
    }

    fn visit_program_clause(&mut self, clause: ProgramClause<'tcx>) {
        self.visit_domain_goal(clause.goal);
        // No need to visit `clause.hypotheses`: they are always of the form
        // `FromEnv(...)` and were visited at a previous round.
    }

    fn visit_clause(&mut self, clause: Clause<'tcx>) {
        match clause {
            Clause::Implies(clause) => self.visit_program_clause(clause),
            Clause::ForAll(clause) => self.visit_program_clause(*clause.skip_binder()),
        }
    }
}

crate fn program_clauses_for_env<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    environment: Environment<'tcx>,
) -> Clauses<'tcx> {
    debug!("program_clauses_for_env(environment={:?})", environment);

    let mut last_round = FxHashSet();
    {
        let mut visitor = ClauseVisitor::new(tcx, &mut last_round);
        for &clause in environment.clauses {
            visitor.visit_clause(clause);
        }
    }

    let mut closure = last_round.clone();
    let mut next_round = FxHashSet();
    while !last_round.is_empty() {
        let mut visitor = ClauseVisitor::new(tcx, &mut next_round);
        for clause in last_round {
            visitor.visit_clause(clause);
        }
        last_round = next_round.drain()
            .filter(|&clause| closure.insert(clause))
            .collect();
    }

    debug!("program_clauses_for_env: closure = {:#?}", closure);

    return tcx.mk_clauses(
        closure.into_iter()
    );
}
<|endoftext|>