<commit_before>// Copyright 2014 Johannes Köster, Christopher Schröder.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Fasta reading and writing.
//!
//! # Example
//!
//! ```
//! use std::io;
//! use bio::io::fasta;
//! let reader = fasta::Reader::new(io::stdin());
//! ```

use std::io;
use std::io::prelude::*;
use std::ascii::AsciiExt;
use std::collections;
use std::fs;
use std::path::Path;
use std::convert::AsRef;
use std::ffi::AsOsStr;

use itertools::Itertools;

use csv;

pub struct Reader<R: io::Read> {
    reader: io::BufReader<R>,
    line: String
}

impl<R: io::Read> Reader<R> {
    /// Create a new FastQ reader.
    pub fn new(reader: R) -> Self {
        Reader { reader: io::BufReader::new(reader), line: String::new() }
    }

    pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Reader<fs::File>> {
        fs::File::open(path).map(|f| Reader::new(f))
    }

    pub fn read(&mut self, record: &mut Record) -> io::Result<()> {
        record.clear();
        if self.line.is_empty() {
            try!(self.reader.read_line(&mut self.line));
            if self.line.is_empty() {
                return Ok(());
            }
        }

        if !self.line.starts_with(">") {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "Expected > at record start."
            ));
        }
        record.header.push_str(&self.line);
        loop {
            self.line.clear();
            try!(self.reader.read_line(&mut self.line));
            record.seq.push_str(&self.line.trim_right());
            if self.line.is_empty() || self.line.starts_with(">") {
                break;
            }
        }

        Ok(())
    }

    /// Return an iterator over the records of this FastQ file.
    pub fn records(self) -> Records<R> {
        Records { reader: self }
    }
}

pub struct Index {
    inner: collections::BTreeMap<Vec<u8>, IndexRecord>,
}

impl Index {
    pub fn new<R: io::Read>(fai: R) -> csv::Result<Self> {
        let mut inner = collections::BTreeMap::new();
        let mut fai_reader = csv::Reader::from_reader(fai).delimiter(b'\t').has_headers(false);
        for row in fai_reader.decode() {
            let (name, record): (String, IndexRecord) = try!(row);
            inner.insert(name.into_bytes(), record);
        }
        Ok(Index { inner: inner })
    }

    pub fn from_file<P: AsRef<Path>>(path: &P) -> csv::Result<Self> {
        match fs::File::open(path) {
            Ok(fai) => Self::new(fai),
            Err(e)  => Err(csv::Error::Io(e))
        }
    }

    pub fn sequences(&self) -> Vec<Sequence> {
        self.inner.iter().map(|(name, record)| Sequence { name: name.clone(), len: record.len }).collect_vec()
    }
}

pub struct IndexedReader<R: io::Read + io::Seek> {
    reader: io::BufReader<R>,
    pub index: Index,
}

impl<R: io::Read + io::Seek> IndexedReader<R> {
    pub fn new<I: io::Read>(fasta: R, fai: I) -> csv::Result<Self> {
        let index = try!(Index::new(fai));
        Ok(IndexedReader { reader: io::BufReader::new(fasta), index: index })
    }

    pub fn with_index(fasta: R, index: Index) -> Self {
        IndexedReader { reader: io::BufReader::new(fasta), index: index }
    }

    pub fn from_file<P: AsRef<Path>>(path: &P) -> csv::Result<IndexedReader<fs::File>> {
        let mut ext = path.as_ref().extension().unwrap_or("".as_os_str()).to_str().unwrap().to_string();
        ext.push_str(".fai");
        let fai_path = path.as_ref().with_extension(ext);

        let index = try!(Index::from_file(&fai_path));
        match fs::File::open(path) {
            Ok(fasta) => Ok(IndexedReader::with_index(fasta, index)),
            Err(e)    => Err(csv::Error::Io(e))
        }
    }

    pub fn read_all(&mut self, seqname: &[u8], seq: &mut Vec<u8>) -> io::Result<()> {
        match self.index.inner.get(seqname) {
            Some(&idx) => self.read(seqname, 0, idx.len, seq),
            None      => Err(
                io::Error::new(
                    io::ErrorKind::Other,
                    "Unknown sequence name."
                )
            )
        }
    }

    pub fn read(&mut self, seqname: &[u8], start: u64, stop: u64, seq: &mut Vec<u8>) -> io::Result<()> {
        match self.index.inner.get(seqname) {
            Some(idx) => {
                seq.clear();
                // derived from
                // http://www.allenyu.info/item/24-quickly-fetch-sequence-from-samtools-faidx-indexed-fasta-sequences.html
                let line = start / idx.line_bases * idx.line_bytes;
                let line_offset = start % idx.line_bases;
                let offset = idx.offset + line + line_offset;
                let lines = stop / idx.line_bases * idx.line_bytes - line;
                let line_stop = stop % idx.line_bases - if lines == 0 { line_offset } else { 0 };

                try!(self.reader.seek(io::SeekFrom::Start(offset)));
                let mut buf = vec![0u8; idx.line_bases as usize];
                for _ in 0..lines {
                    // read full lines
                    try!(self.reader.read(&mut buf));
                    seq.push_all(&buf);
                }
                // read last line
                println!("linestop {}", line_stop);
                try!(self.reader.read(&mut buf[..line_stop as usize]));
                seq.push_all(&buf[..line_stop as usize]);
                Ok(())
            },
            None      => Err(
                io::Error::new(
                    io::ErrorKind::Other,
                    "Unknown sequence name."
                )
            )
        }
    }
}

#[derive(RustcDecodable, Debug, Copy, Clone)]
struct IndexRecord {
    len: u64,
    offset: u64,
    line_bases: u64,
    line_bytes: u64,
}

pub struct Sequence {
    pub name: Vec<u8>,
    pub len: u64,
}

/// A Fasta writer.
pub struct Writer<W: io::Write> {
    writer: io::BufWriter<W>,
}

impl<W: io::Write> Writer<W> {
    /// Create a new Fasta writer.
    pub fn new(writer: W) -> Self {
        Writer { writer: io::BufWriter::new(writer) }
    }

    pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Writer<fs::File>> {
        fs::File::create(path).map(|f| Writer::new(f))
    }

    /// Directly write a Fasta record.
    pub fn write_record(&mut self, record: Record) -> io::Result<()> {
        self.write(record.id().unwrap_or(""), &record.desc(), record.seq())
    }

    /// Write a Fasta record with given values.
    ///
    /// # Arguments
    ///
    /// * `id` - the record id
    /// * `desc` - the optional descriptions
    /// * `seq` - the sequence
    pub fn write(&mut self, id: &str, desc: &[&str], seq: &[u8]) -> io::Result<()> {
        try!(self.writer.write(b">"));
        try!(self.writer.write(id.as_bytes()));
        if !desc.is_empty() {
            for d in desc {
                try!(self.writer.write(b" "));
                try!(self.writer.write(d.as_bytes()));
            }
        }
        try!(self.writer.write(b"\n"));
        try!(self.writer.write(seq));
        try!(self.writer.write(b"\n"));

        Ok(())
    }

    /// Flush the writer, ensuring that everything is written.
    pub fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }
}

pub struct Record {
    header: String,
    seq: String,
}

impl Record {
    pub fn new() -> Self {
        Record { header: String::new(), seq: String::new() }
    }

    pub fn is_empty(&self) -> bool {
        self.header.is_empty() && self.seq.is_empty()
    }

    /// Check validity of Fasta record.
    pub fn check(&self) -> Result<(), &str> {
        if self.id().is_none() {
            return Err("Expecting id for FastQ record.");
        }
        if !self.seq.is_ascii() {
            return Err("Non-ascii character found in sequence.");
        }

        Ok(())
    }

    /// Return the id of the record.
    pub fn id(&self) -> Option<&str> {
        self.header[1..].words().next()
    }

    /// Return descriptions if present.
    pub fn desc(&self) -> Vec<&str> {
        self.header[1..].words().skip(1).collect()
    }

    /// Return the sequence of the record.
    pub fn seq(&self) -> &[u8] {
        self.seq.as_bytes()
    }

    fn clear(&mut self) {
        self.header.clear();
        self.seq.clear();
    }
}

/// An iterator over the records of a Fasta file.
pub struct Records<R: io::Read> {
    reader: Reader<R>,
}

impl<R: io::Read> Iterator for Records<R> {
    type Item = io::Result<Record>;

    fn next(&mut self) -> Option<io::Result<Record>> {
        let mut record = Record::new();
        match self.reader.read(&mut record) {
            Ok(()) if record.is_empty() => None,
            Ok(())   => Some(Ok(record)),
            Err(err) => Some(Err(err))
        }
    }
}

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

    const FASTA_FILE: &'static [u8] = b">id desc
ACCGTAGGCTGA
";
    const FAI_FILE: &'static [u8] = b"id\t12\t9\t60\t61
";

    #[test]
    fn test_reader() {
        let reader = Reader::new(FASTA_FILE);
        let records: Vec<io::Result<Record>> = reader.records().collect();
        assert!(records.len() == 1);
        for res in records {
            let record = res.ok().unwrap();
            assert_eq!(record.check(), Ok(()));
            assert_eq!(record.id(), Some("id"));
            assert_eq!(record.desc(), ["desc"]);
            assert_eq!(record.seq(), b"ACCGTAGGCTGA");
        }
    }

    #[test]
    fn test_indexed_reader() {
        let mut reader = IndexedReader::new(io::Cursor::new(FASTA_FILE), FAI_FILE).ok().expect("Error reading index");
        let mut seq = Vec::new();
        reader.read(b"id", 1, 5, &mut seq).ok().expect("Error reading sequence.");
        assert_eq!(seq, b"CCGT");
    }

    #[test]
    fn test_writer() {
        let mut writer = Writer::new(Vec::new());
        writer.write("id", &["desc"], b"ACCGTAGGCTGA").ok().expect("Expected successful write");
        writer.flush().ok().expect("Expected successful write");
        assert_eq!(writer.writer.get_ref(), &FASTA_FILE);
    }
}
<commit_msg>Minor.<commit_after>// Copyright 2014 Johannes Köster, Christopher Schröder.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Fasta reading and writing.
//!
//! # Example
//!
//! ```
//! use std::io;
//! use bio::io::fasta;
//! let reader = fasta::Reader::new(io::stdin());
//! ```

use std::io;
use std::io::prelude::*;
use std::ascii::AsciiExt;
use std::collections;
use std::fs;
use std::path::Path;
use std::convert::AsRef;
use std::ffi::AsOsStr;

use itertools::Itertools;

use csv;

pub struct Reader<R: io::Read> {
    reader: io::BufReader<R>,
    line: String
}

impl<R: io::Read> Reader<R> {
    /// Create a new FastQ reader.
    pub fn new(reader: R) -> Self {
        Reader { reader: io::BufReader::new(reader), line: String::new() }
    }

    pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Reader<fs::File>> {
        fs::File::open(path).map(|f| Reader::new(f))
    }

    pub fn read(&mut self, record: &mut Record) -> io::Result<()> {
        record.clear();
        if self.line.is_empty() {
            try!(self.reader.read_line(&mut self.line));
            if self.line.is_empty() {
                return Ok(());
            }
        }

        if !self.line.starts_with(">") {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "Expected > at record start."
            ));
        }
        record.header.push_str(&self.line);
        loop {
            self.line.clear();
            try!(self.reader.read_line(&mut self.line));
            record.seq.push_str(&self.line.trim_right());
            if self.line.is_empty() || self.line.starts_with(">") {
                break;
            }
        }

        Ok(())
    }

    /// Return an iterator over the records of this FastQ file.
    pub fn records(self) -> Records<R> {
        Records { reader: self }
    }
}

pub struct Index {
    inner: collections::BTreeMap<Vec<u8>, IndexRecord>,
}

impl Index {
    pub fn new<R: io::Read>(fai: R) -> csv::Result<Self> {
        let mut inner = collections::BTreeMap::new();
        let mut fai_reader = csv::Reader::from_reader(fai).delimiter(b'\t').has_headers(false);
        for row in fai_reader.decode() {
            let (name, record): (String, IndexRecord) = try!(row);
            inner.insert(name.into_bytes(), record);
        }
        Ok(Index { inner: inner })
    }

    pub fn from_file<P: AsRef<Path>>(path: &P) -> csv::Result<Self> {
        match fs::File::open(path) {
            Ok(fai) => Self::new(fai),
            Err(e)  => Err(csv::Error::Io(e))
        }
    }

    pub fn with_fasta_file<P: AsRef<Path>>(fasta_path: &P) -> csv::Result<Self> {
        let mut ext = fasta_path.as_ref().extension().unwrap_or("".as_os_str()).to_str().unwrap().to_string();
        ext.push_str(".fai");
        let fai_path = fasta_path.as_ref().with_extension(ext);

        Self::from_file(&fai_path)
    }

    pub fn sequences(&self) -> Vec<Sequence> {
        self.inner.iter().map(|(name, record)| Sequence { name: name.clone(), len: record.len }).collect_vec()
    }
}

pub struct IndexedReader<R: io::Read + io::Seek> {
    reader: io::BufReader<R>,
    pub index: Index,
}

impl<R: io::Read + io::Seek> IndexedReader<R> {
    pub fn new<I: io::Read>(fasta: R, fai: I) -> csv::Result<Self> {
        let index = try!(Index::new(fai));
        Ok(IndexedReader { reader: io::BufReader::new(fasta), index: index })
    }

    pub fn with_index(fasta: R, index: Index) -> Self {
        IndexedReader { reader: io::BufReader::new(fasta), index: index }
    }

    pub fn from_file<P: AsRef<Path>>(path: &P) -> csv::Result<IndexedReader<fs::File>> {
        let index = try!(Index::with_fasta_file(path));

        match fs::File::open(path) {
            Ok(fasta) => Ok(IndexedReader::with_index(fasta, index)),
            Err(e)    => Err(csv::Error::Io(e))
        }
    }

    pub fn read_all(&mut self, seqname: &[u8], seq: &mut Vec<u8>) -> io::Result<()> {
        match self.index.inner.get(seqname) {
            Some(&idx) => self.read(seqname, 0, idx.len, seq),
            None      => Err(
                io::Error::new(
                    io::ErrorKind::Other,
                    "Unknown sequence name."
                )
            )
        }
    }

    pub fn read(&mut self, seqname: &[u8], start: u64, stop: u64, seq: &mut Vec<u8>) -> io::Result<()> {
        match self.index.inner.get(seqname) {
            Some(idx) => {
                seq.clear();
                // derived from
                // http://www.allenyu.info/item/24-quickly-fetch-sequence-from-samtools-faidx-indexed-fasta-sequences.html
                let line = start / idx.line_bases * idx.line_bytes;
                let line_offset = start % idx.line_bases;
                let offset = idx.offset + line + line_offset;
                let lines = stop / idx.line_bases * idx.line_bytes - line;
                let line_stop = stop % idx.line_bases - if lines == 0 { line_offset } else { 0 };

                try!(self.reader.seek(io::SeekFrom::Start(offset)));
                let mut buf = vec![0u8; idx.line_bases as usize];
                for _ in 0..lines {
                    // read full lines
                    try!(self.reader.read(&mut buf));
                    seq.push_all(&buf);
                }
                // read last line
                println!("linestop {}", line_stop);
                try!(self.reader.read(&mut buf[..line_stop as usize]));
                seq.push_all(&buf[..line_stop as usize]);
                Ok(())
            },
            None      => Err(
                io::Error::new(
                    io::ErrorKind::Other,
                    "Unknown sequence name."
                )
            )
        }
    }
}

#[derive(RustcDecodable, Debug, Copy, Clone)]
struct IndexRecord {
    len: u64,
    offset: u64,
    line_bases: u64,
    line_bytes: u64,
}

pub struct Sequence {
    pub name: Vec<u8>,
    pub len: u64,
}

/// A Fasta writer.
pub struct Writer<W: io::Write> {
    writer: io::BufWriter<W>,
}

impl<W: io::Write> Writer<W> {
    /// Create a new Fasta writer.
    pub fn new(writer: W) -> Self {
        Writer { writer: io::BufWriter::new(writer) }
    }

    pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Writer<fs::File>> {
        fs::File::create(path).map(|f| Writer::new(f))
    }

    /// Directly write a Fasta record.
    pub fn write_record(&mut self, record: Record) -> io::Result<()> {
        self.write(record.id().unwrap_or(""), &record.desc(), record.seq())
    }

    /// Write a Fasta record with given values.
    ///
    /// # Arguments
    ///
    /// * `id` - the record id
    /// * `desc` - the optional descriptions
    /// * `seq` - the sequence
    pub fn write(&mut self, id: &str, desc: &[&str], seq: &[u8]) -> io::Result<()> {
        try!(self.writer.write(b">"));
        try!(self.writer.write(id.as_bytes()));
        if !desc.is_empty() {
            for d in desc {
                try!(self.writer.write(b" "));
                try!(self.writer.write(d.as_bytes()));
            }
        }
        try!(self.writer.write(b"\n"));
        try!(self.writer.write(seq));
        try!(self.writer.write(b"\n"));

        Ok(())
    }

    /// Flush the writer, ensuring that everything is written.
    pub fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }
}

pub struct Record {
    header: String,
    seq: String,
}

impl Record {
    pub fn new() -> Self {
        Record { header: String::new(), seq: String::new() }
    }

    pub fn is_empty(&self) -> bool {
        self.header.is_empty() && self.seq.is_empty()
    }

    /// Check validity of Fasta record.
    pub fn check(&self) -> Result<(), &str> {
        if self.id().is_none() {
            return Err("Expecting id for FastQ record.");
        }
        if !self.seq.is_ascii() {
            return Err("Non-ascii character found in sequence.");
        }

        Ok(())
    }

    /// Return the id of the record.
    pub fn id(&self) -> Option<&str> {
        self.header[1..].words().next()
    }

    /// Return descriptions if present.
    pub fn desc(&self) -> Vec<&str> {
        self.header[1..].words().skip(1).collect()
    }

    /// Return the sequence of the record.
    pub fn seq(&self) -> &[u8] {
        self.seq.as_bytes()
    }

    fn clear(&mut self) {
        self.header.clear();
        self.seq.clear();
    }
}

/// An iterator over the records of a Fasta file.
pub struct Records<R: io::Read> {
    reader: Reader<R>,
}

impl<R: io::Read> Iterator for Records<R> {
    type Item = io::Result<Record>;

    fn next(&mut self) -> Option<io::Result<Record>> {
        let mut record = Record::new();
        match self.reader.read(&mut record) {
            Ok(()) if record.is_empty() => None,
            Ok(())   => Some(Ok(record)),
            Err(err) => Some(Err(err))
        }
    }
}

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

    const FASTA_FILE: &'static [u8] = b">id desc
ACCGTAGGCTGA
";
    const FAI_FILE: &'static [u8] = b"id\t12\t9\t60\t61
";

    #[test]
    fn test_reader() {
        let reader = Reader::new(FASTA_FILE);
        let records: Vec<io::Result<Record>> = reader.records().collect();
        assert!(records.len() == 1);
        for res in records {
            let record = res.ok().unwrap();
            assert_eq!(record.check(), Ok(()));
            assert_eq!(record.id(), Some("id"));
            assert_eq!(record.desc(), ["desc"]);
            assert_eq!(record.seq(), b"ACCGTAGGCTGA");
        }
    }

    #[test]
    fn test_indexed_reader() {
        let mut reader = IndexedReader::new(io::Cursor::new(FASTA_FILE), FAI_FILE).ok().expect("Error reading index");
        let mut seq = Vec::new();
        reader.read(b"id", 1, 5, &mut seq).ok().expect("Error reading sequence.");
        assert_eq!(seq, b"CCGT");
    }

    #[test]
    fn test_writer() {
        let mut writer = Writer::new(Vec::new());
        writer.write("id", &["desc"], b"ACCGTAGGCTGA").ok().expect("Expected successful write");
        writer.flush().ok().expect("Expected successful write");
        assert_eq!(writer.writer.get_ref(), &FASTA_FILE);
    }
}
<|endoftext|>


<commit_before><commit_msg>REMEMBER TO TRACK THE FILES, TICKI<commit_after>//! This is a temporary implementation of rsa until liboctavo is ported to redox
//! Note that this is not secure. It's trivial to crack. This implementation is just
//! for testing.

fn mod_pow(b: u64, e: u64, m: u64) -> u64 {
    let mut c = 1;
    let mut e_prime = 0;

    loop {
        e_prime += 1;
        c = (b * c) % m;

        if e_prime >= e {
            break;
        }
    }

    c
}

fn encrypt(msg: u64, key: (u64, u64)) -> u64 {
    mod_pow(msg, key.1, key.0)
}
fn decrypt(enc_msg: u64, key: (u64, u64)) -> u64 {
    mod_pow(enc_msg, key.1, key.0)
}
<|endoftext|>


<commit_before><commit_msg>Optimize randomizer performance<commit_after><|endoftext|>


<commit_before><commit_msg>[server] Add initial stub server<commit_after>extern crate encoding;

use std::io::{Read, Write};
use std::net::TcpListener;
use std::os::unix::io::AsRawFd;
use std::thread;
use encoding::{Encoding, EncoderTrap, DecoderTrap};
use encoding::all::{ASCII, EUC_JP};

fn main() {
    let listener = TcpListener::bind(("127.0.0.1", 11178)).unwrap();
    let encoding = EUC_JP;

    for stream in listener.incoming() {
        match stream {
            Ok(mut stream) => {
                thread::spawn(move || {
                    println!("Connected {}", stream.as_raw_fd());
                    let _ = handle_stream(&mut stream, encoding);
                    println!("Disconnected {}", stream.as_raw_fd());
                });
            }
            Err(e) => {
                let _ = writeln!(&mut std::io::stderr(), "{}", e);
            }
        }
    }
}

fn handle_stream<T: Read + Write>(stream: &mut T, encoding: &Encoding) -> std::io::Result<()> {
    loop {
        let mut cmd = [0; 1];
        let r = try!(stream.read(&mut cmd));
        if r == 0 {
            break;
        }
        match cmd[0] {
            0x30 => {
                break;
            }
            0x31 => {
                let _ = respond_candidate(stream, encoding);
            }
            0x32 => {
                let _ = respond_version(stream);
            }
            _ => { println!("Unknown message {}", cmd[0]); }
        }
    }
    return Ok(());
}

fn respond_version(stream: &mut Write) -> std::io::Result<()> {
    let _ = try!(write_with_encoding(stream, "skkserv-rust:0.1.0", ASCII));
    try!(stream.flush());
    return Ok(());
}

fn respond_candidate<T: Read + Write>(stream: &mut T, encoding: &Encoding) -> std::io::Result<()> {
    let input = try!(read_candidate(stream, encoding));
    println!("Asked {}", input);
    let _ = try!(write_with_encoding(stream, "1/aiueo/\n", encoding));
    return Ok(());
}

fn read_candidate(stream: &mut Read, encoding: &Encoding) -> std::io::Result<String> {
    let mut buf = Vec::new();

    loop {
        let mut t = [0; 1024];
        let r = try!(stream.read(&mut t));
        if r == 0 {
            panic!("Unterminated input");
        }
        for i in 0..r {
            if t[i] == 0x20 {
                return Ok(encoding.decode(&buf, DecoderTrap::Strict).unwrap());
            }
            buf.push(t[i]);
            // TODO: unpush rest
        }
    }
}

fn write_with_encoding(stream: &mut Write, input: &str, encoding: &Encoding) -> std::io::Result<usize> {
    return stream.write(&encoding.encode(input, EncoderTrap::Strict).unwrap());
}
<|endoftext|>


<commit_before><commit_msg>argh, forgot to put this file in source control earlier<commit_after>const CX_ASI      : u32 = 0x01;
const CX_OPERATOR : u32 = 0x02;

#[derive(Debug, Copy, Eq, PartialEq)]
pub struct Context {
    asi: bool,
    operator: bool
}

impl Context {
    pub fn new() -> Context {
        Context { asi: false, operator: false }
    }
    pub fn is_asi_possible(&mut self) -> bool { self.asi }
    pub fn is_operator(&mut self) -> bool { self.operator }
}

/*
pub struct ParseContext {
    is_asi_possible: bool,
    is_operator: bool
}
*/

pub trait ParseContext {
    fn is_asi_possible(&mut self) -> bool;
    fn is_operator(&mut self) -> bool;
}

pub struct SimpleContext;

impl<'a> ParseContext for &'a SimpleContext {
    fn is_asi_possible(&mut self) -> bool { true }
    fn is_operator(&mut self) -> bool { true }
}

impl SimpleContext {
    pub fn new() -> SimpleContext {
        SimpleContext
    }
}
<|endoftext|>


<commit_before><commit_msg>Refactor(unwise): Happy Fourth! Insomnia commit #2.  Syncfile error handling cleanup.<commit_after><|endoftext|>


<commit_before><commit_msg>Minor improvements to subcommand summaries.<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #78478 - hameerabbasi:const-generics-supertraits, r=lcnr<commit_after>// run-pass
// revisions: full min

#![cfg_attr(full, feature(const_generics))]
#![cfg_attr(full, allow(incomplete_features))]
#![cfg_attr(min, feature(min_const_generics))]

trait Foo<const N: usize> {
    fn myfun(&self) -> usize;
}
trait Bar<const N: usize> : Foo<N> {}
trait Baz: Foo<3> {}

struct FooType<const N: usize>;
struct BarType<const N: usize>;
struct BazType;

impl<const N: usize> Foo<N> for FooType<N> {
    fn myfun(&self) -> usize { N }
}
impl<const N: usize> Foo<N> for BarType<N> {
    fn myfun(&self) -> usize { N + 1 }
}
impl<const N: usize> Bar<N> for BarType<N> {}
impl Foo<3> for BazType {
    fn myfun(&self) -> usize { 999 }
}
impl Baz for BazType {}

trait Foz {}
trait Boz: Foo<3> + Foz {}
trait Bok<const N: usize>: Foo<N> + Foz {}

struct FozType;
struct BozType;
struct BokType<const N: usize>;

impl Foz for FozType {}

impl Foz for BozType {}
impl Foo<3> for BozType {
    fn myfun(&self) -> usize { 9999 }
}
impl Boz for BozType {}

impl<const N: usize> Foz for BokType<N> {}
impl<const N: usize> Foo<N> for BokType<N> {
    fn myfun(&self) -> usize { N + 2 }
}
impl<const N: usize> Bok<N> for BokType<N> {}

fn a<const N: usize>(x: &dyn Foo<N>) -> usize { x.myfun() }
fn b(x: &dyn Foo<3>) -> usize { x.myfun() }
fn c<T: Bok<N>, const N: usize>(x: T) -> usize { a::<N>(&x) }
fn d<T: ?Sized + Foo<3>>(x: &T) -> usize { x.myfun() }
fn e(x: &dyn Bar<3>) -> usize { d(x) }

fn main() {
    let foo = FooType::<3> {};
    assert!(a(&foo) == 3);
    assert!(b(&foo) == 3);
    assert!(d(&foo) == 3);

    let bar = BarType::<3> {};
    assert!(a(&bar) == 4);
    assert!(b(&bar) == 4);
    assert!(d(&bar) == 4);
    assert!(e(&bar) == 4);

    let baz = BazType {};
    assert!(a(&baz) == 999);
    assert!(b(&baz) == 999);
    assert!(d(&baz) == 999);

    let boz = BozType {};
    assert!(a(&boz) == 9999);
    assert!(b(&boz) == 9999);
    assert!(d(&boz) == 9999);

    let bok = BokType::<3> {};
    assert!(a(&bok) == 5);
    assert!(b(&bok) == 5);
    assert!(d(&bok) == 5);
    assert!(c(BokType::<3> {}) == 5);
}
<|endoftext|>


<commit_before><commit_msg>add globs that cause errors instead of ignoring them and printing an error<commit_after><|endoftext|>


<commit_before><commit_msg>Fix mmu read fn to use LittleEndian access to the buffer<commit_after><|endoftext|>


<commit_before><commit_msg>Remove redundant length checks.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed some clippy warnings, and adjusted some comments to fit in rustfmt's guidelines.<commit_after><|endoftext|>


<commit_before>use redox::get_slice::GetSlice;
use redox::ops::DerefMut;
use redox::string::*;
use redox::vec::Vec;
use redox::boxed::Box;
use redox::fs::*;
use redox::io::*;
use redox::env::*;
use redox::time::Duration;
use redox::to_num::*;

/* Magic Macros { */
static mut application: *mut Application<'static> = 0 as *mut Application;

/// Execute a command
macro_rules! exec {
    ($cmd:expr) => ({
        unsafe {
            (*application).on_command(&$cmd.to_string());
        }
    })
}
/* } Magic Macros */

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     main: box|args: &Vec<String>| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command<'a> {
    pub name: &'a str,
    pub main: Box<Fn(&Vec<String>)>,
}

impl<'a> Command<'a> {
    /// Return the vector of the commands
    // TODO: Use a more efficient collection instead
    pub fn vec() -> Vec<Self> {
        let mut commands: Vec<Self> = Vec::new();

        commands.push(Command {
            name: "cat",
            main: Box::new(|args: &Vec<String>| {
                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(mut file) = File::open(&path) {
                    let mut string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read: {}", path),
                    }
                } else {
                    println!("Failed to open file: {}", path);
                }
            }),
        });

        commands.push(Command {
            name: "cd",
            main: Box::new(|args: &Vec<String>| {
                match args.get(1) {
                    Some(path) => {
                        if !change_cwd(&path) {
                            println!("Bad path: {}", path);
                        }
                    }
                    None => println!("No path given")
                }
            }),
        });

        commands.push(Command {
            name: "echo",
            main: Box::new(|args: &Vec<String>| {
                let echo = args.iter()
                    .skip(1)
                    .fold(String::new(), |string, arg| string + " " + arg);
                println!("{}", echo.trim());
            }),
        });

        commands.push(Command {
            name: "else",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "exec",
            main: Box::new(|args: &Vec<String>| {
                if let Some(arg) = args.get(1) {
                    let mut args_str: Vec<&str> = Vec::new();
                    for arg in args.get_slice(Some(2), None) {
                        args_str.push(arg);
                    }

                    File::exec(arg, &args_str);
                }
            }),
        });

        commands.push(Command {
            name: "exit",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "fi",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "if",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "ls",
            main: Box::new(|args: &Vec<String>| {
                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(dir) = read_dir(&path) {
                    for entry in dir {
                        println!("{}", entry.path());
                    }
                } else {
                    println!("Failed to open directory: {}", path);
                }
            }),
        });

        commands.push(Command {
            name: "mkdir",
            main: Box::new(|args: &Vec<String>| {
                match args.get(1) {
                    Some(dir_name) => if DirEntry::create(dir_name).is_none() {
                        println!("Failed to create {}", dir_name);
                    },
                    None => println!("No name provided")
                }
            }),
        });

        commands.push(Command {
            name: "pwd",
            main: Box::new(|_: &Vec<String>| {
                if let Some(file) = File::open("") {
                    if let Some(path) = file.path() {
                        println!("{}", path);
                    } else {
                        println!("Could not get the path");
                    }
                } else {
                    println!("Could not open the working directory");
                }
            }),
        });

        commands.push(Command {
            name: "read",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "run",
            main: Box::new(|args: &Vec<String>| {
                if let Some(path) = args.get(1) {

                    let mut commands = String::new();
                    if let Some(mut file) = File::open(path) {
                        file.read_to_string(&mut commands);
                    }

                    for command in commands.split('\n') {
                        exec!(command);
                    }
                }
            }),
        });

        commands.push(Command {
            name: "sleep",
            main: Box::new(|args: &Vec<String>| {
                let secs = {
                    match args.get(1) {
                        Some(arg) => arg.to_num() as i64,
                        None => 0,
                    }
                };

                let nanos = {
                    match args.get(2) {
                        Some(arg) => arg.to_num() as i32,
                        None => 0,
                    }
                };

                println!("Sleep: {} {}", secs, nanos);
                let remaining = Duration::new(secs, nanos).sleep();
                println!("Remaining: {} {}", remaining.secs, remaining.nanos);
            }),
        });

        commands.push(Command {
            name: "send",
            main: Box::new(|args: &Vec<String>| {
                if args.len() < 3 {
                    println!("Error: incorrect arguments");
                    println!("Usage: send [url] [data]");
                    return;
                }

                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(mut file) = File::open(&path) {
                    println!("URL: {:?}", file.path());

                    let string: String = args.iter()
                        .skip(2)
                        .fold(String::new(), |s, arg| s + " " + arg)
                        + "\r\n\r\n";

                    match file.write(string.trim_left().as_bytes()) {
                        Some(size) => println!("Wrote {} bytes", size),
                        None => println!("Failed to write"),
                    }

                    let mut string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read"),
                    }
                }
            }),
        });

        // Simple command to create a file, in the current directory
        // The file has got the name given as the first argument of the command
        // If the command have no arguments, the command don't create the file
        commands.push(Command {
            name: "touch",
            main: Box::new(|args: &Vec<String>| {
                match args.get(1) {
                    Some(file_name) => if File::create(file_name).is_none() {
                        println!("Failed to create: {}", file_name);
                    },
                    None => println!("No name provided")
                }
            }),
        });

        commands.push(Command {
            name: "url_hex",
            main: Box::new(|args: &Vec<String>| {
                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(mut file) = File::open(&path) {
                    let mut vec: Vec<u8> = Vec::new();
                    match file.read_to_end(&mut vec) {
                        Some(_) => {
                            let mut line = "HEX:".to_string();
                            for byte in vec.iter() {
                                line = line + " " + &format!("{:X}", *byte);
                            }
                            println!("{}", line);
                        }
                        None => println!("Failed to read"),
                    }
                }
            }),
        });

        commands.push(Command {
            name: "wget",
            main: Box::new(|args: &Vec<String>| {
                if let Some(host) = args.get(1) {
                    if let Some(req) = args.get(2) {
                        if let Some(mut con) = File::open(&("tcp://".to_string() + host)) {
                            con.write(("GET ".to_string() + req + " HTTP/1.1").as_bytes());

                            let mut res = Vec::new();
                            con.read_to_end(&mut res);

                            if let Some(mut file) = File::open(&req) {
                                file.write(&res);
                            }
                        }
                    } else {
                        println!("No request given");
                    }
                } else {
                    println!("No url given");
                }
            }),
        });

        let command_list = commands.iter().fold(String::new(), |l , c| l + " " + c.name);

        commands.push(Command {
            name: "help",
            main: Box::new(move |_: &Vec<String>| {
                println!("Commands:{}", command_list);
            }),
         });

        commands
    }
}

/// A (env) variable
pub struct Variable {
    pub name: String,
    pub value: String,
}

pub struct Mode {
    value: bool,
}

/// An application
pub struct Application<'a> {
    commands: Vec<Command<'a>>,
    variables: Vec<Variable>,
    modes: Vec<Mode>,
}

impl<'a> Application<'a> {
    /// Create a new empty application
    pub fn new() -> Self {
        return Application {
            commands: Command::vec(),
            variables: Vec::new(),
            modes: Vec::new(),
        };
    }

    fn on_command(&mut self, command_string: &str) {
        //Comment
        if command_string.starts_with('#') {
            return;
        }

        //Show variables
        if command_string == "$" {
            for variable in self.variables.iter() {
                println!("{}={}", variable.name, variable.value);
            }
            return;
        }

        //Explode into arguments, replace variables
        let mut args: Vec<String> = Vec::<String>::new();
        for arg in command_string.split(' ') {
            if !arg.is_empty() {
                if arg.starts_with('$') {
                    let name = arg[1 .. arg.len()].to_string();
                    for variable in self.variables.iter() {
                        if variable.name == name {
                            args.push(variable.value.clone());
                            break;
                        }
                    }
                } else {
                    args.push(arg.to_string());
                }
            }
        }

        //Execute commands
        if let Some(cmd) = args.get(0) {
            if cmd == "if" {
                let mut value = false;

                if let Some(left) = args.get(1) {
                    if let Some(cmp) = args.get(2) {
                        if let Some(right) = args.get(3) {
                            if cmp == "==" {
                                value = *left == *right;
                            } else if cmp == "!=" {
                                value = *left != *right;
                            } else if cmp == ">" {
                                value = left.to_num_signed() > right.to_num_signed();
                            } else if cmp == ">=" {
                                value = left.to_num_signed() >= right.to_num_signed();
                            } else if cmp == "<" {
                                value = left.to_num_signed() < right.to_num_signed();
                            } else if cmp == "<=" {
                                value = left.to_num_signed() <= right.to_num_signed();
                            } else {
                                println!("Unknown comparison: {}", cmp);
                            }
                        } else {
                            println!("No right hand side");
                        }
                    } else {
                        println!("No comparison operator");
                    }
                } else {
                    println!("No left hand side");
                }

                self.modes.insert(0, Mode { value: value });
                return;
            }

            if cmd == "else" {
                let mut syntax_error = false;
                match self.modes.get_mut(0) {
                    Some(mode) => mode.value = !mode.value,
                    None => syntax_error = true,
                }
                if syntax_error {
                    println!("Syntax error: else found with no previous if");
                }
                return;
            }

            if cmd == "fi" {
                let mut syntax_error = false;
                if !self.modes.is_empty() {
                    self.modes.remove(0);
                } else {
                    syntax_error = true;
                }
                if syntax_error {
                    println!("Syntax error: fi found with no previous if");
                }
                return;
            }

            for mode in self.modes.iter() {
                if !mode.value {
                    return;
                }
            }

            if cmd == "read" {
                for i in 1..args.len() {
                    if let Some(arg_original) = args.get(i) {
                        let arg = arg_original.trim();
                        print!("{}=", arg);
                        if let Some(value_original) = readln!() {
                            let value = value_original.trim();
                            self.set_var(arg, value);
                        }
                    }
                }
            }

            //Set variables
            if let Some(i) = cmd.find('=') {
                let name = cmd[0 .. i].trim();
                let mut value = cmd[i + 1 .. cmd.len()].trim().to_string();

                for i in 1..args.len() {
                    if let Some(arg) = args.get(i) {
                        value = value + " " + &arg;
                    }
                }

                self.set_var(name, &value);
                return;
            }

            //Commands
            for command in self.commands.iter() {
                if &command.name == cmd {
                    (*command.main)(&args);
                    return;
                }
            }

            println!("Unknown command: '{}'", cmd);
        }
    }

    pub fn set_var(&mut self, name: &str, value: &str){
        if name.is_empty() {
            return;
        }

        if value.is_empty() {
            let mut remove = -1;
            for i in 0..self.variables.len() {
                match self.variables.get(i) {
                    Some(variable) => if variable.name == name {
                        remove = i as isize;
                        break;
                    },
                    None => break,
                }
            }

            if remove >= 0 {
                self.variables.remove(remove as usize);
            }
        } else {
            for variable in self.variables.iter_mut() {
                if variable.name == name {
                    variable.value = value.to_string();
                    return;
                }
            }

            self.variables.push(Variable {
                name: name.to_string(),
                value: value.to_string(),
            });
        }
    }

    /// Method to return the current directory
    /// If the current directory cannot be found, a default string ("?") will be returned
    pub fn get_current_directory(&mut self) -> String {
        // Return the current path
        File::open("")
            .and_then(|file| file.path())
            .unwrap_or("?".to_string())
    }

    /// Run the application
    pub fn main(&mut self) {
        println!("Type help for a command list");
        if let Some(arg) = args().get(1) {
            let command = "run ".to_string() + arg;
            println!("user@redox:{}# {}", self.get_current_directory(), command);
            self.on_command(&command);
        }

        loop {
            for mode in self.modes.iter().rev() {
                if mode.value {
                    print!("+ ");
                } else {
                    print!("- ");
                }
            }
            print!("user@redox:{}# ", self.get_current_directory());
            if let Some(command_original) = readln!() {
                let command = command_original.trim();
                if command == "exit" {
                    println!("Exit temporarily blocked (due to using terminal as init)")
                    //break;
                } else if !command.is_empty() {
                    self.on_command(&command);
                }
            } else {
                println!("Failed to read from stdin");
            }
        }
    }
}

pub fn main() {
    unsafe {
        let mut app = Box::new(Application::new());
        application = app.deref_mut();
        app.main();
    }
}
<commit_msg>Add a 'help' field for each command structure, to display a little man for each command<commit_after>use redox::get_slice::GetSlice;
use redox::ops::DerefMut;
use redox::string::*;
use redox::vec::Vec;
use redox::boxed::Box;
use redox::fs::*;
use redox::io::*;
use redox::env::*;
use redox::time::Duration;
use redox::to_num::*;

/* Magic Macros { */
static mut application: *mut Application<'static> = 0 as *mut Application;

/// Execute a command
macro_rules! exec {
    ($cmd:expr) => ({
        unsafe {
            (*application).on_command(&$cmd.to_string());
        }
    })
}
/* } Magic Macros */

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     main: box|args: &Vec<String>| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command<'a> {
    pub name: &'a str,
    pub help: &'a str,
    pub main: Box<Fn(&Vec<String>)>,
}

impl<'a> Command<'a> {
    /// Return the vector of the commands
    // TODO: Use a more efficient collection instead
    pub fn vec() -> Vec<Self> {
        let mut commands: Vec<Self> = Vec::new();

        commands.push(Command {
            name: "cat",
            main: Box::new(|args: &Vec<String>| {
                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(mut file) = File::open(&path) {
                    let mut string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read: {}", path),
                    }
                } else {
                    println!("Failed to open file: {}", path);
                }
            }),
        });

        commands.push(Command {
            name: "cd",
            main: Box::new(|args: &Vec<String>| {
                match args.get(1) {
                    Some(path) => {
                        if !change_cwd(&path) {
                            println!("Bad path: {}", path);
                        }
                    }
                    None => println!("No path given")
                }
            }),
        });

        commands.push(Command {
            name: "echo",
            main: Box::new(|args: &Vec<String>| {
                let echo = args.iter()
                    .skip(1)
                    .fold(String::new(), |string, arg| string + " " + arg);
                println!("{}", echo.trim());
            }),
        });

        commands.push(Command {
            name: "else",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "exec",
            main: Box::new(|args: &Vec<String>| {
                if let Some(arg) = args.get(1) {
                    let mut args_str: Vec<&str> = Vec::new();
                    for arg in args.get_slice(Some(2), None) {
                        args_str.push(arg);
                    }

                    File::exec(arg, &args_str);
                }
            }),
        });

        commands.push(Command {
            name: "exit",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "fi",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "if",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "ls",
            main: Box::new(|args: &Vec<String>| {
                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(dir) = read_dir(&path) {
                    for entry in dir {
                        println!("{}", entry.path());
                    }
                } else {
                    println!("Failed to open directory: {}", path);
                }
            }),
        });

        commands.push(Command {
            name: "mkdir",
            main: Box::new(|args: &Vec<String>| {
                match args.get(1) {
                    Some(dir_name) => if DirEntry::create(dir_name).is_none() {
                        println!("Failed to create {}", dir_name);
                    },
                    None => println!("No name provided")
                }
            }),
        });

        commands.push(Command {
            name: "pwd",
            main: Box::new(|_: &Vec<String>| {
                if let Some(file) = File::open("") {
                    if let Some(path) = file.path() {
                        println!("{}", path);
                    } else {
                        println!("Could not get the path");
                    }
                } else {
                    println!("Could not open the working directory");
                }
            }),
        });

        commands.push(Command {
            name: "read",
            main: Box::new(|_: &Vec<String>| {}),
        });

        commands.push(Command {
            name: "run",
            main: Box::new(|args: &Vec<String>| {
                if let Some(path) = args.get(1) {

                    let mut commands = String::new();
                    if let Some(mut file) = File::open(path) {
                        file.read_to_string(&mut commands);
                    }

                    for command in commands.split('\n') {
                        exec!(command);
                    }
                }
            }),
        });

        commands.push(Command {
            name: "sleep",
            main: Box::new(|args: &Vec<String>| {
                let secs = {
                    match args.get(1) {
                        Some(arg) => arg.to_num() as i64,
                        None => 0,
                    }
                };

                let nanos = {
                    match args.get(2) {
                        Some(arg) => arg.to_num() as i32,
                        None => 0,
                    }
                };

                println!("Sleep: {} {}", secs, nanos);
                let remaining = Duration::new(secs, nanos).sleep();
                println!("Remaining: {} {}", remaining.secs, remaining.nanos);
            }),
        });

        commands.push(Command {
            name: "send",
            main: Box::new(|args: &Vec<String>| {
                if args.len() < 3 {
                    println!("Error: incorrect arguments");
                    println!("Usage: send [url] [data]");
                    return;
                }

                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(mut file) = File::open(&path) {
                    println!("URL: {:?}", file.path());

                    let string: String = args.iter()
                        .skip(2)
                        .fold(String::new(), |s, arg| s + " " + arg)
                        + "\r\n\r\n";

                    match file.write(string.trim_left().as_bytes()) {
                        Some(size) => println!("Wrote {} bytes", size),
                        None => println!("Failed to write"),
                    }

                    let mut string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read"),
                    }
                }
            }),
        });

        // Simple command to create a file, in the current directory
        // The file has got the name given as the first argument of the command
        // If the command have no arguments, the command don't create the file
        commands.push(Command {
            name: "touch",
            main: Box::new(|args: &Vec<String>| {
                match args.get(1) {
                    Some(file_name) => if File::create(file_name).is_none() {
                        println!("Failed to create: {}", file_name);
                    },
                    None => println!("No name provided")
                }
            }),
        });

        commands.push(Command {
            name: "url_hex",
            main: Box::new(|args: &Vec<String>| {
                let path = {
                    match args.get(1) {
                        Some(arg) => arg.clone(),
                        None => String::new(),
                    }
                };

                if let Some(mut file) = File::open(&path) {
                    let mut vec: Vec<u8> = Vec::new();
                    match file.read_to_end(&mut vec) {
                        Some(_) => {
                            let mut line = "HEX:".to_string();
                            for byte in vec.iter() {
                                line = line + " " + &format!("{:X}", *byte);
                            }
                            println!("{}", line);
                        }
                        None => println!("Failed to read"),
                    }
                }
            }),
        });

        commands.push(Command {
            name: "wget",
            main: Box::new(|args: &Vec<String>| {
                if let Some(host) = args.get(1) {
                    if let Some(req) = args.get(2) {
                        if let Some(mut con) = File::open(&("tcp://".to_string() + host)) {
                            con.write(("GET ".to_string() + req + " HTTP/1.1").as_bytes());

                            let mut res = Vec::new();
                            con.read_to_end(&mut res);

                            if let Some(mut file) = File::open(&req) {
                                file.write(&res);
                            }
                        }
                    } else {
                        println!("No request given");
                    }
                } else {
                    println!("No url given");
                }
            }),
        });

        let command_list = commands.iter().fold(String::new(), |l , c| l + " " + c.name);

        commands.push(Command {
            name: "help",
            main: Box::new(move |_: &Vec<String>| {
                println!("Commands:{}", command_list);
            }),
         });

        commands
    }
}

/// A (env) variable
pub struct Variable {
    pub name: String,
    pub value: String,
}

pub struct Mode {
    value: bool,
}

/// An application
pub struct Application<'a> {
    commands: Vec<Command<'a>>,
    variables: Vec<Variable>,
    modes: Vec<Mode>,
}

impl<'a> Application<'a> {
    /// Create a new empty application
    pub fn new() -> Self {
        return Application {
            commands: Command::vec(),
            variables: Vec::new(),
            modes: Vec::new(),
        };
    }

    fn on_command(&mut self, command_string: &str) {
        //Comment
        if command_string.starts_with('#') {
            return;
        }

        //Show variables
        if command_string == "$" {
            for variable in self.variables.iter() {
                println!("{}={}", variable.name, variable.value);
            }
            return;
        }

        //Explode into arguments, replace variables
        let mut args: Vec<String> = Vec::<String>::new();
        for arg in command_string.split(' ') {
            if !arg.is_empty() {
                if arg.starts_with('$') {
                    let name = arg[1 .. arg.len()].to_string();
                    for variable in self.variables.iter() {
                        if variable.name == name {
                            args.push(variable.value.clone());
                            break;
                        }
                    }
                } else {
                    args.push(arg.to_string());
                }
            }
        }

        //Execute commands
        if let Some(cmd) = args.get(0) {
            if cmd == "if" {
                let mut value = false;

                if let Some(left) = args.get(1) {
                    if let Some(cmp) = args.get(2) {
                        if let Some(right) = args.get(3) {
                            if cmp == "==" {
                                value = *left == *right;
                            } else if cmp == "!=" {
                                value = *left != *right;
                            } else if cmp == ">" {
                                value = left.to_num_signed() > right.to_num_signed();
                            } else if cmp == ">=" {
                                value = left.to_num_signed() >= right.to_num_signed();
                            } else if cmp == "<" {
                                value = left.to_num_signed() < right.to_num_signed();
                            } else if cmp == "<=" {
                                value = left.to_num_signed() <= right.to_num_signed();
                            } else {
                                println!("Unknown comparison: {}", cmp);
                            }
                        } else {
                            println!("No right hand side");
                        }
                    } else {
                        println!("No comparison operator");
                    }
                } else {
                    println!("No left hand side");
                }

                self.modes.insert(0, Mode { value: value });
                return;
            }

            if cmd == "else" {
                let mut syntax_error = false;
                match self.modes.get_mut(0) {
                    Some(mode) => mode.value = !mode.value,
                    None => syntax_error = true,
                }
                if syntax_error {
                    println!("Syntax error: else found with no previous if");
                }
                return;
            }

            if cmd == "fi" {
                let mut syntax_error = false;
                if !self.modes.is_empty() {
                    self.modes.remove(0);
                } else {
                    syntax_error = true;
                }
                if syntax_error {
                    println!("Syntax error: fi found with no previous if");
                }
                return;
            }

            for mode in self.modes.iter() {
                if !mode.value {
                    return;
                }
            }

            if cmd == "read" {
                for i in 1..args.len() {
                    if let Some(arg_original) = args.get(i) {
                        let arg = arg_original.trim();
                        print!("{}=", arg);
                        if let Some(value_original) = readln!() {
                            let value = value_original.trim();
                            self.set_var(arg, value);
                        }
                    }
                }
            }

            //Set variables
            if let Some(i) = cmd.find('=') {
                let name = cmd[0 .. i].trim();
                let mut value = cmd[i + 1 .. cmd.len()].trim().to_string();

                for i in 1..args.len() {
                    if let Some(arg) = args.get(i) {
                        value = value + " " + &arg;
                    }
                }

                self.set_var(name, &value);
                return;
            }

            //Commands
            for command in self.commands.iter() {
                if &command.name == cmd {
                    (*command.main)(&args);
                    return;
                }
            }

            println!("Unknown command: '{}'", cmd);
        }
    }

    pub fn set_var(&mut self, name: &str, value: &str){
        if name.is_empty() {
            return;
        }

        if value.is_empty() {
            let mut remove = -1;
            for i in 0..self.variables.len() {
                match self.variables.get(i) {
                    Some(variable) => if variable.name == name {
                        remove = i as isize;
                        break;
                    },
                    None => break,
                }
            }

            if remove >= 0 {
                self.variables.remove(remove as usize);
            }
        } else {
            for variable in self.variables.iter_mut() {
                if variable.name == name {
                    variable.value = value.to_string();
                    return;
                }
            }

            self.variables.push(Variable {
                name: name.to_string(),
                value: value.to_string(),
            });
        }
    }

    /// Method to return the current directory
    /// If the current directory cannot be found, a default string ("?") will be returned
    pub fn get_current_directory(&mut self) -> String {
        // Return the current path
        File::open("")
            .and_then(|file| file.path())
            .unwrap_or("?".to_string())
    }

    /// Run the application
    pub fn main(&mut self) {
        println!("Type help for a command list");
        if let Some(arg) = args().get(1) {
            let command = "run ".to_string() + arg;
            println!("user@redox:{}# {}", self.get_current_directory(), command);
            self.on_command(&command);
        }

        loop {
            for mode in self.modes.iter().rev() {
                if mode.value {
                    print!("+ ");
                } else {
                    print!("- ");
                }
            }
            print!("user@redox:{}# ", self.get_current_directory());
            if let Some(command_original) = readln!() {
                let command = command_original.trim();
                if command == "exit" {
                    println!("Exit temporarily blocked (due to using terminal as init)")
                    //break;
                } else if !command.is_empty() {
                    self.on_command(&command);
                }
            } else {
                println!("Failed to read from stdin");
            }
        }
    }
}

pub fn main() {
    unsafe {
        let mut app = Box::new(Application::new());
        application = app.deref_mut();
        app.main();
    }
}
<|endoftext|>


<commit_before><commit_msg>test(all): add tests for parsing, formatting and matching tags<commit_after>extern crate language_tags;

use std::default::Default;
use std::collections::BTreeMap;

use language_tags::{Error, LanguageTag, Result};

// All tests here may be completly nonsensical.

#[test]
fn test_lang_from_str() {
    let a: LanguageTag = "de".parse().unwrap();
    let mut b: LanguageTag = Default::default();
    b.language = Some("de".to_owned());
    assert_eq!(a, b);
}

#[test]
fn test_extlang_from_str() {
    let a: LanguageTag = "ar-afb".parse().unwrap();
    let mut b: LanguageTag = Default::default();
    b.language = Some("ar".to_owned());
    b.extlang = Some("afb".to_owned());
    assert_eq!(a, b);
}

#[test]
fn test_script_from_str() {
    let a: LanguageTag = "ar-afb-Latn".parse().unwrap();
    let mut b: LanguageTag = Default::default();
    b.language = Some("ar".to_owned());
    b.extlang = Some("afb".to_owned());
    b.script = Some("latn".to_owned());
    assert_eq!(a, b);
}

#[test]
fn test_region_from_str() {
    let mut a: LanguageTag = "ar-DE".parse().unwrap();
    let mut b: LanguageTag = Default::default();
    b.language = Some("ar".to_owned());
    b.region = Some("de".to_owned());
    assert_eq!(a, b);

    a = "ar-005".parse().unwrap();
    b = Default::default();
    b.language = Some("ar".to_owned());
    b.region = Some("005".to_owned());
    assert_eq!(a, b);

    a = "ar-005".parse().unwrap();
    b = Default::default();
    b.language = Some("ar".to_owned());
    b.region = Some("005".to_owned());
    assert_eq!(a, b);
}

#[test]
fn test_variant_from_str() {
    let a: LanguageTag = "sl-IT-nedis".parse().unwrap();
    let mut b: LanguageTag = Default::default();
    b.language = Some("sl".parse().unwrap());
    b.region = Some("it".parse().unwrap());
    b.variants = vec!["nedis".parse().unwrap()];
    assert_eq!(a, b);
}

#[test]
fn test_invalid_from_str() {
    assert_eq!("sl-07".parse::<LanguageTag>(), Err(Error));
}

#[test]
fn test_strange_case_from_str() {
    // This is a perfectly valid language code
    let a: LanguageTag = "SL-AFB-lATN-005-nEdis".parse().unwrap();
    let b = LanguageTag {
        language: Some("sl".to_owned()),
        extlang: Some("afb".to_owned()),
        script: Some("Latn".to_owned()),
        region: Some("005".to_owned()),
        variants: vec!["nedis".to_owned()],
        extensions: BTreeMap::new(),
        privateuse: Vec::new(),
    };
    assert_eq!(a, b);
}

#[test]
fn test_fmt() {
    let a: LanguageTag = "ar-arb-Latn-DE-nedis-foobar".parse().unwrap();
    assert_eq!(format!("{}", a), "ar-arb-Latn-DE-nedis-foobar");
}

#[test]
fn test_match() {
    let de_de: LanguageTag = "de-DE".parse().unwrap();
    let de: LanguageTag = "de".parse().unwrap();
    assert!(de.matches(&de_de));
    assert!(!de_de.matches(&de));
}

#[test]
fn test_klingon() {
    let a: LanguageTag = "i-klingon".parse().unwrap();
    let mut b: LanguageTag = Default::default();
    b.language = Some("i-klingon".to_owned());
    assert_eq!(a, b);
}

#[test]
fn test_private_use() {
    let a: LanguageTag = "es-x-foobar-AT-007".parse().unwrap();
    let mut b: LanguageTag = Default::default();
    b.language = Some("es".to_owned());
    b.privateuse = vec!["foobar".to_owned(), "AT".to_owned(), "007".to_owned()];
    assert_eq!(a, b);
}

#[test]
fn test_unicode() {
    let x: Result<LanguageTag> = "zh-x-Üńìcødê".parse();
    assert!(x.is_err());
}

#[test]
fn test_format() {
    let x: LanguageTag = "HkgnmerM-x-e5-zf-VdDjcpz-1V6".parse().unwrap();
    assert_eq!(format!("{}", x), "HkgnmerM-x-e5-zf-VdDjcpz-1V6");
    let y: LanguageTag = "MgxQa-ywEp-8lcW-7bvT-h-dP1Md-0h7-0Z3ir".parse().unwrap();
    assert_eq!(format!("{}", y), "MgxQa-ywEp-8lcW-7bvT-h-dP1Md-0h7-0Z3ir");
}

#[test]
fn test_wellformed_tags() {
    // Source: http://www.langtag.net/test-suites/well-formed-tags.txt
    let tags = vec![
        "fr ",
        "fr-Latn",
        "fr-fra", // Extended tag
        "fr-Latn-FR",
        "fr-Latn-419",
        "fr-FR",
        "ax-TZ", // Not in the registry, but well-formed
        "fr-shadok", // Variant
        "fr-y-myext-myext2",
        "fra-Latn", // ISO 639 can be 3-letters
        "fra",
        "fra-FX",
        "i-klingon", // grandfathered with singleton
        "I-kLINgon", // tags are case-insensitive...
        "no-bok", // grandfathered without singleton
        "fr-Lat", // Extended",
        "mn-Cyrl-MN",
        "mN-cYrL-Mn",
        "fr-Latn-CA",
        "en-US",
        "fr-Latn-CA",
        "i-enochian", // Grand fathered
        "x-fr-CH ",
        "sr-Latn-CS",
        "es-419",
        "sl-nedis",
        "de-CH-1996",
        "de-Latg-1996",
        "sl-IT-nedis",
        "en-a-bbb-x-a-ccc",
        "de-a-value",
        "en-Latn-GB-boont-r-extended-sequence-x-private",
        "en-x-US",
        "az-Arab-x-AZE-derbend",
        "es-Latn-CO-x-private",
        "en-US-boont",
        "ab-x-abc-x-abc", // anything goes after x
        "ab-x-abc-a-a", // ditto",
        "i-default", // grandfathered",
        "i-klingon", // grandfathered",
        "abcd-Latn", // Language of 4 chars reserved for future use
        "AaBbCcDd-x-y-any-x", // Language of 5-8 chars, registered
        "en",
        "de-AT",
        "es-419",
        "de-CH-1901",
        "sr-Cyrl",
        "sr-Cyrl-CS",
        "sl-Latn-IT-rozaj",
        "en-US-x-twain",
        "zh-cmn",
        "zh-cmn-Hant",
        "zh-cmn-Hant-HK",
        "zh-gan",
        "zh-yue-Hant-HK",
        "xr-lxs-qut", // extlangS
        "xr-lqt-qu", // extlang + region
        "xr-p-lze", // Extension
    ];
    let failed: Vec<&str> = tags.iter().filter(|x| x.parse::<LanguageTag>().is_err()).map(|&x| x).collect();
    println!("Number: { } Failed: {:?}", failed.len(), failed);
    assert!(failed.is_empty());
}

#[test]
fn test_broken_tags() {
    // Source: http://www.langtag.net/test-suites/broken-tags.txt
    let tags = vec![
        "f",
        "f-Latn",
        "fr-Latn-F",
        "a-value",
        "en-a-bbb-a-ccc", // 'a' appears twice
        "tlh-a-b-foo",
        "i-notexist", // grandfathered but not registered: invalid, even if we only test well-formedness
        "abcdefghi-012345678",
        "ab-abc-abc-abc-abc",
        "ab-abcd-abc",
        "ab-ab-abc",
        "ab-123-abc",
        "a-Hant-ZH",
        "a1-Hant-ZH",
        "ab-abcde-abc",
        "ab-1abc-abc",
        "ab-ab-abcd",
        "ab-123-abcd",
        "ab-abcde-abcd",
        "ab-1abc-abcd",
        "ab-a-b",
        "ab-a-x",
        "ab--ab",
        "ab-abc-",
        "-ab-abc",
        "ab-c-abc-r-toto-c-abc  # 'c' appears twice ",
        "abcd-efg",
        "aabbccddE",
    ];
    let failed: Vec<(&str, Result<LanguageTag>)> = tags.iter().map(|x| (*x, x.parse::<LanguageTag>())).filter(|x| x.1.is_ok()).collect();
    println!("Number: { } Failed: {:?}", failed.len(), failed);
    assert!(failed.is_empty());
}

#[test]
fn test_random_good_tags () {
    // Source: http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagTest.txt
    let tags = vec![
        "zszLDm-sCVS-es-x-gn762vG-83-S-mlL",
        "IIJdFI-cfZv",
        "kbAxSgJ-685",
        "tbutP",
        "hDL-595",
        "dUf-iUjq-0hJ4P-5YkF-WD8fk",
        "FZAABA-FH",
        "xZ-lh-4QfM5z9J-1eG4-x-K-R6VPr2z",
        "Fyi",
        "SeI-DbaG",
        "ch-xwFn",
        "OeC-GPVI",
        "JLzvUSi",
        "Fxh-hLAs",
        "pKHzCP-sgaO-554",
        "eytqeW-hfgH-uQ",
        "ydn-zeOP-PR",
        "uoWmBM-yHCf-JE",
        "xwYem",
        "zie",
        "Re-wjSv-Ey-i-XE-E-JjWTEB8-f-DLSH-NVzLH-AtnFGWoH-SIDE",
        "Ri-063-c-u6v-ZfhkToTB-C-IFfmv-XT-j-rdyYFMhK-h-pY-D5-Oh6FqBhL-hcXt-v-WdpNx71-K-c74m4-eBTT7-JdH7Q1Z",
        "ji",
        "IM-487",
        "EPZ-zwcB",
        "GauwEcwo",
        "kDEP",
        "FwDYt-TNvo",
        "ottqP-KLES-x-9-i9",
        "fcflR-grQQ",
        "TvFwdu-kYhs",
        "WE-336",
        "MgxQa-ywEp-8lcW-7bvT-h-dP1Md-0h7-0Z3ir-K-Srkm-kA-7LXM-Z-whb2MiO-2mNsvbLm-W3O-4r-U-KceIxHdI-gvMVgUBV-2uRUni-J0-7C8yTK2",
        "Hyr-B-evMtVoB1-mtsVZf-vQMV-gM-I-rr-kvLzg-f-lAUK-Qb36Ne-Z-7eFzOD-mv6kKf-l-miZ7U3-k-XDGtNQG",
        "ybrlCpzy",
        "PTow-w-cAQ51-8Xd6E-cumicgt-WpkZv3NY-q-ORYPRy-v-A4jL4A-iNEqQZZ-sjKn-W-N1F-pzyc-xP5eWz-LmsCiCcZ",
        "ih-DlPR-PE",
        "Krf-362",
        "WzaD",
        "EPaOnB-gHHn",
        "XYta",
        "NZ-RgOO-tR",
        "at-FE",
        "Tpc-693",
        "YFp",
        "gRQrQULo",
        "pVomZ-585",
        "laSu-ZcAq-338",
        "gCW",
        "PydSwHRI-TYfF",
        "zKmWDD",
        "X-bCrL5RL",
        "HK",
        "YMKGcLY",
        "GDJ-nHYa-bw-X-ke-rohH5GfS-LdJKsGVe",
        "tfOxdau-yjge-489-a-oB-I8Csb-1ESaK1v-VFNz-N-FT-ZQyn-On2-I-hu-vaW3-jIQb-vg0U-hUl-h-dO6KuJqB-U-tde2L-P3gHUY-vnl5c-RyO-H-gK1-zDPu-VF1oeh8W-kGzzvBbW-yuAJZ",
        "LwDux",
        "Zl-072",
        "Ri-Ar",
        "vocMSwo-cJnr-288",
        "kUWq-gWfQ-794",
        "YyzqKL-273",
        "Xrw-ZHwH-841-9foT-ESSZF-6OqO-0knk-991U-9p3m-b-JhiV-0Kq7Y-h-cxphLb-cDlXUBOQ-X-4Ti-jty94yPp",
        "en-GB-oed",
        "LEuZl-so",
        "HyvBvFi-cCAl-X-irMQA-Pzt-H",
        "uDbsrAA-304",
        "wTS",
        "IWXS",
        "XvDqNkSn-jRDR",
        "gX-Ycbb-iLphEks-AQ1aJ5",
        "FbSBz-VLcR-VL",
        "JYoVQOP-Iytp",
        "gDSoDGD-lq-v-7aFec-ag-k-Z4-0kgNxXC-7h",
        "Bjvoayy-029",
        "qSDJd",
        "qpbQov",
        "fYIll-516",
        "GfgLyfWE-EHtB",
        "Wc-ZMtk",
        "cgh-VEYK",
        "WRZs-AaFd-yQ",
        "eSb-CpsZ-788",
        "YVwFU",
        "JSsHiQhr-MpjT-381",
        "LuhtJIQi-JKYt",
        "vVTvS-RHcP",
        "SY",
        "fSf-EgvQfI-ktWoG-8X5z-63PW",
        "NOKcy",
        "OjJb-550",
        "KB",
        "qzKBv-zDKk-589",
        "Jr",
        "Acw-GPXf-088",
        "WAFSbos",
        "HkgnmerM-x-e5-zf-VdDjcpz-1V6",
        "UAfYflJU-uXDc-YV",
        "x-CHsHx-VDcOUAur-FqagDTx-H-V0e74R",
        "uZIAZ-Xmbh-pd"
    ];
    let failed: Vec<(&str, Result<LanguageTag>)> = tags.iter().map(|x| (*x, x.parse::<LanguageTag>())).filter(|x| x.1.is_err()).collect();
    println!("Number: { } Failed: {:?}", failed.len(), failed);
    assert!(failed.is_empty());
}

#[test]
fn test_random_bad_tags () {
    // Source: http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagTest.txt
    let tags = vec![
        "EdY-z_H791Xx6_m_kj",
        "qWt85_8S0-L_rbBDq0gl_m_O_zsAx_nRS",
        "VzyL2",
        "T_VFJq-L-0JWuH_u2_VW-hK-kbE",
        "u-t",
        "Q-f_ZVJXyc-doj_k-i",
        "JWB7gNa_K-5GB-25t_W-s-ZbGVwDu1-H3E",
        "b-2T-Qob_L-C9v_2CZxK86",
        "fQTpX_0_4Vg_L3L_g7VtALh2",
        "S-Z-E_J",
        "f6wsq-02_i-F",
        "9_GcUPq_G",
        "QjsIy_9-0-7_Dv2yPV09_D-JXWXM",
        "D_se-f-k",
        "ON47Wv1_2_W",
        "f-z-R_s-ha",
        "N3APeiw_195_Bx2-mM-pf-Z-Ip5lXWa-5r",
        "IRjxU-E_6kS_D_b1b_H",
        "NB-3-5-AyW_FQ-9hB-TrRJg3JV_3C",
        "yF-3a_V_FoJQAHeL_Z-Mc-u",
        "n_w_bbunOG_1-s-tJMT5je",
        "Q-AEWE_X",
        "57b1O_k_R6MU_sb",
        "hK_65J_i-o_SI-Y",
        "wB4B7u_5I2_I_NZPI",
        "J24Nb_q_d-zE",
        "v6-dHjJmvPS_IEb-x_A-O-i",
        "8_8_dl-ZgBr84u-P-E",
        "nIn-xD7EVhe_C",
        "5_N-6P_x7Of_Lo_6_YX_R",
        "0_46Oo0sZ-YNwiU8Wr_d-M-pg1OriV",
        "laiY-5",
        "K-8Mdd-j_ila0sSpo_aO8_J",
        "wNATtSL-Cp4_gPa_fD41_9z",
        "H_FGz5V8_n6rrcoz0_1O6d-kH-7-N",
        "wDOrnHU-odqJ_vWl",
        "gP_qO-I-jH",
        "h",
        "dJ0hX-o_csBykEhU-F",
        "L-Vf7_BV_eRJ5goSF_Kp",
        "y-oF-chnavU-H",
        "9FkG-8Q-8_v",
        "W_l_NDQqI-O_SFSAOVq",
        "kDG3fzXw",
        "t-nsSp-7-t-mUK2",
        "Yw-F",
        "1-S_3_l",
        "u-v_brn-Y",
        "4_ft_3ZPZC5lA_D",
        "n_dR-QodsqJnh_e",
        "Hwvt-bSwZwj_KL-hxg0m-3_hUG",
        "mQHzvcV-UL-o2O_1KhUJQo_G2_uryk3-a",
        "b-UTn33HF",
        "r-Ep-jY-aFM_N_H",
        "K-k-krEZ0gwD_k_ua-9dm3Oy-s_v",
        "XS_oS-p",
        "EIx_h-zf5",
        "p_z-0_i-omQCo3B",
        "1_q0N_jo_9",
        "0Ai-6-S",
        "L-LZEp_HtW",
        "Zj-A4JD_2A5Aj7_b-m3",
        "x",
        "p-qPuXQpp_d-jeKifB-c-7_G-X",
        "X94cvJ_A",
        "F2D25R_qk_W-w_Okf_kx",
        "rc-f",
        "D",
        "gD_WrDfxmF-wu-E-U4t",
        "Z_BN9O4_D9-D_0E_KnCwZF-84b-19",
        "T-8_g-u-0_E",
        "lXTtys9j_X_A_m-vtNiNMw_X_b-C6Nr",
        "V_Ps-4Y-S",
        "X5wGEA",
        "mIbHFf_ALu4_Jo1Z1",
        "ET-TacYx_c",
        "Z-Lm5cAP_ri88-d_q_fi8-x",
        "rTi2ah-4j_j_4AlxTs6m_8-g9zqncIf-N5",
        "FBaLB85_u-0NxhAy-ZU_9c",
        "x_j_l-5_aV95_s_tY_jp4",
        "PL768_D-m7jNWjfD-Nl_7qvb_bs_8_Vg",
        "9-yOc-gbh",
        "6DYxZ_SL-S_Ye",
        "ZCa-U-muib-6-d-f_oEh_O",
        "Qt-S-o8340F_f_aGax-c-jbV0gfK_p",
        "WE_SzOI_OGuoBDk-gDp",
        "cs-Y_9",
        "m1_uj",
        "Y-ob_PT",
        "li-B",
        "f-2-7-9m_f8den_J_T_d",
        "p-Os0dua-H_o-u",
        "L",
        "rby-w"
    ];
    let failed: Vec<(&str, Result<LanguageTag>)> = tags.iter().map(|x| (*x, x.parse::<LanguageTag>())).filter(|x| x.1.is_ok()).collect();
    println!("Number: { } Failed: {:?}", failed.len(), failed);
    assert!(failed.is_empty());
}
<|endoftext|>


<commit_before><commit_msg>Base directory doesn't work on Windows<commit_after><|endoftext|>


<commit_before>use std::cell::RefCell;
use std::iter::Iterator;
use std::rc::Rc;
use std::ops::Deref;

use storage::file::File;

pub trait FilePrinter {

    fn new(verbose: bool, debug: bool) -> Self;

    /*
     * Print a single file
     */
    fn print_file(&self, Rc<RefCell<File>>);

    /*
     * Print a list of files
     */
    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        for file in files {
            self.print_file(file);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        info!("{}", f(file).join(" "));
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        for file in files {
            self.print_file_custom(file, f);
        }
    }

}

struct DebugPrinter {
    debug: bool,
}

impl FilePrinter for DebugPrinter {

    fn new(_: bool, debug: bool) -> DebugPrinter {
        DebugPrinter {
            debug: debug,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f(file).join(" "));
        }
    }

}

struct SimplePrinter {
    verbose:    bool,
    debug:      bool,
}

impl FilePrinter for SimplePrinter {

    fn new(verbose: bool, debug: bool) -> SimplePrinter {
        SimplePrinter {
            debug:      debug,
            verbose:    verbose,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("{:?}", f);
        } else if self.verbose {
            info!("{}", &*f.deref().borrow());
        } else {
            info!("[File]: {}", f.deref().borrow().id());
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        let s = f(file).join(" ");
        if self.debug {
            debug!("{:?}", s);
        } else if self.verbose {
            info!("{}", s);
        } else {
            info!("[File]: {}", s);
        }
    }

}

pub struct TablePrinter {
    verbose:    bool,
    debug:      bool,
    sp:         SimplePrinter,
}

impl FilePrinter for TablePrinter {

    fn new(verbose: bool, debug: bool) -> TablePrinter {
        TablePrinter {
            debug:      debug,
            verbose:    verbose,
            sp:         SimplePrinter::new(verbose, debug),
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        self.sp.print_file(f);
    }

    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID"];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);
            let row = Row::new(vec![cell_i, cell_o, cell_id]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID", "..."];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);

            let mut row = Row::new(vec![cell_i, cell_o, cell_id]);

            for cell in f(file).iter() {
                debug!("Adding custom cell: {:?}", cell);
                row.add_cell(Cell::new(&cell[..]))
            }

            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

}
<commit_msg>Rename table title<commit_after>use std::cell::RefCell;
use std::iter::Iterator;
use std::rc::Rc;
use std::ops::Deref;

use storage::file::File;

pub trait FilePrinter {

    fn new(verbose: bool, debug: bool) -> Self;

    /*
     * Print a single file
     */
    fn print_file(&self, Rc<RefCell<File>>);

    /*
     * Print a list of files
     */
    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        for file in files {
            self.print_file(file);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        info!("{}", f(file).join(" "));
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        for file in files {
            self.print_file_custom(file, f);
        }
    }

}

struct DebugPrinter {
    debug: bool,
}

impl FilePrinter for DebugPrinter {

    fn new(_: bool, debug: bool) -> DebugPrinter {
        DebugPrinter {
            debug: debug,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f(file).join(" "));
        }
    }

}

struct SimplePrinter {
    verbose:    bool,
    debug:      bool,
}

impl FilePrinter for SimplePrinter {

    fn new(verbose: bool, debug: bool) -> SimplePrinter {
        SimplePrinter {
            debug:      debug,
            verbose:    verbose,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("{:?}", f);
        } else if self.verbose {
            info!("{}", &*f.deref().borrow());
        } else {
            info!("[File]: {}", f.deref().borrow().id());
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        let s = f(file).join(" ");
        if self.debug {
            debug!("{:?}", s);
        } else if self.verbose {
            info!("{}", s);
        } else {
            info!("[File]: {}", s);
        }
    }

}

pub struct TablePrinter {
    verbose:    bool,
    debug:      bool,
    sp:         SimplePrinter,
}

impl FilePrinter for TablePrinter {

    fn new(verbose: bool, debug: bool) -> TablePrinter {
        TablePrinter {
            debug:      debug,
            verbose:    verbose,
            sp:         SimplePrinter::new(verbose, debug),
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        self.sp.print_file(f);
    }

    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID"];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);
            let row = Row::new(vec![cell_i, cell_o, cell_id]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["#", "Module", "ID", "..."];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);

            let mut row = Row::new(vec![cell_i, cell_o, cell_id]);

            for cell in f(file).iter() {
                debug!("Adding custom cell: {:?}", cell);
                row.add_cell(Cell::new(&cell[..]))
            }

            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Uncomment warning line<commit_after><|endoftext|>


<commit_before><commit_msg>Don't panic on VSU reads<commit_after><|endoftext|>


<commit_before><commit_msg>Don’t store computed values of logical properties in style structs<commit_after><|endoftext|>


<commit_before><commit_msg>add compile-fail test sync-cond-shouldnt-escape.rs<commit_after>// error-pattern: reference is not valid outside of its lifetime
fn main() {
    let m = ~sync::new_mutex();
    let mut cond = none;
    do m.lock_cond |c| {
        cond = some(c);
    }
    option::unwrap(cond).signal();
}
<|endoftext|>


<commit_before><commit_msg>Tests from the image crate to be sure we don’t break them<commit_after>#[macro_use] extern crate enum_primitive;

mod gif {
    enum_from_primitive! {
    /// Known block types
    enum Block {
        Image = 0x2C,
        Extension = 0x21,
        Trailer = 0x3B
    }
    }

    enum_from_primitive! {
    /// Known GIF extensions
    enum Extension {
        Text = 0x01,
        Control = 0xF9,
        Comment = 0xFE,
        Application = 0xFF
    }
    }

    enum_from_primitive! {
    /// Method to dispose the image
    enum DisposalMethod {
        Undefined = 0,
        None = 1,
        Previous = 2,
        Background = 3
    }
    }
}

mod png {
    enum_from_primitive! {
    #[derive(Clone, Copy, Debug, PartialEq)]
    enum InterlaceMethod {
        None = 0,
        Adam7 = 1
    }
    }

    enum_from_primitive! {
    #[derive(Debug)]
    pub enum FilterType {
        NoFilter = 0,
        Sub = 1,
        Up = 2,
        Avg = 3,
        Paeth = 4
    }
    }
}

mod tiff {
    enum_from_primitive! {
    #[derive(Clone, Copy, Debug, PartialEq)]
    enum PhotometricInterpretation {
        WhiteIsZero = 0,
        BlackIsZero = 1,
        RGB = 2,
        RGBPalette = 3,
        TransparencyMask = 4,
        CMYK = 5,
        YCbCr = 6,
        CIELab = 8,
    }
    }

    enum_from_primitive! {
    #[derive(Clone, Copy, Debug)]
    enum CompressionMethod {
        None = 1,
        Huffman = 2,
        Fax3 = 3,
        Fax4 = 4,
        LZW = 5,
        JPEG = 6,
        PackBits = 32773
    }
    }

    enum_from_primitive! {
    #[derive(Clone, Copy, Debug)]
    enum PlanarConfiguration {
        Chunky = 1,
        Planar = 2
    }
    }

    enum_from_primitive! {
    #[derive(Clone, Copy, Debug)]
    enum Predictor {
        None = 1,
        Horizontal = 2
    }
    }

    enum_from_primitive! {
    #[derive(Clone, Copy, Debug)]
    pub enum Type {
        BYTE = 1,
        ASCII = 2,
        SHORT = 3,
        LONG = 4,
        RATIONAL = 5,
    }
    }
}
<|endoftext|>


<commit_before><commit_msg>Handle Empty Braces<commit_after><|endoftext|>


<commit_before><commit_msg>Remove allocations<commit_after><|endoftext|>


<commit_before><commit_msg>Added a big random test.<commit_after><|endoftext|>


<commit_before><commit_msg>Add object display test<commit_after>extern crate bnf;

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

    #[test]
    fn validate_display() {
        let input =
            "<postal-address> ::= <name-part> <street-address> <zip-part>;

                <name-part> ::= <personal-part> <last-name> <opt-suffix-part> <EOL>
                                | <personal-part> <name-part>;

            <personal-part> ::= <initial> \".\" | <first-name>;

            <street-address> ::= <house-num> <street-name> <opt-apt-num> <EOL>;

                <zip-part> ::= <town-name> \",\" <state-code> <ZIP-code> <EOL>;

            <opt-suffix-part> ::= \"Sr.\" | \"Jr.\" | <roman-numeral> | \"\";
                <opt-apt-num> ::= <apt-num> | \"\";";

        let display_output =
            "<postal-address> ::= <name-part> <street-address> <zip-part>;\n\
             <name-part> ::= <personal-part> <last-name> <opt-suffix-part> <EOL> | <personal-part> <name-part>;\n\
             <personal-part> ::= <initial> \".\" | <first-name>;\n\
             <street-address> ::= <house-num> <street-name> <opt-apt-num> <EOL>;\n\
             <zip-part> ::= <town-name> \",\" <state-code> <ZIP-code> <EOL>;\n\
             <opt-suffix-part> ::= \"Sr.\" | \"Jr.\" | <roman-numeral> | \"\";\n\
             <opt-apt-num> ::= <apt-num> | \"\";\n";

        let grammar = bnf::parse(input);

        assert_eq!(grammar.to_string(), display_output);
    }
}
<|endoftext|>


<commit_before><commit_msg>add test case for host: `http://192.168.0.257`<commit_after><|endoftext|>


<commit_before><commit_msg>Ignore ".d" binaries in debug build<commit_after><|endoftext|>


<commit_before><commit_msg>finish rust version<commit_after>use std::collections::{HashMap, HashSet};

pub fn min_reorder(n: i32, connections: Vec<Vec<i32>>) -> i32 {
    let mut result = 0;
    let mut set: HashSet<(i32, i32)> = connections.iter().map(|x| (x[0], x[1])).collect();
    let mut graph: HashMap<i32, Vec<i32>> = HashMap::new();

    for road in connections {
        graph.entry(road[0]).or_insert(vec![]).push(road[1]);
        graph.entry(road[1]).or_insert(vec![]).push(road[0]);
    }

    dfs(0, -1, &graph, &set, &mut result)
}

fn dfs(
    i: i32,
    p: i32,
    graph: &HashMap<i32, Vec<i32>>,
    set: &HashSet<(i32, i32)>,
    result: &mut i32,
) -> i32 {
    match set.get(&(p, i)) {
        Some(_) => *result += 1,
        None => (),
    }

    for v in graph.get(&i).unwrap() {
        if *v == p {
            continue;
        }
        dfs(*v, i, graph, set, result);
    }

    *result
}

fn main() {
    assert_eq!(
        min_reorder(
            6,
            vec![vec![0, 1], vec![1, 3], vec![2, 3], vec![4, 0], vec![4, 5]]
        ),
        3
    );

    assert_eq!(
        min_reorder(5, vec![vec![1, 0], vec![1, 2], vec![3, 2], vec![3, 4]]),
        2
    );
}
<|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>