file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
typing.rs
use std::sync::Arc; #[cfg(all(feature = "tokio_compat", not(feature = "tokio")))] use tokio::time::delay_for as sleep; #[cfg(feature = "tokio")] use tokio::time::sleep; use tokio::{ sync::oneshot::{self, error::TryRecvError, Sender}, time::Duration, };
/// It indicates that the current user is currently typing in the channel. /// /// Typing is started by using the [`Typing::start`] method /// and stopped by using the [`Typing::stop`] method. /// Note that on some clients, typing may persist for a few seconds after [`Typing::stop`] is called. /// Typing is also stopped when the struct is dropped. /// /// If a message is sent while typing is triggered, the user will stop typing for a brief period /// of time and then resume again until either [`Typing::stop`] is called or the struct is dropped. /// /// This should rarely be used for bots, although it is a good indicator that a /// long-running command is still being processed. /// /// ## Examples /// /// ```rust,no_run /// # use serenity::{http::{Http, Typing}, Result}; /// # use std::sync::Arc; /// # /// # fn long_process() {} /// # fn main() -> Result<()> { /// # let http = Http::default(); /// // Initiate typing (assuming `http` is bound) /// let typing = Typing::start(Arc::new(http), 7)?; /// /// // Run some long-running process /// long_process(); /// /// // Stop typing /// typing.stop(); /// # /// # Ok(()) /// # } /// ``` /// /// [`Channel`]: crate::model::channel::Channel #[derive(Debug)] pub struct Typing(Sender<()>); impl Typing { /// Starts typing in the specified [`Channel`] for an indefinite period of time. /// /// Returns [`Typing`]. To stop typing, you must call the [`Typing::stop`] method on /// the returned [`Typing`] object or wait for it to be dropped. Note that on some /// clients, typing may persist for a few seconds after stopped. /// /// # Errors /// /// Returns an [`Error::Http`] if there is an error. /// /// [`Channel`]: crate::model::channel::Channel /// [`Error::Http`]: crate::error::Error::Http pub fn start(http: Arc<Http>, channel_id: u64) -> Result<Self> { let (sx, mut rx) = oneshot::channel(); tokio::spawn(async move { loop { match rx.try_recv() { Ok(_) | Err(TryRecvError::Closed) => break, _ => (), } http.broadcast_typing(channel_id).await?; // It is unclear for how long typing persists after this method is called. // It is generally assumed to be 7 or 10 seconds, so we use 7 to be safe. sleep(Duration::from_secs(7)).await; } Result::Ok(()) }); Ok(Self(sx)) } /// Stops typing in [`Channel`]. /// /// This should be used to stop typing after it is started using [`Typing::start`]. /// Typing may persist for a few seconds on some clients after this is called. /// /// [`Channel`]: crate::model::channel::Channel pub fn stop(self) -> Option<()> { self.0.send(()).ok() } }
use crate::{error::Result, http::Http}; /// A struct to start typing in a [`Channel`] for an indefinite period of time. ///
random_line_split
typing.rs
use std::sync::Arc; #[cfg(all(feature = "tokio_compat", not(feature = "tokio")))] use tokio::time::delay_for as sleep; #[cfg(feature = "tokio")] use tokio::time::sleep; use tokio::{ sync::oneshot::{self, error::TryRecvError, Sender}, time::Duration, }; use crate::{error::Result, http::Http}; /// A struct to start typing in a [`Channel`] for an indefinite period of time. /// /// It indicates that the current user is currently typing in the channel. /// /// Typing is started by using the [`Typing::start`] method /// and stopped by using the [`Typing::stop`] method. /// Note that on some clients, typing may persist for a few seconds after [`Typing::stop`] is called. /// Typing is also stopped when the struct is dropped. /// /// If a message is sent while typing is triggered, the user will stop typing for a brief period /// of time and then resume again until either [`Typing::stop`] is called or the struct is dropped. /// /// This should rarely be used for bots, although it is a good indicator that a /// long-running command is still being processed. /// /// ## Examples /// /// ```rust,no_run /// # use serenity::{http::{Http, Typing}, Result}; /// # use std::sync::Arc; /// # /// # fn long_process() {} /// # fn main() -> Result<()> { /// # let http = Http::default(); /// // Initiate typing (assuming `http` is bound) /// let typing = Typing::start(Arc::new(http), 7)?; /// /// // Run some long-running process /// long_process(); /// /// // Stop typing /// typing.stop(); /// # /// # Ok(()) /// # } /// ``` /// /// [`Channel`]: crate::model::channel::Channel #[derive(Debug)] pub struct Typing(Sender<()>); impl Typing { /// Starts typing in the specified [`Channel`] for an indefinite period of time. /// /// Returns [`Typing`]. To stop typing, you must call the [`Typing::stop`] method on /// the returned [`Typing`] object or wait for it to be dropped. Note that on some /// clients, typing may persist for a few seconds after stopped. /// /// # Errors /// /// Returns an [`Error::Http`] if there is an error. /// /// [`Channel`]: crate::model::channel::Channel /// [`Error::Http`]: crate::error::Error::Http pub fn start(http: Arc<Http>, channel_id: u64) -> Result<Self>
Ok(Self(sx)) } /// Stops typing in [`Channel`]. /// /// This should be used to stop typing after it is started using [`Typing::start`]. /// Typing may persist for a few seconds on some clients after this is called. /// /// [`Channel`]: crate::model::channel::Channel pub fn stop(self) -> Option<()> { self.0.send(()).ok() } }
{ let (sx, mut rx) = oneshot::channel(); tokio::spawn(async move { loop { match rx.try_recv() { Ok(_) | Err(TryRecvError::Closed) => break, _ => (), } http.broadcast_typing(channel_id).await?; // It is unclear for how long typing persists after this method is called. // It is generally assumed to be 7 or 10 seconds, so we use 7 to be safe. sleep(Duration::from_secs(7)).await; } Result::Ok(()) });
identifier_body
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cmp; use unicode_width::UnicodeWidthChar as CharWidth; use crate::buffer::Buffer; use crate::caret; use crate::caret::Caret; use crate::screen; #[cfg(not(test))] use crate::screen::Screen; const MIN_VIEW_SIZE: u16 = 1; /* * View handles the presentation of a buffer. * Everything is measured in screen cell coordinates. */ #[derive(Clone, Copy)] pub struct View { scroll_line: usize, scroll_column: usize, size: screen::Size, } impl View { pub fn new() -> View { View { scroll_line: 0, scroll_column: 0, size: screen::Size(MIN_VIEW_SIZE, MIN_VIEW_SIZE), } } pub fn scroll_line(&self) -> usize { self.scroll_line } pub fn scroll_column(&self) -> usize { self.scroll_column } // assumes caret is in view pub fn caret_position(&self, caret: Caret, buffer: &Buffer) -> screen::Cell { let caret_row = (caret.line() - self.scroll_line) as u16; let caret_column = caret::buffer_to_screen_column(caret.line(), caret.column(), buffer) - self.scroll_column; screen::Cell(caret_row, caret_column as u16) } pub fn set_scroll(&mut self, line: usize, column: usize) { self.scroll_line = line; self.scroll_column = column; } pub fn scroll_into_view(&mut self, caret: Caret, buffer: &Buffer) { let (line, column) = (caret.line(), caret.column()); let screen::Size(rows, cols) = self.size; let rows = rows as usize; let cols = cols as usize; self.scroll_line = if line < self.scroll_line { line } else if line >= self.scroll_line + rows { line - rows + 1 } else { self.scroll_line }; // make sure wider characters are scrolled in entirely as well let start = caret::buffer_to_screen_column(line, column, buffer); let end = start + buffer .get_char_by_line_column(line, column) .and_then(CharWidth::width) .unwrap_or(1) - 1; self.scroll_column = if start < self.scroll_column { start } else if end >= self.scroll_column + cols { end - cols + 1 } else { self.scroll_column }; } pub fn line_clamped_to_view(&self, line: usize) -> usize { let screen::Size(rows, _) = self.size; assert!(rows >= MIN_VIEW_SIZE); let last_line = self.scroll_line + rows as usize - 1; cmp::min(cmp::max(line, self.scroll_line), last_line) } pub fn set_size(&mut self, size: screen::Size) { let screen::Size(rows, cols) = size; assert!(rows >= MIN_VIEW_SIZE && cols >= MIN_VIEW_SIZE); self.size = size; } #[cfg(not(test))] pub fn draw( &self, buffer: &Buffer, caret: Caret, focused: bool, position: screen::Cell, screen: &mut Screen, ) { // calculate caret screen position if focused let caret_cell = if focused {
else { None }; // helper to put a character on the screen let put = |character, cell: screen::Cell, screen: &mut Screen| { use screen::Color::*; let highlight = caret_cell.map(|c| c!= cell).unwrap_or(false); let (fg, bg) = if highlight { (Black, White) } else { (White, Black) }; screen.put(cell, character, fg, bg); }; let screen::Size(rows, cols) = self.size; // draw line by line let mut row: u16 = 0; for chars in buffer .line_iter() .from(self.scroll_line) .take(rows as usize) { let line_offset = screen::Cell(row, 0) + position; // draw character by character let mut col = -(self.scroll_column as isize); for character in chars { if col >= cols as isize || character == '\n' { break; } let char_width = CharWidth::width(character).unwrap_or(0) as isize; let end_col = col + char_width; if (col < 0 && end_col >= 0) || end_col > cols as isize { // blank out partially visible characters for col in cmp::max(0, col)..cmp::min(end_col, cols as isize) { put(' ', line_offset + screen::Cell(0, col as u16), screen); } } else if col >= 0 { put(character, line_offset + screen::Cell(0, col as u16), screen); } col += char_width; } // blank out the rest of the row if the line didn't fill it for col in cmp::max(0, col) as u16..cols { put(' ', line_offset + screen::Cell(0, col), screen); } row += 1; } // fill in the rest of the view below the buffer content for row in row..rows { let line_offset = screen::Cell(row, 0) + position; put( if self.scroll_column == 0 { '~' } else {'' }, line_offset, screen, ); for col in 1..cols { put(' ', line_offset + screen::Cell(0, col), screen); } } } } #[cfg(test)] mod test { use std::path::Path; use crate::buffer::Buffer; use crate::caret::Caret; use super::*; #[test] fn scroll_into_view_double_width() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/scroll_into_view_double_width.txt")).unwrap(); let mut view = View::new(); view.set_size(screen::Size(1, 15)); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 0); caret.adjust(caret::Adjustment::Set(0, 12), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 3); caret.adjust(caret::Adjustment::Set(0, 16), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 9); caret.adjust(caret::Adjustment::Set(0, 3), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 6); caret.adjust(caret::Adjustment::Set(3, 10), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 3); assert_eq!(view.scroll_column(), 6); } #[test] fn caret_position() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/caret_position.txt")).unwrap(); let mut view = View::new(); view.set_scroll(1, 1); caret.adjust(caret::Adjustment::Set(1, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(0, 1)); caret.adjust(caret::Adjustment::Set(2, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(1, 0)); } #[test] fn line_clamped_to_view() { let mut view = View::new(); view.set_size(screen::Size(5, 5)); view.set_scroll(5, 5); assert_eq!(view.line_clamped_to_view(1), 5); assert_eq!(view.line_clamped_to_view(7), 7); assert_eq!(view.line_clamped_to_view(10), 9); } }
Some(position + self.caret_position(caret, buffer)) }
conditional_block
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cmp; use unicode_width::UnicodeWidthChar as CharWidth; use crate::buffer::Buffer; use crate::caret; use crate::caret::Caret; use crate::screen; #[cfg(not(test))] use crate::screen::Screen; const MIN_VIEW_SIZE: u16 = 1; /* * View handles the presentation of a buffer. * Everything is measured in screen cell coordinates. */ #[derive(Clone, Copy)] pub struct View { scroll_line: usize, scroll_column: usize, size: screen::Size, } impl View { pub fn new() -> View { View { scroll_line: 0, scroll_column: 0, size: screen::Size(MIN_VIEW_SIZE, MIN_VIEW_SIZE), } } pub fn scroll_line(&self) -> usize { self.scroll_line } pub fn scroll_column(&self) -> usize { self.scroll_column } // assumes caret is in view pub fn caret_position(&self, caret: Caret, buffer: &Buffer) -> screen::Cell { let caret_row = (caret.line() - self.scroll_line) as u16; let caret_column = caret::buffer_to_screen_column(caret.line(), caret.column(), buffer) - self.scroll_column; screen::Cell(caret_row, caret_column as u16) } pub fn set_scroll(&mut self, line: usize, column: usize) { self.scroll_line = line;
let (line, column) = (caret.line(), caret.column()); let screen::Size(rows, cols) = self.size; let rows = rows as usize; let cols = cols as usize; self.scroll_line = if line < self.scroll_line { line } else if line >= self.scroll_line + rows { line - rows + 1 } else { self.scroll_line }; // make sure wider characters are scrolled in entirely as well let start = caret::buffer_to_screen_column(line, column, buffer); let end = start + buffer .get_char_by_line_column(line, column) .and_then(CharWidth::width) .unwrap_or(1) - 1; self.scroll_column = if start < self.scroll_column { start } else if end >= self.scroll_column + cols { end - cols + 1 } else { self.scroll_column }; } pub fn line_clamped_to_view(&self, line: usize) -> usize { let screen::Size(rows, _) = self.size; assert!(rows >= MIN_VIEW_SIZE); let last_line = self.scroll_line + rows as usize - 1; cmp::min(cmp::max(line, self.scroll_line), last_line) } pub fn set_size(&mut self, size: screen::Size) { let screen::Size(rows, cols) = size; assert!(rows >= MIN_VIEW_SIZE && cols >= MIN_VIEW_SIZE); self.size = size; } #[cfg(not(test))] pub fn draw( &self, buffer: &Buffer, caret: Caret, focused: bool, position: screen::Cell, screen: &mut Screen, ) { // calculate caret screen position if focused let caret_cell = if focused { Some(position + self.caret_position(caret, buffer)) } else { None }; // helper to put a character on the screen let put = |character, cell: screen::Cell, screen: &mut Screen| { use screen::Color::*; let highlight = caret_cell.map(|c| c!= cell).unwrap_or(false); let (fg, bg) = if highlight { (Black, White) } else { (White, Black) }; screen.put(cell, character, fg, bg); }; let screen::Size(rows, cols) = self.size; // draw line by line let mut row: u16 = 0; for chars in buffer .line_iter() .from(self.scroll_line) .take(rows as usize) { let line_offset = screen::Cell(row, 0) + position; // draw character by character let mut col = -(self.scroll_column as isize); for character in chars { if col >= cols as isize || character == '\n' { break; } let char_width = CharWidth::width(character).unwrap_or(0) as isize; let end_col = col + char_width; if (col < 0 && end_col >= 0) || end_col > cols as isize { // blank out partially visible characters for col in cmp::max(0, col)..cmp::min(end_col, cols as isize) { put(' ', line_offset + screen::Cell(0, col as u16), screen); } } else if col >= 0 { put(character, line_offset + screen::Cell(0, col as u16), screen); } col += char_width; } // blank out the rest of the row if the line didn't fill it for col in cmp::max(0, col) as u16..cols { put(' ', line_offset + screen::Cell(0, col), screen); } row += 1; } // fill in the rest of the view below the buffer content for row in row..rows { let line_offset = screen::Cell(row, 0) + position; put( if self.scroll_column == 0 { '~' } else {'' }, line_offset, screen, ); for col in 1..cols { put(' ', line_offset + screen::Cell(0, col), screen); } } } } #[cfg(test)] mod test { use std::path::Path; use crate::buffer::Buffer; use crate::caret::Caret; use super::*; #[test] fn scroll_into_view_double_width() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/scroll_into_view_double_width.txt")).unwrap(); let mut view = View::new(); view.set_size(screen::Size(1, 15)); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 0); caret.adjust(caret::Adjustment::Set(0, 12), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 3); caret.adjust(caret::Adjustment::Set(0, 16), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 9); caret.adjust(caret::Adjustment::Set(0, 3), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 6); caret.adjust(caret::Adjustment::Set(3, 10), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 3); assert_eq!(view.scroll_column(), 6); } #[test] fn caret_position() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/caret_position.txt")).unwrap(); let mut view = View::new(); view.set_scroll(1, 1); caret.adjust(caret::Adjustment::Set(1, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(0, 1)); caret.adjust(caret::Adjustment::Set(2, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(1, 0)); } #[test] fn line_clamped_to_view() { let mut view = View::new(); view.set_size(screen::Size(5, 5)); view.set_scroll(5, 5); assert_eq!(view.line_clamped_to_view(1), 5); assert_eq!(view.line_clamped_to_view(7), 7); assert_eq!(view.line_clamped_to_view(10), 9); } }
self.scroll_column = column; } pub fn scroll_into_view(&mut self, caret: Caret, buffer: &Buffer) {
random_line_split
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cmp; use unicode_width::UnicodeWidthChar as CharWidth; use crate::buffer::Buffer; use crate::caret; use crate::caret::Caret; use crate::screen; #[cfg(not(test))] use crate::screen::Screen; const MIN_VIEW_SIZE: u16 = 1; /* * View handles the presentation of a buffer. * Everything is measured in screen cell coordinates. */ #[derive(Clone, Copy)] pub struct View { scroll_line: usize, scroll_column: usize, size: screen::Size, } impl View { pub fn n
) -> View { View { scroll_line: 0, scroll_column: 0, size: screen::Size(MIN_VIEW_SIZE, MIN_VIEW_SIZE), } } pub fn scroll_line(&self) -> usize { self.scroll_line } pub fn scroll_column(&self) -> usize { self.scroll_column } // assumes caret is in view pub fn caret_position(&self, caret: Caret, buffer: &Buffer) -> screen::Cell { let caret_row = (caret.line() - self.scroll_line) as u16; let caret_column = caret::buffer_to_screen_column(caret.line(), caret.column(), buffer) - self.scroll_column; screen::Cell(caret_row, caret_column as u16) } pub fn set_scroll(&mut self, line: usize, column: usize) { self.scroll_line = line; self.scroll_column = column; } pub fn scroll_into_view(&mut self, caret: Caret, buffer: &Buffer) { let (line, column) = (caret.line(), caret.column()); let screen::Size(rows, cols) = self.size; let rows = rows as usize; let cols = cols as usize; self.scroll_line = if line < self.scroll_line { line } else if line >= self.scroll_line + rows { line - rows + 1 } else { self.scroll_line }; // make sure wider characters are scrolled in entirely as well let start = caret::buffer_to_screen_column(line, column, buffer); let end = start + buffer .get_char_by_line_column(line, column) .and_then(CharWidth::width) .unwrap_or(1) - 1; self.scroll_column = if start < self.scroll_column { start } else if end >= self.scroll_column + cols { end - cols + 1 } else { self.scroll_column }; } pub fn line_clamped_to_view(&self, line: usize) -> usize { let screen::Size(rows, _) = self.size; assert!(rows >= MIN_VIEW_SIZE); let last_line = self.scroll_line + rows as usize - 1; cmp::min(cmp::max(line, self.scroll_line), last_line) } pub fn set_size(&mut self, size: screen::Size) { let screen::Size(rows, cols) = size; assert!(rows >= MIN_VIEW_SIZE && cols >= MIN_VIEW_SIZE); self.size = size; } #[cfg(not(test))] pub fn draw( &self, buffer: &Buffer, caret: Caret, focused: bool, position: screen::Cell, screen: &mut Screen, ) { // calculate caret screen position if focused let caret_cell = if focused { Some(position + self.caret_position(caret, buffer)) } else { None }; // helper to put a character on the screen let put = |character, cell: screen::Cell, screen: &mut Screen| { use screen::Color::*; let highlight = caret_cell.map(|c| c!= cell).unwrap_or(false); let (fg, bg) = if highlight { (Black, White) } else { (White, Black) }; screen.put(cell, character, fg, bg); }; let screen::Size(rows, cols) = self.size; // draw line by line let mut row: u16 = 0; for chars in buffer .line_iter() .from(self.scroll_line) .take(rows as usize) { let line_offset = screen::Cell(row, 0) + position; // draw character by character let mut col = -(self.scroll_column as isize); for character in chars { if col >= cols as isize || character == '\n' { break; } let char_width = CharWidth::width(character).unwrap_or(0) as isize; let end_col = col + char_width; if (col < 0 && end_col >= 0) || end_col > cols as isize { // blank out partially visible characters for col in cmp::max(0, col)..cmp::min(end_col, cols as isize) { put(' ', line_offset + screen::Cell(0, col as u16), screen); } } else if col >= 0 { put(character, line_offset + screen::Cell(0, col as u16), screen); } col += char_width; } // blank out the rest of the row if the line didn't fill it for col in cmp::max(0, col) as u16..cols { put(' ', line_offset + screen::Cell(0, col), screen); } row += 1; } // fill in the rest of the view below the buffer content for row in row..rows { let line_offset = screen::Cell(row, 0) + position; put( if self.scroll_column == 0 { '~' } else {'' }, line_offset, screen, ); for col in 1..cols { put(' ', line_offset + screen::Cell(0, col), screen); } } } } #[cfg(test)] mod test { use std::path::Path; use crate::buffer::Buffer; use crate::caret::Caret; use super::*; #[test] fn scroll_into_view_double_width() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/scroll_into_view_double_width.txt")).unwrap(); let mut view = View::new(); view.set_size(screen::Size(1, 15)); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 0); caret.adjust(caret::Adjustment::Set(0, 12), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 3); caret.adjust(caret::Adjustment::Set(0, 16), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 9); caret.adjust(caret::Adjustment::Set(0, 3), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 6); caret.adjust(caret::Adjustment::Set(3, 10), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 3); assert_eq!(view.scroll_column(), 6); } #[test] fn caret_position() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/caret_position.txt")).unwrap(); let mut view = View::new(); view.set_scroll(1, 1); caret.adjust(caret::Adjustment::Set(1, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(0, 1)); caret.adjust(caret::Adjustment::Set(2, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(1, 0)); } #[test] fn line_clamped_to_view() { let mut view = View::new(); view.set_size(screen::Size(5, 5)); view.set_scroll(5, 5); assert_eq!(view.line_clamped_to_view(1), 5); assert_eq!(view.line_clamped_to_view(7), 7); assert_eq!(view.line_clamped_to_view(10), 9); } }
ew(
identifier_name
view.rs
/* * Copyright (c) 2015-2021 Mathias Hällman * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cmp; use unicode_width::UnicodeWidthChar as CharWidth; use crate::buffer::Buffer; use crate::caret; use crate::caret::Caret; use crate::screen; #[cfg(not(test))] use crate::screen::Screen; const MIN_VIEW_SIZE: u16 = 1; /* * View handles the presentation of a buffer. * Everything is measured in screen cell coordinates. */ #[derive(Clone, Copy)] pub struct View { scroll_line: usize, scroll_column: usize, size: screen::Size, } impl View { pub fn new() -> View { View { scroll_line: 0, scroll_column: 0, size: screen::Size(MIN_VIEW_SIZE, MIN_VIEW_SIZE), } } pub fn scroll_line(&self) -> usize { self.scroll_line } pub fn scroll_column(&self) -> usize { self.scroll_column } // assumes caret is in view pub fn caret_position(&self, caret: Caret, buffer: &Buffer) -> screen::Cell { let caret_row = (caret.line() - self.scroll_line) as u16; let caret_column = caret::buffer_to_screen_column(caret.line(), caret.column(), buffer) - self.scroll_column; screen::Cell(caret_row, caret_column as u16) } pub fn set_scroll(&mut self, line: usize, column: usize) { self.scroll_line = line; self.scroll_column = column; } pub fn scroll_into_view(&mut self, caret: Caret, buffer: &Buffer) { let (line, column) = (caret.line(), caret.column()); let screen::Size(rows, cols) = self.size; let rows = rows as usize; let cols = cols as usize; self.scroll_line = if line < self.scroll_line { line } else if line >= self.scroll_line + rows { line - rows + 1 } else { self.scroll_line }; // make sure wider characters are scrolled in entirely as well let start = caret::buffer_to_screen_column(line, column, buffer); let end = start + buffer .get_char_by_line_column(line, column) .and_then(CharWidth::width) .unwrap_or(1) - 1; self.scroll_column = if start < self.scroll_column { start } else if end >= self.scroll_column + cols { end - cols + 1 } else { self.scroll_column }; } pub fn line_clamped_to_view(&self, line: usize) -> usize { let screen::Size(rows, _) = self.size; assert!(rows >= MIN_VIEW_SIZE); let last_line = self.scroll_line + rows as usize - 1; cmp::min(cmp::max(line, self.scroll_line), last_line) } pub fn set_size(&mut self, size: screen::Size) { let screen::Size(rows, cols) = size; assert!(rows >= MIN_VIEW_SIZE && cols >= MIN_VIEW_SIZE); self.size = size; } #[cfg(not(test))] pub fn draw( &self, buffer: &Buffer, caret: Caret, focused: bool, position: screen::Cell, screen: &mut Screen, ) {
let screen::Size(rows, cols) = self.size; // draw line by line let mut row: u16 = 0; for chars in buffer .line_iter() .from(self.scroll_line) .take(rows as usize) { let line_offset = screen::Cell(row, 0) + position; // draw character by character let mut col = -(self.scroll_column as isize); for character in chars { if col >= cols as isize || character == '\n' { break; } let char_width = CharWidth::width(character).unwrap_or(0) as isize; let end_col = col + char_width; if (col < 0 && end_col >= 0) || end_col > cols as isize { // blank out partially visible characters for col in cmp::max(0, col)..cmp::min(end_col, cols as isize) { put(' ', line_offset + screen::Cell(0, col as u16), screen); } } else if col >= 0 { put(character, line_offset + screen::Cell(0, col as u16), screen); } col += char_width; } // blank out the rest of the row if the line didn't fill it for col in cmp::max(0, col) as u16..cols { put(' ', line_offset + screen::Cell(0, col), screen); } row += 1; } // fill in the rest of the view below the buffer content for row in row..rows { let line_offset = screen::Cell(row, 0) + position; put( if self.scroll_column == 0 { '~' } else {'' }, line_offset, screen, ); for col in 1..cols { put(' ', line_offset + screen::Cell(0, col), screen); } } } } #[cfg(test)] mod test { use std::path::Path; use crate::buffer::Buffer; use crate::caret::Caret; use super::*; #[test] fn scroll_into_view_double_width() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/scroll_into_view_double_width.txt")).unwrap(); let mut view = View::new(); view.set_size(screen::Size(1, 15)); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 0); caret.adjust(caret::Adjustment::Set(0, 12), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 3); caret.adjust(caret::Adjustment::Set(0, 16), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 9); caret.adjust(caret::Adjustment::Set(0, 3), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 0); assert_eq!(view.scroll_column(), 6); caret.adjust(caret::Adjustment::Set(3, 10), &buffer); view.scroll_into_view(caret, &buffer); assert_eq!(view.scroll_line(), 3); assert_eq!(view.scroll_column(), 6); } #[test] fn caret_position() { let mut caret = Caret::new(); let buffer = Buffer::open(&Path::new("tests/view/caret_position.txt")).unwrap(); let mut view = View::new(); view.set_scroll(1, 1); caret.adjust(caret::Adjustment::Set(1, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(0, 1)); caret.adjust(caret::Adjustment::Set(2, 1), &buffer); assert_eq!(view.caret_position(caret, &buffer), screen::Cell(1, 0)); } #[test] fn line_clamped_to_view() { let mut view = View::new(); view.set_size(screen::Size(5, 5)); view.set_scroll(5, 5); assert_eq!(view.line_clamped_to_view(1), 5); assert_eq!(view.line_clamped_to_view(7), 7); assert_eq!(view.line_clamped_to_view(10), 9); } }
// calculate caret screen position if focused let caret_cell = if focused { Some(position + self.caret_position(caret, buffer)) } else { None }; // helper to put a character on the screen let put = |character, cell: screen::Cell, screen: &mut Screen| { use screen::Color::*; let highlight = caret_cell.map(|c| c != cell).unwrap_or(false); let (fg, bg) = if highlight { (Black, White) } else { (White, Black) }; screen.put(cell, character, fg, bg); };
identifier_body
callables.rs
use std::fmt; use std::convert::TryInto; use std::collections::{HashMap}; use std::iter::FromIterator; use chainstate::stacks::events::StacksTransactionEvent; use vm::costs::{cost_functions, SimpleCostSpecification}; use vm::errors::{InterpreterResult as Result, Error, check_argument_count}; use vm::analysis::errors::CheckErrors; use vm::representations::{SymbolicExpression, ClarityName}; use vm::types::{TypeSignature, QualifiedContractIdentifier, TraitIdentifier, PrincipalData, FunctionType}; use vm::{eval, Value, LocalContext, Environment}; use vm::contexts::ContractContext; pub enum CallableType { UserFunction(DefinedFunction), NativeFunction(&'static str, NativeHandle, SimpleCostSpecification), SpecialFunction(&'static str, &'static dyn Fn(&[SymbolicExpression], &mut Environment, &LocalContext) -> Result<Value>) } #[derive(Clone, Serialize, Deserialize, PartialEq)] pub enum DefineType { ReadOnly, Public, Private } #[derive(Clone,Serialize, Deserialize)] pub struct DefinedFunction { identifier: FunctionIdentifier, name: ClarityName, arg_types: Vec<TypeSignature>, pub define_type: DefineType, arguments: Vec<ClarityName>, body: SymbolicExpression } pub enum NativeHandle { SingleArg(&'static dyn Fn(Value) -> Result<Value>), DoubleArg(&'static dyn Fn(Value, Value) -> Result<Value>), MoreArg(&'static dyn Fn(Vec<Value>) -> Result<Value>) } impl NativeHandle { pub fn apply(&self, mut args: Vec<Value>) -> Result<Value> { match self { NativeHandle::SingleArg(function) => { check_argument_count(1, &args)?; function(args.pop().unwrap()) }, NativeHandle::DoubleArg(function) => { check_argument_count(2, &args)?; let second = args.pop().unwrap(); let first = args.pop().unwrap(); function(first, second) }, NativeHandle::MoreArg(function) => { function(args) } } } } #[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)] pub struct FunctionIdentifier { identifier: String } impl fmt::Display for FunctionIdentifier { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.identifier) } } impl DefinedFunction { pub fn new(mut arguments: Vec<(ClarityName, TypeSignature)>, body: SymbolicExpression, define_type: DefineType, name: &ClarityName, context_name: &str) -> DefinedFunction { let (argument_names, types) = arguments.drain(..).unzip(); DefinedFunction { identifier: FunctionIdentifier::new_user_function(name, context_name), name: name.clone(), arguments: argument_names, define_type, body, arg_types: types } } pub fn execute_apply(&self, args: &[Value], env: &mut Environment) -> Result<Value> { runtime_cost!(cost_functions::USER_FUNCTION_APPLICATION, env, self.arguments.len())?; for arg_type in self.arg_types.iter() { runtime_cost!(cost_functions::TYPE_CHECK_COST, env, arg_type)?; } let mut context = LocalContext::new(); if args.len()!= self.arguments.len() { Err(CheckErrors::IncorrectArgumentCount(self.arguments.len(), args.len()))? } let mut arg_iterator: Vec<_> = self.arguments.iter().zip(self.arg_types.iter()).zip(args.iter()).collect(); for arg in arg_iterator.drain(..) { let ((name, type_sig), value) = arg; match (type_sig, value) { (TypeSignature::TraitReferenceType(trait_identifier), Value::Principal(PrincipalData::Contract(callee_contract_id))) => { // Argument is a trait reference, probably leading to a dynamic contract call // We keep a reference of the mapping (var-name: (callee_contract_id, trait_id)) in the context. // The code fetching and checking the trait is implemented in the contract_call eval function. context.callable_contracts.insert(name.clone(), (callee_contract_id.clone(), trait_identifier.clone())); }, _ => {
if let Some(_) = context.variables.insert(name.clone(), value.clone()) { return Err(CheckErrors::NameAlreadyUsed(name.to_string()).into()) } } } } let result = eval(&self.body, env, &context); // if the error wasn't actually an error, but a function return, // pull that out and return it. match result { Ok(r) => Ok(r), Err(e) => { match e { Error::ShortReturn(v) => Ok(v.into()), _ => Err(e) } } } } pub fn check_trait_expectations(&self, contract_defining_trait: &ContractContext, trait_identifier: &TraitIdentifier) -> Result<()> { let trait_name = trait_identifier.name.to_string(); let constraining_trait = contract_defining_trait.lookup_trait_definition(&trait_name) .ok_or(CheckErrors::TraitReferenceUnknown(trait_name.to_string()))?; let expected_sig = constraining_trait.get(&self.name) .ok_or(CheckErrors::TraitMethodUnknown(trait_name.to_string(), self.name.to_string()))?; let args = self.arg_types.iter().map(|a| a.clone()).collect(); if!expected_sig.check_args_trait_compliance(args) { return Err(CheckErrors::BadTraitImplementation(trait_name.clone(), self.name.to_string()).into()) } Ok(()) } pub fn is_read_only(&self) -> bool { self.define_type == DefineType::ReadOnly } pub fn apply(&self, args: &[Value], env: &mut Environment) -> Result<Value> { match self.define_type { DefineType::Private => self.execute_apply(args, env), DefineType::Public => env.execute_function_as_transaction(self, args, None), DefineType::ReadOnly => env.execute_function_as_transaction(self, args, None) } } pub fn is_public(&self) -> bool { match self.define_type { DefineType::Public => true, DefineType::Private => false, DefineType::ReadOnly => true } } pub fn get_identifier(&self) -> FunctionIdentifier { self.identifier.clone() } } impl CallableType { pub fn get_identifier(&self) -> FunctionIdentifier { match self { CallableType::UserFunction(f) => f.get_identifier(), CallableType::NativeFunction(s, _, _) => FunctionIdentifier::new_native_function(s), CallableType::SpecialFunction(s, _) => FunctionIdentifier::new_native_function(s), } } } impl FunctionIdentifier { fn new_native_function(name: &str) -> FunctionIdentifier { let identifier = format!("_native_:{}", name); FunctionIdentifier { identifier: identifier } } fn new_user_function(name: &str, context: &str) -> FunctionIdentifier { let identifier = format!("{}:{}", context, name); FunctionIdentifier { identifier: identifier } } }
if !type_sig.admits(value) { return Err(CheckErrors::TypeValueError(type_sig.clone(), value.clone()).into()) }
random_line_split
callables.rs
use std::fmt; use std::convert::TryInto; use std::collections::{HashMap}; use std::iter::FromIterator; use chainstate::stacks::events::StacksTransactionEvent; use vm::costs::{cost_functions, SimpleCostSpecification}; use vm::errors::{InterpreterResult as Result, Error, check_argument_count}; use vm::analysis::errors::CheckErrors; use vm::representations::{SymbolicExpression, ClarityName}; use vm::types::{TypeSignature, QualifiedContractIdentifier, TraitIdentifier, PrincipalData, FunctionType}; use vm::{eval, Value, LocalContext, Environment}; use vm::contexts::ContractContext; pub enum CallableType { UserFunction(DefinedFunction), NativeFunction(&'static str, NativeHandle, SimpleCostSpecification), SpecialFunction(&'static str, &'static dyn Fn(&[SymbolicExpression], &mut Environment, &LocalContext) -> Result<Value>) } #[derive(Clone, Serialize, Deserialize, PartialEq)] pub enum DefineType { ReadOnly, Public, Private } #[derive(Clone,Serialize, Deserialize)] pub struct DefinedFunction { identifier: FunctionIdentifier, name: ClarityName, arg_types: Vec<TypeSignature>, pub define_type: DefineType, arguments: Vec<ClarityName>, body: SymbolicExpression } pub enum
{ SingleArg(&'static dyn Fn(Value) -> Result<Value>), DoubleArg(&'static dyn Fn(Value, Value) -> Result<Value>), MoreArg(&'static dyn Fn(Vec<Value>) -> Result<Value>) } impl NativeHandle { pub fn apply(&self, mut args: Vec<Value>) -> Result<Value> { match self { NativeHandle::SingleArg(function) => { check_argument_count(1, &args)?; function(args.pop().unwrap()) }, NativeHandle::DoubleArg(function) => { check_argument_count(2, &args)?; let second = args.pop().unwrap(); let first = args.pop().unwrap(); function(first, second) }, NativeHandle::MoreArg(function) => { function(args) } } } } #[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)] pub struct FunctionIdentifier { identifier: String } impl fmt::Display for FunctionIdentifier { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.identifier) } } impl DefinedFunction { pub fn new(mut arguments: Vec<(ClarityName, TypeSignature)>, body: SymbolicExpression, define_type: DefineType, name: &ClarityName, context_name: &str) -> DefinedFunction { let (argument_names, types) = arguments.drain(..).unzip(); DefinedFunction { identifier: FunctionIdentifier::new_user_function(name, context_name), name: name.clone(), arguments: argument_names, define_type, body, arg_types: types } } pub fn execute_apply(&self, args: &[Value], env: &mut Environment) -> Result<Value> { runtime_cost!(cost_functions::USER_FUNCTION_APPLICATION, env, self.arguments.len())?; for arg_type in self.arg_types.iter() { runtime_cost!(cost_functions::TYPE_CHECK_COST, env, arg_type)?; } let mut context = LocalContext::new(); if args.len()!= self.arguments.len() { Err(CheckErrors::IncorrectArgumentCount(self.arguments.len(), args.len()))? } let mut arg_iterator: Vec<_> = self.arguments.iter().zip(self.arg_types.iter()).zip(args.iter()).collect(); for arg in arg_iterator.drain(..) { let ((name, type_sig), value) = arg; match (type_sig, value) { (TypeSignature::TraitReferenceType(trait_identifier), Value::Principal(PrincipalData::Contract(callee_contract_id))) => { // Argument is a trait reference, probably leading to a dynamic contract call // We keep a reference of the mapping (var-name: (callee_contract_id, trait_id)) in the context. // The code fetching and checking the trait is implemented in the contract_call eval function. context.callable_contracts.insert(name.clone(), (callee_contract_id.clone(), trait_identifier.clone())); }, _ => { if!type_sig.admits(value) { return Err(CheckErrors::TypeValueError(type_sig.clone(), value.clone()).into()) } if let Some(_) = context.variables.insert(name.clone(), value.clone()) { return Err(CheckErrors::NameAlreadyUsed(name.to_string()).into()) } } } } let result = eval(&self.body, env, &context); // if the error wasn't actually an error, but a function return, // pull that out and return it. match result { Ok(r) => Ok(r), Err(e) => { match e { Error::ShortReturn(v) => Ok(v.into()), _ => Err(e) } } } } pub fn check_trait_expectations(&self, contract_defining_trait: &ContractContext, trait_identifier: &TraitIdentifier) -> Result<()> { let trait_name = trait_identifier.name.to_string(); let constraining_trait = contract_defining_trait.lookup_trait_definition(&trait_name) .ok_or(CheckErrors::TraitReferenceUnknown(trait_name.to_string()))?; let expected_sig = constraining_trait.get(&self.name) .ok_or(CheckErrors::TraitMethodUnknown(trait_name.to_string(), self.name.to_string()))?; let args = self.arg_types.iter().map(|a| a.clone()).collect(); if!expected_sig.check_args_trait_compliance(args) { return Err(CheckErrors::BadTraitImplementation(trait_name.clone(), self.name.to_string()).into()) } Ok(()) } pub fn is_read_only(&self) -> bool { self.define_type == DefineType::ReadOnly } pub fn apply(&self, args: &[Value], env: &mut Environment) -> Result<Value> { match self.define_type { DefineType::Private => self.execute_apply(args, env), DefineType::Public => env.execute_function_as_transaction(self, args, None), DefineType::ReadOnly => env.execute_function_as_transaction(self, args, None) } } pub fn is_public(&self) -> bool { match self.define_type { DefineType::Public => true, DefineType::Private => false, DefineType::ReadOnly => true } } pub fn get_identifier(&self) -> FunctionIdentifier { self.identifier.clone() } } impl CallableType { pub fn get_identifier(&self) -> FunctionIdentifier { match self { CallableType::UserFunction(f) => f.get_identifier(), CallableType::NativeFunction(s, _, _) => FunctionIdentifier::new_native_function(s), CallableType::SpecialFunction(s, _) => FunctionIdentifier::new_native_function(s), } } } impl FunctionIdentifier { fn new_native_function(name: &str) -> FunctionIdentifier { let identifier = format!("_native_:{}", name); FunctionIdentifier { identifier: identifier } } fn new_user_function(name: &str, context: &str) -> FunctionIdentifier { let identifier = format!("{}:{}", context, name); FunctionIdentifier { identifier: identifier } } }
NativeHandle
identifier_name
layout_interface.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to layout. Using this abstract //! interface helps reduce coupling between these two components, and enables //! the DOM to be placed in a separate crate from layout. use dom::node::LayoutData; use euclid::point::Point2D; use euclid::rect::Rect; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use libc::uintptr_t; use msg::compositor_msg::LayerId; use msg::constellation_msg::{ConstellationChan, Failure, PipelineExitType, PipelineId}; use msg::constellation_msg::{WindowSizeData}; use msg::compositor_msg::Epoch; use net_traits::image_cache_task::ImageCacheTask; use net_traits::PendingAsyncLoad; use profile_traits::mem::ReportsChan; use script_traits::{ConstellationControlMsg, LayoutControlMsg}; use script_traits::{OpaqueScriptLayoutChannel, StylesheetLoadResponder, UntrustedNodeAddress}; use selectors::parser::PseudoElement; use std::any::Any; use std::sync::mpsc::{channel, Receiver, Sender}; use string_cache::Atom; use style::animation::PropertyAnimation; use style::media_queries::MediaQueryList; use style::stylesheets::Stylesheet; use url::Url; use util::geometry::Au; pub use dom::node::TrustedNodeAddress; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. AddStylesheet(Stylesheet, MediaQueryList), /// Adds the given stylesheet to the document. LoadStylesheet(Url, MediaQueryList, PendingAsyncLoad, Box<StylesheetLoadResponder+Send>), /// Puts a document into quirks mode, causing the quirks mode stylesheet to be loaded. SetQuirksMode, /// Requests a reflow. Reflow(Box<ScriptReflow>), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout task render the next frame of all animations. TickAnimations, /// Updates the layout visible rects, affecting the area that display lists will be constructed /// for. SetVisibleRects(Vec<(LayerId, Rect<Au>)>), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapLayoutData(LayoutData), /// Requests that the layout task measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout task enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout task immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow(PipelineExitType), /// Get the last epoch counter for this layout task. GetCurrentEpoch(IpcSender<Epoch>), /// Creates a new layout task. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutTask(NewLayoutTaskInfo), } /// Synchronous messages that script can send to layout. /// /// In general, you should use messages to talk to Layout. Use the RPC interface /// if and only if the work is /// /// 1) read-only with respect to LayoutTaskData, /// 2) small, /// 3) and really needs to be fast. pub trait LayoutRPC { /// Requests the dimensions of the content box, as in the `getBoundingClientRect()` call. fn content_box(&self) -> ContentBoxResponse; /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call. fn content_boxes(&self) -> ContentBoxesResponse; /// Requests the geometry of this node. Used by APIs such as `clientTop`. fn node_geometry(&self) -> NodeGeometryResponse; /// Requests the node containing the point of interest fn hit_test(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<HitTestResponse, ()>; fn mouse_over(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<MouseOverResponse, ()>; /// Query layout for the resolved value of a given CSS property fn resolved_style(&self) -> ResolvedStyleResponse; fn offset_parent(&self) -> OffsetParentResponse; } pub struct ContentBoxResponse(pub Rect<Au>); pub struct ContentBoxesResponse(pub Vec<Rect<Au>>); pub struct NodeGeometryResponse { pub client_rect: Rect<i32>, } pub struct HitTestResponse(pub UntrustedNodeAddress); pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>); pub struct ResolvedStyleResponse(pub Option<String>); #[derive(Clone)] pub struct OffsetParentResponse { pub node_address: Option<UntrustedNodeAddress>, pub rect: Rect<Au>, } impl OffsetParentResponse { pub fn empty() -> OffsetParentResponse { OffsetParentResponse { node_address: None, rect: Rect::zero(), } } } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, } /// Any query to perform with this reflow. #[derive(PartialEq)] pub enum ReflowQueryType { NoQuery, ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, Atom), OffsetParentQuery(TrustedNodeAddress), } /// Information needed for a reflow. pub struct Reflow { /// The goal of reflow: either to render to the screen or to flush layout info for script. pub goal: ReflowGoal, /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document_root: TrustedNodeAddress, /// The channel through which messages can be sent back to the script task. pub script_chan: Sender<ConstellationControlMsg>, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<()>, /// Unique identifier pub id: u32, /// The type of query if any to perform during this reflow. pub query_type: ReflowQueryType, } /// Encapsulates a channel to the layout task. #[derive(Clone)] pub struct LayoutChan(pub Sender<Msg>); impl LayoutChan { pub fn new() -> (Receiver<Msg>, LayoutChan) { let (chan, port) = channel(); (port, LayoutChan(chan)) } } /// A trait to manage opaque references to script<->layout channels without needing /// to expose the message type to crates that don't need to know about them. pub trait ScriptLayoutChan { fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> Self; fn sender(&self) -> Sender<Msg>; fn receiver(self) -> Receiver<Msg>; } impl ScriptLayoutChan for OpaqueScriptLayoutChannel { fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> OpaqueScriptLayoutChannel { let inner = (box sender as Box<Any+Send>, box receiver as Box<Any+Send>); OpaqueScriptLayoutChannel(inner) } fn sender(&self) -> Sender<Msg> { let &OpaqueScriptLayoutChannel((ref sender, _)) = self; (*sender.downcast_ref::<Sender<Msg>>().unwrap()).clone() } fn receiver(self) -> Receiver<Msg> { let OpaqueScriptLayoutChannel((_, receiver)) = self; *receiver.downcast::<Receiver<Msg>>().unwrap() } } /// Type of an opaque node. pub type OpaqueNode = uintptr_t; /// State relating to an animation. #[derive(Clone)] pub struct
{ /// An opaque reference to the DOM node participating in the animation. pub node: OpaqueNode, /// A description of the property animation that is occurring. pub property_animation: PropertyAnimation, /// The start time of the animation, as returned by `time::precise_time_s()`. pub start_time: f64, /// The end time of the animation, as returned by `time::precise_time_s()`. pub end_time: f64, } impl Animation { /// Returns the duration of this animation in seconds. #[inline] pub fn duration(&self) -> f64 { self.end_time - self.start_time } } pub struct NewLayoutTaskInfo { pub id: PipelineId, pub url: Url, pub is_parent: bool, pub layout_pair: OpaqueScriptLayoutChannel, pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: ConstellationChan, pub failure: Failure, pub script_chan: Sender<ConstellationControlMsg>, pub image_cache_task: ImageCacheTask, pub paint_chan: Box<Any + Send>, pub layout_shutdown_chan: Sender<()>, }
Animation
identifier_name
layout_interface.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to layout. Using this abstract //! interface helps reduce coupling between these two components, and enables //! the DOM to be placed in a separate crate from layout. use dom::node::LayoutData; use euclid::point::Point2D; use euclid::rect::Rect; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use libc::uintptr_t; use msg::compositor_msg::LayerId; use msg::constellation_msg::{ConstellationChan, Failure, PipelineExitType, PipelineId}; use msg::constellation_msg::{WindowSizeData}; use msg::compositor_msg::Epoch; use net_traits::image_cache_task::ImageCacheTask; use net_traits::PendingAsyncLoad; use profile_traits::mem::ReportsChan; use script_traits::{ConstellationControlMsg, LayoutControlMsg}; use script_traits::{OpaqueScriptLayoutChannel, StylesheetLoadResponder, UntrustedNodeAddress}; use selectors::parser::PseudoElement; use std::any::Any; use std::sync::mpsc::{channel, Receiver, Sender}; use string_cache::Atom; use style::animation::PropertyAnimation; use style::media_queries::MediaQueryList; use style::stylesheets::Stylesheet; use url::Url; use util::geometry::Au; pub use dom::node::TrustedNodeAddress; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. AddStylesheet(Stylesheet, MediaQueryList), /// Adds the given stylesheet to the document. LoadStylesheet(Url, MediaQueryList, PendingAsyncLoad, Box<StylesheetLoadResponder+Send>), /// Puts a document into quirks mode, causing the quirks mode stylesheet to be loaded. SetQuirksMode, /// Requests a reflow. Reflow(Box<ScriptReflow>), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout task render the next frame of all animations. TickAnimations, /// Updates the layout visible rects, affecting the area that display lists will be constructed /// for. SetVisibleRects(Vec<(LayerId, Rect<Au>)>), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapLayoutData(LayoutData), /// Requests that the layout task measure its memory usage. The resulting reports are sent back /// via the supplied channel.
CollectReports(ReportsChan), /// Requests that the layout task enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout task immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow(PipelineExitType), /// Get the last epoch counter for this layout task. GetCurrentEpoch(IpcSender<Epoch>), /// Creates a new layout task. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutTask(NewLayoutTaskInfo), } /// Synchronous messages that script can send to layout. /// /// In general, you should use messages to talk to Layout. Use the RPC interface /// if and only if the work is /// /// 1) read-only with respect to LayoutTaskData, /// 2) small, /// 3) and really needs to be fast. pub trait LayoutRPC { /// Requests the dimensions of the content box, as in the `getBoundingClientRect()` call. fn content_box(&self) -> ContentBoxResponse; /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call. fn content_boxes(&self) -> ContentBoxesResponse; /// Requests the geometry of this node. Used by APIs such as `clientTop`. fn node_geometry(&self) -> NodeGeometryResponse; /// Requests the node containing the point of interest fn hit_test(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<HitTestResponse, ()>; fn mouse_over(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<MouseOverResponse, ()>; /// Query layout for the resolved value of a given CSS property fn resolved_style(&self) -> ResolvedStyleResponse; fn offset_parent(&self) -> OffsetParentResponse; } pub struct ContentBoxResponse(pub Rect<Au>); pub struct ContentBoxesResponse(pub Vec<Rect<Au>>); pub struct NodeGeometryResponse { pub client_rect: Rect<i32>, } pub struct HitTestResponse(pub UntrustedNodeAddress); pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>); pub struct ResolvedStyleResponse(pub Option<String>); #[derive(Clone)] pub struct OffsetParentResponse { pub node_address: Option<UntrustedNodeAddress>, pub rect: Rect<Au>, } impl OffsetParentResponse { pub fn empty() -> OffsetParentResponse { OffsetParentResponse { node_address: None, rect: Rect::zero(), } } } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, } /// Any query to perform with this reflow. #[derive(PartialEq)] pub enum ReflowQueryType { NoQuery, ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, Atom), OffsetParentQuery(TrustedNodeAddress), } /// Information needed for a reflow. pub struct Reflow { /// The goal of reflow: either to render to the screen or to flush layout info for script. pub goal: ReflowGoal, /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document_root: TrustedNodeAddress, /// The channel through which messages can be sent back to the script task. pub script_chan: Sender<ConstellationControlMsg>, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<()>, /// Unique identifier pub id: u32, /// The type of query if any to perform during this reflow. pub query_type: ReflowQueryType, } /// Encapsulates a channel to the layout task. #[derive(Clone)] pub struct LayoutChan(pub Sender<Msg>); impl LayoutChan { pub fn new() -> (Receiver<Msg>, LayoutChan) { let (chan, port) = channel(); (port, LayoutChan(chan)) } } /// A trait to manage opaque references to script<->layout channels without needing /// to expose the message type to crates that don't need to know about them. pub trait ScriptLayoutChan { fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> Self; fn sender(&self) -> Sender<Msg>; fn receiver(self) -> Receiver<Msg>; } impl ScriptLayoutChan for OpaqueScriptLayoutChannel { fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> OpaqueScriptLayoutChannel { let inner = (box sender as Box<Any+Send>, box receiver as Box<Any+Send>); OpaqueScriptLayoutChannel(inner) } fn sender(&self) -> Sender<Msg> { let &OpaqueScriptLayoutChannel((ref sender, _)) = self; (*sender.downcast_ref::<Sender<Msg>>().unwrap()).clone() } fn receiver(self) -> Receiver<Msg> { let OpaqueScriptLayoutChannel((_, receiver)) = self; *receiver.downcast::<Receiver<Msg>>().unwrap() } } /// Type of an opaque node. pub type OpaqueNode = uintptr_t; /// State relating to an animation. #[derive(Clone)] pub struct Animation { /// An opaque reference to the DOM node participating in the animation. pub node: OpaqueNode, /// A description of the property animation that is occurring. pub property_animation: PropertyAnimation, /// The start time of the animation, as returned by `time::precise_time_s()`. pub start_time: f64, /// The end time of the animation, as returned by `time::precise_time_s()`. pub end_time: f64, } impl Animation { /// Returns the duration of this animation in seconds. #[inline] pub fn duration(&self) -> f64 { self.end_time - self.start_time } } pub struct NewLayoutTaskInfo { pub id: PipelineId, pub url: Url, pub is_parent: bool, pub layout_pair: OpaqueScriptLayoutChannel, pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: ConstellationChan, pub failure: Failure, pub script_chan: Sender<ConstellationControlMsg>, pub image_cache_task: ImageCacheTask, pub paint_chan: Box<Any + Send>, pub layout_shutdown_chan: Sender<()>, }
random_line_split
posterize.rs
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ip.rsh" #pragma rs_fp_relaxed
rs_allocation inputImage; float intensityLow = 0.f; float intensityHigh; uchar4 color; const static float3 mono = {0.299f, 0.587f, 0.114f}; void setParams(float intensHigh, float intensLow, uchar r, uchar g, uchar b) { intensityLow = intensLow; intensityHigh = intensHigh; uchar4 hats = {r, g, b, 255}; color = hats; } uchar4 RS_KERNEL root(uchar4 v_in, uint32_t x, uint32_t y) { uchar4 refpix = rsGetElementAt_uchar4(inputImage, x, y); float pixelIntensity = dot(rsUnpackColor8888(refpix).rgb, mono); if ((pixelIntensity <= intensityHigh) && (pixelIntensity >= intensityLow)) { return color; } else { return v_in; } }
random_line_split
posterize.rs
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ip.rsh" #pragma rs_fp_relaxed rs_allocation inputImage; float intensityLow = 0.f; float intensityHigh; uchar4 color; const static float3 mono = {0.299f, 0.587f, 0.114f}; void setParams(float intensHigh, float intensLow, uchar r, uchar g, uchar b) { intensityLow = intensLow; intensityHigh = intensHigh; uchar4 hats = {r, g, b, 255}; color = hats; } uchar4 RS_KERNEL root(uchar4 v_in, uint32_t x, uint32_t y) { uchar4 refpix = rsGetElementAt_uchar4(inputImage, x, y); float pixelIntensity = dot(rsUnpackColor8888(refpix).rgb, mono); if ((pixelIntensity <= intensityHigh) && (pixelIntensity >= intensityLow)) { return color; } else
}
{ return v_in; }
conditional_block
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pub [u8;FINGERPRINT_SIZE]); impl Fingerprint { pub fn from_bytes_unsafe(bytes: &[u8]) -> Fingerprint { if bytes.len()!= FINGERPRINT_SIZE { panic!("Input value was not a fingerprint; had length: {}", bytes.len()); } let mut fingerprint = [0;FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap(); } s } } /// /// A Write instance that fingerprints all data that passes through it. /// pub struct WriterHasher<W: Write> { hasher: Blake2b, inner: W, } impl<W: Write> WriterHasher<W> { pub fn new(inner: W) -> WriterHasher<W> { WriterHasher { hasher: Blake2b::new(FINGERPRINT_SIZE), inner: inner, } } /// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn
(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.update(&buf[0..written]); Ok(written) } fn flush(&mut self) -> Result<()> { self.inner.flush() } }
finish
identifier_name
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pub [u8;FINGERPRINT_SIZE]); impl Fingerprint { pub fn from_bytes_unsafe(bytes: &[u8]) -> Fingerprint { if bytes.len()!= FINGERPRINT_SIZE
let mut fingerprint = [0;FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap(); } s } } /// /// A Write instance that fingerprints all data that passes through it. /// pub struct WriterHasher<W: Write> { hasher: Blake2b, inner: W, } impl<W: Write> WriterHasher<W> { pub fn new(inner: W) -> WriterHasher<W> { WriterHasher { hasher: Blake2b::new(FINGERPRINT_SIZE), inner: inner, } } /// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn finish(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.update(&buf[0..written]); Ok(written) } fn flush(&mut self) -> Result<()> { self.inner.flush() } }
{ panic!("Input value was not a fingerprint; had length: {}", bytes.len()); }
conditional_block
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pub [u8;FINGERPRINT_SIZE]); impl Fingerprint { pub fn from_bytes_unsafe(bytes: &[u8]) -> Fingerprint { if bytes.len()!= FINGERPRINT_SIZE { panic!("Input value was not a fingerprint; had length: {}", bytes.len()); } let mut fingerprint = [0;FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap(); } s } } /// /// A Write instance that fingerprints all data that passes through it. /// pub struct WriterHasher<W: Write> { hasher: Blake2b, inner: W, } impl<W: Write> WriterHasher<W> { pub fn new(inner: W) -> WriterHasher<W>
/// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn finish(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.update(&buf[0..written]); Ok(written) } fn flush(&mut self) -> Result<()> { self.inner.flush() } }
{ WriterHasher { hasher: Blake2b::new(FINGERPRINT_SIZE), inner: inner, } }
identifier_body
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::fmt; use std::io::{Write, Result}; use blake2_rfc::blake2b::Blake2b; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Fingerprint(pub [u8;FINGERPRINT_SIZE]); impl Fingerprint { pub fn from_bytes_unsafe(bytes: &[u8]) -> Fingerprint { if bytes.len()!= FINGERPRINT_SIZE { panic!("Input value was not a fingerprint; had length: {}", bytes.len()); } let mut fingerprint = [0;FINGERPRINT_SIZE]; fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]); Fingerprint(fingerprint) } pub fn to_hex(&self) -> String { let mut s = String::new(); for &byte in self.0.iter() { fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap(); } s } } /// /// A Write instance that fingerprints all data that passes through it. /// pub struct WriterHasher<W: Write> { hasher: Blake2b, inner: W, } impl<W: Write> WriterHasher<W> { pub fn new(inner: W) -> WriterHasher<W> { WriterHasher { hasher: Blake2b::new(FINGERPRINT_SIZE), inner: inner, } } /// /// Returns the result of fingerprinting this stream, and Drops the stream. /// pub fn finish(self) -> Fingerprint { Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes()) } } impl<W: Write> Write for WriterHasher<W> { fn write(&mut self, buf: &[u8]) -> Result<usize> { let written = self.inner.write(buf)?; // Hash the bytes that were successfully written. self.hasher.update(&buf[0..written]); Ok(written) }
self.inner.flush() } }
fn flush(&mut self) -> Result<()> {
random_line_split
test.rs
, and synthesizing a main test harness pub fn modify_for_testing(sess: &ParseSess, cfg: &ast::CrateConfig, krate: ast::Crate, span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate { // We generate the test harness when building in the 'test' // configuration, either with the '--test' or '--cfg test' // command line options. let should_test = attr::contains_name(krate.config.as_slice(), "test"); // Check for #[reexport_test_harness_main = "some_name"] which // creates a `use some_name = __test::main;`. This needs to be // unconditional, so that the attribute is still marked as used in // non-test builds. let reexport_test_harness_main = attr::first_attr_value_str_by_name(krate.attrs.as_slice(), "reexport_test_harness_main"); if should_test { generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic) } else { strip_test_functions(krate) } } struct TestHarnessGenerator<'a> { cx: TestCtxt<'a>, tests: Vec<ast::Ident>, // submodule name, gensym'd identifier for re-exports tested_submods: Vec<(ast::Ident, ast::Ident)>, } impl<'a> fold::Folder for TestHarnessGenerator<'a> { fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate { let mut folded = fold::noop_fold_crate(c, self); // Add a special __test module to the crate that will contain code // generated for the test harness let (mod_, reexport) = mk_test_module(&mut self.cx); folded.module.items.push(mod_); match reexport { Some(re) => folded.module.view_items.push(re), None => {} } folded } fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> { let ident = i.ident; if ident.name!= token::special_idents::invalid.name { self.cx.path.push(ident); } debug!("current path: {}", ast_util::path_name_i(self.cx.path.as_slice())); if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) { match i.node { ast::ItemFn(_, ast::UnsafeFn, _, _, _) => { let diag = self.cx.span_diagnostic; diag.span_fatal(i.span, "unsafe functions cannot be used for \ tests"); } _ => { debug!("this is a test function"); let test = Test { span: i.span, path: self.cx.path.clone(), bench: is_bench_fn(&self.cx, &*i), ignore: is_ignored(&*i), should_fail: should_fail(&*i) }; self.cx.testfns.push(test); self.tests.push(i.ident); // debug!("have {} test/bench functions", // cx.testfns.len()); } } } // We don't want to recurse into anything other than mods, since // mods or tests inside of functions will break things let res = match i.node { ast::ItemMod(..) => fold::noop_fold_item(i, self), _ => SmallVector::one(i), }; if ident.name!= token::special_idents::invalid.name { self.cx.path.pop(); } res } fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod { let tests = mem::replace(&mut self.tests, Vec::new()); let tested_submods = mem::replace(&mut self.tested_submods, Vec::new()); let mut mod_folded = fold::noop_fold_mod(m, self); let tests = mem::replace(&mut self.tests, tests); let tested_submods = mem::replace(&mut self.tested_submods, tested_submods); // Remove any #[main] from the AST so it doesn't clash with // the one we're going to add. Only if compiling an executable. mod_folded.items = mem::replace(&mut mod_folded.items, vec![]).move_map(|item| { item.map(|ast::Item {id, ident, attrs, node, vis, span}| { ast::Item { id: id, ident: ident, attrs: attrs.into_iter().filter_map(|attr| { if!attr.check_name("main") { Some(attr) } else { None } }).collect(), node: node, vis: vis, span: span } }) }); if!tests.is_empty() ||!tested_submods.is_empty() { let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods); mod_folded.items.push(it); if!self.cx.path.is_empty() { self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym)); } else { debug!("pushing nothing, sym: {}", sym); self.cx.toplevel_reexport = Some(sym); } } mod_folded } } fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>, tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) { let mut view_items = Vec::new(); let super_ = token::str_to_ident("super"); view_items.extend(tests.into_iter().map(|r| { cx.ext_cx.view_use_simple(DUMMY_SP, ast::Public, cx.ext_cx.path(DUMMY_SP, vec![super_, r])) })); view_items.extend(tested_submods.into_iter().map(|(r, sym)| { let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]); cx.ext_cx.view_use_simple_(DUMMY_SP, ast::Public, r, path) })); let reexport_mod = ast::Mod { inner: DUMMY_SP, view_items: view_items, items: Vec::new(), }; let sym = token::gensym_ident("__test_reexports"); let it = P(ast::Item { ident: sym.clone(), attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: ast::ItemMod(reexport_mod), vis: ast::Public, span: DUMMY_SP, }); (it, sym) } fn generate_test_harness(sess: &ParseSess, reexport_test_harness_main: Option<InternedString>, krate: ast::Crate, cfg: &ast::CrateConfig, sd: &diagnostic::SpanHandler) -> ast::Crate { let mut cx: TestCtxt = TestCtxt { sess: sess, span_diagnostic: sd, ext_cx: ExtCtxt::new(sess, cfg.clone(), ExpansionConfig::default("test".to_string())), path: Vec::new(), testfns: Vec::new(), reexport_test_harness_main: reexport_test_harness_main, is_test_crate: is_test_crate(&krate), config: krate.config.clone(), toplevel_reexport: None, }; cx.ext_cx.bt_push(ExpnInfo { call_site: DUMMY_SP, callee: NameAndSpan { name: "test".to_string(), format: MacroAttribute, span: None } }); let mut fold = TestHarnessGenerator { cx: cx, tests: Vec::new(), tested_submods: Vec::new(), }; let res = fold.fold_crate(krate); fold.cx.ext_cx.bt_pop(); return res; } fn strip_test_functions(krate: ast::Crate) -> ast::Crate { // When not compiling with --test we should not compile the // #[test] functions config::strip_items(krate, |attrs| { !attr::contains_name(attrs.as_slice(), "test") && !attr::contains_name(attrs.as_slice(), "bench") }) } #[deriving(PartialEq)] enum HasTestSignature { Yes, No, NotEvenAFunction, } fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test"); fn has_test_signature(i: &ast::Item) -> HasTestSignature { match &i.node { &ast::ItemFn(ref decl, _, _, ref generics, _) => { let no_output = match decl.output { ast::Return(ref ret_ty) => match ret_ty.node { ast::TyTup(ref tys) if tys.is_empty() => true, _ => false, }, ast::NoReturn(_) => false }; if decl.inputs.is_empty() && no_output &&!generics.is_parameterized() { Yes } else { No } } _ => NotEvenAFunction, } } if has_test_attr { let diag = cx.span_diagnostic; match has_test_signature(i) { Yes => {}, No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"), NotEvenAFunction => diag.span_err(i.span, "only functions may be used as tests"), } } return has_test_attr && has_test_signature(i) == Yes; } fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench"); fn has_test_signature(i: &ast::Item) -> bool { match i.node { ast::ItemFn(ref decl, _, _, ref generics, _) => { let input_cnt = decl.inputs.len(); let no_output = match decl.output { ast::Return(ref ret_ty) => match ret_ty.node { ast::TyTup(ref tys) if tys.is_empty() => true, _ => false, }, ast::NoReturn(_) => false }; let tparm_cnt = generics.ty_params.len(); // NB: inadequate check, but we're running // well before resolve, can't get too deep. input_cnt == 1u && no_output && tparm_cnt == 0u } _ => false }
diag.span_err(i.span, "functions used as benches must have signature \ `fn(&mut Bencher) -> ()`"); } return has_bench_attr && has_test_signature(i); } fn is_ignored(i: &ast::Item) -> bool { i.attrs.iter().any(|attr| attr.check_name("ignore")) } fn should_fail(i: &ast::Item) -> ShouldFail { match i.attrs.iter().find(|attr| attr.check_name("should_fail")) { Some(attr) => { let msg = attr.meta_item_list() .and_then(|list| list.iter().find(|mi| mi.check_name("expected"))) .and_then(|mi| mi.value_str()); ShouldFail::Yes(msg) } None => ShouldFail::No, } } /* We're going to be building a module that looks more or less like: mod __test { extern crate test (name = "test", vers = "..."); fn main() { test::test_main_static(::os::args().as_slice(), tests) } static tests : &'static [test::TestDescAndFn] = &[ ... the list of tests in the crate... ]; } */ fn mk_std(cx: &TestCtxt) -> ast::ViewItem { let id_test = token::str_to_ident("test"); let (vi, vis) = if cx.is_test_crate { (ast::ViewItemUse( P(nospan(ast::ViewPathSimple(id_test, path_node(vec!(id_test)), ast::DUMMY_NODE_ID)))), ast::Public) } else { (ast::ViewItemExternCrate(id_test, None, ast::DUMMY_NODE_ID), ast::Inherited) }; ast::ViewItem { node: vi, attrs: Vec::new(), vis: vis, span: DUMMY_SP } } fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<ast::ViewItem>) { // Link to test crate let view_items = vec!(mk_std(cx)); // A constant vector of test descriptors. let tests = mk_tests(cx); // The synthesized main function which will call the console test runner // with our list of tests let mainfn = (quote_item!(&mut cx.ext_cx, pub fn main() { #![main] use std::slice::AsSlice; test::test_main_static(::std::os::args().as_slice(), TESTS); } )).unwrap(); let testmod = ast::Mod { inner: DUMMY_SP, view_items: view_items, items: vec!(mainfn, tests), }; let item_ = ast::ItemMod(testmod); let mod_ident = token::gensym_ident("__test"); let item = ast::Item { ident: mod_ident, attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: item_, vis: ast::Public, span: DUMMY_SP, }; let reexport = cx.reexport_test_harness_main.as_ref().map(|s| { // building `use <ident> = __test::main` let reexport_ident = token::str_to_ident(s.get()); let use_path = nospan(ast::ViewPathSimple(reexport_ident, path_node(vec![mod_ident, token::str_to_ident("main")]), ast::DUMMY_NODE_ID)); ast::ViewItem { node: ast::ViewItemUse(P(use_path)), attrs: vec![], vis: ast::Inherited, span: DUMMY_SP } }); debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item)); (P(item), reexport) } fn nospan<T>(t: T) -> codemap::Spanned<T> { codemap::Spanned { node: t, span: DUMMY_SP } } fn path_node(ids: Vec<ast::Ident> ) -> ast::Path { ast::Path { span: DUMMY_SP, global: false, segments: ids.into_iter().map(|identifier| ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), }).collect() } } fn mk_tests(cx: &TestCtxt) -> P<ast::Item> { // The vector of test_descs for this crate let test_descs = mk_test_descs(cx); // FIXME #15962: should be using quote_item, but that stringifies // __test_reexports, causing it to be reinterned, losing the // gensym information. let sp = DUMMY_SP; let ecx = &cx.ext_cx; let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"), ecx.ident_of("test"), ecx.ident_of("TestDescAndFn")])); let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name); // &'static [self::test::TestDescAndFn] let static_type = ecx.ty_rptr(sp, ecx.ty(sp, ast::TyVec(struct_type)), Some(static_lt), ast::MutImmutable); // static TESTS: $static_type = &[...]; ecx.item_const(sp, ecx.ident_of("TESTS"), static_type, test_descs) } fn is_test_crate(krate: &ast::Crate) -> bool { match attr::find_crate_name(krate.attrs.as_slice()) { Some(ref s) if "test" == s.get().as_slice() => true, _ => false } } fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> { debug!("building test vector from {} tests", cx.testfns.len()); P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprAddrOf(ast::MutImmutable, P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprVec(cx.testfns.iter().map(|test| { mk_test_desc_and_fn_rec(cx, test) }).collect()), span:
} if has_bench_attr && !has_test_signature(i) { let diag = cx.span_diagnostic;
random_line_split
test.rs
and synthesizing a main test harness pub fn
(sess: &ParseSess, cfg: &ast::CrateConfig, krate: ast::Crate, span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate { // We generate the test harness when building in the 'test' // configuration, either with the '--test' or '--cfg test' // command line options. let should_test = attr::contains_name(krate.config.as_slice(), "test"); // Check for #[reexport_test_harness_main = "some_name"] which // creates a `use some_name = __test::main;`. This needs to be // unconditional, so that the attribute is still marked as used in // non-test builds. let reexport_test_harness_main = attr::first_attr_value_str_by_name(krate.attrs.as_slice(), "reexport_test_harness_main"); if should_test { generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic) } else { strip_test_functions(krate) } } struct TestHarnessGenerator<'a> { cx: TestCtxt<'a>, tests: Vec<ast::Ident>, // submodule name, gensym'd identifier for re-exports tested_submods: Vec<(ast::Ident, ast::Ident)>, } impl<'a> fold::Folder for TestHarnessGenerator<'a> { fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate { let mut folded = fold::noop_fold_crate(c, self); // Add a special __test module to the crate that will contain code // generated for the test harness let (mod_, reexport) = mk_test_module(&mut self.cx); folded.module.items.push(mod_); match reexport { Some(re) => folded.module.view_items.push(re), None => {} } folded } fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> { let ident = i.ident; if ident.name!= token::special_idents::invalid.name { self.cx.path.push(ident); } debug!("current path: {}", ast_util::path_name_i(self.cx.path.as_slice())); if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) { match i.node { ast::ItemFn(_, ast::UnsafeFn, _, _, _) => { let diag = self.cx.span_diagnostic; diag.span_fatal(i.span, "unsafe functions cannot be used for \ tests"); } _ => { debug!("this is a test function"); let test = Test { span: i.span, path: self.cx.path.clone(), bench: is_bench_fn(&self.cx, &*i), ignore: is_ignored(&*i), should_fail: should_fail(&*i) }; self.cx.testfns.push(test); self.tests.push(i.ident); // debug!("have {} test/bench functions", // cx.testfns.len()); } } } // We don't want to recurse into anything other than mods, since // mods or tests inside of functions will break things let res = match i.node { ast::ItemMod(..) => fold::noop_fold_item(i, self), _ => SmallVector::one(i), }; if ident.name!= token::special_idents::invalid.name { self.cx.path.pop(); } res } fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod { let tests = mem::replace(&mut self.tests, Vec::new()); let tested_submods = mem::replace(&mut self.tested_submods, Vec::new()); let mut mod_folded = fold::noop_fold_mod(m, self); let tests = mem::replace(&mut self.tests, tests); let tested_submods = mem::replace(&mut self.tested_submods, tested_submods); // Remove any #[main] from the AST so it doesn't clash with // the one we're going to add. Only if compiling an executable. mod_folded.items = mem::replace(&mut mod_folded.items, vec![]).move_map(|item| { item.map(|ast::Item {id, ident, attrs, node, vis, span}| { ast::Item { id: id, ident: ident, attrs: attrs.into_iter().filter_map(|attr| { if!attr.check_name("main") { Some(attr) } else { None } }).collect(), node: node, vis: vis, span: span } }) }); if!tests.is_empty() ||!tested_submods.is_empty() { let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods); mod_folded.items.push(it); if!self.cx.path.is_empty() { self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym)); } else { debug!("pushing nothing, sym: {}", sym); self.cx.toplevel_reexport = Some(sym); } } mod_folded } } fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>, tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) { let mut view_items = Vec::new(); let super_ = token::str_to_ident("super"); view_items.extend(tests.into_iter().map(|r| { cx.ext_cx.view_use_simple(DUMMY_SP, ast::Public, cx.ext_cx.path(DUMMY_SP, vec![super_, r])) })); view_items.extend(tested_submods.into_iter().map(|(r, sym)| { let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]); cx.ext_cx.view_use_simple_(DUMMY_SP, ast::Public, r, path) })); let reexport_mod = ast::Mod { inner: DUMMY_SP, view_items: view_items, items: Vec::new(), }; let sym = token::gensym_ident("__test_reexports"); let it = P(ast::Item { ident: sym.clone(), attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: ast::ItemMod(reexport_mod), vis: ast::Public, span: DUMMY_SP, }); (it, sym) } fn generate_test_harness(sess: &ParseSess, reexport_test_harness_main: Option<InternedString>, krate: ast::Crate, cfg: &ast::CrateConfig, sd: &diagnostic::SpanHandler) -> ast::Crate { let mut cx: TestCtxt = TestCtxt { sess: sess, span_diagnostic: sd, ext_cx: ExtCtxt::new(sess, cfg.clone(), ExpansionConfig::default("test".to_string())), path: Vec::new(), testfns: Vec::new(), reexport_test_harness_main: reexport_test_harness_main, is_test_crate: is_test_crate(&krate), config: krate.config.clone(), toplevel_reexport: None, }; cx.ext_cx.bt_push(ExpnInfo { call_site: DUMMY_SP, callee: NameAndSpan { name: "test".to_string(), format: MacroAttribute, span: None } }); let mut fold = TestHarnessGenerator { cx: cx, tests: Vec::new(), tested_submods: Vec::new(), }; let res = fold.fold_crate(krate); fold.cx.ext_cx.bt_pop(); return res; } fn strip_test_functions(krate: ast::Crate) -> ast::Crate { // When not compiling with --test we should not compile the // #[test] functions config::strip_items(krate, |attrs| { !attr::contains_name(attrs.as_slice(), "test") && !attr::contains_name(attrs.as_slice(), "bench") }) } #[deriving(PartialEq)] enum HasTestSignature { Yes, No, NotEvenAFunction, } fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test"); fn has_test_signature(i: &ast::Item) -> HasTestSignature { match &i.node { &ast::ItemFn(ref decl, _, _, ref generics, _) => { let no_output = match decl.output { ast::Return(ref ret_ty) => match ret_ty.node { ast::TyTup(ref tys) if tys.is_empty() => true, _ => false, }, ast::NoReturn(_) => false }; if decl.inputs.is_empty() && no_output &&!generics.is_parameterized() { Yes } else { No } } _ => NotEvenAFunction, } } if has_test_attr { let diag = cx.span_diagnostic; match has_test_signature(i) { Yes => {}, No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"), NotEvenAFunction => diag.span_err(i.span, "only functions may be used as tests"), } } return has_test_attr && has_test_signature(i) == Yes; } fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench"); fn has_test_signature(i: &ast::Item) -> bool { match i.node { ast::ItemFn(ref decl, _, _, ref generics, _) => { let input_cnt = decl.inputs.len(); let no_output = match decl.output { ast::Return(ref ret_ty) => match ret_ty.node { ast::TyTup(ref tys) if tys.is_empty() => true, _ => false, }, ast::NoReturn(_) => false }; let tparm_cnt = generics.ty_params.len(); // NB: inadequate check, but we're running // well before resolve, can't get too deep. input_cnt == 1u && no_output && tparm_cnt == 0u } _ => false } } if has_bench_attr &&!has_test_signature(i) { let diag = cx.span_diagnostic; diag.span_err(i.span, "functions used as benches must have signature \ `fn(&mut Bencher) -> ()`"); } return has_bench_attr && has_test_signature(i); } fn is_ignored(i: &ast::Item) -> bool { i.attrs.iter().any(|attr| attr.check_name("ignore")) } fn should_fail(i: &ast::Item) -> ShouldFail { match i.attrs.iter().find(|attr| attr.check_name("should_fail")) { Some(attr) => { let msg = attr.meta_item_list() .and_then(|list| list.iter().find(|mi| mi.check_name("expected"))) .and_then(|mi| mi.value_str()); ShouldFail::Yes(msg) } None => ShouldFail::No, } } /* We're going to be building a module that looks more or less like: mod __test { extern crate test (name = "test", vers = "..."); fn main() { test::test_main_static(::os::args().as_slice(), tests) } static tests : &'static [test::TestDescAndFn] = &[ ... the list of tests in the crate... ]; } */ fn mk_std(cx: &TestCtxt) -> ast::ViewItem { let id_test = token::str_to_ident("test"); let (vi, vis) = if cx.is_test_crate { (ast::ViewItemUse( P(nospan(ast::ViewPathSimple(id_test, path_node(vec!(id_test)), ast::DUMMY_NODE_ID)))), ast::Public) } else { (ast::ViewItemExternCrate(id_test, None, ast::DUMMY_NODE_ID), ast::Inherited) }; ast::ViewItem { node: vi, attrs: Vec::new(), vis: vis, span: DUMMY_SP } } fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<ast::ViewItem>) { // Link to test crate let view_items = vec!(mk_std(cx)); // A constant vector of test descriptors. let tests = mk_tests(cx); // The synthesized main function which will call the console test runner // with our list of tests let mainfn = (quote_item!(&mut cx.ext_cx, pub fn main() { #![main] use std::slice::AsSlice; test::test_main_static(::std::os::args().as_slice(), TESTS); } )).unwrap(); let testmod = ast::Mod { inner: DUMMY_SP, view_items: view_items, items: vec!(mainfn, tests), }; let item_ = ast::ItemMod(testmod); let mod_ident = token::gensym_ident("__test"); let item = ast::Item { ident: mod_ident, attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: item_, vis: ast::Public, span: DUMMY_SP, }; let reexport = cx.reexport_test_harness_main.as_ref().map(|s| { // building `use <ident> = __test::main` let reexport_ident = token::str_to_ident(s.get()); let use_path = nospan(ast::ViewPathSimple(reexport_ident, path_node(vec![mod_ident, token::str_to_ident("main")]), ast::DUMMY_NODE_ID)); ast::ViewItem { node: ast::ViewItemUse(P(use_path)), attrs: vec![], vis: ast::Inherited, span: DUMMY_SP } }); debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item)); (P(item), reexport) } fn nospan<T>(t: T) -> codemap::Spanned<T> { codemap::Spanned { node: t, span: DUMMY_SP } } fn path_node(ids: Vec<ast::Ident> ) -> ast::Path { ast::Path { span: DUMMY_SP, global: false, segments: ids.into_iter().map(|identifier| ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), }).collect() } } fn mk_tests(cx: &TestCtxt) -> P<ast::Item> { // The vector of test_descs for this crate let test_descs = mk_test_descs(cx); // FIXME #15962: should be using quote_item, but that stringifies // __test_reexports, causing it to be reinterned, losing the // gensym information. let sp = DUMMY_SP; let ecx = &cx.ext_cx; let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"), ecx.ident_of("test"), ecx.ident_of("TestDescAndFn")])); let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name); // &'static [self::test::TestDescAndFn] let static_type = ecx.ty_rptr(sp, ecx.ty(sp, ast::TyVec(struct_type)), Some(static_lt), ast::MutImmutable); // static TESTS: $static_type = &[...]; ecx.item_const(sp, ecx.ident_of("TESTS"), static_type, test_descs) } fn is_test_crate(krate: &ast::Crate) -> bool { match attr::find_crate_name(krate.attrs.as_slice()) { Some(ref s) if "test" == s.get().as_slice() => true, _ => false } } fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> { debug!("building test vector from {} tests", cx.testfns.len()); P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprAddrOf(ast::MutImmutable, P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprVec(cx.testfns.iter().map(|test| { mk_test_desc_and_fn_rec(cx, test) }).collect()),
modify_for_testing
identifier_name
test.rs
and synthesizing a main test harness pub fn modify_for_testing(sess: &ParseSess, cfg: &ast::CrateConfig, krate: ast::Crate, span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate { // We generate the test harness when building in the 'test' // configuration, either with the '--test' or '--cfg test' // command line options. let should_test = attr::contains_name(krate.config.as_slice(), "test"); // Check for #[reexport_test_harness_main = "some_name"] which // creates a `use some_name = __test::main;`. This needs to be // unconditional, so that the attribute is still marked as used in // non-test builds. let reexport_test_harness_main = attr::first_attr_value_str_by_name(krate.attrs.as_slice(), "reexport_test_harness_main"); if should_test { generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic) } else { strip_test_functions(krate) } } struct TestHarnessGenerator<'a> { cx: TestCtxt<'a>, tests: Vec<ast::Ident>, // submodule name, gensym'd identifier for re-exports tested_submods: Vec<(ast::Ident, ast::Ident)>, } impl<'a> fold::Folder for TestHarnessGenerator<'a> { fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate { let mut folded = fold::noop_fold_crate(c, self); // Add a special __test module to the crate that will contain code // generated for the test harness let (mod_, reexport) = mk_test_module(&mut self.cx); folded.module.items.push(mod_); match reexport { Some(re) => folded.module.view_items.push(re), None => {} } folded } fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> { let ident = i.ident; if ident.name!= token::special_idents::invalid.name { self.cx.path.push(ident); } debug!("current path: {}", ast_util::path_name_i(self.cx.path.as_slice())); if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i)
// cx.testfns.len()); } } } // We don't want to recurse into anything other than mods, since // mods or tests inside of functions will break things let res = match i.node { ast::ItemMod(..) => fold::noop_fold_item(i, self), _ => SmallVector::one(i), }; if ident.name!= token::special_idents::invalid.name { self.cx.path.pop(); } res } fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod { let tests = mem::replace(&mut self.tests, Vec::new()); let tested_submods = mem::replace(&mut self.tested_submods, Vec::new()); let mut mod_folded = fold::noop_fold_mod(m, self); let tests = mem::replace(&mut self.tests, tests); let tested_submods = mem::replace(&mut self.tested_submods, tested_submods); // Remove any #[main] from the AST so it doesn't clash with // the one we're going to add. Only if compiling an executable. mod_folded.items = mem::replace(&mut mod_folded.items, vec![]).move_map(|item| { item.map(|ast::Item {id, ident, attrs, node, vis, span}| { ast::Item { id: id, ident: ident, attrs: attrs.into_iter().filter_map(|attr| { if!attr.check_name("main") { Some(attr) } else { None } }).collect(), node: node, vis: vis, span: span } }) }); if!tests.is_empty() ||!tested_submods.is_empty() { let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods); mod_folded.items.push(it); if!self.cx.path.is_empty() { self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym)); } else { debug!("pushing nothing, sym: {}", sym); self.cx.toplevel_reexport = Some(sym); } } mod_folded } } fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>, tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) { let mut view_items = Vec::new(); let super_ = token::str_to_ident("super"); view_items.extend(tests.into_iter().map(|r| { cx.ext_cx.view_use_simple(DUMMY_SP, ast::Public, cx.ext_cx.path(DUMMY_SP, vec![super_, r])) })); view_items.extend(tested_submods.into_iter().map(|(r, sym)| { let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]); cx.ext_cx.view_use_simple_(DUMMY_SP, ast::Public, r, path) })); let reexport_mod = ast::Mod { inner: DUMMY_SP, view_items: view_items, items: Vec::new(), }; let sym = token::gensym_ident("__test_reexports"); let it = P(ast::Item { ident: sym.clone(), attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: ast::ItemMod(reexport_mod), vis: ast::Public, span: DUMMY_SP, }); (it, sym) } fn generate_test_harness(sess: &ParseSess, reexport_test_harness_main: Option<InternedString>, krate: ast::Crate, cfg: &ast::CrateConfig, sd: &diagnostic::SpanHandler) -> ast::Crate { let mut cx: TestCtxt = TestCtxt { sess: sess, span_diagnostic: sd, ext_cx: ExtCtxt::new(sess, cfg.clone(), ExpansionConfig::default("test".to_string())), path: Vec::new(), testfns: Vec::new(), reexport_test_harness_main: reexport_test_harness_main, is_test_crate: is_test_crate(&krate), config: krate.config.clone(), toplevel_reexport: None, }; cx.ext_cx.bt_push(ExpnInfo { call_site: DUMMY_SP, callee: NameAndSpan { name: "test".to_string(), format: MacroAttribute, span: None } }); let mut fold = TestHarnessGenerator { cx: cx, tests: Vec::new(), tested_submods: Vec::new(), }; let res = fold.fold_crate(krate); fold.cx.ext_cx.bt_pop(); return res; } fn strip_test_functions(krate: ast::Crate) -> ast::Crate { // When not compiling with --test we should not compile the // #[test] functions config::strip_items(krate, |attrs| { !attr::contains_name(attrs.as_slice(), "test") && !attr::contains_name(attrs.as_slice(), "bench") }) } #[deriving(PartialEq)] enum HasTestSignature { Yes, No, NotEvenAFunction, } fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test"); fn has_test_signature(i: &ast::Item) -> HasTestSignature { match &i.node { &ast::ItemFn(ref decl, _, _, ref generics, _) => { let no_output = match decl.output { ast::Return(ref ret_ty) => match ret_ty.node { ast::TyTup(ref tys) if tys.is_empty() => true, _ => false, }, ast::NoReturn(_) => false }; if decl.inputs.is_empty() && no_output &&!generics.is_parameterized() { Yes } else { No } } _ => NotEvenAFunction, } } if has_test_attr { let diag = cx.span_diagnostic; match has_test_signature(i) { Yes => {}, No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"), NotEvenAFunction => diag.span_err(i.span, "only functions may be used as tests"), } } return has_test_attr && has_test_signature(i) == Yes; } fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench"); fn has_test_signature(i: &ast::Item) -> bool { match i.node { ast::ItemFn(ref decl, _, _, ref generics, _) => { let input_cnt = decl.inputs.len(); let no_output = match decl.output { ast::Return(ref ret_ty) => match ret_ty.node { ast::TyTup(ref tys) if tys.is_empty() => true, _ => false, }, ast::NoReturn(_) => false }; let tparm_cnt = generics.ty_params.len(); // NB: inadequate check, but we're running // well before resolve, can't get too deep. input_cnt == 1u && no_output && tparm_cnt == 0u } _ => false } } if has_bench_attr &&!has_test_signature(i) { let diag = cx.span_diagnostic; diag.span_err(i.span, "functions used as benches must have signature \ `fn(&mut Bencher) -> ()`"); } return has_bench_attr && has_test_signature(i); } fn is_ignored(i: &ast::Item) -> bool { i.attrs.iter().any(|attr| attr.check_name("ignore")) } fn should_fail(i: &ast::Item) -> ShouldFail { match i.attrs.iter().find(|attr| attr.check_name("should_fail")) { Some(attr) => { let msg = attr.meta_item_list() .and_then(|list| list.iter().find(|mi| mi.check_name("expected"))) .and_then(|mi| mi.value_str()); ShouldFail::Yes(msg) } None => ShouldFail::No, } } /* We're going to be building a module that looks more or less like: mod __test { extern crate test (name = "test", vers = "..."); fn main() { test::test_main_static(::os::args().as_slice(), tests) } static tests : &'static [test::TestDescAndFn] = &[ ... the list of tests in the crate... ]; } */ fn mk_std(cx: &TestCtxt) -> ast::ViewItem { let id_test = token::str_to_ident("test"); let (vi, vis) = if cx.is_test_crate { (ast::ViewItemUse( P(nospan(ast::ViewPathSimple(id_test, path_node(vec!(id_test)), ast::DUMMY_NODE_ID)))), ast::Public) } else { (ast::ViewItemExternCrate(id_test, None, ast::DUMMY_NODE_ID), ast::Inherited) }; ast::ViewItem { node: vi, attrs: Vec::new(), vis: vis, span: DUMMY_SP } } fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<ast::ViewItem>) { // Link to test crate let view_items = vec!(mk_std(cx)); // A constant vector of test descriptors. let tests = mk_tests(cx); // The synthesized main function which will call the console test runner // with our list of tests let mainfn = (quote_item!(&mut cx.ext_cx, pub fn main() { #![main] use std::slice::AsSlice; test::test_main_static(::std::os::args().as_slice(), TESTS); } )).unwrap(); let testmod = ast::Mod { inner: DUMMY_SP, view_items: view_items, items: vec!(mainfn, tests), }; let item_ = ast::ItemMod(testmod); let mod_ident = token::gensym_ident("__test"); let item = ast::Item { ident: mod_ident, attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: item_, vis: ast::Public, span: DUMMY_SP, }; let reexport = cx.reexport_test_harness_main.as_ref().map(|s| { // building `use <ident> = __test::main` let reexport_ident = token::str_to_ident(s.get()); let use_path = nospan(ast::ViewPathSimple(reexport_ident, path_node(vec![mod_ident, token::str_to_ident("main")]), ast::DUMMY_NODE_ID)); ast::ViewItem { node: ast::ViewItemUse(P(use_path)), attrs: vec![], vis: ast::Inherited, span: DUMMY_SP } }); debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item)); (P(item), reexport) } fn nospan<T>(t: T) -> codemap::Spanned<T> { codemap::Spanned { node: t, span: DUMMY_SP } } fn path_node(ids: Vec<ast::Ident> ) -> ast::Path { ast::Path { span: DUMMY_SP, global: false, segments: ids.into_iter().map(|identifier| ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), }).collect() } } fn mk_tests(cx: &TestCtxt) -> P<ast::Item> { // The vector of test_descs for this crate let test_descs = mk_test_descs(cx); // FIXME #15962: should be using quote_item, but that stringifies // __test_reexports, causing it to be reinterned, losing the // gensym information. let sp = DUMMY_SP; let ecx = &cx.ext_cx; let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"), ecx.ident_of("test"), ecx.ident_of("TestDescAndFn")])); let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name); // &'static [self::test::TestDescAndFn] let static_type = ecx.ty_rptr(sp, ecx.ty(sp, ast::TyVec(struct_type)), Some(static_lt), ast::MutImmutable); // static TESTS: $static_type = &[...]; ecx.item_const(sp, ecx.ident_of("TESTS"), static_type, test_descs) } fn is_test_crate(krate: &ast::Crate) -> bool { match attr::find_crate_name(krate.attrs.as_slice()) { Some(ref s) if "test" == s.get().as_slice() => true, _ => false } } fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> { debug!("building test vector from {} tests", cx.testfns.len()); P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprAddrOf(ast::MutImmutable, P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprVec(cx.testfns.iter().map(|test| { mk_test_desc_and_fn_rec(cx, test) }).collect()),
{ match i.node { ast::ItemFn(_, ast::UnsafeFn, _, _, _) => { let diag = self.cx.span_diagnostic; diag.span_fatal(i.span, "unsafe functions cannot be used for \ tests"); } _ => { debug!("this is a test function"); let test = Test { span: i.span, path: self.cx.path.clone(), bench: is_bench_fn(&self.cx, &*i), ignore: is_ignored(&*i), should_fail: should_fail(&*i) }; self.cx.testfns.push(test); self.tests.push(i.ident); // debug!("have {} test/bench functions",
conditional_block
subspace.rs
//! Implements traits for tuples such subspaces can be constructed. use Construct; use Count; use ToIndex; use ToPos; use Zero; impl<T, U> Construct for (T, U) where T: Construct, U: Construct { fn new() -> (T, U) { (Construct::new(), Construct::new()) } } impl<T, U, V, W> Count<(V, W)> for (T, U) where T: Construct + Count<V>, U: Construct + Count<W> { fn count(&self, &(ref dim_t, ref dim_u): &(V, W)) -> usize { let t: T = Construct::new(); let u: U = Construct::new(); t.count(dim_t) * u.count(dim_u)
impl<T, U, V, W, X, Y> Zero<(V, W), (X, Y)> for (T, U) where T: Construct + Zero<V, X>, U: Construct + Zero<W, Y> { fn zero(&self, &(ref dim_t, ref dim_u): &(V, W)) -> (X, Y) { let t: T = Construct::new(); let u: U = Construct::new(); (t.zero(dim_t), u.zero(dim_u)) } } impl<T, U, V, W, X, Y> ToIndex<(V, W), (X, Y)> for (T, U) where T: Construct + ToIndex<V, X>, U: Construct + Count<W> + ToIndex<W, Y> { fn to_index( &self, &(ref dim_t, ref dim_u): &(V, W), &(ref pt, ref pu): &(X, Y) ) -> usize { let t: T = Construct::new(); let u: U = Construct::new(); let count = u.count(dim_u); t.to_index(dim_t, pt) * count + u.to_index(dim_u, pu) } } impl<T, U, V, W, X, Y> ToPos<(V, W), (X, Y)> for (T, U) where T: Construct + ToPos<V, X>, U: Construct + Count<W> + ToPos<W, Y> { fn to_pos( &self, &(ref dim_t, ref dim_u): &(V, W), ind: usize, &mut (ref mut pt, ref mut pu): &mut (X, Y) ) { let t: T = Construct::new(); let u: U = Construct::new(); let count = u.count(dim_u); let x = ind / count; t.to_pos(dim_t, x, pt); u.to_pos(dim_u, ind - x * count, pu); } }
} }
random_line_split
subspace.rs
//! Implements traits for tuples such subspaces can be constructed. use Construct; use Count; use ToIndex; use ToPos; use Zero; impl<T, U> Construct for (T, U) where T: Construct, U: Construct { fn new() -> (T, U) { (Construct::new(), Construct::new()) } } impl<T, U, V, W> Count<(V, W)> for (T, U) where T: Construct + Count<V>, U: Construct + Count<W> { fn count(&self, &(ref dim_t, ref dim_u): &(V, W)) -> usize { let t: T = Construct::new(); let u: U = Construct::new(); t.count(dim_t) * u.count(dim_u) } } impl<T, U, V, W, X, Y> Zero<(V, W), (X, Y)> for (T, U) where T: Construct + Zero<V, X>, U: Construct + Zero<W, Y> { fn zero(&self, &(ref dim_t, ref dim_u): &(V, W)) -> (X, Y) { let t: T = Construct::new(); let u: U = Construct::new(); (t.zero(dim_t), u.zero(dim_u)) } } impl<T, U, V, W, X, Y> ToIndex<(V, W), (X, Y)> for (T, U) where T: Construct + ToIndex<V, X>, U: Construct + Count<W> + ToIndex<W, Y> { fn to_index( &self, &(ref dim_t, ref dim_u): &(V, W), &(ref pt, ref pu): &(X, Y) ) -> usize { let t: T = Construct::new(); let u: U = Construct::new(); let count = u.count(dim_u); t.to_index(dim_t, pt) * count + u.to_index(dim_u, pu) } } impl<T, U, V, W, X, Y> ToPos<(V, W), (X, Y)> for (T, U) where T: Construct + ToPos<V, X>, U: Construct + Count<W> + ToPos<W, Y> { fn to_pos( &self, &(ref dim_t, ref dim_u): &(V, W), ind: usize, &mut (ref mut pt, ref mut pu): &mut (X, Y) )
}
{ let t: T = Construct::new(); let u: U = Construct::new(); let count = u.count(dim_u); let x = ind / count; t.to_pos(dim_t, x, pt); u.to_pos(dim_u, ind - x * count, pu); }
identifier_body
subspace.rs
//! Implements traits for tuples such subspaces can be constructed. use Construct; use Count; use ToIndex; use ToPos; use Zero; impl<T, U> Construct for (T, U) where T: Construct, U: Construct { fn new() -> (T, U) { (Construct::new(), Construct::new()) } } impl<T, U, V, W> Count<(V, W)> for (T, U) where T: Construct + Count<V>, U: Construct + Count<W> { fn
(&self, &(ref dim_t, ref dim_u): &(V, W)) -> usize { let t: T = Construct::new(); let u: U = Construct::new(); t.count(dim_t) * u.count(dim_u) } } impl<T, U, V, W, X, Y> Zero<(V, W), (X, Y)> for (T, U) where T: Construct + Zero<V, X>, U: Construct + Zero<W, Y> { fn zero(&self, &(ref dim_t, ref dim_u): &(V, W)) -> (X, Y) { let t: T = Construct::new(); let u: U = Construct::new(); (t.zero(dim_t), u.zero(dim_u)) } } impl<T, U, V, W, X, Y> ToIndex<(V, W), (X, Y)> for (T, U) where T: Construct + ToIndex<V, X>, U: Construct + Count<W> + ToIndex<W, Y> { fn to_index( &self, &(ref dim_t, ref dim_u): &(V, W), &(ref pt, ref pu): &(X, Y) ) -> usize { let t: T = Construct::new(); let u: U = Construct::new(); let count = u.count(dim_u); t.to_index(dim_t, pt) * count + u.to_index(dim_u, pu) } } impl<T, U, V, W, X, Y> ToPos<(V, W), (X, Y)> for (T, U) where T: Construct + ToPos<V, X>, U: Construct + Count<W> + ToPos<W, Y> { fn to_pos( &self, &(ref dim_t, ref dim_u): &(V, W), ind: usize, &mut (ref mut pt, ref mut pu): &mut (X, Y) ) { let t: T = Construct::new(); let u: U = Construct::new(); let count = u.count(dim_u); let x = ind / count; t.to_pos(dim_t, x, pt); u.to_pos(dim_u, ind - x * count, pu); } }
count
identifier_name
clear_strategy.rs
use clear_strategy::ClearStrategy::*; use std::iter; pub enum ClearStrategy { Vertical, Horizontal, DiagonalUp, DiagonalDown, } impl ClearStrategy { pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> { match *self { Vertical => (iter::repeat(0)).zip(0..width).collect(), Horizontal => (0..height).zip(iter::repeat(0)).collect(), DiagonalUp => ( (0..height).zip(iter::repeat(0))) .chain( iter::repeat(height - 1).zip(1..width) ).collect(), DiagonalDown => ( iter::repeat(0)).zip(0..width) .chain( (1..height).zip(iter::repeat(0)) ).collect(), } } pub fn get_next_point( &self, row: usize, col: usize, height: usize, width: usize ) -> Option<(usize, usize)> { let (new_row, new_col) = match *self { Vertical => (row + 1, col), Horizontal => (row, col + 1), DiagonalUp if row > 0 => (row - 1, col + 1), DiagonalDown => (row + 1, col + 1), _ => return None }; let is_invalid_point = new_row >= height || new_col >= width; if is_invalid_point { None
Some((new_row, new_col)) } } }
} else {
random_line_split
clear_strategy.rs
use clear_strategy::ClearStrategy::*; use std::iter; pub enum ClearStrategy { Vertical, Horizontal, DiagonalUp, DiagonalDown, } impl ClearStrategy { pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> { match *self { Vertical => (iter::repeat(0)).zip(0..width).collect(), Horizontal => (0..height).zip(iter::repeat(0)).collect(), DiagonalUp => ( (0..height).zip(iter::repeat(0))) .chain( iter::repeat(height - 1).zip(1..width) ).collect(), DiagonalDown => ( iter::repeat(0)).zip(0..width) .chain( (1..height).zip(iter::repeat(0)) ).collect(), } } pub fn
( &self, row: usize, col: usize, height: usize, width: usize ) -> Option<(usize, usize)> { let (new_row, new_col) = match *self { Vertical => (row + 1, col), Horizontal => (row, col + 1), DiagonalUp if row > 0 => (row - 1, col + 1), DiagonalDown => (row + 1, col + 1), _ => return None }; let is_invalid_point = new_row >= height || new_col >= width; if is_invalid_point { None } else { Some((new_row, new_col)) } } }
get_next_point
identifier_name
clear_strategy.rs
use clear_strategy::ClearStrategy::*; use std::iter; pub enum ClearStrategy { Vertical, Horizontal, DiagonalUp, DiagonalDown, } impl ClearStrategy { pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> { match *self { Vertical => (iter::repeat(0)).zip(0..width).collect(), Horizontal => (0..height).zip(iter::repeat(0)).collect(), DiagonalUp => ( (0..height).zip(iter::repeat(0))) .chain( iter::repeat(height - 1).zip(1..width) ).collect(), DiagonalDown => ( iter::repeat(0)).zip(0..width) .chain( (1..height).zip(iter::repeat(0)) ).collect(), } } pub fn get_next_point( &self, row: usize, col: usize, height: usize, width: usize ) -> Option<(usize, usize)>
}
{ let (new_row, new_col) = match *self { Vertical => (row + 1, col), Horizontal => (row, col + 1), DiagonalUp if row > 0 => (row - 1, col + 1), DiagonalDown => (row + 1, col + 1), _ => return None }; let is_invalid_point = new_row >= height || new_col >= width; if is_invalid_point { None } else { Some((new_row, new_col)) } }
identifier_body
ws2bth.rs
// 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. use shared::bthdef::{ BTH_ADDR, MAX_L2CAP_INFO_DATA_LENGTH, MAX_L2CAP_PING_DATA_LENGTH, MAX_UUIDS_IN_QUERY, }; use shared::bthsdpdef::{SdpAttributeRange, SdpQueryUuid}; use shared::guiddef::GUID; use shared::minwindef::{DWORD, PULONG, UCHAR, ULONG, USHORT}; use shared::ws2def::IOC_VENDOR; use um::winnt::HANDLE; pub const BT_PORT_ANY: ULONG = -1i32 as ULONG; pub const BT_PORT_MIN: ULONG = 0x1; pub const BT_PORT_MAX: ULONG = 0xffff; pub const BT_PORT_DYN_FIRST: ULONG = 0x1001; pub const AF_BTH: USHORT = 32; pub const PH_BTH: USHORT = AF_BTH; pub const NS_BTH: USHORT = 16; STRUCT!{#[repr(packed)] struct SOCKADDR_BTH { addressFamily: USHORT, btAddr: BTH_ADDR, serviceClassId: GUID, port: ULONG, }} pub type PSOCKADDR_BTH = *mut SOCKADDR_BTH; DEFINE_GUID!{SVCID_BTH_PROVIDER, 0x6aa63e0, 0x7d60, 0x41ff, 0xaf, 0xb2, 0x3e, 0xe6, 0xd2, 0xd9, 0x39, 0x2d} pub const BTH_ADDR_STRING_SIZE: DWORD = 12; pub const BTHPROTO_RFCOMM: USHORT = 0x0003; pub const BTHPROTO_L2CAP: USHORT = 0x0100; pub const SOL_RFCOMM: USHORT = BTHPROTO_RFCOMM; pub const SOL_L2CAP: USHORT = BTHPROTO_L2CAP; pub const SOL_SDP: USHORT = 0x0101; pub const SO_BTH_AUTHENTICATE: ULONG = 0x80000001; pub const SO_BTH_ENCRYPT: ULONG = 0x00000002; pub const SO_BTH_MTU: ULONG = 0x80000007; pub const SO_BTH_MTU_MAX: ULONG = 0x80000008; pub const SO_BTH_MTU_MIN: ULONG = 0x8000000a; pub const RFCOMM_MAX_MTU: ULONG = 0x000003F3; pub const RFCOMM_MIN_MTU: ULONG = 0x00000017; pub const BTH_SDP_VERSION: ULONG = 1; STRUCT!{#[repr(packed)] struct BTH_SET_SERVICE { pSdpVersion: PULONG, pRecordHandle: HANDLE, fCodService: ULONG, Reserved: [ULONG; 5], ulRecordLength: ULONG, pRecord: [UCHAR; 1], }} pub type PBTH_SET_SERVICE = *mut BTH_SET_SERVICE; pub const SDP_DEFAULT_INQUIRY_SECONDS: UCHAR = 6; pub const SDP_MAX_INQUIRY_SECONDS: UCHAR = 60; pub const SDP_DEFAULT_INQUIRY_MAX_RESPONSES: UCHAR = 255; pub const SDP_SERVICE_SEARCH_REQUEST: ULONG = 1; pub const SDP_SERVICE_ATTRIBUTE_REQUEST: ULONG = 2; pub const SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST: ULONG = 3; STRUCT!{#[repr(packed)] struct BTH_QUERY_DEVICE { LAP: ULONG, length: UCHAR, }} pub type PBTH_QUERY_DEVICE = *mut BTH_QUERY_DEVICE; STRUCT!{#[repr(packed)] struct BTH_QUERY_SERVICE { type_: ULONG, serviceHandle: ULONG, uuids: [SdpQueryUuid; MAX_UUIDS_IN_QUERY], numRange: ULONG, pRange: [SdpAttributeRange; 1], }} pub type PBTH_QUERY_SERVICE = *mut BTH_QUERY_SERVICE; pub const BTHNS_RESULT_DEVICE_CONNECTED: DWORD = 0x00010000; pub const BTHNS_RESULT_DEVICE_REMEMBERED: DWORD = 0x00020000; pub const BTHNS_RESULT_DEVICE_AUTHENTICATED: DWORD = 0x00040000; pub const SIO_RFCOMM_SEND_COMMAND: DWORD = _WSAIORW!(IOC_VENDOR, 101); pub const SIO_RFCOMM_WAIT_COMMAND: DWORD = _WSAIORW!(IOC_VENDOR, 102); pub const SIO_BTH_PING: DWORD = _WSAIORW!(IOC_VENDOR, 8); pub const SIO_BTH_INFO: DWORD = _WSAIORW!(IOC_VENDOR, 9); pub const SIO_RFCOMM_SESSION_FLOW_OFF: DWORD = _WSAIORW!(IOC_VENDOR, 103); pub const SIO_RFCOMM_TEST: DWORD = _WSAIORW!(IOC_VENDOR, 104); pub const SIO_RFCOMM_USECFC: DWORD = _WSAIORW!(IOC_VENDOR, 105); macro_rules! BIT { ($b:expr) => { 1 << $b }; } STRUCT!{#[repr(packed)] struct RFCOMM_MSC_DATA { Signals: UCHAR, Break: UCHAR, }} pub type PRFCOMM_MSC_DATA = *mut RFCOMM_MSC_DATA; pub const MSC_EA_BIT: UCHAR = BIT!(0); pub const MSC_FC_BIT: UCHAR = BIT!(1); pub const MSC_RTC_BIT: UCHAR = BIT!(2); pub const MSC_RTR_BIT: UCHAR = BIT!(3); pub const MSC_RESERVED: UCHAR = BIT!(4) | BIT!(5); pub const MSC_IC_BIT: UCHAR = BIT!(6); pub const MSC_DV_BIT: UCHAR = BIT!(7); pub const MSC_BREAK_BIT: UCHAR = BIT!(1); macro_rules! MSC_SET_BREAK_LENGTH { ($b: expr, $l: expr) => { ($b & 0x3) | (($l & 0xf) << 4) }; } STRUCT!{#[repr(packed)] struct RFCOMM_RLS_DATA { LineStatus: UCHAR, }} pub type PRFCOMM_RLS_DATA = *mut RFCOMM_RLS_DATA; pub const RLS_ERROR: UCHAR = 0x01; pub const RLS_OVERRUN: UCHAR = 0x02; pub const RLS_PARITY: UCHAR = 0x04; pub const RLS_FRAMING: UCHAR = 0x08; STRUCT!{#[repr(packed)] struct RFCOMM_RPN_DATA { Baud: UCHAR, Data: UCHAR, FlowControl: UCHAR, XonChar: UCHAR, XoffChar: UCHAR, ParameterMask1: UCHAR, ParameterMask2: UCHAR, }} pub type PRFCOMM_RPN_DATA = *mut RFCOMM_RPN_DATA; pub const RPN_BAUD_2400: UCHAR = 0; pub const RPN_BAUD_4800: UCHAR = 1; pub const RPN_BAUD_7200: UCHAR = 2; pub const RPN_BAUD_9600: UCHAR = 3; pub const RPN_BAUD_19200: UCHAR = 4; pub const RPN_BAUD_38400: UCHAR = 5; pub const RPN_BAUD_57600: UCHAR = 6; pub const RPN_BAUD_115200: UCHAR = 7; pub const RPN_BAUD_230400: UCHAR = 8; pub const RPN_DATA_5: UCHAR = 0x0; pub const RPN_DATA_6: UCHAR = 0x1; pub const RPN_DATA_7: UCHAR = 0x2; pub const RPN_DATA_8: UCHAR = 0x3; pub const RPN_STOP_1: UCHAR = 0x0; pub const RPN_STOP_1_5: UCHAR = 0x4; pub const RPN_PARITY_NONE: UCHAR = 0x00; pub const RPN_PARITY_ODD: UCHAR = 0x08; pub const RPN_PARITY_EVEN: UCHAR = 0x18; pub const RPN_PARITY_MARK: UCHAR = 0x28; pub const RPN_PARITY_SPACE: UCHAR = 0x38; pub const RPN_FLOW_X_IN: UCHAR = 0x01; pub const RPN_FLOW_X_OUT: UCHAR = 0x02; pub const RPN_FLOW_RTR_IN: UCHAR = 0x04; pub const RPN_FLOW_RTR_OUT: UCHAR = 0x08; pub const RPN_FLOW_RTC_IN: UCHAR = 0x10; pub const RPN_FLOW_RTC_OUT: UCHAR = 0x20; pub const RPN_PARAM_BAUD: UCHAR = 0x01; pub const RPN_PARAM_DATA: UCHAR = 0x02; pub const RPN_PARAM_STOP: UCHAR = 0x04; pub const RPN_PARAM_PARITY: UCHAR = 0x08; pub const RPN_PARAM_P_TYPE: UCHAR = 0x10; pub const RPN_PARAM_XON: UCHAR = 0x20; pub const RPN_PARAM_XOFF: UCHAR = 0x40; pub const RPN_PARAM_X_IN: UCHAR = 0x01; pub const RPN_PARAM_X_OUT: UCHAR = 0x02; pub const RPN_PARAM_RTR_IN: UCHAR = 0x04; pub const RPN_PARAM_RTR_OUT: UCHAR = 0x08; pub const RPN_PARAM_RTC_IN: UCHAR = 0x10; pub const RPN_PARAM_RTC_OUT: UCHAR = 0x20;
pub const RFCOMM_CMD_RPN: UCHAR = 3; pub const RFCOMM_CMD_RPN_REQUEST: UCHAR = 4; pub const RFCOMM_CMD_RPN_RESPONSE: UCHAR = 5; UNION!{#[repr(packed)] union RFCOMM_COMMAND_Data { [u8; 7], MSC MSC_mut: RFCOMM_MSC_DATA, RLS RLS_mut: RFCOMM_RLS_DATA, RPN RPN_mut: RFCOMM_RPN_DATA, }} STRUCT!{#[repr(packed)] struct RFCOMM_COMMAND { CmdType: ULONG, Data: RFCOMM_COMMAND_Data, }} pub type PRFCOMM_COMMAND = *mut RFCOMM_COMMAND; STRUCT!{#[repr(packed)] struct BTH_PING_REQ { btAddr: BTH_ADDR, dataLen: UCHAR, data: [UCHAR; MAX_L2CAP_PING_DATA_LENGTH], }} pub type PBTH_PING_REQ = *mut BTH_PING_REQ; STRUCT!{#[repr(packed)] struct BTH_PING_RSP { dataLen: UCHAR, data: [UCHAR; MAX_L2CAP_PING_DATA_LENGTH], }} pub type PBTH_PING_RSP = *mut BTH_PING_RSP; STRUCT!{#[repr(packed)] struct BTH_INFO_REQ { btAddr: BTH_ADDR, infoType: USHORT, }} pub type PBTH_INFO_REQ = *mut BTH_INFO_REQ; UNION!{#[repr(packed)] union BTH_INFO_RSP_u { [u8; MAX_L2CAP_INFO_DATA_LENGTH], connectionlessMTU connectionlessMTU_mut: USHORT, data data_mut: [UCHAR; MAX_L2CAP_INFO_DATA_LENGTH], }} STRUCT!{#[repr(packed)] struct BTH_INFO_RSP { result: USHORT, dataLen: UCHAR, u: BTH_INFO_RSP_u, }} pub type PBTH_INFO_RSP = *mut BTH_INFO_RSP; pub type BTHNS_SETBLOB = BTH_SET_SERVICE; pub type PBTHNS_SETBLOB = PBTH_SET_SERVICE; pub type BTHNS_INQUIRYBLOB = BTH_QUERY_DEVICE; pub type PBTHNS_INQUIRYBLOB = PBTH_QUERY_DEVICE; pub type BTHNS_RESTRICTIONBLOB = BTH_QUERY_SERVICE; pub type PBTHNS_RESTRICTIONBLOB = PBTH_QUERY_SERVICE;
pub const RFCOMM_CMD_NONE: UCHAR = 0; pub const RFCOMM_CMD_MSC: UCHAR = 1; pub const RFCOMM_CMD_RLS: UCHAR = 2;
random_line_split
issue-9446.rs
// Copyright 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. struct
(StrBuf); impl Wrapper { pub fn new(wrapped: StrBuf) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_strbuf()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-box ty Wrapper::new("Bob".to_strbuf()).say_hi(); } }
Wrapper
identifier_name
issue-9446.rs
// Copyright 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. struct Wrapper(StrBuf); impl Wrapper { pub fn new(wrapped: StrBuf) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_strbuf()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-box ty Wrapper::new("Bob".to_strbuf()).say_hi(); } }
random_line_split
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); match fn { get_type => || gobject_sys::g_binding_get_type(), } } impl Binding { pub fn get_flags(&self) -> BindingFlags { unsafe { from_glib(gobject_sys::g_binding_get_flags(self.to_glib_none().0)) } } pub fn get_source(&self) -> Option<Object> { unsafe { from_glib_none(gobject_sys::g_binding_get_source(self.to_glib_none().0)) } } pub fn get_source_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_source_property( self.to_glib_none().0, )) } } pub fn get_target(&self) -> Option<Object> { unsafe { from_glib_none(gobject_sys::g_binding_get_target(self.to_glib_none().0)) } } pub fn get_target_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_target_property( self.to_glib_none().0, )) } } pub fn unbind(&self) { unsafe { gobject_sys::g_binding_unbind(self.to_glib_full()); } } } unsafe impl Send for Binding {} unsafe impl Sync for Binding {}
impl fmt::Display for Binding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Binding") } }
random_line_split
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); match fn { get_type => || gobject_sys::g_binding_get_type(), } } impl Binding { pub fn get_flags(&self) -> BindingFlags { unsafe { from_glib(gobject_sys::g_binding_get_flags(self.to_glib_none().0)) } } pub fn get_source(&self) -> Option<Object> { unsafe { from_glib_none(gobject_sys::g_binding_get_source(self.to_glib_none().0)) } } pub fn get_source_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_source_property( self.to_glib_none().0, )) } } pub fn get_target(&self) -> Option<Object>
pub fn get_target_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_target_property( self.to_glib_none().0, )) } } pub fn unbind(&self) { unsafe { gobject_sys::g_binding_unbind(self.to_glib_full()); } } } unsafe impl Send for Binding {} unsafe impl Sync for Binding {} impl fmt::Display for Binding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Binding") } }
{ unsafe { from_glib_none(gobject_sys::g_binding_get_target(self.to_glib_none().0)) } }
identifier_body
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); match fn { get_type => || gobject_sys::g_binding_get_type(), } } impl Binding { pub fn get_flags(&self) -> BindingFlags { unsafe { from_glib(gobject_sys::g_binding_get_flags(self.to_glib_none().0)) } } pub fn
(&self) -> Option<Object> { unsafe { from_glib_none(gobject_sys::g_binding_get_source(self.to_glib_none().0)) } } pub fn get_source_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_source_property( self.to_glib_none().0, )) } } pub fn get_target(&self) -> Option<Object> { unsafe { from_glib_none(gobject_sys::g_binding_get_target(self.to_glib_none().0)) } } pub fn get_target_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_target_property( self.to_glib_none().0, )) } } pub fn unbind(&self) { unsafe { gobject_sys::g_binding_unbind(self.to_glib_full()); } } } unsafe impl Send for Binding {} unsafe impl Sync for Binding {} impl fmt::Display for Binding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Binding") } }
get_source
identifier_name
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRYPT_COST: u32 = 10; pub struct DatabaseInFile { pub db: Database, pub filepath: String } impl DatabaseInFile { pub fn save(&self) -> io::Result<()>{ self.db.save_to_file(Path::new(&self.filepath)) } } pub struct Database { bcrypt_salt: [u8; SALT_SIZE], bcrypt_pass: [u8; PASS_SIZE], pub entries: Vec<Entry> } impl Database { pub fn empty(password: &str) -> Database { let mut salt = [0u8; SALT_SIZE]; // 16bytes of salt bcrypt let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes OsRng::new().unwrap().fill_bytes(&mut salt); // TODO take only first 72 characters of input bcrypt(BCRYPT_COST, &salt, password.as_bytes(), &mut bcrypt_output); Database { bcrypt_salt: salt, bcrypt_pass: bcrypt_output, entries: Vec::new() } } pub fn open_from_file(path: &Path, password: &str) -> io::Result<Database> { // let mut file = try!(File::open(Path::new(file_path))); let mut file = try!(File::open(path)); Database::open(password, &mut file) } pub fn save_to_file(&self, path: &Path) -> io::Result<()> { // Open the file in write-only mode let mut file = try!(File::create(path)); self.save(&mut file) } pub fn open<T: Read>(password: &str, src: &mut T) -> io::Result<Database> { let mut salt = [0u8; SALT_SIZE]; // 16bytes of salt bcrypt let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes let mut version_buffer = [0u8; 1]; match src.read(&mut version_buffer){ Ok(_) => (), Err(why) => return Err(why) }; if version_buffer[0]!= DB_VERSION { return Database::invalid_data_error(format!("Cannot process DB version {}", version_buffer[0])); } match src.read(&mut salt){ Ok(SALT_SIZE) => (), Ok(count) => return Database::invalid_data_error(format!("Bad number of bytes {} read for salt.", count)), Err(why) => return Err(why) } // Read the rest let mut buffer = Vec::new(); try!(src.read_to_end(&mut buffer)); // Run Bcrypt bcrypt(BCRYPT_COST, &salt, password.as_bytes(), &mut bcrypt_output); // Decrypt let secret = match SecretMsg::from_bytes(&buffer) { Some(msg) => msg, None => return Database::invalid_data_error("Too few bytes (less than NONCE + ZERO bytes of SecretMsg).".to_string()) }; let key = SecretKey::from_slice(&bcrypt_output); let dec = key.decrypt(&secret).unwrap(); let deserialized_entries: Vec<Entry> = serde_json::from_slice(&dec).unwrap(); Ok(Database{ bcrypt_salt: salt, bcrypt_pass: bcrypt_output, entries: deserialized_entries }) } pub fn save<T: Write>(&self, dest: &mut T) -> io::Result<()>{ let serialized = serde_json::to_string(&self.entries).unwrap(); let key = SecretKey::from_slice(&self.bcrypt_pass); let enc: SecretMsg = key.encrypt(serialized.as_bytes()); // write version try!(dest.write(&[DB_VERSION])); // write salt first try!(dest.write(&self.bcrypt_salt)); try!(dest.flush()); // write nonce + encrypted data try!(dest.write(&enc.nonce)); try!(dest.flush()); try!(dest.write(&enc.cipher)); try!(dest.flush()); Ok(()) } pub fn add(&mut self, entry: Entry){ self.entries.push(entry); } pub fn get(&self, entry_title: &str) -> Option<&Entry> { self.entries.iter().find(|entry| entry.title.eq(entry_title)) } pub fn remove(&mut self, entry_title: &str) -> bool{ let pos = self.entries .iter() .position(|entry| entry.title.eq(entry_title)); return match pos { Some(index) => { self.entries.remove(index); true } None => false } } fn invalid_data_error(text: String) -> io::Result<Database>
} #[cfg(test)] mod tests { use db::Entry; use db::Database; use std::io::Cursor; use std::io::Read; #[test] fn test_save_and_load() { let mut buff: Cursor<Vec<u8>> = Cursor::new(vec![]); { let mut db = Database::empty("test"); db.add(Entry::new("service_a", "name_a", "pass_a")); db.add(Entry::new("service_b", "name_b", "pass_b")); db.add(Entry::new("service_c", "name_c", "pass_c")); db.save(&mut buff); } // Cursor position has to be reset before reading buff.set_position(0); let db = Database::open("test", &mut buff).unwrap(); assert_eq!(db.entries.len(), 3); } }
{ Err(Error::new(ErrorKind::InvalidData, text)) }
identifier_body
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRYPT_COST: u32 = 10; pub struct DatabaseInFile { pub db: Database, pub filepath: String } impl DatabaseInFile { pub fn save(&self) -> io::Result<()>{ self.db.save_to_file(Path::new(&self.filepath)) } } pub struct Database { bcrypt_salt: [u8; SALT_SIZE], bcrypt_pass: [u8; PASS_SIZE], pub entries: Vec<Entry> } impl Database { pub fn empty(password: &str) -> Database { let mut salt = [0u8; SALT_SIZE]; // 16bytes of salt bcrypt let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes OsRng::new().unwrap().fill_bytes(&mut salt); // TODO take only first 72 characters of input bcrypt(BCRYPT_COST, &salt, password.as_bytes(), &mut bcrypt_output); Database { bcrypt_salt: salt, bcrypt_pass: bcrypt_output, entries: Vec::new() } } pub fn open_from_file(path: &Path, password: &str) -> io::Result<Database> { // let mut file = try!(File::open(Path::new(file_path))); let mut file = try!(File::open(path)); Database::open(password, &mut file) } pub fn save_to_file(&self, path: &Path) -> io::Result<()> { // Open the file in write-only mode let mut file = try!(File::create(path)); self.save(&mut file) } pub fn open<T: Read>(password: &str, src: &mut T) -> io::Result<Database> { let mut salt = [0u8; SALT_SIZE]; // 16bytes of salt bcrypt
let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes let mut version_buffer = [0u8; 1]; match src.read(&mut version_buffer){ Ok(_) => (), Err(why) => return Err(why) }; if version_buffer[0]!= DB_VERSION { return Database::invalid_data_error(format!("Cannot process DB version {}", version_buffer[0])); } match src.read(&mut salt){ Ok(SALT_SIZE) => (), Ok(count) => return Database::invalid_data_error(format!("Bad number of bytes {} read for salt.", count)), Err(why) => return Err(why) } // Read the rest let mut buffer = Vec::new(); try!(src.read_to_end(&mut buffer)); // Run Bcrypt bcrypt(BCRYPT_COST, &salt, password.as_bytes(), &mut bcrypt_output); // Decrypt let secret = match SecretMsg::from_bytes(&buffer) { Some(msg) => msg, None => return Database::invalid_data_error("Too few bytes (less than NONCE + ZERO bytes of SecretMsg).".to_string()) }; let key = SecretKey::from_slice(&bcrypt_output); let dec = key.decrypt(&secret).unwrap(); let deserialized_entries: Vec<Entry> = serde_json::from_slice(&dec).unwrap(); Ok(Database{ bcrypt_salt: salt, bcrypt_pass: bcrypt_output, entries: deserialized_entries }) } pub fn save<T: Write>(&self, dest: &mut T) -> io::Result<()>{ let serialized = serde_json::to_string(&self.entries).unwrap(); let key = SecretKey::from_slice(&self.bcrypt_pass); let enc: SecretMsg = key.encrypt(serialized.as_bytes()); // write version try!(dest.write(&[DB_VERSION])); // write salt first try!(dest.write(&self.bcrypt_salt)); try!(dest.flush()); // write nonce + encrypted data try!(dest.write(&enc.nonce)); try!(dest.flush()); try!(dest.write(&enc.cipher)); try!(dest.flush()); Ok(()) } pub fn add(&mut self, entry: Entry){ self.entries.push(entry); } pub fn get(&self, entry_title: &str) -> Option<&Entry> { self.entries.iter().find(|entry| entry.title.eq(entry_title)) } pub fn remove(&mut self, entry_title: &str) -> bool{ let pos = self.entries .iter() .position(|entry| entry.title.eq(entry_title)); return match pos { Some(index) => { self.entries.remove(index); true } None => false } } fn invalid_data_error(text: String) -> io::Result<Database>{ Err(Error::new(ErrorKind::InvalidData, text)) } } #[cfg(test)] mod tests { use db::Entry; use db::Database; use std::io::Cursor; use std::io::Read; #[test] fn test_save_and_load() { let mut buff: Cursor<Vec<u8>> = Cursor::new(vec![]); { let mut db = Database::empty("test"); db.add(Entry::new("service_a", "name_a", "pass_a")); db.add(Entry::new("service_b", "name_b", "pass_b")); db.add(Entry::new("service_c", "name_c", "pass_c")); db.save(&mut buff); } // Cursor position has to be reset before reading buff.set_position(0); let db = Database::open("test", &mut buff).unwrap(); assert_eq!(db.entries.len(), 3); } }
random_line_split
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRYPT_COST: u32 = 10; pub struct
{ pub db: Database, pub filepath: String } impl DatabaseInFile { pub fn save(&self) -> io::Result<()>{ self.db.save_to_file(Path::new(&self.filepath)) } } pub struct Database { bcrypt_salt: [u8; SALT_SIZE], bcrypt_pass: [u8; PASS_SIZE], pub entries: Vec<Entry> } impl Database { pub fn empty(password: &str) -> Database { let mut salt = [0u8; SALT_SIZE]; // 16bytes of salt bcrypt let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes OsRng::new().unwrap().fill_bytes(&mut salt); // TODO take only first 72 characters of input bcrypt(BCRYPT_COST, &salt, password.as_bytes(), &mut bcrypt_output); Database { bcrypt_salt: salt, bcrypt_pass: bcrypt_output, entries: Vec::new() } } pub fn open_from_file(path: &Path, password: &str) -> io::Result<Database> { // let mut file = try!(File::open(Path::new(file_path))); let mut file = try!(File::open(path)); Database::open(password, &mut file) } pub fn save_to_file(&self, path: &Path) -> io::Result<()> { // Open the file in write-only mode let mut file = try!(File::create(path)); self.save(&mut file) } pub fn open<T: Read>(password: &str, src: &mut T) -> io::Result<Database> { let mut salt = [0u8; SALT_SIZE]; // 16bytes of salt bcrypt let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes let mut version_buffer = [0u8; 1]; match src.read(&mut version_buffer){ Ok(_) => (), Err(why) => return Err(why) }; if version_buffer[0]!= DB_VERSION { return Database::invalid_data_error(format!("Cannot process DB version {}", version_buffer[0])); } match src.read(&mut salt){ Ok(SALT_SIZE) => (), Ok(count) => return Database::invalid_data_error(format!("Bad number of bytes {} read for salt.", count)), Err(why) => return Err(why) } // Read the rest let mut buffer = Vec::new(); try!(src.read_to_end(&mut buffer)); // Run Bcrypt bcrypt(BCRYPT_COST, &salt, password.as_bytes(), &mut bcrypt_output); // Decrypt let secret = match SecretMsg::from_bytes(&buffer) { Some(msg) => msg, None => return Database::invalid_data_error("Too few bytes (less than NONCE + ZERO bytes of SecretMsg).".to_string()) }; let key = SecretKey::from_slice(&bcrypt_output); let dec = key.decrypt(&secret).unwrap(); let deserialized_entries: Vec<Entry> = serde_json::from_slice(&dec).unwrap(); Ok(Database{ bcrypt_salt: salt, bcrypt_pass: bcrypt_output, entries: deserialized_entries }) } pub fn save<T: Write>(&self, dest: &mut T) -> io::Result<()>{ let serialized = serde_json::to_string(&self.entries).unwrap(); let key = SecretKey::from_slice(&self.bcrypt_pass); let enc: SecretMsg = key.encrypt(serialized.as_bytes()); // write version try!(dest.write(&[DB_VERSION])); // write salt first try!(dest.write(&self.bcrypt_salt)); try!(dest.flush()); // write nonce + encrypted data try!(dest.write(&enc.nonce)); try!(dest.flush()); try!(dest.write(&enc.cipher)); try!(dest.flush()); Ok(()) } pub fn add(&mut self, entry: Entry){ self.entries.push(entry); } pub fn get(&self, entry_title: &str) -> Option<&Entry> { self.entries.iter().find(|entry| entry.title.eq(entry_title)) } pub fn remove(&mut self, entry_title: &str) -> bool{ let pos = self.entries .iter() .position(|entry| entry.title.eq(entry_title)); return match pos { Some(index) => { self.entries.remove(index); true } None => false } } fn invalid_data_error(text: String) -> io::Result<Database>{ Err(Error::new(ErrorKind::InvalidData, text)) } } #[cfg(test)] mod tests { use db::Entry; use db::Database; use std::io::Cursor; use std::io::Read; #[test] fn test_save_and_load() { let mut buff: Cursor<Vec<u8>> = Cursor::new(vec![]); { let mut db = Database::empty("test"); db.add(Entry::new("service_a", "name_a", "pass_a")); db.add(Entry::new("service_b", "name_b", "pass_b")); db.add(Entry::new("service_c", "name_c", "pass_c")); db.save(&mut buff); } // Cursor position has to be reset before reading buff.set_position(0); let db = Database::open("test", &mut buff).unwrap(); assert_eq!(db.entries.len(), 3); } }
DatabaseInFile
identifier_name
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use this module and once //! you get comfortable with this, you can always move to learning the [`rand`] crate as well. If //! the items in this module are not advanced enough for your needs, you probably want to consider //! using the full [`rand`] crate instead. //! //! # Random Number Generation //! //! Computers can't generate "true" random numbers yet, however they can approximate sequences of //! numbers that *look* random. This is called [pseudo-random number generation]. This module //! provides a set of functions (and traits) for generating pseudo-random numbers. //! //! The current set of utilities provided includes: //! //! * [`random()`] - for generating a single random value of a given type //! * [`random_range()`] - for generating a single random value of a given type in a certain range //! * [`shuffle()`] - for mixing up a slice of values (`Vec`, slices, etc.) //! * [`choose()`] - for choosing a single value from a slice of values (`Vec`, slices, etc.) //! //! See the documentation for each of those functions for more on what you can use them for. //! //! # Generating Random Values //! //! The [`random()`] function supports all of the common primitive types you would expect: //! //! * Booleans: `bool` //! * Floating-point: `f32`, `f64` //! * Integers: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize` //! * Tuples, arrays, and [many more][`Random`] //! //! It also supports types specific to the `turtle` crate: //! //! * [`Distance`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Angle`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Speed`] - any speed value in the valid range, not including instant //! * [`Color`] - colors with random red, green, blue, and alpha values (use //! [`opaque()`] to get a solid random color) //! * [`Point`] - a random point with two `f64` values greater than or equal to `0.0` and less than //! or equal to `1.0` //! //! # Random Custom Types //! //! To make types within your application capable of being used with [`random()`] or //! [`random_range()`], implement the [`Random`] or [`RandomRange`] traits respectively. See the //! documentation of those traits for more information. //! //! You typically won't need to implement [`RandomSlice`] for yourself since it is already //! implemented for slices. That being said, if your type can be represented as a slice, you can //! implement [`RandomSlice`] so it can be used with the [`shuffle()`] and [`choose()`] functions. //! //! ```rust //! use turtle::rand::RandomSlice; //! //! // This is a "newtype" wrapper around a Vec<T> which can be represented as a slice. //! #[derive(Debug, Clone)] //! struct MyVec<T>(Vec<T>); //! //! impl<T> RandomSlice for MyVec<T> { //! type Item = T; //! //! fn shuffle(&mut self) { //! (&mut *self.0 as &mut [T]).shuffle(); //! } //! //! fn choose(&self) -> Option<&Self::Item> { //! (&*self.0 as &[T]).choose() //! } //! } //! ``` //! //! [`rand`]: https://docs.rs/rand //! [pseudo-random number generation]: https://en.wikipedia.org/wiki/Pseudorandom_number_generator //! [`random()`]: fn.random.html //! [`random_range()`]: fn.random_range.html //! [`shuffle()`]: fn.shuffle.html //! [`choose()`]: fn.choose.html //! [`Random`]: trait.Random.html //! [`RandomRange`]: trait.RandomRange.html //! [`RandomSlice`]: trait.RandomSlice.html //! [`Distance`]:../type.Distance.html //! [`Angle`]:../type.Angle.html //! [`Speed`]:../speed/struct.Speed.html //! [`Color`]:../color/struct.Color.html //! [`Point`]:../struct.Point.html //! [`opaque()`]:../color/struct.Color.html#method.opaque use std::num::Wrapping; /// This trait represents any type that can have random values generated for it. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// # Example /// /// To implement this trait for your own types, call [`random()`] or [`random_range()`] for each field. /// For enums, generate a random number and pick a variant of your enum based on that. You can then /// use [`random()`] or [`random_range()`] to pick values for that variant's fields (if necessary). /// /// [`random()`]: fn.random.html /// [`random_range()`]: fn.random_range.html /// /// ```rust,no_run /// use turtle::rand::{ /// random, /// Random, /// RandomRange, /// }; /// /// #[derive(Debug, Clone)] /// struct Product { /// price: f64, /// quantity: u32, /// } /// /// impl Random for Product { /// fn random() -> Self { /// Self { /// // Prices sure are fluctuating! /// price: Random::random(), /// // This will generate a value between 1 and 15 (inclusive) /// quantity: RandomRange::random_range(0, 15), /// } /// } /// } /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// enum Door { /// Open, /// Closed, /// Locked, /// } /// /// impl Random for Door { /// fn random() -> Self { /// use Door::*; /// // Pick a variant of `Door` based on a number. /// // Notice the type in the numeric literal so Rust knows what to generate /// match RandomRange::random_range(0u8, 3) { /// 0 => Open, /// 1 => Closed, /// 2 => Locked, /// // Even though we know that the value will be between 0 and 2, the compiler does /// // not, so we instruct it to panic if this case ever occurs. /// _ => unreachable!(), /// } /// } /// } /// /// fn main() { /// // These types can now be used with the `random()` function! /// let product: Product = random(); /// let door: Door = random(); /// /// //... /// } /// ``` pub trait Random { /// Generate a single random value. /// /// # Example /// /// ```rust /// use turtle::{Color, Speed, rand::random}; /// /// // Need to annotate the type so Rust knows what you want it to generate /// let x: f32 = random(); /// let y: f32 = random(); /// /// // Works with turtle specific types too! /// let color: Color = random(); /// let speed: Speed = random(); /// ``` fn random() -> Self; } /// This trait represents any type that can have random values generated for it within a certain /// range. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// It will usually only make sense to implement this trait for types that represent a single /// value (e.g. [`Speed`], [`Color`], `f64`, `u32`, etc.). For example, if you had the type: /// /// ```rust,no_run
/// struct Product { /// price: f64, /// quantity: u32, /// } /// ``` /// /// What would `random_range(1.5, 5.2)` mean for this type? It's hard to say because while you /// could generate a random value for `price`, it doesn't make sense to generate a `quantity` /// given that range. /// /// A notable exception to this is the `Point` type. You can interpret a call to /// `random_range(Point {x: 1.0, y: 2.0}, Point {x: 5.0, y: 8.0})` as wanting to /// generate a random `Point` in the rectangle formed by the two points provided /// as arguments. /// /// [`Speed`]:../speed/struct.Speed.html /// [`Color`]:../color/struct.Color.html /// /// # Example /// /// This example demonstrates how to implement this trait for a type with a limited range of valid /// values. /// /// ```rust,no_run /// use turtle::rand::{Random, RandomRange}; /// /// // Some constants to represent the valid range of difficulty levels /// const MIN_DIFFICULTY: u32 = 1; /// const MAX_DIFFICULTY: u32 = 10; /// /// /// Represents the difficulty level of the game /// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] /// struct Difficulty(u32); /// /// impl Random for Difficulty { /// /// Generates a random difficulty within the valid range of difficulty levels /// fn random() -> Self { /// Difficulty(RandomRange::random_range(MIN_DIFFICULTY, MAX_DIFFICULTY)) /// } /// } /// /// // Choosing `u32` for the `Bound` type because that is more convenient to type than if /// // we had chosen `Difficulty`. /// // /// // Example: `random_range(1, 2)` vs. `random_range(Difficulty(1), Difficulty(2))` /// impl RandomRange<u32> for Difficulty { /// /// Generates a random difficulty level within the given range. /// /// /// /// # Panics /// /// /// /// Panics if either bound could result in a value outside the valid range /// /// of difficulties or if `low > high`. /// fn random_range(low: u32, high: u32) -> Self { /// if low < MIN_DIFFICULTY || high > MAX_DIFFICULTY { /// panic!("The boundaries must be within the valid range of difficulties"); /// } /// /// RandomRange::random_range(low, high) /// } /// } /// /// fn main() { /// use turtle::rand::{random, random_range}; /// /// // We can now generate random values for Difficulty! /// let difficulty: Difficulty = random(); /// let difficulty: Difficulty = random_range(5, 10); /// } /// ``` pub trait RandomRange<Bound = Self> { /// Generate a single random value in the given range. The value `x` that is returned will be /// such that low &le; x &le; high. /// /// The `Bound` type is used to represent the boundaries of the range of values to generate. /// For most types this will just be `Self`. /// /// # Panics /// /// Panics if `low > high`. fn random_range(low: Bound, high: Bound) -> Self; } macro_rules! impl_random { ($($typ:ty),*) => ( $( impl Random for $typ { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } impl RandomRange for $typ { fn random_range(low: Self, high: Self) -> Self { use rand::{Rng, distributions::Uniform}; let uniform = Uniform::new_inclusive(low, high); rand::thread_rng().sample(&uniform) } } )* ); } impl_random!(f32, f64, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize); // `char` does not support sampling in a range, so no RandomRange impl impl Random for char { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } // `bool` does not support sampling in a range, so no RandomRange impl impl Random for bool { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } macro_rules! impl_random_tuple { // Use variables to indicate the arity of the tuple ($($tyvar:ident),* ) => { // Trailing comma for the 1 tuple impl< $( $tyvar: Random ),* > Random for ( $( $tyvar ),*, ) { #[inline] fn random() -> Self { ( // use the $tyvar's to get the appropriate number of repeats (they're not // actually needed because type inference can figure it out) $( random::<$tyvar>() ),* // Trailing comma for the 1 tuple , ) } } } } impl Random for () { fn random() -> Self { () } } impl_random_tuple!(A); impl_random_tuple!(A, B); impl_random_tuple!(A, B, C); impl_random_tuple!(A, B, C, D); impl_random_tuple!(A, B, C, D, E); impl_random_tuple!(A, B, C, D, E, F); impl_random_tuple!(A, B, C, D, E, F, G); impl_random_tuple!(A, B, C, D, E, F, G, H); impl_random_tuple!(A, B, C, D, E, F, G, H, I); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K, L); macro_rules! impl_random_array { // Recursive, given at least one type parameter {$n:expr, $t:ident, $($ts:ident,)*} => { impl_random_array!(($n - 1), $($ts,)*); impl<T: Random> Random for [T; $n] { #[inline] fn random() -> Self { [random::<$t>(), $(random::<$ts>()),*] } } }; // Empty case (no type parameters left) {$n:expr,} => { impl<T: Random> Random for [T; $n] { fn random() -> Self { [] } } }; } impl_random_array!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); impl<T: Random> Random for Option<T> { fn random() -> Self { if Random::random() { Some(Random::random()) } else { None } } } impl<T: Random> Random for Wrapping<T> { fn random() -> Self { Wrapping(Random::random()) } } /// Generates a single random value of the type `T`. /// /// # Specifying the type to generate /// /// Since `T` can be any of a number of different types, you may need to provide a "type parameter" /// explicitly so that Rust knows what to generate. You can do this either by annotating the type /// of the variable you are assigning to or by using "turbofish" syntax to specify the type on /// the `random()` function itself. /// /// ```rust,no_run /// use turtle::{Turtle, Speed, rand::random}; /// let mut turtle = Turtle::new(); /// /// // 1. Separate out into a variable, then annotate the desired type /// let speed: Speed = random(); /// turtle.set_speed(speed); /// /// // 2. Turbofish syntax ::<T> /// turtle.set_speed(random::<Speed>()); /// ``` /// /// # Example /// /// Setting the pen color to a randomly generated color: /// /// ```rust,no_run /// use turtle::{Turtle, Color, rand::random}; /// /// let mut turtle = Turtle::new(); /// let color: Color = random(); /// // Calling `opaque()` because even the `alpha` value of the color is randomized. /// turtle.set_pen_color(color.opaque()); /// ``` pub fn random<T: Random>() -> T { <T as Random>::random() } /// Generates a random value in the given range. /// /// The value `x` that is returned will be such that low &le; x &le; high. /// /// Most types that can be used with [`random()`] can also be used with this function. For a list /// of types that can be passed into this function, see the documentation for the [`RandomRange`] /// trait. /// /// [`random()`]: fn.random.html /// [`RandomRange`]: trait.RandomRange.html /// /// # Panics /// Panics if low > high /// /// # Example: /// /// ```rust /// use turtle::rand::random_range; /// /// // Generates an f64 value between 100 and 199.99999... /// let value: f64 = random_range(100.0, 200.0); /// assert!(value >= 100.0 && value <= 200.0); /// /// // Generates a u64 value between 1000 and 3000000 /// let value = random_range::<u64, _>(1000, 3000001); /// assert!(value >= 1000 && value <= 3000001); /// /// // You do not need to specify the type if the compiler has enough information: /// fn foo(a: u64) {} /// foo(random_range(432, 1938)); /// /// // This will always return the same value because `low == `high` /// assert_eq!(random_range::<i32, _>(10i32, 10), 10); /// ``` pub fn random_range<T: RandomRange<B>, B>(low: B, high: B) -> T { RandomRange::random_range(low, high) } /// This trait represents useful random operations for slices. /// /// You will not typically use this trait directly or even import it. /// The [`shuffle()`] and [`choose()`] functions provide all the functionality of /// this trait without needing to have it in scope. /// /// [`shuffle()`]: fn.shuffle.html /// [`choose()`]: fn.choose.html pub trait RandomSlice { /// The type of item stored in this slice type Item; /// Shuffle the slice's elements in place. None of the elements will be modified during /// this process, only moved. fn shuffle(&mut self); /// Chooses a random element from this slice and returns a reference to it. /// /// If the slice is empty, returns None. fn choose(&self) -> Option<&Self::Item>; } impl<T> RandomSlice for [T] { type Item = T; fn shuffle(&mut self) { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::shuffle(self, &mut rng); } fn choose(&self) -> Option<&Self::Item> { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::choose(self, &mut rng) } } impl<T> RandomSlice for Vec<T> { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } macro_rules! impl_random_slice { // Recursive, given at least one type parameter ($n:expr, $t:ident, $($ts:ident,)*) => { impl_random_slice!(($n - 1), $($ts,)*); impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; // Empty case (no type parameters left) ($n:expr,) => { impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; } impl_random_slice!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); /// Shuffle the elements of the given slice in place. /// /// None of the elements are modified during this process, only moved. /// /// # Example /// /// ```rust,no_run /// use turtle::{rand::shuffle, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // A different order of colors every time! /// shuffle(&mut pen_colors); /// /// // Even works with Vec /// let mut pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// shuffle(&mut pen_colors); /// ``` pub fn shuffle<S: RandomSlice +?Sized>(slice: &mut S) { slice.shuffle(); } /// Chooses a random element from the slice and returns a reference to it. /// /// If the slice is empty, returns None. /// /// # Example /// /// ```rust,no_run /// use turtle::{Turtle, rand::choose, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut turtle = Turtle::new(); /// /// let pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // Choose a random pen color /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// /// // Even works with Vec /// let pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// ``` pub fn choose<S: RandomSlice +?Sized>(slice: &S) -> Option<&<S as RandomSlice>::Item> { slice.choose() }
/// #[derive(Debug, Clone)]
random_line_split
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use this module and once //! you get comfortable with this, you can always move to learning the [`rand`] crate as well. If //! the items in this module are not advanced enough for your needs, you probably want to consider //! using the full [`rand`] crate instead. //! //! # Random Number Generation //! //! Computers can't generate "true" random numbers yet, however they can approximate sequences of //! numbers that *look* random. This is called [pseudo-random number generation]. This module //! provides a set of functions (and traits) for generating pseudo-random numbers. //! //! The current set of utilities provided includes: //! //! * [`random()`] - for generating a single random value of a given type //! * [`random_range()`] - for generating a single random value of a given type in a certain range //! * [`shuffle()`] - for mixing up a slice of values (`Vec`, slices, etc.) //! * [`choose()`] - for choosing a single value from a slice of values (`Vec`, slices, etc.) //! //! See the documentation for each of those functions for more on what you can use them for. //! //! # Generating Random Values //! //! The [`random()`] function supports all of the common primitive types you would expect: //! //! * Booleans: `bool` //! * Floating-point: `f32`, `f64` //! * Integers: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize` //! * Tuples, arrays, and [many more][`Random`] //! //! It also supports types specific to the `turtle` crate: //! //! * [`Distance`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Angle`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Speed`] - any speed value in the valid range, not including instant //! * [`Color`] - colors with random red, green, blue, and alpha values (use //! [`opaque()`] to get a solid random color) //! * [`Point`] - a random point with two `f64` values greater than or equal to `0.0` and less than //! or equal to `1.0` //! //! # Random Custom Types //! //! To make types within your application capable of being used with [`random()`] or //! [`random_range()`], implement the [`Random`] or [`RandomRange`] traits respectively. See the //! documentation of those traits for more information. //! //! You typically won't need to implement [`RandomSlice`] for yourself since it is already //! implemented for slices. That being said, if your type can be represented as a slice, you can //! implement [`RandomSlice`] so it can be used with the [`shuffle()`] and [`choose()`] functions. //! //! ```rust //! use turtle::rand::RandomSlice; //! //! // This is a "newtype" wrapper around a Vec<T> which can be represented as a slice. //! #[derive(Debug, Clone)] //! struct MyVec<T>(Vec<T>); //! //! impl<T> RandomSlice for MyVec<T> { //! type Item = T; //! //! fn shuffle(&mut self) { //! (&mut *self.0 as &mut [T]).shuffle(); //! } //! //! fn choose(&self) -> Option<&Self::Item> { //! (&*self.0 as &[T]).choose() //! } //! } //! ``` //! //! [`rand`]: https://docs.rs/rand //! [pseudo-random number generation]: https://en.wikipedia.org/wiki/Pseudorandom_number_generator //! [`random()`]: fn.random.html //! [`random_range()`]: fn.random_range.html //! [`shuffle()`]: fn.shuffle.html //! [`choose()`]: fn.choose.html //! [`Random`]: trait.Random.html //! [`RandomRange`]: trait.RandomRange.html //! [`RandomSlice`]: trait.RandomSlice.html //! [`Distance`]:../type.Distance.html //! [`Angle`]:../type.Angle.html //! [`Speed`]:../speed/struct.Speed.html //! [`Color`]:../color/struct.Color.html //! [`Point`]:../struct.Point.html //! [`opaque()`]:../color/struct.Color.html#method.opaque use std::num::Wrapping; /// This trait represents any type that can have random values generated for it. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// # Example /// /// To implement this trait for your own types, call [`random()`] or [`random_range()`] for each field. /// For enums, generate a random number and pick a variant of your enum based on that. You can then /// use [`random()`] or [`random_range()`] to pick values for that variant's fields (if necessary). /// /// [`random()`]: fn.random.html /// [`random_range()`]: fn.random_range.html /// /// ```rust,no_run /// use turtle::rand::{ /// random, /// Random, /// RandomRange, /// }; /// /// #[derive(Debug, Clone)] /// struct Product { /// price: f64, /// quantity: u32, /// } /// /// impl Random for Product { /// fn random() -> Self { /// Self { /// // Prices sure are fluctuating! /// price: Random::random(), /// // This will generate a value between 1 and 15 (inclusive) /// quantity: RandomRange::random_range(0, 15), /// } /// } /// } /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// enum Door { /// Open, /// Closed, /// Locked, /// } /// /// impl Random for Door { /// fn random() -> Self { /// use Door::*; /// // Pick a variant of `Door` based on a number. /// // Notice the type in the numeric literal so Rust knows what to generate /// match RandomRange::random_range(0u8, 3) { /// 0 => Open, /// 1 => Closed, /// 2 => Locked, /// // Even though we know that the value will be between 0 and 2, the compiler does /// // not, so we instruct it to panic if this case ever occurs. /// _ => unreachable!(), /// } /// } /// } /// /// fn main() { /// // These types can now be used with the `random()` function! /// let product: Product = random(); /// let door: Door = random(); /// /// //... /// } /// ``` pub trait Random { /// Generate a single random value. /// /// # Example /// /// ```rust /// use turtle::{Color, Speed, rand::random}; /// /// // Need to annotate the type so Rust knows what you want it to generate /// let x: f32 = random(); /// let y: f32 = random(); /// /// // Works with turtle specific types too! /// let color: Color = random(); /// let speed: Speed = random(); /// ``` fn random() -> Self; } /// This trait represents any type that can have random values generated for it within a certain /// range. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// It will usually only make sense to implement this trait for types that represent a single /// value (e.g. [`Speed`], [`Color`], `f64`, `u32`, etc.). For example, if you had the type: /// /// ```rust,no_run /// #[derive(Debug, Clone)] /// struct Product { /// price: f64, /// quantity: u32, /// } /// ``` /// /// What would `random_range(1.5, 5.2)` mean for this type? It's hard to say because while you /// could generate a random value for `price`, it doesn't make sense to generate a `quantity` /// given that range. /// /// A notable exception to this is the `Point` type. You can interpret a call to /// `random_range(Point {x: 1.0, y: 2.0}, Point {x: 5.0, y: 8.0})` as wanting to /// generate a random `Point` in the rectangle formed by the two points provided /// as arguments. /// /// [`Speed`]:../speed/struct.Speed.html /// [`Color`]:../color/struct.Color.html /// /// # Example /// /// This example demonstrates how to implement this trait for a type with a limited range of valid /// values. /// /// ```rust,no_run /// use turtle::rand::{Random, RandomRange}; /// /// // Some constants to represent the valid range of difficulty levels /// const MIN_DIFFICULTY: u32 = 1; /// const MAX_DIFFICULTY: u32 = 10; /// /// /// Represents the difficulty level of the game /// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] /// struct Difficulty(u32); /// /// impl Random for Difficulty { /// /// Generates a random difficulty within the valid range of difficulty levels /// fn random() -> Self { /// Difficulty(RandomRange::random_range(MIN_DIFFICULTY, MAX_DIFFICULTY)) /// } /// } /// /// // Choosing `u32` for the `Bound` type because that is more convenient to type than if /// // we had chosen `Difficulty`. /// // /// // Example: `random_range(1, 2)` vs. `random_range(Difficulty(1), Difficulty(2))` /// impl RandomRange<u32> for Difficulty { /// /// Generates a random difficulty level within the given range. /// /// /// /// # Panics /// /// /// /// Panics if either bound could result in a value outside the valid range /// /// of difficulties or if `low > high`. /// fn random_range(low: u32, high: u32) -> Self { /// if low < MIN_DIFFICULTY || high > MAX_DIFFICULTY { /// panic!("The boundaries must be within the valid range of difficulties"); /// } /// /// RandomRange::random_range(low, high) /// } /// } /// /// fn main() { /// use turtle::rand::{random, random_range}; /// /// // We can now generate random values for Difficulty! /// let difficulty: Difficulty = random(); /// let difficulty: Difficulty = random_range(5, 10); /// } /// ``` pub trait RandomRange<Bound = Self> { /// Generate a single random value in the given range. The value `x` that is returned will be /// such that low &le; x &le; high. /// /// The `Bound` type is used to represent the boundaries of the range of values to generate. /// For most types this will just be `Self`. /// /// # Panics /// /// Panics if `low > high`. fn random_range(low: Bound, high: Bound) -> Self; } macro_rules! impl_random { ($($typ:ty),*) => ( $( impl Random for $typ { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } impl RandomRange for $typ { fn random_range(low: Self, high: Self) -> Self { use rand::{Rng, distributions::Uniform}; let uniform = Uniform::new_inclusive(low, high); rand::thread_rng().sample(&uniform) } } )* ); } impl_random!(f32, f64, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize); // `char` does not support sampling in a range, so no RandomRange impl impl Random for char { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } // `bool` does not support sampling in a range, so no RandomRange impl impl Random for bool { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } macro_rules! impl_random_tuple { // Use variables to indicate the arity of the tuple ($($tyvar:ident),* ) => { // Trailing comma for the 1 tuple impl< $( $tyvar: Random ),* > Random for ( $( $tyvar ),*, ) { #[inline] fn random() -> Self { ( // use the $tyvar's to get the appropriate number of repeats (they're not // actually needed because type inference can figure it out) $( random::<$tyvar>() ),* // Trailing comma for the 1 tuple , ) } } } } impl Random for () { fn random() -> Self { () } } impl_random_tuple!(A); impl_random_tuple!(A, B); impl_random_tuple!(A, B, C); impl_random_tuple!(A, B, C, D); impl_random_tuple!(A, B, C, D, E); impl_random_tuple!(A, B, C, D, E, F); impl_random_tuple!(A, B, C, D, E, F, G); impl_random_tuple!(A, B, C, D, E, F, G, H); impl_random_tuple!(A, B, C, D, E, F, G, H, I); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K, L); macro_rules! impl_random_array { // Recursive, given at least one type parameter {$n:expr, $t:ident, $($ts:ident,)*} => { impl_random_array!(($n - 1), $($ts,)*); impl<T: Random> Random for [T; $n] { #[inline] fn random() -> Self { [random::<$t>(), $(random::<$ts>()),*] } } }; // Empty case (no type parameters left) {$n:expr,} => { impl<T: Random> Random for [T; $n] { fn random() -> Self { [] } } }; } impl_random_array!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); impl<T: Random> Random for Option<T> { fn random() -> Self { if Random::random() { Some(Random::random()) } else { None } } } impl<T: Random> Random for Wrapping<T> { fn random() -> Self { Wrapping(Random::random()) } } /// Generates a single random value of the type `T`. /// /// # Specifying the type to generate /// /// Since `T` can be any of a number of different types, you may need to provide a "type parameter" /// explicitly so that Rust knows what to generate. You can do this either by annotating the type /// of the variable you are assigning to or by using "turbofish" syntax to specify the type on /// the `random()` function itself. /// /// ```rust,no_run /// use turtle::{Turtle, Speed, rand::random}; /// let mut turtle = Turtle::new(); /// /// // 1. Separate out into a variable, then annotate the desired type /// let speed: Speed = random(); /// turtle.set_speed(speed); /// /// // 2. Turbofish syntax ::<T> /// turtle.set_speed(random::<Speed>()); /// ``` /// /// # Example /// /// Setting the pen color to a randomly generated color: /// /// ```rust,no_run /// use turtle::{Turtle, Color, rand::random}; /// /// let mut turtle = Turtle::new(); /// let color: Color = random(); /// // Calling `opaque()` because even the `alpha` value of the color is randomized. /// turtle.set_pen_color(color.opaque()); /// ``` pub fn random<T: Random>() -> T { <T as Random>::random() } /// Generates a random value in the given range. /// /// The value `x` that is returned will be such that low &le; x &le; high. /// /// Most types that can be used with [`random()`] can also be used with this function. For a list /// of types that can be passed into this function, see the documentation for the [`RandomRange`] /// trait. /// /// [`random()`]: fn.random.html /// [`RandomRange`]: trait.RandomRange.html /// /// # Panics /// Panics if low > high /// /// # Example: /// /// ```rust /// use turtle::rand::random_range; /// /// // Generates an f64 value between 100 and 199.99999... /// let value: f64 = random_range(100.0, 200.0); /// assert!(value >= 100.0 && value <= 200.0); /// /// // Generates a u64 value between 1000 and 3000000 /// let value = random_range::<u64, _>(1000, 3000001); /// assert!(value >= 1000 && value <= 3000001); /// /// // You do not need to specify the type if the compiler has enough information: /// fn foo(a: u64) {} /// foo(random_range(432, 1938)); /// /// // This will always return the same value because `low == `high` /// assert_eq!(random_range::<i32, _>(10i32, 10), 10); /// ``` pub fn random_range<T: RandomRange<B>, B>(low: B, high: B) -> T { RandomRange::random_range(low, high) } /// This trait represents useful random operations for slices. /// /// You will not typically use this trait directly or even import it. /// The [`shuffle()`] and [`choose()`] functions provide all the functionality of /// this trait without needing to have it in scope. /// /// [`shuffle()`]: fn.shuffle.html /// [`choose()`]: fn.choose.html pub trait RandomSlice { /// The type of item stored in this slice type Item; /// Shuffle the slice's elements in place. None of the elements will be modified during /// this process, only moved. fn shuffle(&mut self); /// Chooses a random element from this slice and returns a reference to it. /// /// If the slice is empty, returns None. fn choose(&self) -> Option<&Self::Item>; } impl<T> RandomSlice for [T] { type Item = T; fn shuffle(&mut self) { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::shuffle(self, &mut rng); } fn choose(&self) -> Option<&Self::Item> { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::choose(self, &mut rng) } } impl<T> RandomSlice for Vec<T> { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } macro_rules! impl_random_slice { // Recursive, given at least one type parameter ($n:expr, $t:ident, $($ts:ident,)*) => { impl_random_slice!(($n - 1), $($ts,)*); impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; // Empty case (no type parameters left) ($n:expr,) => { impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; } impl_random_slice!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); /// Shuffle the elements of the given slice in place. /// /// None of the elements are modified during this process, only moved. /// /// # Example /// /// ```rust,no_run /// use turtle::{rand::shuffle, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // A different order of colors every time! /// shuffle(&mut pen_colors); /// /// // Even works with Vec /// let mut pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// shuffle(&mut pen_colors); /// ``` pub fn shuffle<S: RandomSlice +?Sized>(slice: &mut S)
/// Chooses a random element from the slice and returns a reference to it. /// /// If the slice is empty, returns None. /// /// # Example /// /// ```rust,no_run /// use turtle::{Turtle, rand::choose, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut turtle = Turtle::new(); /// /// let pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // Choose a random pen color /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// /// // Even works with Vec /// let pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// ``` pub fn choose<S: RandomSlice +?Sized>(slice: &S) -> Option<&<S as RandomSlice>::Item> { slice.choose() }
{ slice.shuffle(); }
identifier_body
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use this module and once //! you get comfortable with this, you can always move to learning the [`rand`] crate as well. If //! the items in this module are not advanced enough for your needs, you probably want to consider //! using the full [`rand`] crate instead. //! //! # Random Number Generation //! //! Computers can't generate "true" random numbers yet, however they can approximate sequences of //! numbers that *look* random. This is called [pseudo-random number generation]. This module //! provides a set of functions (and traits) for generating pseudo-random numbers. //! //! The current set of utilities provided includes: //! //! * [`random()`] - for generating a single random value of a given type //! * [`random_range()`] - for generating a single random value of a given type in a certain range //! * [`shuffle()`] - for mixing up a slice of values (`Vec`, slices, etc.) //! * [`choose()`] - for choosing a single value from a slice of values (`Vec`, slices, etc.) //! //! See the documentation for each of those functions for more on what you can use them for. //! //! # Generating Random Values //! //! The [`random()`] function supports all of the common primitive types you would expect: //! //! * Booleans: `bool` //! * Floating-point: `f32`, `f64` //! * Integers: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize` //! * Tuples, arrays, and [many more][`Random`] //! //! It also supports types specific to the `turtle` crate: //! //! * [`Distance`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Angle`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Speed`] - any speed value in the valid range, not including instant //! * [`Color`] - colors with random red, green, blue, and alpha values (use //! [`opaque()`] to get a solid random color) //! * [`Point`] - a random point with two `f64` values greater than or equal to `0.0` and less than //! or equal to `1.0` //! //! # Random Custom Types //! //! To make types within your application capable of being used with [`random()`] or //! [`random_range()`], implement the [`Random`] or [`RandomRange`] traits respectively. See the //! documentation of those traits for more information. //! //! You typically won't need to implement [`RandomSlice`] for yourself since it is already //! implemented for slices. That being said, if your type can be represented as a slice, you can //! implement [`RandomSlice`] so it can be used with the [`shuffle()`] and [`choose()`] functions. //! //! ```rust //! use turtle::rand::RandomSlice; //! //! // This is a "newtype" wrapper around a Vec<T> which can be represented as a slice. //! #[derive(Debug, Clone)] //! struct MyVec<T>(Vec<T>); //! //! impl<T> RandomSlice for MyVec<T> { //! type Item = T; //! //! fn shuffle(&mut self) { //! (&mut *self.0 as &mut [T]).shuffle(); //! } //! //! fn choose(&self) -> Option<&Self::Item> { //! (&*self.0 as &[T]).choose() //! } //! } //! ``` //! //! [`rand`]: https://docs.rs/rand //! [pseudo-random number generation]: https://en.wikipedia.org/wiki/Pseudorandom_number_generator //! [`random()`]: fn.random.html //! [`random_range()`]: fn.random_range.html //! [`shuffle()`]: fn.shuffle.html //! [`choose()`]: fn.choose.html //! [`Random`]: trait.Random.html //! [`RandomRange`]: trait.RandomRange.html //! [`RandomSlice`]: trait.RandomSlice.html //! [`Distance`]:../type.Distance.html //! [`Angle`]:../type.Angle.html //! [`Speed`]:../speed/struct.Speed.html //! [`Color`]:../color/struct.Color.html //! [`Point`]:../struct.Point.html //! [`opaque()`]:../color/struct.Color.html#method.opaque use std::num::Wrapping; /// This trait represents any type that can have random values generated for it. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// # Example /// /// To implement this trait for your own types, call [`random()`] or [`random_range()`] for each field. /// For enums, generate a random number and pick a variant of your enum based on that. You can then /// use [`random()`] or [`random_range()`] to pick values for that variant's fields (if necessary). /// /// [`random()`]: fn.random.html /// [`random_range()`]: fn.random_range.html /// /// ```rust,no_run /// use turtle::rand::{ /// random, /// Random, /// RandomRange, /// }; /// /// #[derive(Debug, Clone)] /// struct Product { /// price: f64, /// quantity: u32, /// } /// /// impl Random for Product { /// fn random() -> Self { /// Self { /// // Prices sure are fluctuating! /// price: Random::random(), /// // This will generate a value between 1 and 15 (inclusive) /// quantity: RandomRange::random_range(0, 15), /// } /// } /// } /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// enum Door { /// Open, /// Closed, /// Locked, /// } /// /// impl Random for Door { /// fn random() -> Self { /// use Door::*; /// // Pick a variant of `Door` based on a number. /// // Notice the type in the numeric literal so Rust knows what to generate /// match RandomRange::random_range(0u8, 3) { /// 0 => Open, /// 1 => Closed, /// 2 => Locked, /// // Even though we know that the value will be between 0 and 2, the compiler does /// // not, so we instruct it to panic if this case ever occurs. /// _ => unreachable!(), /// } /// } /// } /// /// fn main() { /// // These types can now be used with the `random()` function! /// let product: Product = random(); /// let door: Door = random(); /// /// //... /// } /// ``` pub trait Random { /// Generate a single random value. /// /// # Example /// /// ```rust /// use turtle::{Color, Speed, rand::random}; /// /// // Need to annotate the type so Rust knows what you want it to generate /// let x: f32 = random(); /// let y: f32 = random(); /// /// // Works with turtle specific types too! /// let color: Color = random(); /// let speed: Speed = random(); /// ``` fn random() -> Self; } /// This trait represents any type that can have random values generated for it within a certain /// range. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// It will usually only make sense to implement this trait for types that represent a single /// value (e.g. [`Speed`], [`Color`], `f64`, `u32`, etc.). For example, if you had the type: /// /// ```rust,no_run /// #[derive(Debug, Clone)] /// struct Product { /// price: f64, /// quantity: u32, /// } /// ``` /// /// What would `random_range(1.5, 5.2)` mean for this type? It's hard to say because while you /// could generate a random value for `price`, it doesn't make sense to generate a `quantity` /// given that range. /// /// A notable exception to this is the `Point` type. You can interpret a call to /// `random_range(Point {x: 1.0, y: 2.0}, Point {x: 5.0, y: 8.0})` as wanting to /// generate a random `Point` in the rectangle formed by the two points provided /// as arguments. /// /// [`Speed`]:../speed/struct.Speed.html /// [`Color`]:../color/struct.Color.html /// /// # Example /// /// This example demonstrates how to implement this trait for a type with a limited range of valid /// values. /// /// ```rust,no_run /// use turtle::rand::{Random, RandomRange}; /// /// // Some constants to represent the valid range of difficulty levels /// const MIN_DIFFICULTY: u32 = 1; /// const MAX_DIFFICULTY: u32 = 10; /// /// /// Represents the difficulty level of the game /// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] /// struct Difficulty(u32); /// /// impl Random for Difficulty { /// /// Generates a random difficulty within the valid range of difficulty levels /// fn random() -> Self { /// Difficulty(RandomRange::random_range(MIN_DIFFICULTY, MAX_DIFFICULTY)) /// } /// } /// /// // Choosing `u32` for the `Bound` type because that is more convenient to type than if /// // we had chosen `Difficulty`. /// // /// // Example: `random_range(1, 2)` vs. `random_range(Difficulty(1), Difficulty(2))` /// impl RandomRange<u32> for Difficulty { /// /// Generates a random difficulty level within the given range. /// /// /// /// # Panics /// /// /// /// Panics if either bound could result in a value outside the valid range /// /// of difficulties or if `low > high`. /// fn random_range(low: u32, high: u32) -> Self { /// if low < MIN_DIFFICULTY || high > MAX_DIFFICULTY { /// panic!("The boundaries must be within the valid range of difficulties"); /// } /// /// RandomRange::random_range(low, high) /// } /// } /// /// fn main() { /// use turtle::rand::{random, random_range}; /// /// // We can now generate random values for Difficulty! /// let difficulty: Difficulty = random(); /// let difficulty: Difficulty = random_range(5, 10); /// } /// ``` pub trait RandomRange<Bound = Self> { /// Generate a single random value in the given range. The value `x` that is returned will be /// such that low &le; x &le; high. /// /// The `Bound` type is used to represent the boundaries of the range of values to generate. /// For most types this will just be `Self`. /// /// # Panics /// /// Panics if `low > high`. fn random_range(low: Bound, high: Bound) -> Self; } macro_rules! impl_random { ($($typ:ty),*) => ( $( impl Random for $typ { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } impl RandomRange for $typ { fn random_range(low: Self, high: Self) -> Self { use rand::{Rng, distributions::Uniform}; let uniform = Uniform::new_inclusive(low, high); rand::thread_rng().sample(&uniform) } } )* ); } impl_random!(f32, f64, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize); // `char` does not support sampling in a range, so no RandomRange impl impl Random for char { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } // `bool` does not support sampling in a range, so no RandomRange impl impl Random for bool { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } macro_rules! impl_random_tuple { // Use variables to indicate the arity of the tuple ($($tyvar:ident),* ) => { // Trailing comma for the 1 tuple impl< $( $tyvar: Random ),* > Random for ( $( $tyvar ),*, ) { #[inline] fn random() -> Self { ( // use the $tyvar's to get the appropriate number of repeats (they're not // actually needed because type inference can figure it out) $( random::<$tyvar>() ),* // Trailing comma for the 1 tuple , ) } } } } impl Random for () { fn random() -> Self { () } } impl_random_tuple!(A); impl_random_tuple!(A, B); impl_random_tuple!(A, B, C); impl_random_tuple!(A, B, C, D); impl_random_tuple!(A, B, C, D, E); impl_random_tuple!(A, B, C, D, E, F); impl_random_tuple!(A, B, C, D, E, F, G); impl_random_tuple!(A, B, C, D, E, F, G, H); impl_random_tuple!(A, B, C, D, E, F, G, H, I); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K, L); macro_rules! impl_random_array { // Recursive, given at least one type parameter {$n:expr, $t:ident, $($ts:ident,)*} => { impl_random_array!(($n - 1), $($ts,)*); impl<T: Random> Random for [T; $n] { #[inline] fn random() -> Self { [random::<$t>(), $(random::<$ts>()),*] } } }; // Empty case (no type parameters left) {$n:expr,} => { impl<T: Random> Random for [T; $n] { fn random() -> Self { [] } } }; } impl_random_array!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); impl<T: Random> Random for Option<T> { fn random() -> Self { if Random::random()
else { None } } } impl<T: Random> Random for Wrapping<T> { fn random() -> Self { Wrapping(Random::random()) } } /// Generates a single random value of the type `T`. /// /// # Specifying the type to generate /// /// Since `T` can be any of a number of different types, you may need to provide a "type parameter" /// explicitly so that Rust knows what to generate. You can do this either by annotating the type /// of the variable you are assigning to or by using "turbofish" syntax to specify the type on /// the `random()` function itself. /// /// ```rust,no_run /// use turtle::{Turtle, Speed, rand::random}; /// let mut turtle = Turtle::new(); /// /// // 1. Separate out into a variable, then annotate the desired type /// let speed: Speed = random(); /// turtle.set_speed(speed); /// /// // 2. Turbofish syntax ::<T> /// turtle.set_speed(random::<Speed>()); /// ``` /// /// # Example /// /// Setting the pen color to a randomly generated color: /// /// ```rust,no_run /// use turtle::{Turtle, Color, rand::random}; /// /// let mut turtle = Turtle::new(); /// let color: Color = random(); /// // Calling `opaque()` because even the `alpha` value of the color is randomized. /// turtle.set_pen_color(color.opaque()); /// ``` pub fn random<T: Random>() -> T { <T as Random>::random() } /// Generates a random value in the given range. /// /// The value `x` that is returned will be such that low &le; x &le; high. /// /// Most types that can be used with [`random()`] can also be used with this function. For a list /// of types that can be passed into this function, see the documentation for the [`RandomRange`] /// trait. /// /// [`random()`]: fn.random.html /// [`RandomRange`]: trait.RandomRange.html /// /// # Panics /// Panics if low > high /// /// # Example: /// /// ```rust /// use turtle::rand::random_range; /// /// // Generates an f64 value between 100 and 199.99999... /// let value: f64 = random_range(100.0, 200.0); /// assert!(value >= 100.0 && value <= 200.0); /// /// // Generates a u64 value between 1000 and 3000000 /// let value = random_range::<u64, _>(1000, 3000001); /// assert!(value >= 1000 && value <= 3000001); /// /// // You do not need to specify the type if the compiler has enough information: /// fn foo(a: u64) {} /// foo(random_range(432, 1938)); /// /// // This will always return the same value because `low == `high` /// assert_eq!(random_range::<i32, _>(10i32, 10), 10); /// ``` pub fn random_range<T: RandomRange<B>, B>(low: B, high: B) -> T { RandomRange::random_range(low, high) } /// This trait represents useful random operations for slices. /// /// You will not typically use this trait directly or even import it. /// The [`shuffle()`] and [`choose()`] functions provide all the functionality of /// this trait without needing to have it in scope. /// /// [`shuffle()`]: fn.shuffle.html /// [`choose()`]: fn.choose.html pub trait RandomSlice { /// The type of item stored in this slice type Item; /// Shuffle the slice's elements in place. None of the elements will be modified during /// this process, only moved. fn shuffle(&mut self); /// Chooses a random element from this slice and returns a reference to it. /// /// If the slice is empty, returns None. fn choose(&self) -> Option<&Self::Item>; } impl<T> RandomSlice for [T] { type Item = T; fn shuffle(&mut self) { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::shuffle(self, &mut rng); } fn choose(&self) -> Option<&Self::Item> { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::choose(self, &mut rng) } } impl<T> RandomSlice for Vec<T> { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } macro_rules! impl_random_slice { // Recursive, given at least one type parameter ($n:expr, $t:ident, $($ts:ident,)*) => { impl_random_slice!(($n - 1), $($ts,)*); impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; // Empty case (no type parameters left) ($n:expr,) => { impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; } impl_random_slice!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); /// Shuffle the elements of the given slice in place. /// /// None of the elements are modified during this process, only moved. /// /// # Example /// /// ```rust,no_run /// use turtle::{rand::shuffle, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // A different order of colors every time! /// shuffle(&mut pen_colors); /// /// // Even works with Vec /// let mut pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// shuffle(&mut pen_colors); /// ``` pub fn shuffle<S: RandomSlice +?Sized>(slice: &mut S) { slice.shuffle(); } /// Chooses a random element from the slice and returns a reference to it. /// /// If the slice is empty, returns None. /// /// # Example /// /// ```rust,no_run /// use turtle::{Turtle, rand::choose, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut turtle = Turtle::new(); /// /// let pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // Choose a random pen color /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// /// // Even works with Vec /// let pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// ``` pub fn choose<S: RandomSlice +?Sized>(slice: &S) -> Option<&<S as RandomSlice>::Item> { slice.choose() }
{ Some(Random::random()) }
conditional_block
rand.rs
//! Utilities for generating random values //! //! This module provides a much, much simpler version of the very robust [`rand`] crate. The //! purpose of this is to give people teaching/learning Rust an easier target for doing interesting //! things with random numbers. You don't need to know very much Rust to use this module and once //! you get comfortable with this, you can always move to learning the [`rand`] crate as well. If //! the items in this module are not advanced enough for your needs, you probably want to consider //! using the full [`rand`] crate instead. //! //! # Random Number Generation //! //! Computers can't generate "true" random numbers yet, however they can approximate sequences of //! numbers that *look* random. This is called [pseudo-random number generation]. This module //! provides a set of functions (and traits) for generating pseudo-random numbers. //! //! The current set of utilities provided includes: //! //! * [`random()`] - for generating a single random value of a given type //! * [`random_range()`] - for generating a single random value of a given type in a certain range //! * [`shuffle()`] - for mixing up a slice of values (`Vec`, slices, etc.) //! * [`choose()`] - for choosing a single value from a slice of values (`Vec`, slices, etc.) //! //! See the documentation for each of those functions for more on what you can use them for. //! //! # Generating Random Values //! //! The [`random()`] function supports all of the common primitive types you would expect: //! //! * Booleans: `bool` //! * Floating-point: `f32`, `f64` //! * Integers: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize` //! * Tuples, arrays, and [many more][`Random`] //! //! It also supports types specific to the `turtle` crate: //! //! * [`Distance`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Angle`] - `f64` values greater than or equal to `0.0` and less than or equal to `1.0` //! * [`Speed`] - any speed value in the valid range, not including instant //! * [`Color`] - colors with random red, green, blue, and alpha values (use //! [`opaque()`] to get a solid random color) //! * [`Point`] - a random point with two `f64` values greater than or equal to `0.0` and less than //! or equal to `1.0` //! //! # Random Custom Types //! //! To make types within your application capable of being used with [`random()`] or //! [`random_range()`], implement the [`Random`] or [`RandomRange`] traits respectively. See the //! documentation of those traits for more information. //! //! You typically won't need to implement [`RandomSlice`] for yourself since it is already //! implemented for slices. That being said, if your type can be represented as a slice, you can //! implement [`RandomSlice`] so it can be used with the [`shuffle()`] and [`choose()`] functions. //! //! ```rust //! use turtle::rand::RandomSlice; //! //! // This is a "newtype" wrapper around a Vec<T> which can be represented as a slice. //! #[derive(Debug, Clone)] //! struct MyVec<T>(Vec<T>); //! //! impl<T> RandomSlice for MyVec<T> { //! type Item = T; //! //! fn shuffle(&mut self) { //! (&mut *self.0 as &mut [T]).shuffle(); //! } //! //! fn choose(&self) -> Option<&Self::Item> { //! (&*self.0 as &[T]).choose() //! } //! } //! ``` //! //! [`rand`]: https://docs.rs/rand //! [pseudo-random number generation]: https://en.wikipedia.org/wiki/Pseudorandom_number_generator //! [`random()`]: fn.random.html //! [`random_range()`]: fn.random_range.html //! [`shuffle()`]: fn.shuffle.html //! [`choose()`]: fn.choose.html //! [`Random`]: trait.Random.html //! [`RandomRange`]: trait.RandomRange.html //! [`RandomSlice`]: trait.RandomSlice.html //! [`Distance`]:../type.Distance.html //! [`Angle`]:../type.Angle.html //! [`Speed`]:../speed/struct.Speed.html //! [`Color`]:../color/struct.Color.html //! [`Point`]:../struct.Point.html //! [`opaque()`]:../color/struct.Color.html#method.opaque use std::num::Wrapping; /// This trait represents any type that can have random values generated for it. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// # Example /// /// To implement this trait for your own types, call [`random()`] or [`random_range()`] for each field. /// For enums, generate a random number and pick a variant of your enum based on that. You can then /// use [`random()`] or [`random_range()`] to pick values for that variant's fields (if necessary). /// /// [`random()`]: fn.random.html /// [`random_range()`]: fn.random_range.html /// /// ```rust,no_run /// use turtle::rand::{ /// random, /// Random, /// RandomRange, /// }; /// /// #[derive(Debug, Clone)] /// struct Product { /// price: f64, /// quantity: u32, /// } /// /// impl Random for Product { /// fn random() -> Self { /// Self { /// // Prices sure are fluctuating! /// price: Random::random(), /// // This will generate a value between 1 and 15 (inclusive) /// quantity: RandomRange::random_range(0, 15), /// } /// } /// } /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// enum Door { /// Open, /// Closed, /// Locked, /// } /// /// impl Random for Door { /// fn random() -> Self { /// use Door::*; /// // Pick a variant of `Door` based on a number. /// // Notice the type in the numeric literal so Rust knows what to generate /// match RandomRange::random_range(0u8, 3) { /// 0 => Open, /// 1 => Closed, /// 2 => Locked, /// // Even though we know that the value will be between 0 and 2, the compiler does /// // not, so we instruct it to panic if this case ever occurs. /// _ => unreachable!(), /// } /// } /// } /// /// fn main() { /// // These types can now be used with the `random()` function! /// let product: Product = random(); /// let door: Door = random(); /// /// //... /// } /// ``` pub trait Random { /// Generate a single random value. /// /// # Example /// /// ```rust /// use turtle::{Color, Speed, rand::random}; /// /// // Need to annotate the type so Rust knows what you want it to generate /// let x: f32 = random(); /// let y: f32 = random(); /// /// // Works with turtle specific types too! /// let color: Color = random(); /// let speed: Speed = random(); /// ``` fn random() -> Self; } /// This trait represents any type that can have random values generated for it within a certain /// range. /// /// **Tip:** There is a list later on this page that shows many of the types that implement this /// trait. /// /// It will usually only make sense to implement this trait for types that represent a single /// value (e.g. [`Speed`], [`Color`], `f64`, `u32`, etc.). For example, if you had the type: /// /// ```rust,no_run /// #[derive(Debug, Clone)] /// struct Product { /// price: f64, /// quantity: u32, /// } /// ``` /// /// What would `random_range(1.5, 5.2)` mean for this type? It's hard to say because while you /// could generate a random value for `price`, it doesn't make sense to generate a `quantity` /// given that range. /// /// A notable exception to this is the `Point` type. You can interpret a call to /// `random_range(Point {x: 1.0, y: 2.0}, Point {x: 5.0, y: 8.0})` as wanting to /// generate a random `Point` in the rectangle formed by the two points provided /// as arguments. /// /// [`Speed`]:../speed/struct.Speed.html /// [`Color`]:../color/struct.Color.html /// /// # Example /// /// This example demonstrates how to implement this trait for a type with a limited range of valid /// values. /// /// ```rust,no_run /// use turtle::rand::{Random, RandomRange}; /// /// // Some constants to represent the valid range of difficulty levels /// const MIN_DIFFICULTY: u32 = 1; /// const MAX_DIFFICULTY: u32 = 10; /// /// /// Represents the difficulty level of the game /// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] /// struct Difficulty(u32); /// /// impl Random for Difficulty { /// /// Generates a random difficulty within the valid range of difficulty levels /// fn random() -> Self { /// Difficulty(RandomRange::random_range(MIN_DIFFICULTY, MAX_DIFFICULTY)) /// } /// } /// /// // Choosing `u32` for the `Bound` type because that is more convenient to type than if /// // we had chosen `Difficulty`. /// // /// // Example: `random_range(1, 2)` vs. `random_range(Difficulty(1), Difficulty(2))` /// impl RandomRange<u32> for Difficulty { /// /// Generates a random difficulty level within the given range. /// /// /// /// # Panics /// /// /// /// Panics if either bound could result in a value outside the valid range /// /// of difficulties or if `low > high`. /// fn random_range(low: u32, high: u32) -> Self { /// if low < MIN_DIFFICULTY || high > MAX_DIFFICULTY { /// panic!("The boundaries must be within the valid range of difficulties"); /// } /// /// RandomRange::random_range(low, high) /// } /// } /// /// fn main() { /// use turtle::rand::{random, random_range}; /// /// // We can now generate random values for Difficulty! /// let difficulty: Difficulty = random(); /// let difficulty: Difficulty = random_range(5, 10); /// } /// ``` pub trait RandomRange<Bound = Self> { /// Generate a single random value in the given range. The value `x` that is returned will be /// such that low &le; x &le; high. /// /// The `Bound` type is used to represent the boundaries of the range of values to generate. /// For most types this will just be `Self`. /// /// # Panics /// /// Panics if `low > high`. fn random_range(low: Bound, high: Bound) -> Self; } macro_rules! impl_random { ($($typ:ty),*) => ( $( impl Random for $typ { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } impl RandomRange for $typ { fn random_range(low: Self, high: Self) -> Self { use rand::{Rng, distributions::Uniform}; let uniform = Uniform::new_inclusive(low, high); rand::thread_rng().sample(&uniform) } } )* ); } impl_random!(f32, f64, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize); // `char` does not support sampling in a range, so no RandomRange impl impl Random for char { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } // `bool` does not support sampling in a range, so no RandomRange impl impl Random for bool { fn random() -> Self { use rand::Rng; rand::thread_rng().gen() } } macro_rules! impl_random_tuple { // Use variables to indicate the arity of the tuple ($($tyvar:ident),* ) => { // Trailing comma for the 1 tuple impl< $( $tyvar: Random ),* > Random for ( $( $tyvar ),*, ) { #[inline] fn random() -> Self { ( // use the $tyvar's to get the appropriate number of repeats (they're not // actually needed because type inference can figure it out) $( random::<$tyvar>() ),* // Trailing comma for the 1 tuple , ) } } } } impl Random for () { fn random() -> Self { () } } impl_random_tuple!(A); impl_random_tuple!(A, B); impl_random_tuple!(A, B, C); impl_random_tuple!(A, B, C, D); impl_random_tuple!(A, B, C, D, E); impl_random_tuple!(A, B, C, D, E, F); impl_random_tuple!(A, B, C, D, E, F, G); impl_random_tuple!(A, B, C, D, E, F, G, H); impl_random_tuple!(A, B, C, D, E, F, G, H, I); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K); impl_random_tuple!(A, B, C, D, E, F, G, H, I, J, K, L); macro_rules! impl_random_array { // Recursive, given at least one type parameter {$n:expr, $t:ident, $($ts:ident,)*} => { impl_random_array!(($n - 1), $($ts,)*); impl<T: Random> Random for [T; $n] { #[inline] fn random() -> Self { [random::<$t>(), $(random::<$ts>()),*] } } }; // Empty case (no type parameters left) {$n:expr,} => { impl<T: Random> Random for [T; $n] { fn random() -> Self { [] } } }; } impl_random_array!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); impl<T: Random> Random for Option<T> { fn random() -> Self { if Random::random() { Some(Random::random()) } else { None } } } impl<T: Random> Random for Wrapping<T> { fn random() -> Self { Wrapping(Random::random()) } } /// Generates a single random value of the type `T`. /// /// # Specifying the type to generate /// /// Since `T` can be any of a number of different types, you may need to provide a "type parameter" /// explicitly so that Rust knows what to generate. You can do this either by annotating the type /// of the variable you are assigning to or by using "turbofish" syntax to specify the type on /// the `random()` function itself. /// /// ```rust,no_run /// use turtle::{Turtle, Speed, rand::random}; /// let mut turtle = Turtle::new(); /// /// // 1. Separate out into a variable, then annotate the desired type /// let speed: Speed = random(); /// turtle.set_speed(speed); /// /// // 2. Turbofish syntax ::<T> /// turtle.set_speed(random::<Speed>()); /// ``` /// /// # Example /// /// Setting the pen color to a randomly generated color: /// /// ```rust,no_run /// use turtle::{Turtle, Color, rand::random}; /// /// let mut turtle = Turtle::new(); /// let color: Color = random(); /// // Calling `opaque()` because even the `alpha` value of the color is randomized. /// turtle.set_pen_color(color.opaque()); /// ``` pub fn random<T: Random>() -> T { <T as Random>::random() } /// Generates a random value in the given range. /// /// The value `x` that is returned will be such that low &le; x &le; high. /// /// Most types that can be used with [`random()`] can also be used with this function. For a list /// of types that can be passed into this function, see the documentation for the [`RandomRange`] /// trait. /// /// [`random()`]: fn.random.html /// [`RandomRange`]: trait.RandomRange.html /// /// # Panics /// Panics if low > high /// /// # Example: /// /// ```rust /// use turtle::rand::random_range; /// /// // Generates an f64 value between 100 and 199.99999... /// let value: f64 = random_range(100.0, 200.0); /// assert!(value >= 100.0 && value <= 200.0); /// /// // Generates a u64 value between 1000 and 3000000 /// let value = random_range::<u64, _>(1000, 3000001); /// assert!(value >= 1000 && value <= 3000001); /// /// // You do not need to specify the type if the compiler has enough information: /// fn foo(a: u64) {} /// foo(random_range(432, 1938)); /// /// // This will always return the same value because `low == `high` /// assert_eq!(random_range::<i32, _>(10i32, 10), 10); /// ``` pub fn random_range<T: RandomRange<B>, B>(low: B, high: B) -> T { RandomRange::random_range(low, high) } /// This trait represents useful random operations for slices. /// /// You will not typically use this trait directly or even import it. /// The [`shuffle()`] and [`choose()`] functions provide all the functionality of /// this trait without needing to have it in scope. /// /// [`shuffle()`]: fn.shuffle.html /// [`choose()`]: fn.choose.html pub trait RandomSlice { /// The type of item stored in this slice type Item; /// Shuffle the slice's elements in place. None of the elements will be modified during /// this process, only moved. fn shuffle(&mut self); /// Chooses a random element from this slice and returns a reference to it. /// /// If the slice is empty, returns None. fn choose(&self) -> Option<&Self::Item>; } impl<T> RandomSlice for [T] { type Item = T; fn
(&mut self) { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::shuffle(self, &mut rng); } fn choose(&self) -> Option<&Self::Item> { use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); <Self as SliceRandom>::choose(self, &mut rng) } } impl<T> RandomSlice for Vec<T> { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } macro_rules! impl_random_slice { // Recursive, given at least one type parameter ($n:expr, $t:ident, $($ts:ident,)*) => { impl_random_slice!(($n - 1), $($ts,)*); impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; // Empty case (no type parameters left) ($n:expr,) => { impl<T> RandomSlice for [T; $n] { type Item = T; fn shuffle(&mut self) { (&mut *self as &mut [T]).shuffle(); } fn choose(&self) -> Option<&Self::Item> { (&*self as &[T]).choose() } } }; } impl_random_slice!(32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,); /// Shuffle the elements of the given slice in place. /// /// None of the elements are modified during this process, only moved. /// /// # Example /// /// ```rust,no_run /// use turtle::{rand::shuffle, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // A different order of colors every time! /// shuffle(&mut pen_colors); /// /// // Even works with Vec /// let mut pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// shuffle(&mut pen_colors); /// ``` pub fn shuffle<S: RandomSlice +?Sized>(slice: &mut S) { slice.shuffle(); } /// Chooses a random element from the slice and returns a reference to it. /// /// If the slice is empty, returns None. /// /// # Example /// /// ```rust,no_run /// use turtle::{Turtle, rand::choose, colors::{RED, BLUE, GREEN, YELLOW}}; /// /// let mut turtle = Turtle::new(); /// /// let pen_colors = [RED, BLUE, GREEN, YELLOW]; /// // Choose a random pen color /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// /// // Even works with Vec /// let pen_colors = vec![RED, BLUE, GREEN, YELLOW]; /// let chosen_color = choose(&pen_colors).copied().unwrap(); /// turtle.set_pen_color(chosen_color); /// ``` pub fn choose<S: RandomSlice +?Sized>(slice: &S) -> Option<&<S as RandomSlice>::Item> { slice.choose() }
shuffle
identifier_name
minimax_test.rs
use crate::minimax::{Minimax, MinimaxConfig, MinimaxMovesSorting, MinimaxType}; use env_logger; use oppai_field::construct_field::construct_field; use oppai_field::player::Player; use oppai_test_images::*; use rand::SeedableRng; use rand_xorshift::XorShiftRng; const SEED: [u8; 16] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53]; const MINIMAX_CONFIG_NEGASCOUT: MinimaxConfig = MinimaxConfig { threads_count: 1, minimax_type: MinimaxType::NegaScout, minimax_moves_sorting: MinimaxMovesSorting::TrajectoriesCount, hash_table_size: 10_000, rebuild_trajectories: false, }; const MINIMAX_CONFIG_MTDF: MinimaxConfig = MinimaxConfig { threads_count: 1, minimax_type: MinimaxType::MTDF, minimax_moves_sorting: MinimaxMovesSorting::TrajectoriesCount, hash_table_size: 10_000,
macro_rules! minimax_test { ($(#[$($attr:meta),+])* $name:ident, $config:ident, $image:ident, $depth:expr) => { #[test] $(#[$($attr),+])* fn $name() { env_logger::try_init().ok(); let mut rng = XorShiftRng::from_seed(SEED); let mut field = construct_field(&mut rng, $image.image); let minimax = Minimax::new($config); let pos = minimax.minimax(&mut field, Player::Red, &mut rng, $depth); assert_eq!(pos, Some(field.to_pos($image.solution.0, $image.solution.1))); } } } minimax_test!(negascout_1, MINIMAX_CONFIG_NEGASCOUT, IMAGE_1, 8); minimax_test!(negascout_2, MINIMAX_CONFIG_NEGASCOUT, IMAGE_2, 8); minimax_test!(negascout_3, MINIMAX_CONFIG_NEGASCOUT, IMAGE_3, 8); minimax_test!(negascout_4, MINIMAX_CONFIG_NEGASCOUT, IMAGE_4, 8); minimax_test!(negascout_5, MINIMAX_CONFIG_NEGASCOUT, IMAGE_5, 8); minimax_test!(negascout_6, MINIMAX_CONFIG_NEGASCOUT, IMAGE_6, 8); minimax_test!( #[ignore] negascout_7, MINIMAX_CONFIG_NEGASCOUT, IMAGE_7, 10 ); minimax_test!(negascout_8, MINIMAX_CONFIG_NEGASCOUT, IMAGE_8, 8); minimax_test!( #[ignore] negascout_9, MINIMAX_CONFIG_NEGASCOUT, IMAGE_9, 10 ); minimax_test!(negascout_10, MINIMAX_CONFIG_NEGASCOUT, IMAGE_10, 8); minimax_test!( #[ignore] negascout_11, MINIMAX_CONFIG_NEGASCOUT, IMAGE_11, 12 ); minimax_test!(negascout_12, MINIMAX_CONFIG_NEGASCOUT, IMAGE_12, 8); minimax_test!(negascout_13, MINIMAX_CONFIG_NEGASCOUT, IMAGE_13, 8); minimax_test!(negascout_14, MINIMAX_CONFIG_NEGASCOUT, IMAGE_14, 8); minimax_test!(mtdf_1, MINIMAX_CONFIG_MTDF, IMAGE_1, 8); minimax_test!(mtdf_2, MINIMAX_CONFIG_MTDF, IMAGE_2, 8); minimax_test!(mtdf_3, MINIMAX_CONFIG_MTDF, IMAGE_3, 8); minimax_test!(mtdf_4, MINIMAX_CONFIG_MTDF, IMAGE_4, 8); minimax_test!(mtdf_5, MINIMAX_CONFIG_MTDF, IMAGE_5, 8); minimax_test!(mtdf_6, MINIMAX_CONFIG_MTDF, IMAGE_6, 8); minimax_test!( #[ignore] mtdf_7, MINIMAX_CONFIG_MTDF, IMAGE_7, 10 ); minimax_test!(mtdf_8, MINIMAX_CONFIG_MTDF, IMAGE_8, 8); minimax_test!( #[ignore] mtdf_9, MINIMAX_CONFIG_MTDF, IMAGE_9, 10 ); minimax_test!(mtdf_10, MINIMAX_CONFIG_MTDF, IMAGE_10, 8); minimax_test!( #[ignore] mtdf_11, MINIMAX_CONFIG_MTDF, IMAGE_11, 12 ); minimax_test!(mtdf_12, MINIMAX_CONFIG_MTDF, IMAGE_12, 8); minimax_test!(mtdf_13, MINIMAX_CONFIG_MTDF, IMAGE_13, 8); minimax_test!(mtdf_14, MINIMAX_CONFIG_MTDF, IMAGE_14, 8);
rebuild_trajectories: false, };
random_line_split
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance_timeline; pub mod user_interaction; use dom::globalscope::GlobalScope; use script_thread::{Runnable, RunnableWrapper}; use std::result::Result; pub trait TaskSource { fn queue_with_wrapper<T>(&self, msg: Box<T>, wrapper: &RunnableWrapper) -> Result<(), ()> where T: Runnable + Send +'static; fn
<T: Runnable + Send +'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> { self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
queue
identifier_name
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance_timeline; pub mod user_interaction; use dom::globalscope::GlobalScope; use script_thread::{Runnable, RunnableWrapper}; use std::result::Result; pub trait TaskSource { fn queue_with_wrapper<T>(&self, msg: Box<T>, wrapper: &RunnableWrapper)
self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
-> Result<(), ()> where T: Runnable + Send + 'static; fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> {
random_line_split
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance_timeline; pub mod user_interaction; use dom::globalscope::GlobalScope; use script_thread::{Runnable, RunnableWrapper}; use std::result::Result; pub trait TaskSource { fn queue_with_wrapper<T>(&self, msg: Box<T>, wrapper: &RunnableWrapper) -> Result<(), ()> where T: Runnable + Send +'static; fn queue<T: Runnable + Send +'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()>
}
{ self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) }
identifier_body
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capacity can always //! be a power of two; also, inserts and lookups need to be very fast, so we can make the //! hash function a simple bitmask (assuming `page_id`s are relatively randomly distributed). //! In theory this means we can also omit bounds checking, but we'll see (I don't have any //! `unsafe` blocks in this project yet). //! Because we want lots of caching and we're assuming our inputs are pretty random, we can //! probably get away with open addressing by just incrementing the hash. //! We never remove from these tables, so we can save on the space / complexity by not //! implementing this mechanism. //! This shows a pretty reliable few point bump over `fnv` in lookups and like 10-15% in //! inserts, which is pretty promising (hasn't been tested yet though). // Speed comparison: w/ RT=.5 and BC=6, speedup is almost 50% // Memory comparison: use std::fmt::Debug; // TODO: tweak this? const RESIZE_THRESHOLD: f64 = 0.5; // resize when table is 1/2 full // TODO: tweak this? const BEGIN_CAP: usize = 6; // 2^6 = 64 // TODO: verify this? const ENTRY_RESERVED: u32 = ::std::u32::MAX; // u32::max_value() on nightly pub type IHMap = IHM<u32>; pub type IHSet = IHM<()>; /// Entry in our hash map: Instead of using `Option` or some unsafe magic, we reserve /// one potential value as "none" (where `page_id` is `INT_MAX`). This saves a lot on space /// (probably about 50% of what it would be) while still being fast (it's like 20% /// faster than `Option<Entry<T>>` because of caching or something). /// The idea is stolen from the `optional` crate, but I like my interface better. #[derive(Debug, Clone, Copy)] pub(super) struct Entry<T: Debug+Copy+Default> { key: u32, val: T, } impl<T: Debug+Copy+Default> Entry<T> { #[inline] fn is_none(&self) -> bool { self.key == ENTRY_RESERVED } #[inline] fn is_some(&self) -> bool { self.is_none() == false } #[inline] fn get(&self) -> Option<&Self> { // the fact that this isn't in `optional` makes me worry it's slow? // Am I crazy? if self.is_none() { None } else { Some(self) } } #[inline] fn none() -> Self { Entry { key: ENTRY_RESERVED, val: Default::default(), } } } /// Integer hash map: map keyed by integers for a very specific application. /// Has some restrictions: Can't remove entries, capacity must be a power of 2, /// input must be relatively randomly distributed, etc. #[derive(Debug, Clone)] pub struct IHM<T: Debug+Copy+Default> { size: usize, cap_exp: usize, // capacity is 2**this data: Box<[Entry<T>]>, } impl<T: Debug+Copy+Default> Default for IHM<T> { fn default() -> Self { IHM::with_capacity(BEGIN_CAP) } } impl<T: Debug+Copy+Default> IHM<T> { #[inline] fn hash(&self, n: u32) -> usize { // n % self.capacity() // last `cap_exp` bytes of `n` (n & ((1 << self.cap_exp) - 1)) as usize } #[inline] fn hash_with(n: usize, cap: usize) -> usize { // way to `hash` without requiring a self-borrow :/ // don't mix up the arg order :/ (n & ((1 << cap) -1)) as usize } // uhhhhh note this is cap_exp NOT real capacity // prediction: I forget this and run out of mem :/ pub fn with_capacity(cap_exp: usize) -> Self { // not sure what the proper way to create a big boxed array // without just making it on the stack first // except using a vector let v: Vec<Entry<T>> = vec![Entry::none(); 1<<cap_exp]; IHM { size: 0, cap_exp, data: v.into_boxed_slice(), } } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn len(&self) -> usize { self.size } pub fn capacity(&self) -> usize { 1 << self.cap_exp } pub fn clear(&mut self) { for entry in self.data.iter_mut() { *entry = Entry::none(); } } pub fn contains_key(&self, key: u32) -> bool { let mut addr = self.hash(key); loop { // For now let's see how well rustc optimizes this // but this might need to be rewritten to be faster // because it'll happen a lot // TODO examine asm // TODO eventually don't bounds check // this leads to a few points of speedup // but it also introduces the possibility of a segfault // maybe until everything is stable and if there are no crashes then revisit /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return false, Some(e) if e.key == key => return true, Some(_) => addr = Self::hash_with(addr+1, self.cap_exp), } } } fn resize(&mut self) { // NOTE this doesn't change in-place. It will briefly consume 50% more // mem than in its final state due to this redundancy let mut other = Self::with_capacity(self.cap_exp + 1); assert_eq!(other.capacity(), 2*self.capacity()); for entry in self.data.iter() { if entry.is_some() { other.insert_elem(entry.key, entry.val); } } *self = other; } fn insert_elem(&mut self, key: u32, val: T) { // TODO maybe could add some cool simd stuff or manual unrolling here if self.len() as f64 / self.capacity() as f64 >= RESIZE_THRESHOLD { self.resize(); } self.size += 1; let mut addr = self.hash(key); loop { let entry = &mut self.data[addr]; //let entry = unsafe { self.data.get_unchecked_mut(addr) }; if entry.is_none() { // wasn't present, insert and continue *entry = Entry { key, val }; return; } else if entry.key == key { // entry already there return; } else { // otherwise increment addr and try again //addr = self.hash(addr as u32 + 1); //addr = (addr+1) & ((1 << self.cap_exp) - 1) addr = Self::hash_with(addr+1, self.cap_exp); } } } } use std::iter::FilterMap; use std::slice::Iter; type IterType<'a,T> = FilterMap<Iter<'a, Entry<T>>, for<'r> fn(&'r Entry<T>) -> Option<u32>>; impl IHM<()> { pub fn
(&mut self, key: u32) { self.insert_elem(key, ()) } //pub(super) fn keys<'a>(&'a self) -> IterType<'a, ()> { pub(super) fn keys(&self) -> IterType<()> { self.data.iter().filter_map(|i| i.get().map(|e| e.key)) } } impl IHM<u32> { pub fn insert(&mut self, key: u32, val: u32) { self.insert_elem(key, val) } pub fn get(&self, key: u32) -> Option<u32> { let mut addr = self.hash(key); loop { /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return None, Some(e) if e.key == key => return Some(e.val), Some(_) => addr = (addr+1) & ((1 << self.cap_exp) - 1), } } } }
insert
identifier_name
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capacity can always //! be a power of two; also, inserts and lookups need to be very fast, so we can make the //! hash function a simple bitmask (assuming `page_id`s are relatively randomly distributed). //! In theory this means we can also omit bounds checking, but we'll see (I don't have any //! `unsafe` blocks in this project yet). //! Because we want lots of caching and we're assuming our inputs are pretty random, we can //! probably get away with open addressing by just incrementing the hash. //! We never remove from these tables, so we can save on the space / complexity by not //! implementing this mechanism. //! This shows a pretty reliable few point bump over `fnv` in lookups and like 10-15% in //! inserts, which is pretty promising (hasn't been tested yet though). // Speed comparison: w/ RT=.5 and BC=6, speedup is almost 50% // Memory comparison: use std::fmt::Debug; // TODO: tweak this? const RESIZE_THRESHOLD: f64 = 0.5; // resize when table is 1/2 full // TODO: tweak this? const BEGIN_CAP: usize = 6; // 2^6 = 64 // TODO: verify this? const ENTRY_RESERVED: u32 = ::std::u32::MAX; // u32::max_value() on nightly pub type IHMap = IHM<u32>; pub type IHSet = IHM<()>; /// Entry in our hash map: Instead of using `Option` or some unsafe magic, we reserve /// one potential value as "none" (where `page_id` is `INT_MAX`). This saves a lot on space /// (probably about 50% of what it would be) while still being fast (it's like 20% /// faster than `Option<Entry<T>>` because of caching or something). /// The idea is stolen from the `optional` crate, but I like my interface better. #[derive(Debug, Clone, Copy)] pub(super) struct Entry<T: Debug+Copy+Default> { key: u32, val: T, } impl<T: Debug+Copy+Default> Entry<T> { #[inline] fn is_none(&self) -> bool { self.key == ENTRY_RESERVED } #[inline] fn is_some(&self) -> bool { self.is_none() == false } #[inline] fn get(&self) -> Option<&Self> { // the fact that this isn't in `optional` makes me worry it's slow? // Am I crazy? if self.is_none() { None } else { Some(self) } } #[inline] fn none() -> Self { Entry { key: ENTRY_RESERVED, val: Default::default(), } } } /// Integer hash map: map keyed by integers for a very specific application. /// Has some restrictions: Can't remove entries, capacity must be a power of 2, /// input must be relatively randomly distributed, etc. #[derive(Debug, Clone)] pub struct IHM<T: Debug+Copy+Default> { size: usize, cap_exp: usize, // capacity is 2**this data: Box<[Entry<T>]>, } impl<T: Debug+Copy+Default> Default for IHM<T> { fn default() -> Self { IHM::with_capacity(BEGIN_CAP) } } impl<T: Debug+Copy+Default> IHM<T> { #[inline] fn hash(&self, n: u32) -> usize { // n % self.capacity() // last `cap_exp` bytes of `n` (n & ((1 << self.cap_exp) - 1)) as usize } #[inline] fn hash_with(n: usize, cap: usize) -> usize { // way to `hash` without requiring a self-borrow :/ // don't mix up the arg order :/ (n & ((1 << cap) -1)) as usize } // uhhhhh note this is cap_exp NOT real capacity // prediction: I forget this and run out of mem :/ pub fn with_capacity(cap_exp: usize) -> Self { // not sure what the proper way to create a big boxed array // without just making it on the stack first // except using a vector let v: Vec<Entry<T>> = vec![Entry::none(); 1<<cap_exp]; IHM { size: 0, cap_exp, data: v.into_boxed_slice(), } } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn len(&self) -> usize { self.size } pub fn capacity(&self) -> usize { 1 << self.cap_exp } pub fn clear(&mut self) { for entry in self.data.iter_mut() { *entry = Entry::none(); } } pub fn contains_key(&self, key: u32) -> bool { let mut addr = self.hash(key); loop { // For now let's see how well rustc optimizes this // but this might need to be rewritten to be faster // because it'll happen a lot // TODO examine asm // TODO eventually don't bounds check // this leads to a few points of speedup // but it also introduces the possibility of a segfault // maybe until everything is stable and if there are no crashes then revisit /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return false, Some(e) if e.key == key => return true, Some(_) => addr = Self::hash_with(addr+1, self.cap_exp), } } } fn resize(&mut self) { // NOTE this doesn't change in-place. It will briefly consume 50% more // mem than in its final state due to this redundancy let mut other = Self::with_capacity(self.cap_exp + 1); assert_eq!(other.capacity(), 2*self.capacity()); for entry in self.data.iter() { if entry.is_some() { other.insert_elem(entry.key, entry.val); } } *self = other; } fn insert_elem(&mut self, key: u32, val: T) { // TODO maybe could add some cool simd stuff or manual unrolling here if self.len() as f64 / self.capacity() as f64 >= RESIZE_THRESHOLD { self.resize(); } self.size += 1; let mut addr = self.hash(key); loop { let entry = &mut self.data[addr]; //let entry = unsafe { self.data.get_unchecked_mut(addr) }; if entry.is_none() { // wasn't present, insert and continue *entry = Entry { key, val }; return; } else if entry.key == key { // entry already there return; } else { // otherwise increment addr and try again //addr = self.hash(addr as u32 + 1); //addr = (addr+1) & ((1 << self.cap_exp) - 1) addr = Self::hash_with(addr+1, self.cap_exp); } } } } use std::iter::FilterMap; use std::slice::Iter; type IterType<'a,T> = FilterMap<Iter<'a, Entry<T>>, for<'r> fn(&'r Entry<T>) -> Option<u32>>; impl IHM<()> { pub fn insert(&mut self, key: u32) { self.insert_elem(key, ()) } //pub(super) fn keys<'a>(&'a self) -> IterType<'a, ()> { pub(super) fn keys(&self) -> IterType<()> { self.data.iter().filter_map(|i| i.get().map(|e| e.key)) } } impl IHM<u32> { pub fn insert(&mut self, key: u32, val: u32)
pub fn get(&self, key: u32) -> Option<u32> { let mut addr = self.hash(key); loop { /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return None, Some(e) if e.key == key => return Some(e.val), Some(_) => addr = (addr+1) & ((1 << self.cap_exp) - 1), } } } }
{ self.insert_elem(key, val) }
identifier_body
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capacity can always //! be a power of two; also, inserts and lookups need to be very fast, so we can make the //! hash function a simple bitmask (assuming `page_id`s are relatively randomly distributed). //! In theory this means we can also omit bounds checking, but we'll see (I don't have any //! `unsafe` blocks in this project yet). //! Because we want lots of caching and we're assuming our inputs are pretty random, we can //! probably get away with open addressing by just incrementing the hash. //! We never remove from these tables, so we can save on the space / complexity by not //! implementing this mechanism. //! This shows a pretty reliable few point bump over `fnv` in lookups and like 10-15% in //! inserts, which is pretty promising (hasn't been tested yet though). // Speed comparison: w/ RT=.5 and BC=6, speedup is almost 50% // Memory comparison: use std::fmt::Debug; // TODO: tweak this? const RESIZE_THRESHOLD: f64 = 0.5; // resize when table is 1/2 full // TODO: tweak this? const BEGIN_CAP: usize = 6; // 2^6 = 64 // TODO: verify this? const ENTRY_RESERVED: u32 = ::std::u32::MAX; // u32::max_value() on nightly pub type IHMap = IHM<u32>; pub type IHSet = IHM<()>; /// Entry in our hash map: Instead of using `Option` or some unsafe magic, we reserve /// one potential value as "none" (where `page_id` is `INT_MAX`). This saves a lot on space /// (probably about 50% of what it would be) while still being fast (it's like 20% /// faster than `Option<Entry<T>>` because of caching or something). /// The idea is stolen from the `optional` crate, but I like my interface better. #[derive(Debug, Clone, Copy)] pub(super) struct Entry<T: Debug+Copy+Default> { key: u32, val: T, } impl<T: Debug+Copy+Default> Entry<T> { #[inline] fn is_none(&self) -> bool { self.key == ENTRY_RESERVED } #[inline] fn is_some(&self) -> bool { self.is_none() == false } #[inline] fn get(&self) -> Option<&Self> { // the fact that this isn't in `optional` makes me worry it's slow? // Am I crazy? if self.is_none() { None } else { Some(self) } } #[inline] fn none() -> Self { Entry { key: ENTRY_RESERVED, val: Default::default(), } } } /// Integer hash map: map keyed by integers for a very specific application. /// Has some restrictions: Can't remove entries, capacity must be a power of 2, /// input must be relatively randomly distributed, etc. #[derive(Debug, Clone)] pub struct IHM<T: Debug+Copy+Default> { size: usize, cap_exp: usize, // capacity is 2**this data: Box<[Entry<T>]>, } impl<T: Debug+Copy+Default> Default for IHM<T> { fn default() -> Self { IHM::with_capacity(BEGIN_CAP) } } impl<T: Debug+Copy+Default> IHM<T> { #[inline] fn hash(&self, n: u32) -> usize { // n % self.capacity() // last `cap_exp` bytes of `n` (n & ((1 << self.cap_exp) - 1)) as usize } #[inline] fn hash_with(n: usize, cap: usize) -> usize { // way to `hash` without requiring a self-borrow :/ // don't mix up the arg order :/ (n & ((1 << cap) -1)) as usize } // uhhhhh note this is cap_exp NOT real capacity // prediction: I forget this and run out of mem :/ pub fn with_capacity(cap_exp: usize) -> Self { // not sure what the proper way to create a big boxed array // without just making it on the stack first // except using a vector let v: Vec<Entry<T>> = vec![Entry::none(); 1<<cap_exp]; IHM { size: 0, cap_exp, data: v.into_boxed_slice(), } } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn len(&self) -> usize { self.size } pub fn capacity(&self) -> usize { 1 << self.cap_exp } pub fn clear(&mut self) { for entry in self.data.iter_mut() { *entry = Entry::none(); } } pub fn contains_key(&self, key: u32) -> bool { let mut addr = self.hash(key); loop { // For now let's see how well rustc optimizes this // but this might need to be rewritten to be faster // because it'll happen a lot // TODO examine asm // TODO eventually don't bounds check // this leads to a few points of speedup // but it also introduces the possibility of a segfault // maybe until everything is stable and if there are no crashes then revisit /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return false, Some(e) if e.key == key => return true, Some(_) => addr = Self::hash_with(addr+1, self.cap_exp), } } } fn resize(&mut self) { // NOTE this doesn't change in-place. It will briefly consume 50% more // mem than in its final state due to this redundancy let mut other = Self::with_capacity(self.cap_exp + 1); assert_eq!(other.capacity(), 2*self.capacity()); for entry in self.data.iter() { if entry.is_some() { other.insert_elem(entry.key, entry.val); } } *self = other; } fn insert_elem(&mut self, key: u32, val: T) { // TODO maybe could add some cool simd stuff or manual unrolling here if self.len() as f64 / self.capacity() as f64 >= RESIZE_THRESHOLD
self.size += 1; let mut addr = self.hash(key); loop { let entry = &mut self.data[addr]; //let entry = unsafe { self.data.get_unchecked_mut(addr) }; if entry.is_none() { // wasn't present, insert and continue *entry = Entry { key, val }; return; } else if entry.key == key { // entry already there return; } else { // otherwise increment addr and try again //addr = self.hash(addr as u32 + 1); //addr = (addr+1) & ((1 << self.cap_exp) - 1) addr = Self::hash_with(addr+1, self.cap_exp); } } } } use std::iter::FilterMap; use std::slice::Iter; type IterType<'a,T> = FilterMap<Iter<'a, Entry<T>>, for<'r> fn(&'r Entry<T>) -> Option<u32>>; impl IHM<()> { pub fn insert(&mut self, key: u32) { self.insert_elem(key, ()) } //pub(super) fn keys<'a>(&'a self) -> IterType<'a, ()> { pub(super) fn keys(&self) -> IterType<()> { self.data.iter().filter_map(|i| i.get().map(|e| e.key)) } } impl IHM<u32> { pub fn insert(&mut self, key: u32, val: u32) { self.insert_elem(key, val) } pub fn get(&self, key: u32) -> Option<u32> { let mut addr = self.hash(key); loop { /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return None, Some(e) if e.key == key => return Some(e.val), Some(_) => addr = (addr+1) & ((1 << self.cap_exp) - 1), } } } }
{ self.resize(); }
conditional_block
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capacity can always //! be a power of two; also, inserts and lookups need to be very fast, so we can make the //! hash function a simple bitmask (assuming `page_id`s are relatively randomly distributed). //! In theory this means we can also omit bounds checking, but we'll see (I don't have any //! `unsafe` blocks in this project yet). //! Because we want lots of caching and we're assuming our inputs are pretty random, we can //! probably get away with open addressing by just incrementing the hash. //! We never remove from these tables, so we can save on the space / complexity by not //! implementing this mechanism. //! This shows a pretty reliable few point bump over `fnv` in lookups and like 10-15% in //! inserts, which is pretty promising (hasn't been tested yet though). // Speed comparison: w/ RT=.5 and BC=6, speedup is almost 50% // Memory comparison: use std::fmt::Debug; // TODO: tweak this? const RESIZE_THRESHOLD: f64 = 0.5; // resize when table is 1/2 full // TODO: tweak this? const BEGIN_CAP: usize = 6; // 2^6 = 64 // TODO: verify this? const ENTRY_RESERVED: u32 = ::std::u32::MAX; // u32::max_value() on nightly pub type IHMap = IHM<u32>; pub type IHSet = IHM<()>; /// Entry in our hash map: Instead of using `Option` or some unsafe magic, we reserve /// one potential value as "none" (where `page_id` is `INT_MAX`). This saves a lot on space /// (probably about 50% of what it would be) while still being fast (it's like 20% /// faster than `Option<Entry<T>>` because of caching or something). /// The idea is stolen from the `optional` crate, but I like my interface better. #[derive(Debug, Clone, Copy)] pub(super) struct Entry<T: Debug+Copy+Default> { key: u32, val: T, } impl<T: Debug+Copy+Default> Entry<T> { #[inline] fn is_none(&self) -> bool { self.key == ENTRY_RESERVED } #[inline] fn is_some(&self) -> bool { self.is_none() == false } #[inline] fn get(&self) -> Option<&Self> { // the fact that this isn't in `optional` makes me worry it's slow? // Am I crazy? if self.is_none() { None } else { Some(self)
fn none() -> Self { Entry { key: ENTRY_RESERVED, val: Default::default(), } } } /// Integer hash map: map keyed by integers for a very specific application. /// Has some restrictions: Can't remove entries, capacity must be a power of 2, /// input must be relatively randomly distributed, etc. #[derive(Debug, Clone)] pub struct IHM<T: Debug+Copy+Default> { size: usize, cap_exp: usize, // capacity is 2**this data: Box<[Entry<T>]>, } impl<T: Debug+Copy+Default> Default for IHM<T> { fn default() -> Self { IHM::with_capacity(BEGIN_CAP) } } impl<T: Debug+Copy+Default> IHM<T> { #[inline] fn hash(&self, n: u32) -> usize { // n % self.capacity() // last `cap_exp` bytes of `n` (n & ((1 << self.cap_exp) - 1)) as usize } #[inline] fn hash_with(n: usize, cap: usize) -> usize { // way to `hash` without requiring a self-borrow :/ // don't mix up the arg order :/ (n & ((1 << cap) -1)) as usize } // uhhhhh note this is cap_exp NOT real capacity // prediction: I forget this and run out of mem :/ pub fn with_capacity(cap_exp: usize) -> Self { // not sure what the proper way to create a big boxed array // without just making it on the stack first // except using a vector let v: Vec<Entry<T>> = vec![Entry::none(); 1<<cap_exp]; IHM { size: 0, cap_exp, data: v.into_boxed_slice(), } } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn len(&self) -> usize { self.size } pub fn capacity(&self) -> usize { 1 << self.cap_exp } pub fn clear(&mut self) { for entry in self.data.iter_mut() { *entry = Entry::none(); } } pub fn contains_key(&self, key: u32) -> bool { let mut addr = self.hash(key); loop { // For now let's see how well rustc optimizes this // but this might need to be rewritten to be faster // because it'll happen a lot // TODO examine asm // TODO eventually don't bounds check // this leads to a few points of speedup // but it also introduces the possibility of a segfault // maybe until everything is stable and if there are no crashes then revisit /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return false, Some(e) if e.key == key => return true, Some(_) => addr = Self::hash_with(addr+1, self.cap_exp), } } } fn resize(&mut self) { // NOTE this doesn't change in-place. It will briefly consume 50% more // mem than in its final state due to this redundancy let mut other = Self::with_capacity(self.cap_exp + 1); assert_eq!(other.capacity(), 2*self.capacity()); for entry in self.data.iter() { if entry.is_some() { other.insert_elem(entry.key, entry.val); } } *self = other; } fn insert_elem(&mut self, key: u32, val: T) { // TODO maybe could add some cool simd stuff or manual unrolling here if self.len() as f64 / self.capacity() as f64 >= RESIZE_THRESHOLD { self.resize(); } self.size += 1; let mut addr = self.hash(key); loop { let entry = &mut self.data[addr]; //let entry = unsafe { self.data.get_unchecked_mut(addr) }; if entry.is_none() { // wasn't present, insert and continue *entry = Entry { key, val }; return; } else if entry.key == key { // entry already there return; } else { // otherwise increment addr and try again //addr = self.hash(addr as u32 + 1); //addr = (addr+1) & ((1 << self.cap_exp) - 1) addr = Self::hash_with(addr+1, self.cap_exp); } } } } use std::iter::FilterMap; use std::slice::Iter; type IterType<'a,T> = FilterMap<Iter<'a, Entry<T>>, for<'r> fn(&'r Entry<T>) -> Option<u32>>; impl IHM<()> { pub fn insert(&mut self, key: u32) { self.insert_elem(key, ()) } //pub(super) fn keys<'a>(&'a self) -> IterType<'a, ()> { pub(super) fn keys(&self) -> IterType<()> { self.data.iter().filter_map(|i| i.get().map(|e| e.key)) } } impl IHM<u32> { pub fn insert(&mut self, key: u32, val: u32) { self.insert_elem(key, val) } pub fn get(&self, key: u32) -> Option<u32> { let mut addr = self.hash(key); loop { /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return None, Some(e) if e.key == key => return Some(e.val), Some(_) => addr = (addr+1) & ((1 << self.cap_exp) - 1), } } } }
} } #[inline]
random_line_split
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetworkConnection { host: String, buffer: RefCell<Buffer>, socket: RefCell<TcpStream>, /// Bytes that we need to parse the next message needed: RefCell<usize>, bad_messages: RefCell<usize>, } pub enum BitcoinNetworkError { BadBytes, Closed, ReadTimeout, } impl BitcoinNetworkConnection { pub fn new(host: String) -> Result<BitcoinNetworkConnection, Error> { info!("Trying to initialize connection to {}", host); let addrs: Vec<_> = host.to_socket_addrs()? .collect(); let mut socket = None; for addr in addrs { let s = TcpStream::connect_timeout(&addr, Duration::from_millis(2000)); if let Ok(connected) = s { socket = Some(connected); break; } } if socket.is_none() { return Err(Error::new(IoErrorKind::NotConnected, format!("Couldn't connect to socket for {}", host))); } let socket = socket.unwrap(); socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } pub fn with_stream(host: String, socket: TcpStream) -> Result<BitcoinNetworkConnection, Error> { socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } // fn send(&mut self, message: Message) -> Result<(), Error> { // trace!("{} About to write: {:?}", self.host, message); // let written = self.socket.write(&message.encode())?; // trace!("{} Written: {:}", self.host, written); // Ok(()) // } pub fn try_send(&self, message: Message) -> Result<(), Error> { trace!("{} About to write: {:?}", self.host, message); let written = self.socket.borrow_mut().write(&message.encode(false))?; trace!("{} Written: {:}", self.host, written); Ok(()) } pub fn recv(&self) -> Message { unimplemented!() } pub fn try_recv(&self) -> Option<Result<Message, BitcoinNetworkError>> { let len = self.buffer.borrow().available_data(); trace!("[{}] Buffer len: {}", self.host, len); if let Some(message) = self.try_parse() { return Some(message); } match self.read() { Ok(_) => {}, Err(e) => { return Some(Err(e)) } } // If we haven't received any more data let read = self.buffer.borrow().available_data(); if read < *self.needed.borrow() || read == 0 || read == len { return None; } // let _ = self.sender.try_send(ClientMessage::Alive(self.id)); if let Some(message) = self.try_parse() { return Some(message); } None } fn try_parse(&self) -> Option<Result<Message, BitcoinNetworkError>> { let available_data = self.buffer.borrow().available_data(); if available_data == 0 { return None; } let mut trim = false; let mut consume = 0; let parsed = match message(&self.buffer.borrow().data(), &self.host) { IResult::Done(remaining, msg) => Some((msg, remaining.len())), IResult::Incomplete(len) => { if let Needed::Size(s) = len { *self.needed.borrow_mut() = s; } None } IResult::Error(e) => { match e { Err::Code(ErrorKind::Custom(i)) => { warn!("{} Gave us bad data!", self.host); consume = i; trim = true; } _ => { consume = 1; trim = true; } } None } }; if let Some((message, remaining_len)) = parsed { (self.buffer.borrow_mut()).consume(available_data - remaining_len); *self.needed.borrow_mut() = 0; return Some(Ok(message)); } self.buffer.borrow_mut().consume(consume as usize); if trim { *self.bad_messages.borrow_mut() += 1; return Some(Err(BitcoinNetworkError::BadBytes)) } None } fn read(&self) -> Result<(),BitcoinNetworkError> { let mut buff = [0; 8192]; let read = match self.socket.borrow_mut().read(&mut buff) { Ok(r) => { if r == 0 { // return Err(())? return Err(BitcoinNetworkError::Closed) } r }, Err(_e) => { return Err(BitcoinNetworkError::ReadTimeout); } }; // if read == 0 { // return; // } trace!("[{} / {}] Read: {}, Need: {}", self.buffer.borrow().available_data(), self.buffer.borrow().capacity(), read, *self.needed.borrow()); self.buffer.borrow_mut().grow(read); let _ = self.buffer.borrow_mut().write(&buff[0..read]); if *self.needed.borrow() >= read {
Ok(()) } } impl Debug for BitcoinNetworkConnection { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, r"BitcoinNetworkConnection {{ , }}",) } }
*self.needed.borrow_mut() -= read; } else { *self.needed.borrow_mut() = 0; return Ok(()); }
random_line_split
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetworkConnection { host: String, buffer: RefCell<Buffer>, socket: RefCell<TcpStream>, /// Bytes that we need to parse the next message needed: RefCell<usize>, bad_messages: RefCell<usize>, } pub enum BitcoinNetworkError { BadBytes, Closed, ReadTimeout, } impl BitcoinNetworkConnection { pub fn new(host: String) -> Result<BitcoinNetworkConnection, Error> { info!("Trying to initialize connection to {}", host); let addrs: Vec<_> = host.to_socket_addrs()? .collect(); let mut socket = None; for addr in addrs { let s = TcpStream::connect_timeout(&addr, Duration::from_millis(2000)); if let Ok(connected) = s { socket = Some(connected); break; } } if socket.is_none() { return Err(Error::new(IoErrorKind::NotConnected, format!("Couldn't connect to socket for {}", host))); } let socket = socket.unwrap(); socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } pub fn
(host: String, socket: TcpStream) -> Result<BitcoinNetworkConnection, Error> { socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } // fn send(&mut self, message: Message) -> Result<(), Error> { // trace!("{} About to write: {:?}", self.host, message); // let written = self.socket.write(&message.encode())?; // trace!("{} Written: {:}", self.host, written); // Ok(()) // } pub fn try_send(&self, message: Message) -> Result<(), Error> { trace!("{} About to write: {:?}", self.host, message); let written = self.socket.borrow_mut().write(&message.encode(false))?; trace!("{} Written: {:}", self.host, written); Ok(()) } pub fn recv(&self) -> Message { unimplemented!() } pub fn try_recv(&self) -> Option<Result<Message, BitcoinNetworkError>> { let len = self.buffer.borrow().available_data(); trace!("[{}] Buffer len: {}", self.host, len); if let Some(message) = self.try_parse() { return Some(message); } match self.read() { Ok(_) => {}, Err(e) => { return Some(Err(e)) } } // If we haven't received any more data let read = self.buffer.borrow().available_data(); if read < *self.needed.borrow() || read == 0 || read == len { return None; } // let _ = self.sender.try_send(ClientMessage::Alive(self.id)); if let Some(message) = self.try_parse() { return Some(message); } None } fn try_parse(&self) -> Option<Result<Message, BitcoinNetworkError>> { let available_data = self.buffer.borrow().available_data(); if available_data == 0 { return None; } let mut trim = false; let mut consume = 0; let parsed = match message(&self.buffer.borrow().data(), &self.host) { IResult::Done(remaining, msg) => Some((msg, remaining.len())), IResult::Incomplete(len) => { if let Needed::Size(s) = len { *self.needed.borrow_mut() = s; } None } IResult::Error(e) => { match e { Err::Code(ErrorKind::Custom(i)) => { warn!("{} Gave us bad data!", self.host); consume = i; trim = true; } _ => { consume = 1; trim = true; } } None } }; if let Some((message, remaining_len)) = parsed { (self.buffer.borrow_mut()).consume(available_data - remaining_len); *self.needed.borrow_mut() = 0; return Some(Ok(message)); } self.buffer.borrow_mut().consume(consume as usize); if trim { *self.bad_messages.borrow_mut() += 1; return Some(Err(BitcoinNetworkError::BadBytes)) } None } fn read(&self) -> Result<(),BitcoinNetworkError> { let mut buff = [0; 8192]; let read = match self.socket.borrow_mut().read(&mut buff) { Ok(r) => { if r == 0 { // return Err(())? return Err(BitcoinNetworkError::Closed) } r }, Err(_e) => { return Err(BitcoinNetworkError::ReadTimeout); } }; // if read == 0 { // return; // } trace!("[{} / {}] Read: {}, Need: {}", self.buffer.borrow().available_data(), self.buffer.borrow().capacity(), read, *self.needed.borrow()); self.buffer.borrow_mut().grow(read); let _ = self.buffer.borrow_mut().write(&buff[0..read]); if *self.needed.borrow() >= read { *self.needed.borrow_mut() -= read; } else { *self.needed.borrow_mut() = 0; return Ok(()); } Ok(()) } } impl Debug for BitcoinNetworkConnection { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, r"BitcoinNetworkConnection {{ , }}",) } }
with_stream
identifier_name
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetworkConnection { host: String, buffer: RefCell<Buffer>, socket: RefCell<TcpStream>, /// Bytes that we need to parse the next message needed: RefCell<usize>, bad_messages: RefCell<usize>, } pub enum BitcoinNetworkError { BadBytes, Closed, ReadTimeout, } impl BitcoinNetworkConnection { pub fn new(host: String) -> Result<BitcoinNetworkConnection, Error> { info!("Trying to initialize connection to {}", host); let addrs: Vec<_> = host.to_socket_addrs()? .collect(); let mut socket = None; for addr in addrs { let s = TcpStream::connect_timeout(&addr, Duration::from_millis(2000)); if let Ok(connected) = s { socket = Some(connected); break; } } if socket.is_none() { return Err(Error::new(IoErrorKind::NotConnected, format!("Couldn't connect to socket for {}", host))); } let socket = socket.unwrap(); socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } pub fn with_stream(host: String, socket: TcpStream) -> Result<BitcoinNetworkConnection, Error> { socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } // fn send(&mut self, message: Message) -> Result<(), Error> { // trace!("{} About to write: {:?}", self.host, message); // let written = self.socket.write(&message.encode())?; // trace!("{} Written: {:}", self.host, written); // Ok(()) // } pub fn try_send(&self, message: Message) -> Result<(), Error> { trace!("{} About to write: {:?}", self.host, message); let written = self.socket.borrow_mut().write(&message.encode(false))?; trace!("{} Written: {:}", self.host, written); Ok(()) } pub fn recv(&self) -> Message { unimplemented!() } pub fn try_recv(&self) -> Option<Result<Message, BitcoinNetworkError>>
if let Some(message) = self.try_parse() { return Some(message); } None } fn try_parse(&self) -> Option<Result<Message, BitcoinNetworkError>> { let available_data = self.buffer.borrow().available_data(); if available_data == 0 { return None; } let mut trim = false; let mut consume = 0; let parsed = match message(&self.buffer.borrow().data(), &self.host) { IResult::Done(remaining, msg) => Some((msg, remaining.len())), IResult::Incomplete(len) => { if let Needed::Size(s) = len { *self.needed.borrow_mut() = s; } None } IResult::Error(e) => { match e { Err::Code(ErrorKind::Custom(i)) => { warn!("{} Gave us bad data!", self.host); consume = i; trim = true; } _ => { consume = 1; trim = true; } } None } }; if let Some((message, remaining_len)) = parsed { (self.buffer.borrow_mut()).consume(available_data - remaining_len); *self.needed.borrow_mut() = 0; return Some(Ok(message)); } self.buffer.borrow_mut().consume(consume as usize); if trim { *self.bad_messages.borrow_mut() += 1; return Some(Err(BitcoinNetworkError::BadBytes)) } None } fn read(&self) -> Result<(),BitcoinNetworkError> { let mut buff = [0; 8192]; let read = match self.socket.borrow_mut().read(&mut buff) { Ok(r) => { if r == 0 { // return Err(())? return Err(BitcoinNetworkError::Closed) } r }, Err(_e) => { return Err(BitcoinNetworkError::ReadTimeout); } }; // if read == 0 { // return; // } trace!("[{} / {}] Read: {}, Need: {}", self.buffer.borrow().available_data(), self.buffer.borrow().capacity(), read, *self.needed.borrow()); self.buffer.borrow_mut().grow(read); let _ = self.buffer.borrow_mut().write(&buff[0..read]); if *self.needed.borrow() >= read { *self.needed.borrow_mut() -= read; } else { *self.needed.borrow_mut() = 0; return Ok(()); } Ok(()) } } impl Debug for BitcoinNetworkConnection { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, r"BitcoinNetworkConnection {{ , }}",) } }
{ let len = self.buffer.borrow().available_data(); trace!("[{}] Buffer len: {}", self.host, len); if let Some(message) = self.try_parse() { return Some(message); } match self.read() { Ok(_) => {}, Err(e) => { return Some(Err(e)) } } // If we haven't received any more data let read = self.buffer.borrow().available_data(); if read < *self.needed.borrow() || read == 0 || read == len { return None; } // let _ = self.sender.try_send(ClientMessage::Alive(self.id));
identifier_body
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetworkConnection { host: String, buffer: RefCell<Buffer>, socket: RefCell<TcpStream>, /// Bytes that we need to parse the next message needed: RefCell<usize>, bad_messages: RefCell<usize>, } pub enum BitcoinNetworkError { BadBytes, Closed, ReadTimeout, } impl BitcoinNetworkConnection { pub fn new(host: String) -> Result<BitcoinNetworkConnection, Error> { info!("Trying to initialize connection to {}", host); let addrs: Vec<_> = host.to_socket_addrs()? .collect(); let mut socket = None; for addr in addrs { let s = TcpStream::connect_timeout(&addr, Duration::from_millis(2000)); if let Ok(connected) = s { socket = Some(connected); break; } } if socket.is_none() { return Err(Error::new(IoErrorKind::NotConnected, format!("Couldn't connect to socket for {}", host))); } let socket = socket.unwrap(); socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } pub fn with_stream(host: String, socket: TcpStream) -> Result<BitcoinNetworkConnection, Error> { socket.set_read_timeout(Some(Duration::from_secs(2)))?; //.expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { host: host, // Allocate a buffer with 4MB of capacity buffer: RefCell::new(Buffer::with_capacity(1024 * 1024 * 4)), socket: RefCell::new(socket), needed: RefCell::new(0), bad_messages: RefCell::new(0), }) } // fn send(&mut self, message: Message) -> Result<(), Error> { // trace!("{} About to write: {:?}", self.host, message); // let written = self.socket.write(&message.encode())?; // trace!("{} Written: {:}", self.host, written); // Ok(()) // } pub fn try_send(&self, message: Message) -> Result<(), Error> { trace!("{} About to write: {:?}", self.host, message); let written = self.socket.borrow_mut().write(&message.encode(false))?; trace!("{} Written: {:}", self.host, written); Ok(()) } pub fn recv(&self) -> Message { unimplemented!() } pub fn try_recv(&self) -> Option<Result<Message, BitcoinNetworkError>> { let len = self.buffer.borrow().available_data(); trace!("[{}] Buffer len: {}", self.host, len); if let Some(message) = self.try_parse() { return Some(message); } match self.read() { Ok(_) => {}, Err(e) => { return Some(Err(e)) } } // If we haven't received any more data let read = self.buffer.borrow().available_data(); if read < *self.needed.borrow() || read == 0 || read == len { return None; } // let _ = self.sender.try_send(ClientMessage::Alive(self.id)); if let Some(message) = self.try_parse() { return Some(message); } None } fn try_parse(&self) -> Option<Result<Message, BitcoinNetworkError>> { let available_data = self.buffer.borrow().available_data(); if available_data == 0
let mut trim = false; let mut consume = 0; let parsed = match message(&self.buffer.borrow().data(), &self.host) { IResult::Done(remaining, msg) => Some((msg, remaining.len())), IResult::Incomplete(len) => { if let Needed::Size(s) = len { *self.needed.borrow_mut() = s; } None } IResult::Error(e) => { match e { Err::Code(ErrorKind::Custom(i)) => { warn!("{} Gave us bad data!", self.host); consume = i; trim = true; } _ => { consume = 1; trim = true; } } None } }; if let Some((message, remaining_len)) = parsed { (self.buffer.borrow_mut()).consume(available_data - remaining_len); *self.needed.borrow_mut() = 0; return Some(Ok(message)); } self.buffer.borrow_mut().consume(consume as usize); if trim { *self.bad_messages.borrow_mut() += 1; return Some(Err(BitcoinNetworkError::BadBytes)) } None } fn read(&self) -> Result<(),BitcoinNetworkError> { let mut buff = [0; 8192]; let read = match self.socket.borrow_mut().read(&mut buff) { Ok(r) => { if r == 0 { // return Err(())? return Err(BitcoinNetworkError::Closed) } r }, Err(_e) => { return Err(BitcoinNetworkError::ReadTimeout); } }; // if read == 0 { // return; // } trace!("[{} / {}] Read: {}, Need: {}", self.buffer.borrow().available_data(), self.buffer.borrow().capacity(), read, *self.needed.borrow()); self.buffer.borrow_mut().grow(read); let _ = self.buffer.borrow_mut().write(&buff[0..read]); if *self.needed.borrow() >= read { *self.needed.borrow_mut() -= read; } else { *self.needed.borrow_mut() = 0; return Ok(()); } Ok(()) } } impl Debug for BitcoinNetworkConnection { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, r"BitcoinNetworkConnection {{ , }}",) } }
{ return None; }
conditional_block
glyph.rs
_ligature, glyph_count); let mut val = FLAG_NOT_MISSING; if!starts_cluster { val |= FLAG_NOT_CLUSTER_START; } if!starts_ligature { val |= FLAG_NOT_LIGATURE_GROUP_START; } val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; GlyphEntry::new(val) } /// Create a GlyphEntry for the case where glyphs couldn't be found for the specified /// character. fn missing(glyph_count: uint) -> GlyphEntry { assert!(glyph_count <= u16::MAX as uint); GlyphEntry::new((glyph_count as u32) << GLYPH_COUNT_SHIFT) } } /// The index of a particular glyph within a font pub type GlyphIndex = u32; // TODO: unify with bit flags? #[deriving(Eq)] pub enum BreakType { BreakTypeNone, BreakTypeNormal, BreakTypeHyphen } static BREAK_TYPE_NONE: u8 = 0x0; static BREAK_TYPE_NORMAL: u8 = 0x1; static BREAK_TYPE_HYPHEN: u8 = 0x2; fn break_flag_to_enum(flag: u8) -> BreakType { if (flag & BREAK_TYPE_NORMAL)!= 0 { return BreakTypeNormal; } if (flag & BREAK_TYPE_HYPHEN)!= 0 { return BreakTypeHyphen; } BreakTypeNone } fn break_enum_to_flag(e: BreakType) -> u8 { match e { BreakTypeNone => BREAK_TYPE_NONE, BreakTypeNormal => BREAK_TYPE_NORMAL, BreakTypeHyphen => BREAK_TYPE_HYPHEN, } } // TODO: make this more type-safe. static FLAG_CHAR_IS_SPACE: u32 = 0x10000000; // These two bits store some BREAK_TYPE_* flags static FLAG_CAN_BREAK_MASK: u32 = 0x60000000; static FLAG_CAN_BREAK_SHIFT: u32 = 29; static FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000; // glyph advance; in Au's. static GLYPH_ADVANCE_MASK: u32 = 0x0FFF0000; static GLYPH_ADVANCE_SHIFT: u32 = 16; static GLYPH_ID_MASK: u32 = 0x0000FFFF; // Non-simple glyphs (more than one glyph per char; missing glyph, // newline, tab, large advance, or nonzero x/y offsets) may have one // or more detailed glyphs associated with them. They are stored in a // side array so that there is a 1:1 mapping of GlyphEntry to // unicode char. // The number of detailed glyphs for this char. If the char couldn't // be mapped to a glyph (!FLAG_NOT_MISSING), then this actually holds // the UTF8 code point instead. static GLYPH_COUNT_MASK: u32 = 0x00FFFF00; static GLYPH_COUNT_SHIFT: u32 = 8; // N.B. following Gecko, these are all inverted so that a lot of // missing chars can be memset with zeros in one fell swoop. static FLAG_NOT_MISSING: u32 = 0x00000001; static FLAG_NOT_CLUSTER_START: u32 = 0x00000002; static FLAG_NOT_LIGATURE_GROUP_START: u32 = 0x00000004; static FLAG_CHAR_IS_TAB: u32 = 0x00000008; static FLAG_CHAR_IS_NEWLINE: u32 = 0x00000010; //static FLAG_CHAR_IS_LOW_SURROGATE: u32 = 0x00000020; //static CHAR_IDENTITY_FLAGS_MASK: u32 = 0x00000038; fn is_simple_glyph_id(glyphId: GlyphIndex) -> bool { ((glyphId as u32) & GLYPH_ID_MASK) == glyphId } fn is_simple_advance(advance: Au) -> bool { let unsignedAu = advance.to_u32().unwrap(); (unsignedAu & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsignedAu } type DetailedGlyphCount = u16; // Getters and setters for GlyphEntry. Setter methods are functional, // because GlyphEntry is immutable and only a u32 in size. impl GlyphEntry { // getter methods #[inline(always)] fn advance(&self) -> Au { NumCast::from((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT).unwrap() } fn index(&self) -> GlyphIndex { self.value & GLYPH_ID_MASK } fn is_ligature_start(&self) -> bool { self.has_flag(!FLAG_NOT_LIGATURE_GROUP_START) } fn is_cluster_start(&self) -> bool { self.has_flag(!FLAG_NOT_CLUSTER_START) } // True if original char was normal (U+0020) space. Other chars may // map to space glyph, but this does not account for them. fn char_is_space(&self) -> bool { self.has_flag(FLAG_CHAR_IS_SPACE) } fn char_is_tab(&self) -> bool { !self.is_simple() && self.has_flag(FLAG_CHAR_IS_TAB) } fn char_is_newline(&self) -> bool { !self.is_simple() && self.has_flag(FLAG_CHAR_IS_NEWLINE) } fn can_break_before(&self) -> BreakType { let flag = ((self.value & FLAG_CAN_BREAK_MASK) >> FLAG_CAN_BREAK_SHIFT) as u8; break_flag_to_enum(flag) } // setter methods #[inline(always)] fn set_char_is_space(&self) -> GlyphEntry { GlyphEntry::new(self.value | FLAG_CHAR_IS_SPACE) } #[inline(always)] fn set_char_is_tab(&self) -> GlyphEntry { assert!(!self.is_simple()); GlyphEntry::new(self.value | FLAG_CHAR_IS_TAB) } #[inline(always)] fn set_char_is_newline(&self) -> GlyphEntry { assert!(!self.is_simple()); GlyphEntry::new(self.value | FLAG_CHAR_IS_NEWLINE) } #[inline(always)] fn set_can_break_before(&self, e: BreakType) -> GlyphEntry { let flag = (break_enum_to_flag(e) as u32) << FLAG_CAN_BREAK_SHIFT; GlyphEntry::new(self.value | flag) } // helper methods fn glyph_count(&self) -> u16 { assert!(!self.is_simple()); ((self.value & GLYPH_COUNT_MASK) >> GLYPH_COUNT_SHIFT) as u16 } #[inline(always)] fn is_simple(&self) -> bool { self.has_flag(FLAG_IS_SIMPLE_GLYPH) } #[inline(always)] fn has_flag(&self, flag: u32) -> bool { (self.value & flag)!= 0 } #[inline(always)] fn adapt_character_flags_of_entry(&self, other: GlyphEntry) -> GlyphEntry { GlyphEntry { value: self.value | other.value } } } // Stores data for a detailed glyph, in the case that several glyphs // correspond to one character, or the glyph's data couldn't be packed. #[deriving(Clone)] struct DetailedGlyph { index: GlyphIndex, // glyph's advance, in the text's direction (RTL or RTL) advance: Au, // glyph's offset from the font's em-box (from top-left) offset: Point2D<Au> } impl DetailedGlyph { fn new(index: GlyphIndex, advance: Au, offset: Point2D<Au>) -> DetailedGlyph { DetailedGlyph { index: index, advance: advance, offset: offset } } } #[deriving(Eq, Clone)] struct DetailedGlyphRecord { // source string offset/GlyphEntry offset in the TextRun entry_offset: uint, // offset into the detailed glyphs buffer detail_offset: uint } impl Ord for DetailedGlyphRecord { fn lt(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset < other.entry_offset } fn le(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset <= other.entry_offset } fn ge(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset >= other.entry_offset } fn gt(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset > other.entry_offset } } // Manages the lookup table for detailed glyphs. Sorting is deferred // until a lookup is actually performed; this matches the expected // usage pattern of setting/appending all the detailed glyphs, and // then querying without setting. struct DetailedGlyphStore { // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. detail_buffer: ~[DetailedGlyph], // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. detail_lookup: ~[DetailedGlyphRecord], lookup_is_sorted: bool, } impl<'a> DetailedGlyphStore { fn new() -> DetailedGlyphStore { DetailedGlyphStore { detail_buffer: ~[], // TODO: default size? detail_lookup: ~[], lookup_is_sorted: false } } fn add_detailed_glyphs_for_entry(&mut self, entry_offset: uint, glyphs: &[DetailedGlyph]) { let entry = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: self.detail_buffer.len() }; debug!("Adding entry[off={:u}] for detailed glyphs: {:?}", entry_offset, glyphs); /* TODO: don't actually assert this until asserts are compiled in/out based on severity, debug/release, etc. This assertion would wreck the complexity of the lookup. See Rust Issue #3647, #2228, #3627 for related information. do self.detail_lookup.borrow |arr| { assert!arr.contains(entry) } */ self.detail_lookup.push(entry); self.detail_buffer.push_all(glyphs); self.lookup_is_sorted = false; } fn get_detailed_glyphs_for_entry(&'a self, entry_offset: uint, count: u16) -> &'a [DetailedGlyph] { debug!("Requesting detailed glyphs[n={:u}] for entry[off={:u}]", count as uint, entry_offset); // FIXME: Is this right? --pcwalton // TODO: should fix this somewhere else if count == 0 { return self.detail_buffer.slice(0, 0); } assert!((count as uint) <= self.detail_buffer.len()); assert!(self.lookup_is_sorted); let key = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: 0 // unused }; // FIXME: This is a workaround for borrow of self.detail_lookup not getting inferred. let records : &[DetailedGlyphRecord] = self.detail_lookup; match records.binary_search_index(&key) { None => fail!(~"Invalid index not found in detailed glyph lookup table!"), Some(i) => { assert!(i + (count as uint) <= self.detail_buffer.len()); // return a slice into the buffer self.detail_buffer.slice(i, i + count as uint) } } } fn get_detailed_glyph_with_index(&'a self, entry_offset: uint, detail_offset: u16) -> &'a DetailedGlyph { assert!((detail_offset as uint) <= self.detail_buffer.len()); assert!(self.lookup_is_sorted); let key = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: 0 // unused }; // FIXME: This is a workaround for borrow of self.detail_lookup not getting inferred. let records: &[DetailedGlyphRecord] = self.detail_lookup; match records.binary_search_index(&key) { None => fail!(~"Invalid index not found in detailed glyph lookup table!"), Some(i) => { assert!(i + (detail_offset as uint) < self.detail_buffer.len()); &self.detail_buffer[i+(detail_offset as uint)] } } } fn ensure_sorted(&mut self) { if self.lookup_is_sorted { return; } // Sorting a unique vector is surprisingly hard. The follwing // code is a good argument for using DVecs, but they require // immutable locations thus don't play well with freezing. // Thar be dragons here. You have been warned. (Tips accepted.) let mut unsorted_records: ~[DetailedGlyphRecord] = ~[]; mem::swap(&mut self.detail_lookup, &mut unsorted_records); let mut mut_records : ~[DetailedGlyphRecord] = unsorted_records; mut_records.sort_by(|a, b| { if a < b { Less } else { Greater } }); let mut sorted_records = mut_records; mem::swap(&mut self.detail_lookup, &mut sorted_records); self.lookup_is_sorted = true; } } // This struct is used by GlyphStore clients to provide new glyph data. // It should be allocated on the stack and passed by reference to GlyphStore. pub struct GlyphData { index: GlyphIndex, advance: Au, offset: Point2D<Au>, is_missing: bool, cluster_start: bool, ligature_start: bool, } impl GlyphData { pub fn new(index: GlyphIndex, advance: Au, offset: Option<Point2D<Au>>, is_missing: bool, cluster_start: bool, ligature_start: bool) -> GlyphData { let offset = match offset { None => geometry::zero_point(), Some(o) => o }; GlyphData { index: index, advance: advance, offset: offset, is_missing: is_missing, cluster_start: cluster_start, ligature_start: ligature_start, } } } // This enum is a proxy that's provided to GlyphStore clients when iterating // through glyphs (either for a particular TextRun offset, or all glyphs). // Rather than eagerly assembling and copying glyph data, it only retrieves // values as they are needed from the GlyphStore, using provided offsets. enum
<'a> { SimpleGlyphInfo(&'a GlyphStore, uint), DetailGlyphInfo(&'a GlyphStore, uint, u16) } impl<'a> GlyphInfo<'a> { pub fn index(self) -> GlyphIndex { match self { SimpleGlyphInfo(store, entry_i) => store.entry_buffer[entry_i].index(), DetailGlyphInfo(store, entry_i, detail_j) => { store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).index } } } #[inline(always)] // FIXME: Resolution conflicts with IteratorUtil trait so adding trailing _ pub fn advance(self) -> Au { match self { SimpleGlyphInfo(store, entry_i) => store.entry_buffer[entry_i].advance(), DetailGlyphInfo(store, entry_i, detail_j) => { store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).advance } } } pub fn offset(self) -> Option<Point2D<Au>> { match self { SimpleGlyphInfo(_, _) => None, DetailGlyphInfo(store, entry_i, detail_j) => { Some(store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).offset) } } } } // Public data structure and API for storing and retrieving glyph data pub struct GlyphStore { // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. entry_buffer: ~[GlyphEntry], detail_store: DetailedGlyphStore, is_whitespace: bool, } impl<'a> GlyphStore { // Initializes the glyph store, but doesn't actually shape anything. // Use the set_glyph, set_glyphs() methods to store glyph data. pub fn new(length: uint, is_whitespace: bool) -> GlyphStore { assert!(length > 0); GlyphStore { entry_buffer: vec::from_elem(length, GlyphEntry::initial()), detail_store: DetailedGlyphStore::new(), is_whitespace: is_whitespace, } } pub fn char_len(&self) -> uint { self.entry_buffer.len() } pub fn is_whitespace(&self) -> bool { self.is_whitespace } pub fn finalize_changes(&mut self) { self.detail_store.ensure_sorted(); } pub fn add_glyph_for_char_index(&mut self, i: uint, data: &GlyphData) { fn glyph_is_compressible(data: &GlyphData) -> bool { is_simple_glyph_id(data.index) && is_simple_advance(data.advance) && data.offset == geometry::zero_point() && data.cluster_start // others are stored in detail buffer } assert!(data.ligature_start); // can't compress ligature continuation glyphs. assert!(i < self.entry_buffer.len()); let entry = match (data.is_missing, glyph_is_compressible(data)) { (true, _) => GlyphEntry::missing(1), (false, true) => GlyphEntry::simple(data.index, data.advance), (false, false) => { let glyph = [DetailedGlyph::new(data.index, data.advance, data.offset)]; self.detail_store.add_detailed_glyphs_for_entry(i, glyph); GlyphEntry::complex(data.cluster_start, data.ligature_start, 1) } }.adapt_character_flags_of_entry(self.entry_buffer[i]); self.entry_buffer[i] = entry; } pub fn add_glyphs_for_char_index(&mut self, i: uint, data_for_glyphs: &[GlyphData]) { assert!(i < self.entry_buffer.len()); assert!(data_for_glyphs.len() > 0); let glyph_count = data_for_glyphs.len(); let first_glyph_data = data_for_glyphs[0]; let entry = match first_glyph_data.is_missing { true => GlyphEntry::missing(glyph_count), false => { let glyphs_vec = vec::from_fn(glyph_count, |i| { DetailedGlyph::new(data_for_glyphs[i].index, data_for_glyphs[i].advance, data_for_glyphs[i].offset) }); self.detail_store.add_detailed_glyphs_for_entry(i, glyphs_vec); GlyphEntry::complex(first_glyph_data.cluster_start, first_glyph_data.ligature_start, glyph_count) } }.adapt_character_flags_of_entry(self.entry_buffer[i]); debug!("Adding multiple glyphs[idx={:u}, count={:u}]: {:?}", i, glyph_count, entry); self.entry_buffer[i] = entry; } // used when a character index has no associated glyph---for example, a ligature continuation. pub fn add_nonglyph_for_char_index(&mut self, i: uint, cluster_start: bool, ligature_start: bool) { assert!(i < self.entry_buffer.len()); let entry = GlyphEntry::complex(cluster_start, ligature_start, 0); debug!("adding spacer for chracter without associated glyph[idx={:u}]", i); self.entry_buffer[i] = entry; } pub fn iter_glyphs_for_char_index(&'a self, i: uint) -> GlyphIterator<'a> { self.iter_glyphs_for_char_range(&Range::new(i, 1)) } #[inline] pub fn iter_glyphs_for_char_range(&'a self, rang: &Range) -> GlyphIterator<'a> { if rang.begin() >= self.entry_buffer.len() { fail!("iter_glyphs_for_range: range.begin beyond length!"); } if rang.end() > self.entry_buffer.len() { fail!("iter_glyphs_for_range: range.end beyond length!"); } GlyphIterator { store: self, char_index: rang.begin(), char_range: rang.eachi(), glyph_range: None } } // getter methods pub fn char_is_space(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_space() } pub fn char_is_tab(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_tab() } pub fn char_is_newline(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_newline() } pub fn is_ligature_start(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].is_ligature_start() } pub fn is_cluster_start(&self, i
GlyphInfo
identifier_name
glyph.rs
_ligature, glyph_count); let mut val = FLAG_NOT_MISSING; if!starts_cluster { val |= FLAG_NOT_CLUSTER_START; } if!starts_ligature { val |= FLAG_NOT_LIGATURE_GROUP_START; } val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; GlyphEntry::new(val) } /// Create a GlyphEntry for the case where glyphs couldn't be found for the specified /// character. fn missing(glyph_count: uint) -> GlyphEntry { assert!(glyph_count <= u16::MAX as uint); GlyphEntry::new((glyph_count as u32) << GLYPH_COUNT_SHIFT) } } /// The index of a particular glyph within a font pub type GlyphIndex = u32; // TODO: unify with bit flags? #[deriving(Eq)] pub enum BreakType { BreakTypeNone, BreakTypeNormal, BreakTypeHyphen } static BREAK_TYPE_NONE: u8 = 0x0; static BREAK_TYPE_NORMAL: u8 = 0x1; static BREAK_TYPE_HYPHEN: u8 = 0x2; fn break_flag_to_enum(flag: u8) -> BreakType { if (flag & BREAK_TYPE_NORMAL)!= 0 { return BreakTypeNormal; } if (flag & BREAK_TYPE_HYPHEN)!= 0 { return BreakTypeHyphen; } BreakTypeNone } fn break_enum_to_flag(e: BreakType) -> u8 { match e { BreakTypeNone => BREAK_TYPE_NONE, BreakTypeNormal => BREAK_TYPE_NORMAL, BreakTypeHyphen => BREAK_TYPE_HYPHEN, } } // TODO: make this more type-safe. static FLAG_CHAR_IS_SPACE: u32 = 0x10000000; // These two bits store some BREAK_TYPE_* flags static FLAG_CAN_BREAK_MASK: u32 = 0x60000000; static FLAG_CAN_BREAK_SHIFT: u32 = 29; static FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000; // glyph advance; in Au's. static GLYPH_ADVANCE_MASK: u32 = 0x0FFF0000; static GLYPH_ADVANCE_SHIFT: u32 = 16; static GLYPH_ID_MASK: u32 = 0x0000FFFF; // Non-simple glyphs (more than one glyph per char; missing glyph, // newline, tab, large advance, or nonzero x/y offsets) may have one // or more detailed glyphs associated with them. They are stored in a // side array so that there is a 1:1 mapping of GlyphEntry to // unicode char. // The number of detailed glyphs for this char. If the char couldn't // be mapped to a glyph (!FLAG_NOT_MISSING), then this actually holds // the UTF8 code point instead. static GLYPH_COUNT_MASK: u32 = 0x00FFFF00; static GLYPH_COUNT_SHIFT: u32 = 8; // N.B. following Gecko, these are all inverted so that a lot of // missing chars can be memset with zeros in one fell swoop. static FLAG_NOT_MISSING: u32 = 0x00000001; static FLAG_NOT_CLUSTER_START: u32 = 0x00000002; static FLAG_NOT_LIGATURE_GROUP_START: u32 = 0x00000004; static FLAG_CHAR_IS_TAB: u32 = 0x00000008; static FLAG_CHAR_IS_NEWLINE: u32 = 0x00000010; //static FLAG_CHAR_IS_LOW_SURROGATE: u32 = 0x00000020; //static CHAR_IDENTITY_FLAGS_MASK: u32 = 0x00000038; fn is_simple_glyph_id(glyphId: GlyphIndex) -> bool { ((glyphId as u32) & GLYPH_ID_MASK) == glyphId } fn is_simple_advance(advance: Au) -> bool { let unsignedAu = advance.to_u32().unwrap(); (unsignedAu & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsignedAu } type DetailedGlyphCount = u16; // Getters and setters for GlyphEntry. Setter methods are functional, // because GlyphEntry is immutable and only a u32 in size. impl GlyphEntry { // getter methods #[inline(always)] fn advance(&self) -> Au { NumCast::from((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT).unwrap() } fn index(&self) -> GlyphIndex { self.value & GLYPH_ID_MASK } fn is_ligature_start(&self) -> bool { self.has_flag(!FLAG_NOT_LIGATURE_GROUP_START) } fn is_cluster_start(&self) -> bool { self.has_flag(!FLAG_NOT_CLUSTER_START) } // True if original char was normal (U+0020) space. Other chars may // map to space glyph, but this does not account for them. fn char_is_space(&self) -> bool { self.has_flag(FLAG_CHAR_IS_SPACE) } fn char_is_tab(&self) -> bool { !self.is_simple() && self.has_flag(FLAG_CHAR_IS_TAB) } fn char_is_newline(&self) -> bool { !self.is_simple() && self.has_flag(FLAG_CHAR_IS_NEWLINE) } fn can_break_before(&self) -> BreakType { let flag = ((self.value & FLAG_CAN_BREAK_MASK) >> FLAG_CAN_BREAK_SHIFT) as u8; break_flag_to_enum(flag) } // setter methods #[inline(always)] fn set_char_is_space(&self) -> GlyphEntry { GlyphEntry::new(self.value | FLAG_CHAR_IS_SPACE) } #[inline(always)] fn set_char_is_tab(&self) -> GlyphEntry { assert!(!self.is_simple()); GlyphEntry::new(self.value | FLAG_CHAR_IS_TAB) } #[inline(always)] fn set_char_is_newline(&self) -> GlyphEntry { assert!(!self.is_simple()); GlyphEntry::new(self.value | FLAG_CHAR_IS_NEWLINE) } #[inline(always)] fn set_can_break_before(&self, e: BreakType) -> GlyphEntry { let flag = (break_enum_to_flag(e) as u32) << FLAG_CAN_BREAK_SHIFT; GlyphEntry::new(self.value | flag) } // helper methods fn glyph_count(&self) -> u16 { assert!(!self.is_simple()); ((self.value & GLYPH_COUNT_MASK) >> GLYPH_COUNT_SHIFT) as u16 } #[inline(always)] fn is_simple(&self) -> bool { self.has_flag(FLAG_IS_SIMPLE_GLYPH) } #[inline(always)] fn has_flag(&self, flag: u32) -> bool { (self.value & flag)!= 0 } #[inline(always)] fn adapt_character_flags_of_entry(&self, other: GlyphEntry) -> GlyphEntry { GlyphEntry { value: self.value | other.value } } } // Stores data for a detailed glyph, in the case that several glyphs // correspond to one character, or the glyph's data couldn't be packed. #[deriving(Clone)] struct DetailedGlyph { index: GlyphIndex, // glyph's advance, in the text's direction (RTL or RTL) advance: Au, // glyph's offset from the font's em-box (from top-left) offset: Point2D<Au> } impl DetailedGlyph { fn new(index: GlyphIndex, advance: Au, offset: Point2D<Au>) -> DetailedGlyph { DetailedGlyph { index: index, advance: advance, offset: offset } } } #[deriving(Eq, Clone)] struct DetailedGlyphRecord { // source string offset/GlyphEntry offset in the TextRun entry_offset: uint, // offset into the detailed glyphs buffer detail_offset: uint } impl Ord for DetailedGlyphRecord { fn lt(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset < other.entry_offset } fn le(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset <= other.entry_offset } fn ge(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset >= other.entry_offset } fn gt(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset > other.entry_offset } } // Manages the lookup table for detailed glyphs. Sorting is deferred // until a lookup is actually performed; this matches the expected // usage pattern of setting/appending all the detailed glyphs, and // then querying without setting. struct DetailedGlyphStore { // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. detail_buffer: ~[DetailedGlyph], // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. detail_lookup: ~[DetailedGlyphRecord], lookup_is_sorted: bool, } impl<'a> DetailedGlyphStore { fn new() -> DetailedGlyphStore { DetailedGlyphStore { detail_buffer: ~[], // TODO: default size? detail_lookup: ~[], lookup_is_sorted: false } } fn add_detailed_glyphs_for_entry(&mut self, entry_offset: uint, glyphs: &[DetailedGlyph]) { let entry = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: self.detail_buffer.len() }; debug!("Adding entry[off={:u}] for detailed glyphs: {:?}", entry_offset, glyphs); /* TODO: don't actually assert this until asserts are compiled in/out based on severity, debug/release, etc. This assertion would wreck the complexity of the lookup. See Rust Issue #3647, #2228, #3627 for related information. do self.detail_lookup.borrow |arr| { assert!arr.contains(entry) } */ self.detail_lookup.push(entry); self.detail_buffer.push_all(glyphs); self.lookup_is_sorted = false; } fn get_detailed_glyphs_for_entry(&'a self, entry_offset: uint, count: u16) -> &'a [DetailedGlyph] { debug!("Requesting detailed glyphs[n={:u}] for entry[off={:u}]", count as uint, entry_offset); // FIXME: Is this right? --pcwalton // TODO: should fix this somewhere else if count == 0 { return self.detail_buffer.slice(0, 0); } assert!((count as uint) <= self.detail_buffer.len()); assert!(self.lookup_is_sorted); let key = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: 0 // unused }; // FIXME: This is a workaround for borrow of self.detail_lookup not getting inferred. let records : &[DetailedGlyphRecord] = self.detail_lookup; match records.binary_search_index(&key) { None => fail!(~"Invalid index not found in detailed glyph lookup table!"), Some(i) => { assert!(i + (count as uint) <= self.detail_buffer.len()); // return a slice into the buffer self.detail_buffer.slice(i, i + count as uint) } } } fn get_detailed_glyph_with_index(&'a self, entry_offset: uint, detail_offset: u16) -> &'a DetailedGlyph { assert!((detail_offset as uint) <= self.detail_buffer.len()); assert!(self.lookup_is_sorted); let key = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: 0 // unused }; // FIXME: This is a workaround for borrow of self.detail_lookup not getting inferred. let records: &[DetailedGlyphRecord] = self.detail_lookup; match records.binary_search_index(&key) { None => fail!(~"Invalid index not found in detailed glyph lookup table!"), Some(i) => { assert!(i + (detail_offset as uint) < self.detail_buffer.len()); &self.detail_buffer[i+(detail_offset as uint)] } } } fn ensure_sorted(&mut self) { if self.lookup_is_sorted { return; } // Sorting a unique vector is surprisingly hard. The follwing // code is a good argument for using DVecs, but they require // immutable locations thus don't play well with freezing. // Thar be dragons here. You have been warned. (Tips accepted.) let mut unsorted_records: ~[DetailedGlyphRecord] = ~[]; mem::swap(&mut self.detail_lookup, &mut unsorted_records); let mut mut_records : ~[DetailedGlyphRecord] = unsorted_records; mut_records.sort_by(|a, b| { if a < b { Less } else { Greater } }); let mut sorted_records = mut_records; mem::swap(&mut self.detail_lookup, &mut sorted_records); self.lookup_is_sorted = true; } } // This struct is used by GlyphStore clients to provide new glyph data. // It should be allocated on the stack and passed by reference to GlyphStore. pub struct GlyphData { index: GlyphIndex, advance: Au, offset: Point2D<Au>, is_missing: bool, cluster_start: bool, ligature_start: bool, } impl GlyphData { pub fn new(index: GlyphIndex, advance: Au, offset: Option<Point2D<Au>>, is_missing: bool, cluster_start: bool, ligature_start: bool) -> GlyphData { let offset = match offset { None => geometry::zero_point(), Some(o) => o }; GlyphData { index: index, advance: advance, offset: offset, is_missing: is_missing, cluster_start: cluster_start, ligature_start: ligature_start, } } } // This enum is a proxy that's provided to GlyphStore clients when iterating // through glyphs (either for a particular TextRun offset, or all glyphs). // Rather than eagerly assembling and copying glyph data, it only retrieves // values as they are needed from the GlyphStore, using provided offsets. enum GlyphInfo<'a> { SimpleGlyphInfo(&'a GlyphStore, uint), DetailGlyphInfo(&'a GlyphStore, uint, u16) } impl<'a> GlyphInfo<'a> { pub fn index(self) -> GlyphIndex { match self { SimpleGlyphInfo(store, entry_i) => store.entry_buffer[entry_i].index(), DetailGlyphInfo(store, entry_i, detail_j) => { store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).index } } } #[inline(always)] // FIXME: Resolution conflicts with IteratorUtil trait so adding trailing _ pub fn advance(self) -> Au { match self { SimpleGlyphInfo(store, entry_i) => store.entry_buffer[entry_i].advance(), DetailGlyphInfo(store, entry_i, detail_j) => { store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).advance } } } pub fn offset(self) -> Option<Point2D<Au>> { match self { SimpleGlyphInfo(_, _) => None, DetailGlyphInfo(store, entry_i, detail_j) => { Some(store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).offset) } } } } // Public data structure and API for storing and retrieving glyph data pub struct GlyphStore { // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. entry_buffer: ~[GlyphEntry], detail_store: DetailedGlyphStore, is_whitespace: bool, } impl<'a> GlyphStore { // Initializes the glyph store, but doesn't actually shape anything. // Use the set_glyph, set_glyphs() methods to store glyph data. pub fn new(length: uint, is_whitespace: bool) -> GlyphStore { assert!(length > 0); GlyphStore { entry_buffer: vec::from_elem(length, GlyphEntry::initial()), detail_store: DetailedGlyphStore::new(), is_whitespace: is_whitespace, } } pub fn char_len(&self) -> uint { self.entry_buffer.len() } pub fn is_whitespace(&self) -> bool { self.is_whitespace } pub fn finalize_changes(&mut self) { self.detail_store.ensure_sorted(); } pub fn add_glyph_for_char_index(&mut self, i: uint, data: &GlyphData)
self.entry_buffer[i] = entry; } pub fn add_glyphs_for_char_index(&mut self, i: uint, data_for_glyphs: &[GlyphData]) { assert!(i < self.entry_buffer.len()); assert!(data_for_glyphs.len() > 0); let glyph_count = data_for_glyphs.len(); let first_glyph_data = data_for_glyphs[0]; let entry = match first_glyph_data.is_missing { true => GlyphEntry::missing(glyph_count), false => { let glyphs_vec = vec::from_fn(glyph_count, |i| { DetailedGlyph::new(data_for_glyphs[i].index, data_for_glyphs[i].advance, data_for_glyphs[i].offset) }); self.detail_store.add_detailed_glyphs_for_entry(i, glyphs_vec); GlyphEntry::complex(first_glyph_data.cluster_start, first_glyph_data.ligature_start, glyph_count) } }.adapt_character_flags_of_entry(self.entry_buffer[i]); debug!("Adding multiple glyphs[idx={:u}, count={:u}]: {:?}", i, glyph_count, entry); self.entry_buffer[i] = entry; } // used when a character index has no associated glyph---for example, a ligature continuation. pub fn add_nonglyph_for_char_index(&mut self, i: uint, cluster_start: bool, ligature_start: bool) { assert!(i < self.entry_buffer.len()); let entry = GlyphEntry::complex(cluster_start, ligature_start, 0); debug!("adding spacer for chracter without associated glyph[idx={:u}]", i); self.entry_buffer[i] = entry; } pub fn iter_glyphs_for_char_index(&'a self, i: uint) -> GlyphIterator<'a> { self.iter_glyphs_for_char_range(&Range::new(i, 1)) } #[inline] pub fn iter_glyphs_for_char_range(&'a self, rang: &Range) -> GlyphIterator<'a> { if rang.begin() >= self.entry_buffer.len() { fail!("iter_glyphs_for_range: range.begin beyond length!"); } if rang.end() > self.entry_buffer.len() { fail!("iter_glyphs_for_range: range.end beyond length!"); } GlyphIterator { store: self, char_index: rang.begin(), char_range: rang.eachi(), glyph_range: None } } // getter methods pub fn char_is_space(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_space() } pub fn char_is_tab(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_tab() } pub fn char_is_newline(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_newline() } pub fn is_ligature_start(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].is_ligature_start() } pub fn is_cluster_start(&self, i
{ fn glyph_is_compressible(data: &GlyphData) -> bool { is_simple_glyph_id(data.index) && is_simple_advance(data.advance) && data.offset == geometry::zero_point() && data.cluster_start // others are stored in detail buffer } assert!(data.ligature_start); // can't compress ligature continuation glyphs. assert!(i < self.entry_buffer.len()); let entry = match (data.is_missing, glyph_is_compressible(data)) { (true, _) => GlyphEntry::missing(1), (false, true) => GlyphEntry::simple(data.index, data.advance), (false, false) => { let glyph = [DetailedGlyph::new(data.index, data.advance, data.offset)]; self.detail_store.add_detailed_glyphs_for_entry(i, glyph); GlyphEntry::complex(data.cluster_start, data.ligature_start, 1) } }.adapt_character_flags_of_entry(self.entry_buffer[i]);
identifier_body
glyph.rs
starts_ligature, glyph_count); let mut val = FLAG_NOT_MISSING; if!starts_cluster { val |= FLAG_NOT_CLUSTER_START; } if!starts_ligature { val |= FLAG_NOT_LIGATURE_GROUP_START; } val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; GlyphEntry::new(val) } /// Create a GlyphEntry for the case where glyphs couldn't be found for the specified /// character. fn missing(glyph_count: uint) -> GlyphEntry { assert!(glyph_count <= u16::MAX as uint); GlyphEntry::new((glyph_count as u32) << GLYPH_COUNT_SHIFT) } } /// The index of a particular glyph within a font pub type GlyphIndex = u32; // TODO: unify with bit flags? #[deriving(Eq)] pub enum BreakType { BreakTypeNone, BreakTypeNormal, BreakTypeHyphen } static BREAK_TYPE_NONE: u8 = 0x0; static BREAK_TYPE_NORMAL: u8 = 0x1; static BREAK_TYPE_HYPHEN: u8 = 0x2; fn break_flag_to_enum(flag: u8) -> BreakType { if (flag & BREAK_TYPE_NORMAL)!= 0 { return BreakTypeNormal; } if (flag & BREAK_TYPE_HYPHEN)!= 0 { return BreakTypeHyphen; } BreakTypeNone } fn break_enum_to_flag(e: BreakType) -> u8 { match e { BreakTypeNone => BREAK_TYPE_NONE, BreakTypeNormal => BREAK_TYPE_NORMAL, BreakTypeHyphen => BREAK_TYPE_HYPHEN, } } // TODO: make this more type-safe. static FLAG_CHAR_IS_SPACE: u32 = 0x10000000; // These two bits store some BREAK_TYPE_* flags static FLAG_CAN_BREAK_MASK: u32 = 0x60000000; static FLAG_CAN_BREAK_SHIFT: u32 = 29; static FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000; // glyph advance; in Au's. static GLYPH_ADVANCE_MASK: u32 = 0x0FFF0000; static GLYPH_ADVANCE_SHIFT: u32 = 16; static GLYPH_ID_MASK: u32 = 0x0000FFFF; // Non-simple glyphs (more than one glyph per char; missing glyph, // newline, tab, large advance, or nonzero x/y offsets) may have one // or more detailed glyphs associated with them. They are stored in a // side array so that there is a 1:1 mapping of GlyphEntry to // unicode char. // The number of detailed glyphs for this char. If the char couldn't // be mapped to a glyph (!FLAG_NOT_MISSING), then this actually holds // the UTF8 code point instead. static GLYPH_COUNT_MASK: u32 = 0x00FFFF00; static GLYPH_COUNT_SHIFT: u32 = 8; // N.B. following Gecko, these are all inverted so that a lot of // missing chars can be memset with zeros in one fell swoop. static FLAG_NOT_MISSING: u32 = 0x00000001; static FLAG_NOT_CLUSTER_START: u32 = 0x00000002; static FLAG_NOT_LIGATURE_GROUP_START: u32 = 0x00000004; static FLAG_CHAR_IS_TAB: u32 = 0x00000008; static FLAG_CHAR_IS_NEWLINE: u32 = 0x00000010; //static FLAG_CHAR_IS_LOW_SURROGATE: u32 = 0x00000020; //static CHAR_IDENTITY_FLAGS_MASK: u32 = 0x00000038; fn is_simple_glyph_id(glyphId: GlyphIndex) -> bool { ((glyphId as u32) & GLYPH_ID_MASK) == glyphId } fn is_simple_advance(advance: Au) -> bool { let unsignedAu = advance.to_u32().unwrap(); (unsignedAu & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsignedAu } type DetailedGlyphCount = u16; // Getters and setters for GlyphEntry. Setter methods are functional, // because GlyphEntry is immutable and only a u32 in size. impl GlyphEntry { // getter methods #[inline(always)] fn advance(&self) -> Au { NumCast::from((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT).unwrap() } fn index(&self) -> GlyphIndex { self.value & GLYPH_ID_MASK } fn is_ligature_start(&self) -> bool { self.has_flag(!FLAG_NOT_LIGATURE_GROUP_START) } fn is_cluster_start(&self) -> bool { self.has_flag(!FLAG_NOT_CLUSTER_START) } // True if original char was normal (U+0020) space. Other chars may // map to space glyph, but this does not account for them. fn char_is_space(&self) -> bool { self.has_flag(FLAG_CHAR_IS_SPACE) } fn char_is_tab(&self) -> bool { !self.is_simple() && self.has_flag(FLAG_CHAR_IS_TAB) } fn char_is_newline(&self) -> bool { !self.is_simple() && self.has_flag(FLAG_CHAR_IS_NEWLINE) } fn can_break_before(&self) -> BreakType { let flag = ((self.value & FLAG_CAN_BREAK_MASK) >> FLAG_CAN_BREAK_SHIFT) as u8; break_flag_to_enum(flag) } // setter methods #[inline(always)] fn set_char_is_space(&self) -> GlyphEntry { GlyphEntry::new(self.value | FLAG_CHAR_IS_SPACE) } #[inline(always)] fn set_char_is_tab(&self) -> GlyphEntry { assert!(!self.is_simple()); GlyphEntry::new(self.value | FLAG_CHAR_IS_TAB) } #[inline(always)] fn set_char_is_newline(&self) -> GlyphEntry { assert!(!self.is_simple()); GlyphEntry::new(self.value | FLAG_CHAR_IS_NEWLINE) } #[inline(always)] fn set_can_break_before(&self, e: BreakType) -> GlyphEntry { let flag = (break_enum_to_flag(e) as u32) << FLAG_CAN_BREAK_SHIFT; GlyphEntry::new(self.value | flag) } // helper methods fn glyph_count(&self) -> u16 { assert!(!self.is_simple()); ((self.value & GLYPH_COUNT_MASK) >> GLYPH_COUNT_SHIFT) as u16 } #[inline(always)] fn is_simple(&self) -> bool { self.has_flag(FLAG_IS_SIMPLE_GLYPH) } #[inline(always)] fn has_flag(&self, flag: u32) -> bool { (self.value & flag)!= 0 } #[inline(always)] fn adapt_character_flags_of_entry(&self, other: GlyphEntry) -> GlyphEntry { GlyphEntry { value: self.value | other.value } } } // Stores data for a detailed glyph, in the case that several glyphs // correspond to one character, or the glyph's data couldn't be packed. #[deriving(Clone)] struct DetailedGlyph { index: GlyphIndex, // glyph's advance, in the text's direction (RTL or RTL) advance: Au, // glyph's offset from the font's em-box (from top-left) offset: Point2D<Au> } impl DetailedGlyph { fn new(index: GlyphIndex, advance: Au, offset: Point2D<Au>) -> DetailedGlyph { DetailedGlyph { index: index, advance: advance, offset: offset } } } #[deriving(Eq, Clone)] struct DetailedGlyphRecord { // source string offset/GlyphEntry offset in the TextRun entry_offset: uint, // offset into the detailed glyphs buffer detail_offset: uint } impl Ord for DetailedGlyphRecord { fn lt(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset < other.entry_offset } fn le(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset <= other.entry_offset } fn ge(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset >= other.entry_offset } fn gt(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset > other.entry_offset } } // Manages the lookup table for detailed glyphs. Sorting is deferred // until a lookup is actually performed; this matches the expected // usage pattern of setting/appending all the detailed glyphs, and // then querying without setting. struct DetailedGlyphStore { // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. detail_buffer: ~[DetailedGlyph], // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. detail_lookup: ~[DetailedGlyphRecord], lookup_is_sorted: bool, } impl<'a> DetailedGlyphStore { fn new() -> DetailedGlyphStore { DetailedGlyphStore { detail_buffer: ~[], // TODO: default size? detail_lookup: ~[], lookup_is_sorted: false } } fn add_detailed_glyphs_for_entry(&mut self, entry_offset: uint, glyphs: &[DetailedGlyph]) { let entry = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: self.detail_buffer.len() }; debug!("Adding entry[off={:u}] for detailed glyphs: {:?}", entry_offset, glyphs); /* TODO: don't actually assert this until asserts are compiled in/out based on severity, debug/release, etc. This assertion would wreck the complexity of the lookup. See Rust Issue #3647, #2228, #3627 for related information. do self.detail_lookup.borrow |arr| { assert!arr.contains(entry) } */ self.detail_lookup.push(entry); self.detail_buffer.push_all(glyphs); self.lookup_is_sorted = false; } fn get_detailed_glyphs_for_entry(&'a self, entry_offset: uint, count: u16) -> &'a [DetailedGlyph] { debug!("Requesting detailed glyphs[n={:u}] for entry[off={:u}]", count as uint, entry_offset); // FIXME: Is this right? --pcwalton // TODO: should fix this somewhere else if count == 0 { return self.detail_buffer.slice(0, 0); } assert!((count as uint) <= self.detail_buffer.len()); assert!(self.lookup_is_sorted); let key = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: 0 // unused }; // FIXME: This is a workaround for borrow of self.detail_lookup not getting inferred. let records : &[DetailedGlyphRecord] = self.detail_lookup; match records.binary_search_index(&key) { None => fail!(~"Invalid index not found in detailed glyph lookup table!"), Some(i) => { assert!(i + (count as uint) <= self.detail_buffer.len()); // return a slice into the buffer self.detail_buffer.slice(i, i + count as uint) } } } fn get_detailed_glyph_with_index(&'a self, entry_offset: uint, detail_offset: u16) -> &'a DetailedGlyph { assert!((detail_offset as uint) <= self.detail_buffer.len()); assert!(self.lookup_is_sorted); let key = DetailedGlyphRecord { entry_offset: entry_offset, detail_offset: 0 // unused }; // FIXME: This is a workaround for borrow of self.detail_lookup not getting inferred. let records: &[DetailedGlyphRecord] = self.detail_lookup; match records.binary_search_index(&key) { None => fail!(~"Invalid index not found in detailed glyph lookup table!"), Some(i) => { assert!(i + (detail_offset as uint) < self.detail_buffer.len()); &self.detail_buffer[i+(detail_offset as uint)] } } } fn ensure_sorted(&mut self) { if self.lookup_is_sorted { return; } // Sorting a unique vector is surprisingly hard. The follwing // code is a good argument for using DVecs, but they require // immutable locations thus don't play well with freezing. // Thar be dragons here. You have been warned. (Tips accepted.) let mut unsorted_records: ~[DetailedGlyphRecord] = ~[]; mem::swap(&mut self.detail_lookup, &mut unsorted_records); let mut mut_records : ~[DetailedGlyphRecord] = unsorted_records; mut_records.sort_by(|a, b| { if a < b { Less } else { Greater } }); let mut sorted_records = mut_records; mem::swap(&mut self.detail_lookup, &mut sorted_records); self.lookup_is_sorted = true; } } // This struct is used by GlyphStore clients to provide new glyph data. // It should be allocated on the stack and passed by reference to GlyphStore. pub struct GlyphData { index: GlyphIndex,
advance: Au, offset: Point2D<Au>, is_missing: bool, cluster_start: bool, ligature_start: bool, } impl GlyphData { pub fn new(index: GlyphIndex, advance: Au, offset: Option<Point2D<Au>>, is_missing: bool, cluster_start: bool, ligature_start: bool) -> GlyphData { let offset = match offset { None => geometry::zero_point(), Some(o) => o }; GlyphData { index: index, advance: advance, offset: offset, is_missing: is_missing, cluster_start: cluster_start, ligature_start: ligature_start, } } } // This enum is a proxy that's provided to GlyphStore clients when iterating // through glyphs (either for a particular TextRun offset, or all glyphs). // Rather than eagerly assembling and copying glyph data, it only retrieves // values as they are needed from the GlyphStore, using provided offsets. enum GlyphInfo<'a> { SimpleGlyphInfo(&'a GlyphStore, uint), DetailGlyphInfo(&'a GlyphStore, uint, u16) } impl<'a> GlyphInfo<'a> { pub fn index(self) -> GlyphIndex { match self { SimpleGlyphInfo(store, entry_i) => store.entry_buffer[entry_i].index(), DetailGlyphInfo(store, entry_i, detail_j) => { store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).index } } } #[inline(always)] // FIXME: Resolution conflicts with IteratorUtil trait so adding trailing _ pub fn advance(self) -> Au { match self { SimpleGlyphInfo(store, entry_i) => store.entry_buffer[entry_i].advance(), DetailGlyphInfo(store, entry_i, detail_j) => { store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).advance } } } pub fn offset(self) -> Option<Point2D<Au>> { match self { SimpleGlyphInfo(_, _) => None, DetailGlyphInfo(store, entry_i, detail_j) => { Some(store.detail_store.get_detailed_glyph_with_index(entry_i, detail_j).offset) } } } } // Public data structure and API for storing and retrieving glyph data pub struct GlyphStore { // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // optimization. entry_buffer: ~[GlyphEntry], detail_store: DetailedGlyphStore, is_whitespace: bool, } impl<'a> GlyphStore { // Initializes the glyph store, but doesn't actually shape anything. // Use the set_glyph, set_glyphs() methods to store glyph data. pub fn new(length: uint, is_whitespace: bool) -> GlyphStore { assert!(length > 0); GlyphStore { entry_buffer: vec::from_elem(length, GlyphEntry::initial()), detail_store: DetailedGlyphStore::new(), is_whitespace: is_whitespace, } } pub fn char_len(&self) -> uint { self.entry_buffer.len() } pub fn is_whitespace(&self) -> bool { self.is_whitespace } pub fn finalize_changes(&mut self) { self.detail_store.ensure_sorted(); } pub fn add_glyph_for_char_index(&mut self, i: uint, data: &GlyphData) { fn glyph_is_compressible(data: &GlyphData) -> bool { is_simple_glyph_id(data.index) && is_simple_advance(data.advance) && data.offset == geometry::zero_point() && data.cluster_start // others are stored in detail buffer } assert!(data.ligature_start); // can't compress ligature continuation glyphs. assert!(i < self.entry_buffer.len()); let entry = match (data.is_missing, glyph_is_compressible(data)) { (true, _) => GlyphEntry::missing(1), (false, true) => GlyphEntry::simple(data.index, data.advance), (false, false) => { let glyph = [DetailedGlyph::new(data.index, data.advance, data.offset)]; self.detail_store.add_detailed_glyphs_for_entry(i, glyph); GlyphEntry::complex(data.cluster_start, data.ligature_start, 1) } }.adapt_character_flags_of_entry(self.entry_buffer[i]); self.entry_buffer[i] = entry; } pub fn add_glyphs_for_char_index(&mut self, i: uint, data_for_glyphs: &[GlyphData]) { assert!(i < self.entry_buffer.len()); assert!(data_for_glyphs.len() > 0); let glyph_count = data_for_glyphs.len(); let first_glyph_data = data_for_glyphs[0]; let entry = match first_glyph_data.is_missing { true => GlyphEntry::missing(glyph_count), false => { let glyphs_vec = vec::from_fn(glyph_count, |i| { DetailedGlyph::new(data_for_glyphs[i].index, data_for_glyphs[i].advance, data_for_glyphs[i].offset) }); self.detail_store.add_detailed_glyphs_for_entry(i, glyphs_vec); GlyphEntry::complex(first_glyph_data.cluster_start, first_glyph_data.ligature_start, glyph_count) } }.adapt_character_flags_of_entry(self.entry_buffer[i]); debug!("Adding multiple glyphs[idx={:u}, count={:u}]: {:?}", i, glyph_count, entry); self.entry_buffer[i] = entry; } // used when a character index has no associated glyph---for example, a ligature continuation. pub fn add_nonglyph_for_char_index(&mut self, i: uint, cluster_start: bool, ligature_start: bool) { assert!(i < self.entry_buffer.len()); let entry = GlyphEntry::complex(cluster_start, ligature_start, 0); debug!("adding spacer for chracter without associated glyph[idx={:u}]", i); self.entry_buffer[i] = entry; } pub fn iter_glyphs_for_char_index(&'a self, i: uint) -> GlyphIterator<'a> { self.iter_glyphs_for_char_range(&Range::new(i, 1)) } #[inline] pub fn iter_glyphs_for_char_range(&'a self, rang: &Range) -> GlyphIterator<'a> { if rang.begin() >= self.entry_buffer.len() { fail!("iter_glyphs_for_range: range.begin beyond length!"); } if rang.end() > self.entry_buffer.len() { fail!("iter_glyphs_for_range: range.end beyond length!"); } GlyphIterator { store: self, char_index: rang.begin(), char_range: rang.eachi(), glyph_range: None } } // getter methods pub fn char_is_space(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_space() } pub fn char_is_tab(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_tab() } pub fn char_is_newline(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].char_is_newline() } pub fn is_ligature_start(&self, i: uint) -> bool { assert!(i < self.entry_buffer.len()); self.entry_buffer[i].is_ligature_start() } pub fn is_cluster_start(&self, i:
random_line_split
mod.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// use tink_core::{primitiveset::Entry, Primitive}; use tink_proto::{keyset::Key, KeyStatusType, OutputPrefixType}; use tink_tests::{new_dummy_key, DummyMac}; fn create_keyset() -> Vec<Key> { let key_id0 = 1234543; let key_id1 = 7213743; let key_id2 = key_id1; let key_id3 = 947327; let key_id4 = 529472; let key_id5 = key_id0; vec![ new_dummy_key(key_id0, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id1, KeyStatusType::Enabled, OutputPrefixType::Legacy), new_dummy_key(key_id2, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id3, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id4, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id5, KeyStatusType::Enabled, OutputPrefixType::Tink), ] } #[test] fn test_primitive_set_basic() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); assert!(ps.primary.is_none()); assert!(ps.entries.is_empty()); // generate test keys let keys = create_keyset(); // add all test primitives let mut macs = Vec::with_capacity(keys.len()); let mut entries = Vec::with_capacity(keys.len()); for i in 0..keys.len() { let mac = Box::new(DummyMac { name: format!("Mac#{}", i), }); macs.push(mac); entries.push(ps.add(Primitive::Mac(macs[i].clone()), &keys[i]).unwrap()); } // set primary entry let primary_id = 2; ps.primary = Some(entries[primary_id].clone()); // check raw primitives let raw_ids = vec![keys[3].key_id, keys[4].key_id]; let raw_macs = vec![macs[3].clone(), macs[4].clone()]; let raw_statuses = vec![ KeyStatusType::from_i32(keys[3].status).unwrap(), KeyStatusType::from_i32(keys[4].status).unwrap(), ]; let raw_prefix_types = vec![ OutputPrefixType::from_i32(keys[3].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[4].output_prefix_type).unwrap(), ]; let raw_entries = ps.raw_entries(); assert!( validate_entry_list( &raw_entries, &raw_ids, &raw_macs, &raw_statuses, &raw_prefix_types ), "raw primitives do not match input" ); // check tink primitives, same id let tink_ids = vec![keys[0].key_id, keys[5].key_id]; let tink_macs = vec![macs[0].clone(), macs[5].clone()]; let tink_statuses = vec![ KeyStatusType::from_i32(keys[0].status).unwrap(), KeyStatusType::from_i32(keys[5].status).unwrap(), ]; let tink_prefix_types = vec![ OutputPrefixType::from_i32(keys[0].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[5].output_prefix_type).unwrap(), ]; let prefix = tink_core::cryptofmt::output_prefix(&keys[0]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check another tink primitive let tink_ids = vec![keys[2].key_id]; let tink_macs = vec![macs[2].clone()]; let tink_statuses = vec![KeyStatusType::from_i32(keys[2].status).unwrap()]; let tink_prefix_types = vec![OutputPrefixType::from_i32(keys[2].output_prefix_type).unwrap()]; let prefix = tink_core::cryptofmt::output_prefix(&keys[2]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check legacy primitives let legacy_ids = vec![keys[1].key_id]; let legacy_macs = vec![macs[1].clone()]; let legacy_statuses = vec![KeyStatusType::from_i32(keys[1].status).unwrap()]; let legacy_prefix_types = vec![OutputPrefixType::from_i32(keys[1].output_prefix_type).unwrap()]; let legacy_prefix = tink_core::cryptofmt::output_prefix(&keys[1]).unwrap(); let legacy_entries = ps.entries_for_prefix(&legacy_prefix); assert!( validate_entry_list( &legacy_entries, &legacy_ids, &legacy_macs, &legacy_statuses, &legacy_prefix_types
"legacy primitives do not match the input key" ); } #[test] fn test_add_with_invalid_input() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); let dummy_mac = Box::new(DummyMac { name: "".to_string(), }); // unknown prefix type let invalid_key = new_dummy_key(0, KeyStatusType::Enabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac.clone()), &invalid_key) .is_err(), "expect an error when key is invalid" ); // disabled key let disabled_key = new_dummy_key(0, KeyStatusType::Disabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac), &disabled_key).is_err(), "expect an error when key is disabled" ); } fn validate_entry_list( entries: &[Entry], key_ids: &[tink_core::KeyId], macs: &[Box<DummyMac>], statuses: &[KeyStatusType], prefix_types: &[OutputPrefixType], ) -> bool { if entries.len()!= macs.len() { return false; } for (i, entry) in entries.iter().enumerate() { if!validate_entry(entry, key_ids[i], &macs[i], &statuses[i], &prefix_types[i]) { return false; } } true } // Compare an entry with the [`DummyMAC`] that was used to create the entry. fn validate_entry( entry: &Entry, key_id: tink_core::KeyId, test_mac: &DummyMac, status: &KeyStatusType, output_prefix_type: &OutputPrefixType, ) -> bool { if entry.key_id!= key_id || entry.status!= *status || entry.prefix_type!= *output_prefix_type { return false; } if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_from_slice(test_mac.name.as_bytes()); if digest!= data { return false; } } else { panic!("failed to retrieve MAC primitive"); } true }
),
random_line_split
mod.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// use tink_core::{primitiveset::Entry, Primitive}; use tink_proto::{keyset::Key, KeyStatusType, OutputPrefixType}; use tink_tests::{new_dummy_key, DummyMac}; fn create_keyset() -> Vec<Key> { let key_id0 = 1234543; let key_id1 = 7213743; let key_id2 = key_id1; let key_id3 = 947327; let key_id4 = 529472; let key_id5 = key_id0; vec![ new_dummy_key(key_id0, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id1, KeyStatusType::Enabled, OutputPrefixType::Legacy), new_dummy_key(key_id2, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id3, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id4, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id5, KeyStatusType::Enabled, OutputPrefixType::Tink), ] } #[test] fn test_primitive_set_basic() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); assert!(ps.primary.is_none()); assert!(ps.entries.is_empty()); // generate test keys let keys = create_keyset(); // add all test primitives let mut macs = Vec::with_capacity(keys.len()); let mut entries = Vec::with_capacity(keys.len()); for i in 0..keys.len() { let mac = Box::new(DummyMac { name: format!("Mac#{}", i), }); macs.push(mac); entries.push(ps.add(Primitive::Mac(macs[i].clone()), &keys[i]).unwrap()); } // set primary entry let primary_id = 2; ps.primary = Some(entries[primary_id].clone()); // check raw primitives let raw_ids = vec![keys[3].key_id, keys[4].key_id]; let raw_macs = vec![macs[3].clone(), macs[4].clone()]; let raw_statuses = vec![ KeyStatusType::from_i32(keys[3].status).unwrap(), KeyStatusType::from_i32(keys[4].status).unwrap(), ]; let raw_prefix_types = vec![ OutputPrefixType::from_i32(keys[3].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[4].output_prefix_type).unwrap(), ]; let raw_entries = ps.raw_entries(); assert!( validate_entry_list( &raw_entries, &raw_ids, &raw_macs, &raw_statuses, &raw_prefix_types ), "raw primitives do not match input" ); // check tink primitives, same id let tink_ids = vec![keys[0].key_id, keys[5].key_id]; let tink_macs = vec![macs[0].clone(), macs[5].clone()]; let tink_statuses = vec![ KeyStatusType::from_i32(keys[0].status).unwrap(), KeyStatusType::from_i32(keys[5].status).unwrap(), ]; let tink_prefix_types = vec![ OutputPrefixType::from_i32(keys[0].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[5].output_prefix_type).unwrap(), ]; let prefix = tink_core::cryptofmt::output_prefix(&keys[0]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check another tink primitive let tink_ids = vec![keys[2].key_id]; let tink_macs = vec![macs[2].clone()]; let tink_statuses = vec![KeyStatusType::from_i32(keys[2].status).unwrap()]; let tink_prefix_types = vec![OutputPrefixType::from_i32(keys[2].output_prefix_type).unwrap()]; let prefix = tink_core::cryptofmt::output_prefix(&keys[2]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check legacy primitives let legacy_ids = vec![keys[1].key_id]; let legacy_macs = vec![macs[1].clone()]; let legacy_statuses = vec![KeyStatusType::from_i32(keys[1].status).unwrap()]; let legacy_prefix_types = vec![OutputPrefixType::from_i32(keys[1].output_prefix_type).unwrap()]; let legacy_prefix = tink_core::cryptofmt::output_prefix(&keys[1]).unwrap(); let legacy_entries = ps.entries_for_prefix(&legacy_prefix); assert!( validate_entry_list( &legacy_entries, &legacy_ids, &legacy_macs, &legacy_statuses, &legacy_prefix_types ), "legacy primitives do not match the input key" ); } #[test] fn test_add_with_invalid_input() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); let dummy_mac = Box::new(DummyMac { name: "".to_string(), }); // unknown prefix type let invalid_key = new_dummy_key(0, KeyStatusType::Enabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac.clone()), &invalid_key) .is_err(), "expect an error when key is invalid" ); // disabled key let disabled_key = new_dummy_key(0, KeyStatusType::Disabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac), &disabled_key).is_err(), "expect an error when key is disabled" ); } fn validate_entry_list( entries: &[Entry], key_ids: &[tink_core::KeyId], macs: &[Box<DummyMac>], statuses: &[KeyStatusType], prefix_types: &[OutputPrefixType], ) -> bool { if entries.len()!= macs.len() { return false; } for (i, entry) in entries.iter().enumerate() { if!validate_entry(entry, key_ids[i], &macs[i], &statuses[i], &prefix_types[i]) { return false; } } true } // Compare an entry with the [`DummyMAC`] that was used to create the entry. fn validate_entry( entry: &Entry, key_id: tink_core::KeyId, test_mac: &DummyMac, status: &KeyStatusType, output_prefix_type: &OutputPrefixType, ) -> bool { if entry.key_id!= key_id || entry.status!= *status || entry.prefix_type!= *output_prefix_type
if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_from_slice(test_mac.name.as_bytes()); if digest!= data { return false; } } else { panic!("failed to retrieve MAC primitive"); } true }
{ return false; }
conditional_block
mod.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// use tink_core::{primitiveset::Entry, Primitive}; use tink_proto::{keyset::Key, KeyStatusType, OutputPrefixType}; use tink_tests::{new_dummy_key, DummyMac}; fn create_keyset() -> Vec<Key> { let key_id0 = 1234543; let key_id1 = 7213743; let key_id2 = key_id1; let key_id3 = 947327; let key_id4 = 529472; let key_id5 = key_id0; vec![ new_dummy_key(key_id0, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id1, KeyStatusType::Enabled, OutputPrefixType::Legacy), new_dummy_key(key_id2, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id3, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id4, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id5, KeyStatusType::Enabled, OutputPrefixType::Tink), ] } #[test] fn
() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); assert!(ps.primary.is_none()); assert!(ps.entries.is_empty()); // generate test keys let keys = create_keyset(); // add all test primitives let mut macs = Vec::with_capacity(keys.len()); let mut entries = Vec::with_capacity(keys.len()); for i in 0..keys.len() { let mac = Box::new(DummyMac { name: format!("Mac#{}", i), }); macs.push(mac); entries.push(ps.add(Primitive::Mac(macs[i].clone()), &keys[i]).unwrap()); } // set primary entry let primary_id = 2; ps.primary = Some(entries[primary_id].clone()); // check raw primitives let raw_ids = vec![keys[3].key_id, keys[4].key_id]; let raw_macs = vec![macs[3].clone(), macs[4].clone()]; let raw_statuses = vec![ KeyStatusType::from_i32(keys[3].status).unwrap(), KeyStatusType::from_i32(keys[4].status).unwrap(), ]; let raw_prefix_types = vec![ OutputPrefixType::from_i32(keys[3].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[4].output_prefix_type).unwrap(), ]; let raw_entries = ps.raw_entries(); assert!( validate_entry_list( &raw_entries, &raw_ids, &raw_macs, &raw_statuses, &raw_prefix_types ), "raw primitives do not match input" ); // check tink primitives, same id let tink_ids = vec![keys[0].key_id, keys[5].key_id]; let tink_macs = vec![macs[0].clone(), macs[5].clone()]; let tink_statuses = vec![ KeyStatusType::from_i32(keys[0].status).unwrap(), KeyStatusType::from_i32(keys[5].status).unwrap(), ]; let tink_prefix_types = vec![ OutputPrefixType::from_i32(keys[0].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[5].output_prefix_type).unwrap(), ]; let prefix = tink_core::cryptofmt::output_prefix(&keys[0]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check another tink primitive let tink_ids = vec![keys[2].key_id]; let tink_macs = vec![macs[2].clone()]; let tink_statuses = vec![KeyStatusType::from_i32(keys[2].status).unwrap()]; let tink_prefix_types = vec![OutputPrefixType::from_i32(keys[2].output_prefix_type).unwrap()]; let prefix = tink_core::cryptofmt::output_prefix(&keys[2]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check legacy primitives let legacy_ids = vec![keys[1].key_id]; let legacy_macs = vec![macs[1].clone()]; let legacy_statuses = vec![KeyStatusType::from_i32(keys[1].status).unwrap()]; let legacy_prefix_types = vec![OutputPrefixType::from_i32(keys[1].output_prefix_type).unwrap()]; let legacy_prefix = tink_core::cryptofmt::output_prefix(&keys[1]).unwrap(); let legacy_entries = ps.entries_for_prefix(&legacy_prefix); assert!( validate_entry_list( &legacy_entries, &legacy_ids, &legacy_macs, &legacy_statuses, &legacy_prefix_types ), "legacy primitives do not match the input key" ); } #[test] fn test_add_with_invalid_input() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); let dummy_mac = Box::new(DummyMac { name: "".to_string(), }); // unknown prefix type let invalid_key = new_dummy_key(0, KeyStatusType::Enabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac.clone()), &invalid_key) .is_err(), "expect an error when key is invalid" ); // disabled key let disabled_key = new_dummy_key(0, KeyStatusType::Disabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac), &disabled_key).is_err(), "expect an error when key is disabled" ); } fn validate_entry_list( entries: &[Entry], key_ids: &[tink_core::KeyId], macs: &[Box<DummyMac>], statuses: &[KeyStatusType], prefix_types: &[OutputPrefixType], ) -> bool { if entries.len()!= macs.len() { return false; } for (i, entry) in entries.iter().enumerate() { if!validate_entry(entry, key_ids[i], &macs[i], &statuses[i], &prefix_types[i]) { return false; } } true } // Compare an entry with the [`DummyMAC`] that was used to create the entry. fn validate_entry( entry: &Entry, key_id: tink_core::KeyId, test_mac: &DummyMac, status: &KeyStatusType, output_prefix_type: &OutputPrefixType, ) -> bool { if entry.key_id!= key_id || entry.status!= *status || entry.prefix_type!= *output_prefix_type { return false; } if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_from_slice(test_mac.name.as_bytes()); if digest!= data { return false; } } else { panic!("failed to retrieve MAC primitive"); } true }
test_primitive_set_basic
identifier_name
mod.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// use tink_core::{primitiveset::Entry, Primitive}; use tink_proto::{keyset::Key, KeyStatusType, OutputPrefixType}; use tink_tests::{new_dummy_key, DummyMac}; fn create_keyset() -> Vec<Key> { let key_id0 = 1234543; let key_id1 = 7213743; let key_id2 = key_id1; let key_id3 = 947327; let key_id4 = 529472; let key_id5 = key_id0; vec![ new_dummy_key(key_id0, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id1, KeyStatusType::Enabled, OutputPrefixType::Legacy), new_dummy_key(key_id2, KeyStatusType::Enabled, OutputPrefixType::Tink), new_dummy_key(key_id3, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id4, KeyStatusType::Enabled, OutputPrefixType::Raw), new_dummy_key(key_id5, KeyStatusType::Enabled, OutputPrefixType::Tink), ] } #[test] fn test_primitive_set_basic() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); assert!(ps.primary.is_none()); assert!(ps.entries.is_empty()); // generate test keys let keys = create_keyset(); // add all test primitives let mut macs = Vec::with_capacity(keys.len()); let mut entries = Vec::with_capacity(keys.len()); for i in 0..keys.len() { let mac = Box::new(DummyMac { name: format!("Mac#{}", i), }); macs.push(mac); entries.push(ps.add(Primitive::Mac(macs[i].clone()), &keys[i]).unwrap()); } // set primary entry let primary_id = 2; ps.primary = Some(entries[primary_id].clone()); // check raw primitives let raw_ids = vec![keys[3].key_id, keys[4].key_id]; let raw_macs = vec![macs[3].clone(), macs[4].clone()]; let raw_statuses = vec![ KeyStatusType::from_i32(keys[3].status).unwrap(), KeyStatusType::from_i32(keys[4].status).unwrap(), ]; let raw_prefix_types = vec![ OutputPrefixType::from_i32(keys[3].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[4].output_prefix_type).unwrap(), ]; let raw_entries = ps.raw_entries(); assert!( validate_entry_list( &raw_entries, &raw_ids, &raw_macs, &raw_statuses, &raw_prefix_types ), "raw primitives do not match input" ); // check tink primitives, same id let tink_ids = vec![keys[0].key_id, keys[5].key_id]; let tink_macs = vec![macs[0].clone(), macs[5].clone()]; let tink_statuses = vec![ KeyStatusType::from_i32(keys[0].status).unwrap(), KeyStatusType::from_i32(keys[5].status).unwrap(), ]; let tink_prefix_types = vec![ OutputPrefixType::from_i32(keys[0].output_prefix_type).unwrap(), OutputPrefixType::from_i32(keys[5].output_prefix_type).unwrap(), ]; let prefix = tink_core::cryptofmt::output_prefix(&keys[0]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check another tink primitive let tink_ids = vec![keys[2].key_id]; let tink_macs = vec![macs[2].clone()]; let tink_statuses = vec![KeyStatusType::from_i32(keys[2].status).unwrap()]; let tink_prefix_types = vec![OutputPrefixType::from_i32(keys[2].output_prefix_type).unwrap()]; let prefix = tink_core::cryptofmt::output_prefix(&keys[2]).unwrap(); let tink_entries = ps.entries_for_prefix(&prefix); assert!( validate_entry_list( &tink_entries, &tink_ids, &tink_macs, &tink_statuses, &tink_prefix_types ), "tink primitives do not match the input key" ); // check legacy primitives let legacy_ids = vec![keys[1].key_id]; let legacy_macs = vec![macs[1].clone()]; let legacy_statuses = vec![KeyStatusType::from_i32(keys[1].status).unwrap()]; let legacy_prefix_types = vec![OutputPrefixType::from_i32(keys[1].output_prefix_type).unwrap()]; let legacy_prefix = tink_core::cryptofmt::output_prefix(&keys[1]).unwrap(); let legacy_entries = ps.entries_for_prefix(&legacy_prefix); assert!( validate_entry_list( &legacy_entries, &legacy_ids, &legacy_macs, &legacy_statuses, &legacy_prefix_types ), "legacy primitives do not match the input key" ); } #[test] fn test_add_with_invalid_input() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); let dummy_mac = Box::new(DummyMac { name: "".to_string(), }); // unknown prefix type let invalid_key = new_dummy_key(0, KeyStatusType::Enabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac.clone()), &invalid_key) .is_err(), "expect an error when key is invalid" ); // disabled key let disabled_key = new_dummy_key(0, KeyStatusType::Disabled, OutputPrefixType::UnknownPrefix); assert!( ps.add(Primitive::Mac(dummy_mac), &disabled_key).is_err(), "expect an error when key is disabled" ); } fn validate_entry_list( entries: &[Entry], key_ids: &[tink_core::KeyId], macs: &[Box<DummyMac>], statuses: &[KeyStatusType], prefix_types: &[OutputPrefixType], ) -> bool { if entries.len()!= macs.len() { return false; } for (i, entry) in entries.iter().enumerate() { if!validate_entry(entry, key_ids[i], &macs[i], &statuses[i], &prefix_types[i]) { return false; } } true } // Compare an entry with the [`DummyMAC`] that was used to create the entry. fn validate_entry( entry: &Entry, key_id: tink_core::KeyId, test_mac: &DummyMac, status: &KeyStatusType, output_prefix_type: &OutputPrefixType, ) -> bool
{ if entry.key_id != key_id || entry.status != *status || entry.prefix_type != *output_prefix_type { return false; } if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_from_slice(test_mac.name.as_bytes()); if digest != data { return false; } } else { panic!("failed to retrieve MAC primitive"); } true }
identifier_body
sanity_checks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this? #![allow(unused_imports)] use std::mem; macro_rules! check_enum_value { ($a:expr, $b:expr) => { unsafe { mem::transmute::<[u32; $a as usize], [u32; $b as usize]>([0; $a as usize]); } } } // NB: It's a shame we can't do this statically with bitflags, but no // const-fn and no other way to access the numerical value :-( macro_rules! check_enum_value_non_static { ($a:expr, $b:expr) => { assert_eq!($a as usize, $b as usize); } } #[test] fn assert_restyle_hints_match() { use style::restyle_hints::*; // For flags use style::gecko_bindings::structs::nsRestyleHint; check_enum_value_non_static!(nsRestyleHint::eRestyle_Self, RESTYLE_SELF.bits()); // XXX This for Servo actually means something like an hypothetical // Restyle_AllDescendants (but without running selector matching on the // element). ServoRestyleManager interprets it like that, but in practice we // should align the behavior with Gecko adding a new restyle hint, maybe? // // See https://bugzilla.mozilla.org/show_bug.cgi?id=1291786 check_enum_value_non_static!(nsRestyleHint::eRestyle_SomeDescendants, RESTYLE_DESCENDANTS.bits()); check_enum_value_non_static!(nsRestyleHint::eRestyle_LaterSiblings, RESTYLE_LATER_SIBLINGS.bits()); } // Note that we can't call each_pseudo_element, parse_pseudo_element, or // similar, because we'd need the foreign atom symbols to link. #[test] fn
() { let mut saw_before = false; let mut saw_after = false; macro_rules! pseudo_element { (":before", $atom:expr, false) => { saw_before = true; }; (":after", $atom:expr, false) => { saw_after = true; }; ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => { // Do nothing }; } include!("../../../components/style/gecko/generated/gecko_pseudo_element_helper.rs"); assert!(saw_before); assert!(saw_after); }
assert_basic_pseudo_elements
identifier_name
sanity_checks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this? #![allow(unused_imports)] use std::mem; macro_rules! check_enum_value { ($a:expr, $b:expr) => { unsafe { mem::transmute::<[u32; $a as usize], [u32; $b as usize]>([0; $a as usize]); } } } // NB: It's a shame we can't do this statically with bitflags, but no // const-fn and no other way to access the numerical value :-( macro_rules! check_enum_value_non_static { ($a:expr, $b:expr) => { assert_eq!($a as usize, $b as usize); } } #[test] fn assert_restyle_hints_match() { use style::restyle_hints::*; // For flags use style::gecko_bindings::structs::nsRestyleHint; check_enum_value_non_static!(nsRestyleHint::eRestyle_Self, RESTYLE_SELF.bits()); // XXX This for Servo actually means something like an hypothetical // Restyle_AllDescendants (but without running selector matching on the // element). ServoRestyleManager interprets it like that, but in practice we // should align the behavior with Gecko adding a new restyle hint, maybe? // // See https://bugzilla.mozilla.org/show_bug.cgi?id=1291786 check_enum_value_non_static!(nsRestyleHint::eRestyle_SomeDescendants, RESTYLE_DESCENDANTS.bits()); check_enum_value_non_static!(nsRestyleHint::eRestyle_LaterSiblings, RESTYLE_LATER_SIBLINGS.bits()); } // Note that we can't call each_pseudo_element, parse_pseudo_element, or // similar, because we'd need the foreign atom symbols to link. #[test] fn assert_basic_pseudo_elements() { let mut saw_before = false; let mut saw_after = false; macro_rules! pseudo_element { (":before", $atom:expr, false) => { saw_before = true; }; (":after", $atom:expr, false) => { saw_after = true; }; ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => { // Do nothing }; } include!("../../../components/style/gecko/generated/gecko_pseudo_element_helper.rs"); assert!(saw_before);
assert!(saw_after); }
random_line_split
sanity_checks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this? #![allow(unused_imports)] use std::mem; macro_rules! check_enum_value { ($a:expr, $b:expr) => { unsafe { mem::transmute::<[u32; $a as usize], [u32; $b as usize]>([0; $a as usize]); } } } // NB: It's a shame we can't do this statically with bitflags, but no // const-fn and no other way to access the numerical value :-( macro_rules! check_enum_value_non_static { ($a:expr, $b:expr) => { assert_eq!($a as usize, $b as usize); } } #[test] fn assert_restyle_hints_match() { use style::restyle_hints::*; // For flags use style::gecko_bindings::structs::nsRestyleHint; check_enum_value_non_static!(nsRestyleHint::eRestyle_Self, RESTYLE_SELF.bits()); // XXX This for Servo actually means something like an hypothetical // Restyle_AllDescendants (but without running selector matching on the // element). ServoRestyleManager interprets it like that, but in practice we // should align the behavior with Gecko adding a new restyle hint, maybe? // // See https://bugzilla.mozilla.org/show_bug.cgi?id=1291786 check_enum_value_non_static!(nsRestyleHint::eRestyle_SomeDescendants, RESTYLE_DESCENDANTS.bits()); check_enum_value_non_static!(nsRestyleHint::eRestyle_LaterSiblings, RESTYLE_LATER_SIBLINGS.bits()); } // Note that we can't call each_pseudo_element, parse_pseudo_element, or // similar, because we'd need the foreign atom symbols to link. #[test] fn assert_basic_pseudo_elements()
}
{ let mut saw_before = false; let mut saw_after = false; macro_rules! pseudo_element { (":before", $atom:expr, false) => { saw_before = true; }; (":after", $atom:expr, false) => { saw_after = true; }; ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => { // Do nothing }; } include!("../../../components/style/gecko/generated/gecko_pseudo_element_helper.rs"); assert!(saw_before); assert!(saw_after);
identifier_body
coercion.rs
// Copyright 2012 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. /*! # Type Coercion Under certain circumstances we will coerce from one type to another, for example by auto-borrowing. This occurs in situations where the compiler has a firm 'expected type' that was supplied from the user, and where the actual type is similar to that expected type in purpose but not in representation (so actual subtyping is inappropriate). ## Reborrowing Note that if we are expecting a borrowed pointer, we will *reborrow* even if the argument provided was already a borrowed pointer. This is useful for freezing mut/const things (that is, when the expected is &T but you have &const T or &mut T) and also for avoiding the linearity of mut things (when the expected is &mut T and you have &mut T). See the various `src/test/run-pass/coerce-reborrow-*.rs` tests for examples of where this is useful. ## Subtle note When deciding what type coercions to consider, we do not attempt to resolve any type variables we may encounter. This is because `b` represents the expected type "as the user wrote it", meaning that if the user defined a generic function like fn foo<A>(a: A, b: A) {... } and then we wrote `foo(&1, @2)`, we will not auto-borrow either argument. In older code we went to some lengths to resolve the `b` variable, which could mean that we'd auto-borrow later arguments but not earlier ones, which seems very confusing. ## Subtler note However, right now, if the user manually specifies the values for the type variables, as so: foo::<&int>(@1, @2) then we *will* auto-borrow, because we can't distinguish this from a function that declared `&int`. This is inconsistent but it's easiest at the moment. The right thing to do, I think, is to consider the *unsubstituted* type when deciding whether to auto-borrow, but the *substituted* type when considering the bounds and so forth. But most of our methods don't give access to the unsubstituted type, and rightly so because they'd be error-prone. So maybe the thing to do is to actually determine the kind of coercions that should occur separately and pass them in. Or maybe it's ok as is. Anyway, it's sort of a minor point so I've opted to leave it for later---after all we may want to adjust precisely when coercions occur. */ use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowFn}; use middle::ty::{AutoDerefRef}; use middle::ty::{vstore_slice, vstore_box, vstore_uniq}; use middle::ty::{mt}; use middle::ty; use middle::typeck::infer::{CoerceResult, resolve_type, Coercion}; use middle::typeck::infer::combine::CombineFields; use middle::typeck::infer::sub::Sub; use middle::typeck::infer::to_str::InferStr; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use util::common::indenter; use syntax::ast::m_imm; use syntax::ast; // Note: Coerce is not actually a combiner, in that it does not // conform to the same interface, though it performs a similar // function. pub struct Coerce(CombineFields); impl Coerce { pub fn tys(&self, a: ty::t, b: ty::t) -> CoerceResult { debug!("Coerce.tys(%s => %s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); let _indent = indenter(); // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match ty::get(b).sty { ty::ty_rptr(_, mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_pointer(a, sty_a, b, mt_b) }; } ty::ty_estr(vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_string(a, sty_a, b) }; } ty::ty_evec(mt_b, vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_vector(a, sty_a, b, mt_b) }; } ty::ty_closure(ty::ClosureTy {sigil: ast::BorrowedSigil, _}) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_fn(a, sty_a, b) }; } ty::ty_ptr(mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_unsafe_ptr(a, sty_a, b, mt_b) }; } _ => {} } do self.unpack_actual_value(a) |sty_a| { match *sty_a { ty::ty_bare_fn(ref a_f) => { // Bare functions are coercable to any closure type. // // FIXME(#3320) this should go away and be // replaced with proper inference, got a patch // underway - ndm self.coerce_from_bare_fn(a, a_f, b) } _ => { // Otherwise, just use subtyping rules. self.subtype(a, b) } } } } pub fn subtype(&self, a: ty::t, b: ty::t) -> CoerceResult { match Sub(**self).tys(a, b) { Ok(_) => Ok(None), // No coercion required. Err(ref e) => Err(*e) } } pub fn unpack_actual_value(&self, a: ty::t, f: &fn(&ty::sty) -> CoerceResult) -> CoerceResult { match resolve_type(self.infcx, a, try_resolve_tvar_shallow) { Ok(t) => { f(&ty::get(t).sty) } Err(e) => { self.infcx.tcx.sess.span_bug( self.trace.origin.span(), fmt!("Failed to resolve even without \ any force options: %?", e)); } } } pub fn coerce_borrowed_pointer(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_pointer(a=%s, sty_a=%?, b=%s, mt_b=%?)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx), mt_b); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let inner_ty = match *sty_a { ty::ty_box(mt_a) => mt_a.ty, ty::ty_uniq(mt_a) => mt_a.ty, ty::ty_rptr(_, mt_a) => mt_a.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_rptr(self.infcx.tcx, r_borrow, mt {ty: inner_ty, mutbl: mt_b.mutbl}); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(AutoPtr(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_string(&self, a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult { debug!("coerce_borrowed_string(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); match *sty_a { ty::ty_estr(vstore_box) | ty::ty_estr(vstore_uniq) => {} _ => { return self.subtype(a, b); } }; let r_a = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_estr(self.infcx.tcx, vstore_slice(r_a)); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_a, m_imm)) }))) } pub fn coerce_borrowed_vector(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_vector(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let ty_inner = match *sty_a { ty::ty_evec(mt, _) => mt.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_evec(self.infcx.tcx, mt {ty: ty_inner, mutbl: mt_b.mutbl}, vstore_slice(r_borrow)); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_fn(&self,
debug!("coerce_borrowed_fn(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let fn_ty = match *sty_a { ty::ty_closure(ref f) if f.sigil == ast::ManagedSigil => copy *f, ty::ty_closure(ref f) if f.sigil == ast::OwnedSigil => copy *f, ty::ty_bare_fn(ref f) => { return self.coerce_from_bare_fn(a, f, b); } _ => { return self.subtype(a, b); } }; let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_closure( self.infcx.tcx, ty::ClosureTy { sigil: ast::BorrowedSigil, region: r_borrow, ..fn_ty }); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowFn(r_borrow)) }))) } pub fn coerce_from_bare_fn(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t) -> CoerceResult { do self.unpack_actual_value(b) |sty_b| { self.coerce_from_bare_fn_post_unpack(a, fn_ty_a, b, sty_b) } } pub fn coerce_from_bare_fn_post_unpack(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t, sty_b: &ty::sty) -> CoerceResult { /*! * * Attempts to coerce from a bare Rust function (`extern * "rust" fn`) into a closure. */ debug!("coerce_from_bare_fn(a=%s, b=%s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); if!fn_ty_a.abis.is_rust() { return self.subtype(a, b); } let fn_ty_b = match *sty_b { ty::ty_closure(ref f) => {copy *f} _ => { return self.subtype(a, b); } }; let adj = @ty::AutoAddEnv(fn_ty_b.region, fn_ty_b.sigil); let a_closure = ty::mk_closure( self.infcx.tcx, ty::ClosureTy {sig: copy fn_ty_a.sig,..fn_ty_b}); if_ok!(self.subtype(a_closure, b)); Ok(Some(adj)) } pub fn coerce_unsafe_ptr(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_unsafe_ptr(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let mt_a = match *sty_a { ty::ty_rptr(_, mt) => mt, _ => { return self.subtype(a, b); } }; // check that the types which they point at are compatible let a_unsafe = ty::mk_ptr(self.infcx.tcx, mt_a); if_ok!(self.subtype(a_unsafe, b)); // although borrowed ptrs and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mt_b.mutbl)) }))) } }
a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult {
random_line_split
coercion.rs
// Copyright 2012 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. /*! # Type Coercion Under certain circumstances we will coerce from one type to another, for example by auto-borrowing. This occurs in situations where the compiler has a firm 'expected type' that was supplied from the user, and where the actual type is similar to that expected type in purpose but not in representation (so actual subtyping is inappropriate). ## Reborrowing Note that if we are expecting a borrowed pointer, we will *reborrow* even if the argument provided was already a borrowed pointer. This is useful for freezing mut/const things (that is, when the expected is &T but you have &const T or &mut T) and also for avoiding the linearity of mut things (when the expected is &mut T and you have &mut T). See the various `src/test/run-pass/coerce-reborrow-*.rs` tests for examples of where this is useful. ## Subtle note When deciding what type coercions to consider, we do not attempt to resolve any type variables we may encounter. This is because `b` represents the expected type "as the user wrote it", meaning that if the user defined a generic function like fn foo<A>(a: A, b: A) {... } and then we wrote `foo(&1, @2)`, we will not auto-borrow either argument. In older code we went to some lengths to resolve the `b` variable, which could mean that we'd auto-borrow later arguments but not earlier ones, which seems very confusing. ## Subtler note However, right now, if the user manually specifies the values for the type variables, as so: foo::<&int>(@1, @2) then we *will* auto-borrow, because we can't distinguish this from a function that declared `&int`. This is inconsistent but it's easiest at the moment. The right thing to do, I think, is to consider the *unsubstituted* type when deciding whether to auto-borrow, but the *substituted* type when considering the bounds and so forth. But most of our methods don't give access to the unsubstituted type, and rightly so because they'd be error-prone. So maybe the thing to do is to actually determine the kind of coercions that should occur separately and pass them in. Or maybe it's ok as is. Anyway, it's sort of a minor point so I've opted to leave it for later---after all we may want to adjust precisely when coercions occur. */ use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowFn}; use middle::ty::{AutoDerefRef}; use middle::ty::{vstore_slice, vstore_box, vstore_uniq}; use middle::ty::{mt}; use middle::ty; use middle::typeck::infer::{CoerceResult, resolve_type, Coercion}; use middle::typeck::infer::combine::CombineFields; use middle::typeck::infer::sub::Sub; use middle::typeck::infer::to_str::InferStr; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use util::common::indenter; use syntax::ast::m_imm; use syntax::ast; // Note: Coerce is not actually a combiner, in that it does not // conform to the same interface, though it performs a similar // function. pub struct Coerce(CombineFields); impl Coerce { pub fn tys(&self, a: ty::t, b: ty::t) -> CoerceResult { debug!("Coerce.tys(%s => %s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); let _indent = indenter(); // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match ty::get(b).sty { ty::ty_rptr(_, mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_pointer(a, sty_a, b, mt_b) }; } ty::ty_estr(vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_string(a, sty_a, b) }; } ty::ty_evec(mt_b, vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_vector(a, sty_a, b, mt_b) }; } ty::ty_closure(ty::ClosureTy {sigil: ast::BorrowedSigil, _}) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_fn(a, sty_a, b) }; } ty::ty_ptr(mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_unsafe_ptr(a, sty_a, b, mt_b) }; } _ => {} } do self.unpack_actual_value(a) |sty_a| { match *sty_a { ty::ty_bare_fn(ref a_f) => { // Bare functions are coercable to any closure type. // // FIXME(#3320) this should go away and be // replaced with proper inference, got a patch // underway - ndm self.coerce_from_bare_fn(a, a_f, b) } _ => { // Otherwise, just use subtyping rules. self.subtype(a, b) } } } } pub fn subtype(&self, a: ty::t, b: ty::t) -> CoerceResult { match Sub(**self).tys(a, b) { Ok(_) => Ok(None), // No coercion required. Err(ref e) => Err(*e) } } pub fn unpack_actual_value(&self, a: ty::t, f: &fn(&ty::sty) -> CoerceResult) -> CoerceResult { match resolve_type(self.infcx, a, try_resolve_tvar_shallow) { Ok(t) => { f(&ty::get(t).sty) } Err(e) => { self.infcx.tcx.sess.span_bug( self.trace.origin.span(), fmt!("Failed to resolve even without \ any force options: %?", e)); } } } pub fn coerce_borrowed_pointer(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_pointer(a=%s, sty_a=%?, b=%s, mt_b=%?)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx), mt_b); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let inner_ty = match *sty_a { ty::ty_box(mt_a) => mt_a.ty, ty::ty_uniq(mt_a) => mt_a.ty, ty::ty_rptr(_, mt_a) => mt_a.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_rptr(self.infcx.tcx, r_borrow, mt {ty: inner_ty, mutbl: mt_b.mutbl}); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(AutoPtr(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_string(&self, a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult { debug!("coerce_borrowed_string(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); match *sty_a { ty::ty_estr(vstore_box) | ty::ty_estr(vstore_uniq) => {} _ => { return self.subtype(a, b); } }; let r_a = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_estr(self.infcx.tcx, vstore_slice(r_a)); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_a, m_imm)) }))) } pub fn coerce_borrowed_vector(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_vector(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let ty_inner = match *sty_a { ty::ty_evec(mt, _) => mt.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_evec(self.infcx.tcx, mt {ty: ty_inner, mutbl: mt_b.mutbl}, vstore_slice(r_borrow)); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_fn(&self, a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult { debug!("coerce_borrowed_fn(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let fn_ty = match *sty_a { ty::ty_closure(ref f) if f.sigil == ast::ManagedSigil => copy *f, ty::ty_closure(ref f) if f.sigil == ast::OwnedSigil => copy *f, ty::ty_bare_fn(ref f) => { return self.coerce_from_bare_fn(a, f, b); } _ => { return self.subtype(a, b); } }; let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_closure( self.infcx.tcx, ty::ClosureTy { sigil: ast::BorrowedSigil, region: r_borrow, ..fn_ty }); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowFn(r_borrow)) }))) } pub fn coerce_from_bare_fn(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t) -> CoerceResult { do self.unpack_actual_value(b) |sty_b| { self.coerce_from_bare_fn_post_unpack(a, fn_ty_a, b, sty_b) } } pub fn coerce_from_bare_fn_post_unpack(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t, sty_b: &ty::sty) -> CoerceResult { /*! * * Attempts to coerce from a bare Rust function (`extern * "rust" fn`) into a closure. */ debug!("coerce_from_bare_fn(a=%s, b=%s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); if!fn_ty_a.abis.is_rust() { return self.subtype(a, b); } let fn_ty_b = match *sty_b { ty::ty_closure(ref f) => {copy *f} _ => { return self.subtype(a, b); } }; let adj = @ty::AutoAddEnv(fn_ty_b.region, fn_ty_b.sigil); let a_closure = ty::mk_closure( self.infcx.tcx, ty::ClosureTy {sig: copy fn_ty_a.sig,..fn_ty_b}); if_ok!(self.subtype(a_closure, b)); Ok(Some(adj)) } pub fn
(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_unsafe_ptr(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let mt_a = match *sty_a { ty::ty_rptr(_, mt) => mt, _ => { return self.subtype(a, b); } }; // check that the types which they point at are compatible let a_unsafe = ty::mk_ptr(self.infcx.tcx, mt_a); if_ok!(self.subtype(a_unsafe, b)); // although borrowed ptrs and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mt_b.mutbl)) }))) } }
coerce_unsafe_ptr
identifier_name
coercion.rs
// Copyright 2012 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. /*! # Type Coercion Under certain circumstances we will coerce from one type to another, for example by auto-borrowing. This occurs in situations where the compiler has a firm 'expected type' that was supplied from the user, and where the actual type is similar to that expected type in purpose but not in representation (so actual subtyping is inappropriate). ## Reborrowing Note that if we are expecting a borrowed pointer, we will *reborrow* even if the argument provided was already a borrowed pointer. This is useful for freezing mut/const things (that is, when the expected is &T but you have &const T or &mut T) and also for avoiding the linearity of mut things (when the expected is &mut T and you have &mut T). See the various `src/test/run-pass/coerce-reborrow-*.rs` tests for examples of where this is useful. ## Subtle note When deciding what type coercions to consider, we do not attempt to resolve any type variables we may encounter. This is because `b` represents the expected type "as the user wrote it", meaning that if the user defined a generic function like fn foo<A>(a: A, b: A) {... } and then we wrote `foo(&1, @2)`, we will not auto-borrow either argument. In older code we went to some lengths to resolve the `b` variable, which could mean that we'd auto-borrow later arguments but not earlier ones, which seems very confusing. ## Subtler note However, right now, if the user manually specifies the values for the type variables, as so: foo::<&int>(@1, @2) then we *will* auto-borrow, because we can't distinguish this from a function that declared `&int`. This is inconsistent but it's easiest at the moment. The right thing to do, I think, is to consider the *unsubstituted* type when deciding whether to auto-borrow, but the *substituted* type when considering the bounds and so forth. But most of our methods don't give access to the unsubstituted type, and rightly so because they'd be error-prone. So maybe the thing to do is to actually determine the kind of coercions that should occur separately and pass them in. Or maybe it's ok as is. Anyway, it's sort of a minor point so I've opted to leave it for later---after all we may want to adjust precisely when coercions occur. */ use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowFn}; use middle::ty::{AutoDerefRef}; use middle::ty::{vstore_slice, vstore_box, vstore_uniq}; use middle::ty::{mt}; use middle::ty; use middle::typeck::infer::{CoerceResult, resolve_type, Coercion}; use middle::typeck::infer::combine::CombineFields; use middle::typeck::infer::sub::Sub; use middle::typeck::infer::to_str::InferStr; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use util::common::indenter; use syntax::ast::m_imm; use syntax::ast; // Note: Coerce is not actually a combiner, in that it does not // conform to the same interface, though it performs a similar // function. pub struct Coerce(CombineFields); impl Coerce { pub fn tys(&self, a: ty::t, b: ty::t) -> CoerceResult { debug!("Coerce.tys(%s => %s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); let _indent = indenter(); // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match ty::get(b).sty { ty::ty_rptr(_, mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_pointer(a, sty_a, b, mt_b) }; } ty::ty_estr(vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_string(a, sty_a, b) }; } ty::ty_evec(mt_b, vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_vector(a, sty_a, b, mt_b) }; } ty::ty_closure(ty::ClosureTy {sigil: ast::BorrowedSigil, _}) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_fn(a, sty_a, b) }; } ty::ty_ptr(mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_unsafe_ptr(a, sty_a, b, mt_b) }; } _ => {} } do self.unpack_actual_value(a) |sty_a| { match *sty_a { ty::ty_bare_fn(ref a_f) => { // Bare functions are coercable to any closure type. // // FIXME(#3320) this should go away and be // replaced with proper inference, got a patch // underway - ndm self.coerce_from_bare_fn(a, a_f, b) } _ => { // Otherwise, just use subtyping rules. self.subtype(a, b) } } } } pub fn subtype(&self, a: ty::t, b: ty::t) -> CoerceResult { match Sub(**self).tys(a, b) { Ok(_) => Ok(None), // No coercion required. Err(ref e) => Err(*e) } } pub fn unpack_actual_value(&self, a: ty::t, f: &fn(&ty::sty) -> CoerceResult) -> CoerceResult { match resolve_type(self.infcx, a, try_resolve_tvar_shallow) { Ok(t) => { f(&ty::get(t).sty) } Err(e) => { self.infcx.tcx.sess.span_bug( self.trace.origin.span(), fmt!("Failed to resolve even without \ any force options: %?", e)); } } } pub fn coerce_borrowed_pointer(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_pointer(a=%s, sty_a=%?, b=%s, mt_b=%?)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx), mt_b); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let inner_ty = match *sty_a { ty::ty_box(mt_a) => mt_a.ty, ty::ty_uniq(mt_a) => mt_a.ty, ty::ty_rptr(_, mt_a) => mt_a.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_rptr(self.infcx.tcx, r_borrow, mt {ty: inner_ty, mutbl: mt_b.mutbl}); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(AutoPtr(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_string(&self, a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult { debug!("coerce_borrowed_string(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); match *sty_a { ty::ty_estr(vstore_box) | ty::ty_estr(vstore_uniq) => {} _ =>
}; let r_a = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_estr(self.infcx.tcx, vstore_slice(r_a)); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_a, m_imm)) }))) } pub fn coerce_borrowed_vector(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_vector(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let ty_inner = match *sty_a { ty::ty_evec(mt, _) => mt.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_evec(self.infcx.tcx, mt {ty: ty_inner, mutbl: mt_b.mutbl}, vstore_slice(r_borrow)); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_fn(&self, a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult { debug!("coerce_borrowed_fn(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let fn_ty = match *sty_a { ty::ty_closure(ref f) if f.sigil == ast::ManagedSigil => copy *f, ty::ty_closure(ref f) if f.sigil == ast::OwnedSigil => copy *f, ty::ty_bare_fn(ref f) => { return self.coerce_from_bare_fn(a, f, b); } _ => { return self.subtype(a, b); } }; let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_closure( self.infcx.tcx, ty::ClosureTy { sigil: ast::BorrowedSigil, region: r_borrow, ..fn_ty }); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowFn(r_borrow)) }))) } pub fn coerce_from_bare_fn(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t) -> CoerceResult { do self.unpack_actual_value(b) |sty_b| { self.coerce_from_bare_fn_post_unpack(a, fn_ty_a, b, sty_b) } } pub fn coerce_from_bare_fn_post_unpack(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t, sty_b: &ty::sty) -> CoerceResult { /*! * * Attempts to coerce from a bare Rust function (`extern * "rust" fn`) into a closure. */ debug!("coerce_from_bare_fn(a=%s, b=%s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); if!fn_ty_a.abis.is_rust() { return self.subtype(a, b); } let fn_ty_b = match *sty_b { ty::ty_closure(ref f) => {copy *f} _ => { return self.subtype(a, b); } }; let adj = @ty::AutoAddEnv(fn_ty_b.region, fn_ty_b.sigil); let a_closure = ty::mk_closure( self.infcx.tcx, ty::ClosureTy {sig: copy fn_ty_a.sig,..fn_ty_b}); if_ok!(self.subtype(a_closure, b)); Ok(Some(adj)) } pub fn coerce_unsafe_ptr(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_unsafe_ptr(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let mt_a = match *sty_a { ty::ty_rptr(_, mt) => mt, _ => { return self.subtype(a, b); } }; // check that the types which they point at are compatible let a_unsafe = ty::mk_ptr(self.infcx.tcx, mt_a); if_ok!(self.subtype(a_unsafe, b)); // although borrowed ptrs and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mt_b.mutbl)) }))) } }
{ return self.subtype(a, b); }
conditional_block
coercion.rs
// Copyright 2012 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. /*! # Type Coercion Under certain circumstances we will coerce from one type to another, for example by auto-borrowing. This occurs in situations where the compiler has a firm 'expected type' that was supplied from the user, and where the actual type is similar to that expected type in purpose but not in representation (so actual subtyping is inappropriate). ## Reborrowing Note that if we are expecting a borrowed pointer, we will *reborrow* even if the argument provided was already a borrowed pointer. This is useful for freezing mut/const things (that is, when the expected is &T but you have &const T or &mut T) and also for avoiding the linearity of mut things (when the expected is &mut T and you have &mut T). See the various `src/test/run-pass/coerce-reborrow-*.rs` tests for examples of where this is useful. ## Subtle note When deciding what type coercions to consider, we do not attempt to resolve any type variables we may encounter. This is because `b` represents the expected type "as the user wrote it", meaning that if the user defined a generic function like fn foo<A>(a: A, b: A) {... } and then we wrote `foo(&1, @2)`, we will not auto-borrow either argument. In older code we went to some lengths to resolve the `b` variable, which could mean that we'd auto-borrow later arguments but not earlier ones, which seems very confusing. ## Subtler note However, right now, if the user manually specifies the values for the type variables, as so: foo::<&int>(@1, @2) then we *will* auto-borrow, because we can't distinguish this from a function that declared `&int`. This is inconsistent but it's easiest at the moment. The right thing to do, I think, is to consider the *unsubstituted* type when deciding whether to auto-borrow, but the *substituted* type when considering the bounds and so forth. But most of our methods don't give access to the unsubstituted type, and rightly so because they'd be error-prone. So maybe the thing to do is to actually determine the kind of coercions that should occur separately and pass them in. Or maybe it's ok as is. Anyway, it's sort of a minor point so I've opted to leave it for later---after all we may want to adjust precisely when coercions occur. */ use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowFn}; use middle::ty::{AutoDerefRef}; use middle::ty::{vstore_slice, vstore_box, vstore_uniq}; use middle::ty::{mt}; use middle::ty; use middle::typeck::infer::{CoerceResult, resolve_type, Coercion}; use middle::typeck::infer::combine::CombineFields; use middle::typeck::infer::sub::Sub; use middle::typeck::infer::to_str::InferStr; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use util::common::indenter; use syntax::ast::m_imm; use syntax::ast; // Note: Coerce is not actually a combiner, in that it does not // conform to the same interface, though it performs a similar // function. pub struct Coerce(CombineFields); impl Coerce { pub fn tys(&self, a: ty::t, b: ty::t) -> CoerceResult { debug!("Coerce.tys(%s => %s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); let _indent = indenter(); // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match ty::get(b).sty { ty::ty_rptr(_, mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_pointer(a, sty_a, b, mt_b) }; } ty::ty_estr(vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_string(a, sty_a, b) }; } ty::ty_evec(mt_b, vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_vector(a, sty_a, b, mt_b) }; } ty::ty_closure(ty::ClosureTy {sigil: ast::BorrowedSigil, _}) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_fn(a, sty_a, b) }; } ty::ty_ptr(mt_b) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_unsafe_ptr(a, sty_a, b, mt_b) }; } _ => {} } do self.unpack_actual_value(a) |sty_a| { match *sty_a { ty::ty_bare_fn(ref a_f) => { // Bare functions are coercable to any closure type. // // FIXME(#3320) this should go away and be // replaced with proper inference, got a patch // underway - ndm self.coerce_from_bare_fn(a, a_f, b) } _ => { // Otherwise, just use subtyping rules. self.subtype(a, b) } } } } pub fn subtype(&self, a: ty::t, b: ty::t) -> CoerceResult { match Sub(**self).tys(a, b) { Ok(_) => Ok(None), // No coercion required. Err(ref e) => Err(*e) } } pub fn unpack_actual_value(&self, a: ty::t, f: &fn(&ty::sty) -> CoerceResult) -> CoerceResult { match resolve_type(self.infcx, a, try_resolve_tvar_shallow) { Ok(t) => { f(&ty::get(t).sty) } Err(e) => { self.infcx.tcx.sess.span_bug( self.trace.origin.span(), fmt!("Failed to resolve even without \ any force options: %?", e)); } } } pub fn coerce_borrowed_pointer(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_pointer(a=%s, sty_a=%?, b=%s, mt_b=%?)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx), mt_b); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let inner_ty = match *sty_a { ty::ty_box(mt_a) => mt_a.ty, ty::ty_uniq(mt_a) => mt_a.ty, ty::ty_rptr(_, mt_a) => mt_a.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_rptr(self.infcx.tcx, r_borrow, mt {ty: inner_ty, mutbl: mt_b.mutbl}); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(AutoPtr(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_string(&self, a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult { debug!("coerce_borrowed_string(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); match *sty_a { ty::ty_estr(vstore_box) | ty::ty_estr(vstore_uniq) => {} _ => { return self.subtype(a, b); } }; let r_a = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_estr(self.infcx.tcx, vstore_slice(r_a)); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_a, m_imm)) }))) } pub fn coerce_borrowed_vector(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_borrowed_vector(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let sub = Sub(**self); let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let ty_inner = match *sty_a { ty::ty_evec(mt, _) => mt.ty, _ => { return self.subtype(a, b); } }; let a_borrowed = ty::mk_evec(self.infcx.tcx, mt {ty: ty_inner, mutbl: mt_b.mutbl}, vstore_slice(r_borrow)); if_ok!(sub.tys(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_borrow, mt_b.mutbl)) }))) } pub fn coerce_borrowed_fn(&self, a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult
sigil: ast::BorrowedSigil, region: r_borrow, ..fn_ty }); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowFn(r_borrow)) }))) } pub fn coerce_from_bare_fn(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t) -> CoerceResult { do self.unpack_actual_value(b) |sty_b| { self.coerce_from_bare_fn_post_unpack(a, fn_ty_a, b, sty_b) } } pub fn coerce_from_bare_fn_post_unpack(&self, a: ty::t, fn_ty_a: &ty::BareFnTy, b: ty::t, sty_b: &ty::sty) -> CoerceResult { /*! * * Attempts to coerce from a bare Rust function (`extern * "rust" fn`) into a closure. */ debug!("coerce_from_bare_fn(a=%s, b=%s)", a.inf_str(self.infcx), b.inf_str(self.infcx)); if!fn_ty_a.abis.is_rust() { return self.subtype(a, b); } let fn_ty_b = match *sty_b { ty::ty_closure(ref f) => {copy *f} _ => { return self.subtype(a, b); } }; let adj = @ty::AutoAddEnv(fn_ty_b.region, fn_ty_b.sigil); let a_closure = ty::mk_closure( self.infcx.tcx, ty::ClosureTy {sig: copy fn_ty_a.sig,..fn_ty_b}); if_ok!(self.subtype(a_closure, b)); Ok(Some(adj)) } pub fn coerce_unsafe_ptr(&self, a: ty::t, sty_a: &ty::sty, b: ty::t, mt_b: ty::mt) -> CoerceResult { debug!("coerce_unsafe_ptr(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let mt_a = match *sty_a { ty::ty_rptr(_, mt) => mt, _ => { return self.subtype(a, b); } }; // check that the types which they point at are compatible let a_unsafe = ty::mk_ptr(self.infcx.tcx, mt_a); if_ok!(self.subtype(a_unsafe, b)); // although borrowed ptrs and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mt_b.mutbl)) }))) } }
{ debug!("coerce_borrowed_fn(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let fn_ty = match *sty_a { ty::ty_closure(ref f) if f.sigil == ast::ManagedSigil => copy *f, ty::ty_closure(ref f) if f.sigil == ast::OwnedSigil => copy *f, ty::ty_bare_fn(ref f) => { return self.coerce_from_bare_fn(a, f, b); } _ => { return self.subtype(a, b); } }; let r_borrow = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_closure( self.infcx.tcx, ty::ClosureTy {
identifier_body
nodeinfo.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize )] pub struct NodeInfo { pub parents: [Key; 2], pub linknode: HgId, } #[cfg(any(test, feature = "for-tests"))] use quickcheck::Arbitrary; #[cfg(any(test, feature = "for-tests"))] impl Arbitrary for NodeInfo { fn arbitrary(g: &mut quickcheck::Gen) -> Self
}
{ NodeInfo { parents: [Key::arbitrary(g), Key::arbitrary(g)], linknode: HgId::arbitrary(g), } }
identifier_body
nodeinfo.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize )] pub struct NodeInfo { pub parents: [Key; 2], pub linknode: HgId, } #[cfg(any(test, feature = "for-tests"))] use quickcheck::Arbitrary; #[cfg(any(test, feature = "for-tests"))] impl Arbitrary for NodeInfo { fn arbitrary(g: &mut quickcheck::Gen) -> Self { NodeInfo { parents: [Key::arbitrary(g), Key::arbitrary(g)],
linknode: HgId::arbitrary(g), } } }
random_line_split
nodeinfo.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize )] pub struct NodeInfo { pub parents: [Key; 2], pub linknode: HgId, } #[cfg(any(test, feature = "for-tests"))] use quickcheck::Arbitrary; #[cfg(any(test, feature = "for-tests"))] impl Arbitrary for NodeInfo { fn
(g: &mut quickcheck::Gen) -> Self { NodeInfo { parents: [Key::arbitrary(g), Key::arbitrary(g)], linknode: HgId::arbitrary(g), } } }
arbitrary
identifier_name
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vfpclasssd_1() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 212, 5], OperandSize::Dword) } fn vfpclasssd_2() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K7)), operand2: Some(IndirectScaledDisplaced(EDX, Eight, 153484929, Some(OperandSize::Qword), None)), operand3: Some(Literal8(47)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 60, 213, 129, 254, 37, 9, 47], OperandSize::Dword) } fn vfpclasssd_3() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM16)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 179, 253, 10, 103, 208, 38], OperandSize::Qword) } fn vfpclasssd_4() {
}
run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 243, 253, 9, 103, 20, 214, 3], OperandSize::Qword)
random_line_split
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vfpclasssd_1() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 212, 5], OperandSize::Dword) } fn vfpclasssd_2() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K7)), operand2: Some(IndirectScaledDisplaced(EDX, Eight, 153484929, Some(OperandSize::Qword), None)), operand3: Some(Literal8(47)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 60, 213, 129, 254, 37, 9, 47], OperandSize::Dword) } fn vfpclasssd_3()
fn vfpclasssd_4() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 243, 253, 9, 103, 20, 214, 3], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM16)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 179, 253, 10, 103, 208, 38], OperandSize::Qword) }
identifier_body
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn
() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 212, 5], OperandSize::Dword) } fn vfpclasssd_2() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K7)), operand2: Some(IndirectScaledDisplaced(EDX, Eight, 153484929, Some(OperandSize::Qword), None)), operand3: Some(Literal8(47)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 60, 213, 129, 254, 37, 9, 47], OperandSize::Dword) } fn vfpclasssd_3() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM16)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 179, 253, 10, 103, 208, 38], OperandSize::Qword) } fn vfpclasssd_4() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 243, 253, 9, 103, 20, 214, 3], OperandSize::Qword) }
vfpclasssd_1
identifier_name
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: Scheme> Deref for Authorization<S> { type Target = S; fn deref<'a>(&'a self) -> &'a S { &self.0 } } impl<S: Scheme> DerefMut for Authorization<S> { fn deref_mut<'a>(&'a mut self) -> &'a mut S { &mut self.0 } } impl<S: Scheme> Header for Authorization<S> { fn header_name(_: Option<Authorization<S>>) -> &'static str { "Authorization" } fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { if raw.len() == 1 { match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) }, (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)), _ => None } } else { None } } } impl<S: Scheme> HeaderFormat for Authorization<S> { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match Scheme::scheme(None::<S>) { Some(scheme) => try!(write!(fmt, "{} ", scheme)), None => () }; self.0.fmt_scheme(fmt) } } /// An Authorization scheme to be used in the header. pub trait Scheme: FromStr + Clone + Send + Sync { /// An optional Scheme name. /// /// For example, `Basic asdf` has the name `Basic`. The Option<Self> is /// just a marker that can be removed once UFCS is completed. fn scheme(Option<Self>) -> Option<&'static str>; /// Format the Scheme data into a header value. fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result; } impl Scheme for String { fn scheme(_: Option<String>) -> Option<&'static str> { None } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self) } } /// Credential holder for Basic Authentication #[derive(Clone, PartialEq, Show)] pub struct Basic { /// The username as a possibly empty string pub username: String, /// The password. `None` if the `:` delimiter character was not /// part of the parsed input. pub password: Option<String> } impl Scheme for Basic { fn scheme(_: Option<Basic>) -> Option<&'static str> { Some("Basic") } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { //FIXME: serialize::base64 could use some Show implementation, so //that we don't have to allocate a new string here just to write it //to the formatter. let mut text = self.username.clone(); text.push(':'); if let Some(ref pass) = self.password { text.push_str(&pass[]); } write!(f, "{}", text.as_bytes().to_base64(Config { char_set: Standard, newline: Newline::CRLF, pad: true, line_length: None })) } } impl FromStr for Basic { fn from_str(s: &str) -> Option<Basic> { match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), None => return None }; let password = match parts.next() { Some(part) => Some(part.to_string()), None => None }; Some(Basic { username: user, password: password }) }, Err(e) => { debug!("Basic::from_utf8 error={:?}", e); None } }, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{Headers}; fn mem(s: &str) -> MemReader { MemReader::new(s.as_bytes().to_vec()) } #[test] fn test_raw_auth() { let mut headers = Headers::new(); headers.set(Authorization("foo bar baz".to_string())); assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_string()); } #[test] fn
() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); } #[test] fn test_basic_auth() { let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: Some("open sesame".to_string()) })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_string()); } #[test] fn test_basic_auth_no_password() { let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: None })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_string()); } #[test] fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(&auth.0.username[], "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_string())); } #[test] fn test_basic_auth_parse_no_password() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjo=\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(auth.0.username.as_slice(), "Aladdin"); assert_eq!(auth.0.password, Some("".to_string())); } } bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] }); bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()] });
test_raw_auth_parse
identifier_name
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: Scheme> Deref for Authorization<S> { type Target = S; fn deref<'a>(&'a self) -> &'a S { &self.0 } } impl<S: Scheme> DerefMut for Authorization<S> { fn deref_mut<'a>(&'a mut self) -> &'a mut S { &mut self.0 } } impl<S: Scheme> Header for Authorization<S> { fn header_name(_: Option<Authorization<S>>) -> &'static str { "Authorization" } fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { if raw.len() == 1 { match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) }, (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)), _ => None } } else { None } } } impl<S: Scheme> HeaderFormat for Authorization<S> { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match Scheme::scheme(None::<S>) { Some(scheme) => try!(write!(fmt, "{} ", scheme)), None => () }; self.0.fmt_scheme(fmt) } } /// An Authorization scheme to be used in the header. pub trait Scheme: FromStr + Clone + Send + Sync { /// An optional Scheme name. /// /// For example, `Basic asdf` has the name `Basic`. The Option<Self> is /// just a marker that can be removed once UFCS is completed. fn scheme(Option<Self>) -> Option<&'static str>; /// Format the Scheme data into a header value. fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result; } impl Scheme for String { fn scheme(_: Option<String>) -> Option<&'static str> { None } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self) } } /// Credential holder for Basic Authentication #[derive(Clone, PartialEq, Show)] pub struct Basic { /// The username as a possibly empty string pub username: String, /// The password. `None` if the `:` delimiter character was not /// part of the parsed input. pub password: Option<String> } impl Scheme for Basic { fn scheme(_: Option<Basic>) -> Option<&'static str> { Some("Basic") } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { //FIXME: serialize::base64 could use some Show implementation, so //that we don't have to allocate a new string here just to write it //to the formatter. let mut text = self.username.clone(); text.push(':'); if let Some(ref pass) = self.password { text.push_str(&pass[]); } write!(f, "{}", text.as_bytes().to_base64(Config { char_set: Standard, newline: Newline::CRLF, pad: true, line_length: None })) } } impl FromStr for Basic { fn from_str(s: &str) -> Option<Basic> { match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), None => return None }; let password = match parts.next() { Some(part) => Some(part.to_string()), None => None }; Some(Basic { username: user, password: password }) }, Err(e) =>
}, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{Headers}; fn mem(s: &str) -> MemReader { MemReader::new(s.as_bytes().to_vec()) } #[test] fn test_raw_auth() { let mut headers = Headers::new(); headers.set(Authorization("foo bar baz".to_string())); assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_string()); } #[test] fn test_raw_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); } #[test] fn test_basic_auth() { let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: Some("open sesame".to_string()) })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_string()); } #[test] fn test_basic_auth_no_password() { let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: None })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_string()); } #[test] fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(&auth.0.username[], "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_string())); } #[test] fn test_basic_auth_parse_no_password() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjo=\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(auth.0.username.as_slice(), "Aladdin"); assert_eq!(auth.0.password, Some("".to_string())); } } bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] }); bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()] });
{ debug!("Basic::from_utf8 error={:?}", e); None }
conditional_block
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: Scheme> Deref for Authorization<S> { type Target = S; fn deref<'a>(&'a self) -> &'a S { &self.0 } } impl<S: Scheme> DerefMut for Authorization<S> { fn deref_mut<'a>(&'a mut self) -> &'a mut S { &mut self.0 } } impl<S: Scheme> Header for Authorization<S> { fn header_name(_: Option<Authorization<S>>) -> &'static str { "Authorization" } fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { if raw.len() == 1 { match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) }, (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)), _ => None } } else { None } } } impl<S: Scheme> HeaderFormat for Authorization<S> { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match Scheme::scheme(None::<S>) { Some(scheme) => try!(write!(fmt, "{} ", scheme)), None => () }; self.0.fmt_scheme(fmt) } } /// An Authorization scheme to be used in the header. pub trait Scheme: FromStr + Clone + Send + Sync { /// An optional Scheme name. /// /// For example, `Basic asdf` has the name `Basic`. The Option<Self> is /// just a marker that can be removed once UFCS is completed. fn scheme(Option<Self>) -> Option<&'static str>; /// Format the Scheme data into a header value. fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result; } impl Scheme for String { fn scheme(_: Option<String>) -> Option<&'static str> { None } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self) } } /// Credential holder for Basic Authentication #[derive(Clone, PartialEq, Show)] pub struct Basic { /// The username as a possibly empty string pub username: String, /// The password. `None` if the `:` delimiter character was not /// part of the parsed input. pub password: Option<String> } impl Scheme for Basic { fn scheme(_: Option<Basic>) -> Option<&'static str> { Some("Basic") } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { //FIXME: serialize::base64 could use some Show implementation, so //that we don't have to allocate a new string here just to write it //to the formatter. let mut text = self.username.clone(); text.push(':'); if let Some(ref pass) = self.password { text.push_str(&pass[]); } write!(f, "{}", text.as_bytes().to_base64(Config { char_set: Standard, newline: Newline::CRLF, pad: true, line_length: None })) } } impl FromStr for Basic { fn from_str(s: &str) -> Option<Basic>
None } }, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{Headers}; fn mem(s: &str) -> MemReader { MemReader::new(s.as_bytes().to_vec()) } #[test] fn test_raw_auth() { let mut headers = Headers::new(); headers.set(Authorization("foo bar baz".to_string())); assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_string()); } #[test] fn test_raw_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); } #[test] fn test_basic_auth() { let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: Some("open sesame".to_string()) })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_string()); } #[test] fn test_basic_auth_no_password() { let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: None })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_string()); } #[test] fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(&auth.0.username[], "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_string())); } #[test] fn test_basic_auth_parse_no_password() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjo=\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(auth.0.username.as_slice(), "Aladdin"); assert_eq!(auth.0.password, Some("".to_string())); } } bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] }); bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()] });
{ match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), None => return None }; let password = match parts.next() { Some(part) => Some(part.to_string()), None => None }; Some(Basic { username: user, password: password }) }, Err(e) => { debug!("Basic::from_utf8 error={:?}", e);
identifier_body
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: Scheme> Deref for Authorization<S> { type Target = S; fn deref<'a>(&'a self) -> &'a S { &self.0 } } impl<S: Scheme> DerefMut for Authorization<S> { fn deref_mut<'a>(&'a mut self) -> &'a mut S { &mut self.0 } } impl<S: Scheme> Header for Authorization<S> { fn header_name(_: Option<Authorization<S>>) -> &'static str { "Authorization" } fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { if raw.len() == 1 { match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) }, (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)), _ => None } } else { None } } } impl<S: Scheme> HeaderFormat for Authorization<S> { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match Scheme::scheme(None::<S>) { Some(scheme) => try!(write!(fmt, "{} ", scheme)), None => () }; self.0.fmt_scheme(fmt) } } /// An Authorization scheme to be used in the header. pub trait Scheme: FromStr + Clone + Send + Sync { /// An optional Scheme name. /// /// For example, `Basic asdf` has the name `Basic`. The Option<Self> is /// just a marker that can be removed once UFCS is completed. fn scheme(Option<Self>) -> Option<&'static str>; /// Format the Scheme data into a header value. fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result; } impl Scheme for String { fn scheme(_: Option<String>) -> Option<&'static str> { None } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self) } } /// Credential holder for Basic Authentication #[derive(Clone, PartialEq, Show)] pub struct Basic { /// The username as a possibly empty string pub username: String, /// The password. `None` if the `:` delimiter character was not /// part of the parsed input. pub password: Option<String> } impl Scheme for Basic { fn scheme(_: Option<Basic>) -> Option<&'static str> { Some("Basic") } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { //FIXME: serialize::base64 could use some Show implementation, so //that we don't have to allocate a new string here just to write it //to the formatter. let mut text = self.username.clone(); text.push(':'); if let Some(ref pass) = self.password { text.push_str(&pass[]); } write!(f, "{}", text.as_bytes().to_base64(Config { char_set: Standard, newline: Newline::CRLF, pad: true, line_length: None })) } } impl FromStr for Basic { fn from_str(s: &str) -> Option<Basic> { match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), None => return None }; let password = match parts.next() { Some(part) => Some(part.to_string()), None => None }; Some(Basic { username: user, password: password }) }, Err(e) => { debug!("Basic::from_utf8 error={:?}", e); None } }, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{Headers}; fn mem(s: &str) -> MemReader { MemReader::new(s.as_bytes().to_vec()) } #[test] fn test_raw_auth() { let mut headers = Headers::new(); headers.set(Authorization("foo bar baz".to_string())); assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_string()); } #[test] fn test_raw_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); } #[test] fn test_basic_auth() { let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: Some("open sesame".to_string()) })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_string()); } #[test] fn test_basic_auth_no_password() { let mut headers = Headers::new();
headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: None })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_string()); } #[test] fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(&auth.0.username[], "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_string())); } #[test] fn test_basic_auth_parse_no_password() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjo=\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(auth.0.username.as_slice(), "Aladdin"); assert_eq!(auth.0.password, Some("".to_string())); } } bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] }); bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()] });
random_line_split
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main() { // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24, 1.7, 1.9, 1.0, 0.75, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for x in range(0, img_size) { for y in range(0, img_size) { let n = ngen.get_value2d((x as f64), (y as f64)); let col = (n * 255.0) as u8; let pixel = image::Luma(col); imbuf.put_pixel(x, y, pixel); } } let end = precise_time_s(); let fout = File::create(&Path::new("ridged.png")).unwrap(); let _ = image::ImageLuma8(imbuf).save(fout, image::PNG); println!("ridged.png saved")
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
random_line_split
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main()
let fout = File::create(&Path::new("ridged.png")).unwrap(); let _ = image::ImageLuma8(imbuf).save(fout, image::PNG); println!("ridged.png saved") println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
{ // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24, 1.7, 1.9, 1.0, 0.75, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for x in range(0, img_size) { for y in range(0, img_size) { let n = ngen.get_value2d((x as f64), (y as f64)); let col = (n * 255.0) as u8; let pixel = image::Luma(col); imbuf.put_pixel(x, y, pixel); } } let end = precise_time_s();
identifier_body
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn
() { // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24, 1.7, 1.9, 1.0, 0.75, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for x in range(0, img_size) { for y in range(0, img_size) { let n = ngen.get_value2d((x as f64), (y as f64)); let col = (n * 255.0) as u8; let pixel = image::Luma(col); imbuf.put_pixel(x, y, pixel); } } let end = precise_time_s(); let fout = File::create(&Path::new("ridged.png")).unwrap(); let _ = image::ImageLuma8(imbuf).save(fout, image::PNG); println!("ridged.png saved") println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
main
identifier_name
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct PostgresMiddleware { pub pool: Pool<PostgresConnectionManager>, } impl PostgresMiddleware { /// Create middleware using defaults /// /// The middleware will be setup with no ssl and the r2d2 defaults. pub fn new(db_url: &str) -> Result<PostgresMiddleware, Box<Error>> { let manager = try!(PostgresConnectionManager::new(db_url, SslMode::None)); let pool = try!(Pool::new(Config::default(), manager)); Ok(PostgresMiddleware { pool: pool }) } /// Create middleware using pre-built `r2d2::Pool` /// /// This allows the caller to create and configure the pool with specific settings. pub fn with_pool(pool: Pool<PostgresConnectionManager>) -> PostgresMiddleware { PostgresMiddleware { pool: pool } } } impl Key for PostgresMiddleware { type Value = Pool<PostgresConnectionManager>; } impl<D> Middleware<D> for PostgresMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } /// Add `pg_conn()` helper method to `nickel::Request` /// /// This trait must only be used in conjunction with `PostgresMiddleware`.
/// /// Example: /// /// ```ignore /// app.get("/my_counter", middleware! { |request, response| /// let db = try_with!(response, request.pg_conn()); /// }); /// ``` pub trait PostgresRequestExtensions { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)>; } impl<'a, 'b, D> PostgresRequestExtensions for Request<'a, 'b, D> { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)> { self.extensions() .get::<PostgresMiddleware>() .expect("PostgresMiddleware must be registered before using PostgresRequestExtensions::pg_conn()") .get() .or_else(|err| Err((StatusCode::InternalServerError, err))) } }
/// /// On error, the method returns a tuple per Nickel convention. This allows the route to use the /// `try_with!` macro.
random_line_split
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct PostgresMiddleware { pub pool: Pool<PostgresConnectionManager>, } impl PostgresMiddleware { /// Create middleware using defaults /// /// The middleware will be setup with no ssl and the r2d2 defaults. pub fn new(db_url: &str) -> Result<PostgresMiddleware, Box<Error>> { let manager = try!(PostgresConnectionManager::new(db_url, SslMode::None)); let pool = try!(Pool::new(Config::default(), manager)); Ok(PostgresMiddleware { pool: pool }) } /// Create middleware using pre-built `r2d2::Pool` /// /// This allows the caller to create and configure the pool with specific settings. pub fn with_pool(pool: Pool<PostgresConnectionManager>) -> PostgresMiddleware { PostgresMiddleware { pool: pool } } } impl Key for PostgresMiddleware { type Value = Pool<PostgresConnectionManager>; } impl<D> Middleware<D> for PostgresMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D>
} /// Add `pg_conn()` helper method to `nickel::Request` /// /// This trait must only be used in conjunction with `PostgresMiddleware`. /// /// On error, the method returns a tuple per Nickel convention. This allows the route to use the /// `try_with!` macro. /// /// Example: /// /// ```ignore /// app.get("/my_counter", middleware! { |request, response| /// let db = try_with!(response, request.pg_conn()); /// }); /// ``` pub trait PostgresRequestExtensions { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)>; } impl<'a, 'b, D> PostgresRequestExtensions for Request<'a, 'b, D> { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)> { self.extensions() .get::<PostgresMiddleware>() .expect("PostgresMiddleware must be registered before using PostgresRequestExtensions::pg_conn()") .get() .or_else(|err| Err((StatusCode::InternalServerError, err))) } }
{ req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) }
identifier_body
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct PostgresMiddleware { pub pool: Pool<PostgresConnectionManager>, } impl PostgresMiddleware { /// Create middleware using defaults /// /// The middleware will be setup with no ssl and the r2d2 defaults. pub fn new(db_url: &str) -> Result<PostgresMiddleware, Box<Error>> { let manager = try!(PostgresConnectionManager::new(db_url, SslMode::None)); let pool = try!(Pool::new(Config::default(), manager)); Ok(PostgresMiddleware { pool: pool }) } /// Create middleware using pre-built `r2d2::Pool` /// /// This allows the caller to create and configure the pool with specific settings. pub fn with_pool(pool: Pool<PostgresConnectionManager>) -> PostgresMiddleware { PostgresMiddleware { pool: pool } } } impl Key for PostgresMiddleware { type Value = Pool<PostgresConnectionManager>; } impl<D> Middleware<D> for PostgresMiddleware { fn
<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } /// Add `pg_conn()` helper method to `nickel::Request` /// /// This trait must only be used in conjunction with `PostgresMiddleware`. /// /// On error, the method returns a tuple per Nickel convention. This allows the route to use the /// `try_with!` macro. /// /// Example: /// /// ```ignore /// app.get("/my_counter", middleware! { |request, response| /// let db = try_with!(response, request.pg_conn()); /// }); /// ``` pub trait PostgresRequestExtensions { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)>; } impl<'a, 'b, D> PostgresRequestExtensions for Request<'a, 'b, D> { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)> { self.extensions() .get::<PostgresMiddleware>() .expect("PostgresMiddleware must be registered before using PostgresRequestExtensions::pg_conn()") .get() .or_else(|err| Err((StatusCode::InternalServerError, err))) } }
invoke
identifier_name
htmlhtmlelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct HTMLHtmlElement { htmlelement: HTMLElement } impl HTMLHtmlElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHtmlElement { HTMLHtmlElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHtmlElement> { let element = HTMLHtmlElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap) } }
random_line_split
htmlhtmlelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct
{ htmlelement: HTMLElement } impl HTMLHtmlElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHtmlElement { HTMLHtmlElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHtmlElement> { let element = HTMLHtmlElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap) } }
HTMLHtmlElement
identifier_name
htmlhtmlelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct HTMLHtmlElement { htmlelement: HTMLElement } impl HTMLHtmlElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHtmlElement
#[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHtmlElement> { let element = HTMLHtmlElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap) } }
{ HTMLHtmlElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
example.rs
extern crate bmfont; #[macro_use] extern crate glium; extern crate image; use bmfont::{BMFont, OrdinateOrientation}; use glium::{Display, Program, VertexBuffer}; use std::io::Cursor; fn create_program(display: &Display) -> Program { let vertex_shader_src = r#" #version 140 in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main() { v_tex_coords = tex_coords; gl_Position = vec4(position, 0.0, 1.0); } "#; let fragment_shader_src = r#" #version 140 in vec2 v_tex_coords; out vec4 color; uniform sampler2D tex; void main() { color = texture(tex, v_tex_coords); } "#; Program::from_source(display, vertex_shader_src, fragment_shader_src, None).unwrap() } fn main() { use glium::{DisplayBuild, DrawParameters, Surface}; let display = glium::glutin::WindowBuilder::new().build_glium().unwrap(); let image = image::load(Cursor::new(&include_bytes!("../font.png")[..]), image::PNG)
.to_rgba(); let image_dimensions = image.dimensions(); println!("{:?}", image_dimensions); let image = glium::texture::RawImage2d::from_raw_rgba(image.into_raw(), image_dimensions); let texture = glium::texture::Texture2d::new(&display, image).unwrap(); #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); let design_size = (1024.0, 768.0); let bmfont = BMFont::new( Cursor::new(&include_bytes!("../font.fnt")[..]), OrdinateOrientation::BottomToTop, ) .unwrap(); let char_positions = bmfont.parse("Hello\nmy\nfriend"); #[cfg(feature = "parse-error")] let char_positions = char_positions.unwrap(); let shapes = char_positions.into_iter().map(|char_position| { let left_page_x = char_position.page_rect.x as f32 / image_dimensions.0 as f32; let right_page_x = char_position.page_rect.max_x() as f32 / image_dimensions.0 as f32; let top_page_y = char_position.page_rect.y as f32 / image_dimensions.1 as f32; let bottom_page_y = char_position.page_rect.max_y() as f32 / image_dimensions.1 as f32; let left_screen_x = char_position.screen_rect.x as f32 / design_size.0 as f32; let right_screen_x = char_position.screen_rect.max_x() as f32 / design_size.0 as f32; let bottom_screen_y = char_position.screen_rect.y as f32 / design_size.1 as f32; let top_screen_y = char_position.screen_rect.max_y() as f32 / design_size.1 as f32; vec![ Vertex { position: [left_screen_x, bottom_screen_y], tex_coords: [left_page_x, bottom_page_y], }, Vertex { position: [left_screen_x, top_screen_y], tex_coords: [left_page_x, top_page_y], }, Vertex { position: [right_screen_x, top_screen_y], tex_coords: [right_page_x, top_page_y], }, Vertex { position: [left_screen_x, bottom_screen_y], tex_coords: [left_page_x, bottom_page_y], }, Vertex { position: [right_screen_x, top_screen_y], tex_coords: [right_page_x, top_page_y], }, Vertex { position: [right_screen_x, bottom_screen_y], tex_coords: [right_page_x, bottom_page_y], }, ] }); let mut vertex_buffers = Vec::new(); for shape in shapes { vertex_buffers.push(VertexBuffer::new(&display, &shape).unwrap()); } let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList); let program = create_program(&display); let uniforms = uniform! { tex: &texture }; let draw_parameters = DrawParameters { blend: glium::draw_parameters::Blend::alpha_blending(), ..DrawParameters::default() }; loop { let mut target = display.draw(); target.clear_color(0.0, 0.0, 1.0, 1.0); for vertex_buffer in &vertex_buffers { target .draw( vertex_buffer, &indices, &program, &uniforms, &draw_parameters, ) .unwrap(); } target.finish().unwrap(); for ev in display.poll_events() { match ev { glium::glutin::Event::Closed => return, _ => (), } } } }
.unwrap()
random_line_split
example.rs
extern crate bmfont; #[macro_use] extern crate glium; extern crate image; use bmfont::{BMFont, OrdinateOrientation}; use glium::{Display, Program, VertexBuffer}; use std::io::Cursor; fn create_program(display: &Display) -> Program { let vertex_shader_src = r#" #version 140 in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main() { v_tex_coords = tex_coords; gl_Position = vec4(position, 0.0, 1.0); } "#; let fragment_shader_src = r#" #version 140 in vec2 v_tex_coords; out vec4 color; uniform sampler2D tex; void main() { color = texture(tex, v_tex_coords); } "#; Program::from_source(display, vertex_shader_src, fragment_shader_src, None).unwrap() } fn
() { use glium::{DisplayBuild, DrawParameters, Surface}; let display = glium::glutin::WindowBuilder::new().build_glium().unwrap(); let image = image::load(Cursor::new(&include_bytes!("../font.png")[..]), image::PNG) .unwrap() .to_rgba(); let image_dimensions = image.dimensions(); println!("{:?}", image_dimensions); let image = glium::texture::RawImage2d::from_raw_rgba(image.into_raw(), image_dimensions); let texture = glium::texture::Texture2d::new(&display, image).unwrap(); #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); let design_size = (1024.0, 768.0); let bmfont = BMFont::new( Cursor::new(&include_bytes!("../font.fnt")[..]), OrdinateOrientation::BottomToTop, ) .unwrap(); let char_positions = bmfont.parse("Hello\nmy\nfriend"); #[cfg(feature = "parse-error")] let char_positions = char_positions.unwrap(); let shapes = char_positions.into_iter().map(|char_position| { let left_page_x = char_position.page_rect.x as f32 / image_dimensions.0 as f32; let right_page_x = char_position.page_rect.max_x() as f32 / image_dimensions.0 as f32; let top_page_y = char_position.page_rect.y as f32 / image_dimensions.1 as f32; let bottom_page_y = char_position.page_rect.max_y() as f32 / image_dimensions.1 as f32; let left_screen_x = char_position.screen_rect.x as f32 / design_size.0 as f32; let right_screen_x = char_position.screen_rect.max_x() as f32 / design_size.0 as f32; let bottom_screen_y = char_position.screen_rect.y as f32 / design_size.1 as f32; let top_screen_y = char_position.screen_rect.max_y() as f32 / design_size.1 as f32; vec![ Vertex { position: [left_screen_x, bottom_screen_y], tex_coords: [left_page_x, bottom_page_y], }, Vertex { position: [left_screen_x, top_screen_y], tex_coords: [left_page_x, top_page_y], }, Vertex { position: [right_screen_x, top_screen_y], tex_coords: [right_page_x, top_page_y], }, Vertex { position: [left_screen_x, bottom_screen_y], tex_coords: [left_page_x, bottom_page_y], }, Vertex { position: [right_screen_x, top_screen_y], tex_coords: [right_page_x, top_page_y], }, Vertex { position: [right_screen_x, bottom_screen_y], tex_coords: [right_page_x, bottom_page_y], }, ] }); let mut vertex_buffers = Vec::new(); for shape in shapes { vertex_buffers.push(VertexBuffer::new(&display, &shape).unwrap()); } let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList); let program = create_program(&display); let uniforms = uniform! { tex: &texture }; let draw_parameters = DrawParameters { blend: glium::draw_parameters::Blend::alpha_blending(), ..DrawParameters::default() }; loop { let mut target = display.draw(); target.clear_color(0.0, 0.0, 1.0, 1.0); for vertex_buffer in &vertex_buffers { target .draw( vertex_buffer, &indices, &program, &uniforms, &draw_parameters, ) .unwrap(); } target.finish().unwrap(); for ev in display.poll_events() { match ev { glium::glutin::Event::Closed => return, _ => (), } } } }
main
identifier_name
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an + b is prime for n = 0.. N // p(0) = b => b must be prime // p(1) = 1 + a + b => a > -(1+b) // p(2) = 4 + 2a + b fn get_limit_n(ps: &PrimeSet, a: i32, b: i32) -> u32 { (0..).take_while(|&n| { let val = n * n + a * n + b; (val >= 0 && ps.contains(val as u64)) }).last().unwrap() as u32 } fn compute(limit: u64) -> i32
fn solve() -> String { compute(1000).to_string() } problem!("-59231", solve); #[cfg(test)] mod tests { use prime::PrimeSet; #[test] fn primes() { let ps = PrimeSet::new(); assert_eq!(39, super::get_limit_n(&ps, 1, 41)); assert_eq!(79, super::get_limit_n(&ps, -79, 1601)) } }
{ let ps = PrimeSet::new(); let (a, b, _len) = ps.iter() .take_while(|&p| p < limit) .filter_map(|p| { let b = p as i32; (-b .. 1000) .map(|a| (a, b, get_limit_n(&ps, a, b))) .max_by(|&(_a, _b, len)| len) }).max_by(|&(_a, _b, len)| len) .unwrap(); a * b }
identifier_body
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver.
unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an + b is prime for n = 0.. N // p(0) = b => b must be prime // p(1) = 1 + a + b => a > -(1+b) // p(2) = 4 + 2a + b fn get_limit_n(ps: &PrimeSet, a: i32, b: i32) -> u32 { (0..).take_while(|&n| { let val = n * n + a * n + b; (val >= 0 && ps.contains(val as u64)) }).last().unwrap() as u32 } fn compute(limit: u64) -> i32 { let ps = PrimeSet::new(); let (a, b, _len) = ps.iter() .take_while(|&p| p < limit) .filter_map(|p| { let b = p as i32; (-b.. 1000) .map(|a| (a, b, get_limit_n(&ps, a, b))) .max_by(|&(_a, _b, len)| len) }).max_by(|&(_a, _b, len)| len) .unwrap(); a * b } fn solve() -> String { compute(1000).to_string() } problem!("-59231", solve); #[cfg(test)] mod tests { use prime::PrimeSet; #[test] fn primes() { let ps = PrimeSet::new(); assert_eq!(39, super::get_limit_n(&ps, 1, 41)); assert_eq!(79, super::get_limit_n(&ps, -79, 1601)) } }
#![warn(bad_style,
random_line_split
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an + b is prime for n = 0.. N // p(0) = b => b must be prime // p(1) = 1 + a + b => a > -(1+b) // p(2) = 4 + 2a + b fn get_limit_n(ps: &PrimeSet, a: i32, b: i32) -> u32 { (0..).take_while(|&n| { let val = n * n + a * n + b; (val >= 0 && ps.contains(val as u64)) }).last().unwrap() as u32 } fn compute(limit: u64) -> i32 { let ps = PrimeSet::new(); let (a, b, _len) = ps.iter() .take_while(|&p| p < limit) .filter_map(|p| { let b = p as i32; (-b.. 1000) .map(|a| (a, b, get_limit_n(&ps, a, b))) .max_by(|&(_a, _b, len)| len) }).max_by(|&(_a, _b, len)| len) .unwrap(); a * b } fn
() -> String { compute(1000).to_string() } problem!("-59231", solve); #[cfg(test)] mod tests { use prime::PrimeSet; #[test] fn primes() { let ps = PrimeSet::new(); assert_eq!(39, super::get_limit_n(&ps, 1, 41)); assert_eq!(79, super::get_limit_n(&ps, -79, 1601)) } }
solve
identifier_name
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ---------+--------+-------+---------+---------+------------ 6567R56A | NTSC-M | 262 | 234 | 64 | 411 6567R8 | NTSC-M | 263 | 235 | 65 | 418 6569 | PAL-B | 312 | 284 | 63 | 403 | First | Last | | First | Last | vblank | vblank | First X coo. | visible | visible Type | line | line | of a line | X coo. | X coo. ---------+--------+--------+--------------+------------+----------- 6567R56A | 13 | 40 | 412 ($19c) | 488 ($1e8) | 388 ($184) 6567R8 | 13 | 40 | 412 ($19c) | 489 ($1e9) | 396 ($18c) 6569 | 300 | 15 | 404 ($194) | 480 ($1e0) | 380 ($17c) */ #[derive(Clone, Copy)] pub enum SidModel { Mos6581, Mos8580, } #[derive(Copy, Clone)] pub enum VicModel { Mos6567, // NTSC Mos6569, // PAL } pub struct SystemModel { pub color_ram: usize, pub cpu_freq: u32, pub cycles_per_frame: u16, pub frame_buffer_size: (u32, u32), pub memory_size: usize, pub refresh_rate: f32, pub sid_model: SidModel, pub vic_model: VicModel, pub viewport_offset: (u32, u32), pub viewport_size: (u32, u32), } impl SystemModel { pub fn from(model: &str) -> SystemModel { match model { "ntsc" => SystemModel::c64_ntsc(), "pal" => SystemModel::c64_pal(), "c64-ntsc" => SystemModel::c64_ntsc(), "c64-pal" => SystemModel::c64_pal(), _ => panic!("invalid model {}", model), } } pub fn c64_ntsc() -> SystemModel
pub fn c64_pal() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 985_248, cycles_per_frame: 19656, frame_buffer_size: (504, 312), memory_size: 65536, refresh_rate: 50.125, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6569, viewport_offset: (76, 16), viewport_size: (403, 284), } } }
{ SystemModel { color_ram: 1024, cpu_freq: 1_022_727, cycles_per_frame: 17095, frame_buffer_size: (512, 263), memory_size: 65536, refresh_rate: 59.826, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6567, viewport_offset: (77, 16), viewport_size: (418, 235), } }
identifier_body
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ---------+--------+-------+---------+---------+------------ 6567R56A | NTSC-M | 262 | 234 | 64 | 411 6567R8 | NTSC-M | 263 | 235 | 65 | 418 6569 | PAL-B | 312 | 284 | 63 | 403 | First | Last | | First | Last | vblank | vblank | First X coo. | visible | visible Type | line | line | of a line | X coo. | X coo. ---------+--------+--------+--------------+------------+----------- 6567R56A | 13 | 40 | 412 ($19c) | 488 ($1e8) | 388 ($184) 6567R8 | 13 | 40 | 412 ($19c) | 489 ($1e9) | 396 ($18c) 6569 | 300 | 15 | 404 ($194) | 480 ($1e0) | 380 ($17c) */ #[derive(Clone, Copy)] pub enum SidModel { Mos6581, Mos8580, } #[derive(Copy, Clone)] pub enum VicModel { Mos6567, // NTSC Mos6569, // PAL } pub struct SystemModel { pub color_ram: usize, pub cpu_freq: u32, pub cycles_per_frame: u16, pub frame_buffer_size: (u32, u32), pub memory_size: usize, pub refresh_rate: f32, pub sid_model: SidModel, pub vic_model: VicModel, pub viewport_offset: (u32, u32), pub viewport_size: (u32, u32), } impl SystemModel { pub fn from(model: &str) -> SystemModel { match model { "ntsc" => SystemModel::c64_ntsc(), "pal" => SystemModel::c64_pal(), "c64-ntsc" => SystemModel::c64_ntsc(), "c64-pal" => SystemModel::c64_pal(), _ => panic!("invalid model {}", model), } }
frame_buffer_size: (512, 263), memory_size: 65536, refresh_rate: 59.826, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6567, viewport_offset: (77, 16), viewport_size: (418, 235), } } pub fn c64_pal() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 985_248, cycles_per_frame: 19656, frame_buffer_size: (504, 312), memory_size: 65536, refresh_rate: 50.125, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6569, viewport_offset: (76, 16), viewport_size: (403, 284), } } }
pub fn c64_ntsc() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 1_022_727, cycles_per_frame: 17095,
random_line_split
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ---------+--------+-------+---------+---------+------------ 6567R56A | NTSC-M | 262 | 234 | 64 | 411 6567R8 | NTSC-M | 263 | 235 | 65 | 418 6569 | PAL-B | 312 | 284 | 63 | 403 | First | Last | | First | Last | vblank | vblank | First X coo. | visible | visible Type | line | line | of a line | X coo. | X coo. ---------+--------+--------+--------------+------------+----------- 6567R56A | 13 | 40 | 412 ($19c) | 488 ($1e8) | 388 ($184) 6567R8 | 13 | 40 | 412 ($19c) | 489 ($1e9) | 396 ($18c) 6569 | 300 | 15 | 404 ($194) | 480 ($1e0) | 380 ($17c) */ #[derive(Clone, Copy)] pub enum SidModel { Mos6581, Mos8580, } #[derive(Copy, Clone)] pub enum VicModel { Mos6567, // NTSC Mos6569, // PAL } pub struct SystemModel { pub color_ram: usize, pub cpu_freq: u32, pub cycles_per_frame: u16, pub frame_buffer_size: (u32, u32), pub memory_size: usize, pub refresh_rate: f32, pub sid_model: SidModel, pub vic_model: VicModel, pub viewport_offset: (u32, u32), pub viewport_size: (u32, u32), } impl SystemModel { pub fn
(model: &str) -> SystemModel { match model { "ntsc" => SystemModel::c64_ntsc(), "pal" => SystemModel::c64_pal(), "c64-ntsc" => SystemModel::c64_ntsc(), "c64-pal" => SystemModel::c64_pal(), _ => panic!("invalid model {}", model), } } pub fn c64_ntsc() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 1_022_727, cycles_per_frame: 17095, frame_buffer_size: (512, 263), memory_size: 65536, refresh_rate: 59.826, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6567, viewport_offset: (77, 16), viewport_size: (418, 235), } } pub fn c64_pal() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 985_248, cycles_per_frame: 19656, frame_buffer_size: (504, 312), memory_size: 65536, refresh_rate: 50.125, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6569, viewport_offset: (76, 16), viewport_size: (403, 284), } } }
from
identifier_name
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use ffi; use glib::translate::*; use TextBuffer; use TextIter; impl TextBuffer { pub fn insert(&self, iter: &mut TextIter, text: &str) { unsafe { ffi::gtk_text_buffer_insert(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int); } } pub fn insert_at_cursor(&self, text: &str) { unsafe { ffi::gtk_text_buffer_insert_at_cursor(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int); } } pub fn insert_interactive(&self, iter: &mut TextIter, text: &str, default_editable: bool) -> bool
pub fn insert_interactive_at_cursor(&self, text: &str, default_editable: bool) -> bool { unsafe { from_glib(ffi::gtk_text_buffer_insert_interactive_at_cursor(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } } #[cfg(feature = "3.16")] pub fn insert_markup(&self, iter: &mut TextIter, markup: &str) { unsafe { ffi::gtk_text_buffer_insert_markup(self.to_glib_none().0, iter.to_glib_none_mut().0, markup.as_ptr() as *const c_char, markup.len() as c_int); } } pub fn set_text(&self, text: &str) { unsafe { ffi::gtk_text_buffer_set_text(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int); } } }
{ unsafe { from_glib( ffi::gtk_text_buffer_insert_interactive(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } }
identifier_body
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use ffi; use glib::translate::*; use TextBuffer; use TextIter; impl TextBuffer { pub fn insert(&self, iter: &mut TextIter, text: &str) { unsafe { ffi::gtk_text_buffer_insert(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int); } } pub fn insert_at_cursor(&self, text: &str) { unsafe { ffi::gtk_text_buffer_insert_at_cursor(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int); } } pub fn
(&self, iter: &mut TextIter, text: &str, default_editable: bool) -> bool { unsafe { from_glib( ffi::gtk_text_buffer_insert_interactive(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } } pub fn insert_interactive_at_cursor(&self, text: &str, default_editable: bool) -> bool { unsafe { from_glib(ffi::gtk_text_buffer_insert_interactive_at_cursor(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } } #[cfg(feature = "3.16")] pub fn insert_markup(&self, iter: &mut TextIter, markup: &str) { unsafe { ffi::gtk_text_buffer_insert_markup(self.to_glib_none().0, iter.to_glib_none_mut().0, markup.as_ptr() as *const c_char, markup.len() as c_int); } } pub fn set_text(&self, text: &str) { unsafe { ffi::gtk_text_buffer_set_text(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int); } } }
insert_interactive
identifier_name
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use ffi; use glib::translate::*; use TextBuffer; use TextIter; impl TextBuffer { pub fn insert(&self, iter: &mut TextIter, text: &str) { unsafe { ffi::gtk_text_buffer_insert(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int); } }
text.as_ptr() as *const c_char, text.len() as c_int); } } pub fn insert_interactive(&self, iter: &mut TextIter, text: &str, default_editable: bool) -> bool { unsafe { from_glib( ffi::gtk_text_buffer_insert_interactive(self.to_glib_none().0, iter.to_glib_none_mut().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } } pub fn insert_interactive_at_cursor(&self, text: &str, default_editable: bool) -> bool { unsafe { from_glib(ffi::gtk_text_buffer_insert_interactive_at_cursor(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int, default_editable.to_glib())) } } #[cfg(feature = "3.16")] pub fn insert_markup(&self, iter: &mut TextIter, markup: &str) { unsafe { ffi::gtk_text_buffer_insert_markup(self.to_glib_none().0, iter.to_glib_none_mut().0, markup.as_ptr() as *const c_char, markup.len() as c_int); } } pub fn set_text(&self, text: &str) { unsafe { ffi::gtk_text_buffer_set_text(self.to_glib_none().0, text.as_ptr() as *const c_char, text.len() as c_int); } } }
pub fn insert_at_cursor(&self, text: &str) { unsafe { ffi::gtk_text_buffer_insert_at_cursor(self.to_glib_none().0,
random_line_split
main.rs
extern crate rsedis; extern crate config; extern crate logger; extern crate networking; extern crate compat; use std::env::args; use std::process::exit; use std::thread; use compat::getpid; use config::Config; use networking::Server; use logger::{Logger, Level}; fn main() { let mut config = Config::new(Logger::new(Level::Notice)); match args().nth(1) { Some(f) => match config.parsefile(f) { Ok(_) => (), Err(_) => { thread::sleep_ms(100); // I'm not proud, but fatal errors are logged in a background thread // I need to ensure they were printed exit(1);
} let (port, daemonize) = (config.port, config.daemonize); let mut server = Server::new(config); if!daemonize { println!("Port: {}", port); println!("PID: {}", getpid()); } server.run(); }
}, }, None => (),
random_line_split
main.rs
extern crate rsedis; extern crate config; extern crate logger; extern crate networking; extern crate compat; use std::env::args; use std::process::exit; use std::thread; use compat::getpid; use config::Config; use networking::Server; use logger::{Logger, Level}; fn main()
server.run(); }
{ let mut config = Config::new(Logger::new(Level::Notice)); match args().nth(1) { Some(f) => match config.parsefile(f) { Ok(_) => (), Err(_) => { thread::sleep_ms(100); // I'm not proud, but fatal errors are logged in a background thread // I need to ensure they were printed exit(1); }, }, None => (), } let (port, daemonize) = (config.port, config.daemonize); let mut server = Server::new(config); if !daemonize { println!("Port: {}", port); println!("PID: {}", getpid()); }
identifier_body
main.rs
extern crate rsedis; extern crate config; extern crate logger; extern crate networking; extern crate compat; use std::env::args; use std::process::exit; use std::thread; use compat::getpid; use config::Config; use networking::Server; use logger::{Logger, Level}; fn
() { let mut config = Config::new(Logger::new(Level::Notice)); match args().nth(1) { Some(f) => match config.parsefile(f) { Ok(_) => (), Err(_) => { thread::sleep_ms(100); // I'm not proud, but fatal errors are logged in a background thread // I need to ensure they were printed exit(1); }, }, None => (), } let (port, daemonize) = (config.port, config.daemonize); let mut server = Server::new(config); if!daemonize { println!("Port: {}", port); println!("PID: {}", getpid()); } server.run(); }
main
identifier_name
instruction_def.rs
use instruction::Reg; use operand::OperandSize; pub struct InstructionDefinition { pub mnemonic: String, pub allow_prefix: bool, pub operand_size_prefix: OperandSizePrefixBehavior, pub address_size_prefix: Option<bool>, pub f2_prefix: PrefixBehavior, pub f3_prefix: PrefixBehavior, pub composite_prefix: Option<CompositePrefix>, pub fwait: bool, pub two_byte_opcode: bool, pub primary_opcode: u8, pub secondary_opcode: Option<u8>, pub opcode_ext: Option<u8>, pub has_mod_rm: bool, pub fixed_mod_rm_mod: Option<u8>, pub fixed_mod_rm_reg: Option<u8>, pub allow_mask: bool, pub allow_merge_mode: bool, pub allow_rounding: bool, pub allow_sae: bool, pub operands: [Option<OperandDefinition>; 4], pub feature_set: Option<&'static [FeatureSet]>, pub valid_16: bool, pub valid_32: bool, pub valid_64: bool, pub desc: &'static str, } impl InstructionDefinition { pub fn add_operand(&mut self, operand: OperandDefinition) { if self.operands[0].is_none() { self.operands[0] = Some(operand); } else if self.operands[1].is_none() { self.operands[1] = Some(operand); } else if self.operands[2].is_none() { self.operands[2] = Some(operand); } else if self.operands[3].is_none() { self.operands[3] = Some(operand); } else { panic!("Operands full"); } } } impl Default for InstructionDefinition { fn default() -> InstructionDefinition { InstructionDefinition { mnemonic: String::from(""), allow_prefix: true, operand_size_prefix: OperandSizePrefixBehavior::Never, address_size_prefix: None, composite_prefix: None, fwait: false, f2_prefix: PrefixBehavior::Never, f3_prefix: PrefixBehavior::Never, two_byte_opcode: false, primary_opcode: 0, secondary_opcode: None, opcode_ext: None, has_mod_rm: false, fixed_mod_rm_mod: None, fixed_mod_rm_reg: None, allow_mask: false, allow_merge_mode: false, allow_rounding: false, allow_sae: false, operands: [None, None, None, None], feature_set: None, valid_16: false, valid_32: false, valid_64: false, desc: "" } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum OperandSizePrefixBehavior { Always, RealOnly, NotReal, Never } #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum PrefixBehavior { Always, Optional, Never } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CompositePrefix { Rex { size_64: Option<bool>, }, Vex { vector_size: Option<OperandSize>, operand_behavior: Option<VexOperandBehavior>, we: Option<bool> }, Evex { vector_size: Option<OperandSize>, operand_behavior: Option<VexOperandBehavior>, we: Option<bool>, } } #[derive(Clone, Copy, Debug)] pub enum FeatureSet { Sse, Sse2, Sse3, Sse41, Sse42, Aesni, Pclmulqdq, Avx, Avx512vl, Avx512f, Rdrand } #[derive(Clone, Debug)] pub struct OperandDefinition { pub encoding: OperandEncoding, pub access: OperandAccess, pub size: OperandSize, pub op_type: OperandType } #[derive(Clone, Debug)] pub enum OperandType { Reg(RegType), Mem(Option<OperandSize>), Imm, Constant, Offset, Rel(OperandSize), Mib, Bcst(OperandSize), Fixed(FixedOperand), Set(Vec<OperandType>) } impl OperandType { pub fn is_mem(&self) -> bool { match *self { OperandType::Mem(_) | OperandType::Rel(_) | OperandType::Offset | OperandType::Bcst(_) => true, _ => false } } } #[derive(Clone, Copy, Debug)] pub enum OperandEncoding { ModRmReg, ModRmRm, Vex, Imm, OpcodeAddend, Offset, Mib, Fixed } #[derive(Clone, Copy, Debug)] pub enum OperandAccess { Read, Write, ReadWrite } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RegType { General, Mmx, Avx, Fpu, Bound, Mask, Segment, Control, Debug } #[derive(Clone, Copy, Debug)] pub enum
{ Reg(Reg), Constant(u32) } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VexOperandBehavior { Nds, Ndd, Dds }
FixedOperand
identifier_name
instruction_def.rs
use instruction::Reg; use operand::OperandSize; pub struct InstructionDefinition { pub mnemonic: String, pub allow_prefix: bool, pub operand_size_prefix: OperandSizePrefixBehavior, pub address_size_prefix: Option<bool>, pub f2_prefix: PrefixBehavior, pub f3_prefix: PrefixBehavior, pub composite_prefix: Option<CompositePrefix>, pub fwait: bool, pub two_byte_opcode: bool, pub primary_opcode: u8, pub secondary_opcode: Option<u8>, pub opcode_ext: Option<u8>, pub has_mod_rm: bool, pub fixed_mod_rm_mod: Option<u8>, pub fixed_mod_rm_reg: Option<u8>, pub allow_mask: bool, pub allow_merge_mode: bool, pub allow_rounding: bool, pub allow_sae: bool, pub operands: [Option<OperandDefinition>; 4], pub feature_set: Option<&'static [FeatureSet]>, pub valid_16: bool, pub valid_32: bool, pub valid_64: bool, pub desc: &'static str, } impl InstructionDefinition { pub fn add_operand(&mut self, operand: OperandDefinition) { if self.operands[0].is_none() { self.operands[0] = Some(operand); } else if self.operands[1].is_none() { self.operands[1] = Some(operand); } else if self.operands[2].is_none() { self.operands[2] = Some(operand); } else if self.operands[3].is_none() { self.operands[3] = Some(operand); } else { panic!("Operands full"); } } } impl Default for InstructionDefinition { fn default() -> InstructionDefinition { InstructionDefinition { mnemonic: String::from(""), allow_prefix: true, operand_size_prefix: OperandSizePrefixBehavior::Never, address_size_prefix: None, composite_prefix: None, fwait: false, f2_prefix: PrefixBehavior::Never, f3_prefix: PrefixBehavior::Never, two_byte_opcode: false, primary_opcode: 0, secondary_opcode: None, opcode_ext: None, has_mod_rm: false, fixed_mod_rm_mod: None, fixed_mod_rm_reg: None, allow_mask: false, allow_merge_mode: false, allow_rounding: false, allow_sae: false, operands: [None, None, None, None], feature_set: None, valid_16: false, valid_32: false, valid_64: false, desc: "" } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum OperandSizePrefixBehavior { Always, RealOnly, NotReal, Never } #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum PrefixBehavior { Always, Optional, Never } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CompositePrefix { Rex { size_64: Option<bool>, }, Vex { vector_size: Option<OperandSize>, operand_behavior: Option<VexOperandBehavior>, we: Option<bool> }, Evex { vector_size: Option<OperandSize>, operand_behavior: Option<VexOperandBehavior>, we: Option<bool>, } } #[derive(Clone, Copy, Debug)] pub enum FeatureSet { Sse, Sse2, Sse3, Sse41, Sse42, Aesni, Pclmulqdq, Avx, Avx512vl, Avx512f, Rdrand } #[derive(Clone, Debug)] pub struct OperandDefinition { pub encoding: OperandEncoding, pub access: OperandAccess, pub size: OperandSize, pub op_type: OperandType } #[derive(Clone, Debug)] pub enum OperandType { Reg(RegType), Mem(Option<OperandSize>), Imm, Constant, Offset, Rel(OperandSize), Mib, Bcst(OperandSize), Fixed(FixedOperand), Set(Vec<OperandType>) } impl OperandType { pub fn is_mem(&self) -> bool { match *self { OperandType::Mem(_) | OperandType::Rel(_) | OperandType::Offset | OperandType::Bcst(_) => true, _ => false } } } #[derive(Clone, Copy, Debug)] pub enum OperandEncoding { ModRmReg, ModRmRm, Vex, Imm, OpcodeAddend, Offset, Mib, Fixed
#[derive(Clone, Copy, Debug)] pub enum OperandAccess { Read, Write, ReadWrite } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RegType { General, Mmx, Avx, Fpu, Bound, Mask, Segment, Control, Debug } #[derive(Clone, Copy, Debug)] pub enum FixedOperand { Reg(Reg), Constant(u32) } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VexOperandBehavior { Nds, Ndd, Dds }
}
random_line_split
read-scale.rs
// Copyright 2016 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. extern crate xsettings; extern crate x11_dl; use std::ptr; use std::str; use x11_dl::xlib::Xlib; use xsettings::Client; pub fn main()
for key in &[gdk_unscaled_dpi, gdk_xft_dpi, gdk_window_scaling_factor] { let key_str = str::from_utf8(key).unwrap(); match client.get_setting(*key) { Err(err) => println!("{}: {:?}", key_str, err), Ok(setting) => println!("{}={:?}", key_str, setting), } } }
{ let display; let client; let xlib = Xlib::open().unwrap(); unsafe { display = (xlib.XOpenDisplay)(ptr::null_mut()); // Enumerate all properties. client = Client::new(display, (xlib.XDefaultScreen)(display), Box::new(|name, _, setting| { println!("{:?}={:?}", str::from_utf8(name), setting) }), Box::new(|_, _, _| {})); } // Print out a few well-known properties that describe the window scale. let gdk_unscaled_dpi: &[u8] = b"Gdk/UnscaledDPI"; let gdk_xft_dpi: &[u8] = b"Xft/DPI"; let gdk_window_scaling_factor: &[u8] = b"Gdk/WindowScalingFactor";
identifier_body