<commit_before>
use std;
use piston::{
    Event,
    Input,
    Update,
    UpdateArgs,
};
use piston::input;
use {
    Action,
    AlwaysSucceed,
    Behavior,
    Failure,
    If,
    Not,
    Pressed,
    Released,
    Running,
    Select,
    Sequence,
    Status,
    Success,
    Wait,
    WaitForever,
    WhenAll,
    While,
};

/// Keeps track of a behavior.
#[deriving(Clone)]
pub enum State<A> {
    /// Returns `Success` when button is pressed.
    PressedState(input::Button),
    /// Returns `Success` when button is released.
    ReleasedState(input::Button),
    /// Executes an action.
    ActionState(A),
    /// Converts `Success` into `Failure` and vice versa.
    NotState(Box<State<A>>),
    /// Ignores failures and always return `Success`.
    AlwaysSucceedState(Box<State<A>>),
    /// Number of seconds we should wait and seconds we have waited.
    WaitState(f64, f64),
    /// Waits forever.
    WaitForeverState,
    /// Keeps track of an `If` behavior.
    /// If status is `Running`, then it evaluates the condition.
    /// If status is `Success`, then it evaluates the success behavior.
    /// If status is `Failure`, then it evaluates the failure behavior.
    IfState(Box<Behavior<A>>, Box<Behavior<A>>, Status, Box<State<A>>),
    /// Keeps track of a `Select` behavior.
    SelectState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an `Sequence` behavior.
    SequenceState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of a `While` behavior.
    WhileState(Box<State<A>>, Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an `WhenAll` behavior.
    WhenAllState(Vec<Option<State<A>>>),
}

impl<A: Clone> State<A> {
    /// Creates a state from a behavior.
    pub fn new(behavior: Behavior<A>) -> State<A> {
        match behavior {
            Pressed(button) => PressedState(button),
            Released(button) => ReleasedState(button),
            Action(action) => ActionState(action),
            Not(ev) => NotState(box State::new(*ev)),
            AlwaysSucceed(ev) => AlwaysSucceedState(box State::new(*ev)),
            Wait(dt) => WaitState(dt, 0.0),
            WaitForever => WaitForeverState,
            If(condition, success, failure) => {
                let state = State::new(*condition);
                IfState(success, failure, Running, box state)
            }
            Select(sel) => {
                let state = State::new(sel[0].clone());
                SelectState(sel, 0, box state)
            }
            Sequence(seq) => {
                let state = State::new(seq[0].clone());
                SequenceState(seq, 0, box state)
            }
            While(ev, rep) => {
                let state = State::new(rep[0].clone());
                WhileState(box State::new(*ev), rep, 0, box state)
            }
            WhenAll(all)
                => WhenAllState(all.move_iter().map(
                    |ev| Some(State::new(ev))).collect()),
        }
    }

    /// Updates the cursor that tracks an event.
    ///
    /// The action need to return status and remaining delta time.
    /// Returns status and the remaining delta time.
    pub fn update(
        &mut self,
        e: &Event,
        f: |dt: f64, action: &A| -> (Status, f64)
    ) -> (Status, f64) {
        match (e, self) {
            (&Input(input::Press(button_pressed)), &PressedState(button))
            if button_pressed == button => {
                // Button press is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Input(input::Release(button_released)), &ReleasedState(button))
            if button_released == button => {
                // Button release is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Update(UpdateArgs { dt }), &ActionState(ref action)) => {
                // Execute action.
                f(dt, action)
            }
            (_, &NotState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (Failure, dt) => (Success, dt),
                    (Success, dt) => (Failure, dt),
                }
            }
            (_, &AlwaysSucceedState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (_, dt) => (Success, dt),
                }
            }
            (&Update(UpdateArgs { dt }), &WaitState(wait_t, ref mut t)) => {
                if *t + dt >= wait_t {
                    let remaining_dt = *t + dt - wait_t;
                    *t = wait_t;
                    (Success, remaining_dt)
                } else {
                    *t += dt;
                    (Running, 0.0)
                }
            }
            (_, &IfState(ref success, ref failure,
                         ref mut status, ref mut state)) => {
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                // Run in a loop to evaluate success or failure with
                // remaining delta time after condition.
                loop {
                    *status = match *status {
                        Running => {
                            match state.update(e, |dt, a| f(dt, a)) {
                                (Running, dt) => { return (Running, dt); },
                                (Success, dt) => {
                                    **state = State::new((**success).clone());
                                    remaining_dt = dt;
                                    Success
                                }
                                (Failure, dt) => {
                                    **state = State::new((**failure).clone());
                                    remaining_dt = dt;
                                    Failure
                                }
                            }
                        }
                        _ => {
                            return state.update(match *e {
                                Update(_) => {
                                    remaining_e = Update(UpdateArgs {
                                            dt: remaining_dt
                                        });
                                    &remaining_e
                                }
                                _ => e
                            }, |dt, a| f(dt, a));
                        }
                    }
                }
            }
            (_, &SelectState(
                ref seq,
                ref mut i,
                ref mut cursor
            )) => {
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cursor.update(
                        match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs {
                                        dt: remaining_dt
                                    });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Success, x) => { return (Success, x) }
                        (Running, _) => { break }
                        (Failure, new_dt) => { remaining_dt = new_dt }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Failure, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cursor = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &SequenceState(
                ref seq,
                ref mut i,
                ref mut cursor
            )) => {
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs {
                                        dt: remaining_dt
                                    });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                // If this is the last event, then the sequence succeeded.
                                _ => if *i == seq.len() - 1 {
                                        return (Success, new_dt)
                                    } else {
                                        return (Running, 0.0)
                                    }
                            }
                        }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Success, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhileState(
                ref mut ev_cursor,
                ref rep,
                ref mut i,
                ref mut cursor
            )) => {
                // If the event terminates, do not execute the loop.
                match ev_cursor.update(e, |dt, a| f(dt, a)) {
                    (Running, _) => {}
                    x => return x,
                };
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                loop {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs {
                                        dt: remaining_dt
                                    });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                _ => return (Running, 0.0)
                            }
                        }
                    };
                    *i += 1;
                    // If end of repeated events,
                    // start over from the first one.
                    if *i >= rep.len() { *i = 0; }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(rep[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhenAllState(ref mut cursors)) => {
                // Get the least delta time left over.
                let mut min_dt = std::f64::MAX_VALUE;
                // Count number of terminated events.
                let mut terminated = 0;
                for cur in cursors.mut_iter() {
                    match *cur {
                        None => terminated += 1,
                        Some(ref mut cur) => {
                            match cur.update(e, |dt, a| f(dt, a)) {
                                (Running, _) => {},
                                (Failure, new_dt) => return (Failure, new_dt),
                                (Success, new_dt) => {
                                    min_dt = min_dt.min(new_dt);
                                    terminated += 1;
                                }
                            }
                        }
                    }
                }
                match terminated {
                    // If there are no events, there is a whole 'dt' left.
                    0 if cursors.len() == 0 => (Success, match *e {
                            Update(UpdateArgs { dt }) => dt,
                            // Other kind of events happen instantly.
                            _ => 0.0
                        }),
                    // If all events terminated, the least delta time is left.
                    n if cursors.len() == n => (Success, min_dt),
                    _ => (Running, 0.0)
                }
            }
            _ => (Running, 0.0)
        }
    }
}
<commit_msg>Fixed arguments<commit_after>
use std;
use piston::{
    Event,
    Input,
    Update,
    UpdateArgs,
};
use piston::input;
use {
    Action,
    AlwaysSucceed,
    Behavior,
    Failure,
    If,
    Not,
    Pressed,
    Released,
    Running,
    Select,
    Sequence,
    Status,
    Success,
    Wait,
    WaitForever,
    WhenAll,
    While,
};

/// Keeps track of a behavior.
#[deriving(Clone)]
pub enum State<A> {
    /// Returns `Success` when button is pressed.
    PressedState(input::Button),
    /// Returns `Success` when button is released.
    ReleasedState(input::Button),
    /// Executes an action.
    ActionState(A),
    /// Converts `Success` into `Failure` and vice versa.
    NotState(Box<State<A>>),
    /// Ignores failures and always return `Success`.
    AlwaysSucceedState(Box<State<A>>),
    /// Number of seconds we should wait and seconds we have waited.
    WaitState(f64, f64),
    /// Waits forever.
    WaitForeverState,
    /// Keeps track of an `If` behavior.
    /// If status is `Running`, then it evaluates the condition.
    /// If status is `Success`, then it evaluates the success behavior.
    /// If status is `Failure`, then it evaluates the failure behavior.
    IfState(Box<Behavior<A>>, Box<Behavior<A>>, Status, Box<State<A>>),
    /// Keeps track of a `Select` behavior.
    SelectState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an `Sequence` behavior.
    SequenceState(Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of a `While` behavior.
    WhileState(Box<State<A>>, Vec<Behavior<A>>, uint, Box<State<A>>),
    /// Keeps track of an `WhenAll` behavior.
    WhenAllState(Vec<Option<State<A>>>),
}

impl<A: Clone> State<A> {
    /// Creates a state from a behavior.
    pub fn new(behavior: Behavior<A>) -> State<A> {
        match behavior {
            Pressed(button) => PressedState(button),
            Released(button) => ReleasedState(button),
            Action(action) => ActionState(action),
            Not(ev) => NotState(box State::new(*ev)),
            AlwaysSucceed(ev) => AlwaysSucceedState(box State::new(*ev)),
            Wait(dt) => WaitState(dt, 0.0),
            WaitForever => WaitForeverState,
            If(condition, success, failure) => {
                let state = State::new(*condition);
                IfState(success, failure, Running, box state)
            }
            Select(sel) => {
                let state = State::new(sel[0].clone());
                SelectState(sel, 0, box state)
            }
            Sequence(seq) => {
                let state = State::new(seq[0].clone());
                SequenceState(seq, 0, box state)
            }
            While(ev, rep) => {
                let state = State::new(rep[0].clone());
                WhileState(box State::new(*ev), rep, 0, box state)
            }
            WhenAll(all)
                => WhenAllState(all.move_iter().map(
                    |ev| Some(State::new(ev))).collect()),
        }
    }

    /// Updates the cursor that tracks an event.
    ///
    /// The action need to return status and remaining delta time.
    /// Returns status and the remaining delta time.
    pub fn update(
        &mut self,
        e: &Event,
        f: |dt: f64, action: &A| -> (Status, f64)
    ) -> (Status, f64) {
        match (e, self) {
            (&Input(input::Press(button_pressed)), &PressedState(button))
            if button_pressed == button => {
                // Button press is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Input(input::Release(button_released)), &ReleasedState(button))
            if button_released == button => {
                // Button release is considered to happen instantly.
                // There is no remaining delta time because this is input event.
                (Success, 0.0)
            }
            (&Update(UpdateArgs { dt }), &ActionState(ref action)) => {
                // Execute action.
                f(dt, action)
            }
            (_, &NotState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (Failure, dt) => (Success, dt),
                    (Success, dt) => (Failure, dt),
                }
            }
            (_, &AlwaysSucceedState(ref mut cur)) => {
                match cur.update(e, f) {
                    (Running, dt) => (Running, dt),
                    (_, dt) => (Success, dt),
                }
            }
            (&Update(UpdateArgs { dt }), &WaitState(wait_t, ref mut t)) => {
                if *t + dt >= wait_t {
                    let remaining_dt = *t + dt - wait_t;
                    *t = wait_t;
                    (Success, remaining_dt)
                } else {
                    *t += dt;
                    (Running, 0.0)
                }
            }
            (_, &IfState(ref success, ref failure,
                         ref mut status, ref mut state)) => {
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                // Run in a loop to evaluate success or failure with
                // remaining delta time after condition.
                loop {
                    *status = match *status {
                        Running => {
                            match state.update(e, |dt, a| f(dt, a)) {
                                (Running, dt) => { return (Running, dt); },
                                (Success, dt) => {
                                    **state = State::new((**success).clone());
                                    remaining_dt = dt;
                                    Success
                                }
                                (Failure, dt) => {
                                    **state = State::new((**failure).clone());
                                    remaining_dt = dt;
                                    Failure
                                }
                            }
                        }
                        _ => {
                            return state.update(match *e {
                                Update(_) => {
                                    remaining_e = Update(UpdateArgs {
                                            dt: remaining_dt
                                        });
                                    &remaining_e
                                }
                                _ => e
                            }, |dt, a| f(dt, a));
                        }
                    }
                }
            }
            (_, &SelectState(
                ref seq,
                ref mut i,
                ref mut cursor
            )) => {
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cursor.update(
                        match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs {
                                        dt: remaining_dt
                                    });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Success, x) => { return (Success, x) }
                        (Running, _) => { break }
                        (Failure, new_dt) => { remaining_dt = new_dt }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Failure, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cursor = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &SequenceState(ref seq, ref mut i, ref mut cursor)) => {
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                while *i < seq.len() {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs {
                                        dt: remaining_dt
                                    });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                // If this is the last event, then the sequence succeeded.
                                _ => if *i == seq.len() - 1 {
                                        return (Success, new_dt)
                                    } else {
                                        return (Running, 0.0)
                                    }
                            }
                        }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return (Success, remaining_dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(seq[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhileState(ref mut ev_cursor, ref rep, ref mut i,
                            ref mut cursor)) => {
                // If the event terminates, do not execute the loop.
                match ev_cursor.update(e, |dt, a| f(dt, a)) {
                    (Running, _) => {}
                    x => return x,
                };
                let cur = cursor;
                let mut remaining_dt = match *e {
                        Update(UpdateArgs { dt }) => dt,
                        _ => 0.0,
                    };
                let mut remaining_e;
                loop {
                    match cur.update(match *e {
                            Update(_) => {
                                remaining_e = Update(UpdateArgs {
                                        dt: remaining_dt
                                    });
                                &remaining_e
                            }
                            _ => e
                        },
                        |dt, a| f(dt, a)) {
                        (Failure, x) => return (Failure, x),
                        (Running, _) => { break },
                        (Success, new_dt) => {
                            remaining_dt = match *e {
                                // Change update event with remaining delta time.
                                Update(_) => new_dt,
                                // Other events are 'consumed' and not passed to next.
                                _ => return (Running, 0.0)
                            }
                        }
                    };
                    *i += 1;
                    // If end of repeated events,
                    // start over from the first one.
                    if *i >= rep.len() { *i = 0; }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = State::new(rep[*i].clone());
                }
                (Running, 0.0)
            }
            (_, &WhenAllState(ref mut cursors)) => {
                // Get the least delta time left over.
                let mut min_dt = std::f64::MAX_VALUE;
                // Count number of terminated events.
                let mut terminated = 0;
                for cur in cursors.mut_iter() {
                    match *cur {
                        None => terminated += 1,
                        Some(ref mut cur) => {
                            match cur.update(e, |dt, a| f(dt, a)) {
                                (Running, _) => {},
                                (Failure, new_dt) => return (Failure, new_dt),
                                (Success, new_dt) => {
                                    min_dt = min_dt.min(new_dt);
                                    terminated += 1;
                                }
                            }
                        }
                    }
                }
                match terminated {
                    // If there are no events, there is a whole 'dt' left.
                    0 if cursors.len() == 0 => (Success, match *e {
                            Update(UpdateArgs { dt }) => dt,
                            // Other kind of events happen instantly.
                            _ => 0.0
                        }),
                    // If all events terminated, the least delta time is left.
                    n if cursors.len() == n => (Success, min_dt),
                    _ => (Running, 0.0)
                }
            }
            _ => (Running, 0.0)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix(trash): fix send to trash on windows<commit_after><|endoftext|>


<commit_before><commit_msg>Get started with importing the tcp scheme to userspace<commit_after>use redox::Box;
use redox::fs::file::File;
use redox::io::{Read, Write, Seek, SeekFrom};
use redox::mem;
use redox::net::*;
use redox::ptr;
use redox::rand;
use redox::slice;
use redox::str;
use redox::{String, ToString};
use redox::to_num::*;
use redox::Vec;

/// TCP resource
pub struct Resource {
    ip: Box<Resource>,
    peer_addr: IPv4Addr,
    peer_port: u16,
    host_port: u16,
    sequence: u32,
    acknowledge: u32,
}

impl Resource {
    pub fn dup(&self) -> Option<Box<Self>> {
        match self.ip.dup() {
            Some(ip) => Some(box Resource {
                ip: ip,
                peer_addr: self.peer_addr,
                peer_port: self.peer_port,
                host_port: self.host_port,
                sequence: self.sequence,
                acknowledge: self.acknowledge,
            }),
            None => None
        }
    }

    pub fn path(&self, buf: &mut [u8]) -> Option<usize> {
        let path = format!("tcp://{}:{}/{}", self.peer_addr.to_string(), self.peer_port, self.host_port);

        let mut i = 0;
        for b in path.bytes() {
            if i < buf.len() {
                buf[i] = b;
                i += 1;
            } else {
                break;
            }
        }

        Some(i)
    }

    pub fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        /*
        loop {
            let mut bytes: Vec<u8> = Vec::new();
            match self.ip.read_to_end(&mut bytes) {
                Some(_) => {
                    if let Some(segment) = TCP::from_bytes(bytes) {
                        if (segment.header.flags.get() & (TCP_PSH | TCP_SYN | TCP_ACK)) ==
                           (TCP_PSH | TCP_ACK) &&
                           segment.header.dst.get() == self.host_port &&
                           segment.header.src.get() == self.peer_port {
                            //Send ACK
                            self.sequence = segment.header.ack_num.get();
                            self.acknowledge = segment.header.sequence.get() +
                                               segment.data.len() as u32;
                            let mut tcp = TCP {
                                header: TCPHeader {
                                    src: n16::new(self.host_port),
                                    dst: n16::new(self.peer_port),
                                    sequence: n32::new(self.sequence),
                                    ack_num: n32::new(self.acknowledge),
                                    flags: n16::new(((mem::size_of::<TCPHeader>() << 10) & 0xF000) as u16 | TCP_ACK),
                                    window_size: n16::new(65535),
                                    checksum: Checksum {
                                        data: 0
                                    },
                                    urgent_pointer: n16::new(0)
                                },
                                options: Vec::new(),
                                data: Vec::new()
                            };

                            unsafe {
                                let proto = n16::new(0x06);
                                let segment_len = n16::new((mem::size_of::<TCPHeader>() + tcp.options.len() + tcp.data.len()) as u16);
                                tcp.header.checksum.data = Checksum::compile(
                                    Checksum::sum((&IP_ADDR as *const IPv4Addr) as usize, mem::size_of::<IPv4Addr>()) +
                                    Checksum::sum((&self.peer_addr as *const IPv4Addr) as usize, mem::size_of::<IPv4Addr>()) +
                                    Checksum::sum((&proto as *const n16) as usize, mem::size_of::<n16>()) +
                                    Checksum::sum((&segment_len as *const n16) as usize, mem::size_of::<n16>()) +
                                    Checksum::sum((&tcp.header as *const TCPHeader) as usize, mem::size_of::<TCPHeader>()) +
                                    Checksum::sum(tcp.options.as_ptr() as usize, tcp.options.len()) +
                                    Checksum::sum(tcp.data.as_ptr() as usize, tcp.data.len())
                                );
                            }

                            self.ip.write(&tcp.to_bytes().as_slice());

                            vec.push_all(&segment.data);
                            return Some(segment.data.len());
                        }
                    }
                }
                None => return None,
            }
        }
        */
        None
    }

    pub fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let tcp_data = unsafe { Vec::from_raw_buf(buf.as_ptr(), buf.len()) };

        let mut tcp = TCP {
            header: TCPHeader {
                src: n16::new(self.host_port),
                dst: n16::new(self.peer_port),
                sequence: n32::new(self.sequence),
                ack_num: n32::new(self.acknowledge),
                flags: n16::new((((mem::size_of::<TCPHeader>()) << 10) & 0xF000) as u16 | TCP_PSH |
                                TCP_ACK),
                window_size: n16::new(65535),
                checksum: Checksum { data: 0 },
                urgent_pointer: n16::new(0),
            },
            options: Vec::new(),
            data: tcp_data,
        };

        unsafe {
            let proto = n16::new(0x06);
            let segment_len = n16::new((mem::size_of::<TCPHeader>() + tcp.data.len()) as u16);
            tcp.header.checksum.data =
                Checksum::compile(Checksum::sum((&IP_ADDR as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&self.peer_addr as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&proto as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&segment_len as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&tcp.header as *const TCPHeader) as usize,
                                                mem::size_of::<TCPHeader>()) +
                                  Checksum::sum(tcp.options.as_ptr() as usize, tcp.options.len()) +
                                  Checksum::sum(tcp.data.as_ptr() as usize, tcp.data.len()));
        }

        match self.ip.write(&tcp.to_bytes().as_slice()) {
            Some(size) => loop { // Wait for ACK
                let mut bytes: Vec<u8> = Vec::new();
                match self.ip.read_to_end(&mut bytes) {
                    Some(_) => {
                        if let Some(segment) = TCP::from_bytes(bytes) {
                            if segment.header.dst.get() == self.host_port &&
                               segment.header.src.get() == self.peer_port {
                                if (segment.header.flags.get() & (TCP_PSH | TCP_SYN | TCP_ACK)) ==
                                   TCP_ACK {
                                    self.sequence = segment.header.ack_num.get();
                                    self.acknowledge = segment.header.sequence.get();
                                    return Some(size);
                                } else {
                                    return None;
                                }
                            }
                        }
                    }
                    None => return None,
                }
            },
            None => return None,
        }
    }

    pub fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        None
    }

    pub fn sync(&mut self) -> bool {
        self.ip.sync()
    }
}

/*
impl Resource {
    /// Etablish client
    pub fn client_establish(&mut self) -> bool {
        // Send SYN
        let mut tcp = TCP {
            header: TCPHeader {
                src: n16::new(self.host_port),
                dst: n16::new(self.peer_port),
                sequence: n32::new(self.sequence),
                ack_num: n32::new(self.acknowledge),
                flags: n16::new(((mem::size_of::<TCPHeader>() << 10) & 0xF000) as u16 | TCP_SYN),
                window_size: n16::new(65535),
                checksum: Checksum { data: 0 },
                urgent_pointer: n16::new(0),
            },
            options: Vec::new(),
            data: Vec::new(),
        };

        unsafe {
            let proto = n16::new(0x06);
            let segment_len =
                n16::new((mem::size_of::<TCPHeader>() + tcp.options.len() + tcp.data.len()) as u16);
            tcp.header.checksum.data =
                Checksum::compile(Checksum::sum((&IP_ADDR as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&self.peer_addr as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&proto as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&segment_len as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&tcp.header as *const TCPHeader) as usize,
                                                mem::size_of::<TCPHeader>()) +
                                  Checksum::sum(tcp.options.as_ptr() as usize, tcp.options.len()) +
                                  Checksum::sum(tcp.data.as_ptr() as usize, tcp.data.len()));
        }

        match self.ip.write(&tcp.to_bytes().as_slice()) {
            Some(_) => loop { // Wait for SYN-ACK
                let mut bytes: Vec<u8> = Vec::new();
                match self.ip.read_to_end(&mut bytes) {
                    Some(_) => {
                        if let Some(segment) = TCP::from_bytes(bytes) {
                            if segment.header.dst.get() == self.host_port &&
                               segment.header.src.get() == self.peer_port {
                                if (segment.header.flags.get() & (TCP_PSH | TCP_SYN | TCP_ACK)) ==
                                   (TCP_SYN | TCP_ACK) {
                                    self.sequence = segment.header.ack_num.get();
                                    self.acknowledge = segment.header.sequence.get();

                                    self.acknowledge += 1;
                                    tcp = TCP {
                                        header: TCPHeader {
                                            src: n16::new(self.host_port),
                                            dst: n16::new(self.peer_port),
                                            sequence: n32::new(self.sequence),
                                            ack_num: n32::new(self.acknowledge),
                                            flags: n16::new(((mem::size_of::<TCPHeader>() << 10) & 0xF000) as u16 | TCP_ACK),
                                            window_size: n16::new(65535),
                                            checksum: Checksum {
                                                data: 0
                                            },
                                            urgent_pointer: n16::new(0)
                                        },
                                        options: Vec::new(),
                                        data: Vec::new()
                                    };

                                    unsafe {
                                        let proto = n16::new(0x06);
                                        let segment_len = n16::new((mem::size_of::<TCPHeader>() + tcp.options.len() + tcp.data.len()) as u16);
                                        tcp.header.checksum.data = Checksum::compile(
                                            Checksum::sum((&IP_ADDR as *const IPv4Addr) as usize, mem::size_of::<IPv4Addr>()) +
                                            Checksum::sum((&self.peer_addr as *const IPv4Addr) as usize, mem::size_of::<IPv4Addr>()) +
                                            Checksum::sum((&proto as *const n16) as usize, mem::size_of::<n16>()) +
                                            Checksum::sum((&segment_len as *const n16) as usize, mem::size_of::<n16>()) +
                                            Checksum::sum((&tcp.header as *const TCPHeader) as usize, mem::size_of::<TCPHeader>()) +
                                            Checksum::sum(tcp.options.as_ptr() as usize, tcp.options.len()) +
                                            Checksum::sum(tcp.data.as_ptr() as usize, tcp.data.len())
                                        );
                                    }

                                    self.ip.write(&tcp.to_bytes().as_slice());

                                    return true;
                                } else {
                                    return false;
                                }
                            }
                        }
                    }
                    None => return false,
                }
            },
            None => return false,
        }
    }

    /// Try to establish a server connection
    pub fn server_establish(&mut self, syn: TCP) -> bool {
        //Send SYN-ACK
        self.acknowledge += 1;
        let mut tcp = TCP {
            header: TCPHeader {
                src: n16::new(self.host_port),
                dst: n16::new(self.peer_port),
                sequence: n32::new(self.sequence),
                ack_num: n32::new(self.acknowledge),
                flags: n16::new(((mem::size_of::<TCPHeader>() << 10) & 0xF000) as u16 | TCP_SYN |
                                TCP_ACK),
                window_size: n16::new(65535),
                checksum: Checksum { data: 0 },
                urgent_pointer: n16::new(0),
            },
            options: Vec::new(),
            data: Vec::new(),
        };

        unsafe {
            let proto = n16::new(0x06);
            let segment_len =
                n16::new((mem::size_of::<TCPHeader>() + tcp.options.len() + tcp.data.len()) as u16);
            tcp.header.checksum.data =
                Checksum::compile(Checksum::sum((&IP_ADDR as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&self.peer_addr as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&proto as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&segment_len as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&tcp.header as *const TCPHeader) as usize,
                                                mem::size_of::<TCPHeader>()) +
                                  Checksum::sum(tcp.options.as_ptr() as usize, tcp.options.len()) +
                                  Checksum::sum(tcp.data.as_ptr() as usize, tcp.data.len()));
        }

        match self.ip.write(&tcp.to_bytes().as_slice()) {
            Some(_) => loop { // Wait for ACK
                let mut bytes: Vec<u8> = Vec::new();
                match self.ip.read_to_end(&mut bytes) {
                    Some(_) => {
                        if let Some(segment) = TCP::from_bytes(bytes) {
                            if segment.header.dst.get() == self.host_port &&
                               segment.header.src.get() == self.peer_port {
                                if (segment.header.flags.get() & (TCP_PSH | TCP_SYN | TCP_ACK)) ==
                                   TCP_ACK {
                                    self.sequence = segment.header.ack_num.get();
                                    self.acknowledge = segment.header.sequence.get();
                                    return true;
                                } else {
                                    return false;
                                }
                            }
                        }
                    }
                    None => return false,
                }
            },
            None => return false,
        }
    }
}

impl Drop for Resource {
    fn drop(&mut self) {
        //Send FIN-ACK
        let mut tcp = TCP {
            header: TCPHeader {
                src: n16::new(self.host_port),
                dst: n16::new(self.peer_port),
                sequence: n32::new(self.sequence),
                ack_num: n32::new(self.acknowledge),
                flags: n16::new((((mem::size_of::<TCPHeader>()) << 10) & 0xF000) as u16 | TCP_FIN |
                                TCP_ACK),
                window_size: n16::new(65535),
                checksum: Checksum { data: 0 },
                urgent_pointer: n16::new(0),
            },
            options: Vec::new(),
            data: Vec::new(),
        };

        unsafe {
            let proto = n16::new(0x06);
            let segment_len =
                n16::new((mem::size_of::<TCPHeader>() + tcp.options.len() + tcp.data.len()) as u16);
            tcp.header.checksum.data =
                Checksum::compile(Checksum::sum((&IP_ADDR as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&self.peer_addr as *const IPv4Addr) as usize,
                                                mem::size_of::<IPv4Addr>()) +
                                  Checksum::sum((&proto as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&segment_len as *const n16) as usize,
                                                mem::size_of::<n16>()) +
                                  Checksum::sum((&tcp.header as *const TCPHeader) as usize,
                                                mem::size_of::<TCPHeader>()) +
                                  Checksum::sum(tcp.options.as_ptr() as usize, tcp.options.len()) +
                                  Checksum::sum(tcp.data.as_ptr() as usize, tcp.data.len()));
        }

        self.ip.write(&tcp.to_bytes().as_slice());
    }
}
*/

/// A TCP scheme
pub struct Scheme;

impl Scheme {
    pub fn new() -> Box<Self> {
        box Scheme
    }

    pub fn open(&mut self, url: &str) -> Option<Box<Resource>> {
        if url.host().len() > 0 && url.port().len() > 0 {
            let peer_addr = IPv4Addr::from_string(&url.host());
            let peer_port = url.port().to_num() as u16;
            let host_port = (random::rand() % 32768 + 32768) as u16;

            if let Some(ip) = File::open(&("ip://".to_string() + peer_addr.to_string() + "/6")) {
                let mut ret = box TCPResource {
                    ip: ip,
                    peer_addr: peer_addr,
                    peer_port: peer_port,
                    host_port: host_port,
                    sequence: random::rand() as u32,
                    acknowledge: 0,
                };

                if ret.client_establish() {
                    return Some(ret);
                }
            }
        } else if url.path().len() > 0 {
            let host_port = url.path().to_num() as u16;

            while let Some(mut ip) = File::open("ip:///6") {
                let mut bytes: Vec<u8> = Vec::new();
                match ip.read_to_end(&mut bytes) {
                    Some(_) => {
                        if let Some(segment) = TCP::from_bytes(bytes) {
                            if segment.header.dst.get() == host_port &&
                               (segment.header.flags.get() & (TCP_PSH | TCP_SYN | TCP_ACK)) ==
                               TCP_SYN {
                                let peer_addr = IPv4Addr::from_string(&ip.url().host());

                                let mut ret = box TCPResource {
                                    ip: ip,
                                    peer_addr: peer_addr,
                                    peer_port: segment.header.src.get(),
                                    host_port: host_port,
                                    sequence: random::rand() as u32,
                                    acknowledge: segment.header.sequence.get(),
                                };

                                if ret.server_establish(segment) {
                                    return Some(ret);
                                }
                            }
                        }
                    }
                    None => break,
                }
            }
        } else {
            /*
            debug::d("TCP: No remote endpoint or local port provided\n");
            */
        }

        None
    }
}
<|endoftext|>


<commit_before><commit_msg>add long body tests<commit_after>extern crate http_parser;

use http_parser::{HttpParserType, HttpParser, HttpParserCallback};

mod helper;

#[test]
fn test_no_overflow_long_body_request() {
    test_no_overflow_long_body(HttpParserType::HttpRequest, 1000);
    test_no_overflow_long_body(HttpParserType::HttpRequest, 100000);
}

#[test]
fn test_no_overflow_long_body_response() {
    test_no_overflow_long_body(HttpParserType::HttpResponse, 1000);
    test_no_overflow_long_body(HttpParserType::HttpResponse, 100000);
}

fn test_no_overflow_long_body(tp: HttpParserType, length: u64) {
    let mut hp = HttpParser::new(tp);
    let cb = helper::CallbackEmpty;

    let line = if tp == HttpParserType::HttpRequest {
        "POST / HTTP/1.0"
    } else {
        "HTTP/1.0 200 OK"
    };

    let headers = format!("{}\r\nConnection: Keep-Alive\r\nContent-Length: {}\r\n\r\n",
                          line, length);

    let mut parsed = hp.execute(cb, headers.as_bytes());
    assert_eq!(parsed, headers.len() as u64);

    for i in range(0, length) {
        parsed = hp.execute(cb, [b'a'].as_slice());
        assert_eq!(parsed, 1 as u64);
    }

    parsed = hp.execute(cb, headers.as_bytes());
    assert_eq!(parsed, headers.len() as u64);
}
<|endoftext|>


<commit_before><commit_msg>Add basic API tests<commit_after>extern crate cryptocurrency;
extern crate exonum;
extern crate exonum_harness;
extern crate iron;

use exonum::crypto::{self, PublicKey, SecretKey};
use exonum::messages::Message;
use exonum_harness::{TestHarness, HarnessApi};

use cryptocurrency::{TxCreateWallet, TxTransfer, TransactionResponse, Wallet, blockchain};

fn create_wallet(api: &HarnessApi, name: &str) -> (TxCreateWallet, SecretKey) {
    let (pubkey, key) = crypto::gen_keypair();
    // Create a presigned transaction
    let tx = TxCreateWallet::new(&pubkey, name, &key);

    let tx_info: TransactionResponse = api.post("cryptocurrency", "v1/wallets/transaction", &tx);
    assert_eq!(tx_info.tx_hash, tx.hash());

    (tx, key)
}

fn get_wallet(api: &HarnessApi, pubkey: &PublicKey) -> Wallet {
    api.get(
        "cryptocurrency",
        &format!("v1/wallet/{}", pubkey.to_string()),
    )
}

#[test]
fn test_create_wallet() {
    let mut harness = TestHarness::new(blockchain());
    let api = harness.api();
    let (tx, _) = create_wallet(&api, "Alice");

    harness.create_block();

    // Check that the user indeed is persisted by the service
    let wallet = get_wallet(&api, tx.pub_key());
    assert_eq!(wallet.pub_key(), tx.pub_key());
    assert_eq!(wallet.name(), tx.name());
    assert_eq!(wallet.balance(), 100);
}

#[test]
fn test_transfer() {
    let mut harness = TestHarness::new(blockchain());
    let api = harness.api();
    let (tx_alice, key_alice) = create_wallet(&api, "Alice");
    let (tx_bob, _) = create_wallet(&api, "Bob");

    harness.create_block();

    // Check that the initial Alice's and Bob's balances persisted by the service
    let wallet = get_wallet(&api, tx_alice.pub_key());
    assert_eq!(wallet.balance(), 100);
    let wallet = get_wallet(&api, tx_bob.pub_key());
    assert_eq!(wallet.balance(), 100);

    // Transfer funds
    let tx = TxTransfer::new(
        tx_alice.pub_key(),
        tx_bob.pub_key(),
        10, // amount
        0, // seed
        &key_alice,
    );
    let tx_info: TransactionResponse = api.post("cryptocurrency", "v1/wallets/transaction", &tx);
    assert_eq!(tx_info.tx_hash, tx.hash());

    harness.create_block();

    let wallet = get_wallet(&api, tx_alice.pub_key());
    assert_eq!(wallet.balance(), 90);
    let wallet = get_wallet(&api, tx_bob.pub_key());
    assert_eq!(wallet.balance(), 110);
}
<|endoftext|>


<commit_before><commit_msg>fix: Adapt to new test requirements<commit_after><|endoftext|>


<commit_before><commit_msg>practice<commit_after>fn main() {
    println!("practice")
}
<|endoftext|>


<commit_before><commit_msg>Add basic gpio driver<commit_after>#![allow(dead_code)]
pub const PORTF_BASE: *const u32 = 0x40025000 as (*const u32);

pub const PIN0: u32 = (1 << 0);
pub const PIN1: u32 = (1 << 1);
pub const PIN2: u32 = (1 << 2);
pub const PIN3: u32 = (1 << 3);
pub const PIN4: u32 = (1 << 4);
pub const PIN5: u32 = (1 << 5);
pub const PIN6: u32 = (1 << 6);
pub const PIN7: u32 = (1 << 7);

extern {
    fn GPIOPinTypeGPIOOutput(base: *const u32, mask: u32);
    fn GPIOPinWrite(base: *const u32, mask: u32, value: u32);
}

pub fn make_output(base: *const u32, mask: u32) {
    unsafe {
        GPIOPinTypeGPIOOutput(base, mask);
    }
}

pub fn write(base: *const u32, mask: u32, value: u32) {
    unsafe {
        GPIOPinWrite(base, mask, value);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add the file I've been forgetting to add last two commits<commit_after>use std::cell::{RefCell, UnsafeCell};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fmt::{Display, Error, Formatter};
use std::rc::Rc;
use super::parser::{Builder, ParserError, ShowType};

type RcCell<T> = Rc<RefCell<T>>;

struct DocBuilder;
impl Builder for DocBuilder {
    type Table = Table;
    type Array = Array;
    type Key = Key;
    type Value = Value;

    fn table(lead_ws: &str)-> Table { Table::new(lead_ws.to_string()) }
    fn array(vals: Vec<Value>, lead_ws: &str) -> Array { unimplemented!() }
    fn key(val: String, lead_ws: &str) -> Key { Key::new(val) }
    fn value_string(parsed: String, raw: &str, lead_ws: &str) -> Value { unimplemented!() }
    fn value_integer(parsed: i64, raw: &str, lead_ws: &str) -> Value { unimplemented!() }
    fn value_float(parsed: f64, raw: &str, lead_ws: &str) -> Value  { unimplemented!() }
    fn value_boolean(parsed: bool, raw: &str, lead_ws: &str) -> Value  { unimplemented!() }
    fn value_datetime(parsed: String, raw: &str, lead_ws: &str) -> Value { unimplemented!() }
    fn value_array(parsed: Array, raw: &str, lead_ws: &str) -> Value  { unimplemented!() }
    fn value_table(parsed: Table, raw: &str, lead_ws: &str) -> Value  { Value::Table(parsed) }
    fn insert(table: &mut Table, key: Key, v: Value) -> bool  {
        table.insert(key, Box::new(UnsafeCell::new(v)))
    }
    fn insert_container<'b>(mut cur: &'b mut Table, keys: &[String],
                            key_lo: usize, key_hi: usize)
        -> Result<&'b mut Table, ParserError> {
        for part in keys {
            let tmp = cur;

            if tmp.map.contains_key(part) {
                match unsafe { &mut *tmp.map.get_mut(part).unwrap().get() } {
                    &mut Value::Table(ref mut table) => {
                        cur = table;
                        continue
                    }
                    &mut Value::Array(ref mut array) => {
                        match array.vec.last_mut() {
                            Some(&mut Value::Table(ref mut table)) => cur = table,
                            _ => {
                                return Err(ParserError {
                                    lo: key_lo,
                                    hi: key_hi,
                                    desc: format!("array `{}` does not contain \
                                                   tables", part)
                                });
                            }
                        }
                        continue
                    }
                    _ => {
                        return Err(ParserError {
                            lo: key_lo,
                            hi: key_hi,
                            desc: format!("key `{}` was not previously a table",
                                          part)
                        });
                    }
                }
            }

            // Initialize an empty table as part of this sub-key
            tmp.insert(DocBuilder::key(part.clone(), ""), Box::new(UnsafeCell::new(Value::Table(Table::null()))));
            match unsafe { &mut *tmp.map.get_mut(part).unwrap().get() } {
                &mut Value::Table(ref mut inner) => cur = inner,
                _ => unreachable!(),
            }
        }
        Ok(cur)

    }
    fn get_table<'b>(t: &'b mut Table, key: &'b str) -> Option<&'b mut Table>  {
        t.map.get_mut::<'b>(key).and_then(|x| match unsafe { &mut *x.get() } { &mut Value::Table(ref mut s) => Some(s), _ => None })
    }
    fn get_array<'b>(t: &'b mut Table, key: &'b str) -> Option<&'b mut Array> { unimplemented!() }
    fn contains_table(t: &Table) -> bool  {
        t.map.values().any(|v| if let &mut Value::Table(_) = unsafe { &mut *v.get() } { true } else { false })
    }
    fn merge(table: &mut Table, value: Table) -> Result<(), String> {
        for (k, v) in value.map.into_iter() {
            if !table.insert(DocBuilder::key(k.clone(), ""), v) {
                return Err(k);
            }
        }
        Ok(())
    }
    fn push<'b>(vec: &'b mut Array, value: Value) -> Result<(), &'b str>  { unimplemented!() }
    fn set_trailing_aux(table: &mut Table, aux: &str) {
        table.trail = aux.to_string();
    }
}

pub struct Table {
    map: HashMap<String, Box<UnsafeCell<Value>>>,
    vec: Vec<(Key, *mut UnsafeCell<Value>)>,
    lead: Option<String>, // anonymous tables contain no text
    trail: String
}

impl Table {
    fn new(s: String) -> Table {
        Table {
            map: HashMap::new(),
            vec: Vec::new(),
            lead: Some(s),
            trail: String::new()
        }
    }

    fn null() -> Table {
        Table {
            map: HashMap::new(),
            vec: Vec::new(),
            lead: None,
            trail: String::new()
        }
    }

    fn insert(&mut self, k: Key, mut value: Box<UnsafeCell<Value>>) -> bool {
        let key_string = k.text.clone();
        match self.map.entry(key_string) {
            Entry::Vacant(entry) => {
                self.vec.push((k, &mut *value));
                entry.insert(value);
                true
            },
            Entry::Occupied(_) => false
        }
    }

    fn print(&self, buf: &mut String) {
        buf.push_str(self.lead.as_ref().unwrap());
        for &(ref k, ref v) in self.vec.iter() {
            buf.push_str("[");
            k.print(buf);
            buf.push_str("]");
            unsafe { &*(**v).get() }.print(buf);
        }
        buf.push_str(&*self.trail);
    }
}

pub struct Array {
    vec: Vec<Value>
}

#[derive(PartialEq, Eq, Hash)]
enum KeyKind {
    Plain,
    Table
}
#[derive(PartialEq, Eq, Hash)]
pub struct Key {
    kind: KeyKind,
    text: String,
    lead: String,
    trail: String
}
impl Key {
    fn new(s: String) -> Key {
        Key {
            kind: KeyKind::Plain,
            text: s,
            lead: String::new(),
            trail: String::new()
        }
    }
    fn new_table(s: String) -> Key {
        Key {
            kind: KeyKind::Table,
            text: s,
            lead: String::new(),
            trail: String::new()
        }
    }

    fn print(&self, buf: &mut String) {
        buf.push_str(&*self.lead);
        buf.push_str(&*self.text);
        buf.push_str(&*self.trail);
    }
}

impl Display for Key {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        unimplemented!()
    }
}

pub enum Value {
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Datetime(String),
    Array(Array),
    Table(Table),
}
impl ShowType for Value {
    fn type_str(&self) -> &'static str {
        unimplemented!()
    }
}
impl Value {
    fn print(&self, buf: &mut String) {
        match self {
            &Value::Table(ref t) => t.print(buf),
            _ => unimplemented!()
        }
    }
}

#[cfg(test)]
mod test {
    use super::DocBuilder;
    use super::super::parser::ParseSession;

    macro_rules! round_trip {
        ($text: expr) => ({
            let mut p = ParseSession::new($text, DocBuilder);
            let table = p.parse().unwrap();
            let mut buf = String::new();
            table.print(&mut buf);
            println!("\"{}\"", buf);
            assert!($text == buf);
        })
    }

    #[test]
    fn empty() { round_trip!("  #asd \n ") }
    #[test]
    fn single_table() { round_trip!("  #asd\t  \n [a] \t \n\n  #asdasdad\n ") }

}<|endoftext|>


<commit_before><commit_msg>GDT code<commit_after>use vmx;
use cli;

#[repr(packed)]
struct GDTEntry {
    limit_low: u16,
    base_low: u16,
    base_middle: u8,
    flags: u8,
    more_flags: u8,
    base_high: u8,
}

const GDT: [GDTEntry; 3] = [
    GDTEntry{
        limit_low: 0,
        base_low: 0,
        base_middle: 0,
        flags: 0,
        more_flags: 0,
        base_high: 0,
    },
    GDTEntry{
        limit_low: 0xffff,
        base_low: 0,
        base_middle: 0,
        flags: 0b10101001,
        more_flags: 0b11110111,
        base_high: 0,
    },
    GDTEntry{
        limit_low: 0xffff,
        base_low: 0,
        base_middle: 0,
        flags: 0b00101001,
        more_flags: 0b11110111,
        base_high: 0,
    },
];

pub fn new_host_descriptor() -> vmx::CPUTableDescriptor {
    vmx::CPUTableDescriptor{ limit: 0xffff, base: GDT.as_ptr() as u64 }
}

pub fn test_load() {
    cli::ClearLocalInterruptsGuard::new();
    let gdt_desc = new_host_descriptor();
    let mut orig_gdt_desc: vmx::CPUTableDescriptor = Default::default();
    vmx::sgdt(&mut orig_gdt_desc);
    vmx::lgdt(&gdt_desc);
    vmx::lgdt(&orig_gdt_desc);
}
<|endoftext|>


<commit_before><commit_msg>Remove unnecessary feature attribute<commit_after><|endoftext|>


<commit_before><commit_msg>chore: fixes features declarations<commit_after><|endoftext|>


<commit_before><commit_msg>Minor fixes<commit_after><|endoftext|>


<commit_before><commit_msg>git work, not working yet<commit_after><|endoftext|>


<commit_before><commit_msg>Updated docs<commit_after><|endoftext|>


<commit_before><commit_msg>Dummy lib for root<commit_after>// Dummy lib file so we can refer to the root Calx crate
<|endoftext|>


<commit_before><commit_msg>First insertion implementation, so far without root splitting<commit_after><|endoftext|>


<commit_before><commit_msg>Changed the recv() method to have it return appropriate FunnelErrors and also catch an attempted out-of-bounds read on the sources<commit_after><|endoftext|>


<commit_before>//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which
//! handles receiving events from the OS and dispatching them to a supplied
//! [Handler](handler/trait.Handler.html).
//!
//! # Example
//!
//! ```
//! use mio::*;
//! use mio::tcp::TcpListener;
//! use std::net::SocketAddr;
//! use std::str::FromStr;
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = FromStr::from_str("127.0.0.1:13265").unwrap();
//!
//! // Setup the server socket
//! let server = tcp::listen(&addr).unwrap();
//!
//! // Create an event loop
//! let mut event_loop = EventLoop::new().unwrap();
//!
//! // Start listening for incoming connections
//! event_loop.register(&server, SERVER).unwrap();
//!
//! // Setup the client socket
//! let (sock, _) = tcp::connect(&addr).unwrap();
//!
//! // Register the socket
//! event_loop.register(&sock, CLIENT).unwrap();
//!
//! // Define a handler to process the events
//! struct MyHandler(NonBlock<TcpListener>);
//!
//! impl Handler for MyHandler {
//!     type Timeout = ();
//!     type Message = ();
//!
//!     fn readable(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: ReadHint) {
//!         match token {
//!             SERVER => {
//!                 let MyHandler(ref mut server) = *self;
//!                 // Accept and drop the socket immediately, this will close
//!                 // the socket and notify the client of the EOF.
//!                 let _ = server.accept();
//!             }
//!             CLIENT => {
//!                 // The server just shuts down the socket, let's just
//!                 // shutdown the event loop
//!                 event_loop.shutdown();
//!             }
//!             _ => panic!("unexpected token"),
//!         }
//!     }
//! }
//!
//! // Start handling events
//! event_loop.run(&mut MyHandler(server)).unwrap();
//!
//! ```

#![crate_name = "mio"]

// mio is still in rapid development
#![unstable]

#![feature(alloc, core, io, libc, net, path, std_misc, unsafe_destructor)]

extern crate alloc;
extern crate bytes;
extern crate nix;
extern crate time;

#[macro_use]
extern crate log;

pub mod util;

mod event_loop;
mod handler;
mod io;
mod net;
mod nonblock;
mod notify;
mod os;
mod poll;
mod timer;

pub use buf::{
    Buf,
    MutBuf,
};
pub use event_loop::{
    EventLoop,
    EventLoopConfig,
    EventLoopSender,
};
pub use handler::{
    Handler,
};
pub use io::{
    pipe,
    FromFd,
    Io,
    TryRead,
    TryWrite,
    Evented,
    PipeReader,
    PipeWriter,
};
pub use net::{
    tcp,
    udp,
    unix,
    Socket,
};
pub use nonblock::{
    IntoNonBlock,
    NonBlock,
};
pub use os::token::{
    Token,
};
pub use os::event::{
    PollOpt,
    Interest,
    ReadHint,
};
pub use poll::{
    Poll
};
pub use timer::{
    Timeout,
    TimerError,
    TimerResult
};

pub mod prelude {
    pub use super::{
        EventLoop,
        TryRead,
        TryWrite,
    };
}

// Re-export bytes
pub mod buf {
    pub use bytes::{
        Buf,
        MutBuf,
        ByteBuf,
        MutByteBuf,
        RingBuf,
        SliceBuf,
        MutSliceBuf,
    };
}
<commit_msg>Track Rust master (fix warning)<commit_after>//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which
//! handles receiving events from the OS and dispatching them to a supplied
//! [Handler](handler/trait.Handler.html).
//!
//! # Example
//!
//! ```
//! use mio::*;
//! use mio::tcp::TcpListener;
//! use std::net::SocketAddr;
//! use std::str::FromStr;
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = FromStr::from_str("127.0.0.1:13265").unwrap();
//!
//! // Setup the server socket
//! let server = tcp::listen(&addr).unwrap();
//!
//! // Create an event loop
//! let mut event_loop = EventLoop::new().unwrap();
//!
//! // Start listening for incoming connections
//! event_loop.register(&server, SERVER).unwrap();
//!
//! // Setup the client socket
//! let (sock, _) = tcp::connect(&addr).unwrap();
//!
//! // Register the socket
//! event_loop.register(&sock, CLIENT).unwrap();
//!
//! // Define a handler to process the events
//! struct MyHandler(NonBlock<TcpListener>);
//!
//! impl Handler for MyHandler {
//!     type Timeout = ();
//!     type Message = ();
//!
//!     fn readable(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: ReadHint) {
//!         match token {
//!             SERVER => {
//!                 let MyHandler(ref mut server) = *self;
//!                 // Accept and drop the socket immediately, this will close
//!                 // the socket and notify the client of the EOF.
//!                 let _ = server.accept();
//!             }
//!             CLIENT => {
//!                 // The server just shuts down the socket, let's just
//!                 // shutdown the event loop
//!                 event_loop.shutdown();
//!             }
//!             _ => panic!("unexpected token"),
//!         }
//!     }
//! }
//!
//! // Start handling events
//! event_loop.run(&mut MyHandler(server)).unwrap();
//!
//! ```

#![crate_name = "mio"]

// mio is still in rapid development
#![unstable]

#![feature(alloc, core, io, libc, net, std_misc, unsafe_destructor)]

extern crate alloc;
extern crate bytes;
extern crate nix;
extern crate time;

#[macro_use]
extern crate log;

pub mod util;

mod event_loop;
mod handler;
mod io;
mod net;
mod nonblock;
mod notify;
mod os;
mod poll;
mod timer;

pub use buf::{
    Buf,
    MutBuf,
};
pub use event_loop::{
    EventLoop,
    EventLoopConfig,
    EventLoopSender,
};
pub use handler::{
    Handler,
};
pub use io::{
    pipe,
    FromFd,
    Io,
    TryRead,
    TryWrite,
    Evented,
    PipeReader,
    PipeWriter,
};
pub use net::{
    tcp,
    udp,
    unix,
    Socket,
};
pub use nonblock::{
    IntoNonBlock,
    NonBlock,
};
pub use os::token::{
    Token,
};
pub use os::event::{
    PollOpt,
    Interest,
    ReadHint,
};
pub use poll::{
    Poll
};
pub use timer::{
    Timeout,
    TimerError,
    TimerResult
};

pub mod prelude {
    pub use super::{
        EventLoop,
        TryRead,
        TryWrite,
    };
}

// Re-export bytes
pub mod buf {
    pub use bytes::{
        Buf,
        MutBuf,
        ByteBuf,
        MutByteBuf,
        RingBuf,
        SliceBuf,
        MutSliceBuf,
    };
}
<|endoftext|>


<commit_before><commit_msg>add error method<commit_after><|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before>use std::process::Command;

use self::grammar::pipelines;
use glob::glob;

#[derive(Debug, PartialEq, Clone)]
pub struct Pipeline {
    pub jobs: Vec<Job>,
    pub stdout_file: Option<String>,
    pub stdin_file: Option<String>,
}

impl Pipeline {

    pub fn new(jobs: Vec<Job>, stdin: Option<String>, stdout: Option<String>) -> Self {
        Pipeline {
            jobs: jobs,
            stdin_file: stdin,
            stdout_file: stdout,
        }
    }

    pub fn expand_globs(&mut self) {
        let jobs = self.jobs.drain(..).map(|mut job| {
            job.expand_globs();
            job
        }).collect();
        self.jobs = jobs;
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct Job {
    pub command: String,
    pub args: Vec<String>,
    pub background: bool,
}

impl Job {

    pub fn new(args: Vec<String>, background: bool) -> Self {
        let command = args[0].clone();
        Job {
            command: command,
            args: args,
            background: background,
        }
    }

    pub fn expand_globs(&mut self) {
        let mut new_args: Vec<String> = vec![];
        for arg in self.args.drain(..) {
            let mut pushed_glob = false;
            if let Ok(expanded) = glob(&arg) {
                for path in expanded.filter_map(Result::ok) {
                    pushed_glob = true;
                    new_args.push(path.to_string_lossy().into_owned());
                }
            }
            if !pushed_glob {
                new_args.push(arg);
            }
        }
        self.args = new_args;
    }

    pub fn build_command(&self) -> Command {
        let mut command = Command::new(&self.command);
        for i in 1..self.args.len() {
            if let Some(arg) = self.args.get(i) {
                command.arg(arg);
            }
        }
        command
    }
}

pub fn parse(code: &str) -> Vec<Pipeline> {
    pipelines(code).unwrap_or(vec![])
}

peg! grammar(r#"
use super::Pipeline;
use super::Job;

#[pub]
pipelines -> Vec<Pipeline>
    = (unused* newline)* pipelines:pipeline ++ ((job_ending+ unused*)+) (newline unused*)* { pipelines }
    / (unused*) ** newline { vec![] }

pipeline -> Pipeline
    = whitespace? res:job ++ pipeline_sep whitespace? redir:redirection whitespace? comment? { Pipeline::new(res, redir.0, redir.1) }

job -> Job
    = args:word ++ whitespace background:background_token? {
        Job::new(args.iter().map(|arg|arg.to_string()).collect(), background.is_some())
    }

redirection -> (Option<String>, Option<String>)
    = stdin:redirect_stdin whitespace? stdout:redirect_stdout? { (Some(stdin), stdout) }
    / stdout:redirect_stdout whitespace? stdin:redirect_stdin? { (stdin, Some(stdout)) }
    / { (None, None) }

redirect_stdin -> String
    = [<] whitespace? file:word { file.to_string() }

redirect_stdout -> String
    = [>] whitespace? file:word { file.to_string() }

pipeline_sep -> ()
    = (whitespace? [|] whitespace?) { }

background_token -> ()
    = [&]
    / whitespace [&]

word -> &'input str
    = double_quoted_word
    / single_quoted_word
    / [^ \t\r\n#;&|<>]+ { match_str }

double_quoted_word -> &'input str
    = ["] word:_double_quoted_word ["] { word }

_double_quoted_word -> &'input str
    = [^"]+ { match_str }

single_quoted_word -> &'input str
    = ['] word:_single_quoted_word ['] { word }

_single_quoted_word -> &'input str
    = [^']+ { match_str }

unused -> ()
    = whitespace comment? { () }
    / comment { () }

comment -> ()
    = [#] [^\r\n]*

whitespace -> ()
    = [ \t]+

job_ending -> ()
    = [;]
    / newline
    / newline

newline -> ()
    = [\r\n]
"#);

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

    #[test]
    fn single_job_no_args() {
        let jobs = parse("cat").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("cat", jobs[0].command);
        assert_eq!(1, jobs[0].args.len());
    }

    #[test]
    fn single_job_with_args() {
        let jobs = parse("ls -al dir").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[1]);
        assert_eq!("dir", jobs[0].args[2]);
    }

    #[test]
    fn multiple_jobs_with_args() {
        let pipelines = parse("ls -al;cat tmp.txt");
        assert_eq!(2, pipelines.len());
        assert_eq!("ls", pipelines[0].jobs[0].command);
        assert_eq!("-al", pipelines[0].jobs[0].args[1]);
        assert_eq!("cat", pipelines[1].jobs[0].command);
        assert_eq!("tmp.txt", pipelines[1].jobs[0].args[1]);
    }

    #[test]
    fn parse_empty_string() {
        let pipelines = parse("");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn multiple_white_space_between_words() {
        let jobs = parse("ls \t -al\t\tdir").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[1]);
        assert_eq!("dir", jobs[0].args[2]);
    }

    #[test]
    fn trailing_whitespace() {
        let pipelines = parse("ls -al\t ");
        assert_eq!(1, pipelines.len());
        assert_eq!("ls", pipelines[0].jobs[0].command);
        assert_eq!("-al", pipelines[0].jobs[0].args[1]);
    }

    #[test]
    fn double_quoting() {
        let jobs = parse("echo \"Hello World\"").remove(0).jobs;
        assert_eq!(2, jobs[0].args.len());
        assert_eq!("Hello World", jobs[0].args[1]);
    }

    #[test]
    fn all_whitespace() {
        let pipelines = parse("  \t ");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn not_background_job() {
        let jobs = parse("echo hello world").remove(0).jobs;
        assert_eq!(false, jobs[0].background);
    }

    #[test]
    fn background_job() {
        let jobs = parse("echo hello world&").remove(0).jobs;
        assert_eq!(true, jobs[0].background);
    }

    #[test]
    fn background_job_with_space() {
        let jobs = parse("echo hello world &").remove(0).jobs;
        assert_eq!(true, jobs[0].background);
    }

    #[test]
    fn lone_comment() {
        let pipelines = parse("# ; \t as!!+dfa");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn command_followed_by_comment() {
        let pipelines = parse("cat # ; \t as!!+dfa");
        assert_eq!(1, pipelines.len());
        assert_eq!(1, pipelines[0].jobs[0].args.len());
    }

    #[test]
    fn comments_in_multiline_script() {
        let pipelines = parse("echo\n# a comment;\necho#asfasdf");
        assert_eq!(2, pipelines.len());
    }

    #[test]
    fn multiple_newlines() {
        let pipelines = parse("echo\n\ncat");
        assert_eq!(2, pipelines.len());
    }

    #[test]
    fn leading_whitespace() {
        let jobs = parse("    \techo").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("echo", jobs[0].command);
    }

    #[test]
    fn indentation_on_multiple_lines() {
        let pipelines = parse("echo\n  cat");
        assert_eq!(2, pipelines.len());
        assert_eq!("echo", pipelines[0].jobs[0].command);
        assert_eq!("cat", pipelines[1].jobs[0].command);
    }

    #[test]
    fn single_quoting() {
        let jobs = parse("echo '#!!;\"\\'").remove(0).jobs;
        assert_eq!("#!!;\"\\", jobs[0].args[1]);
    }

    #[test]
    fn mixed_quoted_and_unquoted() {
        let jobs = parse("echo '#!!;\"\\' and \t some \"more' 'stuff\"").remove(0).jobs;
        assert_eq!("#!!;\"\\", jobs[0].args[1]);
        assert_eq!("and", jobs[0].args[2]);
        assert_eq!("some", jobs[0].args[3]);
        assert_eq!("more' 'stuff", jobs[0].args[4]);
    }

    #[test]
    fn several_blank_lines() {
        let pipelines = parse("\n\n\n");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn pipelines_with_redirection() {
        let pipelines = parse("cat | echo hello | cat < stuff > other");
        assert_eq!(3, pipelines[0].jobs.len());
        assert_eq!(Some("stuff".to_string()), pipelines[0].stdin_file);
        assert_eq!(Some("other".to_string()), pipelines[0].stdout_file);
    }

    #[test]
    fn pipelines_with_redirection_reverse_order() {
        let pipelines = parse("cat | echo hello | cat > stuff < other");
        assert_eq!(3, pipelines[0].jobs.len());
        assert_eq!(Some("other".to_string()), pipelines[0].stdin_file);
        assert_eq!(Some("stuff".to_string()), pipelines[0].stdout_file);
    }

    #[test]
    fn full_script() {
        pipelines(r#"if a == a
  echo true a == a

  if b != b
    echo true b != b
  else
    echo false b != b

    if 3 > 2
      echo true 3 > 2
    else
      echo false 3 > 2
    fi
  fi
else
  echo false a == a
fi
"#)
            .unwrap();  // Make sure it parses
    }

    #[test]
    fn leading_and_trailing_junk() {
        pipelines(r#"

# comment
   # comment

    if a == a
  echo true a == a  # Line ending commment

  if b != b
    echo true b != b
  else
    echo false b != b

    if 3 > 2
      echo true 3 > 2
    else
      echo false 3 > 2
    fi
  fi
else
  echo false a == a
      fi

# comment

"#).unwrap();  // Make sure it parses
    }
}
<commit_msg>Only expand globs if they contain a metacharater<commit_after>use std::process::Command;

use self::grammar::pipelines;
use glob::glob;

#[derive(Debug, PartialEq, Clone)]
pub struct Pipeline {
    pub jobs: Vec<Job>,
    pub stdout_file: Option<String>,
    pub stdin_file: Option<String>,
}

impl Pipeline {

    pub fn new(jobs: Vec<Job>, stdin: Option<String>, stdout: Option<String>) -> Self {
        Pipeline {
            jobs: jobs,
            stdin_file: stdin,
            stdout_file: stdout,
        }
    }

    pub fn expand_globs(&mut self) {
        let jobs = self.jobs.drain(..).map(|mut job| {
            job.expand_globs();
            job
        }).collect();
        self.jobs = jobs;
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct Job {
    pub command: String,
    pub args: Vec<String>,
    pub background: bool,
}

impl Job {

    pub fn new(args: Vec<String>, background: bool) -> Self {
        let command = args[0].clone();
        Job {
            command: command,
            args: args,
            background: background,
        }
    }

    pub fn expand_globs(&mut self) {
        let mut new_args: Vec<String> = vec![];
        for arg in self.args.drain(..) {
            let mut pushed_glob = false;
            if arg.contains(|chr| chr == '?' || chr == '*' || chr == '[') {
                if let Ok(expanded) = glob(&arg) {
                    for path in expanded.filter_map(Result::ok) {
                        pushed_glob = true;
                        new_args.push(path.to_string_lossy().into_owned());
                    }
                }
            }
            if !pushed_glob {
                new_args.push(arg);
            }
        }
        self.args = new_args;
    }

    pub fn build_command(&self) -> Command {
        let mut command = Command::new(&self.command);
        for i in 1..self.args.len() {
            if let Some(arg) = self.args.get(i) {
                command.arg(arg);
            }
        }
        command
    }
}

pub fn parse(code: &str) -> Vec<Pipeline> {
    pipelines(code).unwrap_or(vec![])
}

peg! grammar(r#"
use super::Pipeline;
use super::Job;

#[pub]
pipelines -> Vec<Pipeline>
    = (unused* newline)* pipelines:pipeline ++ ((job_ending+ unused*)+) (newline unused*)* { pipelines }
    / (unused*) ** newline { vec![] }

pipeline -> Pipeline
    = whitespace? res:job ++ pipeline_sep whitespace? redir:redirection whitespace? comment? { Pipeline::new(res, redir.0, redir.1) }

job -> Job
    = args:word ++ whitespace background:background_token? {
        Job::new(args.iter().map(|arg|arg.to_string()).collect(), background.is_some())
    }

redirection -> (Option<String>, Option<String>)
    = stdin:redirect_stdin whitespace? stdout:redirect_stdout? { (Some(stdin), stdout) }
    / stdout:redirect_stdout whitespace? stdin:redirect_stdin? { (stdin, Some(stdout)) }
    / { (None, None) }

redirect_stdin -> String
    = [<] whitespace? file:word { file.to_string() }

redirect_stdout -> String
    = [>] whitespace? file:word { file.to_string() }

pipeline_sep -> ()
    = (whitespace? [|] whitespace?) { }

background_token -> ()
    = [&]
    / whitespace [&]

word -> &'input str
    = double_quoted_word
    / single_quoted_word
    / [^ \t\r\n#;&|<>]+ { match_str }

double_quoted_word -> &'input str
    = ["] word:_double_quoted_word ["] { word }

_double_quoted_word -> &'input str
    = [^"]+ { match_str }

single_quoted_word -> &'input str
    = ['] word:_single_quoted_word ['] { word }

_single_quoted_word -> &'input str
    = [^']+ { match_str }

unused -> ()
    = whitespace comment? { () }
    / comment { () }

comment -> ()
    = [#] [^\r\n]*

whitespace -> ()
    = [ \t]+

job_ending -> ()
    = [;]
    / newline
    / newline

newline -> ()
    = [\r\n]
"#);

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

    #[test]
    fn single_job_no_args() {
        let jobs = parse("cat").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("cat", jobs[0].command);
        assert_eq!(1, jobs[0].args.len());
    }

    #[test]
    fn single_job_with_args() {
        let jobs = parse("ls -al dir").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[1]);
        assert_eq!("dir", jobs[0].args[2]);
    }

    #[test]
    fn multiple_jobs_with_args() {
        let pipelines = parse("ls -al;cat tmp.txt");
        assert_eq!(2, pipelines.len());
        assert_eq!("ls", pipelines[0].jobs[0].command);
        assert_eq!("-al", pipelines[0].jobs[0].args[1]);
        assert_eq!("cat", pipelines[1].jobs[0].command);
        assert_eq!("tmp.txt", pipelines[1].jobs[0].args[1]);
    }

    #[test]
    fn parse_empty_string() {
        let pipelines = parse("");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn multiple_white_space_between_words() {
        let jobs = parse("ls \t -al\t\tdir").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[1]);
        assert_eq!("dir", jobs[0].args[2]);
    }

    #[test]
    fn trailing_whitespace() {
        let pipelines = parse("ls -al\t ");
        assert_eq!(1, pipelines.len());
        assert_eq!("ls", pipelines[0].jobs[0].command);
        assert_eq!("-al", pipelines[0].jobs[0].args[1]);
    }

    #[test]
    fn double_quoting() {
        let jobs = parse("echo \"Hello World\"").remove(0).jobs;
        assert_eq!(2, jobs[0].args.len());
        assert_eq!("Hello World", jobs[0].args[1]);
    }

    #[test]
    fn all_whitespace() {
        let pipelines = parse("  \t ");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn not_background_job() {
        let jobs = parse("echo hello world").remove(0).jobs;
        assert_eq!(false, jobs[0].background);
    }

    #[test]
    fn background_job() {
        let jobs = parse("echo hello world&").remove(0).jobs;
        assert_eq!(true, jobs[0].background);
    }

    #[test]
    fn background_job_with_space() {
        let jobs = parse("echo hello world &").remove(0).jobs;
        assert_eq!(true, jobs[0].background);
    }

    #[test]
    fn lone_comment() {
        let pipelines = parse("# ; \t as!!+dfa");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn command_followed_by_comment() {
        let pipelines = parse("cat # ; \t as!!+dfa");
        assert_eq!(1, pipelines.len());
        assert_eq!(1, pipelines[0].jobs[0].args.len());
    }

    #[test]
    fn comments_in_multiline_script() {
        let pipelines = parse("echo\n# a comment;\necho#asfasdf");
        assert_eq!(2, pipelines.len());
    }

    #[test]
    fn multiple_newlines() {
        let pipelines = parse("echo\n\ncat");
        assert_eq!(2, pipelines.len());
    }

    #[test]
    fn leading_whitespace() {
        let jobs = parse("    \techo").remove(0).jobs;
        assert_eq!(1, jobs.len());
        assert_eq!("echo", jobs[0].command);
    }

    #[test]
    fn indentation_on_multiple_lines() {
        let pipelines = parse("echo\n  cat");
        assert_eq!(2, pipelines.len());
        assert_eq!("echo", pipelines[0].jobs[0].command);
        assert_eq!("cat", pipelines[1].jobs[0].command);
    }

    #[test]
    fn single_quoting() {
        let jobs = parse("echo '#!!;\"\\'").remove(0).jobs;
        assert_eq!("#!!;\"\\", jobs[0].args[1]);
    }

    #[test]
    fn mixed_quoted_and_unquoted() {
        let jobs = parse("echo '#!!;\"\\' and \t some \"more' 'stuff\"").remove(0).jobs;
        assert_eq!("#!!;\"\\", jobs[0].args[1]);
        assert_eq!("and", jobs[0].args[2]);
        assert_eq!("some", jobs[0].args[3]);
        assert_eq!("more' 'stuff", jobs[0].args[4]);
    }

    #[test]
    fn several_blank_lines() {
        let pipelines = parse("\n\n\n");
        assert_eq!(0, pipelines.len());
    }

    #[test]
    fn pipelines_with_redirection() {
        let pipelines = parse("cat | echo hello | cat < stuff > other");
        assert_eq!(3, pipelines[0].jobs.len());
        assert_eq!(Some("stuff".to_string()), pipelines[0].stdin_file);
        assert_eq!(Some("other".to_string()), pipelines[0].stdout_file);
    }

    #[test]
    fn pipelines_with_redirection_reverse_order() {
        let pipelines = parse("cat | echo hello | cat > stuff < other");
        assert_eq!(3, pipelines[0].jobs.len());
        assert_eq!(Some("other".to_string()), pipelines[0].stdin_file);
        assert_eq!(Some("stuff".to_string()), pipelines[0].stdout_file);
    }

    #[test]
    fn full_script() {
        pipelines(r#"if a == a
  echo true a == a

  if b != b
    echo true b != b
  else
    echo false b != b

    if 3 > 2
      echo true 3 > 2
    else
      echo false 3 > 2
    fi
  fi
else
  echo false a == a
fi
"#)
            .unwrap();  // Make sure it parses
    }

    #[test]
    fn leading_and_trailing_junk() {
        pipelines(r#"

# comment
   # comment

    if a == a
  echo true a == a  # Line ending commment

  if b != b
    echo true b != b
  else
    echo false b != b

    if 3 > 2
      echo true 3 > 2
    else
      echo false 3 > 2
    fi
  fi
else
  echo false a == a
      fi

# comment

"#).unwrap();  // Make sure it parses
    }
}
<|endoftext|>


<commit_before><commit_msg>[projecteuler] Add solution for problem 12 using rust.<commit_after>//! # Problem 12 from projecteuler.net
//!
//! You can find problem description [here][problem].
//!
//! [problem]: https://projecteuler.net/problem=12

mod factorization {

use std::collections::HashMap;

fn ferma_factorization(number: u64) -> (u64, u64)
{
    assert!(number % 2 != 0);
    let mut x = (number as f64).sqrt().ceil() as u64;

    if x == number {
        return (x, 1);
    }

    loop {
        let y = ((x * x - number) as f64).sqrt();
        if y == y.round() {
            return (x - y as u64, x + y as u64);
        }
        x += 1;
    }
}

fn map_incr(map: &mut HashMap<u64, u64>, key: u64) {
        if map.contains_key(&key) {
            *map.get_mut(&key) += 1;
        } else {
            map.insert(key, 1);
        }
}

fn recoursive_factorization(map: &mut HashMap<u64, u64>, mut num: u64) {
    while num % 2 == 0 {
        map_incr(map, 2);
        num /= 2;
    }

    if num == 1 {
        return;
    }

    let factorization = ferma_factorization(num);
    if num == factorization.val0() {
        map_incr(map, num);
    } else {
        recoursive_factorization(map, factorization.val0());
    }

    if num == factorization.val1() {
        map_incr(map, num);
    } else {
        recoursive_factorization(map, factorization.val1());
    }
}

pub fn fast_number_of_divisors(number: u64) -> u64
{
    let mut map: HashMap<u64, u64> = HashMap::new();

    recoursive_factorization(&mut map, number);
    let mut result = 1u64;

    for val in map.values() {
        result *= val + 1;
    }
    return result;
}

fn number_of_divisors(value: u64) -> u64
{
    let mut result = 1;
    let mut current = 1;

    while current < value {
        if value % current == 0 {
            result += 1;
        }
        current += 1;
    }

    return result;
}

#[allow(dead_code)]
pub fn stress_test(n: u64) {
    for n in range(1u64, n) {
        let fast = fast_number_of_divisors(n);
        let slow = number_of_divisors(n);
        if fast != slow {
            println!("n = {}\tgot {}\texpect {}", n, fast, slow);
        }
    }
    println!("TEST OK!");
}

} // mod factorization

fn calc_triangular(num: u64) -> u64
{
    return num * (num + 1) / 2;
}

fn triangular_number_from_divisors(num_divisors: u64) -> u64
{
    let mut current: u64 = 1;
    loop {
        let triangular = calc_triangular(current);
        let triangular_divisors = factorization::fast_number_of_divisors(triangular);

        if triangular_divisors > num_divisors {
            return triangular;
        }

        current += 1;
    }
}

fn main()
{
    factorization::stress_test(500);

    println!("{}", triangular_number_from_divisors(500));
}
<|endoftext|>