<commit_before>use std::env;

extern crate syn;
use syn::*;

mod rust_lib;

fn has_attribute(target: MetaItem, attrs: &Vec<Attribute>) -> bool {
    return attrs
               .iter()
               .any(|ref attr| attr.style == AttrStyle::Outer && attr.value == target);
}

fn has_no_mangle(attrs: &Vec<Attribute>) -> bool {
    has_attribute(MetaItem::Word(Ident::new("no_mangle")), attrs)
}

fn wr_func_body(attrs: &Vec<Attribute>) -> String {
    if has_attribute(MetaItem::Word(Ident::new("destructor_safe")), attrs) {
        String::from("WR_DESTRUCTOR_SAFE_FUNC")
    } else {
        String::from("WR_FUNC")
    }
}

fn is_repr_c(attrs: &Vec<Attribute>) -> bool {
    let repr_args = vec![NestedMetaItem::MetaItem(MetaItem::Word(Ident::new("C")))];
    has_attribute(MetaItem::List(Ident::new("repr"), repr_args), attrs)
}

fn is_c_abi(abi: &Option<Abi>) -> bool {
    abi == &Some(Abi::Named(String::from("C")))
}

fn map_path(p: &Path) -> String {
    let l = p.segments[0].ident.to_string();
    match l.as_ref() {
        "usize" => "size_t".to_string(),
        "u8" => "uint8_t".to_string(),
        "u32" => "uint32_t".to_string(),
        "f32" => "float".to_string(),
        "c_void" => "void".to_string(),
        _ => l,
    }
}

fn map_mut_ty(mut_ty: &MutTy) -> String {
    map_ty(&mut_ty.ty)
}

fn map_ty(ty: &Ty) -> String {
    match ty {
        &Ty::Path(_, ref p) => map_path(p),
        &Ty::Ptr(ref p) => format!("{}*", map_ty(&p.ty)),
        &Ty::Rptr(_, ref mut_ty) => format!("{}*", map_mut_ty(mut_ty)),
        _ => format!("unknown {:?}", ty),
    }

}

fn map_return_type(ret: &FunctionRetTy) -> String {
    match ret {
        &FunctionRetTy::Default => "void".to_string(),
        &FunctionRetTy::Ty(ref ty) => map_ty(ty),
    }
}

fn map_pat(pat: &Pat) -> String {
    match pat {
        &Pat::Ident(_, ref ident, _) => ident.to_string(),
        _ => format!("unknown {:?}", pat),
    }

}

fn map_arg(f: &FnArg) -> String {
    match f {
        &FnArg::Captured(ref pat, ref ty) => format!("{} {}", map_ty(ty), map_pat(pat)),
        _ => "unknown".to_string(),
    }
}

fn map_field(f: &Field) -> String {
    let mut ret = String::from("  ");
    ret.push_str(&map_ty(&f.ty));
    ret.push(' ');
    ret.push_str(&f.ident.as_ref().expect("Struct fields must have idents").to_string());
    ret.push_str(";\n");
    ret
}

fn main() {
    let p = env::args().nth(1).unwrap();

    rust_lib::parse(p, &|_, items| {
        for item in items {
            match item.node {
                ItemKind::Fn(ref decl,
                             ref _unsafe,
                             ref _const,
                             ref abi,
                             ref _generic,
                             ref _block) => {
                    if has_no_mangle(&item.attrs) && is_c_abi(&abi) {
                        println!("WR_INLINE {}\n{}({})\n{};\n",
                                 map_return_type(&decl.output),
                                 item.ident,
                                 decl.inputs
                                     .iter()
                                     .map(map_arg)
                                     .collect::<Vec<_>>()
                                     .join(", "),
                                 wr_func_body(&item.attrs));
                    }
                }
                ItemKind::Struct(ref variant,
                                 ref _generics) => {
                    if is_repr_c(&item.attrs) {
                        if let &VariantData::Struct(ref fields) = variant {
                            println!("struct {} {{\n{}}};\n",
                                     item.ident,
                                     fields
                                         .iter()
                                         .map(map_field)
                                         .collect::<String>());
                        }
                    }
                }
                _ => {}
            }
        }
    });
}
<commit_msg>Convert generic structs to templates<commit_after>use std::env;

extern crate syn;
use syn::*;

mod rust_lib;

fn has_attribute(target: MetaItem, attrs: &Vec<Attribute>) -> bool {
    return attrs
               .iter()
               .any(|ref attr| attr.style == AttrStyle::Outer && attr.value == target);
}

fn has_no_mangle(attrs: &Vec<Attribute>) -> bool {
    has_attribute(MetaItem::Word(Ident::new("no_mangle")), attrs)
}

fn wr_func_body(attrs: &Vec<Attribute>) -> String {
    if has_attribute(MetaItem::Word(Ident::new("destructor_safe")), attrs) {
        String::from("WR_DESTRUCTOR_SAFE_FUNC")
    } else {
        String::from("WR_FUNC")
    }
}

fn is_repr_c(attrs: &Vec<Attribute>) -> bool {
    let repr_args = vec![NestedMetaItem::MetaItem(MetaItem::Word(Ident::new("C")))];
    has_attribute(MetaItem::List(Ident::new("repr"), repr_args), attrs)
}

fn is_c_abi(abi: &Option<Abi>) -> bool {
    abi == &Some(Abi::Named(String::from("C")))
}

fn map_path(p: &Path) -> String {
    let l = p.segments[0].ident.to_string();
    match l.as_ref() {
        "usize" => "size_t".to_string(),
        "u8" => "uint8_t".to_string(),
        "u32" => "uint32_t".to_string(),
        "f32" => "float".to_string(),
        "c_void" => "void".to_string(),
        _ => l,
    }
}

fn map_mut_ty(mut_ty: &MutTy) -> String {
    map_ty(&mut_ty.ty)
}

fn map_ty(ty: &Ty) -> String {
    match ty {
        &Ty::Path(_, ref p) => map_path(p),
        &Ty::Ptr(ref p) => format!("{}*", map_ty(&p.ty)),
        &Ty::Rptr(_, ref mut_ty) => format!("{}*", map_mut_ty(mut_ty)),
        _ => format!("unknown {:?}", ty),
    }

}

fn map_return_type(ret: &FunctionRetTy) -> String {
    match ret {
        &FunctionRetTy::Default => "void".to_string(),
        &FunctionRetTy::Ty(ref ty) => map_ty(ty),
    }
}

fn map_pat(pat: &Pat) -> String {
    match pat {
        &Pat::Ident(_, ref ident, _) => ident.to_string(),
        _ => format!("unknown {:?}", pat),
    }

}

fn map_arg(f: &FnArg) -> String {
    match f {
        &FnArg::Captured(ref pat, ref ty) => format!("{} {}", map_ty(ty), map_pat(pat)),
        _ => "unknown".to_string(),
    }
}

fn map_field(f: &Field) -> String {
    let mut ret = String::from("  ");
    ret.push_str(&map_ty(&f.ty));
    ret.push(' ');
    ret.push_str(&f.ident.as_ref().expect("Struct fields must have idents").to_string());
    ret.push_str(";\n");
    ret
}

fn map_generic_param(t: &TyParam) -> String {
    let mut ret = String::from("typename ");
    ret.push_str(&t.ident.to_string());
    ret
}

fn main() {
    let p = env::args().nth(1).unwrap();

    rust_lib::parse(p, &|_, items| {
        for item in items {
            match item.node {
                ItemKind::Fn(ref decl,
                             ref _unsafe,
                             ref _const,
                             ref abi,
                             ref _generic,
                             ref _block) => {
                    if has_no_mangle(&item.attrs) && is_c_abi(&abi) {
                        println!("WR_INLINE {}\n{}({})\n{};\n",
                                 map_return_type(&decl.output),
                                 item.ident,
                                 decl.inputs
                                     .iter()
                                     .map(map_arg)
                                     .collect::<Vec<_>>()
                                     .join(", "),
                                 wr_func_body(&item.attrs));
                    }
                }
                ItemKind::Struct(ref variant,
                                 ref generics) => {
                    if is_repr_c(&item.attrs) {
                        if !generics.ty_params.is_empty() {
                            println!("template<{}>",
                                     generics.ty_params
                                         .iter()
                                         .map(map_generic_param)
                                         .collect::<Vec<_>>()
                                         .join(", "));
                        }
                        if let &VariantData::Struct(ref fields) = variant {
                            println!("struct {} {{\n{}}};\n",
                                     item.ident,
                                     fields
                                         .iter()
                                         .map(map_field)
                                         .collect::<String>());
                        }
                    }
                }
                _ => {}
            }
        }
    });
}
<|endoftext|>


<commit_before>
extern crate clap;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;

use clap::{App, Arg, SubCommand};

mod types;
mod log;
mod descriptor;
mod command;
mod installer;
mod runner;

fn main() {
    let name = "make";
    let version = env!("CARGO_PKG_VERSION");
    let author = env!("CARGO_PKG_AUTHORS");
    let description = env!("CARGO_PKG_DESCRIPTION");

    let default_toml = "Makefile.toml";

    let mut build_file_arg = "-b, --buildFile=[FILE] 'Build toml file containing the build descriptor (default: ".to_string();
    build_file_arg.push_str(&default_toml);
    build_file_arg.push_str(" if exists)'");

    let matches = App::new("cargo")
        .subcommand(
            SubCommand::with_name(name)
                .version(version)
                .author(author)
                .about(description)
                .arg_from_usage(&build_file_arg)
                .arg_from_usage("-t, --task=[TASK NAME] 'The task name to execute (default: default)'")
                .arg(Arg::from_usage("-l, --loglevel=[LOG LEVEL] 'The log level (default: info)'").possible_values(&["verbose", "info", "error"]))
        )
        .get_matches();

    let (build_file, task, log_level) = if let Some(cmd_matches) = (cmd_matches.value_of("buildFile").unwrap_or(&default_toml), cmd_matches.value_of("task").unwrap_or("default"), cmd_matches.value_of("loglevel").unwrap_or("info"));

    let logger = log::create(log_level);

    logger.info::<()>("Using Build File: ", &[build_file], None);
    logger.info::<()>("Task: ", &[task], None);

    let config = descriptor::load(&build_file, &logger);

    runner::run(&logger, &config, &task);
}
<commit_msg>build<commit_after>
extern crate clap;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;

use clap::{App, Arg, SubCommand};

mod types;
mod log;
mod descriptor;
mod command;
mod installer;
mod runner;

fn main() {
    let name = "make";
    let version = env!("CARGO_PKG_VERSION");
    let author = env!("CARGO_PKG_AUTHORS");
    let description = env!("CARGO_PKG_DESCRIPTION");

    let default_toml = "Makefile.toml";

    let mut build_file_arg = "-b, --buildFile=[FILE] 'Build toml file containing the build descriptor (default: ".to_string();
    build_file_arg.push_str(&default_toml);
    build_file_arg.push_str(" if exists)'");

    let matches = App::new("cargo")
        .subcommand(
            SubCommand::with_name(name)
                .version(version)
                .author(author)
                .about(description)
                .arg_from_usage(&build_file_arg)
                .arg_from_usage("-t, --task=[TASK NAME] 'The task name to execute (default: default)'")
                .arg(Arg::from_usage("-l, --loglevel=[LOG LEVEL] 'The log level (default: info)'").possible_values(&["verbose", "info", "error"]))
        )
        .get_matches();

    let (build_file, task, log_level) = if let Some(cmd_matches) = matches.subcommand_matches(name) {
        (cmd_matches.value_of("buildFile").unwrap_or(&default_toml), cmd_matches.value_of("task").unwrap_or("default"), cmd_matches.value_of("loglevel").unwrap_or("info"))
    } else {
        panic!("cargo-{} not invoked via cargo.", name);
    };

    let logger = log::create(log_level);

    logger.info::<()>("Using Build File: ", &[build_file], None);
    logger.info::<()>("Task: ", &[task], None);

    let config = descriptor::load(&build_file, &logger);

    runner::run(&logger, &config, &task);
}
<|endoftext|>


<commit_before>#[macro_use] extern crate log;
extern crate env_logger;

use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::collections::HashMap;
use std::string::String;
use std::vec::Vec;
use std::path::Path;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::result;
use std::fs;
use std::sync::{Arc, Mutex};
use std::env;
use std::error;
use std::env::Args;

struct CacheError {
    reason: String
}

impl CacheError{
    pub fn with_reason( reason: String ) -> CacheError {
        return CacheError{
            reason: reason.clone()
        }
    }
}

struct CacheOperation {
    commands: Vec<char>,
    value: String
}

impl CacheOperation {
    fn new_from_string(cache_op_str: &String) -> CacheOperation {
        let mut cache_op = CacheOperation {
            commands: Vec::new(),
            value: String::new()
        };
        let mut idx = 0;
        let chars_iter = cache_op_str.chars();
        for c in chars_iter {
            idx += 1;
            if c == '$' {
                cache_op.value = String::from(&cache_op_str[idx..]);
                break;
            }
            cache_op.commands.push(c);
        }
        return cache_op;
    }
}

struct Cache {
    map_internal: HashMap<String, Vec<u8>>
}

impl Cache {
    fn new() -> Cache {
        return Cache {
            map_internal: HashMap::new()
        }
    }

    fn cache_item(&mut self, key: String, val: Vec<u8>) -> Result<(), CacheError>{
        debug!("Writing to cache: key={:?} val={:?}", key, val);
        fs::create_dir("_cache");
        let mut f: File = File::create(format!("_cache/{}", key)).unwrap();
        f.write(&val.as_slice());
        f.flush();
        self.map_internal.insert(key, val);
        return Ok(());
    }

    fn read_item(&self, key: String) -> Option<Box<Vec<u8>>> {
        let mut res: Option<Box<Vec<u8>>> = None;
        if self.map_internal.contains_key(&key) {
            let res_opt = self.map_internal.get(&key);
            match res_opt {
                Some(vec_ref) => res = Some(Box::new(vec_ref.clone())),
                None => res = None
            }
        } else {
            let mut buf: Vec<u8> = Vec::new();
            let mut f_res = match File::open(&key) {
                Err(why) => res = None,
                Ok(mut file) => {
                    file.read_to_end(&mut buf);
                    res = Some(Box::new(buf));
                }
            };
        }
        return res;
    }

    fn delete_item(&mut self, key: String) -> Result<(), CacheError>{
        if self.map_internal.contains_key(&key) {
            self.map_internal.remove(&key);
        }
        let path = format!("_cache/{}", key);
        if Path::new(&path).exists() {
            match fs::remove_file(path) {
                Ok(x) => x,
                Err(e) => return Err(CacheError::with_reason(format!("Failed to delete file for key: {}", key)))
            }
        }
        return Ok(())
    }
}

fn handle_client(mut stream: &mut TcpStream, mut cache: &Arc<Mutex<Cache>>) -> Result<(), CacheError>{
    stream.set_nodelay(true);
    let mut buf_arr: [u8; 64] = [0; 64];
    stream.read(&mut buf_arr);

    let mut size_str = String::new();
    let mut buf_size: usize = 0;
    for i in 0..64 {
        buf_size += 1;
        if buf_arr[i] == '|' as u8 {
            break;
        }
        size_str.push(buf_arr[i as usize] as char);
    }

    let upper_idx: usize = size_str.parse::<i32>().unwrap() as usize;
    let msg_buf = buf_arr;
    let mut buf_temp: Vec<u8> = msg_buf.to_vec();
    let mut buf: Vec<u8> = buf_temp.drain(buf_size..upper_idx + buf_size).collect();

    stream.flush().unwrap();

    let buf_str: String = String::from_utf8(buf).unwrap();
    if buf_str.len() > 0 {
        let cache_op: CacheOperation = CacheOperation::new_from_string(&buf_str);

        debug!("cmds = {:?}, value = {}", cache_op.commands, cache_op.value);

        if cache_op.commands.len() > 0 {
            let prim_cmd: char = cache_op.commands[0];
            return match prim_cmd {
                'W' => write_stream_str_to_cache(cache_op.value, cache),
                'R' => read_value_from_cache(cache_op.value, cache, &mut stream),
                'D' => delete_value_from_cache(cache_op.value, cache),
                _ => Err(CacheError::with_reason(format!("Invalid cache command {:?}", prim_cmd)))
            }
        }
    } else {
        panic!("Empty cache operation");
    }
    return Ok(());
}

fn read_value_from_cache(key: String, cache_mtx: &Arc<Mutex<Cache>>, stream: &mut TcpStream) -> Result<(), CacheError> {
    let cache = cache_mtx.lock().unwrap();
    let cache_opt: Option<Box<Vec<u8>>> = cache.read_item(key);
    match cache_opt {
        Some(boxed_val) => {
            let val = *boxed_val;
            debug!("Writing to stream {:?}", val);
            stream.write(&val[0..val.len()]);
            stream.flush();
            return Ok(());
        },
        None => {
            stream.write(&[65, 65, 65, 65]);
            stream.flush();
            return Err(CacheError::with_reason(String::from("Could not read from cache")));
        }
    }
}

fn write_stream_str_to_cache(stream_str: String, cache_mtx: &Arc<Mutex<Cache>>) -> Result<(), CacheError>{
    let mut key: String = String::new();
    let mut val: String = String::new();
    let mut idx = 0;
    let mut chars_iter = stream_str.chars();
    for c in chars_iter {
        idx += 1;
        if c == ':' {
            val = String::from(&stream_str[idx..]);
            break;
        }
        key.push(c);
    }
    let bytes = val.into_bytes();
    let mut cache = cache_mtx.lock().unwrap();
    return cache.cache_item(key, bytes);
}

fn delete_value_from_cache(key: String, cache_mtx: &Arc<Mutex<Cache>>) -> Result<(), CacheError>{
    let mut cache = cache_mtx.lock().unwrap();
    return cache.delete_item(key);
}

fn main() {
    env_logger::init().unwrap();

    let mut args: Args = env::args();

    let mut ip:String = String::from("127.0.0.1");
    let mut port:String = String::from("8080");

    loop{
        match args.next().as_ref() {
            Some(opt)=>{
                match opt.as_ref(){
                    "-port" => {
                        match args.next(){
                            Some(x) => port = x,
                            None => break
                        }
                    },
                    "-ip" =>{
                        match args.next(){
                            Some(x) => ip = x,
                            None => break
                        }
                    }
                    _ => continue
                }
            }
            None => break
        }
    }

    info!("Starting on {}:{}", ip, port);

    let listener: TcpListener = TcpListener::bind( format!( "{}:{}", ip, port).as_str() ).unwrap();

    let cache = Arc::new(Mutex::new(Cache::new()));

    // accept connections and process them, spawning a new thread for each one
    for stream in listener.incoming() {
        let cache: Arc<Mutex<Cache>> = cache.clone();
        match stream {
            Ok(mut stream) => {
                thread::spawn(move || {
                    info!("Incoming connection: {:?}", stream.peer_addr());
                    io::stdout().flush().unwrap();
                    loop {
                        handle_client(&mut stream, &cache);
                    }
                });
            }
            Err(e) => { error! {"Incoming connection failed"} }
        }
    }
}

<commit_msg>Work on basic client<commit_after>#[macro_use] extern crate log;
extern crate env_logger;

use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::collections::HashMap;
use std::string::String;
use std::vec::Vec;
use std::path::Path;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::result;
use std::fs;
use std::sync::{Arc, Mutex};
use std::env;
use std::error;
use std::env::Args;

enum Mode {
    NONE,
    CLIENT,
    SERVER
}

struct CacheError {
    reason: String
}

impl CacheError{
    pub fn with_reason( reason: String ) -> CacheError {
        return CacheError{
            reason: reason.clone()
        }
    }
}

struct CacheOperation {
    commands: Vec<char>,
    value: String
}

impl CacheOperation {
    fn new_from_string(cache_op_str: &String) -> CacheOperation {
        let mut cache_op = CacheOperation {
            commands: Vec::new(),
            value: String::new()
        };
        let mut idx = 0;
        let chars_iter = cache_op_str.chars();
        for c in chars_iter {
            idx += 1;
            if c == '$' {
                cache_op.value = String::from(&cache_op_str[idx..]);
                break;
            }
            cache_op.commands.push(c);
        }
        return cache_op;
    }
}

struct Cache {
    map_internal: HashMap<String, Vec<u8>>
}

impl Cache {
    fn new() -> Cache {
        return Cache {
            map_internal: HashMap::new()
        }
    }

    fn cache_item(&mut self, key: String, val: Vec<u8>) -> Result<(), CacheError>{
        debug!("Writing to cache: key={:?} val={:?}", key, val);
        fs::create_dir("_cache");
        let mut f: File = File::create(format!("_cache/{}", key)).unwrap();
        f.write(&val.as_slice());
        f.flush();
        self.map_internal.insert(key, val);
        return Ok(());
    }

    fn read_item(&self, key: String) -> Option<Box<Vec<u8>>> {
        let mut res: Option<Box<Vec<u8>>> = None;
        if self.map_internal.contains_key(&key) {
            let res_opt = self.map_internal.get(&key);
            match res_opt {
                Some(vec_ref) => res = Some(Box::new(vec_ref.clone())),
                None => res = None
            }
        } else {
            let mut buf: Vec<u8> = Vec::new();
            let mut f_res = match File::open(&key) {
                Err(why) => res = None,
                Ok(mut file) => {
                    file.read_to_end(&mut buf);
                    res = Some(Box::new(buf));
                }
            };
        }
        return res;
    }

    fn delete_item(&mut self, key: String) -> Result<(), CacheError>{
        if self.map_internal.contains_key(&key) {
            self.map_internal.remove(&key);
        }
        let path = format!("_cache/{}", key);
        if Path::new(&path).exists() {
            match fs::remove_file(path) {
                Ok(x) => x,
                Err(e) => return Err(CacheError::with_reason(format!("Failed to delete file for key: {}", key)))
            }
        }
        return Ok(())
    }
}

fn string_from_stream( mut stream: &mut TcpStream ) -> String {
    stream.set_nodelay(true);
    let mut buf_arr: [u8; 64] = [0; 64];
    stream.read(&mut buf_arr);

    let mut size_str = String::new();
    let mut buf_size: usize = 0;
    for i in 0..64 {
        buf_size += 1;
        if buf_arr[i] == '|' as u8 {
            break;
        }
        size_str.push(buf_arr[i as usize] as char);
    }

    let upper_idx: usize = size_str.parse::<i32>().unwrap() as usize;
    let msg_buf = buf_arr;
    let mut buf_temp: Vec<u8> = msg_buf.to_vec();
    let mut buf: Vec<u8> = buf_temp.drain(buf_size..upper_idx + buf_size).collect();

    stream.flush().unwrap();

    let buf_str: String = String::from_utf8(buf).unwrap();
    return buf_str;
}

fn handle_client(mut stream: &mut TcpStream, mut cache: &Arc<Mutex<Cache>>) -> Result<(), CacheError>{
    let buf_str: String = string_from_stream( stream );
    if buf_str.len() > 0 {
        let cache_op: CacheOperation = CacheOperation::new_from_string(&buf_str);

        debug!("cmds = {:?}, value = {}", cache_op.commands, cache_op.value);

        if cache_op.commands.len() > 0 {
            let prim_cmd: char = cache_op.commands[0];
            return match prim_cmd {
                'W' => write_stream_str_to_cache(cache_op.value, cache),
                'R' => read_value_from_cache(cache_op.value, cache, &mut stream),
                'D' => delete_value_from_cache(cache_op.value, cache),
                _ => Err(CacheError::with_reason(format!("Invalid cache command {:?}", prim_cmd)))
            }
        }
    } else {
        panic!("Empty cache operation");
    }
    return Ok(());
}

fn read_value_from_cache(key: String, cache_mtx: &Arc<Mutex<Cache>>, stream: &mut TcpStream) -> Result<(), CacheError> {
    let cache = cache_mtx.lock().unwrap();
    let cache_opt: Option<Box<Vec<u8>>> = cache.read_item(key);
    match cache_opt {
        Some(boxed_val) => {
            let mut val:Vec<u8> = *boxed_val;
            debug!("Writing to stream {:?}", val);
            let mut sized_val:Vec<u8> = String::from(format!("{}|", val.len())).into_bytes();
            sized_val.append(val.as_mut());
            stream.write( &sized_val.as_slice() );
            stream.flush();
            return Ok(());
        },
        None => {
            stream.write(&[65, 65, 65, 65]);
            stream.flush();
            return Err(CacheError::with_reason(String::from("Could not read from cache")));
        }
    }
}

fn write_stream_str_to_cache(stream_str: String, cache_mtx: &Arc<Mutex<Cache>>) -> Result<(), CacheError>{
    let mut key: String = String::new();
    let mut val: String = String::new();
    let mut idx = 0;
    let mut chars_iter = stream_str.chars();
    for c in chars_iter {
        idx += 1;
        if c == ':' {
            val = String::from(&stream_str[idx..]);
            break;
        }
        key.push(c);
    }
    let bytes = val.into_bytes();
    let mut cache = cache_mtx.lock().unwrap();
    return cache.cache_item(key, bytes);
}

fn delete_value_from_cache(key: String, cache_mtx: &Arc<Mutex<Cache>>) -> Result<(), CacheError>{
    let mut cache = cache_mtx.lock().unwrap();
    return cache.delete_item(key);
}

fn launch_client( ip:String, port:String ){
    info!("Connection to {}:{}", ip, port);

    match TcpStream::connect(format!("{}:{}", ip, port).as_str()){
        Ok( mut stream ) => {
            loop {
                 let stdin = io::stdin();
                 for line_res in stdin.lock().lines() {
                    let mut line:String = line_res.unwrap();
                    if line.starts_with("write "){
                        let key_val = String::from(&line["write ".len()..line.len()]);
                        let delim_idx = key_val.find(" ").unwrap();
                        let key = &key_val[0..delim_idx];
                        let val = &key_val[delim_idx + 1..key_val.len()];
                        let sized_val = String::from( format!("W${}:{}", key, val));
                        let formatted = String::from(format!("{}|{}", sized_val.len(), sized_val));
                        stream.write(formatted.as_bytes());
                        stream.flush();
                    }else if line.starts_with("read "){
                        let key = String::from(&line["read ".len()..line.len()]);
                        let cmd_val = String::from( format!("R${}", key));
                        let sized_val = String::from( format!("{}|{}", cmd_val.len(), cmd_val));
                        stream.write( String::from(sized_val).as_bytes());
                        stream.flush();
                        let val:String = string_from_stream( &mut stream );
                        println!("{}", val);
                        io::stdout().flush();
                    }else if line.starts_with("delete "){

                    }
                }
            }
        },
        Err(e) => {
            panic!("Failed to connect to server");
        }
    }

}

fn launch_server( ip:String, port:String ){

    info!("Starting on {}:{}", ip, port);

    let listener: TcpListener = TcpListener::bind( format!( "{}:{}", ip, port).as_str() ).unwrap();

    let cache = Arc::new(Mutex::new(Cache::new()));

    loop{
        // accept connections and process them, spawning a new thread for each one
        for stream in listener.incoming() {
            let cache: Arc<Mutex<Cache>> = cache.clone();
            match stream {
                Ok(mut stream) => {
                    thread::spawn(move || {
                        info!("Incoming connection: {:?}", stream.peer_addr());
                        io::stdout().flush().unwrap();
                        loop {
                            handle_client(&mut stream, &cache);
                        }
                    });
                }
                Err(e) => { error! {"Incoming connection failed"} }
            }
        }
    }
}

fn main() {
    env_logger::init().unwrap();

    let mut args: Args = env::args();

    let mut ip:String = String::from("127.0.0.1");
    let mut port:String = String::from("8080");

    let mut mode:Mode = Mode::NONE;

    loop{
        match args.next().as_ref() {
            Some(opt)=>{
                match opt.as_ref(){
                    "server" => {
                        mode = Mode::SERVER;
                    },
                    "client" => {
                        mode = Mode::CLIENT;
                    }
                    "-port" => {
                        match args.next(){
                            Some(x) => port = x,
                            None => break
                        }
                    },
                    "-ip" =>{
                        match args.next(){
                            Some(x) => ip = x,
                            None => break
                        }
                    }
                    _ => continue
                }
            }
            None => break
        }
    }

    match mode {
        Mode::CLIENT => launch_client(ip, port),
        Mode::SERVER => launch_server(ip, port),
        Mode::NONE => panic!("Mode must be specified")
    }
}

<|endoftext|>


<commit_before>use Model;
use linear_algebra::Vector;
use std::marker::PhantomData;

/// Models the target as a constant `c`
///
/// This model predicts a number. The cost function used during training decides
/// whether this number is a mean, median, or something else.
///
/// # Examples
///
/// Estimate mean
///
/// ```
/// use vikos::model::Constant;
/// use vikos::cost::LeastSquares;
/// use vikos::teacher::GradientDescentAl;
/// use vikos::learn_history;
///
/// let features = ();
/// let history = [1f64, 3.0, 4.0, 7.0, 8.0, 11.0, 29.0]; //mean is 9
///
/// let cost = LeastSquares{};
/// let mut model = Constant::new(0.0);
///
/// let teacher = GradientDescentAl{ l0 : 0.3, t : 4.0 };
/// learn_history(&teacher, &cost, &mut model, history.iter().cycle().map(|&y|((),y)).take(100));
/// println!("{}", model.c);
/// ```
#[derive(Debug, Default, RustcDecodable, RustcEncodable)]
pub struct Constant<Input> {
    /// Any prediction made by this model will have the value of `c`
    pub c: f64,
    _phantom: PhantomData<Input>,
}

impl<I> Constant<I> {
    /// Creates a new Constant from a `f64`
    pub fn new(c: f64) -> Constant<I> {
        Constant {
            c: c,
            _phantom: PhantomData::<I> {},
        }
    }
}

impl<I> Clone for Constant<I> {
    fn clone(&self) -> Self {
        Constant::new(self.c)
    }
}

impl<I> Model for Constant<I> {
    type Input = I;

    fn predict(&self, _: &I) -> f64 {
        self.c
    }

    fn num_coefficents(&self) -> usize {
        1
    }

    fn gradient(&self, coefficent: usize, _: &I) -> f64 {
        match coefficent {
            0 => 1.0,
            _ => panic!("coefficent index out of range"),
        }
    }

    fn coefficent(&mut self, coefficent: usize) -> &mut f64 {
        match coefficent {
            0 => &mut self.c,
            _ => panic!("coefficent index out of range"),
        }
    }
}

/// Models the target as `y = m * x + c`
#[derive(Debug, Clone, Default, RustcDecodable, RustcEncodable)]
pub struct Linear<V: Vector> {
    /// Slope
    pub m: V,
    /// Offset
    pub c: V::Scalar,
}

impl<V> Model for Linear<V>
    where V: Vector<Scalar = f64>
{
    type Input = V;

    fn predict(&self, input: &V) -> V::Scalar {
        self.m.dot(input) + self.c
    }

    fn num_coefficents(&self) -> usize {
        self.m.dimension() + 1
    }

    fn gradient(&self, coefficent: usize, input: &V) -> V::Scalar {

        use num::One;

        if coefficent == self.m.dimension() {
            V::Scalar::one() //c
        } else {
            input.at(coefficent)
        }
    }

    fn coefficent(&mut self, coefficent: usize) -> &mut V::Scalar {
        if coefficent == self.m.dimension() {
            &mut self.c
        } else {
            self.m.mut_at(coefficent)
        }
    }
}

/// Models target as `y = 1/(1+e^(m * x + c))`
#[derive(Debug, Clone, Default, RustcDecodable, RustcEncodable)]
pub struct Logistic<V: Vector>(Linear<V>);

impl<V> Model for Logistic<V>
    where V: Vector<Scalar = f64>
{
    type Input = V;

    fn predict(&self, input: &V) -> f64 {
        1.0 / (1.0 + self.0.predict(input).exp())
    }

    fn num_coefficents(&self) -> usize {
        self.0.num_coefficents()
    }

    fn gradient(&self, coefficent: usize, input: &V) -> f64 {
        let p = self.predict(input);
        -p * (1.0 - p) * self.0.gradient(coefficent, input)
    }

    fn coefficent(&mut self, coefficent: usize) -> &mut f64 {
        self.0.coefficent(coefficent)
    }
}
<commit_msg>added first implementation of glm model<commit_after>use Model;
use linear_algebra::Vector;
use std::marker::PhantomData;

/// Models the target as a constant `c`
///
/// This model predicts a number. The cost function used during training decides
/// whether this number is a mean, median, or something else.
///
/// # Examples
///
/// Estimate mean
///
/// ```
/// use vikos::model::Constant;
/// use vikos::cost::LeastSquares;
/// use vikos::teacher::GradientDescentAl;
/// use vikos::learn_history;
///
/// let features = ();
/// let history = [1f64, 3.0, 4.0, 7.0, 8.0, 11.0, 29.0]; //mean is 9
///
/// let cost = LeastSquares{};
/// let mut model = Constant::new(0.0);
///
/// let teacher = GradientDescentAl{ l0 : 0.3, t : 4.0 };
/// learn_history(&teacher, &cost, &mut model, history.iter().cycle().map(|&y|((),y)).take(100));
/// println!("{}", model.c);
/// ```
#[derive(Debug, Default, RustcDecodable, RustcEncodable)]
pub struct Constant<Input> {
    /// Any prediction made by this model will have the value of `c`
    pub c: f64,
    _phantom: PhantomData<Input>,
}

impl<I> Constant<I> {
    /// Creates a new Constant from a `f64`
    pub fn new(c: f64) -> Constant<I> {
        Constant {
            c: c,
            _phantom: PhantomData::<I> {},
        }
    }
}

impl<I> Clone for Constant<I> {
    fn clone(&self) -> Self {
        Constant::new(self.c)
    }
}

impl<I> Model for Constant<I> {
    type Input = I;

    fn predict(&self, _: &I) -> f64 {
        self.c
    }

    fn num_coefficents(&self) -> usize {
        1
    }

    fn gradient(&self, coefficent: usize, _: &I) -> f64 {
        match coefficent {
            0 => 1.0,
            _ => panic!("coefficent index out of range"),
        }
    }

    fn coefficent(&mut self, coefficent: usize) -> &mut f64 {
        match coefficent {
            0 => &mut self.c,
            _ => panic!("coefficent index out of range"),
        }
    }
}

/// Models the target as `y = m * x + c`
#[derive(Debug, Clone, Default, RustcDecodable, RustcEncodable)]
pub struct Linear<V: Vector> {
    /// Slope
    pub m: V,
    /// Offset
    pub c: V::Scalar,
}

impl<V> Model for Linear<V>
    where V: Vector<Scalar = f64>
{
    type Input = V;

    fn predict(&self, input: &V) -> V::Scalar {
        self.m.dot(input) + self.c
    }

    fn num_coefficents(&self) -> usize {
        self.m.dimension() + 1
    }

    fn gradient(&self, coefficent: usize, input: &V) -> V::Scalar {

        use num::One;

        if coefficent == self.m.dimension() {
            V::Scalar::one() //c
        } else {
            input.at(coefficent)
        }
    }

    fn coefficent(&mut self, coefficent: usize) -> &mut V::Scalar {
        if coefficent == self.m.dimension() {
            &mut self.c
        } else {
            self.m.mut_at(coefficent)
        }
    }
}

/// Models target as `y = 1/(1+e^(m * x + c))`
#[derive(Debug, Clone, Default, RustcDecodable, RustcEncodable)]
pub struct Logistic<V: Vector>(Linear<V>);

impl<V> Model for Logistic<V>
    where V: Vector<Scalar = f64>
{
    type Input = V;

    fn predict(&self, input: &V) -> f64 {
        1.0 / (1.0 + self.0.predict(input).exp())
    }

    fn num_coefficents(&self) -> usize {
        self.0.num_coefficents()
    }

    fn gradient(&self, coefficent: usize, input: &V) -> f64 {
        let p = self.predict(input);
        -p * (1.0 - p) * self.0.gradient(coefficent, input)
    }

    fn coefficent(&mut self, coefficent: usize) -> &mut f64 {
        self.0.coefficent(coefficent)
    }
}

#[derive(Clone)]
pub struct GLM<F,Df>{
    pub linear : Linear<f64>,
    g_inv : F,
    g_invderivate : Df,
}

impl<F,Df> Model for GLM<F,Df> where F : Fn (f64) -> f64,
 Df : Fn (f64) -> f64, F : Clone, Df : Clone
{
    type Input = f64;

    fn predict(&self, input: &f64) -> f64 {
        let f = &self.g_inv;
        f(self.linear.predict(input))
    }

    fn num_coefficents(&self) -> usize {
        self.linear.num_coefficents()
    }

    fn gradient(&self, coefficent: usize, input: &f64) -> f64 {
        let f = &self.g_invderivate;
        f(self.linear.predict(input))
    }

    fn coefficent(&mut self, coefficent: usize) -> &mut f64 {
        self.linear.coefficent(coefficent)
    }
}<|endoftext|>


<commit_before>//*****************************
// Output to MELO format

extern crate classreader;
use std::io::prelude::*;
use std::fs::File;
use codecity::{MusicMeta, MeasureMeta};

const TONES: &'static [&'static str] = &["C", "D", "E", "F", "G", "a", "b", "c", "d", "e", "f", "g", "a'", "b'", "c'", "d'", "e'", "f'", "g'"];

pub fn write_to_file(path: &String, music: &Vec<MusicMeta>) {
    let mut file = File::create(path).unwrap();

    write!(file, "tempo: 200\n\nvoice Right {{ channel: 2 }}\nvoice Left {{ channel: 1, octave: -1 }}\n\n").unwrap();

    // Right hand
    write!(file, "play Right\n{{\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_measure(&mut file, m);
        }
    }
    write!(file, "\n}}\n\n").unwrap();

    // Left hand
    write!(file, "play Left\n{{\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_chord(&mut file, m, 0);
        }
    }
    write!(file, "\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_chord(&mut file, m, 1);
        }
    }
    write!(file, "\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_chord(&mut file, m, 2);
        }
    }
    write!(file, "\n}}\n\n").unwrap();
}

fn render_measure(file: &mut File, m: &MeasureMeta) {
    let tone_count = get_tone_count(m.lines);
    let base = get_base(m.size);
    for x in 0..tone_count {
        write!(file, "{} ", get_tone(base, m.complexity, x)).unwrap();
    }
    if tone_count > 0 {
        write!(file, "|").unwrap();
    }
}

fn render_chord(file: &mut File, m: &MeasureMeta, finger: u16) {
    let tone_count = get_tone_count(m.lines);
    let base = get_base(m.size);
    if tone_count > 0 {
        write!(file, "{} |", get_tone(base, m.complexity, finger)).unwrap();
    }
}

fn get_tone_count(c: u16) -> u16 {
    match c / 4 {
        0...8 => c/4,
        _      => 8
    }
}

fn get_base(c: usize) -> usize {
    match c/2 {
        0  ... 10  => c,
        11 ... 20  => 10 + (c - 10)/2,
        21 ... 40  => 15 + (c - 20)/4,
        41 ... 80  => 20 + (c - 40)/8,
        81 ... 160 => 30 + (c - 80)/16,
        _ => 18
    }
}

fn get_complexity_shift(complexity: u16) -> u16 {
    match complexity {
        0  ...  2 => 2,
        3  ...  4 => 3,
        _         => 3 + complexity / 5
    }
}

fn get_tone(base: usize, complexity: u16, offset: u16) -> &'static str {
    let i = base as u16 + (offset % 3)*get_complexity_shift(complexity);
    TONES[(i % 19) as usize]
}

//*****************************
// Unit tests
<commit_msg>Some more changes<commit_after>//*****************************
// Output to MELO format

extern crate classreader;
use std::io::prelude::*;
use std::fs::File;
use codecity::{MusicMeta, MeasureMeta};

const TONES: &'static [&'static str] = &["C", "D", "E", "F", "G", "a", "b", "c", "d", "e", "f", "g", "a'", "b'", "c'", "d'", "e'", "f'", "g'"];

pub fn write_to_file(path: &String, music: &Vec<MusicMeta>) {
    let mut file = File::create(path).unwrap();

    write!(file, "tempo: 200\n\nvoice Right {{ channel: 2 }}\nvoice Left {{ channel: 1, octave: -1, volume: 80 }}\n\n").unwrap();

    // Right hand
    write!(file, "play Right\n{{\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_measure(&mut file, m);
        }
    }
    write!(file, "\n}}\n\n").unwrap();

    // Left hand
    write!(file, "play Left\n{{\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_chord(&mut file, m, 0);
        }
    }
    write!(file, "\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_chord(&mut file, m, get_complexity_shift(m.complexity));
        }
    }
    write!(file, "\n:|").unwrap();
    for c in music {
        for m in c.methods() {
            render_chord(&mut file, m, get_complexity_shift(m.complexity) + 1);
        }
    }
    write!(file, "\n}}\n\n").unwrap();
}

fn render_measure(file: &mut File, m: &MeasureMeta) {
    let tone_count = get_tone_count(m.lines);
    let base = get_base(m.size);
    for x in 0..tone_count {
        write!(file, "{} ", get_tone(base, m.complexity, x)).unwrap();
    }
    if tone_count > 0 {
        write!(file, "|").unwrap();
    }
}

fn render_chord(file: &mut File, m: &MeasureMeta, finger: u16) {
    let tone_count = get_tone_count(m.lines);
    let base = get_base(m.size);
    if tone_count > 0 {
        write!(file, "{} |", get_tone(base, m.complexity, finger)).unwrap();
    }
}

fn get_tone_count(c: u16) -> u16 {
    match c / 8 {
        0...8 => c/8,
        _      => 8
    }
}

fn get_base(c: usize) -> usize {
    match c/2 {
        0  ... 10  => c,
        11 ... 20  => 10 + (c - 10)/2,
        21 ... 40  => 15 + (c - 20)/4,
        41 ... 80  => 20 + (c - 40)/8,
        81 ... 160 => 30 + (c - 80)/16,
        _ => 18
    }
}

fn get_complexity_shift(complexity: u16) -> u16 {
    match complexity {
        0  ...  2 => 2,
        3  ...  4 => 3,
        _         => 4
    }
}

fn get_tone(base: usize, complexity: u16, offset: u16) -> &'static str {
    let i = base as u16 + (offset % get_complexity_shift(complexity));
    TONES[(i % 19) as usize]
}

//*****************************
// Unit tests
<|endoftext|>


<commit_before>use num::{Signed, Unsigned};
use approx::Approx;

#[inline(always)]
pub fn inverse<'a, 'b, T: Signed>(out: &'a mut [T; 2], a: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = -a[0];
    out[1] = -a[1];
    out
}
#[test]
fn test_inverse() {
    let mut v = [0, 0];
    inverse(&mut v, &[1, 1]);
    assert!(v[0] == -1);
    assert!(v[1] == -1);
}

#[inline(always)]
pub fn lerp<'a, 'b, T: Unsigned, N: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], b: &'b [T; 2], t: N) -> &'a mut [T; 2] {
    let t_f64 = t.to_f64();
    out[0] = T::from_f64((a[0] + (b[0] - a[0])).to_f64() * t_f64);
    out[1] = T::from_f64((a[1] + (b[1] - a[1])).to_f64() * t_f64);
    out
}
#[test]
fn test_lerp() {
    let mut v = [0, 0];
    lerp(&mut v, &[0, 0], &[2, 2], 0.5);
    assert_eq!(v[0], 1);
    assert_eq!(v[1], 1);
}

#[inline(always)]
pub fn perp_l<'a, 'b, T: Signed>(out: &'a mut [T; 2], a: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = a[1];
    out[1] = -a[0];
    out
}
#[test]
fn test_perp_l() {
    let mut v = [0, 0];
    perp_l(&mut v, &[1, 1]);
    assert!(v[0] == 1);
    assert!(v[1] == -1);
}

#[inline(always)]
pub fn perp_r<'a, 'b, T: Signed>(out: &'a mut [T; 2], a: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = -a[1];
    out[1] = a[0];
    out
}
#[test]
fn test_perp_r() {
    let mut v = [0, 0];
    perp_r(&mut v, &[1, 1]);
    assert!(v[0] == -1);
    assert!(v[1] == 1);
}

#[inline(always)]
pub fn min<'a, 'b, T: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], b: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = if b[0] < a[0] {b[0]} else {a[0]};
    out[1] = if b[1] < a[1] {b[1]} else {a[1]};
    out
}
#[test]
fn test_min() {
    let mut v = [0, 0];
    min(&mut v, &[1, 0], &[0, 1]);
    assert!(v == [0, 0]);
}

#[inline(always)]
pub fn max<'a, 'b, T: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], b: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = if b[0] > a[0] {b[0]} else {a[0]};
    out[1] = if b[1] > a[1] {b[1]} else {a[1]};
    out
}
#[test]
fn test_max() {
    let mut v = [0, 0];
    max(&mut v, &[1, 0], &[0, 1]);
    assert!(v == [1, 1]);
}

#[inline(always)]
pub fn clamp<'a, 'b, T: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], min: &'b [T; 2], max: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = if a[0] < min[0] {min[0]} else if a[0] > max[0] {max[0]} else {a[0]};
    out[1] = if a[1] < min[1] {min[1]} else if a[1] > max[1] {max[1]} else {a[1]};
    out
}
#[test]
fn test_clamp() {
    let mut v = [0, 0];
    clamp(&mut v, &[2, 2], &[0, 0], &[1, 1]);
    assert!(v == [1, 1]);
}

#[inline(always)]
pub fn eq<'a, T: Unsigned>(a: &'a [T; 2], b: &'a [T; 2]) -> bool {
    !ne(a, b)
}
#[test]
fn test_eq() {
    assert_eq!(eq(&[1f32, 1f32], &[1f32, 1f32]), true);
    assert_eq!(eq(&[0f32, 0f32], &[1f32, 1f32]), false);
}

#[inline(always)]
pub fn ne<'a, T: Unsigned>(a: &'a [T; 2], b: &'a [T; 2]) -> bool {
    !a[0].approx_eq(b[0]) ||
    !a[1].approx_eq(b[1])
}
#[test]
fn test_ne() {
    assert_eq!(ne(&[1f32, 1f32], &[1f32, 1f32]), false);
    assert_eq!(ne(&[0f32, 0f32], &[1f32, 1f32]), true);
}
<commit_msg>clean up<commit_after>use num::{Signed, Unsigned};
use approx::Approx;

#[inline(always)]
pub fn inverse<'a, 'b, T: Signed>(out: &'a mut [T; 2], a: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = -a[0];
    out[1] = -a[1];
    out
}
#[test]
fn test_inverse() {
    let mut v = [0, 0];
    inverse(&mut v, &[1, 1]);
    assert!(v[0] == -1);
    assert!(v[1] == -1);
}

#[inline(always)]
pub fn lerp<'a, 'b, T: Unsigned, N: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], b: &'b [T; 2], t: N) -> &'a mut [T; 2] {
    let t_f64 = t.to_f64();
    out[0] = T::from_f64((a[0] + (b[0] - a[0])).to_f64() * t_f64);
    out[1] = T::from_f64((a[1] + (b[1] - a[1])).to_f64() * t_f64);
    out
}
#[test]
fn test_lerp() {
    let mut v = [0, 0];
    lerp(&mut v, &[0, 0], &[2, 2], 0.5);
    assert_eq!(v[0], 1);
    assert_eq!(v[1], 1);
}

#[inline(always)]
pub fn perp_l<'a, 'b, T: Signed>(out: &'a mut [T; 2], a: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = a[1];
    out[1] = -a[0];
    out
}
#[test]
fn test_perp_l() {
    let mut v = [0, 0];
    perp_l(&mut v, &[1, 1]);
    assert!(v[0] == 1);
    assert!(v[1] == -1);
}

#[inline(always)]
pub fn perp_r<'a, 'b, T: Signed>(out: &'a mut [T; 2], a: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = -a[1];
    out[1] = a[0];
    out
}
#[test]
fn test_perp_r() {
    let mut v = [0, 0];
    perp_r(&mut v, &[1, 1]);
    assert!(v[0] == -1);
    assert!(v[1] == 1);
}

#[inline(always)]
pub fn min<'a, 'b, T: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], b: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = if b[0] < a[0] {b[0]} else {a[0]};
    out[1] = if b[1] < a[1] {b[1]} else {a[1]};
    out
}
#[test]
fn test_min() {
    let mut v = [0, 0];
    min(&mut v, &[1, 0], &[0, 1]);
    assert!(v == [0, 0]);
}

#[inline(always)]
pub fn max<'a, 'b, T: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], b: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = if b[0] > a[0] {b[0]} else {a[0]};
    out[1] = if b[1] > a[1] {b[1]} else {a[1]};
    out
}
#[test]
fn test_max() {
    let mut v = [0, 0];
    max(&mut v, &[1, 0], &[0, 1]);
    assert!(v == [1, 1]);
}

#[inline(always)]
pub fn clamp<'a, 'b, T: Unsigned>(out: &'a mut [T; 2], a: &'b [T; 2], min: &'b [T; 2], max: &'b [T; 2]) -> &'a mut [T; 2] {
    out[0] = if a[0] < min[0] {min[0]} else if a[0] > max[0] {max[0]} else {a[0]};
    out[1] = if a[1] < min[1] {min[1]} else if a[1] > max[1] {max[1]} else {a[1]};
    out
}
#[test]
fn test_clamp() {
    let mut v = [0, 0];
    clamp(&mut v, &[2, 2], &[0, 0], &[1, 1]);
    assert!(v == [1, 1]);
}

#[inline(always)]
pub fn eq<'a, T: Unsigned>(a: &'a [T; 2], b: &'a [T; 2]) -> bool {
    !ne(a, b)
}
#[test]
fn test_eq() {
    assert_eq!(eq(&[1f32, 1f32], &[1f32, 1f32]), true);
    assert_eq!(eq(&[0f32, 0f32], &[1f32, 1f32]), false);
}

#[inline(always)]
pub fn ne<'a, T: Unsigned>(a: &'a [T; 2], b: &'a [T; 2]) -> bool {
    !Approx::approx_eq(a[0], b[0]) ||
    !Approx::approx_eq(a[1], b[1])
}
#[test]
fn test_ne() {
    assert_eq!(ne(&[1f32, 1f32], &[1f32, 1f32]), false);
    assert_eq!(ne(&[0f32, 0f32], &[1f32, 1f32]), true);
}
<|endoftext|>


<commit_before>use super::{child_properties, function, general, properties, signal, trait_impls, trampoline};
use crate::{
    analysis::{self, rust_type::rust_type},
    case::CaseExt,
    codegen::general::{version_condition, version_condition_string},
    env::Env,
    library, nameutil,
};
use std::io::{Result, Write};

pub fn generate(
    w: &mut dyn Write,
    env: &Env,
    analysis: &analysis::object::Info,
    generate_display_trait: bool,
) -> Result<()> {
    general::start_comments(w, &env.config)?;
    general::uses(w, env, &analysis.imports)?;

    general::define_object_type(
        w,
        env,
        &analysis.name,
        &analysis.c_type,
        &analysis.c_class_type.as_ref().map(|s| &s[..]),
        &analysis.rust_class_type.as_ref().map(|s| &s[..]),
        &analysis.get_type,
        analysis.is_interface,
        &analysis.supertypes,
    )?;

    if need_generate_inherent(analysis) {
        writeln!(w)?;
        write!(w, "impl {} {{", analysis.name)?;
        for func_analysis in &analysis.constructors() {
            function::generate(w, env, func_analysis, false, false, 1)?;
        }

        if !need_generate_trait(analysis) {
            for func_analysis in &analysis.methods() {
                function::generate(w, env, func_analysis, false, false, 1)?;
            }

            for property in &analysis.properties {
                properties::generate(w, env, property, false, false, 1)?;
            }

            for child_property in &analysis.child_properties {
                child_properties::generate(w, env, child_property, false, false, 1)?;
            }
        }

        for func_analysis in &analysis.functions() {
            function::generate(w, env, func_analysis, false, false, 1)?;
        }

        if !need_generate_trait(analysis) {
            for signal_analysis in analysis
                .signals
                .iter()
                .chain(analysis.notify_signals.iter())
            {
                signal::generate(
                    w,
                    env,
                    signal_analysis,
                    &analysis.trampolines,
                    false,
                    false,
                    1,
                )?;
            }
        }

        writeln!(w, "}}")?;

        general::declare_default_from_new(w, env, &analysis.name, &analysis.functions)?;
    }

    trait_impls::generate(
        w,
        &analysis.name,
        &analysis.functions,
        &analysis.specials,
        if need_generate_trait(analysis) {
            Some(&analysis.trait_name)
        } else {
            None
        },
    )?;

    if analysis.concurrency != library::Concurrency::None {
        writeln!(w)?;
    }

    // TODO: include parent properties.
    if !analysis.builder_properties.is_empty() {
        generate_builder(w, env, analysis)?;
    }

    match analysis.concurrency {
        library::Concurrency::Send | library::Concurrency::SendSync => {
            writeln!(w, "unsafe impl Send for {} {{}}", analysis.name)?;
        }
        library::Concurrency::SendUnique => {
            if env.namespaces.is_glib_crate {
                writeln!(w, "unsafe impl ::SendUnique for {} {{", analysis.name)?;
            } else {
                writeln!(w, "unsafe impl glib::SendUnique for {} {{", analysis.name)?;
            }

            writeln!(w, "    fn is_unique(&self) -> bool {{")?;
            writeln!(w, "        self.ref_count() == 1")?;
            writeln!(w, "    }}")?;

            writeln!(w, "}}")?;
        }
        _ => (),
    }

    if let library::Concurrency::SendSync = analysis.concurrency {
        writeln!(w, "unsafe impl Sync for {} {{}}", analysis.name)?;
    }

    if !analysis.final_type {
        writeln!(w)?;
        writeln!(
            w,
            "pub const NONE_{}: Option<&{}> = None;",
            analysis.name.to_snake().to_uppercase(),
            analysis.name
        )?;
    }

    if need_generate_trait(analysis) {
        writeln!(w)?;
        generate_trait(w, env, analysis)?;
    }

    if !analysis.trampolines.is_empty() {
        for trampoline in &analysis.trampolines {
            trampoline::generate(
                w,
                env,
                trampoline,
                need_generate_trait(analysis),
                &analysis.name,
            )?;
        }
    }

    if generate_display_trait {
        writeln!(w, "\nimpl fmt::Display for {} {{", analysis.name,)?;
        // Generate Display trait implementation.
        writeln!(
            w,
            "\tfn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{\n\
             \t\twrite!(f, \"{}\")\n\
             \t}}\n\
             }}",
            analysis.name
        )?;
    }

    Ok(())
}

// TODO: instead create a Vec<> inside the Builder instead of Options.
fn generate_builder(w: &mut dyn Write, env: &Env, analysis: &analysis::object::Info) -> Result<()> {
    let mut methods = vec![];
    let mut properties = vec![];
    writeln!(
        w,
        "#[cfg(any(feature = \"builders\", feature = \"dox\"))]
pub struct {}Builder {{",
        analysis.name
    )?;
    for property in &analysis.builder_properties {
        match rust_type(env, property.typ) {
            Ok(type_string) => {
                let type_string = match type_string.as_str() {
                    "GString" => "String",
                    "Vec<GString>" => "Vec<String>",
                    typ => typ,
                };
                let (param_type, conversion) = match type_string {
                    "String" => ("&str", ".to_string()"),
                    typ => (typ, ""),
                };
                let name = nameutil::mangle_keywords(nameutil::signal_to_snake(&property.name));
                let version_condition_string =
                    version_condition_string(env, property.version, false, 1);
                if let Some(ref version_condition_string) = version_condition_string {
                    writeln!(w, "{}", version_condition_string)?;
                }
                writeln!(w, "    {}: Option<{}>,", name, type_string)?;
                let prefix = version_condition_string
                    .map(|version| format!("{}\n", version))
                    .unwrap_or_default();
                methods.push(format!(
                    "\n{prefix}    pub fn {name}(mut self, {name}: {param_type}) -> Self {{
        self.{name} = Some({name}{conversion});
        self
    }}",
                    prefix = prefix,
                    param_type = param_type,
                    name = name,
                    conversion = conversion
                ));
                properties.push(property);
            }
            Err(_) => writeln!(w, "    //{}: /*Unknown type*/,", property.name)?,
        }
    }
    writeln!(
        w,
        "}}

#[cfg(any(feature = \"builders\", feature = \"dox\"))]
impl {}Builder {{
    pub fn new() -> Self {{
        Self {{",
        analysis.name
    )?;
    for property in &properties {
        version_condition(w, env, property.version, false, 3)?;
        let name = nameutil::mangle_keywords(nameutil::signal_to_snake(&property.name));
        writeln!(w, "            {}: None,", name)?;
    }
    writeln!(
        w,
        "        }}
    }}

    pub fn build(self) -> {} {{
        let mut properties: Vec<(&str, &dyn ToValue)> = vec![];",
        analysis.name
    )?;
    for property in &properties {
        let name = nameutil::mangle_keywords(nameutil::signal_to_snake(&property.name));
        let version_condition_string = version_condition_string(env, property.version, false, 2);
        let condition_tabs = if version_condition_string.is_some() {
            "\t"
        } else {
            ""
        };
        if let Some(ref version_condition_string) = version_condition_string {
            writeln!(w, "{}", version_condition_string)?;
            writeln!(w, "        {{")?;
        }
        writeln!(
            w,
            "{tabs}        if let Some(ref {field}) = self.{field} {{
{tabs}            properties.push((\"{name}\", {field}));
{tabs}        }}",
            name = property.name,
            field = name,
            tabs = condition_tabs
        )?;
        if version_condition_string.is_some() {
            writeln!(w, "        }}")?;
        }
    }
    writeln!(w,
"        crate::Object::new({}::static_type(), &properties).expect(\"object new\").downcast().expect(\"downcast\")
    }}", analysis.name)?;
    for method in methods {
        writeln!(w, "{}", method)?;
    }
    writeln!(w, "}}")
}

fn generate_trait(w: &mut dyn Write, env: &Env, analysis: &analysis::object::Info) -> Result<()> {
    write!(w, "pub trait {}: 'static {{", analysis.trait_name)?;

    for func_analysis in &analysis.methods() {
        function::generate(w, env, func_analysis, true, true, 1)?;
    }
    for property in &analysis.properties {
        properties::generate(w, env, property, true, true, 1)?;
    }
    for child_property in &analysis.child_properties {
        child_properties::generate(w, env, child_property, true, true, 1)?;
    }
    for signal_analysis in analysis
        .signals
        .iter()
        .chain(analysis.notify_signals.iter())
    {
        signal::generate(
            w,
            env,
            signal_analysis,
            &analysis.trampolines,
            true,
            true,
            1,
        )?;
    }
    writeln!(w, "}}")?;

    writeln!(w)?;
    write!(
        w,
        "impl<O: IsA<{}>> {} for O {{",
        analysis.name, analysis.trait_name,
    )?;

    for func_analysis in &analysis.methods() {
        function::generate(w, env, func_analysis, true, false, 1)?;
    }
    for property in &analysis.properties {
        properties::generate(w, env, property, true, false, 1)?;
    }
    for child_property in &analysis.child_properties {
        child_properties::generate(w, env, child_property, true, false, 1)?;
    }
    for signal_analysis in analysis
        .signals
        .iter()
        .chain(analysis.notify_signals.iter())
    {
        signal::generate(
            w,
            env,
            signal_analysis,
            &analysis.trampolines,
            true,
            false,
            1,
        )?;
    }
    writeln!(w, "}}")?;

    Ok(())
}

fn need_generate_inherent(analysis: &analysis::object::Info) -> bool {
    analysis.has_constructors || analysis.has_functions || !need_generate_trait(analysis)
}

fn need_generate_trait(analysis: &analysis::object::Info) -> bool {
    analysis.generate_trait
}

pub fn generate_reexports(
    env: &Env,
    analysis: &analysis::object::Info,
    module_name: &str,
    contents: &mut Vec<String>,
    traits: &mut Vec<String>,
) {
    let mut cfgs: Vec<String> = Vec::new();
    if let Some(cfg) = general::cfg_condition_string(&analysis.cfg_condition, false, 0) {
        cfgs.push(cfg);
    }
    if let Some(cfg) = general::version_condition_string(env, analysis.version, false, 0) {
        cfgs.push(cfg);
    }
    contents.push("".to_owned());
    contents.extend_from_slice(&cfgs);
    contents.push(format!("mod {};", module_name));
    contents.extend_from_slice(&cfgs);

    let none_type = if !analysis.final_type {
        format!(", NONE_{}", analysis.name.to_snake().to_uppercase())
    } else {
        String::new()
    };

    if let Some(ref class_name) = analysis.rust_class_type {
        contents.push(format!(
            "pub use self::{}::{{{}, {}{}}};",
            module_name, analysis.name, class_name, none_type
        ));
    } else {
        contents.push(format!(
            "pub use self::{}::{{{}{}}};",
            module_name, analysis.name, none_type
        ));
    }
    if need_generate_trait(analysis) {
        contents.extend_from_slice(&cfgs);
        contents.push(format!(
            "pub use self::{}::{};",
            module_name, analysis.trait_name
        ));
        for cfg in &cfgs {
            traits.push(format!("\t{}", cfg));
        }
        traits.push(format!("\tpub use super::{};", analysis.trait_name));
    }

    if !analysis.builder_properties.is_empty() {
        contents.extend_from_slice(&cfgs);
        contents.push(format!(
            "#[cfg(any(feature = \"builders\", feature = \"dox\"))]
pub use self::{}::{}Builder;",
            module_name, analysis.name
        ));
    }
}
<commit_msg>Fix glib::Object::new call<commit_after>use super::{child_properties, function, general, properties, signal, trait_impls, trampoline};
use crate::{
    analysis::{self, rust_type::rust_type},
    case::CaseExt,
    codegen::general::{version_condition, version_condition_string},
    env::Env,
    library, nameutil,
};
use std::io::{Result, Write};

pub fn generate(
    w: &mut dyn Write,
    env: &Env,
    analysis: &analysis::object::Info,
    generate_display_trait: bool,
) -> Result<()> {
    general::start_comments(w, &env.config)?;
    general::uses(w, env, &analysis.imports)?;

    general::define_object_type(
        w,
        env,
        &analysis.name,
        &analysis.c_type,
        &analysis.c_class_type.as_ref().map(|s| &s[..]),
        &analysis.rust_class_type.as_ref().map(|s| &s[..]),
        &analysis.get_type,
        analysis.is_interface,
        &analysis.supertypes,
    )?;

    if need_generate_inherent(analysis) {
        writeln!(w)?;
        write!(w, "impl {} {{", analysis.name)?;
        for func_analysis in &analysis.constructors() {
            function::generate(w, env, func_analysis, false, false, 1)?;
        }

        if !need_generate_trait(analysis) {
            for func_analysis in &analysis.methods() {
                function::generate(w, env, func_analysis, false, false, 1)?;
            }

            for property in &analysis.properties {
                properties::generate(w, env, property, false, false, 1)?;
            }

            for child_property in &analysis.child_properties {
                child_properties::generate(w, env, child_property, false, false, 1)?;
            }
        }

        for func_analysis in &analysis.functions() {
            function::generate(w, env, func_analysis, false, false, 1)?;
        }

        if !need_generate_trait(analysis) {
            for signal_analysis in analysis
                .signals
                .iter()
                .chain(analysis.notify_signals.iter())
            {
                signal::generate(
                    w,
                    env,
                    signal_analysis,
                    &analysis.trampolines,
                    false,
                    false,
                    1,
                )?;
            }
        }

        writeln!(w, "}}")?;

        general::declare_default_from_new(w, env, &analysis.name, &analysis.functions)?;
    }

    trait_impls::generate(
        w,
        &analysis.name,
        &analysis.functions,
        &analysis.specials,
        if need_generate_trait(analysis) {
            Some(&analysis.trait_name)
        } else {
            None
        },
    )?;

    if analysis.concurrency != library::Concurrency::None {
        writeln!(w)?;
    }

    // TODO: include parent properties.
    if !analysis.builder_properties.is_empty() {
        generate_builder(w, env, analysis)?;
    }

    match analysis.concurrency {
        library::Concurrency::Send | library::Concurrency::SendSync => {
            writeln!(w, "unsafe impl Send for {} {{}}", analysis.name)?;
        }
        library::Concurrency::SendUnique => {
            if env.namespaces.is_glib_crate {
                writeln!(w, "unsafe impl ::SendUnique for {} {{", analysis.name)?;
            } else {
                writeln!(w, "unsafe impl glib::SendUnique for {} {{", analysis.name)?;
            }

            writeln!(w, "    fn is_unique(&self) -> bool {{")?;
            writeln!(w, "        self.ref_count() == 1")?;
            writeln!(w, "    }}")?;

            writeln!(w, "}}")?;
        }
        _ => (),
    }

    if let library::Concurrency::SendSync = analysis.concurrency {
        writeln!(w, "unsafe impl Sync for {} {{}}", analysis.name)?;
    }

    if !analysis.final_type {
        writeln!(w)?;
        writeln!(
            w,
            "pub const NONE_{}: Option<&{}> = None;",
            analysis.name.to_snake().to_uppercase(),
            analysis.name
        )?;
    }

    if need_generate_trait(analysis) {
        writeln!(w)?;
        generate_trait(w, env, analysis)?;
    }

    if !analysis.trampolines.is_empty() {
        for trampoline in &analysis.trampolines {
            trampoline::generate(
                w,
                env,
                trampoline,
                need_generate_trait(analysis),
                &analysis.name,
            )?;
        }
    }

    if generate_display_trait {
        writeln!(w, "\nimpl fmt::Display for {} {{", analysis.name,)?;
        // Generate Display trait implementation.
        writeln!(
            w,
            "\tfn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{\n\
             \t\twrite!(f, \"{}\")\n\
             \t}}\n\
             }}",
            analysis.name
        )?;
    }

    Ok(())
}

// TODO: instead create a Vec<> inside the Builder instead of Options.
fn generate_builder(w: &mut dyn Write, env: &Env, analysis: &analysis::object::Info) -> Result<()> {
    let mut methods = vec![];
    let mut properties = vec![];
    writeln!(
        w,
        "#[cfg(any(feature = \"builders\", feature = \"dox\"))]
pub struct {}Builder {{",
        analysis.name
    )?;
    for property in &analysis.builder_properties {
        match rust_type(env, property.typ) {
            Ok(type_string) => {
                let type_string = match type_string.as_str() {
                    "GString" => "String",
                    "Vec<GString>" => "Vec<String>",
                    typ => typ,
                };
                let (param_type, conversion) = match type_string {
                    "String" => ("&str", ".to_string()"),
                    typ => (typ, ""),
                };
                let name = nameutil::mangle_keywords(nameutil::signal_to_snake(&property.name));
                let version_condition_string =
                    version_condition_string(env, property.version, false, 1);
                if let Some(ref version_condition_string) = version_condition_string {
                    writeln!(w, "{}", version_condition_string)?;
                }
                writeln!(w, "    {}: Option<{}>,", name, type_string)?;
                let prefix = version_condition_string
                    .map(|version| format!("{}\n", version))
                    .unwrap_or_default();
                methods.push(format!(
                    "\n{prefix}    pub fn {name}(mut self, {name}: {param_type}) -> Self {{
        self.{name} = Some({name}{conversion});
        self
    }}",
                    prefix = prefix,
                    param_type = param_type,
                    name = name,
                    conversion = conversion
                ));
                properties.push(property);
            }
            Err(_) => writeln!(w, "    //{}: /*Unknown type*/,", property.name)?,
        }
    }
    writeln!(
        w,
        "}}

#[cfg(any(feature = \"builders\", feature = \"dox\"))]
impl {}Builder {{
    pub fn new() -> Self {{
        Self {{",
        analysis.name
    )?;
    for property in &properties {
        version_condition(w, env, property.version, false, 3)?;
        let name = nameutil::mangle_keywords(nameutil::signal_to_snake(&property.name));
        writeln!(w, "            {}: None,", name)?;
    }
    writeln!(
        w,
        "        }}
    }}

    pub fn build(self) -> {} {{
        let mut properties: Vec<(&str, &dyn ToValue)> = vec![];",
        analysis.name
    )?;
    for property in &properties {
        let name = nameutil::mangle_keywords(nameutil::signal_to_snake(&property.name));
        let version_condition_string = version_condition_string(env, property.version, false, 2);
        let condition_tabs = if version_condition_string.is_some() {
            "\t"
        } else {
            ""
        };
        if let Some(ref version_condition_string) = version_condition_string {
            writeln!(w, "{}", version_condition_string)?;
            writeln!(w, "        {{")?;
        }
        writeln!(
            w,
            "{tabs}        if let Some(ref {field}) = self.{field} {{
{tabs}            properties.push((\"{name}\", {field}));
{tabs}        }}",
            name = property.name,
            field = name,
            tabs = condition_tabs
        )?;
        if version_condition_string.is_some() {
            writeln!(w, "        }}")?;
        }
    }
    let glib_crate_name = if env.namespaces.is_glib_crate {
        "crate"
    } else {
        "glib"
    };
    writeln!(w,
"        {}::Object::new({}::static_type(), &properties).expect(\"object new\").downcast().expect(\"downcast\")
    }}", glib_crate_name, analysis.name)?;
    for method in methods {
        writeln!(w, "{}", method)?;
    }
    writeln!(w, "}}")
}

fn generate_trait(w: &mut dyn Write, env: &Env, analysis: &analysis::object::Info) -> Result<()> {
    write!(w, "pub trait {}: 'static {{", analysis.trait_name)?;

    for func_analysis in &analysis.methods() {
        function::generate(w, env, func_analysis, true, true, 1)?;
    }
    for property in &analysis.properties {
        properties::generate(w, env, property, true, true, 1)?;
    }
    for child_property in &analysis.child_properties {
        child_properties::generate(w, env, child_property, true, true, 1)?;
    }
    for signal_analysis in analysis
        .signals
        .iter()
        .chain(analysis.notify_signals.iter())
    {
        signal::generate(
            w,
            env,
            signal_analysis,
            &analysis.trampolines,
            true,
            true,
            1,
        )?;
    }
    writeln!(w, "}}")?;

    writeln!(w)?;
    write!(
        w,
        "impl<O: IsA<{}>> {} for O {{",
        analysis.name, analysis.trait_name,
    )?;

    for func_analysis in &analysis.methods() {
        function::generate(w, env, func_analysis, true, false, 1)?;
    }
    for property in &analysis.properties {
        properties::generate(w, env, property, true, false, 1)?;
    }
    for child_property in &analysis.child_properties {
        child_properties::generate(w, env, child_property, true, false, 1)?;
    }
    for signal_analysis in analysis
        .signals
        .iter()
        .chain(analysis.notify_signals.iter())
    {
        signal::generate(
            w,
            env,
            signal_analysis,
            &analysis.trampolines,
            true,
            false,
            1,
        )?;
    }
    writeln!(w, "}}")?;

    Ok(())
}

fn need_generate_inherent(analysis: &analysis::object::Info) -> bool {
    analysis.has_constructors || analysis.has_functions || !need_generate_trait(analysis)
}

fn need_generate_trait(analysis: &analysis::object::Info) -> bool {
    analysis.generate_trait
}

pub fn generate_reexports(
    env: &Env,
    analysis: &analysis::object::Info,
    module_name: &str,
    contents: &mut Vec<String>,
    traits: &mut Vec<String>,
) {
    let mut cfgs: Vec<String> = Vec::new();
    if let Some(cfg) = general::cfg_condition_string(&analysis.cfg_condition, false, 0) {
        cfgs.push(cfg);
    }
    if let Some(cfg) = general::version_condition_string(env, analysis.version, false, 0) {
        cfgs.push(cfg);
    }
    contents.push("".to_owned());
    contents.extend_from_slice(&cfgs);
    contents.push(format!("mod {};", module_name));
    contents.extend_from_slice(&cfgs);

    let none_type = if !analysis.final_type {
        format!(", NONE_{}", analysis.name.to_snake().to_uppercase())
    } else {
        String::new()
    };

    if let Some(ref class_name) = analysis.rust_class_type {
        contents.push(format!(
            "pub use self::{}::{{{}, {}{}}};",
            module_name, analysis.name, class_name, none_type
        ));
    } else {
        contents.push(format!(
            "pub use self::{}::{{{}{}}};",
            module_name, analysis.name, none_type
        ));
    }
    if need_generate_trait(analysis) {
        contents.extend_from_slice(&cfgs);
        contents.push(format!(
            "pub use self::{}::{};",
            module_name, analysis.trait_name
        ));
        for cfg in &cfgs {
            traits.push(format!("\t{}", cfg));
        }
        traits.push(format!("\tpub use super::{};", analysis.trait_name));
    }

    if !analysis.builder_properties.is_empty() {
        contents.extend_from_slice(&cfgs);
        contents.push(format!(
            "#[cfg(any(feature = \"builders\", feature = \"dox\"))]
pub use self::{}::{}Builder;",
            module_name, analysis.name
        ));
    }
}
<|endoftext|>


<commit_before>use std::fs;
use std::path::{Path, PathBuf};
use std::env;
use std::process;
use std::process::{Command, Stdio};

use clap::ArgMatches;
use kuchiki::traits::*;
use hyper::{Client, Url};
use hyper::client::Response;
use hyper::Result as HyperResult;
use util;

pub fn versions() {
    let groonga_versioned_dir = util::obtain_groonga_versioned_path();
    let paths = fs::read_dir(&Path::new(&groonga_versioned_dir)).unwrap();

    let names = paths.filter_map(|entry| {
            entry.ok().and_then(|e| {
                e.path()
                    .file_name()
                    .and_then(|n| n.to_str().map(|s| String::from(s)))
            })
        })
        .collect::<Vec<String>>();

    println!("Installed Groonga:");
    println!("\tsystem");
    for entry in names {
        println!("\t{}", entry);
    }
}

pub struct MaybeProxyUrl {
    pub url: Url,
}

impl<'a> IntoResponse for MaybeProxyUrl {
    fn into_response(self) -> HyperResult<Response> {
        extern crate env_proxy;
        let maybe_proxy = env_proxy::for_url(&self.url);

        let client = match maybe_proxy {
            None => Client::new(),
            Some(host_port) => Client::with_http_proxy(host_port.0, host_port.1),
        };
        client.get(self.url).send()
    }
}

pub fn execute_external_command(cmd: &str, ext_m: &ArgMatches) {
    let command_exe = format!("grnenv-{}{}", cmd, env::consts::EXE_SUFFIX);
    let ext_args: Vec<&str> = match ext_m.values_of("") {
        Some(c) => c.collect(),
        None => vec![],
    };
    let path = search_directories()
        .iter()
        .map(|dir| dir.join(&command_exe))
        .find(|file| is_executable(file));
    let command = match path {
        Some(command) => command,
        None => {
            println!("no such subcommand: `{}`", cmd);
            process::exit(1);
        }
    };
    let err = match Command::new(command)
        .args(&ext_args.as_slice()[0..])
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn() {
        Ok(_) => return (),
        Err(e) => e,
    };

    println!("Failed to execute external subcommand. reason: {:?}", err);
    process::exit(1);
}

fn search_directories() -> Vec<PathBuf> {
    let home = env::home_dir().unwrap();
    let mut dirs = vec![home.join("bin")];
    if let Some(val) = env::var_os("PATH") {
        dirs.extend(env::split_paths(&val));
    }
    dirs
}

#[cfg(unix)]
fn is_executable<P: AsRef<Path>>(path: P) -> bool {
    use std::os::unix::prelude::*;
    fs::metadata(path)
        .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}
#[cfg(windows)]
fn is_executable<P: AsRef<Path>>(path: P) -> bool {
    fs::metadata(path).map(|metadata| metadata.is_file()).unwrap_or(false)
}
<commit_msg>command versions: Tidy up output<commit_after>use std::fs;
use std::path::{Path, PathBuf};
use std::env;
use std::process;
use std::process::{Command, Stdio};

use clap::ArgMatches;
use kuchiki::traits::*;
use hyper::{Client, Url};
use hyper::client::Response;
use hyper::Result as HyperResult;
use util;

pub fn versions() {
    let groonga_versioned_dir = util::obtain_groonga_versioned_path();
    let paths = fs::read_dir(&Path::new(&groonga_versioned_dir)).unwrap();

    let names = paths.filter_map(|entry| {
            entry.ok().and_then(|e| {
                e.path()
                    .file_name()
                    .and_then(|n| n.to_str().map(|s| String::from(s)))
            })
        })
        .collect::<Vec<String>>();

    println!("Installed Groonga:");
    println!("\tsystem");
    for entry in names {
        let e = entry.split("-").collect::<Vec<_>>();
        println!("\t{} ({})", e.get(1).unwrap_or(&""), e.get(2).unwrap_or(&"build from source"));
    }
}

pub struct MaybeProxyUrl {
    pub url: Url,
}

impl<'a> IntoResponse for MaybeProxyUrl {
    fn into_response(self) -> HyperResult<Response> {
        extern crate env_proxy;
        let maybe_proxy = env_proxy::for_url(&self.url);

        let client = match maybe_proxy {
            None => Client::new(),
            Some(host_port) => Client::with_http_proxy(host_port.0, host_port.1),
        };
        client.get(self.url).send()
    }
}

pub fn execute_external_command(cmd: &str, ext_m: &ArgMatches) {
    let command_exe = format!("grnenv-{}{}", cmd, env::consts::EXE_SUFFIX);
    let ext_args: Vec<&str> = match ext_m.values_of("") {
        Some(c) => c.collect(),
        None => vec![],
    };
    let path = search_directories()
        .iter()
        .map(|dir| dir.join(&command_exe))
        .find(|file| is_executable(file));
    let command = match path {
        Some(command) => command,
        None => {
            println!("no such subcommand: `{}`", cmd);
            process::exit(1);
        }
    };
    let err = match Command::new(command)
        .args(&ext_args.as_slice()[0..])
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn() {
        Ok(_) => return (),
        Err(e) => e,
    };

    println!("Failed to execute external subcommand. reason: {:?}", err);
    process::exit(1);
}

fn search_directories() -> Vec<PathBuf> {
    let home = env::home_dir().unwrap();
    let mut dirs = vec![home.join("bin")];
    if let Some(val) = env::var_os("PATH") {
        dirs.extend(env::split_paths(&val));
    }
    dirs
}

#[cfg(unix)]
fn is_executable<P: AsRef<Path>>(path: P) -> bool {
    use std::os::unix::prelude::*;
    fs::metadata(path)
        .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}
#[cfg(windows)]
fn is_executable<P: AsRef<Path>>(path: P) -> bool {
    fs::metadata(path).map(|metadata| metadata.is_file()).unwrap_or(false)
}
<|endoftext|>


<commit_before>use cocoa::base::{YES, id, nil};
use cocoa::foundation::NSString;
use std::borrow::Cow;
use std::convert::AsRef;
use std::ffi::CStr;
#[cfg(feature = "time2")]
use std::time::Instant;
use sys::{MTLCommandBuffer, MTLCommandBufferStatus};
use {AsRaw, Drawable};

pub struct CommandBuffer(id);

unsafe impl Send for CommandBuffer {}
unsafe impl Sync for CommandBuffer {}

impl CommandBuffer {
    pub fn enqueue(&mut self) {
        unsafe { self.0.enqueue() }
    }

    pub fn commit(&mut self) -> Result<(), CommandBufferError> {
        unsafe {
            self.0.commit();
            let error = self.0.error();
            if error != nil { Err(CommandBufferError) } else { Ok(()) }
        }
    }

    pub fn present_drawable(&mut self, drawable: &mut Drawable) {
        unsafe { self.0.presentDrawable(*drawable.as_raw_mut()) }
    }

    #[cfg(feature = "time2")]
    pub fn present_drawable_at_time(&mut self, drawable: &mut Drawable, time: Instant) {
        unsafe { self.0.presentDrawable(*drawable.as_raw_mut(), time.elapsed().as_seconds()) }
    }

    pub fn present_drawable_at_time_secs(&mut self, drawable: &mut Drawable, time: f64) {
        unsafe { self.0.presentDrawable_atTime(*drawable.as_raw_mut(), time) }
    }

    pub fn wait_until_scheduled(&mut self) {
        unsafe { self.0.waitUntilScheduled() }
    }

    pub fn wait_until_completed(&mut self) {
        unsafe { self.0.waitUntilCompleted() }
    }

    pub fn get_status(&self) -> CommandBufferStatus {
        unsafe { self.0.status().into() }
    }

    pub fn has_retained_references(&self) -> bool {
        unsafe { self.0.retainedReferences() == YES }
    }

    pub fn set_label(&mut self, label: &AsRef<str>) {
        unsafe { MTLCommandBuffer::setLabel(self.0, NSString::alloc(nil).init_str(label.as_ref())) }
    }

    pub fn label(&self) -> Cow<str> {
        unsafe { CStr::from_ptr(MTLCommandBuffer::label(self.0).UTF8String()).to_string_lossy() }
    }
}

impl_from_into_raw!(CommandBuffer, of protocol "MTLCommandBuffer");

convertible_enum! {
    #[derive(Clone, Copy, Eq, Hash, PartialEq)]
    pub enum CommandBufferStatus : MTLCommandBufferStatus {
        CommandBufferStatusNotEnqueued => MTLCommandBufferStatusNotEnqueued,
        CommandBufferStatusEnqueued => MTLCommandBufferStatusEnqueued,
        CommandBufferStatusCommitted => MTLCommandBufferStatusCommitted,
        CommandBufferStatusScheduled => MTLCommandBufferStatusScheduled,
        CommandBufferStatusCompleted => MTLCommandBufferStatusCompleted,
        CommandBufferStatusError => MTLCommandBufferStatusError
    }
}

pub struct CommandBufferError;
<commit_msg>Rename CommandBuffer::get_status to CommandBuffer:status<commit_after>use cocoa::base::{YES, id, nil};
use cocoa::foundation::NSString;
use std::borrow::Cow;
use std::convert::AsRef;
use std::ffi::CStr;
#[cfg(feature = "time2")]
use std::time::Instant;
use sys::{MTLCommandBuffer, MTLCommandBufferStatus};
use {AsRaw, Drawable};

pub struct CommandBuffer(id);

unsafe impl Send for CommandBuffer {}
unsafe impl Sync for CommandBuffer {}

impl CommandBuffer {
    pub fn enqueue(&mut self) {
        unsafe { self.0.enqueue() }
    }

    pub fn commit(&mut self) -> Result<(), CommandBufferError> {
        unsafe {
            self.0.commit();
            let error = self.0.error();
            if error != nil { Err(CommandBufferError) } else { Ok(()) }
        }
    }

    pub fn present_drawable(&mut self, drawable: &mut Drawable) {
        unsafe { self.0.presentDrawable(*drawable.as_raw_mut()) }
    }

    #[cfg(feature = "time2")]
    pub fn present_drawable_at_time(&mut self, drawable: &mut Drawable, time: Instant) {
        unsafe { self.0.presentDrawable(*drawable.as_raw_mut(), time.elapsed().as_seconds()) }
    }

    pub fn present_drawable_at_time_secs(&mut self, drawable: &mut Drawable, time: f64) {
        unsafe { self.0.presentDrawable_atTime(*drawable.as_raw_mut(), time) }
    }

    pub fn wait_until_scheduled(&mut self) {
        unsafe { self.0.waitUntilScheduled() }
    }

    pub fn wait_until_completed(&mut self) {
        unsafe { self.0.waitUntilCompleted() }
    }

    pub fn status(&self) -> CommandBufferStatus {
        unsafe { self.0.status().into() }
    }

    pub fn has_retained_references(&self) -> bool {
        unsafe { self.0.retainedReferences() == YES }
    }

    pub fn set_label(&mut self, label: &AsRef<str>) {
        unsafe { MTLCommandBuffer::setLabel(self.0, NSString::alloc(nil).init_str(label.as_ref())) }
    }

    pub fn label(&self) -> Cow<str> {
        unsafe { CStr::from_ptr(MTLCommandBuffer::label(self.0).UTF8String()).to_string_lossy() }
    }
}

impl_from_into_raw!(CommandBuffer, of protocol "MTLCommandBuffer");

convertible_enum! {
    #[derive(Clone, Copy, Eq, Hash, PartialEq)]
    pub enum CommandBufferStatus : MTLCommandBufferStatus {
        CommandBufferStatusNotEnqueued => MTLCommandBufferStatusNotEnqueued,
        CommandBufferStatusEnqueued => MTLCommandBufferStatusEnqueued,
        CommandBufferStatusCommitted => MTLCommandBufferStatusCommitted,
        CommandBufferStatusScheduled => MTLCommandBufferStatusScheduled,
        CommandBufferStatusCompleted => MTLCommandBufferStatusCompleted,
        CommandBufferStatusError => MTLCommandBufferStatusError
    }
}

pub struct CommandBufferError;
<|endoftext|>


<commit_before>use crate::utils::printing;
use dirs;
use std::fs;
use std::path::PathBuf;

pub fn create_dir(path: &PathBuf) {
    if path.exists() {
        printing::info(format!(
            "A directory already exists at {}.",
            path.to_string_lossy()
        ))
    } else {
        printing::progress(format!("Creating directory at {}.", path.to_string_lossy()));
        match fs::create_dir_all(&path) {
            Ok(_) => (),
            Err(error) => panic!("There was a problem: {:?}", error),
        }
    }
}

pub fn remove_dir(path: &PathBuf) {
    if path.exists() {
        printing::progress(format!("Deleting directory at {}.", path.to_string_lossy()));
        match fs::remove_dir_all(&path) {
            Ok(_) => (),
            Err(error) => panic!("There was a problem: {:?}", error),
        }
    } else {
        printing::info(format!(
            "A directory doesn't exist at {}.",
            path.to_string_lossy()
        ));
    }
}

pub fn create_file(path: &PathBuf, contents: &str) {
    if path.exists() {
        printing::info(format!(
            "A file already exists at {}.",
            path.to_string_lossy()
        ))
    } else {
        printing::progress(format!("Creating file at {}.", path.to_string_lossy()));
        match fs::File::create(&path) {
            Ok(_) => {
                match fs::write(&path, &contents) {
                    Ok(_) => (),
                    Err(error) => panic!("There was a problem: {:?}", error),
                };
            }
            Err(error) => panic!("There was a problem: {:?}", error),
        }
    }
}

pub fn file_stem(file: PathBuf) -> std::string::String {
    match file.file_stem() {
        Some(file_stem) => match file_stem.to_str() {
            Some(string) => string.to_string(),
            None => panic!("There was a problem."),
        },
        None => panic!("Cannot find the file stem for {}.", file.to_string_lossy()),
    }
}

pub fn vim_plugins() -> PathBuf {
    home()
        .join(".vim")
        .join("pack")
        .join("plugins")
        .join("start")
}

pub fn repos() -> PathBuf {
    home().join("repos")
}

pub fn notes() -> PathBuf {
    home()
        .join("repos")
        .join("trevordmiller")
        .join("src")
        .join("notes")
}

pub fn public() -> PathBuf {
    home().join("repos").join("trevordmiller").join("public")
}

pub fn cname() -> PathBuf {
    home()
        .join("repos")
        .join("trevordmiller")
        .join("public")
        .join("CNAME")
}

fn home() -> PathBuf {
    match dirs::home_dir() {
        Some(directory) => directory,
        None => panic!("Cannot find the home directory."),
    }
}
<commit_msg>Replace "public" specific paths:: with current directory so that it works in CI/CD<commit_after>use crate::utils::printing;
use dirs;
use std::env;
use std::fs;
use std::path::PathBuf;

pub fn create_dir(path: &PathBuf) {
    if path.exists() {
        printing::info(format!(
            "A directory already exists at {}.",
            path.to_string_lossy()
        ))
    } else {
        printing::progress(format!("Creating directory at {}.", path.to_string_lossy()));
        match fs::create_dir_all(&path) {
            Ok(_) => (),
            Err(error) => panic!("There was a problem: {:?}", error),
        }
    }
}

pub fn remove_dir(path: &PathBuf) {
    if path.exists() {
        printing::progress(format!("Deleting directory at {}.", path.to_string_lossy()));
        match fs::remove_dir_all(&path) {
            Ok(_) => (),
            Err(error) => panic!("There was a problem: {:?}", error),
        }
    } else {
        printing::info(format!(
            "A directory doesn't exist at {}.",
            path.to_string_lossy()
        ));
    }
}

pub fn create_file(path: &PathBuf, contents: &str) {
    if path.exists() {
        printing::info(format!(
            "A file already exists at {}.",
            path.to_string_lossy()
        ))
    } else {
        printing::progress(format!("Creating file at {}.", path.to_string_lossy()));
        match fs::File::create(&path) {
            Ok(_) => {
                match fs::write(&path, &contents) {
                    Ok(_) => (),
                    Err(error) => panic!("There was a problem: {:?}", error),
                };
            }
            Err(error) => panic!("There was a problem: {:?}", error),
        }
    }
}

pub fn file_stem(file: PathBuf) -> std::string::String {
    match file.file_stem() {
        Some(file_stem) => match file_stem.to_str() {
            Some(string) => string.to_string(),
            None => panic!("There was a problem."),
        },
        None => panic!("Cannot find the file stem for {}.", file.to_string_lossy()),
    }
}

pub fn vim_plugins() -> PathBuf {
    home()
        .join(".vim")
        .join("pack")
        .join("plugins")
        .join("start")
}

pub fn repos() -> PathBuf {
    home().join("repos")
}

pub fn notes() -> PathBuf {
    project_root().join("src").join("notes")
}

pub fn public() -> PathBuf {
    project_root().join("public")
}

pub fn cname() -> PathBuf {
    project_root().join("public").join("CNAME")
}

fn home() -> PathBuf {
    match dirs::home_dir() {
        Some(directory) => directory,
        None => panic!("Cannot find the home directory."),
    }
}

fn project_root() -> PathBuf {
    match env::current_dir() {
        Ok(directory) => directory,
        Err(error) => panic!("There was a problem: {:?}", error),
    }
}
<|endoftext|>


<commit_before>use num::Num;

/// A non-resizable (after creation) buffer.
pub struct ShiftBuf<T: Num + Copy> {
    qs: Box<[T]>,
}

impl<T: Num + Copy> ShiftBuf<T> {
    /// Create a new shift register.
    ///
    /// # Examples
    /// ```
    /// # use dsp::common::buffers::ShiftBuf;
    /// let buf: ShiftBuf<f32> = ShiftBuf::new(10);
    /// ```
    pub fn new(n: usize) -> Self {
        let mut qs = Vec::new();
        for _ in 0..n {
            qs.push(T::zero());
        }
        ShiftBuf { qs: qs.into_boxed_slice() }
    }

    /// Shift new simples into the register.
    ///
    /// ```
    /// # use dsp::common::buffers::ShiftBuf;
    /// let buf: ShiftBuf<f32> = ShiftBuf::new(10);
    /// ```
    pub fn push(&mut self, xs: &[T]) {
        if xs.len() >= self.len() {
            let pivot = xs.len() - self.len();
            let new_qs = &xs[pivot..];
            for i in 0..self.len() {
                self.qs[i] = new_qs[i];
            }
        } else {
            for i in 0..(self.len()-xs.len()) {
                self.qs[i] = self.qs[i+xs.len()];
            }
            let pivot = self.len()-xs.len();
            let mut xidx = 0;
            for i in pivot..self.len() {
                self.qs[i] = xs[xidx];
                xidx += 1;
            }
        }
    }

    /// Returns the length of the shift registers.
    ///
    /// # Examples
    /// ```
    /// # use dsp::common::buffers::ShiftBuf;
    /// let buf = ShiftBuf::<i32>::new(10);
    /// assert_eq!(10, buf.len())
    /// ```
    pub fn len(&self) -> usize {
        self.qs.len()
    }

}

impl<T: Num + Copy> AsRef<[T]> for ShiftBuf<T> {
    fn as_ref(&self) -> &[T] {
        self.qs.as_ref()
    }
}

#[cfg(test)]
mod test {
    use ::common::buffers::ShiftBuf;

    #[test]
    fn test_shift_register_multipart() {
        let mut buf = ShiftBuf::<i32>::new(5);
        buf.push([0,1,2,3,4].as_ref());
        buf.push([5].as_ref());
        assert_eq!(buf.as_ref(),[1,2,3,4,5].as_ref())
    }
}
<commit_msg>Implement Index trait for ShiftBuf<commit_after>use num::Num;
use std::ops::Index;

/// A non-resizable (after creation) buffer.
pub struct ShiftBuf<T: Num + Copy> {
    qs: Box<[T]>,
}

impl<T: Num + Copy> ShiftBuf<T> {
    /// Create a new shift register.
    ///
    /// # Examples
    /// ```
    /// # use dsp::common::buffers::ShiftBuf;
    /// let buf: ShiftBuf<f32> = ShiftBuf::new(10);
    /// ```
    pub fn new(n: usize) -> Self {
        let mut qs = Vec::new();
        for _ in 0..n {
            qs.push(T::zero());
        }
        ShiftBuf { qs: qs.into_boxed_slice() }
    }

    /// Shift new samples into the register.
    ///
    /// ```
    /// # use dsp::common::buffers::ShiftBuf;
    /// let buf: ShiftBuf<f32> = ShiftBuf::new(10);
    /// ```
    pub fn push(&mut self, xs: &[T]) {
        if xs.len() >= self.len() {
            let pivot = xs.len() - self.len();
            let new_qs = &xs[pivot..];
            for i in 0..self.len() {
                self.qs[i] = new_qs[i];
            }
        } else {
            for i in 0..(self.len() - xs.len()) {
                self.qs[i] = self.qs[i + xs.len()];
            }
            let pivot = self.len() - xs.len();
            let mut xidx = 0;
            for i in pivot..self.len() {
                self.qs[i] = xs[xidx];
                xidx += 1;
            }
        }
    }

    /// Returns the length of the shift registers.
    ///
    /// # Examples
    /// ```
    /// # use dsp::common::buffers::ShiftBuf;
    /// let buf = ShiftBuf::<i32>::new(10);
    /// assert_eq!(10, buf.len())
    /// ```
    pub fn len(&self) -> usize {
        self.qs.len()
    }
}

impl<T: Num + Copy> AsRef<[T]> for ShiftBuf<T> {
    fn as_ref(&self) -> &[T] {
        self.qs.as_ref()
    }
}

impl<T: Num + Copy> Index<usize> for ShiftBuf<T> {
    type Output = T;
    fn index(&self, _index: usize) -> &T {
        &self.qs[_index]
    }
}

#[cfg(test)]
mod test {
    use ::common::buffers::ShiftBuf;

    #[test]
    fn test_shiftbuf_multipart() {
        let mut buf = ShiftBuf::<i32>::new(5);
        buf.push([0, 1, 2, 3, 4].as_ref());
        buf.push([5].as_ref());
        assert_eq!(buf.as_ref(), [1, 2, 3, 4, 5].as_ref())
    }

    #[test]
    fn test_shiftbuf_index() {
        let mut buf = ShiftBuf::<i32>::new(5);
        let elems = [0, 1, 2, 3, 4];
        buf.push(&elems);
        for i in 0..buf.len() {
            assert_eq!(buf[i], elems[i]);
        }
    }

    #[test]
    fn test_shiftbuf_len() {
        let mut buf = ShiftBuf::<i32>::new(5);
        let elems = [0, 1, 2, 3, 4];
        buf.push(&elems);
        assert_eq!(elems.len(), buf.len());
    }
}
<|endoftext|>