<commit_before>use redox::{self, cmp, env, BMPFile, Color};
use redox::collections::BTreeMap;
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::File;
use redox::io::{Read, Seek, SeekFrom};
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileType {
    description: String,
    icon: BMPFile,
}

impl FileType {
    pub fn new(desc: &str, icon: &str) -> FileType {
        FileType { description: desc.to_string(), icon: load_icon(icon) }
    }

}

pub struct FileManager {
    file_types: BTreeMap<String, FileType>,
    files: Vec<String>,
    file_sizes: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut vec: Vec<u8> = Vec::new();
    if let Some(mut file) = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp")) {
        file.read_to_end(&mut vec);
    }
    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            file_types: {
                let mut file_types = BTreeMap::<String, FileType>::new();
                file_types.insert("/".to_string(),
                                  FileType::new("Folder", "inode-directory"));
                file_types.insert("wav".to_string(),
                                  FileType::new("WAV audio", "audio-x-wav"));
                file_types.insert("bin".to_string(),
                                  FileType::new("Executable", "application-x-executable"));
                file_types.insert("bmp".to_string(),
                                  FileType::new("Bitmap Image", "image-x-generic"));
                file_types.insert("rs".to_string(),
                                  FileType::new("Rust source code", "text-x-makefile"));
                file_types.insert("crate".to_string(),
                                  FileType::new("Rust crate", "image-x-makefile"));
                file_types.insert("asm".to_string(),
                                  FileType::new("Assembly source", "text-x-makefile"));
                file_types.insert("list".to_string(),
                                  FileType::new("Disassembly source", "text-x-makefile"));
                file_types.insert("c".to_string(),
                                  FileType::new("C source code", "text-x-makefile"));
                file_types.insert("cpp".to_string(),
                                  FileType::new("C++ source code", "text-x-makefile"));
                file_types.insert("sh".to_string(),
                                  FileType::new("Shell script", "text-x-script"));
                file_types.insert("lua".to_string(),
                                  FileType::new("Lua script", "text-x-script"));
                file_types.insert("txt".to_string(),
                                  FileType::new("plain text document", "text-x-generic"));
                file_types.insert("md".to_string(),
                                  FileType::new("Markdown", "text-x-generic"));
                file_types.insert("REDOX".to_string(),
                                  FileType::new("Redox package", "text-x-generic"));
                file_types.insert(String::new(),
                                  FileType::new("Unknown file", "unknown"));
                file_types
            },
            files: Vec::new(),
            file_sizes: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn load_icon_with(&self, file_name: &str, row: isize, window: &mut Window) {
        if file_name.ends_with('/') {
            window.image(0,
                         32 * row as isize,
                         self.file_types["/"].icon.width(),
                         self.file_types["/"].icon.height(),
                         self.file_types["/"].icon.as_slice());
        } else {
            let pos = file_name.rfind('.').unwrap_or(0) + 1;
            match self.file_types.get(&file_name[pos..]) {
                Some(file_type) => {
                    window.image(0,
                                 32 * row,
                                 file_type.icon.width(),
                                 file_type.icon.height(),
                                 file_type.icon.as_slice());
                }
                None => {
                    window.image(0,
                                 32 * row,
                                 self.file_types[""].icon.width(),
                                 self.file_types[""].icon.height(),
                                 self.file_types[""].icon.as_slice());
                }
            }
        }
    }

    fn get_description(&self, file_name: &str) -> String {
        if file_name.ends_with('/') {
            self.file_types["/"].description.clone()
        } else {
            let pos = file_name.rfind('.').unwrap_or(0) + 1;
            match self.file_types.get(&file_name[pos..]) {
                Some(file_type) => file_type.description.clone(),
                None => self.file_types[""].description.clone(),
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set(Color::WHITE);

        let mut i = 0;
        let mut row = 0;
        let column = {
            let mut tmp = [0, 0];
            for string in self.files.iter() {
                if tmp[0] < string.len() {
                    tmp[0] = string.len();
                }
            }

            tmp[0] += 1;

            for file_size in self.file_sizes.iter() {
                if tmp[1] < file_size.len() {
                    tmp[1] = file_size.len();
                }
            }

            tmp[1] += tmp[0] + 1;
            tmp
        };
        for (file_name, file_size) in self.files.iter().zip(self.file_sizes.iter()) {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, Color::rgba(224, 224, 224, 255));
            }

            self.load_icon_with(&file_name, row as isize, window);

            let mut col = 0;
            for c in file_name.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    Color::BLACK);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column[0];

            for c in file_size.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    Color::BLACK);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column[1];

            for c in self.get_description(file_name).chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    Color::BLACK);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = [48, 48, 48];
        let mut height = 0;
        if let Some(mut file) = File::open(path) {
            let mut list = String::new();
            file.read_to_string(&mut list);

            for entry in list.split('\n') {
                self.files.push(entry.to_string());
                self.file_sizes.push(
                    match File::open(&(path.to_string() + entry)) {
                        Some(mut file) => {
                            // When the entry is a folder
                            if entry.ends_with('/') {
                                let mut string = String::new();
                                file.read_to_string(&mut string);

                                let count = string.split('\n').count();
                                if count == 1 {
                                    "1 entry".to_string()
                                } else {
                                    format!("{} entries", count)
                                }
                            } else {
                                match file.seek(SeekFrom::End(0)) {
                                    Some(size) => {
                                        if size >= 1_000_000_000 {
                                            format!("{:.1} GB", (size as f64)/1_000_000_000.0)
                                        } else if size >= 1_000_000 {
                                            format!("{:.1} MB", (size as f64)/1_000_000.0)
                                        } else if size >= 1_000 {
                                            format!("{:.1} KB", (size as f64)/1_000.0)
                                        } else {
                                            format!("{:.1} bytes", size)
                                        }
                                    }
                                    None => "Failed to seek".to_string()
                                }
                            }
                        },
                        None => "Failed to open".to_string(),
                    }
                );
                // Unwrapping the last file size will not panic since it has
                // been at least pushed once in the vector
                width[0] = cmp::max(width[0], 48 + (entry.len()) * 8);
                width[1] = cmp::max(width[1], 8 + (self.file_sizes.last().unwrap().len()) * 8);
                width[2] = cmp::max(width[2], 8 + (self.get_description(entry).len()) * 8);
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width.iter().sum(),
                                     height,
                                     &path).unwrap();

        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

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

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && self.last_mouse_event.x == mouse_event.x
                            && self.last_mouse_event.y == mouse_event.y {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                if let Some(file) = self.files.get(self.selected as usize) {
                                    File::exec(&(path.to_string() + &file));
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                EventOption::Quit(quit_event) => break,
                _ => (),
            }
        }
    }
}

pub fn main() {
    match env::args().get(1) {
        Some(arg) => FileManager::new().main(arg),
        None => FileManager::new().main("file:///"),
    }
}
<commit_msg>Add more file types, update descriptions, change icons in file manager<commit_after>use redox::{self, cmp, env, BMPFile, Color};
use redox::collections::BTreeMap;
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::File;
use redox::io::{Read, Seek, SeekFrom};
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileType {
    description: String,
    icon: BMPFile,
}

impl FileType {
    pub fn new(desc: &str, icon: &str) -> FileType {
        FileType { description: desc.to_string(), icon: load_icon(icon) }
    }

}

pub struct FileManager {
    file_types: BTreeMap<String, FileType>,
    files: Vec<String>,
    file_sizes: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut vec: Vec<u8> = Vec::new();
    if let Some(mut file) = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp")) {
        file.read_to_end(&mut vec);
    }
    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            file_types: {
                let mut file_types = BTreeMap::<String, FileType>::new();
                file_types.insert("/".to_string(),
                                  FileType::new("Folder", "inode-directory"));
                file_types.insert("wav".to_string(),
                                  FileType::new("WAV audio", "audio-x-wav"));
                file_types.insert("bin".to_string(),
                                  FileType::new("Executable", "application-x-executable"));
                file_types.insert("bmp".to_string(),
                                  FileType::new("Bitmap Image", "image-x-generic"));
                file_types.insert("rs".to_string(),
                                  FileType::new("Rust source code", "text-x-makefile"));
                file_types.insert("crate".to_string(),
                                  FileType::new("Rust crate", "application-x-archive"));
                file_types.insert("rlib".to_string(),
                                  FileType::new("Static Rust library", "application-x-object"));
                file_types.insert("asm".to_string(),
                                  FileType::new("Assembly source", "text-x-makefile"));
                file_types.insert("list".to_string(),
                                  FileType::new("Disassembly source", "text-x-makefile"));
                file_types.insert("c".to_string(),
                                  FileType::new("C source code", "text-x-csrc"));
                file_types.insert("cpp".to_string(),
                                  FileType::new("C++ source code", "text-x-c++src"));
                file_types.insert("h".to_string(),
                                  FileType::new("C header", "text-x-chdr"));
                file_types.insert("sh".to_string(),
                                  FileType::new("Shell script", "text-x-script"));
                file_types.insert("lua".to_string(),
                                  FileType::new("Lua script", "text-x-script"));
                file_types.insert("txt".to_string(),
                                  FileType::new("Plain text document", "text-x-generic"));
                file_types.insert("md".to_string(),
                                  FileType::new("Markdown document", "text-x-generic"));
                file_types.insert("toml".to_string(),
                                  FileType::new("TOML document", "text-x-generic"));
                file_types.insert("json".to_string(),
                                  FileType::new("JSON document", "text-x-generic"));
                file_types.insert("REDOX".to_string(),
                                  FileType::new("Redox package", "text-x-generic"));
                file_types.insert(String::new(),
                                  FileType::new("Unknown file", "unknown"));
                file_types
            },
            files: Vec::new(),
            file_sizes: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn load_icon_with(&self, file_name: &str, row: isize, window: &mut Window) {
        if file_name.ends_with('/') {
            window.image(0,
                         32 * row as isize,
                         self.file_types["/"].icon.width(),
                         self.file_types["/"].icon.height(),
                         self.file_types["/"].icon.as_slice());
        } else {
            let pos = file_name.rfind('.').unwrap_or(0) + 1;
            match self.file_types.get(&file_name[pos..]) {
                Some(file_type) => {
                    window.image(0,
                                 32 * row,
                                 file_type.icon.width(),
                                 file_type.icon.height(),
                                 file_type.icon.as_slice());
                }
                None => {
                    window.image(0,
                                 32 * row,
                                 self.file_types[""].icon.width(),
                                 self.file_types[""].icon.height(),
                                 self.file_types[""].icon.as_slice());
                }
            }
        }
    }

    fn get_description(&self, file_name: &str) -> String {
        if file_name.ends_with('/') {
            self.file_types["/"].description.clone()
        } else {
            let pos = file_name.rfind('.').unwrap_or(0) + 1;
            match self.file_types.get(&file_name[pos..]) {
                Some(file_type) => file_type.description.clone(),
                None => self.file_types[""].description.clone(),
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set(Color::WHITE);

        let mut i = 0;
        let mut row = 0;
        let column = {
            let mut tmp = [0, 0];
            for string in self.files.iter() {
                if tmp[0] < string.len() {
                    tmp[0] = string.len();
                }
            }

            tmp[0] += 1;

            for file_size in self.file_sizes.iter() {
                if tmp[1] < file_size.len() {
                    tmp[1] = file_size.len();
                }
            }

            tmp[1] += tmp[0] + 1;
            tmp
        };
        for (file_name, file_size) in self.files.iter().zip(self.file_sizes.iter()) {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, Color::rgba(224, 224, 224, 255));
            }

            self.load_icon_with(&file_name, row as isize, window);

            let mut col = 0;
            for c in file_name.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    Color::BLACK);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column[0];

            for c in file_size.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    Color::BLACK);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column[1];

            for c in self.get_description(file_name).chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    Color::BLACK);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = [48, 48, 48];
        let mut height = 0;
        if let Some(mut file) = File::open(path) {
            let mut list = String::new();
            file.read_to_string(&mut list);

            for entry in list.split('\n') {
                self.files.push(entry.to_string());
                self.file_sizes.push(
                    match File::open(&(path.to_string() + entry)) {
                        Some(mut file) => {
                            // When the entry is a folder
                            if entry.ends_with('/') {
                                let mut string = String::new();
                                file.read_to_string(&mut string);

                                let count = string.split('\n').count();
                                if count == 1 {
                                    "1 entry".to_string()
                                } else {
                                    format!("{} entries", count)
                                }
                            } else {
                                match file.seek(SeekFrom::End(0)) {
                                    Some(size) => {
                                        if size >= 1_000_000_000 {
                                            format!("{:.1} GB", (size as f64)/1_000_000_000.0)
                                        } else if size >= 1_000_000 {
                                            format!("{:.1} MB", (size as f64)/1_000_000.0)
                                        } else if size >= 1_000 {
                                            format!("{:.1} KB", (size as f64)/1_000.0)
                                        } else {
                                            format!("{:.1} bytes", size)
                                        }
                                    }
                                    None => "Failed to seek".to_string()
                                }
                            }
                        },
                        None => "Failed to open".to_string(),
                    }
                );
                // Unwrapping the last file size will not panic since it has
                // been at least pushed once in the vector
                width[0] = cmp::max(width[0], 48 + (entry.len()) * 8);
                width[1] = cmp::max(width[1], 8 + (self.file_sizes.last().unwrap().len()) * 8);
                width[2] = cmp::max(width[2], 8 + (self.get_description(entry).len()) * 8);
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width.iter().sum(),
                                     height,
                                     &path).unwrap();

        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

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

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && self.last_mouse_event.x == mouse_event.x
                            && self.last_mouse_event.y == mouse_event.y {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                if let Some(file) = self.files.get(self.selected as usize) {
                                    File::exec(&(path.to_string() + &file));
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                EventOption::Quit(quit_event) => break,
                _ => (),
            }
        }
    }
}

pub fn main() {
    match env::args().get(1) {
        Some(arg) => FileManager::new().main(arg),
        None => FileManager::new().main("file:///"),
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for associated constants in the sidebar<commit_after>#![crate_name = "foo"]

pub trait Trait {
    const FOO: u32 = 12;

    fn foo();
}

pub struct Bar;

// @has 'foo/struct.Bar.html'
// @has - '//h3[@class="sidebar-title"]' 'Associated Constants'
// @has - '//div[@class="sidebar-elems"]//div[@class="sidebar-links"]/a' 'FOO'
impl Trait for Bar {
    const FOO: u32 = 1;

    fn foo() {}
}

pub enum Foo {
    A,
}

// @has 'foo/enum.Foo.html'
// @has - '//h3[@class="sidebar-title"]' 'Associated Constants'
// @has - '//div[@class="sidebar-elems"]//div[@class="sidebar-links"]/a' 'FOO'
impl Trait for Foo {
    const FOO: u32 = 1;

    fn foo() {}
}
<|endoftext|>


<commit_before><commit_msg>initial implementation SecretCollection<commit_after>use glib::object::{Wrapper, Ref};
use glib::types::{StaticType, Type};
use ffi;

pub struct SecretCollection(Ref);

impl SecretCollection {

    #[inline]
    fn raw(&self) -> *mut ffi::SecretCollectionFFI {
        self.0.to_glib_none() as *mut ffi::SecretCollectionFFI
    }
}

impl StaticType for SecretCollection {
    fn static_type() -> Type{
        Type::BaseObject
    }
}

impl Wrapper for SecretCollection {
    type GlibType = ffi::SecretCollectionFFI;

    /// Wraps a `Ref`.
    unsafe fn wrap(r: Ref) -> Self{
        SecretCollection(r)
    }

    /// Returns a reference to the inner `Ref`.
    fn as_ref(&self) -> &Ref{
        &self.0
    }
    /// Transforms into the inner `Ref`.
    fn unwrap(self) -> Ref{
        self.0
    }
}
<|endoftext|>


<commit_before><commit_msg>Add staged_columns builder example<commit_after>extern crate ruroonga_command as ruroonga;
use ruroonga::selectable::staged_columns::StagedColumns;
use ruroonga::commandable::Commandable;
use ruroonga::dsl::*;
use ruroonga::types::data_type::DataType;
use ruroonga::types::column_flag_type::ColumnFlagType;

fn staged_columns_to_command() {
    let label = "filtered".to_string();
    let stage = "filtered".to_string();
    let value = "'_id'".to_string();
    let select = select("Items".to_string())
        .filter("price < 1200".to_string())
        .output_columns(vec![("_id".to_string()),
                             ("_key".to_string()),
                             ("price".to_string()),
                             ("filtered".to_string())]);
    let staged_columns = StagedColumns::new(label.clone(),
                                            stage.clone(),
                                            DataType::UInt32,
                                            vec![(ColumnFlagType::Scalar)],
                                            value.clone());
    let builder = (select + staged_columns).to_command();
    println!("staged columns: {}", builder);
}

fn main() {
    staged_columns_to_command();
}
<|endoftext|>


<commit_before>use core::clone::Clone;
use core::cmp::PartialEq;
use core::iter::Iterator;
use core::ops::{Add, Index};
use core::option::Option;
use core::ptr;
use core::slice::SliceExt;
use core::str::StrExt;

use common::debug::*;
use common::memory::*;
use common::vec::*;

/// A trait for types that can be converted to `String`
pub trait ToString {
    /// Convert the type to strings
    fn to_string(&self) -> String;
}

impl ToString for &'static str {
    /// Convert the type to `String`
    fn to_string(&self) -> String {
        String::from_str(self)
    }
}

/// An iterator over unicode characters
pub struct Chars<'a> {
    /// The string iterating over
    string: &'a String,
    /// The offset of the iterator
    offset: usize,
}

impl <'a> Iterator for Chars<'a> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        if self.offset < self.string.len() {
            let ret = Some(self.string[self.offset]);
            self.offset += 1;
            ret
        } else {
            None
        }
    }
}

/// A split
pub struct Split<'a> {
    /// The string being split
    string: &'a String,
    /// The offset of the split
    offset: usize,
    /// The string seperator
    seperator: String,
}

impl <'a> Iterator for Split<'a> {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        if self.offset < self.string.len() {
            let start = self.offset;
            let mut len = 0;
            for i in start..self.string.len() {
                if self.seperator == self.string.substr(i, self.seperator.len()) {
                    self.offset += self.seperator.len();
                    break;
                } else {
                    self.offset += 1;
                    len += 1;
                }
            }
            Some(self.string.substr(start, len))
        } else {
            None
        }
    }
}

/// A set of lines
pub struct Lines<'a> {
    /// The string being split into lines
    string: &'a String,
    /// The underlying split
    split: Split<'a>
}

impl <'a> Iterator for Lines<'a> {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        match self.split.next() {
            Some(string) => if string.ends_with("\r".to_string()) {
                Some(string.substr(0, string.len() - 1))
            } else {
                Some(string)
            },
            None => None
        }
    }
}

/// A heap allocated, owned string.
pub struct String {
    /// The vector of the chars
    pub vec: Vec<char>,
}

impl String {
    /// Create a new empty `String`
    pub fn new() -> Self {
        String { vec: Vec::new() }
    }

    // TODO FromStr trait
    /// Convert a string literal to a `String`
    pub fn from_str(s: &str) -> Self {
        let mut vec: Vec<char> = Vec::new();

        for c in s.chars() {
            vec.push(c);
        }

        String { vec: vec }
    }

    /// Convert a c-style string slice to a String
    pub fn from_c_slice(s: &[u8]) -> Self {
        let mut vec: Vec<char> = Vec::new();

        for b in s {
            let c = *b as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
        }

        String { vec: vec }
    }

    /// Convert a utf8 vector to a string
    // Why &Vec?
    pub fn from_utf8(utf_vec: &Vec<u8>) -> Self {
        let mut vec: Vec<char> = Vec::new();

        //TODO: better UTF support
        for b in utf_vec.iter() {
            let c = *b as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
        }

        String { vec: vec }
    }

    /// Convert a C-style string literal to a `String`
    pub unsafe fn from_c_str(s: *const u8) -> Self {
        let mut vec: Vec<char> = Vec::new();

        let mut i = 0;
        loop {
            let c = ptr::read(s.offset(i)) as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
            i += 1;
        }

        String { vec: vec }
    }

    /// Convert an integer to a String using a given radix
    pub fn from_num_radix(num: usize, radix: usize) -> Self {
        if radix == 0 {
            return String::new();
        }

        let mut vec: Vec<char> = Vec::new();

        let mut digit_num = num;
        loop {
            let mut digit = (digit_num % radix) as u8;
            if digit > 9 {
                digit += 'A' as u8 - 10;
            } else {
                digit += '0' as u8;
            }

            vec.insert(0, digit as char);

            if digit_num < radix {
                break;
            }

            digit_num /= radix;
        }

        String { vec: vec }
    }

    /// Convert a signed integer to a String
    // TODO: Consider using `int` instead of `num`
    pub fn from_num_radix_signed(num: isize, radix: usize) -> Self {
        if num >= 0 {
            String::from_num_radix(num as usize, radix)
        } else {
            "-".to_string() + String::from_num_radix((-num) as usize, radix)
        }
    }

    /// Convert a `char` to a string
    pub fn from_char(c: char) -> Self {
        if c == '\0' {
            return String::new();
        }

        let mut vec: Vec<char> = Vec::new();
        vec.push(c);

        String { vec: vec }
    }

    /// Convert an unsigned integer to a `String` in base 10
    pub fn from_num(num: usize) -> Self {
        String::from_num_radix(num, 10)
    }

    /// Convert a signed int to a `String` in base 10
    pub fn from_num_signed(num: isize) -> Self {
        String::from_num_radix_signed(num, 10)
    }

    /// Get a substring
    // TODO: Consider to use a string slice
    pub fn substr(&self, start: usize, len: usize) -> Self {
        let mut i = start;
        if i > self.len() {
            i = self.len();
        }

        let mut j = i + len;
        if j > self.len() {
            j = self.len();
        }

        let mut vec: Vec<char> = Vec::new();

        for k in i..j {
            vec.push(self[k]);
        }

        String { vec: vec }
    }

    /// Find the index of a substring in a string
    pub fn find(&self, other: Self) -> Option<usize> {
        if self.len() >= other.len() {
            for i in 0..self.len() + 1 - other.len() {
                if self.substr(i, other.len()) == other {
                    return Some(i);
                }
            }
        }
        None
    }

    /// Check if the string starts with a given string
    pub fn starts_with(&self, other: Self) -> bool {
        if self.len() >= other.len() {
            // FIXME: This is inefficient
            self.substr(0, other.len()) == other
        } else {
            false
        }
    }

    /// Check if a string ends with another string
    pub fn ends_with(&self, other: Self) -> bool {
        if self.len() >= other.len() {
            // FIXME: Inefficient
            self.substr(self.len() - other.len(), other.len()) == other
        } else {
            false
        }
    }

    /// Get the length of the string
    pub fn len(&self) -> usize {
        self.vec.len()
    }

    /// Get a iterator over the chars of the string
    pub fn chars(&self) -> Chars {
        Chars {
            string: &self,
            offset: 0,
        }
    }

    /// Get a iterator of the splits of the string (by a seperator)
    pub fn split(&self, seperator: Self) -> Split {
        Split {
            string: &self,
            offset: 0,
            seperator: seperator,
        }
    }

    /// Get a iterator of lines from the string
    pub fn lines(&self) -> Lines {
        Lines {
            string: &self,
            split: self.split("\n".to_string())
        }
    }

    /// Convert the string to UTF-8
    pub fn to_utf8(&self) -> Vec<u8> {
        let mut vec: Vec<u8> = Vec::new();

        for c in self.chars() {
            let u = c as usize;
            if u < 0x80 {
                vec.push(u as u8);
            } else if u < 0x800 {
                vec.push(0b11000000 | ((u >> 6) as u8 & 0b00011111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            } else if u < 0x10000 {
                vec.push(0b11100000 | ((u >> 12) as u8 & 0b00001111));
                vec.push(0b10000000 | ((u >> 6) as u8 & 0b00111111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            } else {
                d("Unhandled to_utf8 code ");
                dh(u);
                dl();
                unsafe {
                    dh(self.vec.as_ptr() as usize);
                }
                d(" ");
                dd(self.vec.len());
                d(" to ");
                unsafe {
                    dh(vec.as_ptr() as usize);
                }
                d(" ");
                dd(vec.len());
                dl();
                break;
            }
        }

        vec
    }

    /// Convert the string to a C-style string
    pub unsafe fn to_c_str(&self) -> *const u8 {
        let length = self.len() + 1;

        let data = alloc(length) as *mut u8;

        for i in 0..self.len() {
            ptr::write(data.offset(i as isize), self[i] as u8);
        }
        ptr::write(data.offset(self.len() as isize), 0);

        data
    }

    /// Parse the string to a integer using a given radix
    pub fn to_num_radix(&self, radix: usize) -> usize {
        if radix == 0 {
            return 0;
        }

        let mut num = 0;
        for c in self.chars() {
            let digit;
            if c >= '0' && c <= '9' {
                digit = c as usize - '0' as usize
            } else if c >= 'A' && c <= 'Z' {
                digit = c as usize - 'A' as usize + 10
            } else if c >= 'a' && c <= 'z' {
                digit = c as usize - 'a' as usize + 10
            } else {
                break;
            }

            if digit >= radix {
                break;
            }

            num *= radix;
            num += digit;
        }

        num
    }

    /// Parse the string as a signed integer using a given radix
    pub fn to_num_radix_signed(&self, radix: usize) -> isize {
        if self[0] == '-' {
            -(self.substr(1, self.len() - 1).to_num_radix(radix) as isize)
        } else {
            self.to_num_radix(radix) as isize
        }
    }

    /// Parse it as a unsigned integer in base 10
    pub fn to_num(&self) -> usize {
        self.to_num_radix(10)
    }

    /// Parse it as a signed integer in base 10
    pub fn to_num_signed(&self) -> isize {
        self.to_num_radix_signed(10)
    }

    /// Debug
    pub fn d(&self) {
        for c in self.chars() {
            dc(c);
        }
    }
}

static NULL_CHAR: char = '\0';

impl Index<usize> for String {
    type Output = char;
    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        match self.vec.get(i) {
            Some(c) => c,
            None => &NULL_CHAR,
        }
    }
}

impl PartialEq for String {
    fn eq(&self, other: &Self) -> bool {
        if self.len() == other.len() {
            for i in 0..self.len() {
                if self[i] != other[i] {
                    return false;
                }
            }

            true
        } else {
            false
        }
    }
}

impl Clone for String {
    fn clone(&self) -> Self {
        self.substr(0, self.len())
    }
}

impl<'a> Add<&'a String> for String {
    type Output = String;
    fn add(mut self, other: &'a Self) -> Self {
        self.vec.push_all(&other.vec);
        self
    }
}

impl<'a> Add<&'a mut String> for String {
    type Output = String;
    fn add(mut self, other: &'a mut Self) -> Self {
        self.vec.push_all(&other.vec);
        self
    }
}

impl Add for String {
    type Output = String;
    fn add(mut self, other: Self) -> Self {
        self.vec.push_all(&other.vec);
        self
    }
}

impl<'a> Add<&'a str> for String {
    type Output = String;
    fn add(self, other: &'a str) -> Self {
        self + String::from_str(other)
    }
}

impl Add<char> for String {
    type Output = String;
    fn add(mut self, other: char) -> Self {
        self.vec.push(other);
        self
    }
}

impl Add<usize> for String {
    type Output = String;
    fn add(self, other: usize) -> Self {
        self + String::from_num(other)
    }
}

impl Add<isize> for String {
    type Output = String;
    fn add(self, other: isize) -> Self {
        self + String::from_num_signed(other)
    }
}

// Slightly modified version of the impl_eq found in the std collections String
// Ideally, we'd compare these as arrays. However, we'd need to flesh out String a bit more
macro_rules! impl_chars_eq {
    ($lhs:ty, $rhs: ty) => {
        impl<'a> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
            #[inline]
            fn ne(&self, other: &$rhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
        }

        impl<'a> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
            #[inline]
            fn ne(&self, other: &$lhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
        }

    }
}

impl_chars_eq! { String, str }
impl_chars_eq! { String, &'a str }
<commit_msg>Removed string field from `Lines`-iterator<commit_after>use core::clone::Clone;
use core::cmp::PartialEq;
use core::iter::Iterator;
use core::ops::{Add, Index};
use core::option::Option;
use core::ptr;
use core::slice::SliceExt;
use core::str::StrExt;

use common::debug::*;
use common::memory::*;
use common::vec::*;

/// A trait for types that can be converted to `String`
pub trait ToString {
    /// Convert the type to strings
    fn to_string(&self) -> String;
}

impl ToString for &'static str {
    /// Convert the type to `String`
    fn to_string(&self) -> String {
        String::from_str(self)
    }
}

/// An iterator over unicode characters
pub struct Chars<'a> {
    /// The string iterating over
    string: &'a String,
    /// The offset of the iterator
    offset: usize,
}

impl <'a> Iterator for Chars<'a> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        if self.offset < self.string.len() {
            let ret = Some(self.string[self.offset]);
            self.offset += 1;
            ret
        } else {
            None
        }
    }
}

/// A split
pub struct Split<'a> {
    /// The string being split
    string: &'a String,
    /// The offset of the split
    offset: usize,
    /// The string seperator
    seperator: String,
}

impl <'a> Iterator for Split<'a> {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        if self.offset < self.string.len() {
            let start = self.offset;
            let mut len = 0;
            for i in start..self.string.len() {
                if self.seperator == self.string.substr(i, self.seperator.len()) {
                    self.offset += self.seperator.len();
                    break;
                } else {
                    self.offset += 1;
                    len += 1;
                }
            }
            Some(self.string.substr(start, len))
        } else {
            None
        }
    }
}

/// A set of lines
pub struct Lines<'a> {
    /// The underlying split
    split: Split<'a>
}

impl <'a> Iterator for Lines<'a> {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        match self.split.next() {
            Some(string) => if string.ends_with("\r".to_string()) {
                Some(string.substr(0, string.len() - 1))
            } else {
                Some(string)
            },
            None => None
        }
    }
}

/// A heap allocated, owned string.
pub struct String {
    /// The vector of the chars
    pub vec: Vec<char>,
}

impl String {
    /// Create a new empty `String`
    pub fn new() -> Self {
        String { vec: Vec::new() }
    }

    // TODO FromStr trait
    /// Convert a string literal to a `String`
    pub fn from_str(s: &str) -> Self {
        let mut vec: Vec<char> = Vec::new();

        for c in s.chars() {
            vec.push(c);
        }

        String { vec: vec }
    }

    /// Convert a c-style string slice to a String
    pub fn from_c_slice(s: &[u8]) -> Self {
        let mut vec: Vec<char> = Vec::new();

        for b in s {
            let c = *b as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
        }

        String { vec: vec }
    }

    /// Convert a utf8 vector to a string
    // Why &Vec?
    pub fn from_utf8(utf_vec: &Vec<u8>) -> Self {
        let mut vec: Vec<char> = Vec::new();

        //TODO: better UTF support
        for b in utf_vec.iter() {
            let c = *b as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
        }

        String { vec: vec }
    }

    /// Convert a C-style string literal to a `String`
    pub unsafe fn from_c_str(s: *const u8) -> Self {
        let mut vec: Vec<char> = Vec::new();

        let mut i = 0;
        loop {
            let c = ptr::read(s.offset(i)) as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
            i += 1;
        }

        String { vec: vec }
    }

    /// Convert an integer to a String using a given radix
    pub fn from_num_radix(num: usize, radix: usize) -> Self {
        if radix == 0 {
            return String::new();
        }

        let mut vec: Vec<char> = Vec::new();

        let mut digit_num = num;
        loop {
            let mut digit = (digit_num % radix) as u8;
            if digit > 9 {
                digit += 'A' as u8 - 10;
            } else {
                digit += '0' as u8;
            }

            vec.insert(0, digit as char);

            if digit_num < radix {
                break;
            }

            digit_num /= radix;
        }

        String { vec: vec }
    }

    /// Convert a signed integer to a String
    // TODO: Consider using `int` instead of `num`
    pub fn from_num_radix_signed(num: isize, radix: usize) -> Self {
        if num >= 0 {
            String::from_num_radix(num as usize, radix)
        } else {
            "-".to_string() + String::from_num_radix((-num) as usize, radix)
        }
    }

    /// Convert a `char` to a string
    pub fn from_char(c: char) -> Self {
        if c == '\0' {
            return String::new();
        }

        let mut vec: Vec<char> = Vec::new();
        vec.push(c);

        String { vec: vec }
    }

    /// Convert an unsigned integer to a `String` in base 10
    pub fn from_num(num: usize) -> Self {
        String::from_num_radix(num, 10)
    }

    /// Convert a signed int to a `String` in base 10
    pub fn from_num_signed(num: isize) -> Self {
        String::from_num_radix_signed(num, 10)
    }

    /// Get a substring
    // TODO: Consider to use a string slice
    pub fn substr(&self, start: usize, len: usize) -> Self {
        let mut i = start;
        if i > self.len() {
            i = self.len();
        }

        let mut j = i + len;
        if j > self.len() {
            j = self.len();
        }

        let mut vec: Vec<char> = Vec::new();

        for k in i..j {
            vec.push(self[k]);
        }

        String { vec: vec }
    }

    /// Find the index of a substring in a string
    pub fn find(&self, other: Self) -> Option<usize> {
        if self.len() >= other.len() {
            for i in 0..self.len() + 1 - other.len() {
                if self.substr(i, other.len()) == other {
                    return Some(i);
                }
            }
        }
        None
    }

    /// Check if the string starts with a given string
    pub fn starts_with(&self, other: Self) -> bool {
        if self.len() >= other.len() {
            // FIXME: This is inefficient
            self.substr(0, other.len()) == other
        } else {
            false
        }
    }

    /// Check if a string ends with another string
    pub fn ends_with(&self, other: Self) -> bool {
        if self.len() >= other.len() {
            // FIXME: Inefficient
            self.substr(self.len() - other.len(), other.len()) == other
        } else {
            false
        }
    }

    /// Get the length of the string
    pub fn len(&self) -> usize {
        self.vec.len()
    }

    /// Get a iterator over the chars of the string
    pub fn chars(&self) -> Chars {
        Chars {
            string: &self,
            offset: 0,
        }
    }

    /// Get a iterator of the splits of the string (by a seperator)
    pub fn split(&self, seperator: Self) -> Split {
        Split {
            string: &self,
            offset: 0,
            seperator: seperator,
        }
    }

    /// Get a iterator of lines from the string
    pub fn lines(&self) -> Lines {
        Lines {
            split: self.split("\n".to_string())
        }
    }

    /// Convert the string to UTF-8
    pub fn to_utf8(&self) -> Vec<u8> {
        let mut vec: Vec<u8> = Vec::new();

        for c in self.chars() {
            let u = c as usize;
            if u < 0x80 {
                vec.push(u as u8);
            } else if u < 0x800 {
                vec.push(0b11000000 | ((u >> 6) as u8 & 0b00011111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            } else if u < 0x10000 {
                vec.push(0b11100000 | ((u >> 12) as u8 & 0b00001111));
                vec.push(0b10000000 | ((u >> 6) as u8 & 0b00111111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            } else {
                d("Unhandled to_utf8 code ");
                dh(u);
                dl();
                unsafe {
                    dh(self.vec.as_ptr() as usize);
                }
                d(" ");
                dd(self.vec.len());
                d(" to ");
                unsafe {
                    dh(vec.as_ptr() as usize);
                }
                d(" ");
                dd(vec.len());
                dl();
                break;
            }
        }

        vec
    }

    /// Convert the string to a C-style string
    pub unsafe fn to_c_str(&self) -> *const u8 {
        let length = self.len() + 1;

        let data = alloc(length) as *mut u8;

        for i in 0..self.len() {
            ptr::write(data.offset(i as isize), self[i] as u8);
        }
        ptr::write(data.offset(self.len() as isize), 0);

        data
    }

    /// Parse the string to a integer using a given radix
    pub fn to_num_radix(&self, radix: usize) -> usize {
        if radix == 0 {
            return 0;
        }

        let mut num = 0;
        for c in self.chars() {
            let digit;
            if c >= '0' && c <= '9' {
                digit = c as usize - '0' as usize
            } else if c >= 'A' && c <= 'Z' {
                digit = c as usize - 'A' as usize + 10
            } else if c >= 'a' && c <= 'z' {
                digit = c as usize - 'a' as usize + 10
            } else {
                break;
            }

            if digit >= radix {
                break;
            }

            num *= radix;
            num += digit;
        }

        num
    }

    /// Parse the string as a signed integer using a given radix
    pub fn to_num_radix_signed(&self, radix: usize) -> isize {
        if self[0] == '-' {
            -(self.substr(1, self.len() - 1).to_num_radix(radix) as isize)
        } else {
            self.to_num_radix(radix) as isize
        }
    }

    /// Parse it as a unsigned integer in base 10
    pub fn to_num(&self) -> usize {
        self.to_num_radix(10)
    }

    /// Parse it as a signed integer in base 10
    pub fn to_num_signed(&self) -> isize {
        self.to_num_radix_signed(10)
    }

    /// Debug
    pub fn d(&self) {
        for c in self.chars() {
            dc(c);
        }
    }
}

static NULL_CHAR: char = '\0';

impl Index<usize> for String {
    type Output = char;
    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        match self.vec.get(i) {
            Some(c) => c,
            None => &NULL_CHAR,
        }
    }
}

impl PartialEq for String {
    fn eq(&self, other: &Self) -> bool {
        if self.len() == other.len() {
            for i in 0..self.len() {
                if self[i] != other[i] {
                    return false;
                }
            }

            true
        } else {
            false
        }
    }
}

impl Clone for String {
    fn clone(&self) -> Self {
        self.substr(0, self.len())
    }
}

impl<'a> Add<&'a String> for String {
    type Output = String;
    fn add(mut self, other: &'a Self) -> Self {
        self.vec.push_all(&other.vec);
        self
    }
}

impl<'a> Add<&'a mut String> for String {
    type Output = String;
    fn add(mut self, other: &'a mut Self) -> Self {
        self.vec.push_all(&other.vec);
        self
    }
}

impl Add for String {
    type Output = String;
    fn add(mut self, other: Self) -> Self {
        self.vec.push_all(&other.vec);
        self
    }
}

impl<'a> Add<&'a str> for String {
    type Output = String;
    fn add(self, other: &'a str) -> Self {
        self + String::from_str(other)
    }
}

impl Add<char> for String {
    type Output = String;
    fn add(mut self, other: char) -> Self {
        self.vec.push(other);
        self
    }
}

impl Add<usize> for String {
    type Output = String;
    fn add(self, other: usize) -> Self {
        self + String::from_num(other)
    }
}

impl Add<isize> for String {
    type Output = String;
    fn add(self, other: isize) -> Self {
        self + String::from_num_signed(other)
    }
}

// Slightly modified version of the impl_eq found in the std collections String
// Ideally, we'd compare these as arrays. However, we'd need to flesh out String a bit more
macro_rules! impl_chars_eq {
    ($lhs:ty, $rhs: ty) => {
        impl<'a> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
            #[inline]
            fn ne(&self, other: &$rhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
        }

        impl<'a> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
            #[inline]
            fn ne(&self, other: &$lhs) -> bool { self.chars().zip(other.chars()).all(|(a,b)| a == b) }
        }

    }
}

impl_chars_eq! { String, str }
impl_chars_eq! { String, &'a str }
<|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/3-chapter/25-code/multiple_phrases/src/lib.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Made types other than Light private.<commit_after><|endoftext|>


<commit_before><commit_msg>add an interesting demo for &mut being unique<commit_after>fn demo_mut_advanced_unique(our: &mut i32) -> i32 {
  unknown_code_1(&*our);

  // This "re-asserts" uniqueness of the reference: After writing, we know
  // our tag is at the top of the stack.
  *our = 5;

  unknown_code_2();

  // We know this will return 5
  *our
}

// Now comes the evil context
use std::ptr;

static mut LEAK: *mut i32 = ptr::null_mut();

fn unknown_code_1(x: &i32) { unsafe {
    LEAK = x as *const _ as *mut _;
} }

fn unknown_code_2() { unsafe {
    *LEAK = 7; //~ ERROR does not exist on the stack
} }

fn main() {
    assert_eq!(demo_mut_advanced_unique(&mut 0), 5);
}
<|endoftext|>


<commit_before><commit_msg>chore: impl middleware mechanismJ<commit_after><|endoftext|>


<commit_before><commit_msg>Default session removal cookie path to '/'.<commit_after><|endoftext|>


<commit_before><commit_msg>add simple integration test<commit_after>extern crate aurelius;
extern crate websocket;
extern crate url;

use websocket::{Client, Message, Receiver};
use url::Url;

use aurelius::Server;

#[test]
fn simple() {
    let mut server = Server::new();
    let sender = server.start();

    let websocket_port = server.websocket_addr().unwrap().port();

    let url = Url::parse(&format!("ws://localhost:{}", websocket_port)).unwrap();

    let request = Client::connect(url).unwrap();
    let response = request.send().unwrap();

    response.validate().unwrap();

    let (_, mut receiver) = response.begin().split();
    sender.send(String::from("Hello, world!")).unwrap();

    let message: Message = receiver.incoming_messages().next().unwrap().unwrap();
    let html: String = String::from_utf8(message.payload.into_owned()).unwrap();
    assert_eq!(html.trim(), String::from("
Hello, world!
"));
}
<|endoftext|>


<commit_before><commit_msg>Logging tweaks.<commit_after><|endoftext|>


<commit_before><commit_msg>diagonal differences<commit_after>//https://www.hackerrank.com/challenges/diagonal-difference

use std::io;
use std::io::prelude::*;

fn main() {
    let stdin = io::stdin();

    let count: usize = stdin.lock().lines()
        .next().unwrap().unwrap()
        .trim().parse().unwrap();

    let mut step = 0;
    let mut sum1 = 0;
    let mut sum2 = 0;

    for line in stdin.lock().lines() {
        let line: String = line.unwrap();
        let v: Vec<&str> = line.trim().split(' ').collect();
        sum1 += v[0 + step].parse::<i64>().unwrap();
        sum2 += v[count - 1 - step].parse::<i64>().unwrap();
        step +=1;
    }

    println!("{}", (sum1 - sum2).abs());
}<|endoftext|>


<commit_before><commit_msg>Removed console output of run<commit_after><|endoftext|>


<commit_before>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use collections::btree_map::BTreeMap as HashMap;  //redox::HashMap;
use redox::*;

#[derive(Clone, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, Hash)]
pub enum Unit {
    /// Single [repeated] instruction
    Inst(u16, char),
    /// Multiple instructions
    Block(u16, Vec<Unit>),
}

#[derive(Clone, Hash)]
/// The state of the editor
pub struct State {
    /// 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: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
}

impl State {
    fn new() -> State {
        State {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
        }
    }
}

/// A command char
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

#[derive(Clone, Hash)]
/// The editor
pub struct Editor<I: Iterator<Item = Unit>> {
    /// The state of the editor
    pub state: State,
    /// The commands
    pub commands: HashMap<Mode,
                          HashMap<CommandChar,
                                  FnMut<(u16, &mut State, &mut I, char)>>>,
}

impl<I: Iterator<Item = Unit>> Editor<I> {
    pub fn new() -> Self {
        let mut commands = HashMap::new();
        commands.insert(Mode::Primitive(PrimitiveMode::Insert), {
            let mut hm = HashMap::new();
            hm.insert(CommandChar::Wildcard, |_, state, iter, c| {
                state.insert(c);
            });
            hm
        });
        Editor {
            state: State::new(),
            commands: commands,
        }
    }

    pub fn exec(&mut self, cmd: &Unit) {
        let mut commands = self.commands.get(self.mode).unwrap();

        match *cmd {
            Unit::Single(n, c) => {
                commands.get(c).call((n, &mut self.state, self.cmd.iter(), c));
            },
            Unit::Block(n, units) => {
                for _ in 1..n {
                    for &i in units {
                        self.exec(i);
                    }
                }
            },
        }
    }
}

#[derive(Clone, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Unit>,
}

#[derive(Clone, Hash)]
/// An iterator over units
pub struct UnitIterator<'a, I: Iterator<Item = char>> {
    /// The iterator over the chars
    char_iter: &'a mut I,
    /// The state
    state: &'a mut State,
}

impl<'a, I: Iterator<Item = char>> Iterator for UnitIterator<'a, I> {
    type Item = Unit;

    fn next(&mut self) -> Unit {
        match self.cursors[self.cursor as usize].mode {
            Mode::Primitive(_) => Unit::Single(1, self.char_iter.next().unwrap()),
            Mode::Command(_) => {
                let mut ch = self.first().unwrap_or('\0');
                let mut n = 1;

                let mut unset = true;
                for c in self.char_iter {
                    n = match c {
                        '0' if n != 0 => n * 10,
                        '1'           => n * 10 + 1,
                        '2'           => n * 10 + 2,
                        '3'           => n * 10 + 3,
                        '4'           => n * 10 + 4,
                        '5'           => n * 10 + 5,
                        '6'           => n * 10 + 6,
                        '7'           => n * 10 + 7,
                        '8'           => n * 10 + 8,
                        '9'           => n * 10 + 9,
                        _             => {
                            ch = c;
                            break;
                        },
                    };

                    if unset {
                        unset = false;
                        n     = 0;
                    }
                }

                if ch == '(' {
                    let mut level = 0;
                    *self = self.take_while(|c| {
                        level = match c {
                            '(' => level + 1,
                            ')' => level - 1,
                            ';' => 0,
                        }
                    }).skip(1).reverse().skip(1).reverse().unit_iter();
                    Unit::Block(n, self.collect())
                } else if let Some(ch) = self.char_iter.next() {
                    Unit::Inst(n, ch)
                }
            }
        }
    }
}

impl<I: Iterator<Item = char>> I {
    /// Create a iterator of the unit given by the chars
    pub fn unit_iter<'a>(&'a self, state: &'a mut State) -> UnitIterator<'a, I> {
        UnitIterator {
            char_iter: &mut *self,
            state: state,
        }
    }
}
<commit_msg>More work on sodium<commit_after>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use redox::*;

/// A temporary, very slow replacement for HashMaps, until redox::collections is finish.
pub struct HashMapTmp<K, V> {
    data: Vec<(K, V)>,
}
impl<K: PartialEq, V> HashMapTmp<K, V> {
    pub fn get(&self, key: &K) -> Option<&V> {
        match self.data.iter().find(|(k, _)| {
            k == *key
        }) {
            Some((k, ref v)) => Some(v),
            None => None
        }
    }
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        match self.data.iter().find(|(k, _)| {
            k == *key
        }) {
            Some((k, ref mut v)) => Some(v),
            None => None
        }
    }
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        let old = self.get_mut(&key);

        match old {
            Some(v) => {
                *v = value;
                Some(*v)
            },
            None => {
                self.data.push((key, value));
                None
            },
        }
    }
}

type Map<K, V> = HashMapTmp<K, V>;

#[derive(Clone, PartialEq, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, PartialEq, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, PartialEq, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, PartialEq, Hash)]
pub enum Unit {
    /// Single [repeated] instruction
    Inst(u16, char),
    /// Multiple instructions
    Block(u16, Vec<Unit>),
}

#[derive(Clone, PartialEq, Hash)]
/// The state of the editor
pub struct State {
    /// 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: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
}

impl State {
    fn new() -> State {
        State {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
        }
    }
}

/// A command char
#[derive(Clone, Copy, Hash, PartialEq)]
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

#[derive(Clone, PartialEq, Hash)]
/// The editor
pub struct Editor<'a, I: Iterator<Item = Unit>> {
    /// The state of the editor
    pub state: State,
    /// The commands
    pub commands: Map<Mode,
                      Map<CommandChar,
                          Box<FnOnce(u16, &'a mut State, &'a mut I, char)>>>,
}

impl<'a, I: Iterator<Item = Unit>> Editor<'a, I> {
    pub fn new() -> Self {
        let mut commands = Map::new();
        commands.insert(Mode::Primitive(PrimitiveMode::Insert), {
            let mut hm = Map::new();
            hm.insert(CommandChar::Wildcard, |_, state, iter, c| {
                state.insert(c);
            });
            hm
        });
        Editor {
            state: State::new(),
            commands: commands,
        }
    }

    pub fn exec(&mut self, cmd: &Unit) {
        let mut commands = self.commands.get(&self.mode).unwrap();

        match *cmd {
            Unit::Inst(n, c) => {
                commands.get(&c).call((n, &mut self.state, self.cmd.iter(), c));
            },
            Unit::Block(n, units) => {
                for _ in 1..n {
                    for &i in units {
                        self.exec(i);
                    }
                }
            },
        }
    }
}

#[derive(Clone, PartialEq, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Unit>,
}

#[derive(Clone, PartialEq, Hash)]
/// An iterator over units
pub struct UnitIterator<'a, I: Iterator<Item = char> + 'a> {
    /// The iterator over the chars
    char_iter: &'a mut I,
    /// The state
    state: &'a mut State,
}

impl<'a, I: Iterator<Item = char>> Iterator for UnitIterator<'a, I> {
    type Item = Unit;

    fn next(&mut self) -> Option<Unit> {
        match self.cursors[self.cursor as usize].mode {
            Mode::Primitive(_) => Unit::Inst(1, match self.char_iter.next() {
                Some(c) => c,
                None => return None,
            }),
            Mode::Command(_) => {
                let mut ch = self.first().unwrap_or('\0');
                let mut n = 1;

                let mut unset = true;
                for c in self.char_iter {
                    n = match c {
                        '0' if n != 0 => n * 10,
                        '1'           => n * 10 + 1,
                        '2'           => n * 10 + 2,
                        '3'           => n * 10 + 3,
                        '4'           => n * 10 + 4,
                        '5'           => n * 10 + 5,
                        '6'           => n * 10 + 6,
                        '7'           => n * 10 + 7,
                        '8'           => n * 10 + 8,
                        '9'           => n * 10 + 9,
                        _             => {
                            ch = c;
                            break;
                        },
                    };

                    if unset {
                        unset = false;
                        n     = 0;
                    }
                }

                if ch == '(' {
                    let mut level = 0;
                    *self = self.take_while(|c| {
                        level = match c {
                            '(' => level + 1,
                            ')' => level - 1,
                            ';' => 0,
                        }
                    }).skip(1).reverse().skip(1).reverse().unit_iter();
                    Some(Unit::Block(n, self.collect()))
                } else if let Some(ch) = self.char_iter.next() {
                    Some(Unit::Inst(n, ch))
                } else {
                    None
                }
            }
        }
    }
}

pub trait ToUnitIterator: Iterator<Item = char> {
    /// Create a iterator of the unit given by the chars
    fn unit_iter<'a>(&'a self, state: &'a mut State) -> UnitIterator<'a, Self>;
}

impl<I: Iterator<Item = char>> ToUnitIterator for I {
    fn unit_iter<'a>(&'a self, state: &'a mut State) -> UnitIterator<'a, I> {
        UnitIterator {
            char_iter: &mut *self,
            state: state,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>added pointer example<commit_after>fn main() {
    let mut x = 5;

    add_one(&mut x);
    println!("add one: {}" , x);

    add_two(&mut x);
    println!("add two: {}" , x);
}

fn add_one(num: &mut i32) { *num += 1; }

fn add_two(num: *mut i32) { unsafe { *num += 2; } }<|endoftext|>


<commit_before><commit_msg>Add txid to transaction trace<commit_after><|endoftext|>