<commit_before>#![feature(convert)]
extern crate byteorder;
extern crate rocksdb;

use byteorder::{BigEndian, WriteBytesExt};

struct Error(i32, String);
type Result<T> = std::result::Result<T, Error>;

fn encode(key :&[u8], ver :u64) -> Result<Vec<u8>> {
    let mut data = key;
    let mut new_key = Vec::with_capacity(key.len() + 20);

    if data.len() > 0 && data[0] == b'\xff' {
        // we must escape 0xFF here to guarantee encoded value < InfiniteValue \xFF\xFF.
        new_key.push(b'\xff');
        new_key.push(b'\x00');
        data = &data[1..];
    }
    for c in data {
        match *c {
            b'\x00' =>  {
                new_key.push(b'\x00');
                new_key.push(b'\xff');
            }
            _ => {
                new_key.push(*c);
            }
        }
    }
    new_key.push(b'\x00');
    new_key.push(b'\x01');

    // put version
    let mut wtr = Vec::with_capacity(8);
    wtr.write_u64::<BigEndian>(ver).unwrap();
    new_key.extend(&*wtr);

    Ok(new_key)
}

fn decode(encoded :&[u8]) -> Result<(Vec<u8>, u64)> {
    let mut data = encoded;
    let mut key = Vec::new();

    if data[0] == b'\xff' {
        if data[1] != b'\x00' {
            return Err(Error(-1, "invalid format".to_string()))
        }
        key.push(data[0]);
        data = &data[2..]
    }
    for (i, c) in data.iter().enumerate() {
        // find \x00 => {\xff, \x01 -> term}
        match *c {
            b'\x00' => {
                if i + 1 >= data.len() {
                    return Err(Error(-2, "invalid format".to_string()))
                }
                match data[i+1] {
                    b'\xff' => {
                        key.push(b'\x00');
                        continue
                    }
                    b'\x01' => {
                        break
                    }
                    _ => {
                        return Err(Error(-3, "invalid format".to_string()))
                    }
                }
            }
            _ => {
                key.push(*c);
            }
        }
    }
    Ok((key, 0))
}

trait MvccDB {
    fn put(&self, key :&[u8], val :&[u8], ver :u64) -> Result<()>;
    fn get(&self, key :&[u8], ver :u64) -> Result<&[u8]>;
}

struct MvccRocks;
impl MvccDB for MvccRocks {
    fn put(&self, key :&[u8], val :&[u8], ver :u64) -> Result<()> {
        println!("put {:?}, {:?}, {}", key, val, ver);
        Ok(())
    }

    fn get(&self, key :&[u8], ver :u64) -> Result<&[u8]> {
        println!("get {:?}, {}", key, ver);
        Ok(b"hello")
    }
}

fn main() {
    let b = Box::new(MvccRocks);
    match b.put(b"hello", b"world", 1) {
        Ok(()) => println!("ok"),
        Err(Error(code, msg)) => println!("err code: {:?}, msg: {:?}", code, msg),
    }

    match encode(b"\xffhe\x00llo", 23) {
        Ok(key) => {
            println!("encoded: {:?}", key);
            match decode(key.as_slice()) {
                Ok((ori, ver)) => {
                    println!("decoded: {:?}", ori);
                }
                _ => (),
            }
        }
        _ => (),
    }
}
<commit_msg>add decode func<commit_after>#![feature(convert)]
extern crate byteorder;
extern crate rocksdb;

use byteorder::{BigEndian, WriteBytesExt};

struct Error(i32, String);
type Result<T> = std::result::Result<T, Error>;

fn encode(key :&[u8], ver :u64) -> Result<Vec<u8>> {
    let mut data = key;
    let mut new_key = Vec::with_capacity(key.len() + 20);

    if data.len() > 0 && data[0] == b'\xff' {
        // we must escape 0xFF here to guarantee encoded value < InfiniteValue \xFF\xFF.
        new_key.push(b'\xff');
        new_key.push(b'\x00');
        data = &data[1..];
    }
    for c in data {
        match *c {
            b'\x00' =>  {
                new_key.push(b'\x00');
                new_key.push(b'\xff');
            }
            _ => {
                new_key.push(*c);
            }
        }
    }
    new_key.push(b'\x00');
    new_key.push(b'\x01');

    let mut wtr = Vec::with_capacity(8);
    wtr.write_u64::<BigEndian>(ver).unwrap();
    new_key.extend(&*wtr);

    Ok(new_key)
}

fn decode(encoded :&[u8]) -> Result<(Vec<u8>, u64)> {
    let mut data = encoded;
    let mut key = Vec::new();

    if data[0] == b'\xff' {
        if data[1] != b'\x00' {
            return Err(Error(-1, "invalid format".to_string()))
        }
        key.push(data[0]);
        data = &data[2..]
    }

    let mut ver_buf :&[u8];
    'outer: loop {
        let mut idx = 0;
        for (i, c) in data.iter().enumerate() {
            if *c == b'\x00' {
                idx = i;
                if data[i + 1] == b'\x01' {
                    key.extend(&data[..idx]);
                    ver_buf = &data[idx+2..];
                    break 'outer;
                }
                break
            }
        }
        key.extend(&data[..idx]);
        key.push(b'\x00');
        data = &data[idx+2..];
    }

    // TODO: deal with ver_buf
    Ok((key, 0))
}

trait MvccDB {
    fn put(&self, key :&[u8], val :&[u8], ver :u64) -> Result<()>;
    fn get(&self, key :&[u8], ver :u64) -> Result<&[u8]>;
}

struct MvccRocks;
impl MvccDB for MvccRocks {
    fn put(&self, key :&[u8], val :&[u8], ver :u64) -> Result<()> {
        println!("put {:?}, {:?}, {}", key, val, ver);
        Ok(())
    }

    fn get(&self, key :&[u8], ver :u64) -> Result<&[u8]> {
        println!("get {:?}, {}", key, ver);
        Ok(b"hello")
    }
}

fn main() {
    let b = Box::new(MvccRocks);
    match b.put(b"hello", b"world", 1) {
        Ok(()) => println!("ok"),
        Err(Error(code, msg)) => println!("err code: {:?}, msg: {:?}", code, msg),
    }

    let ori = b"\xff\xffh\x00e\x00llo";
    match encode(ori, 23) {
        Ok(key) => {
            println!("encoded: {:?}", key);
            match decode(key.as_slice()) {
                Ok((r, ver)) => {
                    println!("ori:{:?} decoded: {:?}", ori, r);
                }
                _ => (),
            }
        }
        _ => (),
    }
}
<|endoftext|>


<commit_before>#![warn(rust_2018_idioms)]

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

use futures::FutureExt;
use std::env;
use std::error::Error;

use nix::sys::socket::{sockopt,getsockopt,InetAddr};
use std::os::unix::io::AsRawFd;
use std::net::SocketAddr;

use bytes::BytesMut;

const BUF_SIZE: usize = 1024 * 1024;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let listen_addr = env::args()
        .nth(1)
        .unwrap_or_else(|| "127.0.0.1:1080".to_string());

    println!("Listening on: {}", listen_addr);

    let listener = TcpListener::bind(listen_addr).await?;

    while let Ok((inbound, client_addr)) = listener.accept().await {
        let server_addr = getsockopt(inbound.as_raw_fd(), sockopt::OriginalDst).unwrap();
        let server_addr = InetAddr::V4(server_addr).to_std();
        eprintln!("[INFO]{} -> {}: connection incoming", client_addr, server_addr);
        if inbound.local_addr().unwrap() == server_addr {
            eprintln!("[WARM]{} -> {}: connection from local network", client_addr, server_addr);
            continue;
        }
        let transfer = transfer(inbound, server_addr).map(move |r| {
            if let Err(e) = r {
                println!("[INFO]{} -> {}: connection closed with error; {}", client_addr, server_addr, e);
            }
        });
        tokio::spawn(transfer);
    }

    Ok(())
}

async fn transfer(mut inbound: TcpStream, proxy_addr: SocketAddr) -> Result<(), Box<dyn Error>> {
    let mut outbound = TcpStream::connect(proxy_addr).await?;

    inbound.set_nodelay(true)?;
    outbound.set_nodelay(true)?;

    let client_addr = inbound.peer_addr().unwrap();
    let server_addr = outbound.peer_addr().unwrap();

    let (mut ri, mut wi) = inbound.split();
    let (mut ro, mut wo) = outbound.split();

    let client_to_server = async {
        let mut buf = BytesMut::with_capacity(BUF_SIZE);
        loop {
            let n = ri.read_buf(&mut buf).await?;
            if n == 0 { break }
            let n = wo.write_buf(&mut buf).await?;
            if n == 0 { break }
        }
        wo.shutdown().await
    };

    let server_to_client = async {
        let mut buf = BytesMut::with_capacity(BUF_SIZE);
        loop {
            let n = ro.read_buf(&mut buf).await?;
            if n == 0 { break }
            let n = wi.write_buf(&mut buf).await?;
            if n == 0 { break }
        }
        wi.shutdown().await
    };

    tokio::try_join!(client_to_server, server_to_client)?;
    eprintln!("[INFO]{} -> {}: connection closed", client_addr, server_addr);

    Ok(())
}
<commit_msg>Refact copy procedure<commit_after>#![warn(rust_2018_idioms)]

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

use futures::FutureExt;
use std::env;
use std::error::Error;

use nix::sys::socket::{sockopt,getsockopt,InetAddr};
use std::os::unix::io::AsRawFd;
use std::net::SocketAddr;

use bytes::BytesMut;

const BUF_SIZE: usize = 1024 * 1024;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let listen_addr = env::args()
        .nth(1)
        .unwrap_or_else(|| "127.0.0.1:1080".to_string());

    println!("Listening on: {}", listen_addr);

    let listener = TcpListener::bind(listen_addr).await?;

    while let Ok((inbound, client_addr)) = listener.accept().await {
        let server_addr = getsockopt(inbound.as_raw_fd(), sockopt::OriginalDst).unwrap();
        let server_addr = InetAddr::V4(server_addr).to_std();
        eprintln!("[INFO]{} -> {}: connection incoming", client_addr, server_addr);
        if inbound.local_addr().unwrap() == server_addr {
            eprintln!("[WARM]{} -> {}: connection from local network", client_addr, server_addr);
            continue;
        }
        let transfer = transfer(inbound, server_addr).map(move |r| {
            if let Err(e) = r {
                println!("[INFO]{} -> {}: connection closed with error; {}", client_addr, server_addr, e);
            }
        });
        tokio::spawn(transfer);
    }

    Ok(())
}

async fn transfer(mut inbound: TcpStream, proxy_addr: SocketAddr) -> Result<(), Box<dyn Error>> {
    let mut outbound = TcpStream::connect(proxy_addr).await?;

    inbound.set_nodelay(true)?;
    outbound.set_nodelay(true)?;

    let client_addr = inbound.peer_addr().unwrap();
    let server_addr = outbound.peer_addr().unwrap();

    let (ri, wi) = inbound.split();
    let (ro, wo) = outbound.split();

    tokio::try_join!(
        copy_one_direction(ro, wi),
        copy_one_direction(ri, wo)
    )?;
    eprintln!("[INFO]{} -> {}: connection closed", client_addr, server_addr);

    Ok(())
}

async fn copy_one_direction<T, U>(mut from: T, mut to: U) -> std::io::Result<()>
    where T: AsyncReadExt + Unpin, U: AsyncWriteExt + Unpin
{
    let mut buf = BytesMut::with_capacity(BUF_SIZE);
    loop {
        let n = from.read_buf(&mut buf).await?;
        if n == 0 { break }
        let n = to.write_buf(&mut buf).await?;
        if n == 0 { break }
    }
    to.shutdown().await
}

<|endoftext|>


<commit_before>#![feature(core, path)]

extern crate curl;
extern crate git;
extern crate "rustc-serialize" as rustc_serialize;
extern crate time;

use git::Result as GitResult;
use std::default::Default;
use std::old_io::IoResult;
use std::env::args;

use description::Description;

mod description;

fn main() {
    macro_rules! ok(
        ($result:expr) => (
            if let Err(e) = $result {
                error(e);
                std::os::set_exit_status(1);
                return;
            }
        );
    );

    let mut args = args();

    args.next();

    let command = match args.next() {
        Some(command) => command.into_string().ok().unwrap(),
        _ => {
            usage();
            return;
        }
    };

    let path = match args.next() {
        Some(path) => Path::new(path.into_string().ok().unwrap()),
        _ => {
            usage();
            return;
        }
    };

    match &command[] {
        "status" => ok!(status(&mut std::old_io::stdio::stdout(), &path)),
        "push" => ok!(push(&path)),
        _ => usage(),
    }
}

fn error<T: std::fmt::Debug>(e: T) {
    println!("{:?}", e);
}

fn usage() {
    println!("Usage: {} (status|push) <path>",
        args().next().unwrap().into_string().ok().unwrap());
}

fn status<T: Writer>(writer: &mut T, path: &Path) -> IoResult<()> {
    use std::old_io::MemWriter;
    use std::old_io::{IoError, OtherIoError};

    macro_rules! display(
        ($writer:expr, $title:expr, $paths:expr) => {
            if !$paths.is_empty() {
                try!(display($writer, $title, &$paths));
            }
        };
    );

    let (new, updated, removed) = match summarize(path) {
        Ok(result) => result,
        Err(error) => return Err(IoError {
            kind: OtherIoError,
            desc: "cannot check the status of the repository",
            detail: Some(format!("{:?}", error)),
        }),
    };

    let mut buffer = MemWriter::new();

    display!(&mut buffer, "New", new);
    display!(&mut buffer, "Updated", updated);
    display!(&mut buffer, "Deleted", removed);

    let data = buffer.into_inner();

    if data.len() > 0 {
        try!(writeln!(writer, "### {}", timestamp()));
        try!(writeln!(writer, ""));
        try!(writer.write_all(&data[]));
    }

    Ok(())
}

fn push(path: &Path) -> GitResult<()> {
    let mut git = try!(git::open(path));

    if try!(git.status()).len() > 0 {
        try!(git.add_all());
        try!(git.commit("Synchronized with the official repository"));
    }

    try!(git.push());

    Ok(())
}

fn summarize(dir: &Path) -> GitResult<(Vec<Path>, Vec<Path>, Vec<Path>)> {
    use git::status::{Flag, Flags};

    macro_rules! equal(
        ($one:expr, $two:expr) => ($one.dir_path() == $two.dir_path());
    );

    macro_rules! find(
        ($vector:expr, $element:expr) => (
            $vector.iter().find(|p| equal!(p, $element))
        );
    );

    const NEW: Flags = Flags(Flag::IndexNew as u32 | Flag::WorkDirNew as u32);
    const UPDATED: Flags = Flags(Flag::IndexModified as u32 | Flag::WorkDirModified as u32);
    const REMOVED: Flags = Flags(Flag::IndexDeleted as u32 | Flag::WorkDirDeleted as u32);

    let repo = try!(git::Repository::open(dir));
    let list = try!(repo.status(&Default::default()));

    let mut new = vec![];
    let mut updated = vec![];
    let mut removed = vec![];

    fn push(vector: &mut Vec<Path>, path: &Path) {
        if find!(vector, path).is_none() {
            vector.push(path.clone());
        }
    }

    for entry in list.iter() {
        let status = entry.status();
        let path = dir.join(entry.new_path());

        if status.has_any(NEW) {
            push(&mut new, &path);
        } else if status.has_any(UPDATED) {
            push(&mut updated, &path);
        } else if status.has_any(REMOVED) {
            push(&mut removed, &path);
        }
    }

    let new = new.into_iter().filter(|path| {
        if find!(removed, path).is_some() {
            push(&mut updated, path);
            false
        } else {
            true
        }
    }).collect::<Vec<_>>();

    let removed = removed.into_iter().filter(|path| {
        (find!(updated, path).is_none())
    }).collect::<Vec<_>>();

    Ok((new, updated, removed))
}

fn display<T: Writer>(writer: &mut T, title: &str, paths: &Vec<Path>) -> IoResult<()> {
    let lines = paths.iter().by_ref()
                     .map(|path| format(path))
                     .filter(|line| line.is_some())
                     .map(|line| line.unwrap())
                     .collect::<Vec<_>>();

    let len = lines.len();
    if len == 0 {
        return Ok(());
    }

    try!(writeln!(writer, "{}:", title));
    try!(writeln!(writer, ""));
    for (i, line) in lines.iter().enumerate() {
        if i + 1 == len {
            try!(writeln!(writer, "* {}.", line));
        } else if i + 2 == len {
            if len == 2 {
                try!(writeln!(writer, "* {} and", line));
            } else {
                try!(writeln!(writer, "* {}, and", line));
            }
        } else {
            try!(writeln!(writer, "* {},", line));
        }
    }
    try!(writeln!(writer, ""));

    Ok(())
}

fn format(path: &Path) -> Option<String> {
    let mut line = String::new();

    let desc = Description::load(path);

    match desc.name {
        Some(ref name) => line.push_str(&name[]),
        None => return None,
    }

    match desc.url {
        Some(ref url) => {
            line.insert(0, '[');
            line.push_str("](");
            line.push_str(&url[]);
            line.push_str(")");
        },
        None => {},
    }

    match desc.designer {
        Some(ref designer) => {
            line.push_str(" by ");
            line.push_str(&designer[]);
        },
        None => {},
    }

    Some(line)
}

fn timestamp() -> String {
    let time = time::now();

    const MONTHS: [&'static str; 12] = ["January", "February", "March", "April",
                                        "May", "June", "July", "August", "September",
                                        "October", "November", "December"];

    format!("{} {}, {}", MONTHS[time.tm_mon as usize], time.tm_mday, 1900 + time.tm_year)
}
<commit_msg>Adjusted #![feature(…)]<commit_after>#![feature(core, env, io, os, path)]

extern crate curl;
extern crate git;
extern crate "rustc-serialize" as rustc_serialize;
extern crate time;

use git::Result as GitResult;
use std::default::Default;
use std::old_io::IoResult;
use std::env::args;

use description::Description;

mod description;

fn main() {
    macro_rules! ok(
        ($result:expr) => (
            if let Err(e) = $result {
                error(e);
                std::os::set_exit_status(1);
                return;
            }
        );
    );

    let mut args = args();

    args.next();

    let command = match args.next() {
        Some(command) => command.into_string().ok().unwrap(),
        _ => {
            usage();
            return;
        }
    };

    let path = match args.next() {
        Some(path) => Path::new(path.into_string().ok().unwrap()),
        _ => {
            usage();
            return;
        }
    };

    match &command[] {
        "status" => ok!(status(&mut std::old_io::stdio::stdout(), &path)),
        "push" => ok!(push(&path)),
        _ => usage(),
    }
}

fn error<T: std::fmt::Debug>(e: T) {
    println!("{:?}", e);
}

fn usage() {
    println!("Usage: {} (status|push) <path>",
        args().next().unwrap().into_string().ok().unwrap());
}

fn status<T: Writer>(writer: &mut T, path: &Path) -> IoResult<()> {
    use std::old_io::MemWriter;
    use std::old_io::{IoError, OtherIoError};

    macro_rules! display(
        ($writer:expr, $title:expr, $paths:expr) => {
            if !$paths.is_empty() {
                try!(display($writer, $title, &$paths));
            }
        };
    );

    let (new, updated, removed) = match summarize(path) {
        Ok(result) => result,
        Err(error) => return Err(IoError {
            kind: OtherIoError,
            desc: "cannot check the status of the repository",
            detail: Some(format!("{:?}", error)),
        }),
    };

    let mut buffer = MemWriter::new();

    display!(&mut buffer, "New", new);
    display!(&mut buffer, "Updated", updated);
    display!(&mut buffer, "Deleted", removed);

    let data = buffer.into_inner();

    if data.len() > 0 {
        try!(writeln!(writer, "### {}", timestamp()));
        try!(writeln!(writer, ""));
        try!(writer.write_all(&data[]));
    }

    Ok(())
}

fn push(path: &Path) -> GitResult<()> {
    let mut git = try!(git::open(path));

    if try!(git.status()).len() > 0 {
        try!(git.add_all());
        try!(git.commit("Synchronized with the official repository"));
    }

    try!(git.push());

    Ok(())
}

fn summarize(dir: &Path) -> GitResult<(Vec<Path>, Vec<Path>, Vec<Path>)> {
    use git::status::{Flag, Flags};

    macro_rules! equal(
        ($one:expr, $two:expr) => ($one.dir_path() == $two.dir_path());
    );

    macro_rules! find(
        ($vector:expr, $element:expr) => (
            $vector.iter().find(|p| equal!(p, $element))
        );
    );

    const NEW: Flags = Flags(Flag::IndexNew as u32 | Flag::WorkDirNew as u32);
    const UPDATED: Flags = Flags(Flag::IndexModified as u32 | Flag::WorkDirModified as u32);
    const REMOVED: Flags = Flags(Flag::IndexDeleted as u32 | Flag::WorkDirDeleted as u32);

    let repo = try!(git::Repository::open(dir));
    let list = try!(repo.status(&Default::default()));

    let mut new = vec![];
    let mut updated = vec![];
    let mut removed = vec![];

    fn push(vector: &mut Vec<Path>, path: &Path) {
        if find!(vector, path).is_none() {
            vector.push(path.clone());
        }
    }

    for entry in list.iter() {
        let status = entry.status();
        let path = dir.join(entry.new_path());

        if status.has_any(NEW) {
            push(&mut new, &path);
        } else if status.has_any(UPDATED) {
            push(&mut updated, &path);
        } else if status.has_any(REMOVED) {
            push(&mut removed, &path);
        }
    }

    let new = new.into_iter().filter(|path| {
        if find!(removed, path).is_some() {
            push(&mut updated, path);
            false
        } else {
            true
        }
    }).collect::<Vec<_>>();

    let removed = removed.into_iter().filter(|path| {
        (find!(updated, path).is_none())
    }).collect::<Vec<_>>();

    Ok((new, updated, removed))
}

fn display<T: Writer>(writer: &mut T, title: &str, paths: &Vec<Path>) -> IoResult<()> {
    let lines = paths.iter().by_ref()
                     .map(|path| format(path))
                     .filter(|line| line.is_some())
                     .map(|line| line.unwrap())
                     .collect::<Vec<_>>();

    let len = lines.len();
    if len == 0 {
        return Ok(());
    }

    try!(writeln!(writer, "{}:", title));
    try!(writeln!(writer, ""));
    for (i, line) in lines.iter().enumerate() {
        if i + 1 == len {
            try!(writeln!(writer, "* {}.", line));
        } else if i + 2 == len {
            if len == 2 {
                try!(writeln!(writer, "* {} and", line));
            } else {
                try!(writeln!(writer, "* {}, and", line));
            }
        } else {
            try!(writeln!(writer, "* {},", line));
        }
    }
    try!(writeln!(writer, ""));

    Ok(())
}

fn format(path: &Path) -> Option<String> {
    let mut line = String::new();

    let desc = Description::load(path);

    match desc.name {
        Some(ref name) => line.push_str(&name[]),
        None => return None,
    }

    match desc.url {
        Some(ref url) => {
            line.insert(0, '[');
            line.push_str("](");
            line.push_str(&url[]);
            line.push_str(")");
        },
        None => {},
    }

    match desc.designer {
        Some(ref designer) => {
            line.push_str(" by ");
            line.push_str(&designer[]);
        },
        None => {},
    }

    Some(line)
}

fn timestamp() -> String {
    let time = time::now();

    const MONTHS: [&'static str; 12] = ["January", "February", "March", "April",
                                        "May", "June", "July", "August", "September",
                                        "October", "November", "December"];

    format!("{} {}, {}", MONTHS[time.tm_mon as usize], time.tm_mday, 1900 + time.tm_year)
}
<|endoftext|>


<commit_before>use std::error::Error;
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;

fn main() {
    let args: Vec<String> = env::args().collect();

    let argument_spaces = args.get(1).map(|x| x.as_str()).unwrap_or("2");

    let argument_path = args.get(2).map(|x| x.as_str()).unwrap_or(".");

    let file_name = "/.editorconfig";
    let full_path = argument_path.to_owned() + file_name;

    let save_path = Path::new(&full_path);
    let save_path_display = save_path.display();

    let part_1 = "# editorconfig.org\n\
        \n\
        root = true\n\
        \n\
        [*]\n\
        end_of_line = lf\n\
        charset = utf-8\n\
        trim_trailing_whitespace = true\n\
        insert_final_newline = true\n\
        indent_style = space\n\
        indent_size = ";

    let part_2 = "\n\
        \n\
        [*.md]\n\
        trim_trailing_whitespace = false\n";

    let contents = part_1.to_owned() + argument_spaces + part_2;

    let mut output_file = match File::create(&save_path) {
        Err(error) => {
            panic!(
                "Could not create {}: {}",
                save_path_display,
                error.description()
            )
        }
        Ok(file) => file,
    };

    output_file.write_all(contents.as_bytes()).unwrap();
}
<commit_msg>Unindent strings<commit_after>use std::error::Error;
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;

fn main() {
    let args: Vec<String> = env::args().collect();

    let argument_spaces = args.get(1).map(|x| x.as_str()).unwrap_or("2");

    let argument_path = args.get(2).map(|x| x.as_str()).unwrap_or(".");

    let file_name = "/.editorconfig";
    let full_path = argument_path.to_owned() + file_name;

    let save_path = Path::new(&full_path);
    let save_path_display = save_path.display();

    let part_1 = "# editorconfig.org\n\
\n\
root = true\n\
\n\
[*]\n\
end_of_line = lf\n\
charset = utf-8\n\
trim_trailing_whitespace = true\n\
insert_final_newline = true\n\
indent_style = space\n\
indent_size = ";

    let part_2 = "\n\
\n\
[*.md]\n\
trim_trailing_whitespace = false\n";

    let contents = part_1.to_owned() + argument_spaces + part_2;

    let mut output_file = match File::create(&save_path) {
        Err(error) => {
            panic!(
                "Could not create {}: {}",
                save_path_display,
                error.description()
            )
        }
        Ok(file) => file,
    };

    output_file.write_all(contents.as_bytes()).unwrap();
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate clap;
extern crate craycray;
extern crate rayon;
extern crate sdl2;

use std::time::Instant;

use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::EventPump;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;

use rayon::prelude::*;

use craycray::scene::Scene;

struct FpsCounter {
    ts: Instant,
    cnt: usize,
    freq: usize,
}

impl FpsCounter {
    pub fn new(freq: usize) -> Self {
        let cnt = 0;
        let ts = Instant::now();
        FpsCounter { ts, cnt, freq }
    }

    pub fn update(&mut self) {
        if self.cnt >= self.freq {
            let elapsed = self.ts.elapsed();
            let msecs = (u64::from(elapsed.as_secs()) * 1000) +
                (u64::from(elapsed.subsec_nanos()) / 1_000_000);
            self.ts = Instant::now();
            eprintln!("FPS {}", (self.cnt as f32) / (msecs as f32 / 1000.0));
            self.cnt = 0;
        }

        self.cnt += 1;
    }
}

// Return true for quit
fn handle_events(scene: &mut Scene, event_pump: &mut EventPump) -> bool {
    for event in event_pump.poll_iter() {
        match event {
            Event::Quit { .. } |
            Event::KeyDown {
                keycode: Some(Keycode::Escape),
                ..
            } => return true,
            Event::KeyDown {
                keycode: Some(Keycode::W),
                ..
            } => {
                scene.mv_camera_fwd();
            }
            Event::KeyDown {
                keycode: Some(Keycode::S),
                ..
            } => {
                scene.mv_camera_back();
            }
            _ => {}
        }
    }

    let rel_mouse = event_pump.relative_mouse_state();

    let x_rot = f64::from(rel_mouse.x()) * (0.010);
    let y_rot = f64::from(rel_mouse.y()) as f64 * (0.010);
    scene.rot_camera(x_rot, y_rot);
    false
}

// A simple test code that uses SDL for rendering
fn main() {
    let matches = clap_app!(craycray =>
        (version: "0.1")
        (about: "craycray")
        (@arg RESOLUTION: -r --resolution +takes_value "Render resolution")
        (@arg FULLSCREEN: -f --fullscreen "Fullscreen")
    ).get_matches();

    let fullscreen = matches.is_present("FULLSCREEN");
    let resolution: u32 = matches
        .value_of("RESOLUTION")
        .unwrap_or("512")
        .parse()
        .unwrap_or(512);
    let res_u = resolution as usize;
    let mut scene = Scene::from_file("scene.json").unwrap();

    // Stuff from sdl2-rust example
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = if fullscreen {
        let display_mode = video_subsystem.desktop_display_mode(0).unwrap();
        video_subsystem
            .window("craycray", display_mode.w as u32, display_mode.h as u32)
            .fullscreen_desktop()
            .build()
            .unwrap()
    } else {
        video_subsystem
            .window("craycray", resolution, resolution)
            .position_centered()
            .build()
            .unwrap()
    };

    let (_, window_h) = window.size();

    let mut canvas = window.into_canvas().build().unwrap();
    let texture_creator = canvas.texture_creator();

    let mut texture = texture_creator
        .create_texture_streaming(PixelFormatEnum::RGB24, resolution, resolution)
        .unwrap();
    sdl_context.mouse().show_cursor(false);
    sdl_context.mouse().set_relative_mouse_mode(true);

    let mut event_pump = sdl_context.event_pump().unwrap();
    let mut fps = FpsCounter::new(10);

    loop {
        let quit = handle_events(&mut scene, &mut event_pump);
        if quit {
            break;
        }

        scene.step();

        texture
            .with_lock(None, |buffer: &mut [u8], pitch: usize| {
                let pchunks = buffer.par_chunks_mut(pitch);
                pchunks.enumerate().for_each(|(line_no, chunk)| {
                    let line_iter = scene.line_iter(res_u, res_u, line_no);
                    for (idx, c) in line_iter.enumerate() {
                        let (r, g, b) = c.into();
                        chunk[idx * 3] = r;
                        chunk[idx * 3 + 1] = g;
                        chunk[idx * 3 + 2] = b;
                    }
                });
            })
            .unwrap();
        canvas.clear();
        canvas
            .copy(&texture, None, Some(Rect::new(0, 0, window_h, window_h)))
            .unwrap();
        canvas.present();

        fps.update();
    }
}
<commit_msg>Use chunks for pixel access<commit_after>#[macro_use]
extern crate clap;
extern crate craycray;
extern crate rayon;
extern crate sdl2;

use std::time::Instant;

use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::EventPump;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;

use rayon::prelude::*;

use craycray::scene::Scene;

struct FpsCounter {
    ts: Instant,
    cnt: usize,
    freq: usize,
}

impl FpsCounter {
    pub fn new(freq: usize) -> Self {
        let cnt = 0;
        let ts = Instant::now();
        FpsCounter { ts, cnt, freq }
    }

    pub fn update(&mut self) {
        if self.cnt >= self.freq {
            let elapsed = self.ts.elapsed();
            let msecs = (u64::from(elapsed.as_secs()) * 1000) +
                (u64::from(elapsed.subsec_nanos()) / 1_000_000);
            self.ts = Instant::now();
            eprintln!("FPS {}", (self.cnt as f32) / (msecs as f32 / 1000.0));
            self.cnt = 0;
        }

        self.cnt += 1;
    }
}

// Return true for quit
fn handle_events(scene: &mut Scene, event_pump: &mut EventPump) -> bool {
    for event in event_pump.poll_iter() {
        match event {
            Event::Quit { .. } |
            Event::KeyDown {
                keycode: Some(Keycode::Escape),
                ..
            } => return true,
            Event::KeyDown {
                keycode: Some(Keycode::W),
                ..
            } => {
                scene.mv_camera_fwd();
            }
            Event::KeyDown {
                keycode: Some(Keycode::S),
                ..
            } => {
                scene.mv_camera_back();
            }
            _ => {}
        }
    }

    let rel_mouse = event_pump.relative_mouse_state();

    let x_rot = f64::from(rel_mouse.x()) * (0.010);
    let y_rot = f64::from(rel_mouse.y()) as f64 * (0.010);
    scene.rot_camera(x_rot, y_rot);
    false
}

// A simple test code that uses SDL for rendering
fn main() {
    let matches = clap_app!(craycray =>
        (version: "0.1")
        (about: "craycray")
        (@arg RESOLUTION: -r --resolution +takes_value "Render resolution")
        (@arg FULLSCREEN: -f --fullscreen "Fullscreen")
    ).get_matches();

    let fullscreen = matches.is_present("FULLSCREEN");
    let resolution: u32 = matches
        .value_of("RESOLUTION")
        .unwrap_or("512")
        .parse()
        .unwrap_or(512);
    let res_u = resolution as usize;
    let mut scene = Scene::from_file("scene.json").unwrap();

    // Stuff from sdl2-rust example
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = if fullscreen {
        let display_mode = video_subsystem.desktop_display_mode(0).unwrap();
        video_subsystem
            .window("craycray", display_mode.w as u32, display_mode.h as u32)
            .fullscreen_desktop()
            .build()
            .unwrap()
    } else {
        video_subsystem
            .window("craycray", resolution, resolution)
            .position_centered()
            .build()
            .unwrap()
    };

    let (_, window_h) = window.size();

    let mut canvas = window.into_canvas().build().unwrap();
    let texture_creator = canvas.texture_creator();

    let mut texture = texture_creator
        .create_texture_streaming(PixelFormatEnum::RGB24, resolution, resolution)
        .unwrap();
    sdl_context.mouse().show_cursor(false);
    sdl_context.mouse().set_relative_mouse_mode(true);

    let mut event_pump = sdl_context.event_pump().unwrap();
    let mut fps = FpsCounter::new(10);

    loop {
        let quit = handle_events(&mut scene, &mut event_pump);
        if quit {
            break;
        }

        scene.step();

        texture
            .with_lock(None, |buffer: &mut [u8], pitch: usize| {
                let pchunks = buffer.par_chunks_mut(pitch);
                pchunks.enumerate().for_each(|(line_no, chunk)| {
                    let line_iter = scene.line_iter(res_u, res_u, line_no);
                    for (c, pix) in line_iter.zip(chunk.chunks_mut(3)) {
                        let (r, g, b) = c.into();
                        pix[0] = r;
                        pix[1] = g;
                        pix[2] = b;
                    }
                });
            })
            .unwrap();
        canvas.clear();
        canvas
            .copy(&texture, None, Some(Rect::new(0, 0, window_h, window_h)))
            .unwrap();
        canvas.present();

        fps.update();
    }
}
<|endoftext|>


<commit_before>//! Compiler plugin defining macros that create PHF data structures.
//!
//! # Example
//!
//! ```rust
//! #![feature(plugin, core)]
//! #![plugin(phf_macros)]
//!
//! extern crate phf;
//!
//! #[derive(Clone)]
//! pub enum Keyword {
//!     Loop,
//!     Continue,
//!     Break,
//!     Fn,
//!     Extern,
//! }
//!
//! static KEYWORDS: phf::Map<&'static str, Keyword> = phf_map! {
//!     "loop" => Keyword::Loop,
//!     "continue" => Keyword::Continue,
//!     "break" => Keyword::Break,
//!     "fn" => Keyword::Fn,
//!     "extern" => Keyword::Extern,
//! };
//!
//! pub fn parse_keyword(keyword: &str) -> Option<Keyword> {
//!     KEYWORDS.get(keyword).cloned()
//! }
//! # fn main() {}
//! ```
#![doc(html_root_url="http://sfackler.github.io/rust-phf/doc/v0.7.12")]
#![feature(plugin_registrar, quote, rustc_private)]

extern crate syntax;
#[cfg(feature = "stats")]
extern crate time;
extern crate rustc_plugin;
extern crate phf_shared;
extern crate phf_generator;

use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use syntax::ast::{self, Expr, ExprLit, ExprVec, MutImmutable, TokenTree, TyVec};
use syntax::codemap::{Span, Spanned};
use syntax::ext::base::{DummyResult, ExtCtxt, MacResult};
use syntax::ext::build::AstBuilder;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token::{InternedString, Comma, Eof, FatArrow};
use syntax::print::pprust;
use syntax::ptr::P;
use rustc_plugin::Registry;
use phf_generator::HashState;
use std::env;

use util::{Entry, Key};
use util::{create_map, create_set, create_ordered_map, create_ordered_set};

pub mod util;
mod macros;

#[plugin_registrar]
#[doc(hidden)]
pub fn macro_registrar(reg: &mut Registry) {
    reg.register_macro("phf_map", expand_phf_map);
    reg.register_macro("phf_set", expand_phf_set);
    reg.register_macro("phf_ordered_map", expand_phf_ordered_map);
    reg.register_macro("phf_ordered_set", expand_phf_ordered_set);
}

fn generate_hash(cx: &mut ExtCtxt, sp: Span, entries: &[Entry]) -> HashState {
    #[cfg(feature = "stats")]
    use time::precise_time_s;
    #[cfg(not(feature = "stats"))]
    fn precise_time_s() -> f64 {
        0.
    }

    let start = precise_time_s();
    let state = phf_generator::generate_hash(entries);
    let time = precise_time_s() - start;

    if cfg!(feature = "stats") && env::var_os("PHF_STATS").is_some() {
        cx.parse_sess
          .span_diagnostic
          .span_note_without_error(sp, &format!("PHF generation took {} seconds", time));
    }

    state
}

fn expand_phf_map(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult + 'static> {
    let entries = match parse_map(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_map(cx, sp, entries, state)
}

fn expand_phf_set(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult + 'static> {
    let entries = match parse_set(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_set(cx, sp, entries, state)
}

fn expand_phf_ordered_map(cx: &mut ExtCtxt,
                          sp: Span,
                          tts: &[TokenTree])
                          -> Box<MacResult + 'static> {
    let entries = match parse_map(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_ordered_map(cx, sp, entries, state)
}

fn expand_phf_ordered_set(cx: &mut ExtCtxt,
                          sp: Span,
                          tts: &[TokenTree])
                          -> Box<MacResult + 'static> {
    let entries = match parse_set(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_ordered_set(cx, sp, entries, state)
}

fn parse_map(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Option<Vec<Entry>> {
    let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec());
    let mut entries = Vec::new();

    let mut bad = false;
    while parser.token != Eof {
        let key = cx.expander().fold_expr(parser.parse_expr().unwrap());
        let key_contents = parse_key(cx, &*key).unwrap_or_else(|| {
            bad = true;
            Key::Str(InternedString::new(""))
        });
        let key = adjust_key(cx, key);

        if !parser.eat(&FatArrow) {
            cx.span_err(parser.span, "expected `=>`");
            return None;
        }

        let value = parser.parse_expr().unwrap();

        entries.push(Entry {
            key_contents: key_contents,
            key: key,
            value: value,
        });

        if !parser.eat(&Comma) && parser.token != Eof {
            cx.span_err(parser.span, "expected `,`");
            return None;
        }
    }

    if bad {
        return None;
    }

    Some(entries)
}

fn parse_set(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Option<Vec<Entry>> {
    let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec());
    let mut entries = Vec::new();
    let value = quote_expr!(&*cx, ());

    let mut bad = false;
    while parser.token != Eof {
        let key = cx.expander().fold_expr(parser.parse_expr().unwrap());
        let key_contents = parse_key(cx, &*key).unwrap_or_else(|| {
            bad = true;
            Key::Str(InternedString::new(""))
        });
        let key = adjust_key(cx, key);

        entries.push(Entry {
            key_contents: key_contents,
            key: key,
            value: value.clone(),
        });

        if !parser.eat(&Comma) && parser.token != Eof {
            cx.span_err(parser.span, "expected `,`");
            return None;
        }
    }

    if bad {
        return None;
    }

    Some(entries)
}

fn parse_key(cx: &mut ExtCtxt, e: &Expr) -> Option<Key> {
    match e.node {
        ExprLit(ref lit) => {
            match lit.node {
                ast::LitStr(ref s, _) => Some(Key::Str(s.clone())),
                ast::LitByteStr(ref b) => Some(Key::Binary(b.clone())),
                ast::LitByte(b) => Some(Key::U8(b)),
                ast::LitChar(c) => Some(Key::Char(c)),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI8, ast::Plus)) => Some(Key::I8(i as i8)),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI8, ast::Minus)) =>
                    Some(Key::I8(-(i as i8))),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI16, ast::Plus)) =>
                    Some(Key::I16(i as i16)),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI16, ast::Minus)) =>
                    Some(Key::I16(-(i as i16))),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI32, ast::Plus)) =>
                    Some(Key::I32(i as i32)),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI32, ast::Minus)) =>
                    Some(Key::I32(-(i as i32))),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI64, ast::Plus)) =>
                    Some(Key::I64(i as i64)),
                ast::LitInt(i, ast::SignedIntLit(ast::TyI64, ast::Minus)) =>
                    Some(Key::I64(-(i as i64))),
                ast::LitInt(i, ast::UnsignedIntLit(ast::TyU8)) => Some(Key::U8(i as u8)),
                ast::LitInt(i, ast::UnsignedIntLit(ast::TyU16)) => Some(Key::U16(i as u16)),
                ast::LitInt(i, ast::UnsignedIntLit(ast::TyU32)) => Some(Key::U32(i as u32)),
                ast::LitInt(i, ast::UnsignedIntLit(ast::TyU64)) => Some(Key::U64(i as u64)),
                ast::LitBool(b) => Some(Key::Bool(b)),
                _ => {
                    cx.span_err(e.span, "unsupported literal type");
                    None
                }
            }
        }
        ExprVec(ref v) => {
            let bytes: Vec<Option<u8>> = v.iter().map(|expr|
                if let ExprLit(ref p) = expr.node {
                    match **p {
                        Spanned {node: ast::LitInt(val, ast::UnsignedIntLit(ast::UintTy::TyU8)), ..} if val < 256 => Some(val as u8),
                        Spanned {node: ast::LitInt(val, ast::UnsuffixedIntLit(ast::Plus)), ..} if val < 256 => Some(val as u8),
                        _ => None,
                    }
                } else {
                    None
            }).collect();
            if bytes.iter().all(|x| x.is_some()) {
                Some(Key::Binary(std::rc::Rc::new(bytes.iter().map(|x| x.unwrap()).collect())))
            } else {
                cx.span_err(e.span,
                            "not all elements of an expected u8 array literal were u8 literals");
                None
            }
        }
        _ => {
            cx.span_err(e.span, "expected a literal");
            None
        }
    }
}

fn adjust_key(cx: &mut ExtCtxt, e: P<Expr>) -> P<Expr> {
    let coerce_as_slice = match e.node {
        ExprLit(ref lit) => {
            match lit.node {
                ast::LitByteStr(_) => true,
                _ => false,
            }
        },
        _ => false,
    };
    if coerce_as_slice {
        let u8_type = cx.ty_path(cx.path_ident(e.span, cx.ident_of("u8")));
        let array_type = cx.ty(e.span, TyVec(u8_type));
        let slice_type = cx.ty_rptr(e.span, array_type, None, MutImmutable);
        cx.expr_cast(e.span, e, slice_type)
    } else {
        e
    }
}

fn has_duplicates(cx: &mut ExtCtxt, sp: Span, entries: &[Entry]) -> bool {
    let mut dups = false;
    let mut strings = HashMap::new();
    for entry in entries.iter() {
        let &mut (ref mut spans, _) = match strings.entry(&entry.key_contents) {
            Occupied(e) => e.into_mut(),
            Vacant(e) => e.insert((vec![], &entry.key)),
        };
        spans.push(entry.key.span);
    }

    for &(ref spans, key) in strings.values() {
        if spans.len() == 1 {
            continue;
        }

        dups = true;
        let mut err = cx.struct_span_err(sp, &*format!("duplicate key {}",
                                                       pprust::expr_to_string(&**key)));
        for span in spans.iter() {
            err.span_note(*span, "one occurrence here");
        }
        err.emit();
    }

    dups
}
<commit_msg>Update to Rust 2016-02-22<commit_after>//! Compiler plugin defining macros that create PHF data structures.
//!
//! # Example
//!
//! ```rust
//! #![feature(plugin, core)]
//! #![plugin(phf_macros)]
//!
//! extern crate phf;
//!
//! #[derive(Clone)]
//! pub enum Keyword {
//!     Loop,
//!     Continue,
//!     Break,
//!     Fn,
//!     Extern,
//! }
//!
//! static KEYWORDS: phf::Map<&'static str, Keyword> = phf_map! {
//!     "loop" => Keyword::Loop,
//!     "continue" => Keyword::Continue,
//!     "break" => Keyword::Break,
//!     "fn" => Keyword::Fn,
//!     "extern" => Keyword::Extern,
//! };
//!
//! pub fn parse_keyword(keyword: &str) -> Option<Keyword> {
//!     KEYWORDS.get(keyword).cloned()
//! }
//! # fn main() {}
//! ```
#![doc(html_root_url="http://sfackler.github.io/rust-phf/doc/v0.7.12")]
#![feature(plugin_registrar, quote, rustc_private)]

extern crate syntax;
#[cfg(feature = "stats")]
extern crate time;
extern crate rustc_plugin;
extern crate phf_shared;
extern crate phf_generator;

use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use syntax::ast::{self, Expr, ExprKind, Mutability, TokenTree, TyKind};
use syntax::codemap::Span;
use syntax::ext::base::{DummyResult, ExtCtxt, MacResult};
use syntax::ext::build::AstBuilder;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token::{InternedString, Comma, Eof, FatArrow};
use syntax::print::pprust;
use syntax::ptr::P;
use rustc_plugin::Registry;
use phf_generator::HashState;
use std::env;

use util::{Entry, Key};
use util::{create_map, create_set, create_ordered_map, create_ordered_set};

pub mod util;
mod macros;

#[plugin_registrar]
#[doc(hidden)]
pub fn macro_registrar(reg: &mut Registry) {
    reg.register_macro("phf_map", expand_phf_map);
    reg.register_macro("phf_set", expand_phf_set);
    reg.register_macro("phf_ordered_map", expand_phf_ordered_map);
    reg.register_macro("phf_ordered_set", expand_phf_ordered_set);
}

fn generate_hash(cx: &mut ExtCtxt, sp: Span, entries: &[Entry]) -> HashState {
    #[cfg(feature = "stats")]
    use time::precise_time_s;
    #[cfg(not(feature = "stats"))]
    fn precise_time_s() -> f64 {
        0.
    }

    let start = precise_time_s();
    let state = phf_generator::generate_hash(entries);
    let time = precise_time_s() - start;

    if cfg!(feature = "stats") && env::var_os("PHF_STATS").is_some() {
        cx.parse_sess
          .span_diagnostic
          .span_note_without_error(sp, &format!("PHF generation took {} seconds", time));
    }

    state
}

fn expand_phf_map(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult + 'static> {
    let entries = match parse_map(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_map(cx, sp, entries, state)
}

fn expand_phf_set(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult + 'static> {
    let entries = match parse_set(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_set(cx, sp, entries, state)
}

fn expand_phf_ordered_map(cx: &mut ExtCtxt,
                          sp: Span,
                          tts: &[TokenTree])
                          -> Box<MacResult + 'static> {
    let entries = match parse_map(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_ordered_map(cx, sp, entries, state)
}

fn expand_phf_ordered_set(cx: &mut ExtCtxt,
                          sp: Span,
                          tts: &[TokenTree])
                          -> Box<MacResult + 'static> {
    let entries = match parse_set(cx, tts) {
        Some(entries) => entries,
        None => return DummyResult::expr(sp),
    };

    if has_duplicates(cx, sp, &*entries) {
        return DummyResult::expr(sp);
    }

    let state = generate_hash(cx, sp, &*entries);

    create_ordered_set(cx, sp, entries, state)
}

fn parse_map(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Option<Vec<Entry>> {
    let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec());
    let mut entries = Vec::new();

    let mut bad = false;
    while parser.token != Eof {
        let key = cx.expander().fold_expr(parser.parse_expr().unwrap());
        let key_contents = parse_key(cx, &*key).unwrap_or_else(|| {
            bad = true;
            Key::Str(InternedString::new(""))
        });
        let key = adjust_key(cx, key);

        if !parser.eat(&FatArrow) {
            cx.span_err(parser.span, "expected `=>`");
            return None;
        }

        let value = parser.parse_expr().unwrap();

        entries.push(Entry {
            key_contents: key_contents,
            key: key,
            value: value,
        });

        if !parser.eat(&Comma) && parser.token != Eof {
            cx.span_err(parser.span, "expected `,`");
            return None;
        }
    }

    if bad {
        return None;
    }

    Some(entries)
}

fn parse_set(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Option<Vec<Entry>> {
    let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec());
    let mut entries = Vec::new();
    let value = quote_expr!(&*cx, ());

    let mut bad = false;
    while parser.token != Eof {
        let key = cx.expander().fold_expr(parser.parse_expr().unwrap());
        let key_contents = parse_key(cx, &*key).unwrap_or_else(|| {
            bad = true;
            Key::Str(InternedString::new(""))
        });
        let key = adjust_key(cx, key);

        entries.push(Entry {
            key_contents: key_contents,
            key: key,
            value: value.clone(),
        });

        if !parser.eat(&Comma) && parser.token != Eof {
            cx.span_err(parser.span, "expected `,`");
            return None;
        }
    }

    if bad {
        return None;
    }

    Some(entries)
}

fn parse_key(cx: &mut ExtCtxt, e: &Expr) -> Option<Key> {
    match e.node {
        ExprKind::Lit(ref lit) => {
            match lit.node {
                ast::LitKind::Str(ref s, _) => Some(Key::Str(s.clone())),
                ast::LitKind::ByteStr(ref b) => Some(Key::Binary(b.clone())),
                ast::LitKind::Byte(b) => Some(Key::U8(b)),
                ast::LitKind::Char(c) => Some(Key::Char(c)),
                ast::LitKind::Int(i, ast::LitIntType::Signed(ast::IntTy::I8)) =>
                    Some(Key::I8(i as i8)),
                ast::LitKind::Int(i, ast::LitIntType::Signed(ast::IntTy::I16)) =>
                    Some(Key::I16(i as i16)),
                ast::LitKind::Int(i, ast::LitIntType::Signed(ast::IntTy::I32)) =>
                    Some(Key::I32(i as i32)),
                ast::LitKind::Int(i, ast::LitIntType::Signed(ast::IntTy::I64)) =>
                    Some(Key::I64(i as i64)),
                ast::LitKind::Int(i, ast::LitIntType::Unsigned(ast::UintTy::U8)) =>
                    Some(Key::U8(i as u8)),
                ast::LitKind::Int(i, ast::LitIntType::Unsigned(ast::UintTy::U16)) =>
                    Some(Key::U16(i as u16)),
                ast::LitKind::Int(i, ast::LitIntType::Unsigned(ast::UintTy::U32)) =>
                    Some(Key::U32(i as u32)),
                ast::LitKind::Int(i, ast::LitIntType::Unsigned(ast::UintTy::U64)) =>
                    Some(Key::U64(i as u64)),
                ast::LitKind::Bool(b) => Some(Key::Bool(b)),
                _ => {
                    cx.span_err(e.span, "unsupported literal type");
                    None
                }
            }
        }
        ExprKind::Vec(ref v) => {
            let bytes: Vec<Option<u8>> = v.iter().map(|expr|
                if let ExprKind::Lit(ref p) = expr.node {
                    match p.node {
                        ast::LitKind::Int(val, ast::LitIntType::Unsigned(ast::UintTy::U8)) if val < 256 =>
                            Some(val as u8),
                        ast::LitKind::Int(val, ast::LitIntType::Unsuffixed) if val < 256 =>
                            Some(val as u8),
                        _ => None,
                    }
                } else {
                    None
            }).collect();
            if bytes.iter().all(|x| x.is_some()) {
                Some(Key::Binary(std::rc::Rc::new(bytes.iter().map(|x| x.unwrap()).collect())))
            } else {
                cx.span_err(e.span,
                            "not all elements of an expected u8 array literal were u8 literals");
                None
            }
        }
        _ => {
            cx.span_err(e.span, "expected a literal");
            None
        }
    }
}

fn adjust_key(cx: &mut ExtCtxt, e: P<Expr>) -> P<Expr> {
    let coerce_as_slice = match e.node {
        ExprKind::Lit(ref lit) => {
            match lit.node {
                ast::LitKind::ByteStr(_) => true,
                _ => false,
            }
        },
        _ => false,
    };
    if coerce_as_slice {
        let u8_type = cx.ty_path(cx.path_ident(e.span, cx.ident_of("u8")));
        let array_type = cx.ty(e.span, TyKind::Vec(u8_type));
        let slice_type = cx.ty_rptr(e.span, array_type, None, Mutability::Immutable);
        cx.expr_cast(e.span, e, slice_type)
    } else {
        e
    }
}

fn has_duplicates(cx: &mut ExtCtxt, sp: Span, entries: &[Entry]) -> bool {
    let mut dups = false;
    let mut strings = HashMap::new();
    for entry in entries.iter() {
        let &mut (ref mut spans, _) = match strings.entry(&entry.key_contents) {
            Occupied(e) => e.into_mut(),
            Vacant(e) => e.insert((vec![], &entry.key)),
        };
        spans.push(entry.key.span);
    }

    for &(ref spans, key) in strings.values() {
        if spans.len() == 1 {
            continue;
        }

        dups = true;
        let mut err = cx.struct_span_err(sp, &*format!("duplicate key {}",
                                                       pprust::expr_to_string(&**key)));
        for span in spans.iter() {
            err.span_note(*span, "one occurrence here");
        }
        err.emit();
    }

    dups
}
<|endoftext|>


<commit_before>#![feature(core)]

use std::num::Float;
use std::collections::binary_heap::BinaryHeap; // pq
use std::cmp::Ordering;

type float = f64;
type time = u64;

const TIME_RESOLUTION: time = 1000_000; // in micro seconds.

#[derive(Debug, Copy)]
struct NeuronConfig {
    arp:       time,
    tau_m:     float,
    tau_r:     float,
    weight_r:  float,
    threshold: float,
    record:    Option<&'static str>,
}

#[derive(Debug, Copy)]
struct NeuronConfigId(usize);

#[derive(Debug, Copy)]
struct Neuron {
    /// End of absolute refractory period
    arp_end:         time,
    last_spike_time: time,
    mem_pot:         float,

    /// An index into a [NeuronConfig] table.
    config_id:       NeuronConfigId,
}

#[derive(Debug, Copy)]
struct NeuronId(usize);

#[derive(Debug, Copy)]
enum NeuronResult {
    InArp,
    NoFire,
    Fire
}

impl Neuron {
    fn new(config_id: NeuronConfigId) -> Neuron {
        Neuron {
            arp_end: 0,
            last_spike_time: 0,
            mem_pot: 0.0,
            config_id: config_id,
        }
    }

    fn spike(&mut self, timestamp: time, weight: float, cfg: &NeuronConfig) -> NeuronResult {
        assert!(timestamp >= self.last_spike_time);
        assert!(cfg.tau_m >= 0.0);

        // Return early if still in absolute refractory period (arp)
        if timestamp < self.arp_end {
            return NeuronResult::InArp;
        }

        // Time since end of last absolute refractory period (arp)
        assert!(timestamp >= self.arp_end);
        let delta = timestamp - self.arp_end;

        // Convert delta to float
        let delta: float = (delta as float) / TIME_RESOLUTION as float;

        // Calculate dynamic threshold
        let dyn_threshold = cfg.threshold +
                            cfg.weight_r * (-delta / cfg.tau_r).exp();

        // Update memory potential
        if cfg.tau_m > 0.0 {

            let d = timestamp - self.last_spike_time;
            // Convert delta to float
            let d: float = (d as float) / TIME_RESOLUTION as float;

            let decay = (-d / cfg.tau_m).exp();
            self.mem_pot *= decay;
            self.mem_pot += weight;
        }
        else {
            self.mem_pot = weight;
        }

        // Update last spike time
        self.last_spike_time = timestamp;

        if self.mem_pot >= dyn_threshold {
            self.arp_end = timestamp + cfg.arp;
            NeuronResult::Fire
        }
        else {
            NeuronResult::NoFire
        }
    }
}

#[derive(Debug)]
struct Event {
    time:   time,
    weight: float,
    target: NeuronId
}

impl PartialEq for Event {
    fn eq(&self, other: &Self) -> bool {
        self.time == other.time
    }
}

impl Eq for Event {}

impl PartialOrd for Event {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.time.partial_cmp(&other.time).map(|o| o.reverse())
    }
}

impl Ord for Event {
    fn cmp(&self, other: &Self) -> Ordering {
        self.time.cmp(&other.time).reverse()
    }
}

fn ms(n: time) -> time { n * 1000 }
fn us(n: time) -> time { n }

#[derive(Debug)]
struct Synapse {
    delay:  time,
    weight: float,
    post_neuron: NeuronId,
}

struct Net {
    neurons: Vec<Neuron>,
    neuron_configs: Vec<NeuronConfig>,
    synapses: Vec<Vec<Synapse>>,
    events: BinaryHeap<Event>,
}

impl Net {
    fn new() -> Net {
        Net {
            neurons: vec![],
            neuron_configs: vec![],
            synapses: vec![],
            events: BinaryHeap::new(),
        }
    }

    fn create_neuron_config(&mut self, config: NeuronConfig) -> NeuronConfigId {
        self.neuron_configs.push(config);
        NeuronConfigId(self.neuron_configs.len() - 1)
    }

    fn create_neuron(&mut self, config_id: NeuronConfigId) -> NeuronId {
        self.neurons.push(Neuron::new(config_id));
        self.synapses.push(vec![]);
        NeuronId(self.neurons.len() - 1)
    }

    fn create_synapse(&mut self, from_neuron: NeuronId, synapse: Synapse) {
        let mut syn_arr = &mut (self.synapses.as_mut_slice())[from_neuron.0];
        syn_arr.push(synapse);
    }

    fn add_event(&mut self, event: Event) {
        self.events.push(event);
    }

    fn fire(&mut self, timestamp: time, neuron_id: NeuronId) {
        for syn in &self.synapses[neuron_id.0] {
            println!("{:?}", syn);
            self.events.push(Event {
                time: timestamp + syn.delay,
                weight: syn.weight,
                target: syn.post_neuron
            });
        }

        if let Some(ident) = self.get_config_for_neuron_id(neuron_id).record {
            println!("RECORD\t{}\t{}\t{}", ident, neuron_id.0, timestamp);
        }
    }

    fn get_neuron(&self, neuron_id: NeuronId) -> &Neuron {
        &self.neurons[neuron_id.0]
    }

    fn get_config_for_neuron<'a>(&'a self, neuron: &Neuron) -> &'a NeuronConfig {
        &(self.neuron_configs.as_slice())[neuron.config_id.0]
    }

    fn get_config_for_neuron_id(&self, neuron_id: NeuronId) -> &NeuronConfig {
        self.get_config_for_neuron(self.get_neuron(neuron_id))
    }

    fn simulate(&mut self) {
	loop {
	    println!("-------------------------------------");

	    if let Some(ev) = self.events.pop() {
		println!("{:?}", ev);
                let neuron_id = ev.target;
                let fire = {
		    let neuron = &mut (self.neurons.as_mut_slice())[neuron_id.0];
                    let cfg = &(self.neuron_configs.as_slice())[neuron.config_id.0];
		    let fire = neuron.spike(ev.time, ev.weight, cfg);
		    println!("{:?}", fire);
		    println!("{:?}", neuron);
                    fire
                };
                match fire {
                    NeuronResult::Fire => {
                        // Post a new event to all synapses
                        self.fire(ev.time, neuron_id);
                    }
                    _ => {
                    }
                }
	    }
	    else {
		break;
	    }
	}
    }
}

fn main() {
    let mut net = Net::new();

    let input_neuron_template = NeuronConfig {
        arp: ms(1),
        tau_m: 0.0,
        tau_r: 0.5,
        weight_r: 0.0,
        threshold: 0.6,
        record: None
    };

    // Koinzidenz neurons
    let cfg_k = net.create_neuron_config(NeuronConfig {
        arp: us(500), // 0.5 ms = 500 us
        tau_m: 0.04,
        tau_r: 0.5,
        weight_r: 0.0,
        threshold: 1.1,
        record: None,
    });

    // Input neurons
    let cfg_i1 = net.create_neuron_config(NeuronConfig {
        record: Some("input1"),
        ..input_neuron_template
    });
    let cfg_i2 = net.create_neuron_config(NeuronConfig {
        record: Some("input2"),
        ..input_neuron_template
    });

    let inp1 = net.create_neuron(cfg_i1);
    let inp2 = net.create_neuron(cfg_i2);

    net.create_synapse(inp1, Synapse {delay: us(160), weight: 1.0, post_neuron: inp2});

    // Fill event queue with events
    for i in 1..100 {
        let ev = Event {
            time:   ms(i) / 10,
            weight: 0.6,
            target: inp1
        };

        net.add_event(ev);
    }

    net.simulate();
}
<commit_msg>Add example net (Jeffress) from Johannes diploma thesis<commit_after>#![feature(core)]

use std::num::Float;
use std::collections::binary_heap::BinaryHeap; // pq
use std::cmp::Ordering;

type float = f64;
type time = u64;

const TIME_RESOLUTION: time = 1000_000; // in micro seconds.

#[derive(Debug, Copy)]
struct NeuronConfig {
    arp:       time,
    tau_m:     float,
    tau_r:     float,
    weight_r:  float,
    threshold: float,
    record:    Option<&'static str>,
}

#[derive(Debug, Copy)]
struct NeuronConfigId(usize);

#[derive(Debug, Copy)]
struct Neuron {
    /// End of absolute refractory period
    arp_end:         time,
    last_spike_time: time,
    mem_pot:         float,

    /// An index into a [NeuronConfig] table.
    config_id:       NeuronConfigId,
}

#[derive(Debug, Copy)]
struct NeuronId(usize);

#[derive(Debug, Copy)]
enum NeuronResult {
    InArp,
    NoFire,
    Fire
}

impl Neuron {
    fn new(config_id: NeuronConfigId) -> Neuron {
        Neuron {
            arp_end: 0,
            last_spike_time: 0,
            mem_pot: 0.0,
            config_id: config_id,
        }
    }

    fn spike(&mut self, timestamp: time, weight: float, cfg: &NeuronConfig) -> NeuronResult {
        assert!(timestamp >= self.last_spike_time);
        assert!(cfg.tau_m >= 0.0);

        // Return early if still in absolute refractory period (arp)
        if timestamp < self.arp_end {
            return NeuronResult::InArp;
        }

        // Time since end of last absolute refractory period (arp)
        assert!(timestamp >= self.arp_end);
        let delta = timestamp - self.arp_end;

        // Convert delta to float
        let delta: float = (delta as float) / TIME_RESOLUTION as float;

        // Calculate dynamic threshold
        let dyn_threshold = cfg.threshold +
                            cfg.weight_r * (-delta / cfg.tau_r).exp();

        // Update memory potential
        if cfg.tau_m > 0.0 {

            let d = timestamp - self.last_spike_time;
            // Convert delta to float
            let d: float = (d as float) / TIME_RESOLUTION as float;

            let decay = (-d / cfg.tau_m).exp();
            self.mem_pot *= decay;
            self.mem_pot += weight;
        }
        else {
            self.mem_pot = weight;
        }

        // Update last spike time
        self.last_spike_time = timestamp;

        if self.mem_pot >= dyn_threshold {
            self.arp_end = timestamp + cfg.arp;
            NeuronResult::Fire
        }
        else {
            NeuronResult::NoFire
        }
    }
}

#[derive(Debug)]
struct Event {
    time:   time,
    weight: float,
    target: NeuronId
}

impl PartialEq for Event {
    fn eq(&self, other: &Self) -> bool {
        self.time == other.time
    }
}

impl Eq for Event {}

impl PartialOrd for Event {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.time.partial_cmp(&other.time).map(|o| o.reverse())
    }
}

impl Ord for Event {
    fn cmp(&self, other: &Self) -> Ordering {
        self.time.cmp(&other.time).reverse()
    }
}

fn ms(n: time) -> time { n * 1000 }
fn us(n: time) -> time { n }

#[derive(Debug)]
struct Synapse {
    delay:  time,
    weight: float,
    post_neuron: NeuronId,
}

struct Net {
    neurons: Vec<Neuron>,
    neuron_configs: Vec<NeuronConfig>,
    synapses: Vec<Vec<Synapse>>,
    events: BinaryHeap<Event>,
}

impl Net {
    fn new() -> Net {
        Net {
            neurons: vec![],
            neuron_configs: vec![],
            synapses: vec![],
            events: BinaryHeap::new(),
        }
    }

    fn create_neuron_config(&mut self, config: NeuronConfig) -> NeuronConfigId {
        self.neuron_configs.push(config);
        NeuronConfigId(self.neuron_configs.len() - 1)
    }

    fn create_neuron(&mut self, config_id: NeuronConfigId) -> NeuronId {
        self.neurons.push(Neuron::new(config_id));
        self.synapses.push(vec![]);
        NeuronId(self.neurons.len() - 1)
    }

    fn create_synapse(&mut self, from_neuron: NeuronId, synapse: Synapse) {
        let mut syn_arr = &mut (self.synapses.as_mut_slice())[from_neuron.0];
        syn_arr.push(synapse);
    }

    fn add_event(&mut self, event: Event) {
        self.events.push(event);
    }

    // values are in ms
    fn add_spike_train_float_ms(&mut self, target: NeuronId, weight: float, spikes: &[float]) {
        for &t in spikes {
            self.add_event(Event {
                time: (t * 1000.0) as time, // convert to us
                weight: weight,
                target: target
            });
        }
    }

    fn fire(&mut self, timestamp: time, neuron_id: NeuronId) {
        for syn in &self.synapses[neuron_id.0] {
            println!("{:?}", syn);
            self.events.push(Event {
                time: timestamp + syn.delay,
                weight: syn.weight,
                target: syn.post_neuron
            });
        }

        if let Some(ident) = self.get_config_for_neuron_id(neuron_id).record {
            println!("RECORD\t{}\t{}\t{}", ident, neuron_id.0, timestamp);
        }
    }

    fn get_neuron(&self, neuron_id: NeuronId) -> &Neuron {
        &self.neurons[neuron_id.0]
    }

    fn get_config_for_neuron<'a>(&'a self, neuron: &Neuron) -> &'a NeuronConfig {
        &(self.neuron_configs.as_slice())[neuron.config_id.0]
    }

    fn get_config_for_neuron_id(&self, neuron_id: NeuronId) -> &NeuronConfig {
        self.get_config_for_neuron(self.get_neuron(neuron_id))
    }

    fn simulate(&mut self) {
	loop {
	    println!("-------------------------------------");

	    if let Some(ev) = self.events.pop() {
		println!("{:?}", ev);
                let neuron_id = ev.target;
                let fire = {
		    let neuron = &mut (self.neurons.as_mut_slice())[neuron_id.0];
                    let cfg = &(self.neuron_configs.as_slice())[neuron.config_id.0];
		    let fire = neuron.spike(ev.time, ev.weight, cfg);
		    println!("{:?}", fire);
		    println!("{:?}", neuron);
                    fire
                };
                match fire {
                    NeuronResult::Fire => {
                        // Post a new event to all synapses
                        self.fire(ev.time, neuron_id);
                    }
                    _ => {
                    }
                }
	    }
	    else {
		break;
	    }
	}
    }
}

// From Optimierung-1/stimuli.txt

const spikes_input_0: [float; 49] = [
    0.38, 3.38, 6.38, 9.38, 12.38, 15.38, 18.38,
    21.38, 24.38, 27.38, 30.38, 33.38, 36.38, 39.38,
    42.38, 45.38, 48.38, 52.98, 55.98, 58.98,
    61.98, 64.98, 67.98, 70.98, 73.98, 76.98, 79.98,
    82.98, 85.98, 88.98, 91.98, 94.98, 97.98,
    103.59, 106.59, 109.59, 112.59, 115.59, 118.59,
    121.59, 124.59, 127.59, 130.59, 133.59, 136.59, 139.59,
    142.59, 145.59, 148.59
];

const spikes_input_1: [float; 49] = [
    1.0, 4.0, 7.0, 10.0, 13.0, 16.0, 19.0,
    22.0, 25.0, 28.0, 31.0, 34.0, 37.0,
    40.0, 43.0, 46.0, 49.0, 53.0, 56.0, 59.0,
    62.0, 65.0, 68.0, 71.0, 74.0, 77.0,
    80.0, 83.0, 86.0, 89.0, 92.0, 95.0, 98.0,
    103.0, 106.0, 109.0, 112.0, 115.0, 118.0,
    121.0, 124.0, 127.0, 130.0, 133.0, 136.0, 139.0,
    142.0, 145.0, 148.0
];

const correct_output_0: (float, float) = (  0.0,  47.0);
const correct_output_1: (float, float) = ( 47.0, 100.0);
const correct_output_2: (float, float) = (100.0, 170.0);

fn main() {
    let mut net = Net::new();

    let input_neuron_template = NeuronConfig {
        arp: ms(0),
        tau_m: 0.0,
        tau_r: 0.0,
        weight_r: 0.0,
        threshold: 0.0,
        record: Some("input"),
    };
    let output_neuron_template = NeuronConfig {
        arp: ms(0),
        tau_m: 0.0,
        tau_r: 0.0,
        weight_r: 0.0,
        threshold: 0.609375,
        record: Some("output"),
    };

    let cfg_input0 = net.create_neuron_config(NeuronConfig {
        record: Some("input0"),
        ..input_neuron_template
    });
    let cfg_input1 = net.create_neuron_config(NeuronConfig {
        record: Some("input1"),
        ..input_neuron_template
    });
    let cfg_output0 = net.create_neuron_config(NeuronConfig {
        record: Some("output0"),
        ..output_neuron_template
    });
    let cfg_output1 = net.create_neuron_config(NeuronConfig {
        record: Some("output1"),
        ..output_neuron_template
    });
    let cfg_output2 = net.create_neuron_config(NeuronConfig {
        record: Some("output2"),
        ..output_neuron_template
    });
    let cfg_innerinp = net.create_neuron_config(NeuronConfig {
        arp: ms(1),
        tau_m: 0.0,
        tau_r: 0.0,
        weight_r: 0.0,
        threshold: 0.59375,
        record: None,
    });
    // Koinzidenz neurons
    let cfg_k = net.create_neuron_config(NeuronConfig {
        arp: us(500), // 0.5 ms = 500 us
        tau_m: 0.046875,
        tau_r: 0.0,
        weight_r: 0.0,
        threshold: 1.09375,
        record: None,
    });

    let n_input0 = net.create_neuron(cfg_input0);
    let n_input1 = net.create_neuron(cfg_input1);
    let n_output0 = net.create_neuron(cfg_output0);
    let n_output1 = net.create_neuron(cfg_output1);
    let n_output2 = net.create_neuron(cfg_output2);
    let n_innerinp0 = net.create_neuron(cfg_innerinp);
    let n_innerinp1 = net.create_neuron(cfg_innerinp);
    let n_k0 = net.create_neuron(cfg_k);
    let n_k1 = net.create_neuron(cfg_k);
    let n_k2 = net.create_neuron(cfg_k);

    net.create_synapse(n_input0, Synapse {delay: us(0), weight: 1.0, post_neuron: n_innerinp0});
    net.create_synapse(n_input1, Synapse {delay: us(0), weight: 1.0, post_neuron: n_innerinp1});
    net.create_synapse(n_k0, Synapse {delay: us(0), weight: 1.0, post_neuron: n_output0});
    net.create_synapse(n_k1, Synapse {delay: us(0), weight: 1.0, post_neuron: n_output1});
    net.create_synapse(n_k2, Synapse {delay: us(0), weight: 1.0, post_neuron: n_output2});

    net.create_synapse(n_innerinp0, Synapse {delay: us(625), weight: 1.0, post_neuron: n_k0});
    net.create_synapse(n_innerinp0, Synapse {delay: us(15), weight: 1.0, post_neuron: n_k1}); // 0.015625
    net.create_synapse(n_innerinp0, Synapse {delay: us(0), weight: 1.0, post_neuron: n_k2});

    net.create_synapse(n_innerinp1, Synapse {delay: us(0), weight: 1.0, post_neuron: n_k0});
    //net.create_synapse(n_innerinp1, Synapse {delay: us(0), weight: 1.0, post_neuron: n_k1});
    net.create_synapse(n_innerinp1, Synapse {delay: us(15), weight: 1.0, post_neuron: n_k1});
    net.create_synapse(n_innerinp1, Synapse {delay: us(593), weight: 1.0, post_neuron: n_k2});

    net.add_spike_train_float_ms(n_input0, 1.0, &spikes_input_0);
    net.add_spike_train_float_ms(n_input1, 1.0, &spikes_input_1);

    net.simulate();
}
<|endoftext|>


<commit_before>#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate sdl2;
extern crate rand;

use std::{thread, time};

use rand::Rng;

use sdl2::rect::Rect;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::render::Renderer;
use sdl2::EventPump;

const MAX_X: usize = 49;
const MAX_Y: usize = 49;
const CELL_WIDTH: isize = 25;
const CELL_HEIGHT: isize = 25;
const NCELLS: usize = (MAX_Y + 1) * (MAX_X + 1);
const FRAMETIME: u64 = 100;

fn init<'a>() -> (Renderer<'a>, EventPump) {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem.window("Conway's Game of Life",
                ((MAX_X + 1) * CELL_WIDTH as usize) as u32,
                ((MAX_Y + 1) * CELL_HEIGHT as usize) as u32)
        .position_centered()
        .opengl()
        .build()
        .unwrap();

    let mut renderer = window.renderer().build().unwrap();

    let event_pump = sdl_context.event_pump().unwrap();

    renderer.set_draw_color(Color::RGB(255, 255, 255));
    renderer.clear();
    renderer.present();

    (renderer, event_pump)
}

fn get_cell(cells: &[bool], i: usize) -> Option<bool> {
    let (x, y) = get_coords(i);
    if let Some(i) = get_index(x, y) {
        Some(cells[i])
    } else {
        None
    }
}

fn count_neighbors(cells: &[bool], i: usize) -> i32 {
    let mut counter = 0;
    let (origx, origy) = get_coords(i);
    for ty in -1isize..2isize {
        for tx in (-1isize..2isize).filter(|tx| *tx != 0 || ty != 0) {
            if let Some(i) = get_index((origx as isize + tx), origy as isize + ty) {
                if let Some(x) = get_cell(cells, i) {
                    if x {
                        counter += 1;
                    }
                }
            }
        }
    }
    counter
}

fn toggle_field(x: isize, y: isize, cells: &mut Vec<bool>) {
    let cell_x = x / CELL_WIDTH;
    let cell_y = y / CELL_HEIGHT;
    cells[get_index(cell_x, cell_y).unwrap()] = !cells[get_index(cell_x, cell_y).unwrap()]
}

fn get_index(x: isize, y: isize) -> Option<usize> {
    if x < 0 || y < 0 || x > MAX_X as isize || y > MAX_Y as isize {
        None
    } else {
        Some((x + (y * (MAX_X + 1) as isize)) as usize)
    }
}

fn get_coords(i: usize) -> (isize, isize) {
    ((i % (MAX_X + 1)) as isize, (i / (MAX_X + 1)) as isize)
}

fn main() {
    let mut rng = rand::thread_rng();
    let (mut r, mut events) = init();
    let bg = Color::RGB(0xff, 0xff, 0xff);
    let fg = Color::RGB(0, 0, 0);
    let mut cells: Vec<bool> = Vec::with_capacity(NCELLS as usize);
    let mut paused: bool = false;

    for _ in 0..NCELLS {
        cells.push(rng.gen());
    }

    'running: loop {
        let timer = thread::spawn(|| thread::sleep(time::Duration::from_millis(FRAMETIME)));
        for event in events.poll_iter() {
            match event {
                Event::KeyDown { keycode: Some(Keycode::Escape), .. } |
                Event::Quit { .. } => break 'running,
                Event::KeyDown { keycode: Some(Keycode::Space), .. } => paused = !paused,
                Event::KeyDown { keycode: Some(Keycode::F), .. } => {
                    for cell in &mut cells {
                        *cell = true;
                    }
                }
                Event::KeyDown { keycode: Some(Keycode::C), .. } => {
                    for cell in &mut cells {
                        *cell = false;
                    }
                }
                Event::MouseButtonDown { x, y, .. } => {
                    if paused {
                        toggle_field(x as isize, y as isize, &mut cells);
                    }
                }
                _ => {}
            }
        }

        r.set_draw_color(bg);
        r.clear();
        r.set_draw_color(fg);
        for (cell, i) in cells.iter().zip(0..NCELLS) {
            if *cell {
                let (x, y) = get_coords(i);
                r.fill_rect(Rect::new((x * CELL_WIDTH) as i32,
                                         (y * CELL_HEIGHT) as i32,
                                         CELL_WIDTH as u32,
                                         CELL_HEIGHT as u32))
                    .unwrap();
            }
        }

        r.present();

        if !paused {
            let old_cells = cells.clone();
            for (cell, i) in old_cells.iter().zip(0usize..(NCELLS as usize)) {
                let neighbors = count_neighbors(&old_cells, i);
                if *cell {
                    if neighbors < 2 || neighbors > 3 {
                        cells[i] = false;
                    } else {
                        cells[i] = true;
                    }
                } else if neighbors == 3 {
                    cells[i] = true;
                } else {
                    cells[i] = false;

                }
            }
        }
        timer.join().unwrap();

    }
}
<commit_msg>made default constants reasonable<commit_after>#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate sdl2;
extern crate rand;

use std::{thread, time};

use rand::Rng;

use sdl2::rect::Rect;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::render::Renderer;
use sdl2::EventPump;

const MAX_X: usize = 199;
const MAX_Y: usize = 199;
const CELL_WIDTH: isize = 5;
const CELL_HEIGHT: isize = 5;
const NCELLS: usize = (MAX_Y + 1) * (MAX_X + 1);
const FRAMETIME: u64 = 1000 / 30;

fn init<'a>() -> (Renderer<'a>, EventPump) {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem.window("Conway's Game of Life",
                ((MAX_X + 1) * CELL_WIDTH as usize) as u32,
                ((MAX_Y + 1) * CELL_HEIGHT as usize) as u32)
        .position_centered()
        .opengl()
        .build()
        .unwrap();

    let mut renderer = window.renderer().build().unwrap();

    let event_pump = sdl_context.event_pump().unwrap();

    renderer.set_draw_color(Color::RGB(255, 255, 255));
    renderer.clear();
    renderer.present();

    (renderer, event_pump)
}

fn get_cell(cells: &[bool], i: usize) -> Option<bool> {
    let (x, y) = get_coords(i);
    if let Some(i) = get_index(x, y) {
        Some(cells[i])
    } else {
        None
    }
}

fn count_neighbors(cells: &[bool], i: usize) -> i32 {
    let mut counter = 0;
    let (origx, origy) = get_coords(i);
    for ty in -1isize..2isize {
        for tx in (-1isize..2isize).filter(|tx| *tx != 0 || ty != 0) {
            if let Some(i) = get_index((origx as isize + tx), origy as isize + ty) {
                if let Some(x) = get_cell(cells, i) {
                    if x {
                        counter += 1;
                    }
                }
            }
        }
    }
    counter
}

fn toggle_field(x: isize, y: isize, cells: &mut Vec<bool>) {
    let cell_x = x / CELL_WIDTH;
    let cell_y = y / CELL_HEIGHT;
    cells[get_index(cell_x, cell_y).unwrap()] = !cells[get_index(cell_x, cell_y).unwrap()]
}

fn get_index(x: isize, y: isize) -> Option<usize> {
    if x < 0 || y < 0 || x > MAX_X as isize || y > MAX_Y as isize {
        None
    } else {
        Some((x + (y * (MAX_X + 1) as isize)) as usize)
    }
}

fn get_coords(i: usize) -> (isize, isize) {
    ((i % (MAX_X + 1)) as isize, (i / (MAX_X + 1)) as isize)
}

fn main() {
    let mut rng = rand::thread_rng();
    let (mut r, mut events) = init();
    let bg = Color::RGB(0xff, 0xff, 0xff);
    let fg = Color::RGB(0, 0, 0);
    let mut cells: Vec<bool> = Vec::with_capacity(NCELLS as usize);
    let mut paused: bool = false;

    for _ in 0..NCELLS {
        cells.push(rng.gen());
    }

    'running: loop {
        let timer = thread::spawn(|| thread::sleep(time::Duration::from_millis(FRAMETIME)));
        for event in events.poll_iter() {
            match event {
                Event::KeyDown { keycode: Some(Keycode::Escape), .. } |
                Event::Quit { .. } => break 'running,
                Event::KeyDown { keycode: Some(Keycode::Space), .. } => paused = !paused,
                Event::KeyDown { keycode: Some(Keycode::F), .. } => {
                    for cell in &mut cells {
                        *cell = true;
                    }
                }
                Event::KeyDown { keycode: Some(Keycode::C), .. } => {
                    for cell in &mut cells {
                        *cell = false;
                    }
                }
                Event::MouseButtonDown { x, y, .. } => {
                    if paused {
                        toggle_field(x as isize, y as isize, &mut cells);
                    }
                }
                _ => {}
            }
        }

        r.set_draw_color(bg);
        r.clear();
        r.set_draw_color(fg);
        for (cell, i) in cells.iter().zip(0..NCELLS) {
            if *cell {
                let (x, y) = get_coords(i);
                r.fill_rect(Rect::new((x * CELL_WIDTH) as i32,
                                         (y * CELL_HEIGHT) as i32,
                                         CELL_WIDTH as u32,
                                         CELL_HEIGHT as u32))
                    .unwrap();
            }
        }

        r.present();

        if !paused {
            let old_cells = cells.clone();
            for (cell, i) in old_cells.iter().zip(0usize..(NCELLS as usize)) {
                let neighbors = count_neighbors(&old_cells, i);
                if *cell {
                    if neighbors < 2 || neighbors > 3 {
                        cells[i] = false;
                    } else {
                        cells[i] = true;
                    }
                } else if neighbors == 3 {
                    cells[i] = true;
                } else {
                    cells[i] = false;

                }
            }
        }
        timer.join().unwrap();

    }
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2016, Boris Popov <popov@whitekefir.ru>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#![allow(non_snake_case)]

extern crate libc;

mod forker;
mod logger;

use forker::hello;
//use forker::hello;
//use libc;
//use libc::fork;
//use libc::exit;

fn main() {
    println!("Hello, world!");
    hello();

    let x: i32;
    unsafe {
        x = libc::fork();
    }

    if x == 0 {
        unsafe {
            libc::sleep(10);
            libc::exit(2);
        }
    }
    /*
    unsafe {
        sleep(5);
    }
     */
    //pub unsafe extern fn fork() -> pid_t
    println!("Exit!");
}
<commit_msg>fix main()<commit_after>//
// Copyright (c) 2016, Boris Popov <popov@whitekefir.ru>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#![allow(non_snake_case)]

mod forker;
mod worker;

fn main() {

    let forker = forker::Forker::new();
    forker.spawn();
}
<|endoftext|>


<commit_before>#![feature(alloc_system)]
extern crate alloc_system;

#[macro_use]
extern crate log;
extern crate getopts;
#[macro_use]
extern crate shoop;

use std::str;
use std::env;
use getopts::Options;
use shoop::{ShoopLogger, ShoopMode, TransferMode, Target, Server, Client};
use shoop::connection::PortRange;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const DEFAULT_PORT_RANGE: &'static str = "55000-55050";

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Shoop is a ultrafast, (hopefully) secure file transfer tool, that is
(hopefully) ideal for transferring large files.

Usage: {0} [options] SOURCE DEST
...where HOST is an SSH host
...where PATH is the path on the *remote* machine of the file you want
...where DEST is either an existing folder or a location for the new
                 file (\".\" by default)

Example: {0} seedbox.facebook.com:/home/zuck/internalized_sadness.zip .",
                        program);
    print!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    // TODO
    // opts.optopt("o", "output", "set output file name", "NAME");
    // opts.optopt("a", "ssh-args", "arguments to pass to ssh directly (at your own risk)", ARGS);
    opts.optopt("p",
                "port-range",
                "server listening port range",
                DEFAULT_PORT_RANGE);
    opts.optflag("f", "force", "force overwrite (client only)");
    opts.optflag("r", "receive", "receive mode (server mode only)");
    opts.optflag("s", "server", "server mode (advanced usage only)");
    opts.optflag("h", "help", "print this help menu");
    opts.optflag("v", "version", "print the version");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    if matches.opt_present("v") {
        println!("shoop {}", VERSION);
        return;
    }

    let raw_source = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    let mode = if matches.opt_present("s") {
        ShoopMode::Server
    } else {
        ShoopMode::Client
    };

    let port_range = {
        let range_opt = &matches.opt_str("p").unwrap_or_else(|| String::from(DEFAULT_PORT_RANGE));
        PortRange::from(range_opt).unwrap()
    };

    ShoopLogger::init(mode).expect("Error starting shoop logger.");

    match mode {
        ShoopMode::Server => {
            let transfer_mode = if matches.opt_present("r") {
                TransferMode::Receive
            } else {
                TransferMode::Send
            };

            if let Ok(mut server) = Server::new(port_range, &raw_source) {
                server.start(transfer_mode);
                info!("exiting.");
            }
        }
        ShoopMode::Client => {
            let raw_dest = if matches.free.len() > 1 {
                matches.free[1].clone()
            } else {
                String::from(".")
            };

            let source = Target::from(raw_source.clone());
            let dest = Target::from(raw_dest.clone());

            match Client::new(source, dest, port_range) {
                Ok(mut client) => client.start(matches.opt_present("f")),
                Err(e) => error!("{}", e),
            }
        }
    }
}
<commit_msg>disable system allocator, valgrind isn't that helpful anyway<commit_after>// #![feature(alloc_system)]
// extern crate alloc_system;

#[macro_use]
extern crate log;
extern crate getopts;
#[macro_use]
extern crate shoop;

use std::str;
use std::env;
use getopts::Options;
use shoop::{ShoopLogger, ShoopMode, TransferMode, Target, Server, Client};
use shoop::connection::PortRange;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const DEFAULT_PORT_RANGE: &'static str = "55000-55050";

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Shoop is a ultrafast, (hopefully) secure file transfer tool, that is
(hopefully) ideal for transferring large files.

Usage: {0} [options] SOURCE DEST
...where HOST is an SSH host
...where PATH is the path on the *remote* machine of the file you want
...where DEST is either an existing folder or a location for the new
                 file (\".\" by default)

Example: {0} seedbox.facebook.com:/home/zuck/internalized_sadness.zip .",
                        program);
    print!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    // TODO
    // opts.optopt("o", "output", "set output file name", "NAME");
    // opts.optopt("a", "ssh-args", "arguments to pass to ssh directly (at your own risk)", ARGS);
    opts.optopt("p",
                "port-range",
                "server listening port range",
                DEFAULT_PORT_RANGE);
    opts.optflag("f", "force", "force overwrite (client only)");
    opts.optflag("r", "receive", "receive mode (server mode only)");
    opts.optflag("s", "server", "server mode (advanced usage only)");
    opts.optflag("h", "help", "print this help menu");
    opts.optflag("v", "version", "print the version");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    if matches.opt_present("v") {
        println!("shoop {}", VERSION);
        return;
    }

    let raw_source = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    let mode = if matches.opt_present("s") {
        ShoopMode::Server
    } else {
        ShoopMode::Client
    };

    let port_range = {
        let range_opt = &matches.opt_str("p").unwrap_or_else(|| String::from(DEFAULT_PORT_RANGE));
        PortRange::from(range_opt).unwrap()
    };

    ShoopLogger::init(mode).expect("Error starting shoop logger.");

    match mode {
        ShoopMode::Server => {
            let transfer_mode = if matches.opt_present("r") {
                TransferMode::Receive
            } else {
                TransferMode::Send
            };

            if let Ok(mut server) = Server::new(port_range, &raw_source) {
                server.start(transfer_mode);
                info!("exiting.");
            }
        }
        ShoopMode::Client => {
            let raw_dest = if matches.free.len() > 1 {
                matches.free[1].clone()
            } else {
                String::from(".")
            };

            let source = Target::from(raw_source.clone());
            let dest = Target::from(raw_dest.clone());

            match Client::new(source, dest, port_range) {
                Ok(mut client) => client.start(matches.opt_present("f")),
                Err(e) => error!("{}", e),
            }
        }
    }
}
<|endoftext|>