<commit_before>use core::ops::Deref;
use core_collections::borrow::ToOwned;
use io::{self, Read, Error, Result, Write, Seek, SeekFrom};
use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use mem;
use path::{PathBuf, Path};
use str;
use string::String;
use sys_common::AsInner;
use vec::Vec;

use system::syscall::{sys_open, sys_dup, sys_close, sys_fpath, sys_ftruncate, sys_read,
              sys_write, sys_lseek, sys_fsync, sys_mkdir, sys_rmdir, sys_stat, sys_unlink};
use system::syscall::{O_RDWR, O_RDONLY, O_WRONLY, O_APPEND, O_CREAT, O_TRUNC, MODE_DIR, MODE_FILE, SEEK_SET, SEEK_CUR, SEEK_END, Stat};

/// A Unix-style file
#[derive(Debug)]
pub struct File {
    /// The id for the file
    fd: usize,
}

impl File {
    /// Open a new file using a path
    pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_RDONLY, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Create a new file using a path
    pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_CREAT | O_RDWR | O_TRUNC, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Duplicate the file
    pub fn dup(&self) -> Result<File> {
        sys_dup(self.fd).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
    }

    /// Get the canonical path of the file
    pub fn path(&self) -> Result<PathBuf> {
        let mut buf: [u8; 4096] = [0; 4096];
        match sys_fpath(self.fd, &mut buf) {
            Ok(count) => Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[0..count])) })),
            Err(err) => Err(Error::from_sys(err)),
        }
    }

    /// Flush the file data and metadata
    pub fn sync_all(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Flush the file data
    pub fn sync_data(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Truncates the file
    pub fn set_len(&mut self, size: u64) -> Result<()> {
        sys_ftruncate(self.fd, size as usize).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl AsRawFd for File {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl FromRawFd for File {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        File {
            fd: fd
        }
    }
}

impl IntoRawFd for File {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.fd;
        mem::forget(self);
        fd
    }
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        sys_read(self.fd, buf).map_err(|x| Error::from_sys(x))
    }
}

impl Write for File {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        sys_write(self.fd, buf).map_err(|x| Error::from_sys(x))
    }

    // TODO buffered fs
    fn flush(&mut self) -> Result<()> { Ok(()) }
}

impl Seek for File {
    /// Seek a given position
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let (whence, offset) = match pos {
            SeekFrom::Start(offset) => (SEEK_SET, offset as isize),
            SeekFrom::Current(offset) => (SEEK_CUR, offset as isize),
            SeekFrom::End(offset) => (SEEK_END, offset as isize),
        };

        sys_lseek(self.fd, offset, whence).map(|position| position as u64).map_err(|x| Error::from_sys(x))
    }
}

impl Drop for File {
    fn drop(&mut self) {
        let _ = sys_close(self.fd);
    }
}

pub struct FileType {
    dir: bool,
    file: bool,
}

impl FileType {
    pub fn is_dir(&self) -> bool {
        self.dir
    }

    pub fn is_file(&self) -> bool {
        self.file
    }
}

pub struct OpenOptions {
    read: bool,
    write: bool,
    append: bool,
    create: bool,
    truncate: bool,
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            read: false,
            write: false,
            append: false,
            create: false,
            truncate: false,
        }
    }

    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
        self.read = read;
        self
    }

    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
        self.write = write;
        self
    }

    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
        self.append = append;
        self
    }

    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
        self.create = create;
        self
    }

    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
        self.truncate = truncate;
        self
    }

    pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let mut flags = 0;

        if self.read && self.write {
            flags |= O_RDWR;
        } else if self.read {
            flags |= O_RDONLY;
        } else if self.write {
            flags |= O_WRONLY;
        }

        if self.append {
            flags |= O_APPEND;
        }

        if self.create {
            flags |= O_CREAT;
        }

        if self.truncate {
            flags |= O_TRUNC;
        }

        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), flags, 0).map(|fd| File::from_raw_fd(fd))
        }.map_err(|x| Error::from_sys(x))
    }
}

pub struct Metadata {
    stat: Stat
}

impl Metadata {
    pub fn file_type(&self) -> FileType {
        FileType {
            dir: self.stat.st_mode & MODE_DIR == MODE_DIR,
            file: self.stat.st_mode & MODE_FILE == MODE_FILE
        }
    }

    pub fn is_dir(&self) -> bool {
        self.stat.st_mode & MODE_DIR == MODE_DIR
    }

    pub fn is_file(&self) -> bool {
        self.stat.st_mode & MODE_FILE == MODE_FILE
    }

    pub fn len(&self) -> u64 {
        self.stat.st_size
    }
}

pub struct DirEntry {
    path: String,
    dir: bool,
    file: bool,
}

impl DirEntry {
    pub fn file_name(&self) -> &Path {
        unsafe { mem::transmute(self.path.deref()) }
    }

    pub fn file_type(&self) -> Result<FileType> {
        Ok(FileType {
            dir: self.dir,
            file: self.file,
        })
    }

    pub fn path(&self) -> PathBuf {
        PathBuf::from(self.path.clone())
    }
}

pub struct ReadDir {
    file: File,
}

impl Iterator for ReadDir {
    type Item = Result<DirEntry>;
    fn next(&mut self) -> Option<Result<DirEntry>> {
        let mut path = String::new();
        let mut buf: [u8; 1] = [0; 1];
        loop {
            match self.file.read(&mut buf) {
                Ok(0) => break,
                Ok(count) => {
                    if buf[0] == 10 {
                        break;
                    } else {
                        path.push_str(unsafe { str::from_utf8_unchecked(&buf[..count]) });
                    }
                }
                Err(_err) => break,
            }
        }
        if path.is_empty() {
            None
        } else {
            let dir = path.ends_with('/');
            if dir {
                path.pop();
            }
            Some(Ok(DirEntry {
                path: path,
                dir: dir,
                file: !dir,
            }))
        }
    }
}

/// Find the canonical path of a file
pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    match File::open(path) {
        Ok(file) => {
            match file.path() {
                Ok(realpath) => Ok(realpath),
                Err(err) => Err(err)
            }
        },
        Err(err) => Err(err)
    }
}

pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    let mut stat = Stat {
        st_mode: 0,
        st_size: 0
    };
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        try!(sys_stat(path_c.as_ptr(), &mut stat).map_err(|x| Error::from_sys(x)));
    }
    Ok(Metadata {
        stat: stat
    })
}

/// Create a new directory, using a path
/// The default mode of the directory is 744
pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_mkdir(path_c.as_ptr(), 755).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> {
    let mut infile = try!(File::open(from));
    let mut outfile = try!(File::create(to));
    io::copy(&mut infile, &mut outfile)
}

pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
    try!(copy(Path::new(from.as_ref()), to));
    remove_file(from)
}

pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> {
    File::open(path).map(|file| ReadDir { file: file })
}

pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_rmdir(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}

pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_unlink(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}
<commit_msg>USe bufreader for readdir, allow fsync of file<commit_after>use core::ops::Deref;
use core_collections::borrow::ToOwned;
use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom};
use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use mem;
use path::{PathBuf, Path};
use string::String;
use sys_common::AsInner;
use vec::Vec;

use system::syscall::{sys_open, sys_dup, sys_close, sys_fpath, sys_ftruncate, sys_read,
              sys_write, sys_lseek, sys_fsync, sys_mkdir, sys_rmdir, sys_stat, sys_unlink};
use system::syscall::{O_RDWR, O_RDONLY, O_WRONLY, O_APPEND, O_CREAT, O_TRUNC, MODE_DIR, MODE_FILE, SEEK_SET, SEEK_CUR, SEEK_END, Stat};

/// A Unix-style file
#[derive(Debug)]
pub struct File {
    /// The id for the file
    fd: usize,
}

impl File {
    /// Open a new file using a path
    pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_RDONLY, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Create a new file using a path
    pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_CREAT | O_RDWR | O_TRUNC, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Duplicate the file
    pub fn dup(&self) -> Result<File> {
        sys_dup(self.fd).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
    }

    /// Get the canonical path of the file
    pub fn path(&self) -> Result<PathBuf> {
        let mut buf: [u8; 4096] = [0; 4096];
        match sys_fpath(self.fd, &mut buf) {
            Ok(count) => Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[0..count])) })),
            Err(err) => Err(Error::from_sys(err)),
        }
    }

    /// Flush the file data and metadata
    pub fn sync_all(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Flush the file data
    pub fn sync_data(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Truncates the file
    pub fn set_len(&mut self, size: u64) -> Result<()> {
        sys_ftruncate(self.fd, size as usize).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl AsRawFd for File {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl FromRawFd for File {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        File {
            fd: fd
        }
    }
}

impl IntoRawFd for File {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.fd;
        mem::forget(self);
        fd
    }
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        sys_read(self.fd, buf).map_err(|x| Error::from_sys(x))
    }
}

impl Write for File {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        sys_write(self.fd, buf).map_err(|x| Error::from_sys(x))
    }

    fn flush(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl Seek for File {
    /// Seek a given position
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let (whence, offset) = match pos {
            SeekFrom::Start(offset) => (SEEK_SET, offset as isize),
            SeekFrom::Current(offset) => (SEEK_CUR, offset as isize),
            SeekFrom::End(offset) => (SEEK_END, offset as isize),
        };

        sys_lseek(self.fd, offset, whence).map(|position| position as u64).map_err(|x| Error::from_sys(x))
    }
}

impl Drop for File {
    fn drop(&mut self) {
        let _ = sys_close(self.fd);
    }
}

pub struct FileType {
    dir: bool,
    file: bool,
}

impl FileType {
    pub fn is_dir(&self) -> bool {
        self.dir
    }

    pub fn is_file(&self) -> bool {
        self.file
    }
}

pub struct OpenOptions {
    read: bool,
    write: bool,
    append: bool,
    create: bool,
    truncate: bool,
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            read: false,
            write: false,
            append: false,
            create: false,
            truncate: false,
        }
    }

    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
        self.read = read;
        self
    }

    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
        self.write = write;
        self
    }

    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
        self.append = append;
        self
    }

    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
        self.create = create;
        self
    }

    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
        self.truncate = truncate;
        self
    }

    pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let mut flags = 0;

        if self.read && self.write {
            flags |= O_RDWR;
        } else if self.read {
            flags |= O_RDONLY;
        } else if self.write {
            flags |= O_WRONLY;
        }

        if self.append {
            flags |= O_APPEND;
        }

        if self.create {
            flags |= O_CREAT;
        }

        if self.truncate {
            flags |= O_TRUNC;
        }

        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), flags, 0).map(|fd| File::from_raw_fd(fd))
        }.map_err(|x| Error::from_sys(x))
    }
}

pub struct Metadata {
    stat: Stat
}

impl Metadata {
    pub fn file_type(&self) -> FileType {
        FileType {
            dir: self.stat.st_mode & MODE_DIR == MODE_DIR,
            file: self.stat.st_mode & MODE_FILE == MODE_FILE
        }
    }

    pub fn is_dir(&self) -> bool {
        self.stat.st_mode & MODE_DIR == MODE_DIR
    }

    pub fn is_file(&self) -> bool {
        self.stat.st_mode & MODE_FILE == MODE_FILE
    }

    pub fn len(&self) -> u64 {
        self.stat.st_size
    }
}

pub struct DirEntry {
    path: String,
    dir: bool,
    file: bool,
}

impl DirEntry {
    pub fn file_name(&self) -> &Path {
        unsafe { mem::transmute(self.path.deref()) }
    }

    pub fn file_type(&self) -> Result<FileType> {
        Ok(FileType {
            dir: self.dir,
            file: self.file,
        })
    }

    pub fn path(&self) -> PathBuf {
        PathBuf::from(self.path.clone())
    }
}

pub struct ReadDir {
    file: BufReader<File>,
}

impl Iterator for ReadDir {
    type Item = Result<DirEntry>;
    fn next(&mut self) -> Option<Result<DirEntry>> {
        let mut path = String::new();
        match self.file.read_line(&mut path) {
            Ok(0) => None,
            Ok(_) => {
                if path.ends_with('\n') {
                    path.pop();
                }
                let dir = path.ends_with('/');
                if dir {
                    path.pop();
                }
                Some(Ok(DirEntry {
                    path: path,
                    dir: dir,
                    file: !dir,
                }))
            },
            Err(err) => Some(Err(err))
        }
    }
}

/// Find the canonical path of a file
pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    match File::open(path) {
        Ok(file) => {
            match file.path() {
                Ok(realpath) => Ok(realpath),
                Err(err) => Err(err)
            }
        },
        Err(err) => Err(err)
    }
}

pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    let mut stat = Stat {
        st_mode: 0,
        st_size: 0
    };
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        try!(sys_stat(path_c.as_ptr(), &mut stat).map_err(|x| Error::from_sys(x)));
    }
    Ok(Metadata {
        stat: stat
    })
}

/// Create a new directory, using a path
/// The default mode of the directory is 744
pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_mkdir(path_c.as_ptr(), 755).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> {
    let mut infile = try!(File::open(from));
    let mut outfile = try!(File::create(to));
    io::copy(&mut infile, &mut outfile)
}

pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
    try!(copy(Path::new(from.as_ref()), to));
    remove_file(from)
}

pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> {
    File::open(path).map(|file| ReadDir { file: BufReader::new(file) })
}

pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_rmdir(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}

pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_unlink(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}

<|endoftext|>


<commit_before><commit_msg>Added small demo<commit_after>extern crate peel_ip;
use peel_ip::prelude::*;

extern crate pcap;
use pcap::{Active, Capture, Device};

extern crate rain;
use rain::Graph;

extern crate time;
use time::Duration;

use std::thread::{self, JoinHandle};
use std::sync::mpsc::{channel, Sender, Receiver};

type IpIdentifier = Identifier<IpProtocol>;

#[derive(Debug)]
struct Packet {
    identifier: IpIdentifier,
    length: usize,
    result: String,
}

impl Packet {
    fn new(identifier: IpIdentifier, result: String, length: usize) -> Packet {
        Packet {
            identifier: identifier,
            length: length,
            result: result,
        }
    }
}

pub fn main() {
    start().expect("Failed in main function");
}

fn start() -> Result<(), Box<Error>> {
    let (tx, rx) = channel();

    // Worker thread for capturing packets
    let capture = Device::lookup()?.open()?;
    let peel = PeelIp::new();
    let packet_capture = start_packet_capture_thread(capture, peel, tx);

    // Worker thread for doing the computation on packets
    let mut path: Path<IpProtocol, usize> = Path::new();
    path.timeout = Duration::seconds(4);
    let graph = Graph::with_prefix_length(135);
    let computation = start_graph_drawing_thread(path, graph, rx);

    // Join the threads together
    computation.join().unwrap();
    packet_capture.join().unwrap();
    Ok(())
}

fn start_packet_capture_thread(mut capture: Capture<Active>, mut peel: PeelIp, tx: Sender<Packet>) -> JoinHandle<()> {
    thread::spawn(move || {
        while let Ok(packet) = capture.next() {
            // Parse the packet
            if let Ok(res) = peel.traverse(packet.data, vec![]) {
                if let Some(identifier) = get_identifier(&res) {
                    let mut result_string = res.iter().map(|r| format!("{}, ", r)).collect::<Vec<String>>().concat();
                    result_string.pop();
                    result_string.pop();
                    let packet = Packet::new(identifier, result_string, packet.data.len());
                    tx.send(packet).unwrap();
                }
            }
        }
    })
}

fn start_graph_drawing_thread(mut path: Path<IpProtocol, usize>,
                              mut graph: Graph<u32>,
                              rx: Receiver<Packet>)
                              -> JoinHandle<()> {
    thread::spawn(move || {
        loop {
            thread::sleep(std::time::Duration::from_secs(2));

            // Get all pending values
            for packet in rx.try_iter() {
                let line_string = format!("{}: {}", packet.identifier, packet.result);

                // Track the connection as usual if no error happended
                match path.track(packet.identifier.clone()) {
                    Ok(connection) => {
                        connection.data.custom = Some(connection.data.custom.unwrap_or_default() + packet.length);
                        graph.add(&line_string,
                                 connection.data.custom.unwrap_or_default() as u32)
                            .is_ok();
                    }
                    Err(_) => {
                        graph.remove(&line_string).is_ok();
                    }
                };

                // Flush connections with a timeout
                for _ in path.flush() {
                    graph.remove(&line_string).is_ok();
                }
            }

            // Print the graph
            graph.print().unwrap();
        }
    })
}

fn get_identifier(result: &[Layer]) -> Option<IpIdentifier> {
    // Try to get the ports
    let ports = match result.get(2) {
        Some(&Layer::Tcp(ref tcp)) => Some((tcp.header.source_port, tcp.header.dest_port)),
        Some(&Layer::Udp(ref udp)) => Some((udp.header.source_port, udp.header.dest_port)),
        _ => None,
    };

    match (result.get(1), ports) {
        (Some(&Layer::Ipv4(ref p)), Some((src_port, dst_port))) => {
            Some(Identifier::new(IpAddr::V4(p.src),
                                 src_port,
                                 IpAddr::V4(p.dst),
                                 dst_port,
                                 p.protocol))
        }
        (Some(&Layer::Ipv6(ref p)), Some((src_port, dst_port))) => {
            Some(Identifier::new(IpAddr::V6(p.src),
                                 src_port,
                                 IpAddr::V6(p.dst),
                                 dst_port,
                                 p.next_header))
        }
        // Previous result found, but not the correct one
        _ => None,
    }
}
<|endoftext|>


<commit_before>/*!
 * A simple map based on a vector for small integer keys. Space requirements
 * are O(highest integer key).
 */
use core::option;
use core::option::{Some, None};
use dvec::DVec;
use map::map;

// FIXME (#2347): Should not be @; there's a bug somewhere in rustc that
// requires this to be.
type smallintmap_<T: copy> = {v: DVec<Option<T>>};

enum smallintmap<T:copy> {
    smallintmap_(@smallintmap_<T>)
}

/// Create a smallintmap
fn mk<T: copy>() -> smallintmap<T> {
    let v = DVec();
    return smallintmap_(@{v: v});
}

/**
 * Add a value to the map. If the map already contains a value for
 * the specified key then the original value is replaced.
 */
#[inline(always)]
fn insert<T: copy>(self: smallintmap<T>, key: uint, val: T) {
    //io::println(fmt!("%?", key));
    self.v.grow_set_elt(key, None, Some(val));
}

/**
 * Get the value for the specified key. If the key does not exist
 * in the map then returns none
 */
pure fn find<T: copy>(self: smallintmap<T>, key: uint) -> Option<T> {
    if key < self.v.len() { return self.v.get_elt(key); }
    return None::<T>;
}

/**
 * Get the value for the specified key
 *
 * # Failure
 *
 * If the key does not exist in the map
 */
pure fn get<T: copy>(self: smallintmap<T>, key: uint) -> T {
    match find(self, key) {
      None => {
        error!("smallintmap::get(): key not present");
        fail;
      }
      Some(v) => return v
    }
}

/// Returns true if the map contains a value for the specified key
fn contains_key<T: copy>(self: smallintmap<T>, key: uint) -> bool {
    return !option::is_none(find(self, key));
}

/// Implements the map::map interface for smallintmap
impl<V: copy> smallintmap<V>: map::map<uint, V> {
    pure fn size() -> uint {
        let mut sz = 0u;
        for self.v.each |item| {
            match item {
              Some(_) => sz += 1u,
              _ => ()
            }
        }
        sz
    }
    #[inline(always)]
    fn insert(+key: uint, +value: V) -> bool {
        let exists = contains_key(self, key);
        insert(self, key, value);
        return !exists;
    }
    fn remove(+key: uint) -> bool {
        if key >= self.v.len() {
            return false;
        }
        let old = self.v.get_elt(key);
        self.v.set_elt(key, None);
        old.is_some()
    }
    fn clear() {
        self.v.set(~[mut]);
    }
    fn contains_key(+key: uint) -> bool {
        contains_key(self, key)
    }
    fn contains_key_ref(key: &uint) -> bool {
        contains_key(self, *key)
    }
    fn get(+key: uint) -> V { get(self, key) }
    pure fn find(+key: uint) -> Option<V> { find(self, key) }
    fn rehash() { fail }
    pure fn each(it: fn(+key: uint, +value: V) -> bool) {
        let mut idx = 0u, l = self.v.len();
        while idx < l {
            match self.v.get_elt(idx) {
              Some(elt) => if !it(idx, elt) { break },
              None => ()
            }
            idx += 1u;
        }
    }
    pure fn each_key(it: fn(+key: uint) -> bool) {
        self.each(|k, _v| it(k))
    }
    pure fn each_value(it: fn(+value: V) -> bool) {
        self.each(|_k, v| it(v))
    }
    pure fn each_ref(it: fn(key: &uint, value: &V) -> bool) {
        let mut idx = 0u, l = self.v.len();
        while idx < l {
            match self.v.get_elt(idx) {
              Some(elt) => if !it(&idx, &elt) { break },
              None => ()
            }
            idx += 1u;
        }
    }
    pure fn each_key_ref(blk: fn(key: &uint) -> bool) {
        self.each_ref(|k, _v| blk(k))
    }
    pure fn each_value_ref(blk: fn(value: &V) -> bool) {
        self.each_ref(|_k, v| blk(v))
    }
}

impl<V: copy> smallintmap<V>: ops::Index<uint, V> {
    pure fn index(&&key: uint) -> V {
        unchecked {
            get(self, key)
        }
    }
}

/// Cast the given smallintmap to a map::map
fn as_map<V: copy>(s: smallintmap<V>) -> map::map<uint, V> {
    s as map::map::<uint, V>
}
<commit_msg>Confirm demoding of smallintmap.rs<commit_after>/*!
 * A simple map based on a vector for small integer keys. Space requirements
 * are O(highest integer key).
 */
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

use core::option;
use core::option::{Some, None};
use dvec::DVec;
use map::map;

// FIXME (#2347): Should not be @; there's a bug somewhere in rustc that
// requires this to be.
type smallintmap_<T: copy> = {v: DVec<Option<T>>};

enum smallintmap<T:copy> {
    smallintmap_(@smallintmap_<T>)
}

/// Create a smallintmap
fn mk<T: copy>() -> smallintmap<T> {
    let v = DVec();
    return smallintmap_(@{v: v});
}

/**
 * Add a value to the map. If the map already contains a value for
 * the specified key then the original value is replaced.
 */
#[inline(always)]
fn insert<T: copy>(self: smallintmap<T>, key: uint, +val: T) {
    //io::println(fmt!("%?", key));
    self.v.grow_set_elt(key, None, Some(val));
}

/**
 * Get the value for the specified key. If the key does not exist
 * in the map then returns none
 */
pure fn find<T: copy>(self: smallintmap<T>, key: uint) -> Option<T> {
    if key < self.v.len() { return self.v.get_elt(key); }
    return None::<T>;
}

/**
 * Get the value for the specified key
 *
 * # Failure
 *
 * If the key does not exist in the map
 */
pure fn get<T: copy>(self: smallintmap<T>, key: uint) -> T {
    match find(self, key) {
      None => {
        error!("smallintmap::get(): key not present");
        fail;
      }
      Some(v) => return v
    }
}

/// Returns true if the map contains a value for the specified key
fn contains_key<T: copy>(self: smallintmap<T>, key: uint) -> bool {
    return !option::is_none(find(self, key));
}

/// Implements the map::map interface for smallintmap
impl<V: copy> smallintmap<V>: map::map<uint, V> {
    pure fn size() -> uint {
        let mut sz = 0u;
        for self.v.each |item| {
            match item {
              Some(_) => sz += 1u,
              _ => ()
            }
        }
        sz
    }
    #[inline(always)]
    fn insert(+key: uint, +value: V) -> bool {
        let exists = contains_key(self, key);
        insert(self, key, value);
        return !exists;
    }
    fn remove(+key: uint) -> bool {
        if key >= self.v.len() {
            return false;
        }
        let old = self.v.get_elt(key);
        self.v.set_elt(key, None);
        old.is_some()
    }
    fn clear() {
        self.v.set(~[mut]);
    }
    fn contains_key(+key: uint) -> bool {
        contains_key(self, key)
    }
    fn contains_key_ref(key: &uint) -> bool {
        contains_key(self, *key)
    }
    fn get(+key: uint) -> V { get(self, key) }
    pure fn find(+key: uint) -> Option<V> { find(self, key) }
    fn rehash() { fail }
    pure fn each(it: fn(+key: uint, +value: V) -> bool) {
        let mut idx = 0u, l = self.v.len();
        while idx < l {
            match self.v.get_elt(idx) {
              Some(elt) => if !it(idx, elt) { break },
              None => ()
            }
            idx += 1u;
        }
    }
    pure fn each_key(it: fn(+key: uint) -> bool) {
        self.each(|k, _v| it(k))
    }
    pure fn each_value(it: fn(+value: V) -> bool) {
        self.each(|_k, v| it(v))
    }
    pure fn each_ref(it: fn(key: &uint, value: &V) -> bool) {
        let mut idx = 0u, l = self.v.len();
        while idx < l {
            match self.v.get_elt(idx) {
              Some(elt) => if !it(&idx, &elt) { break },
              None => ()
            }
            idx += 1u;
        }
    }
    pure fn each_key_ref(blk: fn(key: &uint) -> bool) {
        self.each_ref(|k, _v| blk(k))
    }
    pure fn each_value_ref(blk: fn(value: &V) -> bool) {
        self.each_ref(|_k, v| blk(v))
    }
}

impl<V: copy> smallintmap<V>: ops::Index<uint, V> {
    pure fn index(&&key: uint) -> V {
        unchecked {
            get(self, key)
        }
    }
}

/// Cast the given smallintmap to a map::map
fn as_map<V: copy>(s: smallintmap<V>) -> map::map<uint, V> {
    s as map::map::<uint, V>
}
<|endoftext|>


<commit_before><commit_msg>Move Sized bound to coerce; unnecessary in general<commit_after><|endoftext|>


<commit_before><commit_msg>Add color2index<commit_after><|endoftext|>


<commit_before><commit_msg>Forgott to add a file<commit_after>
use std::io;
use game;
use game::{GameState, PointState, PlayerColor};
use ai;

pub enum HumanPlayer {
    Active
}

pub fn print_gamestate(state : &GameState) {
    // Here I am iterating y, z, x in that strange order to get a nice output.
    println!("  ----   ----   ----   ---- ");
    for y in (0..4).rev() {
        let mut line = "".to_string();
        for z in 0..4 {
            line = line + " |";
            for x in 0..4 {
                let flat_coordinate = game::flatten(x, y, z);
                line = line + match state.points[flat_coordinate as usize] {
                    PointState::Empty => ".",
                    PointState::Piece(PlayerColor::White) => "X",
                    PointState::Piece(PlayerColor::Black) => "O"
                }
            }
            line = line + "|";
        }
        println!("{}", line);
    }
    println!("  ----   ----   ----   ---- ");
}

pub fn ask_for_move() -> ai::Move {
    let mut instruction = String::new();

    io::stdin().read_line(&mut instruction).expect("Failed to read line");

    let s = String::from("0123456789ABCDEF");
    let _index = s.find(instruction.chars().nth(0).unwrap());

    let index = match _index {
        None    => return ai::Move::Surrender,
        Some(i) => i as i8
    };

    return ai::Move::Play { x : index % 4, y : index / 4};
}

impl ai::SogoAI for HumanPlayer {
    fn reset_game(&self) { }
    fn execute_move(&self, state : &game::GameState) -> ai::Move {
        print_gamestate(state);
        ask_for_move()
    }
}
<|endoftext|>


<commit_before>#![feature(custom_derive, plugin, custom_attribute, test)]
#![plugin(diesel_codegen, dotenv_macros)]
#[macro_use]
extern crate diesel;
extern crate test;

mod schema;

use self::test::Bencher;
use self::schema::*;
use diesel::*;

#[bench]
fn bench_selecting_0_rows_with_trivial_query(b: &mut Bencher) {
    let conn = connection();

    b.iter(|| {
        users::table.load::<User>(&conn).unwrap();
    })
}

#[bench]
fn bench_selecting_10k_rows_with_trivial_query(b: &mut Bencher) {
    let conn = connection();
    let data: Vec<_> = (0..10_000).map(|i| {
        NewUser::new(&format!("User {}", i), None)
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        users::table.load::<User>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_10k_rows_with_trivial_query_boxed(b: &mut Bencher) {
    let conn = connection();
    let data: Vec<_> = (0..10_000).map(|i| {
        NewUser::new(&format!("User {}", i), None)
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        users::table.into_boxed().load::<User>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_0_rows_with_medium_complex_query(b: &mut Bencher) {
    let conn = connection();

    b.iter(|| {
        use schema::users::dsl::*;
        let target = users.left_outer_join(posts::table)
            .filter(hair_color.eq("black"))
            .order(name.desc());
        target.load::<(User, Option<Post>)>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_10k_rows_with_medium_complex_query(b: &mut Bencher) {
    let conn = connection();

    let data: Vec<_> = (0..10_000).map(|i| {
        let hair_color = if i % 2 == 0 { "black" } else { "brown" };
        NewUser::new(&format!("User {}", i), Some(hair_color))
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        use schema::users::dsl::*;
        let target = users.left_outer_join(posts::table)
            .filter(hair_color.eq("black"))
            .order(name.desc());
        target.load::<(User, Option<Post>)>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_10k_rows_with_medium_complex_query_boxed(b: &mut Bencher) {
    let conn = connection();

    let data: Vec<_> = (0..10_000).map(|i| {
        let hair_color = if i % 2 == 0 { "black" } else { "brown" };
        NewUser::new(&format!("User {}", i), Some(hair_color))
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        use schema::users::dsl::*;
        let target = users.left_outer_join(posts::table)
            .filter(hair_color.eq("black"))
            .order(name.desc())
            .into_boxed();
        target.load::<(User, Option<Post>)>(&conn).unwrap()
    })
}
<commit_msg>Ensure PG gives consistent benchmark results<commit_after>#![feature(custom_derive, plugin, custom_attribute, test)]
#![plugin(diesel_codegen, dotenv_macros)]
#[macro_use]
extern crate diesel;
extern crate test;

mod schema;

use self::test::Bencher;
use self::schema::{users, NewUser, User, Post, TestConnection, posts, batch_insert};
use diesel::*;

#[cfg(not(feature = "sqlite"))]
fn connection() -> TestConnection {
    let conn = schema::connection();
    conn.execute("TRUNCATE TABLE USERS").unwrap();
    conn
}

#[cfg(feature = "sqlite")]
fn connection() -> TestConnection {
    schema::connection()
}

#[bench]
fn bench_selecting_0_rows_with_trivial_query(b: &mut Bencher) {
    let conn = connection();

    b.iter(|| {
        users::table.load::<User>(&conn).unwrap();
    })
}

#[bench]
fn bench_selecting_10k_rows_with_trivial_query(b: &mut Bencher) {
    let conn = connection();
    let data: Vec<_> = (0..10_000).map(|i| {
        NewUser::new(&format!("User {}", i), None)
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        users::table.load::<User>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_10k_rows_with_trivial_query_boxed(b: &mut Bencher) {
    let conn = connection();
    let data: Vec<_> = (0..10_000).map(|i| {
        NewUser::new(&format!("User {}", i), None)
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        users::table.into_boxed().load::<User>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_0_rows_with_medium_complex_query(b: &mut Bencher) {
    let conn = connection();

    b.iter(|| {
        use schema::users::dsl::*;
        let target = users.left_outer_join(posts::table)
            .filter(hair_color.eq("black"))
            .order(name.desc());
        target.load::<(User, Option<Post>)>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_10k_rows_with_medium_complex_query(b: &mut Bencher) {
    let conn = connection();

    let data: Vec<_> = (0..10_000).map(|i| {
        let hair_color = if i % 2 == 0 { "black" } else { "brown" };
        NewUser::new(&format!("User {}", i), Some(hair_color))
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        use schema::users::dsl::*;
        let target = users.left_outer_join(posts::table)
            .filter(hair_color.eq("black"))
            .order(name.desc());
        target.load::<(User, Option<Post>)>(&conn).unwrap()
    })
}

#[bench]
fn bench_selecting_10k_rows_with_medium_complex_query_boxed(b: &mut Bencher) {
    let conn = connection();

    let data: Vec<_> = (0..10_000).map(|i| {
        let hair_color = if i % 2 == 0 { "black" } else { "brown" };
        NewUser::new(&format!("User {}", i), Some(hair_color))
    }).collect();
    batch_insert(&data, users::table, &conn);

    b.iter(|| {
        use schema::users::dsl::*;
        let target = users.left_outer_join(posts::table)
            .filter(hair_color.eq("black"))
            .order(name.desc())
            .into_boxed();
        target.load::<(User, Option<Post>)>(&conn).unwrap()
    })
}
<|endoftext|>


<commit_before><commit_msg>(cleanup) Removed reference to mixins.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for #22403<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #116<commit_after>#[crate_type = "rlib"];

use std::iter;
use std::hashmap::HashMap;

pub static EXPECTED_ANSWER: &'static str = "20492570929";

fn count(len: uint, unit: uint, map: &mut HashMap<(uint, uint), uint>) -> uint {
    match map.find(&(len, unit)) {
        Some(&x) => return x,
        None => {}
    }

    if len < unit { map.insert((len, unit), 1); return 1; }

    let mut sum = 0;
    for i in iter::range_inclusive(0, len - unit) { // most left block position
        sum += count(len - (unit + i), unit, map);
    }
    sum += 1;
    map.insert((len, unit), sum);
    sum
}

fn count_red(len: uint, map: &mut HashMap<(uint, uint), uint>) -> uint { count(len, 2, map) - 1 }
fn count_green(len: uint, map: &mut HashMap<(uint, uint), uint>) -> uint { count(len, 3, map) - 1 }
fn count_blue(len: uint, map: &mut HashMap<(uint, uint), uint>) -> uint { count(len, 4, map) - 1 }
fn count_all(len: uint, map: &mut HashMap<(uint, uint), uint>) -> uint {
    count_red(len, map) + count_green(len, map) + count_blue(len, map)
}

pub fn solve() -> ~str {
    let mut map = HashMap::new();
    count_all(50, &mut map).to_str()
}

#[cfg(test)]
mod test {
    use super::{count_red, count_green, count_blue, count_all};
    use std::hashmap::HashMap;

    #[test]
    fn count() {
        let mut map = HashMap::new();
        assert_eq!(7, count_red(5, &mut map));
        assert_eq!(3, count_green(5, &mut map));
        assert_eq!(2, count_blue(5, &mut map));
        assert_eq!(12, count_all(5, &mut map));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add ui test for imag-view<commit_after><|endoftext|>


<commit_before><commit_msg>Add anagrams lifetimes<commit_after>use std::io::Write; // Needed for writing to stderr

fn main() {
    let args = std::env::args();
    if args.len() != 2 {
        let _ = writeln!(std::io::stderr(), "Please enter exactly one argument");
        std::process::exit(1);
    }
    if let Some(last_arg) = args.last() {
        let mut word: Vec<_> = last_arg.chars().collect();
        generate_permutations(word.len() - 1, &mut word);
    }
}

fn generate_permutations<'a>(n: usize, a: &'a mut Vec<char>) {
    if n == 0 {
        println!("{}", a.clone().into_iter().collect::<String>());
    } else {
        for i in 0..n+1 {
            generate_permutations(n - 1, a);
            a.swap(if n % 2 == 0 { i } else { 0 }, n);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix multi-line reading<commit_after><|endoftext|>


<commit_before><commit_msg>Add a hello world example<commit_after>extern crate robots;

use std::sync::Arc;
use std::time::Duration;

use robots::actors::{Actor, ActorSystem, ActorCell, ActorContext, Props, Message};

#[derive(Copy, Clone, PartialEq)]
enum Greetings {
    Greet,
    Done,
}

struct HelloWorld;

impl Actor<Greetings> for HelloWorld {
    fn pre_start<Args: Message>(&self, context: ActorCell<Args, Greetings, HelloWorld>) {
        let props = Props::new(Arc::new(Greeter::new), ());
        let greeter = context.actor_of(props);
        context.tell(greeter, Greetings::Greet);
    }
    fn receive<Args: Message>(&self, message: Greetings, _context: ActorCell<Args, Greetings, HelloWorld>) {
        if message == Greetings::Done {
            println!("The greeting is done");
        }
    }
}

impl HelloWorld {
    fn new(_dummy: ()) -> HelloWorld {
        HelloWorld
    }
}

struct Greeter;

impl Actor<Greetings> for Greeter {
    fn receive<Args: Message>(&self, message: Greetings, context: ActorCell<Args, Greetings, Greeter>) {
        if message == Greetings::Greet {
            println!("Hello World");
            context.tell(context.sender(), Greetings::Done);
        }
    }
}

impl Greeter {
    fn new(_dummy: ()) -> Greeter {
        Greeter
    }
}

fn main() {
    let actor_system = ActorSystem::new("test".to_owned());
    actor_system.spawn_threads(1);

    let props = Props::new(Arc::new(HelloWorld::new), ());
    let _actor = actor_system.actor_of(props);

    std::thread::sleep(Duration::from_millis(100));

    actor_system.terminate_threads(1);
}
<|endoftext|>


<commit_before><commit_msg>Add example<commit_after>extern crate redpitaya_scpi;

use redpitaya_scpi::digital::{ Led, State };
use redpitaya_scpi::Redpitaya;
use std::thread::sleep;
use std::time::Duration;

fn main() {
    let mut redpitaya = Redpitaya::new("192.168.1.5:5000");

    loop {
        let leds = [
            Led::LED0,
            Led::LED1,
            Led::LED2,
            Led::LED3,
            Led::LED4,
            Led::LED5,
            Led::LED6,
            Led::LED7,
        ];

        for led in leds.iter() {
            redpitaya.digital.set_state(*led, State::HIGH);
            sleep(Duration::from_millis(100));
            redpitaya.digital.set_state(*led, State::LOW);
        }

        for led in leds.iter().rev() {
            redpitaya.digital.set_state(*led, State::HIGH);
            sleep(Duration::from_millis(100));
            redpitaya.digital.set_state(*led, State::LOW);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Clean-up form parsing tests.<commit_after><|endoftext|>


<commit_before>extern crate forth;

use forth::{Error, Forth, Value};

#[test]
fn no_input_no_stack() {
    assert_eq!(Vec::<Value>::new(), Forth::new().stack());
}

#[test]
#[ignore]
fn numbers_just_get_pushed_onto_the_stack() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 3 4 5").is_ok());
    assert_eq!(vec![1, 2, 3, 4, 5], f.stack());
}

#[test]
#[ignore]
fn non_word_characters_are_separators() {
    let mut f = Forth::new();
    assert!(f.eval("1\u{0000}2\u{0001}3\n4\r5 6\t7").is_ok());
    assert_eq!(vec![1, 2, 3, 4, 5, 6, 7], f.stack());
}

#[test]
#[ignore]
fn can_add_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 +").is_ok());
    assert_eq!(vec![3], f.stack());
}

#[test]
#[ignore]
fn addition_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 +"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("+"));
}

#[test]
#[ignore]
fn can_subtract_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("3 4 -").is_ok());
    assert_eq!(vec![-1], f.stack());
}

#[test]
#[ignore]
fn subtraction_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 -"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("-"));
}

#[test]
#[ignore]
fn can_multiply_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("2 4 *").is_ok());
    assert_eq!(vec![8], f.stack());
}

#[test]
#[ignore]
fn multiplication_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 *"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("*"));
}

#[test]
#[ignore]
fn can_divide_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("12 3 /").is_ok());
    assert_eq!(vec![4], f.stack());
}

#[test]
#[ignore]
fn performs_integer_division() {
    let mut f = Forth::new();
    assert!(f.eval("8 3 /").is_ok());
    assert_eq!(vec![2], f.stack());
}

#[test]
#[ignore]
fn division_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 /"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("/"));
}

#[test]
#[ignore]
fn errors_if_dividing_by_zero() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::DivisionByZero), f.eval("4 0 /"));
}

#[test]
#[ignore]
fn addition_and_subtraction() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 + 4 -").is_ok());
    assert_eq!(vec![-1], f.stack());
}

#[test]
#[ignore]
fn multiplication_and_division() {
    let mut f = Forth::new();
    assert!(f.eval("2 4 * 3 /").is_ok());
    assert_eq!(vec![2], f.stack());
}

#[test]
#[ignore]
fn dup() {
    let mut f = Forth::new();
    assert!(f.eval("1 DUP").is_ok());
    assert_eq!(vec![1, 1], f.stack());
}

#[test]
#[ignore]
fn dup_case_insensitive() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 Dup").is_ok());
    assert_eq!(vec![1, 2, 2], f.stack());
}

#[test]
#[ignore]
fn dup_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("dup"));
}

#[test]
#[ignore]
fn drop() {
    let mut f = Forth::new();
    assert!(f.eval("1 drop").is_ok());
    assert_eq!(Vec::<Value>::new(), f.stack());
}

#[test]
#[ignore]
fn drop_with_two() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 drop").is_ok());
    assert_eq!(vec![1], f.stack());
}

#[test]
#[ignore]
fn drop_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("drop"));
}

#[test]
#[ignore]
fn swap() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 swap").is_ok());
    assert_eq!(vec![2, 1], f.stack());
}

#[test]
#[ignore]
fn swap_with_three() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 3 swap").is_ok());
    assert_eq!(vec![1, 3, 2], f.stack());
}

#[test]
#[ignore]
fn swap_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 swap"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("swap"));
}

#[test]
#[ignore]
fn over() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 over").is_ok());
    assert_eq!(vec![1, 2, 1], f.stack());
}

#[test]
#[ignore]
fn over_with_three() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 3 over").is_ok());
    assert_eq!(vec![1, 2, 3, 2], f.stack());
}

#[test]
#[ignore]
fn over_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 over"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("over"));
}

// User-defined words

#[test]
#[ignore]
fn can_consist_of_built_in_words() {
    let mut f = Forth::new();
    assert!(f.eval(": dup-twice dup dup ;").is_ok());
    assert!(f.eval("1 dup-twice").is_ok());
    assert_eq!(vec![1, 1, 1], f.stack());
}

#[test]
#[ignore]
fn execute_in_the_right_order() {
    let mut f = Forth::new();
    assert!(f.eval(": countup 1 2 3 ;").is_ok());
    assert!(f.eval("countup").is_ok());
    assert_eq!(vec![1, 2, 3], f.stack());
}

#[test]
#[ignore]
fn definitions_are_case_insensitive() {
    let mut f = Forth::new();
    assert!(f.eval(": CoUnT 1 2 3 ;").is_ok());
    assert!(f.eval("count COUNT").is_ok());
    assert_eq!(vec![1, 2, 3, 1, 2, 3], f.stack());
}

#[test]
#[ignore]
fn redefining_an_existing_word() {
    let mut f = Forth::new();
    assert!(f.eval(": foo dup ;").is_ok());
    assert!(f.eval(": foo dup dup ;").is_ok());
    assert!(f.eval("1 foo").is_ok());
    assert_eq!(vec![1, 1, 1], f.stack());
}

#[test]
#[ignore]
fn redefining_an_existing_built_in_word() {
    let mut f = Forth::new();
    assert!(f.eval(": swap dup ;").is_ok());
    assert!(f.eval("1 swap").is_ok());
    assert_eq!(vec![1, 1], f.stack());
}

#[test]
#[ignore]
fn defining_words_with_odd_characters() {
    let mut f = Forth::new();
    assert!(f.eval(": € 220371 ; €").is_ok());
    assert_eq!(vec![220371], f.stack());
}

#[test]
#[ignore]
fn defining_a_number() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::InvalidWord), f.eval(": 1 2 ;"));
}

#[test]
#[ignore]
fn malformed_word_definition() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::InvalidWord), f.eval(":"));
    assert_eq!(Err(Error::InvalidWord), f.eval(": foo"));
    assert_eq!(Err(Error::InvalidWord), f.eval(": foo 1"));
}

#[test]
#[ignore]
fn calling_non_existing_word() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::UnknownWord), f.eval("1 foo"));
}
<commit_msg>forth: rm unicode character as a word<commit_after>extern crate forth;

use forth::{Error, Forth, Value};

#[test]
fn no_input_no_stack() {
    assert_eq!(Vec::<Value>::new(), Forth::new().stack());
}

#[test]
#[ignore]
fn numbers_just_get_pushed_onto_the_stack() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 3 4 5").is_ok());
    assert_eq!(vec![1, 2, 3, 4, 5], f.stack());
}

#[test]
#[ignore]
fn non_word_characters_are_separators() {
    let mut f = Forth::new();
    assert!(f.eval("1\u{0000}2\u{0001}3\n4\r5 6\t7").is_ok());
    assert_eq!(vec![1, 2, 3, 4, 5, 6, 7], f.stack());
}

#[test]
#[ignore]
fn can_add_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 +").is_ok());
    assert_eq!(vec![3], f.stack());
}

#[test]
#[ignore]
fn addition_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 +"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("+"));
}

#[test]
#[ignore]
fn can_subtract_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("3 4 -").is_ok());
    assert_eq!(vec![-1], f.stack());
}

#[test]
#[ignore]
fn subtraction_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 -"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("-"));
}

#[test]
#[ignore]
fn can_multiply_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("2 4 *").is_ok());
    assert_eq!(vec![8], f.stack());
}

#[test]
#[ignore]
fn multiplication_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 *"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("*"));
}

#[test]
#[ignore]
fn can_divide_two_numbers() {
    let mut f = Forth::new();
    assert!(f.eval("12 3 /").is_ok());
    assert_eq!(vec![4], f.stack());
}

#[test]
#[ignore]
fn performs_integer_division() {
    let mut f = Forth::new();
    assert!(f.eval("8 3 /").is_ok());
    assert_eq!(vec![2], f.stack());
}

#[test]
#[ignore]
fn division_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 /"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("/"));
}

#[test]
#[ignore]
fn errors_if_dividing_by_zero() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::DivisionByZero), f.eval("4 0 /"));
}

#[test]
#[ignore]
fn addition_and_subtraction() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 + 4 -").is_ok());
    assert_eq!(vec![-1], f.stack());
}

#[test]
#[ignore]
fn multiplication_and_division() {
    let mut f = Forth::new();
    assert!(f.eval("2 4 * 3 /").is_ok());
    assert_eq!(vec![2], f.stack());
}

#[test]
#[ignore]
fn dup() {
    let mut f = Forth::new();
    assert!(f.eval("1 DUP").is_ok());
    assert_eq!(vec![1, 1], f.stack());
}

#[test]
#[ignore]
fn dup_case_insensitive() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 Dup").is_ok());
    assert_eq!(vec![1, 2, 2], f.stack());
}

#[test]
#[ignore]
fn dup_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("dup"));
}

#[test]
#[ignore]
fn drop() {
    let mut f = Forth::new();
    assert!(f.eval("1 drop").is_ok());
    assert_eq!(Vec::<Value>::new(), f.stack());
}

#[test]
#[ignore]
fn drop_with_two() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 drop").is_ok());
    assert_eq!(vec![1], f.stack());
}

#[test]
#[ignore]
fn drop_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("drop"));
}

#[test]
#[ignore]
fn swap() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 swap").is_ok());
    assert_eq!(vec![2, 1], f.stack());
}

#[test]
#[ignore]
fn swap_with_three() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 3 swap").is_ok());
    assert_eq!(vec![1, 3, 2], f.stack());
}

#[test]
#[ignore]
fn swap_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 swap"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("swap"));
}

#[test]
#[ignore]
fn over() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 over").is_ok());
    assert_eq!(vec![1, 2, 1], f.stack());
}

#[test]
#[ignore]
fn over_with_three() {
    let mut f = Forth::new();
    assert!(f.eval("1 2 3 over").is_ok());
    assert_eq!(vec![1, 2, 3, 2], f.stack());
}

#[test]
#[ignore]
fn over_error() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::StackUnderflow), f.eval("1 over"));
    assert_eq!(Err(Error::StackUnderflow), f.eval("over"));
}

// User-defined words

#[test]
#[ignore]
fn can_consist_of_built_in_words() {
    let mut f = Forth::new();
    assert!(f.eval(": dup-twice dup dup ;").is_ok());
    assert!(f.eval("1 dup-twice").is_ok());
    assert_eq!(vec![1, 1, 1], f.stack());
}

#[test]
#[ignore]
fn execute_in_the_right_order() {
    let mut f = Forth::new();
    assert!(f.eval(": countup 1 2 3 ;").is_ok());
    assert!(f.eval("countup").is_ok());
    assert_eq!(vec![1, 2, 3], f.stack());
}

#[test]
#[ignore]
fn definitions_are_case_insensitive() {
    let mut f = Forth::new();
    assert!(f.eval(": CoUnT 1 2 3 ;").is_ok());
    assert!(f.eval("count COUNT").is_ok());
    assert_eq!(vec![1, 2, 3, 1, 2, 3], f.stack());
}

#[test]
#[ignore]
fn redefining_an_existing_word() {
    let mut f = Forth::new();
    assert!(f.eval(": foo dup ;").is_ok());
    assert!(f.eval(": foo dup dup ;").is_ok());
    assert!(f.eval("1 foo").is_ok());
    assert_eq!(vec![1, 1, 1], f.stack());
}

#[test]
#[ignore]
fn redefining_an_existing_built_in_word() {
    let mut f = Forth::new();
    assert!(f.eval(": swap dup ;").is_ok());
    assert!(f.eval("1 swap").is_ok());
    assert_eq!(vec![1, 1], f.stack());
}

#[test]
#[ignore]
fn defining_a_number() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::InvalidWord), f.eval(": 1 2 ;"));
}

#[test]
#[ignore]
fn malformed_word_definition() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::InvalidWord), f.eval(":"));
    assert_eq!(Err(Error::InvalidWord), f.eval(": foo"));
    assert_eq!(Err(Error::InvalidWord), f.eval(": foo 1"));
}

#[test]
#[ignore]
fn calling_non_existing_word() {
    let mut f = Forth::new();
    assert_eq!(Err(Error::UnknownWord), f.eval("1 foo"));
}
<|endoftext|>


<commit_before><commit_msg>Rust: Add ownership with references example<commit_after><|endoftext|>


<commit_before><commit_msg>Remove periods from error messages<commit_after><|endoftext|>


<commit_before><commit_msg>build: extract downloaded tar<commit_after><|endoftext|>


<commit_before><commit_msg>Stop specifying VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT as it doesn't seem correct<commit_after><|endoftext|>


<commit_before><commit_msg>rustc: Use set recovery APIs in the TyCtxt interners.<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests to wound allocation and fix a bug found<commit_after><|endoftext|>


<commit_before><commit_msg>Create 4_traitsbounds_mistake1.rs<commit_after>/* Writing a function which adds 2 to every element of vector and a function to multiply 2
   to every element of the vector */

/* NOTES: OWNERSHIP AND BORROW RULES
    1. Only one owner at a time
    2. Only 1 active mutable borrow at a time
    3. Every other borrow after a shared borrow should be a shared borrow
*/

trait Arith:Copy{
    fn add(self, b: Self) -> Self;
    fn mult(self, b: Self) -> Self;
    fn print(self);
}

impl Arith for i32{
    fn add(self, b: i32) -> i32{
        self + b
    }

    fn mult(self, b: Self) -> Self{
        self * b
    }

    fn print(self) {
        println!("Val = {}", self);
    }
}

fn vec_add<T: Arith>(vec: &mut Vec<T>){
    for e in vec.iter_mut(){
        /* e is of type &mut i32. But you can give it to print() which
           expects i32 because rust derefs it implicitly */
        e.print();
        e.add(5);
    }
}

fn main(){
    println!("Hello World");
    let mut vec: Vec<i32> = vec![1,2,3,4,5];
    vec_add(&mut vec);
}

/*

What's the mistake with e.add(5) which is throwing below error. Isn't 'b:Self' of type i32 for the current example

<anon>:35:15: 35:16 error: mismatched types:
 expected `T`,
    found `_`
(expected type parameter,
    found integral variable) [E0308]
<anon>:35         e.add(5);

ANS: Rust won't know the type of 'e' during compile time. It just knows that 'e' is of type 'T' and type 'T'
     is implementing trait 'Arithmatic'.

     It'll just compare : T.add(5)  <--> fn add(val: T, b: T)   because Self is implementors type
     so you are comparing 5 and T here which is wrong

     Practically, lets say you have implemented 'Arith' for 'f32'. e.add(5) cannot be correct for both i32 and f32
     at the same time because 'f32' expects 'f32' as argument.
*/
<|endoftext|>


<commit_before><commit_msg>Added missing files<commit_after>
use {
    EventType,
    Field,
    Observer,
    Triggered,
    Value,
};

/// A event context that can be triggered if ALL event in `events` happened.
pub struct AllEvent<'a, 'b> {
    /// A sequence of events.
    pub events: Field<'a, &'b [&'b Triggered]>,
}

impl<'a, 'b> Clone for AllEvent<'a, 'b> {
    fn clone(&self) -> AllEvent<'static, 'b> {
        AllEvent {
            events: Value(*self.events.get()),
        }
    }
}

impl<'a, 'b> Triggered for AllEvent<'a, 'b> {
    fn get_observer(&self) -> Box<Observer> {
        box AllEventObserver::new(*self.events.get()) as Box<Observer>
    }
}

struct AllEventObserver<'a> {
    observers: Vec<Box<Observer>>,
}

impl<'a> AllEventObserver<'a> {
    pub fn new(events: &'a [&'a Triggered]) -> AllEventObserver<'a> {
        let mut observers = Vec::<Box<Observer>>::new();
        for event in events.iter() {
            observers.push(event.get_observer());
        }
        AllEventObserver {
            observers: observers,
        }
    }
}

impl<'a> Observer for AllEventObserver<'a> {
    fn reset(&mut self) {
        for observer in self.observers.mut_iter() {
            observer.reset();
        }
    }

    fn can_trigger(&self) -> bool {
        for observer in self.observers.iter() {
            if !observer.can_trigger() {
                return false;
            }
        }
        true
    }

    fn after_trigger(&mut self) {
        for observer in self.observers.mut_iter() {
            observer.after_trigger();
        }
    }

    fn update(&mut self, dt: f64) {
        for observer in self.observers.mut_iter() {
            if !observer.can_trigger() {
                observer.update(dt);
            }
        }
    }

    fn on_event(&mut self, e: &EventType) {
        for observer in self.observers.mut_iter() {
            if !observer.can_trigger() {
                observer.on_event(e);
            }
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>hey you know what's a good idea? I should port this to rust for some reason<commit_after>struct Point {
	x: float,
	y: float
}

fn getSquareDistance(p1: Point, p2: Point) -> float {
	let dx : float = p1.x - p2.x;
	let dy : float = p1.y - p2.y;
	return dx * dx + dy * dy;
	}

fn getSquareSegmentDistance(p: Point, p1: Point, p2: Point) -> float {
	let mut dxy = Point { x: p2.x - p1.x, y: p2.y-p1.x};
	let mut xy : Point = Point { x: p1.x, y: p1.y};
	 if dxy.x != 0.0 && dxy.y != 0.0 {
		let t : float =((p.x - p1.x) * dxy.x + (p.y - p1.y) * dxy.y) / (dxy.y * dxy.y + dxy.y * dxy.y);
		if t>1.0 {
			 xy = p2;
		}else if t>0.0 {
			 xy = Point { x: dxy.x * t + p1.x,y: dxy.y * t + p1.y};
		}else{
			 xy  = Point { x: p1.x,y:  p1.y};
		}
	}
	dxy = Point {x: (p.x - xy.x), y: (p.y - xy.y)};
	return dxy.x * dxy.x + dxy.x * dxy.y;
}

fn main() {
	io::println(fmt!("%f",getSquareDistance(Point { x : 1.0, y: 1.0}, Point { x : 3.0, y : 3.0})));
}
<|endoftext|>


<commit_before><commit_msg>Add some basic stuff<commit_after><|endoftext|>


<commit_before><commit_msg>Modeling CPU, part 1<commit_after><|endoftext|>


<commit_before><commit_msg>Unwraps print result<commit_after><|endoftext|>


<commit_before>//! The Ref object is a helper over the link functionality, so one is able to create references to
//! files outside of the imag store.

use std::path::PathBuf;
use std::ops::Deref;
use std::ops::DerefMut;

use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagstore::store::Store;
use libimagerror::into::IntoError;

use toml::Value;

use error::RefErrorKind as REK;
use flags::RefFlags;
use result::Result;

pub struct Ref<'a>(FileLockEntry<'a>);

impl<'a> Ref<'a> {

    /// Try to get `si` as Ref object from the store
    pub fn get(store: &'a Store, si: StoreId) -> Result<Ref<'a>> {
        match store.get(si) {
            Err(e) => return Err(REK::StoreReadError.into_error_with_cause(Box::new(e))),
            Ok(None) => return Err(REK::RefNotInStore.into_error()),
            Ok(Some(fle)) => Ref::read_reference(&fle).map(|_| Ref(fle)),
        }
    }

    fn read_reference(fle: &FileLockEntry<'a>) -> Result<PathBuf> {
        match fle.get_header().read("ref.reference") {
            Ok(Some(Value::String(s))) => Ok(PathBuf::from(s)),
            Ok(Some(_)) => Err(REK::HeaderTypeError.into_error()),
            Ok(None)    => Err(REK::HeaderFieldMissingError.into_error()),
            Err(e)      => Err(REK::StoreReadError.into_error_with_cause(Box::new(e))),
        }
    }

    /// Create a Ref object which refers to `pb`
    pub fn create(store: &Store, pb: PathBuf, flags: RefFlags) -> Result<Ref<'a>> {
        unimplemented!()
    }

    /// Creates a Hash from a PathBuf by making the PathBuf absolute and then running a hash
    /// algorithm on it
    fn hash_path(pb: &PathBuf) -> String {
        unimplemented!()
    }

    /// check whether the pointer the Ref represents still points to a file which exists
    pub fn fs_link_exists(&self) -> bool {
        unimplemented!()
    }

    /// Alias for `r.fs_link_exists() && r.deref().is_file()`
    pub fn is_ref_to_file(&self) -> bool {
        unimplemented!()
    }

    /// Alias for `!Ref::fs_link_exists()`
    pub fn is_dangling(&self) -> bool {
        !self.fs_link_exists()
    }

    /// check whether the pointer the Ref represents is valid
    /// This includes:
    ///     - Hashsum of the file is still the same as stored in the Ref
    ///     - file permissions are still valid
    pub fn fs_link_valid(&self) -> bool {
        unimplemented!()
    }

    /// Check whether the file permissions of the referenced file are equal to the stored
    /// permissions
    pub fn fs_link_valid_permissions(&self) -> bool {
        unimplemented!()
    }

    /// Check whether the Hashsum of the referenced file is equal to the stored hashsum
    pub fn fs_link_valid_hash(&self) -> bool {
        unimplemented!()
    }

    /// Update the Ref by re-checking the file from FS
    /// This errors if the file is not present or cannot be read()
    pub fn update_ref(&mut self) -> Result<()> {
        unimplemented!()
    }

    /// Get the path of the file which is reffered to by this Ref
    pub fn fs_file(&self) -> &PathBuf {
        unimplemented!()
    }

    /// Check whether there is a reference to the file at `pb`
    pub fn exists(store: &Store, pb: PathBuf) -> Result<bool> {
        unimplemented!()
    }

    /// Re-find a referenced file
    ///
    /// This function tries to re-find a ref by searching all directories in `search_roots` recursively
    /// for a file which matches the hash of the Ref `ref`.
    ///
    /// If `search_roots` is `None`, it starts at the filesystem root `/`.
    ///
    /// # Warning
    ///
    /// This option causes heavy I/O as it recursively searches the Filesystem.
    pub fn refind(&self, search_roots: Option<Vec<PathBuf>>) -> Option<PathBuf> {
        unimplemented!()
    }

}

impl<'a> Deref for Ref<'a> {
    type Target = FileLockEntry<'a>;

    fn deref(&self) -> &FileLockEntry<'a> {
        &self.0
    }

}

impl<'a> DerefMut for Ref<'a> {

    fn deref_mut(&mut self) -> &mut FileLockEntry<'a> {
        &mut self.0
    }

}
<commit_msg>Impl Ref::is_ref_to_dir()<commit_after>//! The Ref object is a helper over the link functionality, so one is able to create references to
//! files outside of the imag store.

use std::path::PathBuf;
use std::ops::Deref;
use std::ops::DerefMut;

use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagstore::store::Store;
use libimagerror::into::IntoError;

use toml::Value;

use error::RefErrorKind as REK;
use flags::RefFlags;
use result::Result;

pub struct Ref<'a>(FileLockEntry<'a>);

impl<'a> Ref<'a> {

    /// Try to get `si` as Ref object from the store
    pub fn get(store: &'a Store, si: StoreId) -> Result<Ref<'a>> {
        match store.get(si) {
            Err(e) => return Err(REK::StoreReadError.into_error_with_cause(Box::new(e))),
            Ok(None) => return Err(REK::RefNotInStore.into_error()),
            Ok(Some(fle)) => Ref::read_reference(&fle).map(|_| Ref(fle)),
        }
    }

    fn read_reference(fle: &FileLockEntry<'a>) -> Result<PathBuf> {
        match fle.get_header().read("ref.reference") {
            Ok(Some(Value::String(s))) => Ok(PathBuf::from(s)),
            Ok(Some(_)) => Err(REK::HeaderTypeError.into_error()),
            Ok(None)    => Err(REK::HeaderFieldMissingError.into_error()),
            Err(e)      => Err(REK::StoreReadError.into_error_with_cause(Box::new(e))),
        }
    }

    /// Create a Ref object which refers to `pb`
    pub fn create(store: &Store, pb: PathBuf, flags: RefFlags) -> Result<Ref<'a>> {
        unimplemented!()
    }

    /// Creates a Hash from a PathBuf by making the PathBuf absolute and then running a hash
    /// algorithm on it
    fn hash_path(pb: &PathBuf) -> String {
        unimplemented!()
    }

    /// check whether the pointer the Ref represents still points to a file which exists
    pub fn fs_link_exists(&self) -> bool {
        unimplemented!()
    }

    /// Alias for `r.fs_link_exists() && r.deref().is_file()`
    pub fn is_ref_to_file(&self) -> bool {
        unimplemented!()
    }

    /// Alias for `r.fs_link_exists() && r.deref().is_dir()`
    pub fn is_ref_to_dir(&self) -> bool {
        unimplemented!()
    }

    /// Alias for `!Ref::fs_link_exists()`
    pub fn is_dangling(&self) -> bool {
        !self.fs_link_exists()
    }

    /// check whether the pointer the Ref represents is valid
    /// This includes:
    ///     - Hashsum of the file is still the same as stored in the Ref
    ///     - file permissions are still valid
    pub fn fs_link_valid(&self) -> bool {
        unimplemented!()
    }

    /// Check whether the file permissions of the referenced file are equal to the stored
    /// permissions
    pub fn fs_link_valid_permissions(&self) -> bool {
        unimplemented!()
    }

    /// Check whether the Hashsum of the referenced file is equal to the stored hashsum
    pub fn fs_link_valid_hash(&self) -> bool {
        unimplemented!()
    }

    /// Update the Ref by re-checking the file from FS
    /// This errors if the file is not present or cannot be read()
    pub fn update_ref(&mut self) -> Result<()> {
        unimplemented!()
    }

    /// Get the path of the file which is reffered to by this Ref
    pub fn fs_file(&self) -> &PathBuf {
        unimplemented!()
    }

    /// Check whether there is a reference to the file at `pb`
    pub fn exists(store: &Store, pb: PathBuf) -> Result<bool> {
        unimplemented!()
    }

    /// Re-find a referenced file
    ///
    /// This function tries to re-find a ref by searching all directories in `search_roots` recursively
    /// for a file which matches the hash of the Ref `ref`.
    ///
    /// If `search_roots` is `None`, it starts at the filesystem root `/`.
    ///
    /// # Warning
    ///
    /// This option causes heavy I/O as it recursively searches the Filesystem.
    pub fn refind(&self, search_roots: Option<Vec<PathBuf>>) -> Option<PathBuf> {
        unimplemented!()
    }

}

impl<'a> Deref for Ref<'a> {
    type Target = FileLockEntry<'a>;

    fn deref(&self) -> &FileLockEntry<'a> {
        &self.0
    }

}

impl<'a> DerefMut for Ref<'a> {

    fn deref_mut(&mut self) -> &mut FileLockEntry<'a> {
        &mut self.0
    }

}
<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::ops::Deref;
use std::path::Path;
use std::path::PathBuf;

use std::fmt::{Display, Debug, Formatter};
use std::fmt::Error as FmtError;
use std::result::Result as RResult;
use std::path::Components;

use libimagerror::into::IntoError;

use error::StoreErrorKind as SEK;
use error::MapErrInto;
use store::Result;

/// The Index into the Store
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub struct StoreId {
    base: Option<PathBuf>,
    id:   PathBuf,
}

impl StoreId {

    pub fn new(base: Option<PathBuf>, id: PathBuf) -> Result<StoreId> {
        StoreId::new_baseless(id).map(|mut sid| { sid.base = base; sid })
    }

    /// Try to create a StoreId object from a filesystem-absolute path.
    ///
    /// Automatically creates a StoreId object which has a `base` set to `store_part` if stripping
    /// the `store_part` from the `full_path` succeeded.
    ///
    /// Returns a `StoreErrorKind::StoreIdBuildFromFullPathError` if stripping failes.
    pub fn from_full_path<D>(store_part: &PathBuf, full_path: D) -> Result<StoreId>
        where D: Deref<Target = Path>
    {
        let p = try!(
            full_path.strip_prefix(store_part).map_err_into(SEK::StoreIdBuildFromFullPathError)
        );
        StoreId::new(Some(store_part.clone()), PathBuf::from(p))
    }

    pub fn new_baseless(id: PathBuf) -> Result<StoreId> {
        if id.is_absolute() {
            Err(SEK::StoreIdLocalPartAbsoluteError.into_error())
        } else {
            Ok(StoreId {
                base: None,
                id: id
            })
        }
    }

    pub fn without_base(mut self) -> StoreId {
        self.base = None;
        self
    }

    pub fn with_base(mut self, base: PathBuf) -> Self {
        self.base = Some(base);
        self
    }

    /// Transform the StoreId object into a PathBuf, error if the base of the StoreId is not
    /// specified.
    pub fn into_pathbuf(self) -> Result<PathBuf> {
        let mut base = try!(self.base.ok_or(SEK::StoreIdHasNoBaseError.into_error()));
        base.push(self.id);
        Ok(base)
    }

    pub fn exists(&self) -> bool {
        // TODO: hiding error here.
        self.clone().into_pathbuf().map(|pb| pb.exists()).unwrap_or(false)
    }

    pub fn to_str(&self) -> Result<String> {
        if self.base.is_some() {
            let mut base = self.base.as_ref().cloned().unwrap();
            base.push(self.id.clone());
            base
        } else {
            self.id.clone()
        }
        .to_str()
        .map(String::from)
        .ok_or(SEK::StoreIdHandlingError.into_error())
    }

    /// Returns the components of the `id` part of the StoreId object.
    ///
    /// Can be used to check whether a StoreId points to an entry in a specific collection of
    /// StoreIds.
    pub fn components(&self) -> Components {
        self.id.components()
    }

    /// Get the _local_ part of a StoreId object, as in "the part from the store root to the entry".
    pub fn local(&self) -> &PathBuf {
        &self.id
    }

}

impl Display for StoreId {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        match self.id.to_str() {
            Some(s) => write!(fmt, "{}", s),
            None    => write!(fmt, "{}", self.id.to_string_lossy()),
        }
    }

}

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
pub trait IntoStoreId {
    fn into_storeid(self) -> Result<StoreId>;
}

impl IntoStoreId for StoreId {
    fn into_storeid(self) -> Result<StoreId> {
        Ok(self)
    }
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> Result<StoreId> {
        StoreId::new_baseless(self)
    }
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        /// A helper module to create valid module entry paths
        pub mod module_path {
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            use $crate::storeid::StoreId;
            use $crate::store::Result;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("{}", $name));
                    path.push(pa.as_ref().clone());
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(name);
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(self) -> Result<$crate::storeid::StoreId> {
                    StoreId::new(None, self.0)
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    iter: Box<Iterator<Item = StoreId>>,
}

impl Debug for StoreIdIterator {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        write!(fmt, "StoreIdIterator")
    }

}

impl StoreIdIterator {

    pub fn new(iter: Box<Iterator<Item = StoreId>>) -> StoreIdIterator {
        StoreIdIterator {
            iter: iter,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.iter.next()
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().unwrap().to_str().unwrap(), "test/test");
    }

}
<commit_msg>Reimplement StoreId::to_str() to remove unwrap()<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::ops::Deref;
use std::path::Path;
use std::path::PathBuf;

use std::fmt::{Display, Debug, Formatter};
use std::fmt::Error as FmtError;
use std::result::Result as RResult;
use std::path::Components;

use libimagerror::into::IntoError;

use error::StoreErrorKind as SEK;
use error::MapErrInto;
use store::Result;

/// The Index into the Store
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub struct StoreId {
    base: Option<PathBuf>,
    id:   PathBuf,
}

impl StoreId {

    pub fn new(base: Option<PathBuf>, id: PathBuf) -> Result<StoreId> {
        StoreId::new_baseless(id).map(|mut sid| { sid.base = base; sid })
    }

    /// Try to create a StoreId object from a filesystem-absolute path.
    ///
    /// Automatically creates a StoreId object which has a `base` set to `store_part` if stripping
    /// the `store_part` from the `full_path` succeeded.
    ///
    /// Returns a `StoreErrorKind::StoreIdBuildFromFullPathError` if stripping failes.
    pub fn from_full_path<D>(store_part: &PathBuf, full_path: D) -> Result<StoreId>
        where D: Deref<Target = Path>
    {
        let p = try!(
            full_path.strip_prefix(store_part).map_err_into(SEK::StoreIdBuildFromFullPathError)
        );
        StoreId::new(Some(store_part.clone()), PathBuf::from(p))
    }

    pub fn new_baseless(id: PathBuf) -> Result<StoreId> {
        if id.is_absolute() {
            Err(SEK::StoreIdLocalPartAbsoluteError.into_error())
        } else {
            Ok(StoreId {
                base: None,
                id: id
            })
        }
    }

    pub fn without_base(mut self) -> StoreId {
        self.base = None;
        self
    }

    pub fn with_base(mut self, base: PathBuf) -> Self {
        self.base = Some(base);
        self
    }

    /// Transform the StoreId object into a PathBuf, error if the base of the StoreId is not
    /// specified.
    pub fn into_pathbuf(self) -> Result<PathBuf> {
        let mut base = try!(self.base.ok_or(SEK::StoreIdHasNoBaseError.into_error()));
        base.push(self.id);
        Ok(base)
    }

    pub fn exists(&self) -> bool {
        // TODO: hiding error here.
        self.clone().into_pathbuf().map(|pb| pb.exists()).unwrap_or(false)
    }

    pub fn to_str(&self) -> Result<String> {
        self.base
            .as_ref()
            .cloned()
            .map(|mut base| { base.push(self.id.clone()); base })
            .unwrap_or_else(|| self.id.clone())
            .to_str()
            .map(String::from)
            .ok_or(SEK::StoreIdHandlingError.into_error())
    }

    /// Returns the components of the `id` part of the StoreId object.
    ///
    /// Can be used to check whether a StoreId points to an entry in a specific collection of
    /// StoreIds.
    pub fn components(&self) -> Components {
        self.id.components()
    }

    /// Get the _local_ part of a StoreId object, as in "the part from the store root to the entry".
    pub fn local(&self) -> &PathBuf {
        &self.id
    }

}

impl Display for StoreId {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        match self.id.to_str() {
            Some(s) => write!(fmt, "{}", s),
            None    => write!(fmt, "{}", self.id.to_string_lossy()),
        }
    }

}

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
pub trait IntoStoreId {
    fn into_storeid(self) -> Result<StoreId>;
}

impl IntoStoreId for StoreId {
    fn into_storeid(self) -> Result<StoreId> {
        Ok(self)
    }
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> Result<StoreId> {
        StoreId::new_baseless(self)
    }
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        /// A helper module to create valid module entry paths
        pub mod module_path {
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            use $crate::storeid::StoreId;
            use $crate::store::Result;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("{}", $name));
                    path.push(pa.as_ref().clone());
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(name);
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(self) -> Result<$crate::storeid::StoreId> {
                    StoreId::new(None, self.0)
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    iter: Box<Iterator<Item = StoreId>>,
}

impl Debug for StoreIdIterator {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        write!(fmt, "StoreIdIterator")
    }

}

impl StoreIdIterator {

    pub fn new(iter: Box<Iterator<Item = StoreId>>) -> StoreIdIterator {
        StoreIdIterator {
            iter: iter,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.iter.next()
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().unwrap().to_str().unwrap(), "test/test");
    }

}
<|endoftext|>


<commit_before><commit_msg>refactor(tokenizer): remove nested match<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify get_sample_count()<commit_after><|endoftext|>


<commit_before><commit_msg>Add another file to the examples directory<commit_after>
extern crate itertools;

use itertools::Itertools;

fn main() {
    let data = "abc12345abc".chars();

    // This example does something like .group_by().
    //
    // Instead of allocating, it just walks the iterator twice, and this
    // requires that the iterator is small and easy to clone, like for example
    // the slice or chars iterators.

    // using Itertools::batching
    //
    // Yield (key, iterator) for each run of identical keys.
    let key_func = |c: char| c.is_alphabetic();
    for (key, iter) in data.batching(|mut it| {
            let start = it.clone();
            match it.next() {
                None => return None,
                Some(elt) => {
                    let key = key_func(elt);
                    // using Itertools::take_while_ref
                    let n = 1 + it.take_while_ref(|elt| key_func(*elt) == key).count();
                    return Some((key, start.take(n)))
                }
            }
        })
    {
        for elt in iter {
            println!("Key={:?}, elt={:?}", key, elt);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>new example<commit_after>extern crate lua_patterns;
use lua_patterns::LuaPattern;

fn main() {
    let mut m = LuaPattern::new("(%a+) one");
    let text = " hello one two";
    assert!(m.matches(text));
    assert_eq!(m.capture(1),1..6);
    assert_eq!(m.capture(0),1..10);
}
<|endoftext|>


<commit_before><commit_msg>new variable names<commit_after><|endoftext|>


<commit_before><commit_msg>Make get_prompt() more readable.<commit_after><|endoftext|>


<commit_before><commit_msg>Minor tidy of create_logger.<commit_after><|endoftext|>


<commit_before><commit_msg>config files<commit_after><|endoftext|>


<commit_before><commit_msg>Output as the program is interpreted<commit_after><|endoftext|>


<commit_before><commit_msg>Chore(util): file_is_binary param and error string cleanup<commit_after><|endoftext|>