<commit_before><commit_msg>watchman_client: add an example for query<commit_after>//! This example shows how to send a query to watchman and print out the files
//! changed since the given timestamp.

use std::path::PathBuf;
use structopt::StructOpt;
use watchman_client::prelude::*;

#[derive(Debug, StructOpt)]
#[structopt(about = "Query files changed since a timestamp")]
struct Opt {
    #[structopt()]
    /// Specifies the clock. Use `watchman clock <PATH>` to retrieve the current clock of a watched
    /// directory
    clock: String,

    #[structopt(short, long)]
    /// [not recommended] Uses Unix timestamp as clock
    unix_timestamp: bool,

    #[structopt(short, long, default_value = ".")]
    /// Specifies the path to watched directory
    path: PathBuf,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    if let Err(err) = run().await {
        // Print a prettier error than the default
        eprintln!("{}", err);
        std::process::exit(1);
    }
    Ok(())
}

async fn run() -> Result<(), Box<dyn std::error::Error>> {
    let opt = Opt::from_args();
    let client = Connector::new().connect().await?;
    let resolved = client
        .resolve_root(CanonicalPath::canonicalize(opt.path)?)
        .await?;

    let clock_spec = if opt.unix_timestamp {
        // it is better to use watchman's clock rather than Unix timestamp.
        // see `watchman_client::pdu::ClockSpec::unix_timestamp` for details.
        ClockSpec::UnixTimestamp(opt.clock.parse()?)
    } else {
        ClockSpec::StringClock(opt.clock)
    };

    let result = client
        .query::<NameOnly>(
            &resolved,
            QueryRequestCommon {
                since: Some(Clock::Spec(clock_spec.clone())),
                ..Default::default()
            },
        )
        .await?;

    eprintln!("Clock is now: {:?}", result.clock);

    if let Some(files) = result.files {
        for file in files.iter() {
            println!("{}", file.name.display());
        }
    } else {
        eprintln!("no file changed since {:?}", clock_spec);
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>msg fix<commit_after><|endoftext|>


<commit_before><commit_msg>tests: Add disabled tuple test<commit_after>//! This test is disable because Tuples are not yet supported.

#[cfg(never)]

#[macro_use] extern crate columnar_derive;
extern crate columnar;

#[cfg(never)]
#[derive(Eq, PartialEq, Debug, Clone, Columnar)]
pub struct Useless(u64, Option<i64>);

#[cfg(never)]
#[test]
fn test() {
    let u = vec![Useless(1, None), Useless(1, Some(-1))];
    let original = u.clone();
    let mut columnar = UselessColumnar::with_capacity(u.len());
    columnar.extend(u.into_iter());
    let result: Vec<_> = columnar.iter().map(|e| UselessRef::to_owned(&e)).collect();
    assert_eq!(original, result);
}

#[cfg(never)]
#[test]
fn test_mul_2() {
    let u = vec![Useless(1, None), Useless(1, Some(-1))];
    let mut original = u.clone();
    for e in original.iter_mut() {
        e.0 *= 2;
    }
    let mut columnar = UselessColumnar::with_capacity(u.len());
    columnar.extend(u.into_iter());
    for e in columnar.iter_mut() {
        *e.0 *= 2;
    }
    let result: Vec<_> = columnar.iter().map(|e| UselessRef::to_owned(&e)).collect();
    assert_eq!(original, result);
}
<|endoftext|>


<commit_before>use {Future, Poll, Task};

pub fn forget<T: Future>(t: T) {
    let thunk = ThunkFuture { inner: t.boxed() }.boxed();
    Task::new().run(thunk)
}

// FIXME(rust-lang/rust#34416) should just be able to use map/map_err, but that
//                             causes trans to go haywire.
struct ThunkFuture<T, E> {
    inner: Box<Future<Item=T, Error=E>>,
}

impl<T: Send + 'static, E: Send + 'static> Future for ThunkFuture<T, E> {
    type Item = ();
    type Error = ();

    fn poll(&mut self, task: &mut Task) -> Poll<(), ()> {
        self.inner.poll(task).map(|_| ()).map_err(|_| ())
    }

    fn schedule(&mut self, task: &mut Task) {
        self.inner.schedule(task)
    }

    fn tailcall(&mut self) -> Option<Box<Future<Item=(), Error=()>>> {
        if let Some(f) = self.inner.tailcall() {
            self.inner = f;
        }
        None
    }
}
<commit_msg>Remove extraneous allocation in forget<commit_after>use {Future, Poll, Task};
use util::Collapsed;

pub fn forget<T: Future>(t: T) {
    let thunk = ThunkFuture { inner: Collapsed::Start(t) }.boxed();
    Task::new().run(thunk)
}

// FIXME(rust-lang/rust#34416) should just be able to use map/map_err, but that
//                             causes trans to go haywire.
struct ThunkFuture<T: Future> {
    inner: Collapsed<T>,
}

impl<T: Future> Future for ThunkFuture<T> {
    type Item = ();
    type Error = ();

    fn poll(&mut self, task: &mut Task) -> Poll<(), ()> {
        self.inner.poll(task).map(|_| ()).map_err(|_| ())
    }

    fn schedule(&mut self, task: &mut Task) {
        self.inner.schedule(task)
    }

    fn tailcall(&mut self) -> Option<Box<Future<Item=(), Error=()>>> {
        self.inner.collapse();
        None
    }
}
<|endoftext|>


<commit_before>use redox::*;

#[derive(Copy, Clone)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset + 1].to_string() +
                &self.string[self.offset + 1 .. self.string.len() - 1];
        }
    }

    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        use self::Mode::*;
                        match (mode, key_event.scancode) {
                            (Insert, K_ESC) => {
                                mode = Normal;
                            },
                            (Insert, K_BKSP) => self.backspace(&mut window),
                            (Insert, K_DEL) => self.delete(&mut window),
                            (_, K_F5) => self.reload(&mut window),
                            (_, K_F6) => self.save(&mut window),
                            (_, K_HOME) => self.offset = 0,
                            (_, K_UP) => self.up(),
                            (_, K_LEFT) => self.left(),
                            (_, K_RIGHT) => self.right(),
                            (_, K_END) => self.offset = self.string.len(),
                            (_, K_DOWN) => self.down(),
                            (m, _) => match (m, key_event.character) {
                                (Normal, 'i') => {
                                    mode = Insert;
                                    last_change = self.string.clone();
                                },
                                (Normal, 'h') => self.left(),
                                (Normal, 'l') => self.right(),
                                (Normal, 'k') => self.up(),
                                (Normal, 'j') => self.down(),
                                (Normal, 'G') => self.offset = self.string.len(),
                                (Normal, 'a') => {
                                    self.right();
                                    mode = Insert;
                                    last_change = self.string.clone();
                                },
                                (Normal, 'x') => self.delete(&mut window),
                                (Normal, 'X') => self.backspace(&mut window),
                                (Normal, 'u') => {
                                    self.offset = 0;
                                    ::core::mem::swap(&mut last_change, &mut self.string);
                                },
                                (Insert, '\0') => (),
                                (Insert, _) => {
                                    window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                    self.string = self.string[0 .. self.offset].to_string() +
                                                  &key_event.character.to_string() +
                                                  &self.string[self.offset .. self.string.len()];
                                    self.offset += 1;
                                },
                                _ => {},
                            }
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<commit_msg>Add numerals (multiple commands at once), s.a. `2j`.<commit_after>use redox::*;

#[derive(Copy, Clone)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset + 1].to_string() +
                &self.string[self.offset + 1 .. self.string.len() - 1];
        }
    }

    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        use self::Mode::*;
                        match (mode, key_event.scancode) {
                            (Insert, K_ESC) => {
                                mode = Normal;
                            },
                            (Insert, K_BKSP) => self.backspace(&mut window),
                            (Insert, K_DEL) => self.delete(&mut window),
                            (_, K_F5) => self.reload(&mut window),
                            (_, K_F6) => self.save(&mut window),
                            (_, K_HOME) => self.offset = 0,
                            (_, K_UP) => self.up(),
                            (_, K_LEFT) => self.left(),
                            (_, K_RIGHT) => self.right(),
                            (_, K_END) => self.offset = self.string.len(),
                            (_, K_DOWN) => self.down(),
                            (m, _) => {
                                let (no_mult, mut times) = match multiplier {
                                    Some(n) => (false, n),
                                    None => (true, 1),
                                };
                                let mut is_none = false;

                                match key_event.character {
                                    '0' if no_mult => times = 0,
                                    '0' => times *= 10,

                                    '1' if no_mult => times = 1,
                                    '1' => times = times * 10 + 1,

                                    '2' if no_mult => times = 2,
                                    '2' => times = times * 10 + 2,

                                    '3' if no_mult => times = 3,
                                    '3' => times = times * 10 + 3,

                                    '4' if no_mult => times = 4,
                                    '4' => times = times * 10 + 4,

                                    '5' if no_mult => times = 5,
                                    '5' => times = times * 10 + 5,

                                    '6' if no_mult => times = 6,
                                    '6' => times = times * 10 + 6,

                                    '7' if no_mult => times = 7,
                                    '7' => times = times * 10 + 7,

                                    '8' if no_mult => times = 8,
                                    '8' => times = times * 10 + 8,

                                    '9' if no_mult => times = 9,
                                    '9' => times = times * 10 + 9,
                                    _ => {
                                        for _ in 0 .. times {
                                            match (m, key_event.character) {
                                                (Normal, 'i') => {
                                                    mode = Insert;
                                                    last_change = self.string.clone();
                                                },
                                                (Normal, 'h') => self.left(),
                                                (Normal, 'l') => self.right(),
                                                (Normal, 'k') => self.up(),
                                                (Normal, 'j') => self.down(),
                                                (Normal, 'G') => self.offset = self.string.len(),
                                                (Normal, 'a') => {
                                                    self.right();
                                                    mode = Insert;
                                                    last_change = self.string.clone();
                                                },
                                                (Normal, 'x') => self.delete(&mut window),
                                                (Normal, 'X') => self.backspace(&mut window),
                                                (Normal, 'u') => {
                                                    self.offset = 0;
                                                    ::core::mem::swap(&mut last_change, &mut self.string);
                                                },
                                                (Insert, '\0') => (),
                                                (Insert, _) => {
                                                    window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                                    self.string = self.string[0 .. self.offset].to_string() +
                                                        &key_event.character.to_string() +
                                                        &self.string[self.offset .. self.string.len()];
                                                    self.offset += 1;
                                                },
                                                _ => {},
                                            }
                                        }
                                        is_none = true;
                                    }
                                }

                                if !is_none {
                                    multiplier = Some(times);
                                } else {
                                    multiplier = None;
                                }

                            }
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before>use redox::*;

#[derive(Copy, Clone)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset + 1].to_string() +
                &self.string[self.offset + 1 .. self.string.len() - 1];
        }
    }

    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        use self::Mode::*;
                        match (mode, key_event.scancode) {
                            (Insert, K_ESC) => {
                                mode = Normal;
                            },
                            (Insert, K_BKSP) => self.backspace(&mut window),
                            (Insert, K_DEL) => self.delete(&mut window),
                            (_, K_F5) => self.reload(&mut window),
                            (_, K_F6) => self.save(&mut window),
                            (_, K_HOME) => self.offset = 0,
                            (_, K_UP) => self.up(),
                            (_, K_LEFT) => self.left(),
                            (_, K_RIGHT) => self.right(),
                            (_, K_END) => self.offset = self.string.len(),
                            (_, K_DOWN) => self.down(),
                            (m, _) => {
                                let (no_mult, mut times) = match multiplier {
                                    Some(n) => (false, n),
                                    None => (true, 1),
                                };
                                let mut is_none = false;

                                match key_event.character {
                                    '0' if no_mult => times = 0,
                                    '0' => times *= 10,

                                    '1' if no_mult => times = 1,
                                    '1' => times = times * 10 + 1,

                                    '2' if no_mult => times = 2,
                                    '2' => times = times * 10 + 2,

                                    '3' if no_mult => times = 3,
                                    '3' => times = times * 10 + 3,

                                    '4' if no_mult => times = 4,
                                    '4' => times = times * 10 + 4,

                                    '5' if no_mult => times = 5,
                                    '5' => times = times * 10 + 5,

                                    '6' if no_mult => times = 6,
                                    '6' => times = times * 10 + 6,

                                    '7' if no_mult => times = 7,
                                    '7' => times = times * 10 + 7,

                                    '8' if no_mult => times = 8,
                                    '8' => times = times * 10 + 8,

                                    '9' if no_mult => times = 9,
                                    '9' => times = times * 10 + 9,
                                    _ => {
                                        for _ in 0 .. times {
                                            match (m, key_event.character) {
                                                (Normal, 'i') => {
                                                    mode = Insert;
                                                    last_change = self.string.clone();
                                                },
                                                (Normal, 'h') => self.left(),
                                                (Normal, 'l') => self.right(),
                                                (Normal, 'k') => self.up(),
                                                (Normal, 'j') => self.down(),
                                                (Normal, 'G') => self.offset = self.string.len(),
                                                (Normal, 'a') => {
                                                    self.right();
                                                    mode = Insert;
                                                    last_change = self.string.clone();
                                                },
                                                (Normal, 'x') => self.delete(&mut window),
                                                (Normal, 'X') => self.backspace(&mut window),
                                                (Normal, 'u') => {
                                                    self.offset = 0;
                                                    ::core::mem::swap(&mut last_change, &mut self.string);
                                                },
                                                (Insert, '\0') => (),
                                                (Insert, _) => {
                                                    window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                                    self.string = self.string[0 .. self.offset].to_string() +
                                                        &key_event.character.to_string() +
                                                        &self.string[self.offset .. self.string.len()];
                                                    self.offset += 1;
                                                },
                                                _ => {},
                                            }
                                        }
                                        is_none = true;
                                    }
                                }

                                if !is_none {
                                    multiplier = Some(times);
                                } else {
                                    multiplier = None;
                                }

                            }
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<commit_msg>Add $ and 0 commands to editor<commit_after>use redox::*;

#[derive(Copy, Clone)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset + 1].to_string() +
                &self.string[self.offset + 1 .. self.string.len() - 1];
        }
    }

    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        use self::Mode::*;
                        match (mode, key_event.scancode) {
                            (Insert, K_ESC) => {
                                mode = Normal;
                            },
                            (Insert, K_BKSP) => self.backspace(&mut window),
                            (Insert, K_DEL) => self.delete(&mut window),
                            (_, K_F5) => self.reload(&mut window),
                            (_, K_F6) => self.save(&mut window),
                            (_, K_HOME) => self.offset = 0,
                            (_, K_UP) => self.up(),
                            (_, K_LEFT) => self.left(),
                            (_, K_RIGHT) => self.right(),
                            (_, K_END) => self.offset = self.string.len(),
                            (_, K_DOWN) => self.down(),
                            (m, _) => {
                                let (no_mult, mut times) = match multiplier {
                                    Some(n) => (false, n),
                                    None => (true, 1),
                                };
                                let mut is_none = false;

                                match key_event.character {
                                    '0' if !no_mult => times *= 10,

                                    '1' if no_mult => times = 1,
                                    '1' => times = times * 10 + 1,

                                    '2' if no_mult => times = 2,
                                    '2' => times = times * 10 + 2,

                                    '3' if no_mult => times = 3,
                                    '3' => times = times * 10 + 3,

                                    '4' if no_mult => times = 4,
                                    '4' => times = times * 10 + 4,

                                    '5' if no_mult => times = 5,
                                    '5' => times = times * 10 + 5,

                                    '6' if no_mult => times = 6,
                                    '6' => times = times * 10 + 6,

                                    '7' if no_mult => times = 7,
                                    '7' => times = times * 10 + 7,

                                    '8' if no_mult => times = 8,
                                    '8' => times = times * 10 + 8,

                                    '9' if no_mult => times = 9,
                                    '9' => times = times * 10 + 9,
                                    _ => {
                                        for _ in 0 .. times {
                                            match (m, key_event.character) {
                                                (Normal, 'i') => {
                                                    mode = Insert;
                                                    last_change = self.string.clone();
                                                },
                                                (Normal, 'h') => self.left(),
                                                (Normal, 'l') => self.right(),
                                                (Normal, 'k') => self.up(),
                                                (Normal, 'j') => self.down(),
                                                (Normal, 'G') => self.offset = self.string.len(),
                                                (Normal, 'a') => {
                                                    self.right();
                                                    mode = Insert;
                                                    last_change = self.string.clone();
                                                },
                                                (Normal, 'x') => self.delete(&mut window),
                                                (Normal, 'X') => self.backspace(&mut window),
                                                (Normal, 'u') => {
                                                    self.offset = 0;
                                                    ::core::mem::swap(&mut last_change, &mut self.string);
                                                },
                                                (Normal, '$') => {
                                                    let mut new_offset = self.string.len();
                                                    for i in self.offset..self.string.len() {
                                                        match self.string.as_bytes()[i] {
                                                            0 => break,
                                                            10 => {
                                                                new_offset = i;
                                                                break;
                                                            }
                                                            _ => (),
                                                        }
                                                    }
                                                    self.offset = new_offset;
                                                },
                                                (Normal, '0') => {

                                                    let mut new_offset = 0;
                                                    for i in 2..self.offset {
                                                        match self.string.as_bytes()[self.offset - i] {
                                                            0 => break,
                                                            10 => {
                                                                new_offset = self.offset - i + 1;
                                                                break;
                                                            }
                                                            _ => (),
                                                        }
                                                    }
                                                    self.offset = new_offset;
                                                },
                                                (Insert, '\0') => (),
                                                (Insert, _) => {
                                                    window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
                                                    self.string = self.string[0 .. self.offset].to_string() +
                                                        &key_event.character.to_string() +
                                                        &self.string[self.offset .. self.string.len()];
                                                    self.offset += 1;
                                                },
                                                _ => {},
                                            }
                                        }
                                        is_none = true;
                                    }
                                }

                                if !is_none {
                                    multiplier = Some(times);
                                } else {
                                    multiplier = None;
                                }

                            }
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before>use super::*;
use redox::*;

/// The state of the editor
pub struct Editor {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: usize,
    /// The y coordinate of the scroll
    pub scroll_y: usize,
    /// The window
    pub window: Window,
    /// The key state
    pub key_state: KeyState,
    /// The status bar
    pub status_bar: StatusBar,
    /// The prompt
    pub prompt: String,
    /// The settings
    pub options: Options,
}

impl Editor {
    /// Create new default state editor
    pub fn new() -> Editor {

        let window = Window::new((rand() % 400 + 50) as isize,
                                 (rand() % 300 + 50) as isize,
                                 700,
                                 500,
                                 &"Sodium").unwrap();

        let mut editor = Editor {
            current_cursor: 0,
            cursors: vec![Cursor::new()],
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
            window: *window,
            key_state: KeyState::new(),
            status_bar: StatusBar::new(),
            prompt: String::new(),
            options: Options::new(),
        };

        editor.text.push_back(VecDeque::new());

        editor.redraw();

        loop {
            let inp = editor.next_inst();
            editor.exec(inp);
            editor.redraw();
            editor.status_bar.mode = editor.cursor().mode.to_string();
        }

        editor
    }

    /// Get a slice of the current line
    pub fn get_ln(&self, n: usize) -> &[char] {
        self.text[n].as_slices().0
    }

    /// Get the leading whitespaces
    pub fn get_indent(&self, n: usize) -> VecDeque<char> {
        let mut ind = VecDeque::new();
        let ln = self.get_ln(n);
        for &c in ln {
            match c {
                '\t' | ' ' => ind.push_back(c),
                _ => break,
            }
        }
        ind
    }
}

<commit_msg>"Fix" bug ;)<commit_after>use super::*;
use redox::*;

/// The state of the editor
pub struct Editor {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: usize,
    /// The y coordinate of the scroll
    pub scroll_y: usize,
    /// The window
    pub window: Window,
    /// The key state
    pub key_state: KeyState,
    /// The status bar
    pub status_bar: StatusBar,
    /// The prompt
    pub prompt: String,
    /// The settings
    pub options: Options,
}

impl Editor {
    /// Create new default state editor
    pub fn new() -> Editor {

        let window = Window::new((rand() % 400 + 50) as isize,
                                 (rand() % 300 + 50) as isize,
                                 700,
                                 500,
                                 &"Sodium").unwrap();

        let mut editor = Editor {
            current_cursor: 0,
            cursors: vec![Cursor::new()],
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
            window: *window,
            key_state: KeyState::new(),
            status_bar: StatusBar::new(),
            prompt: String::new(),
            options: Options::new(),
        };

        editor.text.push_back(VecDeque::new());

        // Temporary hacky solution
        editor.text[0].push_back(' ');

        editor.redraw();

        loop {
            let inp = editor.next_inst();
            editor.exec(inp);
            editor.redraw();
            editor.status_bar.mode = editor.cursor().mode.to_string();
        }

        editor
    }

    /// Get a slice of the current line
    pub fn get_ln(&self, n: usize) -> &[char] {
        self.text[n].as_slices().0
    }

    /// Get the leading whitespaces
    pub fn get_indent(&self, n: usize) -> VecDeque<char> {
        let mut ind = VecDeque::new();
        let ln = self.get_ln(n);
        for &c in ln {
            match c {
                '\t' | ' ' => ind.push_back(c),
                _ => break,
            }
        }
        ind
    }
}

<|endoftext|>


<commit_before><commit_msg>unbreak BTree::fold_with_key<commit_after><|endoftext|>


<commit_before><commit_msg>Extract out writer function.<commit_after><|endoftext|>


<commit_before>// Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use common;
use common::config;

pub struct TestProps {
    // Lines that should be expected, in order, on standard out
    error_patterns: ~[~str],
    // Extra flags to pass to the compiler
    compile_flags: Option<~str>,
    // If present, the name of a file that this test should match when
    // pretty-printed
    pp_exact: Option<Path>,
    // Modules from aux directory that should be compiled
    aux_builds: ~[~str],
    // Environment settings to use during execution
    exec_env: ~[(~str,~str)],
    // Commands to be given to the debugger, when testing debug info
    debugger_cmds: ~[~str],
    // Lines to check if they appear in the expected debugger output
    check_lines: ~[~str],
}

// Load any test directives embedded in the file
pub fn load_props(testfile: &Path) -> TestProps {
    let mut error_patterns = ~[];
    let mut aux_builds = ~[];
    let mut exec_env = ~[];
    let mut compile_flags = None;
    let mut pp_exact = None;
    let mut debugger_cmds = ~[];
    let mut check_lines = ~[];
    for iter_header(testfile) |ln| {
        match parse_error_pattern(ln) {
          Some(ep) => error_patterns.push(ep),
          None => ()
        };

        if compile_flags.is_none() {
            compile_flags = parse_compile_flags(ln);
        }

        if pp_exact.is_none() {
            pp_exact = parse_pp_exact(ln, testfile);
        }

        for parse_aux_build(ln).each |ab| {
            aux_builds.push(*ab);
        }

        for parse_exec_env(ln).each |ee| {
            exec_env.push(*ee);
        }

        match parse_debugger_cmd(ln) {
            Some(dc) => debugger_cmds.push(dc),
            None => ()
        };

        match parse_check_line(ln) {
            Some(cl) => check_lines.push(cl),
            None => ()
        };
    };
    return TestProps {
        error_patterns: error_patterns,
        compile_flags: compile_flags,
        pp_exact: pp_exact,
        aux_builds: aux_builds,
        exec_env: exec_env,
        debugger_cmds: debugger_cmds,
        check_lines: check_lines
    };
}

pub fn is_test_ignored(config: config, testfile: &Path) -> bool {
    for iter_header(testfile) |ln| {
        if parse_name_directive(ln, ~"xfail-test") { return true; }
        if parse_name_directive(ln, xfail_target()) { return true; }
        if config.mode == common::mode_pretty &&
           parse_name_directive(ln, ~"xfail-pretty") { return true; }
    };
    return true;

    fn xfail_target() -> ~str {
        ~"xfail-" + str::from_slice(os::SYSNAME)
    }
}

fn iter_header(testfile: &Path, it: &fn(~str) -> bool) -> bool {
    let rdr = io::file_reader(testfile).get();
    while !rdr.eof() {
        let ln = rdr.read_line();

        // Assume that any directives will be found before the first
        // module or function. This doesn't seem to be an optimization
        // with a warm page cache. Maybe with a cold one.
        if str::starts_with(ln, ~"fn")
            || str::starts_with(ln, ~"mod") {
            return false;
        } else { if !(it(ln)) { return false; } }
    }
    return true;
}

fn parse_error_pattern(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"error-pattern")
}

fn parse_aux_build(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"aux-build")
}

fn parse_compile_flags(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"compile-flags")
}

fn parse_debugger_cmd(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"debugger")
}

fn parse_check_line(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"check")
}

fn parse_exec_env(line: ~str) -> Option<(~str, ~str)> {
    do parse_name_value_directive(line, ~"exec-env").map |nv| {
        // nv is either FOO or FOO=BAR
        let mut strs = ~[];
        for str::each_splitn_char(*nv, '=', 1u) |s| { strs.push(s.to_owned()); }
        match strs.len() {
          1u => (strs[0], ~""),
          2u => (strs[0], strs[1]),
          n => fail!(fmt!("Expected 1 or 2 strings, not %u", n))
        }
    }
}

fn parse_pp_exact(line: ~str, testfile: &Path) -> Option<Path> {
    match parse_name_value_directive(line, ~"pp-exact") {
      Some(s) => Some(Path(s)),
      None => {
        if parse_name_directive(line, ~"pp-exact") {
            Some(testfile.file_path())
        } else {
            None
        }
      }
    }
}

fn parse_name_directive(line: ~str, directive: ~str) -> bool {
    str::contains(line, directive)
}

fn parse_name_value_directive(line: ~str,
                              directive: ~str) -> Option<~str> {
    let keycolon = directive + ~":";
    match str::find_str(line, keycolon) {
        Some(colon) => {
            let value = str::slice(line, colon + str::len(keycolon),
                                   str::len(line)).to_owned();
            debug!("%s: %s", directive,  value);
            Some(value)
        }
        None => None
    }
}
<commit_msg>compiletest: stop ignoring all tests.<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use common;
use common::config;

pub struct TestProps {
    // Lines that should be expected, in order, on standard out
    error_patterns: ~[~str],
    // Extra flags to pass to the compiler
    compile_flags: Option<~str>,
    // If present, the name of a file that this test should match when
    // pretty-printed
    pp_exact: Option<Path>,
    // Modules from aux directory that should be compiled
    aux_builds: ~[~str],
    // Environment settings to use during execution
    exec_env: ~[(~str,~str)],
    // Commands to be given to the debugger, when testing debug info
    debugger_cmds: ~[~str],
    // Lines to check if they appear in the expected debugger output
    check_lines: ~[~str],
}

// Load any test directives embedded in the file
pub fn load_props(testfile: &Path) -> TestProps {
    let mut error_patterns = ~[];
    let mut aux_builds = ~[];
    let mut exec_env = ~[];
    let mut compile_flags = None;
    let mut pp_exact = None;
    let mut debugger_cmds = ~[];
    let mut check_lines = ~[];
    for iter_header(testfile) |ln| {
        match parse_error_pattern(ln) {
          Some(ep) => error_patterns.push(ep),
          None => ()
        };

        if compile_flags.is_none() {
            compile_flags = parse_compile_flags(ln);
        }

        if pp_exact.is_none() {
            pp_exact = parse_pp_exact(ln, testfile);
        }

        for parse_aux_build(ln).each |ab| {
            aux_builds.push(*ab);
        }

        for parse_exec_env(ln).each |ee| {
            exec_env.push(*ee);
        }

        match parse_debugger_cmd(ln) {
            Some(dc) => debugger_cmds.push(dc),
            None => ()
        };

        match parse_check_line(ln) {
            Some(cl) => check_lines.push(cl),
            None => ()
        };
    };
    return TestProps {
        error_patterns: error_patterns,
        compile_flags: compile_flags,
        pp_exact: pp_exact,
        aux_builds: aux_builds,
        exec_env: exec_env,
        debugger_cmds: debugger_cmds,
        check_lines: check_lines
    };
}

pub fn is_test_ignored(config: config, testfile: &Path) -> bool {
    for iter_header(testfile) |ln| {
        if parse_name_directive(ln, ~"xfail-test") { return true; }
        if parse_name_directive(ln, xfail_target()) { return true; }
        if config.mode == common::mode_pretty &&
           parse_name_directive(ln, ~"xfail-pretty") { return true; }
    };
    return false;

    fn xfail_target() -> ~str {
        ~"xfail-" + str::from_slice(os::SYSNAME)
    }
}

fn iter_header(testfile: &Path, it: &fn(~str) -> bool) -> bool {
    let rdr = io::file_reader(testfile).get();
    while !rdr.eof() {
        let ln = rdr.read_line();

        // Assume that any directives will be found before the first
        // module or function. This doesn't seem to be an optimization
        // with a warm page cache. Maybe with a cold one.
        if str::starts_with(ln, ~"fn")
            || str::starts_with(ln, ~"mod") {
            return false;
        } else { if !(it(ln)) { return false; } }
    }
    return true;
}

fn parse_error_pattern(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"error-pattern")
}

fn parse_aux_build(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"aux-build")
}

fn parse_compile_flags(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"compile-flags")
}

fn parse_debugger_cmd(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"debugger")
}

fn parse_check_line(line: ~str) -> Option<~str> {
    parse_name_value_directive(line, ~"check")
}

fn parse_exec_env(line: ~str) -> Option<(~str, ~str)> {
    do parse_name_value_directive(line, ~"exec-env").map |nv| {
        // nv is either FOO or FOO=BAR
        let mut strs = ~[];
        for str::each_splitn_char(*nv, '=', 1u) |s| { strs.push(s.to_owned()); }
        match strs.len() {
          1u => (strs[0], ~""),
          2u => (strs[0], strs[1]),
          n => fail!(fmt!("Expected 1 or 2 strings, not %u", n))
        }
    }
}

fn parse_pp_exact(line: ~str, testfile: &Path) -> Option<Path> {
    match parse_name_value_directive(line, ~"pp-exact") {
      Some(s) => Some(Path(s)),
      None => {
        if parse_name_directive(line, ~"pp-exact") {
            Some(testfile.file_path())
        } else {
            None
        }
      }
    }
}

fn parse_name_directive(line: ~str, directive: ~str) -> bool {
    str::contains(line, directive)
}

fn parse_name_value_directive(line: ~str,
                              directive: ~str) -> Option<~str> {
    let keycolon = directive + ~":";
    match str::find_str(line, keycolon) {
        Some(colon) => {
            let value = str::slice(line, colon + str::len(keycolon),
                                   str::len(line)).to_owned();
            debug!("%s: %s", directive,  value);
            Some(value)
        }
        None => None
    }
}
<|endoftext|>


<commit_before><commit_msg>Move lint note message to correct spot.<commit_after><|endoftext|>


<commit_before><commit_msg>add some more tests<commit_after><|endoftext|>


<commit_before><commit_msg>update move methods<commit_after><|endoftext|>


<commit_before><commit_msg>Added spline.rs.<commit_after>use std::f32::consts;
use std::ops::{Add, Div, Mul, Sub};
use nalgebra::{UnitQuaternion, Vector2, Vector3, Vector4};

/// Time used as sampling type in splines.
pub type Time = f32;

/// A spline control point.
///
/// This type associates a value at a given type. It also contains an interpolation object used to
/// determine how to interpolate values on the segment defined by this key and the next one.
#[derive(Copy, Clone, Debug)]
pub struct Key<T> {
  /// Time at which the `Key` should be reached.
  pub t: Time,
  /// Actual value.
  pub value: T,
  /// Interpolation mode.
  pub interpolation: Interpolation
}

impl<T> Key<T> {
  pub fn new(t: Time, value: T, interpolation: Interpolation) -> Self {
    Key {
      t: t,
      value: value,
      interpolation: interpolation
    }
  }
}

/// Interpolation mode.
#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub enum Interpolation {
  /// Hold a `Key` until the time passes the normalized step threshold, in which case the next
  /// key is used.
  ///
  /// *Note: if you set the threshold to `0.5`, the first key will be used until the time is half
  /// between the two keys; the second key will be in used afterwards. If you set it to `1.0`, the
  /// first key will be kept until the next key.*
  Step(f32),
  /// Linear interpolation between a key and the next one.
  Linear,
  /// Cosine interpolation between a key and the next one.
  Cosine,
  /// Catmull-Rom interpolation.
  CatmullRom
}

/// Spline curve used to provide interpolation between control points (keys).
#[derive(Debug)]
pub struct Spline<T> {
  keys: Vec<Key<T>>,
}

impl<T> Spline<T> {
  pub fn new(mut cps: Vec<Key<T>>) -> Self {
    cps.sort_by(|k0, k1| k0.t.partial_cmp(&k1.t).unwrap());

    Spline {
      keys: cps
    }
  }
}

pub struct SplineIterator<'a, T> where T: 'a {
  anim_param: &'a Spline<T>,
  i: usize
}

impl<'a, T> Iterator for SplineIterator<'a, T> {
  type Item = &'a Key<T>;

  fn next(&mut self) -> Option<Self::Item> {
    let r = self.anim_param.keys.get(self.i);

    if let Some(_) = r {
      self.i += 1;
    }

    r
  }
}

impl<'a, T> IntoIterator for &'a Spline<T> {
  type Item = &'a Key<T>;
  type IntoIter = SplineIterator<'a, T>;

  fn into_iter(self) -> Self::IntoIter {
    SplineIterator {
      anim_param: self,
      i: 0
    }
  }
}

/// Implement this trait if your type is a key you want to sample with.
pub trait Interpolate: Copy {
  /// Linear interpolation.
  fn lerp(a: Self, b: Self, t: Time) -> Self;
  /// Cubic hermite interpolation.
  fn cubic_hermite(_: (Self, Time), a: (Self, Time), b: (Self, Time), _: (Self, Time), t: Time) -> Self {
    Self::lerp(a.0, b.0, t)
  }
}

impl Interpolate for f32 {
  fn lerp(a: Self, b: Self, t: Time) -> Self {
    lerp(a, b, t)
  }

  fn cubic_hermite(x: (Self, Time), a: (Self, Time), b: (Self, Time), y: (Self, Time), t: Time) -> Self {
    cubic_hermite(x, a, b, y, t)
  }
}

impl Interpolate for Vector2<f32> {
  fn lerp(a: Self, b: Self, t: Time) -> Self {
    lerp(a, b, t)
  }

  fn cubic_hermite(x: (Self, Time), a: (Self, Time), b: (Self, Time), y: (Self, Time), t: Time) -> Self {
    cubic_hermite(x, a, b, y, t)
  }
}

impl Interpolate for Vector3<f32> {
  fn lerp(a: Self, b: Self, t: Time) -> Self {
    lerp(a, b, t)
  }

  fn cubic_hermite(x: (Self, Time), a: (Self, Time), b: (Self, Time), y: (Self, Time), t: Time) -> Self {
    cubic_hermite(x, a, b, y, t)
  }
}

impl Interpolate for Vector4<f32> {
  fn lerp(a: Self, b: Self, t: Time) -> Self {
    lerp(a, b, t)
  }

  fn cubic_hermite(x: (Self, Time), a: (Self, Time), b: (Self, Time), y: (Self, Time), t: Time) -> Self {
    cubic_hermite(x, a, b, y, t)
  }
}

impl Interpolate for UnitQuaternion<f32> {
  fn lerp(a: Self, b: Self, t: Time) -> Self {
    a * UnitQuaternion::new(&(UnitQuaternion::new(&a.quaternion().conjugate()) * b).quaternion().powf(t))
  }
}

// Default implementation of Interpolate::lerp.
fn lerp<T>(a: T, b: T, t: Time) -> T where T: Add<Output = T> + Mul<Time, Output = T> {
  a * (1. - t) + b * t
}

// Default implementation of Interpolate::cubic_hermit.

fn cubic_hermite<T>(x: (T, Time), a: (T, Time), b: (T, Time), y: (T, Time), t: Time) -> T
    where T: Copy + Add<Output = T> + Sub<Output = T> + Mul<Time, Output = T> + Div<Time, Output = T> {
  // time stuff
  let t2 = t * t;
  let t3 = t2 * t;
  let two_t3 = 2. * t3;
  let three_t2 = 3. * t2;

  // tangents
  let m0 = (b.0 - x.0) / (b.1 - x.1);
	let m1 = (y.0 - a.0) / (y.1 - a.1);

  a.0 * (two_t3 - three_t2 + 1.) + m0 * (t3 - 2. * t2 + t) + b.0 * (-two_t3 + three_t2) + m1 * (t3 - t2)
}

/// Samplers can sample `Spline` by providing a `Time`. They should be mutable so that they can
/// maintain an internal state for optimization purposes.
#[derive(Default)]
pub struct Sampler {
  /// Playback cursor – gives the lower control point index of the current portion of the curve
  /// we’re sampling at.
  cursor: usize
}

impl Sampler {
  pub fn new() -> Self {
    Sampler {
      cursor: 0
    }
  }

  /// Sample a spline. If `random_sampling` is set, random sampling is generally faster than
  /// continuous sampling. Though, if you use continuous sampling, set `random_sampling` to `false`
	/// for max speed performance.
  pub fn sample<T>(&mut self, t: Time, param: &Spline<T>, random_sampling: bool) -> Option<T>
      where T: Interpolate {
    let i = if random_sampling {
      binary_search_lower_cp(&param.keys, t)
    } else {
      let i = around_search_lower_cp(&param.keys, self.cursor, t);

      // if we’ve found the index, replace the cursor to speed up next searches
      if let Some(cursor) = i {
        self.cursor = cursor;
      }

      i
    };

    let i = match i {
      Some(i) => i,
      None => return None
    };

    let cp0 = &param.keys[i];

    match cp0.interpolation {
      Interpolation::Step(threshold) => {
        let cp1 = &param.keys[i+1];
        Some(if t < threshold { cp0.value } else { cp1.value })
      },
      Interpolation::Linear => {
        let cp1 = &param.keys[i+1];
        let nt = normalize_time(t, cp0, cp1);

        Some(Interpolate::lerp(cp0.value, cp1.value, nt))
      },
      Interpolation::Cosine => {
        let cp1 = &param.keys[i+1];
        let nt = normalize_time(t, cp0, cp1);
        let cos_nt = (1. - f32::cos(nt * consts::PI)) * 0.5;

        Some(Interpolate::lerp(cp0.value, cp1.value, cos_nt))
      },
      Interpolation::CatmullRom => {
        // We need at least four points for Catmull Rom; ensure we have them, otherwise, return
        // None.
        if i == 0 || i >= param.keys.len() - 2 {
          None
        } else {
          let cp1 = &param.keys[i+1];
          let cpm0 = &param.keys[i-1];
          let cpm1 = &param.keys[i+2];
          let nt = normalize_time(t, cp0, cp1);

          Some(Interpolate::cubic_hermite((cpm0.value, cpm0.t), (cp0.value, cp0.t), (cp1.value, cp1.t), (cpm1.value, cpm1.t), nt))
        }
      }
    }
  }
}

// Normalize a time ([0;1]) given two control points.
fn normalize_time<T>(t: Time, cp: &Key<T>, cp1: &Key<T>) -> Time {
  (t - cp.t) / (cp1.t - cp.t)
}

// Find the lower control point corresponding to a given time. Random version.
fn binary_search_lower_cp<T>(cps: &[Key<T>], t: Time) -> Option<usize> {
  let len = cps.len() as i32;
  if len < 2 {
    return None;
  }

  let mut down = 0;
  let mut up = len - 1;

  while down <= up {
    let m = (up + down) / 2;
    if m < 0 || m >= len - 1 {
      return None;
    }

    let cp0 = &cps[m as usize];

    if cp0.t > t {
      up = m-1;
    } else {
      let cp1 = &cps[(m+1) as usize];

      if t >= cp1.t {
        down = m+1;
      } else {
        return Some(m as usize)
      }
    }
  }

  None
}

// Find the lower control point corresponding to a given time. Continuous version. `i` is the last
// known found index.
fn around_search_lower_cp<T>(cps: &[Key<T>], mut i: usize, t: Time) -> Option<usize> {
  let len = cps.len();

  if len < 2 {
    return None;
  }

  loop {
    let cp = &cps[i];
    let cp1 = &cps[i+1];

    if t >= cp1.t {
      if i >= len - 2 {
        return None;
      }

      i += 1;
    } else if t < cp.t {
      if i == 0 {
        return None;
      }

      i -= 1;
    } else {
      break; // found
    }
  }

  Some(i)
}
<|endoftext|>


<commit_before><commit_msg>Add space doc<commit_after><|endoftext|>