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 |
---|---|---|---|---|
owned.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.
//! A unique pointer type
use core::any::{Any, AnyRefExt};
use core::clone::Clone;
use core::cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering};
use core::default::Default;
use core::fmt;
use core::intrinsics;
use core::mem;
use core::raw::TraitObject;
use core::result::{Ok, Err, Result};
/// A value that represents the global exchange heap. This is the default
/// place that the `box` keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// let foo = box(HEAP) Bar::new(...);
/// let foo = box Bar::new(...);
#[lang="exchange_heap"]
pub static HEAP: () = ();
/// A type that represents a uniquely-owned value.
#[lang="owned_box"]
pub struct Box<T>(*T);
impl<T: Default> Default for Box<T> {
fn default() -> Box<T> { box Default::default() }
}
impl<T: Clone> Clone for Box<T> {
/// Return a copy of the owned box.
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Perform copy-assignment from `source` by reusing the existing allocation.
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
|
#[inline]
fn eq(&self, other: &Box<T>) -> bool { *(*self) == *(*other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { *(*self)!= *(*other) }
}
impl<T:Ord> Ord for Box<T> {
#[inline]
fn lt(&self, other: &Box<T>) -> bool { *(*self) < *(*other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { *(*self) <= *(*other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { *(*self) >= *(*other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { *(*self) > *(*other) }
}
impl<T: TotalOrd> TotalOrd for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering { (**self).cmp(*other) }
}
impl<T: TotalEq> TotalEq for Box<T> {}
/// Extension methods for an owning `Any` trait object
pub trait AnyOwnExt {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
fn move<T:'static>(self) -> Result<Box<T>, Self>;
}
impl AnyOwnExt for Box<Any> {
#[inline]
fn move<T:'static>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject =
*mem::transmute::<&Box<Any>, &TraitObject>(&self);
// Prevent destructor on self being run
intrinsics::forget(self);
// Extract the data pointer
Ok(mem::transmute(to.data))
}
} else {
Err(self)
}
}
}
impl<T: fmt::Show> fmt::Show for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
impl fmt::Show for Box<Any> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Box<Any>")
}
}
|
}
// box pointers
impl<T:Eq> Eq for Box<T> {
|
random_line_split
|
tokenizer.rs
|
use super::Matcher;
use super::{Token, TokenType, TokenPosition};
#[derive(Clone, Debug)]
pub struct Snapshot {
pub pos: TokenPosition,
pub index: usize,
}
impl Snapshot {
pub fn new(index: usize, pos: TokenPosition) -> Snapshot {
Snapshot {
index,
pos,
}
}
}
#[derive(Clone, Debug)]
pub struct Tokenizer {
pub pos: TokenPosition,
index: usize,
items: Vec<char>,
snapshots: Vec<Snapshot>,
}
impl Iterator for Tokenizer {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
self.read().cloned()
}
}
#[allow(dead_code)]
impl Tokenizer {
pub fn new(items: &mut Iterator<Item = char>) -> Tokenizer {
Tokenizer {
index: 0,
pos: TokenPosition::default(),
items: items.collect(),
snapshots: Vec::new(),
}
}
pub fn end(&self) -> bool {
self.end_n(0)
}
pub fn end_n(&self, lookahead: usize) -> bool {
self.index + lookahead >= self.items.len()
}
pub fn peek(&self) -> Option<&char> {
self.peek_n(0)
}
pub fn peek_n(&self, n: usize) -> Option<&char> {
if self.end_n(n)
|
Some(&self.items[self.index + n])
}
pub fn read(&mut self) -> Option<&char> {
if self.end() {
return None
}
self.advance(1);
Some(&self.items[self.index - 1])
}
pub fn advance(&mut self, a: usize) {
if self.index + a <= self.items.len() {
for item in &self.items[self.index.. self.index + a] {
match *item {
'\n' => {
self.pos.line += 1;
self.pos.col = 0;
}
_ => self.pos.col += 1
}
}
self.index += a
}
}
pub fn take_snapshot(&mut self) {
self.snapshots.push(Snapshot::new(self.index, self.pos));
}
pub fn peek_snapshot(&self) -> Option<&Snapshot> {
self.snapshots.last()
}
pub fn rollback_snapshot(&mut self) {
let snapshot = self.snapshots.pop().unwrap();
self.index = snapshot.index;
self.pos = snapshot.pos;
}
pub fn commit_snapshot(&mut self) {
self.snapshots.pop();
}
pub fn last_position(&self) -> TokenPosition {
self.peek_snapshot().unwrap().pos
}
pub fn try_match_token(&mut self, matcher: &Matcher) -> Option<Token> {
if self.end() {
return Some(Token::new(TokenType::EOF,
TokenPosition::new(self.index, self.index),
String::new()));
}
self.take_snapshot();
match matcher.try_match(self) {
Some(t) => {
self.commit_snapshot();
Some(t)
}
None => {
self.rollback_snapshot();
None
}
}
}
pub fn index(&self) -> &usize {
&self.index
}
}
|
{
return None
}
|
conditional_block
|
tokenizer.rs
|
use super::Matcher;
use super::{Token, TokenType, TokenPosition};
#[derive(Clone, Debug)]
pub struct Snapshot {
pub pos: TokenPosition,
pub index: usize,
}
impl Snapshot {
pub fn new(index: usize, pos: TokenPosition) -> Snapshot {
Snapshot {
index,
pos,
}
}
}
#[derive(Clone, Debug)]
pub struct Tokenizer {
pub pos: TokenPosition,
index: usize,
items: Vec<char>,
snapshots: Vec<Snapshot>,
}
impl Iterator for Tokenizer {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
self.read().cloned()
}
}
#[allow(dead_code)]
impl Tokenizer {
pub fn new(items: &mut Iterator<Item = char>) -> Tokenizer {
Tokenizer {
index: 0,
pos: TokenPosition::default(),
items: items.collect(),
snapshots: Vec::new(),
}
}
pub fn end(&self) -> bool {
self.end_n(0)
}
pub fn end_n(&self, lookahead: usize) -> bool {
self.index + lookahead >= self.items.len()
}
pub fn peek(&self) -> Option<&char> {
self.peek_n(0)
}
pub fn peek_n(&self, n: usize) -> Option<&char> {
if self.end_n(n) {
return None
}
Some(&self.items[self.index + n])
}
pub fn read(&mut self) -> Option<&char>
|
pub fn advance(&mut self, a: usize) {
if self.index + a <= self.items.len() {
for item in &self.items[self.index.. self.index + a] {
match *item {
'\n' => {
self.pos.line += 1;
self.pos.col = 0;
}
_ => self.pos.col += 1
}
}
self.index += a
}
}
pub fn take_snapshot(&mut self) {
self.snapshots.push(Snapshot::new(self.index, self.pos));
}
pub fn peek_snapshot(&self) -> Option<&Snapshot> {
self.snapshots.last()
}
pub fn rollback_snapshot(&mut self) {
let snapshot = self.snapshots.pop().unwrap();
self.index = snapshot.index;
self.pos = snapshot.pos;
}
pub fn commit_snapshot(&mut self) {
self.snapshots.pop();
}
pub fn last_position(&self) -> TokenPosition {
self.peek_snapshot().unwrap().pos
}
pub fn try_match_token(&mut self, matcher: &Matcher) -> Option<Token> {
if self.end() {
return Some(Token::new(TokenType::EOF,
TokenPosition::new(self.index, self.index),
String::new()));
}
self.take_snapshot();
match matcher.try_match(self) {
Some(t) => {
self.commit_snapshot();
Some(t)
}
None => {
self.rollback_snapshot();
None
}
}
}
pub fn index(&self) -> &usize {
&self.index
}
}
|
{
if self.end() {
return None
}
self.advance(1);
Some(&self.items[self.index - 1])
}
|
identifier_body
|
tokenizer.rs
|
use super::Matcher;
use super::{Token, TokenType, TokenPosition};
#[derive(Clone, Debug)]
pub struct Snapshot {
pub pos: TokenPosition,
pub index: usize,
}
impl Snapshot {
pub fn new(index: usize, pos: TokenPosition) -> Snapshot {
Snapshot {
index,
pos,
}
}
}
#[derive(Clone, Debug)]
pub struct Tokenizer {
pub pos: TokenPosition,
index: usize,
items: Vec<char>,
snapshots: Vec<Snapshot>,
}
impl Iterator for Tokenizer {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
self.read().cloned()
}
}
#[allow(dead_code)]
impl Tokenizer {
pub fn new(items: &mut Iterator<Item = char>) -> Tokenizer {
Tokenizer {
index: 0,
pos: TokenPosition::default(),
items: items.collect(),
snapshots: Vec::new(),
}
}
pub fn end(&self) -> bool {
self.end_n(0)
}
pub fn end_n(&self, lookahead: usize) -> bool {
self.index + lookahead >= self.items.len()
}
pub fn peek(&self) -> Option<&char> {
self.peek_n(0)
}
pub fn peek_n(&self, n: usize) -> Option<&char> {
if self.end_n(n) {
return None
}
Some(&self.items[self.index + n])
}
pub fn read(&mut self) -> Option<&char> {
if self.end() {
return None
}
self.advance(1);
Some(&self.items[self.index - 1])
}
pub fn advance(&mut self, a: usize) {
if self.index + a <= self.items.len() {
for item in &self.items[self.index.. self.index + a] {
match *item {
'\n' => {
self.pos.line += 1;
self.pos.col = 0;
}
_ => self.pos.col += 1
}
}
self.index += a
}
}
pub fn take_snapshot(&mut self) {
self.snapshots.push(Snapshot::new(self.index, self.pos));
}
pub fn peek_snapshot(&self) -> Option<&Snapshot> {
self.snapshots.last()
}
pub fn rollback_snapshot(&mut self) {
let snapshot = self.snapshots.pop().unwrap();
self.index = snapshot.index;
self.pos = snapshot.pos;
}
pub fn
|
(&mut self) {
self.snapshots.pop();
}
pub fn last_position(&self) -> TokenPosition {
self.peek_snapshot().unwrap().pos
}
pub fn try_match_token(&mut self, matcher: &Matcher) -> Option<Token> {
if self.end() {
return Some(Token::new(TokenType::EOF,
TokenPosition::new(self.index, self.index),
String::new()));
}
self.take_snapshot();
match matcher.try_match(self) {
Some(t) => {
self.commit_snapshot();
Some(t)
}
None => {
self.rollback_snapshot();
None
}
}
}
pub fn index(&self) -> &usize {
&self.index
}
}
|
commit_snapshot
|
identifier_name
|
tokenizer.rs
|
use super::Matcher;
use super::{Token, TokenType, TokenPosition};
#[derive(Clone, Debug)]
pub struct Snapshot {
pub pos: TokenPosition,
pub index: usize,
}
impl Snapshot {
pub fn new(index: usize, pos: TokenPosition) -> Snapshot {
Snapshot {
index,
pos,
}
}
}
#[derive(Clone, Debug)]
pub struct Tokenizer {
pub pos: TokenPosition,
index: usize,
items: Vec<char>,
snapshots: Vec<Snapshot>,
}
impl Iterator for Tokenizer {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
self.read().cloned()
}
}
#[allow(dead_code)]
impl Tokenizer {
pub fn new(items: &mut Iterator<Item = char>) -> Tokenizer {
Tokenizer {
index: 0,
pos: TokenPosition::default(),
items: items.collect(),
snapshots: Vec::new(),
}
}
pub fn end(&self) -> bool {
self.end_n(0)
}
pub fn end_n(&self, lookahead: usize) -> bool {
self.index + lookahead >= self.items.len()
}
pub fn peek(&self) -> Option<&char> {
self.peek_n(0)
}
pub fn peek_n(&self, n: usize) -> Option<&char> {
if self.end_n(n) {
return None
}
Some(&self.items[self.index + n])
}
pub fn read(&mut self) -> Option<&char> {
if self.end() {
return None
}
self.advance(1);
Some(&self.items[self.index - 1])
}
pub fn advance(&mut self, a: usize) {
if self.index + a <= self.items.len() {
for item in &self.items[self.index.. self.index + a] {
match *item {
'\n' => {
self.pos.line += 1;
self.pos.col = 0;
}
_ => self.pos.col += 1
}
}
self.index += a
}
}
pub fn take_snapshot(&mut self) {
self.snapshots.push(Snapshot::new(self.index, self.pos));
}
pub fn peek_snapshot(&self) -> Option<&Snapshot> {
self.snapshots.last()
}
pub fn rollback_snapshot(&mut self) {
let snapshot = self.snapshots.pop().unwrap();
self.index = snapshot.index;
self.pos = snapshot.pos;
}
pub fn commit_snapshot(&mut self) {
self.snapshots.pop();
}
pub fn last_position(&self) -> TokenPosition {
self.peek_snapshot().unwrap().pos
}
pub fn try_match_token(&mut self, matcher: &Matcher) -> Option<Token> {
if self.end() {
return Some(Token::new(TokenType::EOF,
|
self.take_snapshot();
match matcher.try_match(self) {
Some(t) => {
self.commit_snapshot();
Some(t)
}
None => {
self.rollback_snapshot();
None
}
}
}
pub fn index(&self) -> &usize {
&self.index
}
}
|
TokenPosition::new(self.index, self.index),
String::new()));
}
|
random_line_split
|
mod.rs
|
//! M17n
//!
//! The docs in this module quote the [m17n "Data format of the m17n database"
//! docs][1] a lot.
//!
//! [1]: https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html
use regex::Regex;
use std::{convert::TryFrom, str::FromStr};
mod ser;
pub use ser::ToMim;
/// M17n Input Method, i.e., the content of a `.mim` file
//
// INPUT-METHOD ::=
// IM-DECLARATION? IM-DESCRIPTION? TITLE?
// VARIABLE-LIST? COMMAND-LIST? MODULE-LIST?
// MACRO-LIST? MAP-LIST? STATE-LIST?
//
//
// IM-DESCRIPTION ::= '(' 'description' DESCRIPTION ')'
// DESCRIPTION ::= MTEXT-OR-GETTEXT | 'nil'
// MTEXT-OR-GETTEXT ::= [ MTEXT | '(' '_' MTEXT ')']
//
// TITLE ::= '(' 'title' TITLE-TEXT ')'
// TITLE-TEXT ::= MTEXT
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Root {
pub input_method: InputMethod,
pub description: Option<Text>,
pub title: Text,
// variable_list: Vec<Variable>,
// command_list: Vec<Command>,
// module_list: Vec<Mgodule>,
// macro_list: Vec<Macro>,
pub maps: Vec<Map>,
pub states: Vec<State>,
}
// IM-DECLARATION ::= '(' 'input-method' LANGUAGE NAME EXTRA-ID? VERSION? ')'
// LANGUAGE ::= SYMBOL
// NAME ::= SYMBOL
// EXTRA-ID ::= SYMBOL
// VERSION ::= '(''version' VERSION-NUMBER ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct InputMethod {
pub language: Symbol,
pub name: Symbol,
pub extra_id: Option<Symbol>,
pub version: Option<String>,
}
// MAP-LIST ::= MAP-INCLUSION? '(''map' MAP * ')'
// MAP ::= '(' MAP-NAME RULE * ')'
// MAP-NAME ::= SYMBOL
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Map {
pub name: Symbol,
pub rules: Vec<Rule>,
}
// RULE ::= '(' KEYSEQ MAP-ACTION * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Rule {
/// Keys to press to produce mapping
pub keyseq: KeySeq,
/// The mapping describes what to do
///
/// Right now we only support inserting characters.
pub action: MapAction,
}
// KEYSEQ ::= MTEXT | '(' [ SYMBOL | INTEGER ] * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum KeySeq {
/// > MTEXT in the definition of `KEYSEQ` consists of characters that can be
/// > generated by a keyboard. Therefore MTEXT usually contains only ASCII
/// > characters. However, if the input method is intended to be used, for
/// > instance, with a West European keyboard, MTEXT may contain Latin-1
/// > characters.
Character(Text),
/// > If the shift, control, meta, alt, super, and hyper modifiers are used,
/// > they are represented by the `S-`, `C-`, `M-`, `A-`, `s-`, and `H-`
/// > prefixes respectively in this order. Thus, "return with shift with
/// > meta with hyper" is `(S-M-H-Return)`. Note that "a with shift".. "z
/// > with shift" are represented simply as `A.. Z`. Thus "a with shift
/// > with meta with hyper" is `(M-H-A)`.
KeyCombo(KeyCombo),
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct KeyCombo {
/// Represents something like `C-S` for "Control + Shift"
pub modifiers: Vec<Modifier>,
// Can be TEXT or INTEGER but let's be conservative and expect a character
// code.
pub key: KeyDef,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum KeyDef {
/// > INTEGER in the definition of `KEYSEQ` must be a valid character code.
CharacterCode(Integer),
/// > SYMBOL in the definition of `KEYSEQ` must be the return value of the
/// > `minput_event_to_key()` function. Under the X window system, you can
/// > quickly check the value using the `xev` command. For example, the
/// > return key, the backspace key, and the 0 key on the keypad are
/// > represented as `(Return)`, `(BackSpace)`, and `(KP_0)` respectively.
Character(Symbol),
}
/// Modifier keys
///
/// > "S-" (Shift), "C-" (Control), "M-" (Meta), "A-" (Alt), "G-" (AltGr), "s-"
/// > (Super), and "H-" (Hyper)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(strum_macros::EnumString, strum_macros::Display)]
#[strum(serialize_all = "snake_case")]
pub enum Modifier {
Shift,
#[strum(serialize = "ctrl", serialize = "control")]
Control,
/// Often one of the Alt keys in terminals
Meta,
Alt,
AltGr,
/// Super key is assumed to be Command key on macOS
#[strum(serialize = "super", serialize = "cmd")]
Super,
/// Mo layers, mo fun. Let's pick caps lock for this.
#[strum(serialize = "hyper", serialize = "caps")]
Hyper,
}
impl Modifier {
/// Parse kbdgen-typical key combo syntax
///
/// ```rust
/// use kbdgen::m17n_mim::Modifier;
///
/// assert_eq!(
/// Modifier::parse_keycombo("ctrl").unwrap(),
/// vec![Modifier::Control],
/// );
/// assert_eq!(
/// Modifier::parse_keycombo("alt+shift").unwrap(),
/// vec![Modifier::Alt, Modifier::Shift],
/// );
/// assert_eq!(
/// Modifier::parse_keycombo("cmd+alt").unwrap(),
/// vec![Modifier::Super, Modifier::Alt],
/// );
/// ```
pub fn parse_keycombo(input: &str) -> Result<Vec<Modifier>, MimConversion> {
let mut res = vec![];
for m in input.split('+') {
if let Ok(m) = Modifier::from_str(m) {
res.push(m);
} else {
return Err(MimConversion::InvalidKeyCombo {
input: format!("unknown modifier `{}`", m),
});
}
}
Ok(res)
}
}
// Originally a quite complex type, defined as:
//
// ```bnf
// MAP-ACTION ::= ACTION
//
// ACTION ::= INSERT | DELETE | SELECT | MOVE | MARK
// | SHOW | HIDE | PUSHBACK | POP | UNDO
// | COMMIT | UNHANDLE | SHIFT | CALL
// | SET | IF | COND | '(' MACRO-NAME ')'
//
// PREDEFINED-SYMBOL ::=
// '@0' | '@1' | '@2' | '@3' | '@4'
// | '@5' | '@6' | '@7' | '@8' | '@9'
// | '@<' | '@=' | '@>' | '@-' | '@+' | '@[' | '@]'
// | '@@'
// | '@-0' | '@-N' | '@+N'
// ```
//
// but we've only implemented the trivial Insert variants at the moment.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum MapAction {
Insert(Insert),
#[cfg(sorry_not_yet_implemented)]
Delete(Delete),
#[cfg(sorry_not_yet_implemented)]
Select(Select),
#[cfg(sorry_not_yet_implemented)]
Move(Move),
#[cfg(sorry_not_yet_implemented)]
Mark(Mark),
#[cfg(sorry_not_yet_implemented)]
Show(Show),
#[cfg(sorry_not_yet_implemented)]
Hide(Hide),
#[cfg(sorry_not_yet_implemented)]
Pushback(Pushback),
#[cfg(sorry_not_yet_implemented)]
Pop(Pop),
#[cfg(sorry_not_yet_implemented)]
Undo(Undo),
#[cfg(sorry_not_yet_implemented)]
Commit(Commit),
#[cfg(sorry_not_yet_implemented)]
Unhandle(Unhandle),
#[cfg(sorry_not_yet_implemented)]
Shift(Shift),
#[cfg(sorry_not_yet_implemented)]
Call(Call),
#[cfg(sorry_not_yet_implemented)]
Set(Set),
#[cfg(sorry_not_yet_implemented)]
If(If),
#[cfg(sorry_not_yet_implemented)]
Cond(Cond),
#[cfg(sorry_not_yet_implemented)]
Macro(Symbol),
}
/// Insert action: insert something before the current position
//
// Originally defined as:
//
// ```bnf
// INSERT ::= '(' 'insert' MTEXT ')'
// | MTEXT
// | INTEGER
// | SYMBOL
// | '(' 'insert' SYMBOL ')'
// | '(' 'insert' '(' CANDIDATES * ')' ')'
// | '(' CANDIDATES * ')'
//
// CANDIDATES ::= MTEXT | '(' MTEXT * ')'
// ```
//
// but we'll only use the simple forms for now
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Insert {
/// > insert TEXT before the current position
Character(Text),
/// > inserts the character INTEGER before the current position
CharacterCode(Integer),
#[cfg(sorry_not_yet_implemented)]
/// > treats SYMBOL as a variable, and inserts its value (if it is a valid
/// > character code) before the current position
KeyCombo(Symbol),
#[cfg(sorry_not_yet_implemented)]
/// > each CANDIDATES represents a candidate group, and each element of
/// >CANDIDATES represents a candidate, i.e. if CANDIDATES is an M-text, the
/// >candidates are the characters in the M-text; if CANDIDATES is a list of
/// >M-texts, the candidates are the M-texts in the list.
/// >
/// >These forms insert the first candidate before the current position. The
/// >inserted string is associated with the list of candidates and the
/// >information indicating the currently selected candidate.
Candidates(Vec<Text>),
}
// STATE-LIST ::= STATE-INCUSION? '(''state' STATE * ')' STATE-INCUSION?
// STATE ::= '(' STATE-NAME [ STATE-TITLE-TEXT ] BRANCH * ')'
// STATE-NAME ::= SYMBOL
// STATE-TITLE-TEXT ::= MTEXT
// STATE-INCLUSION ::= '(' 'include' TAGS'state' STATE-NAME? ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct State {
pub name: Symbol,
pub title: Option<Text>,
pub branches: Vec<Branch>,
}
// BRANCH ::= '(' MAP-NAME BRANCH-ACTION * ')'
// | '(' 'nil' BRANCH-ACTION * ')'
// | '(' 't' BRANCH-ACTION * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Branch {
pub map_name: Symbol,
#[cfg(sorry_not_yet_implemented)]
pub actions: Vec<Action>,
}
/// The "MSymbol" type
|
/// > `\r`, and `\e` are replaced with tab (code 9), newline (code 10), carriage
/// > return (code 13), and escape (code 27) respectively. Other characters
/// > following a backslash is interpreted as it is. The value of the property
/// > is the symbol having the resulting string as its name.
/// >
/// > For instance, the element `abc\ def` represents a property whose value is
/// > the symbol having the name "abc def".
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Symbol(String);
impl TryFrom<String> for Symbol {
type Error = MimConversion;
fn try_from(x: String) -> Result<Self, Self::Error> {
// FIXME: Escaping and stuff
Ok(Symbol(x))
}
}
/// The "MText" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `([^"]|\")*` represents a
/// > property whose key is `Mtext`. The backslash escape explained above also
/// > applies here. Moreover, each part in the element matching the regular
/// > expression `\[xX][0-9A-Fa-f][0-9A-Fa-f]` is replaced with its hexadecimal
/// > interpretation.
///
/// > After having resolved the backslash escapes, the byte sequence between the
/// > double quotes is interpreted as a UTF-8 sequence and decoded into an
/// > M-text. This M-text is the value of the property.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Text(String);
impl TryFrom<String> for Text {
type Error = MimConversion;
fn try_from(input: String) -> Result<Self, Self::Error> {
// FIXME: Escaping and stuff
// FIXME: transforming existing escapes like `\u{30A}` to `\x30A`
lazy_static::lazy_static! {
static ref RE: Regex = Regex::new(r"\\u\{([0-9A-Fa-f]{1,6})\}").expect("valid regex");
}
let new = RE.replace_all(&input, |cap: ®ex::Captures| {
let hex = cap.get(1).unwrap().as_str();
format!("\\x{}", hex)
});
Ok(Text(new.to_string()))
}
}
/// The "Minteger" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `-?[0-9]+ or
/// > 0[xX][0-9A-Fa-f]+` represents a property whose key is `Minteger`. An
/// > element matching the former expression is interpreted as an integer in
/// > decimal notation, and one matching the latter is interpreted as an integer
/// > in hexadecimal notation. The value of the property is the result of
/// > interpretation.
/// >
/// > For instance, the element `0xA0` represents a property whose value is 160
/// > in decimal.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Integer(String);
impl TryFrom<String> for Integer {
type Error = MimConversion;
fn try_from(input: String) -> Result<Self, Self::Error> {
// decimal
if u32::from_str_radix(&input, 10).is_ok() {
return Ok(Integer(input));
}
// hex
if!(input.starts_with("0x") || input.starts_with("0X")) {
return Err(MimConversion::InvalidIntegerHexPrefix { input });
}
match u64::from_str_radix(&input[2..], 16) {
Ok(_) => Ok(Integer(input)),
Err(source) => Err(MimConversion::InvalidIntegerHexValue { input, source }),
}
}
}
/// Possible errors when converting values to their MIM representation
#[derive(Debug, thiserror::Error)]
pub enum MimConversion {
#[error("Could not serialize MIM symbol")]
InvalidSymbol,
#[error("Could not serialize MIM text")]
InvalidText,
#[error("Could not serialize MIM key combo: {}", input)]
InvalidKeyCombo { input: String },
#[error("Could not map index `{}` to a character code", index)]
InvalidCharactorCodeIndex { index: usize },
#[error(
"Assumed hexadecimal MIM integer but there was no `0x` prefix in `{}`",
input
)]
InvalidIntegerHexPrefix { input: String },
#[error(
"Assumed hexadecimal MIM integer but `{}` is not a valid hex value",
input
)]
InvalidIntegerHexValue {
input: String,
source: std::num::ParseIntError,
},
}
|
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `[^-0-9(]([^\()]|\.)+`
/// > represents a property whose key is `Msymbol`. In the element, `\t`, `\n`,
|
random_line_split
|
mod.rs
|
//! M17n
//!
//! The docs in this module quote the [m17n "Data format of the m17n database"
//! docs][1] a lot.
//!
//! [1]: https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html
use regex::Regex;
use std::{convert::TryFrom, str::FromStr};
mod ser;
pub use ser::ToMim;
/// M17n Input Method, i.e., the content of a `.mim` file
//
// INPUT-METHOD ::=
// IM-DECLARATION? IM-DESCRIPTION? TITLE?
// VARIABLE-LIST? COMMAND-LIST? MODULE-LIST?
// MACRO-LIST? MAP-LIST? STATE-LIST?
//
//
// IM-DESCRIPTION ::= '(' 'description' DESCRIPTION ')'
// DESCRIPTION ::= MTEXT-OR-GETTEXT | 'nil'
// MTEXT-OR-GETTEXT ::= [ MTEXT | '(' '_' MTEXT ')']
//
// TITLE ::= '(' 'title' TITLE-TEXT ')'
// TITLE-TEXT ::= MTEXT
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Root {
pub input_method: InputMethod,
pub description: Option<Text>,
pub title: Text,
// variable_list: Vec<Variable>,
// command_list: Vec<Command>,
// module_list: Vec<Mgodule>,
// macro_list: Vec<Macro>,
pub maps: Vec<Map>,
pub states: Vec<State>,
}
// IM-DECLARATION ::= '(' 'input-method' LANGUAGE NAME EXTRA-ID? VERSION? ')'
// LANGUAGE ::= SYMBOL
// NAME ::= SYMBOL
// EXTRA-ID ::= SYMBOL
// VERSION ::= '(''version' VERSION-NUMBER ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct InputMethod {
pub language: Symbol,
pub name: Symbol,
pub extra_id: Option<Symbol>,
pub version: Option<String>,
}
// MAP-LIST ::= MAP-INCLUSION? '(''map' MAP * ')'
// MAP ::= '(' MAP-NAME RULE * ')'
// MAP-NAME ::= SYMBOL
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct
|
{
pub name: Symbol,
pub rules: Vec<Rule>,
}
// RULE ::= '(' KEYSEQ MAP-ACTION * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Rule {
/// Keys to press to produce mapping
pub keyseq: KeySeq,
/// The mapping describes what to do
///
/// Right now we only support inserting characters.
pub action: MapAction,
}
// KEYSEQ ::= MTEXT | '(' [ SYMBOL | INTEGER ] * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum KeySeq {
/// > MTEXT in the definition of `KEYSEQ` consists of characters that can be
/// > generated by a keyboard. Therefore MTEXT usually contains only ASCII
/// > characters. However, if the input method is intended to be used, for
/// > instance, with a West European keyboard, MTEXT may contain Latin-1
/// > characters.
Character(Text),
/// > If the shift, control, meta, alt, super, and hyper modifiers are used,
/// > they are represented by the `S-`, `C-`, `M-`, `A-`, `s-`, and `H-`
/// > prefixes respectively in this order. Thus, "return with shift with
/// > meta with hyper" is `(S-M-H-Return)`. Note that "a with shift".. "z
/// > with shift" are represented simply as `A.. Z`. Thus "a with shift
/// > with meta with hyper" is `(M-H-A)`.
KeyCombo(KeyCombo),
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct KeyCombo {
/// Represents something like `C-S` for "Control + Shift"
pub modifiers: Vec<Modifier>,
// Can be TEXT or INTEGER but let's be conservative and expect a character
// code.
pub key: KeyDef,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum KeyDef {
/// > INTEGER in the definition of `KEYSEQ` must be a valid character code.
CharacterCode(Integer),
/// > SYMBOL in the definition of `KEYSEQ` must be the return value of the
/// > `minput_event_to_key()` function. Under the X window system, you can
/// > quickly check the value using the `xev` command. For example, the
/// > return key, the backspace key, and the 0 key on the keypad are
/// > represented as `(Return)`, `(BackSpace)`, and `(KP_0)` respectively.
Character(Symbol),
}
/// Modifier keys
///
/// > "S-" (Shift), "C-" (Control), "M-" (Meta), "A-" (Alt), "G-" (AltGr), "s-"
/// > (Super), and "H-" (Hyper)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(strum_macros::EnumString, strum_macros::Display)]
#[strum(serialize_all = "snake_case")]
pub enum Modifier {
Shift,
#[strum(serialize = "ctrl", serialize = "control")]
Control,
/// Often one of the Alt keys in terminals
Meta,
Alt,
AltGr,
/// Super key is assumed to be Command key on macOS
#[strum(serialize = "super", serialize = "cmd")]
Super,
/// Mo layers, mo fun. Let's pick caps lock for this.
#[strum(serialize = "hyper", serialize = "caps")]
Hyper,
}
impl Modifier {
/// Parse kbdgen-typical key combo syntax
///
/// ```rust
/// use kbdgen::m17n_mim::Modifier;
///
/// assert_eq!(
/// Modifier::parse_keycombo("ctrl").unwrap(),
/// vec![Modifier::Control],
/// );
/// assert_eq!(
/// Modifier::parse_keycombo("alt+shift").unwrap(),
/// vec![Modifier::Alt, Modifier::Shift],
/// );
/// assert_eq!(
/// Modifier::parse_keycombo("cmd+alt").unwrap(),
/// vec![Modifier::Super, Modifier::Alt],
/// );
/// ```
pub fn parse_keycombo(input: &str) -> Result<Vec<Modifier>, MimConversion> {
let mut res = vec![];
for m in input.split('+') {
if let Ok(m) = Modifier::from_str(m) {
res.push(m);
} else {
return Err(MimConversion::InvalidKeyCombo {
input: format!("unknown modifier `{}`", m),
});
}
}
Ok(res)
}
}
// Originally a quite complex type, defined as:
//
// ```bnf
// MAP-ACTION ::= ACTION
//
// ACTION ::= INSERT | DELETE | SELECT | MOVE | MARK
// | SHOW | HIDE | PUSHBACK | POP | UNDO
// | COMMIT | UNHANDLE | SHIFT | CALL
// | SET | IF | COND | '(' MACRO-NAME ')'
//
// PREDEFINED-SYMBOL ::=
// '@0' | '@1' | '@2' | '@3' | '@4'
// | '@5' | '@6' | '@7' | '@8' | '@9'
// | '@<' | '@=' | '@>' | '@-' | '@+' | '@[' | '@]'
// | '@@'
// | '@-0' | '@-N' | '@+N'
// ```
//
// but we've only implemented the trivial Insert variants at the moment.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum MapAction {
Insert(Insert),
#[cfg(sorry_not_yet_implemented)]
Delete(Delete),
#[cfg(sorry_not_yet_implemented)]
Select(Select),
#[cfg(sorry_not_yet_implemented)]
Move(Move),
#[cfg(sorry_not_yet_implemented)]
Mark(Mark),
#[cfg(sorry_not_yet_implemented)]
Show(Show),
#[cfg(sorry_not_yet_implemented)]
Hide(Hide),
#[cfg(sorry_not_yet_implemented)]
Pushback(Pushback),
#[cfg(sorry_not_yet_implemented)]
Pop(Pop),
#[cfg(sorry_not_yet_implemented)]
Undo(Undo),
#[cfg(sorry_not_yet_implemented)]
Commit(Commit),
#[cfg(sorry_not_yet_implemented)]
Unhandle(Unhandle),
#[cfg(sorry_not_yet_implemented)]
Shift(Shift),
#[cfg(sorry_not_yet_implemented)]
Call(Call),
#[cfg(sorry_not_yet_implemented)]
Set(Set),
#[cfg(sorry_not_yet_implemented)]
If(If),
#[cfg(sorry_not_yet_implemented)]
Cond(Cond),
#[cfg(sorry_not_yet_implemented)]
Macro(Symbol),
}
/// Insert action: insert something before the current position
//
// Originally defined as:
//
// ```bnf
// INSERT ::= '(' 'insert' MTEXT ')'
// | MTEXT
// | INTEGER
// | SYMBOL
// | '(' 'insert' SYMBOL ')'
// | '(' 'insert' '(' CANDIDATES * ')' ')'
// | '(' CANDIDATES * ')'
//
// CANDIDATES ::= MTEXT | '(' MTEXT * ')'
// ```
//
// but we'll only use the simple forms for now
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Insert {
/// > insert TEXT before the current position
Character(Text),
/// > inserts the character INTEGER before the current position
CharacterCode(Integer),
#[cfg(sorry_not_yet_implemented)]
/// > treats SYMBOL as a variable, and inserts its value (if it is a valid
/// > character code) before the current position
KeyCombo(Symbol),
#[cfg(sorry_not_yet_implemented)]
/// > each CANDIDATES represents a candidate group, and each element of
/// >CANDIDATES represents a candidate, i.e. if CANDIDATES is an M-text, the
/// >candidates are the characters in the M-text; if CANDIDATES is a list of
/// >M-texts, the candidates are the M-texts in the list.
/// >
/// >These forms insert the first candidate before the current position. The
/// >inserted string is associated with the list of candidates and the
/// >information indicating the currently selected candidate.
Candidates(Vec<Text>),
}
// STATE-LIST ::= STATE-INCUSION? '(''state' STATE * ')' STATE-INCUSION?
// STATE ::= '(' STATE-NAME [ STATE-TITLE-TEXT ] BRANCH * ')'
// STATE-NAME ::= SYMBOL
// STATE-TITLE-TEXT ::= MTEXT
// STATE-INCLUSION ::= '(' 'include' TAGS'state' STATE-NAME? ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct State {
pub name: Symbol,
pub title: Option<Text>,
pub branches: Vec<Branch>,
}
// BRANCH ::= '(' MAP-NAME BRANCH-ACTION * ')'
// | '(' 'nil' BRANCH-ACTION * ')'
// | '(' 't' BRANCH-ACTION * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Branch {
pub map_name: Symbol,
#[cfg(sorry_not_yet_implemented)]
pub actions: Vec<Action>,
}
/// The "MSymbol" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `[^-0-9(]([^\()]|\.)+`
/// > represents a property whose key is `Msymbol`. In the element, `\t`, `\n`,
/// > `\r`, and `\e` are replaced with tab (code 9), newline (code 10), carriage
/// > return (code 13), and escape (code 27) respectively. Other characters
/// > following a backslash is interpreted as it is. The value of the property
/// > is the symbol having the resulting string as its name.
/// >
/// > For instance, the element `abc\ def` represents a property whose value is
/// > the symbol having the name "abc def".
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Symbol(String);
impl TryFrom<String> for Symbol {
type Error = MimConversion;
fn try_from(x: String) -> Result<Self, Self::Error> {
// FIXME: Escaping and stuff
Ok(Symbol(x))
}
}
/// The "MText" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `([^"]|\")*` represents a
/// > property whose key is `Mtext`. The backslash escape explained above also
/// > applies here. Moreover, each part in the element matching the regular
/// > expression `\[xX][0-9A-Fa-f][0-9A-Fa-f]` is replaced with its hexadecimal
/// > interpretation.
///
/// > After having resolved the backslash escapes, the byte sequence between the
/// > double quotes is interpreted as a UTF-8 sequence and decoded into an
/// > M-text. This M-text is the value of the property.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Text(String);
impl TryFrom<String> for Text {
type Error = MimConversion;
fn try_from(input: String) -> Result<Self, Self::Error> {
// FIXME: Escaping and stuff
// FIXME: transforming existing escapes like `\u{30A}` to `\x30A`
lazy_static::lazy_static! {
static ref RE: Regex = Regex::new(r"\\u\{([0-9A-Fa-f]{1,6})\}").expect("valid regex");
}
let new = RE.replace_all(&input, |cap: ®ex::Captures| {
let hex = cap.get(1).unwrap().as_str();
format!("\\x{}", hex)
});
Ok(Text(new.to_string()))
}
}
/// The "Minteger" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `-?[0-9]+ or
/// > 0[xX][0-9A-Fa-f]+` represents a property whose key is `Minteger`. An
/// > element matching the former expression is interpreted as an integer in
/// > decimal notation, and one matching the latter is interpreted as an integer
/// > in hexadecimal notation. The value of the property is the result of
/// > interpretation.
/// >
/// > For instance, the element `0xA0` represents a property whose value is 160
/// > in decimal.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Integer(String);
impl TryFrom<String> for Integer {
type Error = MimConversion;
fn try_from(input: String) -> Result<Self, Self::Error> {
// decimal
if u32::from_str_radix(&input, 10).is_ok() {
return Ok(Integer(input));
}
// hex
if!(input.starts_with("0x") || input.starts_with("0X")) {
return Err(MimConversion::InvalidIntegerHexPrefix { input });
}
match u64::from_str_radix(&input[2..], 16) {
Ok(_) => Ok(Integer(input)),
Err(source) => Err(MimConversion::InvalidIntegerHexValue { input, source }),
}
}
}
/// Possible errors when converting values to their MIM representation
#[derive(Debug, thiserror::Error)]
pub enum MimConversion {
#[error("Could not serialize MIM symbol")]
InvalidSymbol,
#[error("Could not serialize MIM text")]
InvalidText,
#[error("Could not serialize MIM key combo: {}", input)]
InvalidKeyCombo { input: String },
#[error("Could not map index `{}` to a character code", index)]
InvalidCharactorCodeIndex { index: usize },
#[error(
"Assumed hexadecimal MIM integer but there was no `0x` prefix in `{}`",
input
)]
InvalidIntegerHexPrefix { input: String },
#[error(
"Assumed hexadecimal MIM integer but `{}` is not a valid hex value",
input
)]
InvalidIntegerHexValue {
input: String,
source: std::num::ParseIntError,
},
}
|
Map
|
identifier_name
|
mod.rs
|
//! M17n
//!
//! The docs in this module quote the [m17n "Data format of the m17n database"
//! docs][1] a lot.
//!
//! [1]: https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html
use regex::Regex;
use std::{convert::TryFrom, str::FromStr};
mod ser;
pub use ser::ToMim;
/// M17n Input Method, i.e., the content of a `.mim` file
//
// INPUT-METHOD ::=
// IM-DECLARATION? IM-DESCRIPTION? TITLE?
// VARIABLE-LIST? COMMAND-LIST? MODULE-LIST?
// MACRO-LIST? MAP-LIST? STATE-LIST?
//
//
// IM-DESCRIPTION ::= '(' 'description' DESCRIPTION ')'
// DESCRIPTION ::= MTEXT-OR-GETTEXT | 'nil'
// MTEXT-OR-GETTEXT ::= [ MTEXT | '(' '_' MTEXT ')']
//
// TITLE ::= '(' 'title' TITLE-TEXT ')'
// TITLE-TEXT ::= MTEXT
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Root {
pub input_method: InputMethod,
pub description: Option<Text>,
pub title: Text,
// variable_list: Vec<Variable>,
// command_list: Vec<Command>,
// module_list: Vec<Mgodule>,
// macro_list: Vec<Macro>,
pub maps: Vec<Map>,
pub states: Vec<State>,
}
// IM-DECLARATION ::= '(' 'input-method' LANGUAGE NAME EXTRA-ID? VERSION? ')'
// LANGUAGE ::= SYMBOL
// NAME ::= SYMBOL
// EXTRA-ID ::= SYMBOL
// VERSION ::= '(''version' VERSION-NUMBER ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct InputMethod {
pub language: Symbol,
pub name: Symbol,
pub extra_id: Option<Symbol>,
pub version: Option<String>,
}
// MAP-LIST ::= MAP-INCLUSION? '(''map' MAP * ')'
// MAP ::= '(' MAP-NAME RULE * ')'
// MAP-NAME ::= SYMBOL
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Map {
pub name: Symbol,
pub rules: Vec<Rule>,
}
// RULE ::= '(' KEYSEQ MAP-ACTION * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Rule {
/// Keys to press to produce mapping
pub keyseq: KeySeq,
/// The mapping describes what to do
///
/// Right now we only support inserting characters.
pub action: MapAction,
}
// KEYSEQ ::= MTEXT | '(' [ SYMBOL | INTEGER ] * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum KeySeq {
/// > MTEXT in the definition of `KEYSEQ` consists of characters that can be
/// > generated by a keyboard. Therefore MTEXT usually contains only ASCII
/// > characters. However, if the input method is intended to be used, for
/// > instance, with a West European keyboard, MTEXT may contain Latin-1
/// > characters.
Character(Text),
/// > If the shift, control, meta, alt, super, and hyper modifiers are used,
/// > they are represented by the `S-`, `C-`, `M-`, `A-`, `s-`, and `H-`
/// > prefixes respectively in this order. Thus, "return with shift with
/// > meta with hyper" is `(S-M-H-Return)`. Note that "a with shift".. "z
/// > with shift" are represented simply as `A.. Z`. Thus "a with shift
/// > with meta with hyper" is `(M-H-A)`.
KeyCombo(KeyCombo),
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct KeyCombo {
/// Represents something like `C-S` for "Control + Shift"
pub modifiers: Vec<Modifier>,
// Can be TEXT or INTEGER but let's be conservative and expect a character
// code.
pub key: KeyDef,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum KeyDef {
/// > INTEGER in the definition of `KEYSEQ` must be a valid character code.
CharacterCode(Integer),
/// > SYMBOL in the definition of `KEYSEQ` must be the return value of the
/// > `minput_event_to_key()` function. Under the X window system, you can
/// > quickly check the value using the `xev` command. For example, the
/// > return key, the backspace key, and the 0 key on the keypad are
/// > represented as `(Return)`, `(BackSpace)`, and `(KP_0)` respectively.
Character(Symbol),
}
/// Modifier keys
///
/// > "S-" (Shift), "C-" (Control), "M-" (Meta), "A-" (Alt), "G-" (AltGr), "s-"
/// > (Super), and "H-" (Hyper)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(strum_macros::EnumString, strum_macros::Display)]
#[strum(serialize_all = "snake_case")]
pub enum Modifier {
Shift,
#[strum(serialize = "ctrl", serialize = "control")]
Control,
/// Often one of the Alt keys in terminals
Meta,
Alt,
AltGr,
/// Super key is assumed to be Command key on macOS
#[strum(serialize = "super", serialize = "cmd")]
Super,
/// Mo layers, mo fun. Let's pick caps lock for this.
#[strum(serialize = "hyper", serialize = "caps")]
Hyper,
}
impl Modifier {
/// Parse kbdgen-typical key combo syntax
///
/// ```rust
/// use kbdgen::m17n_mim::Modifier;
///
/// assert_eq!(
/// Modifier::parse_keycombo("ctrl").unwrap(),
/// vec![Modifier::Control],
/// );
/// assert_eq!(
/// Modifier::parse_keycombo("alt+shift").unwrap(),
/// vec![Modifier::Alt, Modifier::Shift],
/// );
/// assert_eq!(
/// Modifier::parse_keycombo("cmd+alt").unwrap(),
/// vec![Modifier::Super, Modifier::Alt],
/// );
/// ```
pub fn parse_keycombo(input: &str) -> Result<Vec<Modifier>, MimConversion> {
let mut res = vec![];
for m in input.split('+') {
if let Ok(m) = Modifier::from_str(m) {
res.push(m);
} else {
return Err(MimConversion::InvalidKeyCombo {
input: format!("unknown modifier `{}`", m),
});
}
}
Ok(res)
}
}
// Originally a quite complex type, defined as:
//
// ```bnf
// MAP-ACTION ::= ACTION
//
// ACTION ::= INSERT | DELETE | SELECT | MOVE | MARK
// | SHOW | HIDE | PUSHBACK | POP | UNDO
// | COMMIT | UNHANDLE | SHIFT | CALL
// | SET | IF | COND | '(' MACRO-NAME ')'
//
// PREDEFINED-SYMBOL ::=
// '@0' | '@1' | '@2' | '@3' | '@4'
// | '@5' | '@6' | '@7' | '@8' | '@9'
// | '@<' | '@=' | '@>' | '@-' | '@+' | '@[' | '@]'
// | '@@'
// | '@-0' | '@-N' | '@+N'
// ```
//
// but we've only implemented the trivial Insert variants at the moment.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum MapAction {
Insert(Insert),
#[cfg(sorry_not_yet_implemented)]
Delete(Delete),
#[cfg(sorry_not_yet_implemented)]
Select(Select),
#[cfg(sorry_not_yet_implemented)]
Move(Move),
#[cfg(sorry_not_yet_implemented)]
Mark(Mark),
#[cfg(sorry_not_yet_implemented)]
Show(Show),
#[cfg(sorry_not_yet_implemented)]
Hide(Hide),
#[cfg(sorry_not_yet_implemented)]
Pushback(Pushback),
#[cfg(sorry_not_yet_implemented)]
Pop(Pop),
#[cfg(sorry_not_yet_implemented)]
Undo(Undo),
#[cfg(sorry_not_yet_implemented)]
Commit(Commit),
#[cfg(sorry_not_yet_implemented)]
Unhandle(Unhandle),
#[cfg(sorry_not_yet_implemented)]
Shift(Shift),
#[cfg(sorry_not_yet_implemented)]
Call(Call),
#[cfg(sorry_not_yet_implemented)]
Set(Set),
#[cfg(sorry_not_yet_implemented)]
If(If),
#[cfg(sorry_not_yet_implemented)]
Cond(Cond),
#[cfg(sorry_not_yet_implemented)]
Macro(Symbol),
}
/// Insert action: insert something before the current position
//
// Originally defined as:
//
// ```bnf
// INSERT ::= '(' 'insert' MTEXT ')'
// | MTEXT
// | INTEGER
// | SYMBOL
// | '(' 'insert' SYMBOL ')'
// | '(' 'insert' '(' CANDIDATES * ')' ')'
// | '(' CANDIDATES * ')'
//
// CANDIDATES ::= MTEXT | '(' MTEXT * ')'
// ```
//
// but we'll only use the simple forms for now
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Insert {
/// > insert TEXT before the current position
Character(Text),
/// > inserts the character INTEGER before the current position
CharacterCode(Integer),
#[cfg(sorry_not_yet_implemented)]
/// > treats SYMBOL as a variable, and inserts its value (if it is a valid
/// > character code) before the current position
KeyCombo(Symbol),
#[cfg(sorry_not_yet_implemented)]
/// > each CANDIDATES represents a candidate group, and each element of
/// >CANDIDATES represents a candidate, i.e. if CANDIDATES is an M-text, the
/// >candidates are the characters in the M-text; if CANDIDATES is a list of
/// >M-texts, the candidates are the M-texts in the list.
/// >
/// >These forms insert the first candidate before the current position. The
/// >inserted string is associated with the list of candidates and the
/// >information indicating the currently selected candidate.
Candidates(Vec<Text>),
}
// STATE-LIST ::= STATE-INCUSION? '(''state' STATE * ')' STATE-INCUSION?
// STATE ::= '(' STATE-NAME [ STATE-TITLE-TEXT ] BRANCH * ')'
// STATE-NAME ::= SYMBOL
// STATE-TITLE-TEXT ::= MTEXT
// STATE-INCLUSION ::= '(' 'include' TAGS'state' STATE-NAME? ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct State {
pub name: Symbol,
pub title: Option<Text>,
pub branches: Vec<Branch>,
}
// BRANCH ::= '(' MAP-NAME BRANCH-ACTION * ')'
// | '(' 'nil' BRANCH-ACTION * ')'
// | '(' 't' BRANCH-ACTION * ')'
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Branch {
pub map_name: Symbol,
#[cfg(sorry_not_yet_implemented)]
pub actions: Vec<Action>,
}
/// The "MSymbol" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `[^-0-9(]([^\()]|\.)+`
/// > represents a property whose key is `Msymbol`. In the element, `\t`, `\n`,
/// > `\r`, and `\e` are replaced with tab (code 9), newline (code 10), carriage
/// > return (code 13), and escape (code 27) respectively. Other characters
/// > following a backslash is interpreted as it is. The value of the property
/// > is the symbol having the resulting string as its name.
/// >
/// > For instance, the element `abc\ def` represents a property whose value is
/// > the symbol having the name "abc def".
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Symbol(String);
impl TryFrom<String> for Symbol {
type Error = MimConversion;
fn try_from(x: String) -> Result<Self, Self::Error> {
// FIXME: Escaping and stuff
Ok(Symbol(x))
}
}
/// The "MText" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `([^"]|\")*` represents a
/// > property whose key is `Mtext`. The backslash escape explained above also
/// > applies here. Moreover, each part in the element matching the regular
/// > expression `\[xX][0-9A-Fa-f][0-9A-Fa-f]` is replaced with its hexadecimal
/// > interpretation.
///
/// > After having resolved the backslash escapes, the byte sequence between the
/// > double quotes is interpreted as a UTF-8 sequence and decoded into an
/// > M-text. This M-text is the value of the property.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Text(String);
impl TryFrom<String> for Text {
type Error = MimConversion;
fn try_from(input: String) -> Result<Self, Self::Error> {
// FIXME: Escaping and stuff
// FIXME: transforming existing escapes like `\u{30A}` to `\x30A`
lazy_static::lazy_static! {
static ref RE: Regex = Regex::new(r"\\u\{([0-9A-Fa-f]{1,6})\}").expect("valid regex");
}
let new = RE.replace_all(&input, |cap: ®ex::Captures| {
let hex = cap.get(1).unwrap().as_str();
format!("\\x{}", hex)
});
Ok(Text(new.to_string()))
}
}
/// The "Minteger" type
///
/// [Defined](https://www.nongnu.org/m17n/manual-en/m17nDBFormat.html) as:
///
/// > An element that matches the regular expression `-?[0-9]+ or
/// > 0[xX][0-9A-Fa-f]+` represents a property whose key is `Minteger`. An
/// > element matching the former expression is interpreted as an integer in
/// > decimal notation, and one matching the latter is interpreted as an integer
/// > in hexadecimal notation. The value of the property is the result of
/// > interpretation.
/// >
/// > For instance, the element `0xA0` represents a property whose value is 160
/// > in decimal.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Integer(String);
impl TryFrom<String> for Integer {
type Error = MimConversion;
fn try_from(input: String) -> Result<Self, Self::Error> {
// decimal
if u32::from_str_radix(&input, 10).is_ok()
|
// hex
if!(input.starts_with("0x") || input.starts_with("0X")) {
return Err(MimConversion::InvalidIntegerHexPrefix { input });
}
match u64::from_str_radix(&input[2..], 16) {
Ok(_) => Ok(Integer(input)),
Err(source) => Err(MimConversion::InvalidIntegerHexValue { input, source }),
}
}
}
/// Possible errors when converting values to their MIM representation
#[derive(Debug, thiserror::Error)]
pub enum MimConversion {
#[error("Could not serialize MIM symbol")]
InvalidSymbol,
#[error("Could not serialize MIM text")]
InvalidText,
#[error("Could not serialize MIM key combo: {}", input)]
InvalidKeyCombo { input: String },
#[error("Could not map index `{}` to a character code", index)]
InvalidCharactorCodeIndex { index: usize },
#[error(
"Assumed hexadecimal MIM integer but there was no `0x` prefix in `{}`",
input
)]
InvalidIntegerHexPrefix { input: String },
#[error(
"Assumed hexadecimal MIM integer but `{}` is not a valid hex value",
input
)]
InvalidIntegerHexValue {
input: String,
source: std::num::ParseIntError,
},
}
|
{
return Ok(Integer(input));
}
|
conditional_block
|
c_vec.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.
//! Library to interface with chunks of memory allocated in C.
//!
//! It is often desirable to safely interface with memory allocated from C,
//! encapsulating the unsafety into allocation and destruction time. Indeed,
//! allocating memory externally is currently the only way to give Rust shared
//! mut state with C programs that keep their own references; vectors are
//! unsuitable because they could be reallocated or moved at any time, and
//! importing C memory into a vector takes a one-time snapshot of the memory.
//!
//! This module simplifies the usage of such external blocks of memory. Memory
//! is encapsulated into an opaque object after creation; the lifecycle of the
//! memory can be optionally managed by Rust, if an appropriate destructor
//! closure is provided. Safety is ensured by bounds-checking accesses, which
//! are marshalled through get and set functions.
//!
//! There are three unsafe functions: the two constructors, and the
//! unwrap method. The constructors are unsafe for the
//! obvious reason (they act on a pointer that cannot be checked inside the
//! method), but `unwrap()` is somewhat more subtle in its unsafety.
//! It returns the contained pointer, but at the same time destroys the CVec
//! without running its destructor. This can be used to pass memory back to
//! C, but care must be taken that the ownership of underlying resources are
//! handled correctly, i.e. that allocated memory is eventually freed
//! if necessary.
#![experimental]
use collections::Collection;
use kinds::Send;
use mem;
use ops::Drop;
use option::{Option, Some, None};
use ptr::RawPtr;
use ptr;
use raw;
use slice::AsSlice;
/// The type representing a foreign chunk of memory
pub struct CVec<T> {
base: *mut T,
len: uint,
dtor: Option<proc():Send>,
}
#[unsafe_destructor]
|
Some(f) => f()
}
}
}
impl<T> CVec<T> {
/// Create a `CVec` from a raw pointer to a buffer with a given length.
///
/// Fails if the given pointer is null. The returned vector will not attempt
/// to deallocate the vector when dropped.
///
/// # Arguments
///
/// * base - A raw pointer to a buffer
/// * len - The number of elements in the buffer
pub unsafe fn new(base: *mut T, len: uint) -> CVec<T> {
assert!(base!= ptr::null_mut());
CVec {
base: base,
len: len,
dtor: None,
}
}
/// Create a `CVec` from a foreign buffer, with a given length,
/// and a function to run upon destruction.
///
/// Fails if the given pointer is null.
///
/// # Arguments
///
/// * base - A foreign pointer to a buffer
/// * len - The number of elements in the buffer
/// * dtor - A proc to run when the value is destructed, useful
/// for freeing the buffer, etc.
pub unsafe fn new_with_dtor(base: *mut T, len: uint,
dtor: proc():Send) -> CVec<T> {
assert!(base!= ptr::null_mut());
CVec {
base: base,
len: len,
dtor: Some(dtor),
}
}
/// View the stored data as a mutable slice.
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
/// Retrieves an element at a given index, returning `None` if the requested
/// index is greater than the length of the vector.
pub fn get<'a>(&'a self, ofs: uint) -> Option<&'a T> {
if ofs < self.len {
Some(unsafe { &*self.base.offset(ofs as int) })
} else {
None
}
}
/// Retrieves a mutable element at a given index, returning `None` if the
/// requested index is greater than the length of the vector.
pub fn get_mut<'a>(&'a mut self, ofs: uint) -> Option<&'a mut T> {
if ofs < self.len {
Some(unsafe { &mut *self.base.offset(ofs as int) })
} else {
None
}
}
/// Unwrap the pointer without running the destructor
///
/// This method retrieves the underlying pointer, and in the process
/// destroys the CVec but without running the destructor. A use case
/// would be transferring ownership of the buffer to a C function, as
/// in this case you would not want to run the destructor.
///
/// Note that if you want to access the underlying pointer without
/// cancelling the destructor, you can simply call `transmute` on the return
/// value of `get(0)`.
pub unsafe fn unwrap(mut self) -> *mut T {
self.dtor = None;
self.base
}
}
impl<T> AsSlice<T> for CVec<T> {
/// View the stored data as a slice.
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
}
impl<T> Collection for CVec<T> {
fn len(&self) -> uint { self.len }
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::CVec;
use libc;
use ptr;
use rt::libc_heap::malloc_raw;
fn malloc(n: uint) -> CVec<u8> {
unsafe {
let mem = malloc_raw(n);
CVec::new_with_dtor(mem as *mut u8, n,
proc() { libc::free(mem as *mut libc::c_void); })
}
}
#[test]
fn test_basic() {
let mut cv = malloc(16);
*cv.get_mut(3).unwrap() = 8;
*cv.get_mut(4).unwrap() = 9;
assert_eq!(*cv.get(3).unwrap(), 8);
assert_eq!(*cv.get(4).unwrap(), 9);
assert_eq!(cv.len(), 16);
}
#[test]
#[should_fail]
fn test_fail_at_null() {
unsafe {
CVec::new(ptr::null_mut::<u8>(), 9);
}
}
#[test]
fn test_overrun_get() {
let cv = malloc(16);
assert!(cv.get(17).is_none());
}
#[test]
fn test_overrun_set() {
let mut cv = malloc(16);
assert!(cv.get_mut(17).is_none());
}
#[test]
fn test_unwrap() {
unsafe {
let cv = CVec::new_with_dtor(1 as *mut int, 0,
proc() { fail!("Don't run this destructor!") });
let p = cv.unwrap();
assert_eq!(p, 1 as *mut int);
}
}
}
|
impl<T> Drop for CVec<T> {
fn drop(&mut self) {
match self.dtor.take() {
None => (),
|
random_line_split
|
c_vec.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.
//! Library to interface with chunks of memory allocated in C.
//!
//! It is often desirable to safely interface with memory allocated from C,
//! encapsulating the unsafety into allocation and destruction time. Indeed,
//! allocating memory externally is currently the only way to give Rust shared
//! mut state with C programs that keep their own references; vectors are
//! unsuitable because they could be reallocated or moved at any time, and
//! importing C memory into a vector takes a one-time snapshot of the memory.
//!
//! This module simplifies the usage of such external blocks of memory. Memory
//! is encapsulated into an opaque object after creation; the lifecycle of the
//! memory can be optionally managed by Rust, if an appropriate destructor
//! closure is provided. Safety is ensured by bounds-checking accesses, which
//! are marshalled through get and set functions.
//!
//! There are three unsafe functions: the two constructors, and the
//! unwrap method. The constructors are unsafe for the
//! obvious reason (they act on a pointer that cannot be checked inside the
//! method), but `unwrap()` is somewhat more subtle in its unsafety.
//! It returns the contained pointer, but at the same time destroys the CVec
//! without running its destructor. This can be used to pass memory back to
//! C, but care must be taken that the ownership of underlying resources are
//! handled correctly, i.e. that allocated memory is eventually freed
//! if necessary.
#![experimental]
use collections::Collection;
use kinds::Send;
use mem;
use ops::Drop;
use option::{Option, Some, None};
use ptr::RawPtr;
use ptr;
use raw;
use slice::AsSlice;
/// The type representing a foreign chunk of memory
pub struct CVec<T> {
base: *mut T,
len: uint,
dtor: Option<proc():Send>,
}
#[unsafe_destructor]
impl<T> Drop for CVec<T> {
fn drop(&mut self) {
match self.dtor.take() {
None => (),
Some(f) => f()
}
}
}
impl<T> CVec<T> {
/// Create a `CVec` from a raw pointer to a buffer with a given length.
///
/// Fails if the given pointer is null. The returned vector will not attempt
/// to deallocate the vector when dropped.
///
/// # Arguments
///
/// * base - A raw pointer to a buffer
/// * len - The number of elements in the buffer
pub unsafe fn new(base: *mut T, len: uint) -> CVec<T> {
assert!(base!= ptr::null_mut());
CVec {
base: base,
len: len,
dtor: None,
}
}
/// Create a `CVec` from a foreign buffer, with a given length,
/// and a function to run upon destruction.
///
/// Fails if the given pointer is null.
///
/// # Arguments
///
/// * base - A foreign pointer to a buffer
/// * len - The number of elements in the buffer
/// * dtor - A proc to run when the value is destructed, useful
/// for freeing the buffer, etc.
pub unsafe fn new_with_dtor(base: *mut T, len: uint,
dtor: proc():Send) -> CVec<T> {
assert!(base!= ptr::null_mut());
CVec {
base: base,
len: len,
dtor: Some(dtor),
}
}
/// View the stored data as a mutable slice.
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
/// Retrieves an element at a given index, returning `None` if the requested
/// index is greater than the length of the vector.
pub fn get<'a>(&'a self, ofs: uint) -> Option<&'a T> {
if ofs < self.len {
Some(unsafe { &*self.base.offset(ofs as int) })
} else {
None
}
}
/// Retrieves a mutable element at a given index, returning `None` if the
/// requested index is greater than the length of the vector.
pub fn get_mut<'a>(&'a mut self, ofs: uint) -> Option<&'a mut T> {
if ofs < self.len {
Some(unsafe { &mut *self.base.offset(ofs as int) })
} else {
None
}
}
/// Unwrap the pointer without running the destructor
///
/// This method retrieves the underlying pointer, and in the process
/// destroys the CVec but without running the destructor. A use case
/// would be transferring ownership of the buffer to a C function, as
/// in this case you would not want to run the destructor.
///
/// Note that if you want to access the underlying pointer without
/// cancelling the destructor, you can simply call `transmute` on the return
/// value of `get(0)`.
pub unsafe fn unwrap(mut self) -> *mut T {
self.dtor = None;
self.base
}
}
impl<T> AsSlice<T> for CVec<T> {
/// View the stored data as a slice.
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
}
impl<T> Collection for CVec<T> {
fn len(&self) -> uint { self.len }
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::CVec;
use libc;
use ptr;
use rt::libc_heap::malloc_raw;
fn malloc(n: uint) -> CVec<u8> {
unsafe {
let mem = malloc_raw(n);
CVec::new_with_dtor(mem as *mut u8, n,
proc() { libc::free(mem as *mut libc::c_void); })
}
}
#[test]
fn test_basic() {
let mut cv = malloc(16);
*cv.get_mut(3).unwrap() = 8;
*cv.get_mut(4).unwrap() = 9;
assert_eq!(*cv.get(3).unwrap(), 8);
assert_eq!(*cv.get(4).unwrap(), 9);
assert_eq!(cv.len(), 16);
}
#[test]
#[should_fail]
fn test_fail_at_null() {
unsafe {
CVec::new(ptr::null_mut::<u8>(), 9);
}
}
#[test]
fn test_overrun_get() {
let cv = malloc(16);
assert!(cv.get(17).is_none());
}
#[test]
fn
|
() {
let mut cv = malloc(16);
assert!(cv.get_mut(17).is_none());
}
#[test]
fn test_unwrap() {
unsafe {
let cv = CVec::new_with_dtor(1 as *mut int, 0,
proc() { fail!("Don't run this destructor!") });
let p = cv.unwrap();
assert_eq!(p, 1 as *mut int);
}
}
}
|
test_overrun_set
|
identifier_name
|
c_vec.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.
//! Library to interface with chunks of memory allocated in C.
//!
//! It is often desirable to safely interface with memory allocated from C,
//! encapsulating the unsafety into allocation and destruction time. Indeed,
//! allocating memory externally is currently the only way to give Rust shared
//! mut state with C programs that keep their own references; vectors are
//! unsuitable because they could be reallocated or moved at any time, and
//! importing C memory into a vector takes a one-time snapshot of the memory.
//!
//! This module simplifies the usage of such external blocks of memory. Memory
//! is encapsulated into an opaque object after creation; the lifecycle of the
//! memory can be optionally managed by Rust, if an appropriate destructor
//! closure is provided. Safety is ensured by bounds-checking accesses, which
//! are marshalled through get and set functions.
//!
//! There are three unsafe functions: the two constructors, and the
//! unwrap method. The constructors are unsafe for the
//! obvious reason (they act on a pointer that cannot be checked inside the
//! method), but `unwrap()` is somewhat more subtle in its unsafety.
//! It returns the contained pointer, but at the same time destroys the CVec
//! without running its destructor. This can be used to pass memory back to
//! C, but care must be taken that the ownership of underlying resources are
//! handled correctly, i.e. that allocated memory is eventually freed
//! if necessary.
#![experimental]
use collections::Collection;
use kinds::Send;
use mem;
use ops::Drop;
use option::{Option, Some, None};
use ptr::RawPtr;
use ptr;
use raw;
use slice::AsSlice;
/// The type representing a foreign chunk of memory
pub struct CVec<T> {
base: *mut T,
len: uint,
dtor: Option<proc():Send>,
}
#[unsafe_destructor]
impl<T> Drop for CVec<T> {
fn drop(&mut self)
|
}
impl<T> CVec<T> {
/// Create a `CVec` from a raw pointer to a buffer with a given length.
///
/// Fails if the given pointer is null. The returned vector will not attempt
/// to deallocate the vector when dropped.
///
/// # Arguments
///
/// * base - A raw pointer to a buffer
/// * len - The number of elements in the buffer
pub unsafe fn new(base: *mut T, len: uint) -> CVec<T> {
assert!(base!= ptr::null_mut());
CVec {
base: base,
len: len,
dtor: None,
}
}
/// Create a `CVec` from a foreign buffer, with a given length,
/// and a function to run upon destruction.
///
/// Fails if the given pointer is null.
///
/// # Arguments
///
/// * base - A foreign pointer to a buffer
/// * len - The number of elements in the buffer
/// * dtor - A proc to run when the value is destructed, useful
/// for freeing the buffer, etc.
pub unsafe fn new_with_dtor(base: *mut T, len: uint,
dtor: proc():Send) -> CVec<T> {
assert!(base!= ptr::null_mut());
CVec {
base: base,
len: len,
dtor: Some(dtor),
}
}
/// View the stored data as a mutable slice.
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
/// Retrieves an element at a given index, returning `None` if the requested
/// index is greater than the length of the vector.
pub fn get<'a>(&'a self, ofs: uint) -> Option<&'a T> {
if ofs < self.len {
Some(unsafe { &*self.base.offset(ofs as int) })
} else {
None
}
}
/// Retrieves a mutable element at a given index, returning `None` if the
/// requested index is greater than the length of the vector.
pub fn get_mut<'a>(&'a mut self, ofs: uint) -> Option<&'a mut T> {
if ofs < self.len {
Some(unsafe { &mut *self.base.offset(ofs as int) })
} else {
None
}
}
/// Unwrap the pointer without running the destructor
///
/// This method retrieves the underlying pointer, and in the process
/// destroys the CVec but without running the destructor. A use case
/// would be transferring ownership of the buffer to a C function, as
/// in this case you would not want to run the destructor.
///
/// Note that if you want to access the underlying pointer without
/// cancelling the destructor, you can simply call `transmute` on the return
/// value of `get(0)`.
pub unsafe fn unwrap(mut self) -> *mut T {
self.dtor = None;
self.base
}
}
impl<T> AsSlice<T> for CVec<T> {
/// View the stored data as a slice.
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
}
impl<T> Collection for CVec<T> {
fn len(&self) -> uint { self.len }
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::CVec;
use libc;
use ptr;
use rt::libc_heap::malloc_raw;
fn malloc(n: uint) -> CVec<u8> {
unsafe {
let mem = malloc_raw(n);
CVec::new_with_dtor(mem as *mut u8, n,
proc() { libc::free(mem as *mut libc::c_void); })
}
}
#[test]
fn test_basic() {
let mut cv = malloc(16);
*cv.get_mut(3).unwrap() = 8;
*cv.get_mut(4).unwrap() = 9;
assert_eq!(*cv.get(3).unwrap(), 8);
assert_eq!(*cv.get(4).unwrap(), 9);
assert_eq!(cv.len(), 16);
}
#[test]
#[should_fail]
fn test_fail_at_null() {
unsafe {
CVec::new(ptr::null_mut::<u8>(), 9);
}
}
#[test]
fn test_overrun_get() {
let cv = malloc(16);
assert!(cv.get(17).is_none());
}
#[test]
fn test_overrun_set() {
let mut cv = malloc(16);
assert!(cv.get_mut(17).is_none());
}
#[test]
fn test_unwrap() {
unsafe {
let cv = CVec::new_with_dtor(1 as *mut int, 0,
proc() { fail!("Don't run this destructor!") });
let p = cv.unwrap();
assert_eq!(p, 1 as *mut int);
}
}
}
|
{
match self.dtor.take() {
None => (),
Some(f) => f()
}
}
|
identifier_body
|
cmn.rs
|
to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, serde::json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool
|
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() &&!self.is_depleted() {
match self.read(&mut buf[total_bytes_read..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
// The following macro invocation needs to be expanded, as `include!`
// doens't support external macros
// header!{
// #[doc="The `X-Upload-Content-Type` header."]
// (XUploadContentType, "X-Upload-Content-Type") => [Mime]
// xupload_content_type {
// test_header!(
// test1,
// vec![b"text/plain"],
// Some(HeaderField(
// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())]
// )));
// }
// }
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len()!= 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> Option<Self> {
None
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Some(RangeResponseHeader(c))
}
}
}
}
None
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<oauth2::Scheme>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
|
{
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
|
identifier_body
|
cmn.rs
|
(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, serde::json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() &&!self.is_depleted() {
match self.read(&mut buf[total_bytes_read..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
// The following macro invocation needs to be expanded, as `include!`
// doens't support external macros
// header!{
// #[doc="The `X-Upload-Content-Type` header."]
// (XUploadContentType, "X-Upload-Content-Type") => [Mime]
// xupload_content_type {
// test_header!(
// test1,
// vec![b"text/plain"],
// Some(HeaderField(
// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())]
// )));
// }
// }
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len()!= 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> Option<Self> {
None
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Some(RangeResponseHeader(c))
}
}
}
}
None
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<oauth2::Scheme>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
|
peer_addr
|
identifier_name
|
|
cmn.rs
|
calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, serde::json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
|
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() &&!self.is_depleted() {
match self.read(&mut buf[total_bytes_read..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
// The following macro invocation needs to be expanded, as `include!`
// doens't support external macros
// header!{
// #[doc="The `X-Upload-Content-Type` header."]
// (XUploadContentType, "X-Upload-Content-Type") => [Mime]
// xupload_content_type {
// test_header!(
// test1,
// vec![b"text/plain"],
// Some(HeaderField(
// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())]
// )));
// }
// }
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len()!= 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> Option<Self> {
None
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Some(RangeResponseHeader(c))
}
}
}
}
None
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<oauth2::Scheme>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
|
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
|
random_line_split
|
borrowed-tuple.rs
|
// Copyright 2013-2014 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.
// min-lldb-version: 310
|
// gdb-command:run
// gdb-command:print *stack_val_ref
// gdbg-check:$1 = {__0 = -14, __1 = -19}
// gdbr-check:$1 = (-14, -19)
// gdb-command:print *ref_to_unnamed
// gdbg-check:$2 = {__0 = -15, __1 = -20}
// gdbr-check:$2 = (-15, -20)
// gdb-command:print *unique_val_ref
// gdbg-check:$3 = {__0 = -17, __1 = -22}
// gdbr-check:$3 = (-17, -22)
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *stack_val_ref
// lldbg-check:[...]$0 = (-14, -19)
// lldbr-check:((i16, f32)) *stack_val_ref = { = -14 = -19 }
// lldb-command:print *ref_to_unnamed
// lldbg-check:[...]$1 = (-15, -20)
// lldbr-check:((i16, f32)) *ref_to_unnamed = { = -15 = -20 }
// lldb-command:print *unique_val_ref
// lldbg-check:[...]$2 = (-17, -22)
// lldbr-check:((i16, f32)) *unique_val_ref = { = -17 = -22 }
#![allow(unused_variables)]
#![feature(box_syntax)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let stack_val: (i16, f32) = (-14, -19f32);
let stack_val_ref: &(i16, f32) = &stack_val;
let ref_to_unnamed: &(i16, f32) = &(-15, -20f32);
let unique_val: Box<(i16, f32)> = box (-17, -22f32);
let unique_val_ref: &(i16, f32) = &*unique_val;
zzz(); // #break
}
fn zzz() {()}
|
// compile-flags:-g
// === GDB TESTS ===================================================================================
|
random_line_split
|
borrowed-tuple.rs
|
// Copyright 2013-2014 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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *stack_val_ref
// gdbg-check:$1 = {__0 = -14, __1 = -19}
// gdbr-check:$1 = (-14, -19)
// gdb-command:print *ref_to_unnamed
// gdbg-check:$2 = {__0 = -15, __1 = -20}
// gdbr-check:$2 = (-15, -20)
// gdb-command:print *unique_val_ref
// gdbg-check:$3 = {__0 = -17, __1 = -22}
// gdbr-check:$3 = (-17, -22)
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *stack_val_ref
// lldbg-check:[...]$0 = (-14, -19)
// lldbr-check:((i16, f32)) *stack_val_ref = { = -14 = -19 }
// lldb-command:print *ref_to_unnamed
// lldbg-check:[...]$1 = (-15, -20)
// lldbr-check:((i16, f32)) *ref_to_unnamed = { = -15 = -20 }
// lldb-command:print *unique_val_ref
// lldbg-check:[...]$2 = (-17, -22)
// lldbr-check:((i16, f32)) *unique_val_ref = { = -17 = -22 }
#![allow(unused_variables)]
#![feature(box_syntax)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main()
|
fn zzz() {()}
|
{
let stack_val: (i16, f32) = (-14, -19f32);
let stack_val_ref: &(i16, f32) = &stack_val;
let ref_to_unnamed: &(i16, f32) = &(-15, -20f32);
let unique_val: Box<(i16, f32)> = box (-17, -22f32);
let unique_val_ref: &(i16, f32) = &*unique_val;
zzz(); // #break
}
|
identifier_body
|
borrowed-tuple.rs
|
// Copyright 2013-2014 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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *stack_val_ref
// gdbg-check:$1 = {__0 = -14, __1 = -19}
// gdbr-check:$1 = (-14, -19)
// gdb-command:print *ref_to_unnamed
// gdbg-check:$2 = {__0 = -15, __1 = -20}
// gdbr-check:$2 = (-15, -20)
// gdb-command:print *unique_val_ref
// gdbg-check:$3 = {__0 = -17, __1 = -22}
// gdbr-check:$3 = (-17, -22)
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *stack_val_ref
// lldbg-check:[...]$0 = (-14, -19)
// lldbr-check:((i16, f32)) *stack_val_ref = { = -14 = -19 }
// lldb-command:print *ref_to_unnamed
// lldbg-check:[...]$1 = (-15, -20)
// lldbr-check:((i16, f32)) *ref_to_unnamed = { = -15 = -20 }
// lldb-command:print *unique_val_ref
// lldbg-check:[...]$2 = (-17, -22)
// lldbr-check:((i16, f32)) *unique_val_ref = { = -17 = -22 }
#![allow(unused_variables)]
#![feature(box_syntax)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let stack_val: (i16, f32) = (-14, -19f32);
let stack_val_ref: &(i16, f32) = &stack_val;
let ref_to_unnamed: &(i16, f32) = &(-15, -20f32);
let unique_val: Box<(i16, f32)> = box (-17, -22f32);
let unique_val_ref: &(i16, f32) = &*unique_val;
zzz(); // #break
}
fn
|
() {()}
|
zzz
|
identifier_name
|
mod.rs
|
//! Provide helpers for making ioctl system calls
//!
//! Currently supports Linux on all architectures. Other platforms welcome!
//!
//! This library is pretty low-level and messy. `ioctl` is not fun.
//!
//! What is an `ioctl`?
//! ===================
//!
//! The `ioctl` syscall is the grab-bag syscall on POSIX systems. Don't want
//! to add a new syscall? Make it an `ioctl`! `ioctl` refers to both the syscall,
//! and the commands that can be send with it. `ioctl` stands for "IO control",
//! and the commands are always sent to a file descriptor.
//!
//! It is common to see `ioctl`s used for the following purposes:
//!
//! * Provide read/write access to out-of-band data related
//! to a device such as configuration (for instance, setting
//! serial port options)
//! * Provide a mechanism for performing full-duplex data
//! transfers (for instance, xfer on SPI devices).
//! * Provide access to control functions on a device (for example,
//! on Linux you can send commands like pause, resume, and eject
//! to the CDROM device.
//! * Do whatever else the device driver creator thought made most sense.
//!
//! `ioctl`s are synchronous system calls and are similar to read and
//! write calls in that regard.
//!
//! What does this module support?
//! ===============================
//!
//! This library provides the `ioctl!` macro, for binding `ioctl`s.
//! Here's a few examples of how that can work for SPI under Linux
//! from [rust-spidev](https://github.com/posborne/rust-spidev).
//!
//! ```
//! #[macro_use] extern crate nix;
//!
//! #[allow(non_camel_case_types)]
//! pub struct spi_ioc_transfer {
//! pub tx_buf: u64,
//! pub rx_buf: u64,
//! pub len: u32,
//!
//! // optional overrides
//! pub speed_hz: u32,
//! pub delay_usecs: u16,
//! pub bits_per_word: u8,
//! pub cs_change: u8,
//! pub pad: u32,
//! }
//!
//! #[cfg(linux)]
//! mod ioctl {
//! use super::*;
//!
//! const SPI_IOC_MAGIC: u8 = 'k' as u8;
//! const SPI_IOC_NR_TRANSFER: u8 = 0;
//! const SPI_IOC_NR_MODE: u8 = 1;
//! const SPI_IOC_NR_LSB_FIRST: u8 = 2;
//! const SPI_IOC_NR_BITS_PER_WORD: u8 = 3;
|
//! ioctl!(read get_mode_u32 with SPI_IOC_MAGIC, SPI_IOC_NR_MODE; u32);
//! ioctl!(write set_mode_u8 with SPI_IOC_MAGIC, SPI_IOC_NR_MODE; u8);
//! ioctl!(write set_mode_u32 with SPI_IOC_MAGIC, SPI_IOC_NR_MODE32; u32);
//! ioctl!(read get_lsb_first with SPI_IOC_MAGIC, SPI_IOC_NR_LSB_FIRST; u8);
//! ioctl!(write set_lsb_first with SPI_IOC_MAGIC, SPI_IOC_NR_LSB_FIRST; u8);
//! ioctl!(read get_bits_per_word with SPI_IOC_MAGIC, SPI_IOC_NR_BITS_PER_WORD; u8);
//! ioctl!(write set_bits_per_word with SPI_IOC_MAGIC, SPI_IOC_NR_BITS_PER_WORD; u8);
//! ioctl!(read get_max_speed_hz with SPI_IOC_MAGIC, SPI_IOC_NR_MAX_SPEED_HZ; u32);
//! ioctl!(write set_max_speed_hz with SPI_IOC_MAGIC, SPI_IOC_NR_MAX_SPEED_HZ; u32);
//! ioctl!(write spidev_transfer with SPI_IOC_MAGIC, SPI_IOC_NR_TRANSFER; spi_ioc_transfer);
//! ioctl!(write buf spidev_transfer_buf with SPI_IOC_MAGIC, SPI_IOC_NR_TRANSFER; spi_ioc_transfer);
//! }
//!
//! // doctest workaround
//! fn main() {}
//! ```
//!
//! Spidev uses the `_IOC` macros that are encouraged (as far as
//! `ioctl` can be encouraged at all) for newer drivers. Many
//! drivers, however, just use magic numbers with no attached
//! semantics. For those, the `ioctl!(bad...)` variant should be
//! used (the "bad" terminology is from the Linux kernel).
//!
//! How do I get the magic numbers?
//! ===============================
//!
//! For Linux, look at your system's headers. For example, `/usr/include/linxu/input.h` has a lot
//! of lines defining macros which use `_IOR`, `_IOW`, `_IOC`, and `_IORW`. These macros
//! correspond to the `ior!`, `iow!`, `ioc!`, and `iorw!` macros defined in this crate.
//! Additionally, there is the `ioctl!` macro for creating a wrapper around `ioctl` that is
//! somewhat more type-safe.
//!
//! Most `ioctl`s have no or little documentation. You'll need to scrounge through
//! the source to figure out what they do and how they should be used.
//!
#[cfg(any(target_os = "linux", target_os = "android"))]
#[path = "platform/linux.rs"]
#[macro_use]
mod platform;
#[cfg(target_os = "macos")]
#[path = "platform/macos.rs"]
#[macro_use]
mod platform;
#[cfg(target_os = "ios")]
#[path = "platform/ios.rs"]
#[macro_use]
mod platform;
#[cfg(target_os = "freebsd")]
#[path = "platform/freebsd.rs"]
#[macro_use]
mod platform;
#[cfg(target_os = "openbsd")]
#[path = "platform/openbsd.rs"]
#[macro_use]
mod platform;
#[cfg(target_os = "dragonfly")]
#[path = "platform/dragonfly.rs"]
#[macro_use]
mod platform;
pub use self::platform::*;
// liblibc has the wrong decl for linux :| hack until #26809 lands.
extern "C" {
#[doc(hidden)]
pub fn ioctl(fd: libc::c_int, req: libc::c_ulong,...) -> libc::c_int;
}
/// A hack to get the macros to work nicely.
#[doc(hidden)]
pub use ::libc as libc;
|
//! const SPI_IOC_NR_MAX_SPEED_HZ: u8 = 4;
//! const SPI_IOC_NR_MODE32: u8 = 5;
//!
//! ioctl!(read get_mode_u8 with SPI_IOC_MAGIC, SPI_IOC_NR_MODE; u8);
|
random_line_split
|
tararchiver.rs
|
use lzma::LzmaWriter as XzEncoder;
use bzip2::write::BzEncoder;
use flate2::write::GzEncoder;
use tar::Builder;
use std::io::{Write, Result};
use std::path::Path;
use std::convert::AsRef;
use std::fs::File;
use std::marker::PhantomData;
use archiver::FileArchiver;
use tarcompressor::HasTarCompressor;
use tarcompressor::TarCompressor;
pub enum TarCompressionLevel {
None,
Fast,
Best,
Default,
}
struct TarArchiver<W: Write, C: TarCompressor<W>> {
tar_builder: Builder<C>,
phantom: PhantomData<W>,
}
impl<C: TarCompressor<W>, W: Write> TarArchiver<W, C> {
pub fn new(compressor: C) -> Self {
TarArchiver {
tar_builder: Builder::new_with_compressor(compressor),
phantom: PhantomData,
}
}
}
impl<T: TarCompressor<File>> FileArchiver for TarArchiver<File, T> {
fn add_file<P: AsRef<Path>>(&mut self, file_path: P, archive_path: P) -> Result<()> {
let mut f_in = File::open(file_path)?;
self.tar_builder.append_file(archive_path, &mut f_in)?;
Ok(())
}
fn add_directory<P: AsRef<Path>>(&mut self, dir_path: P, archive_dir_path: P) -> Result<()> {
self.tar_builder.append_dir(archive_dir_path, dir_path)?;
Ok(())
}
fn finish(&mut self) -> Result<()> {
self.tar_builder.finish()?;
Ok(())
}
}
macro_rules! make_archiver {
($name:ident, $encoder:ident, #[$doc:meta]) => {
#[$doc]
pub struct $name<W: Write> {
inner: TarArchiver<W, $encoder<W>>,
}
impl FileArchiver for $name<File> {
type CompressionEnum = TarCompressionLevel;
fn create<P: AsRef<Path>>(output_path: P) -> Result<Self> {
Ok(
$name {
inner: TarArchiver::new($encoder::new_with_compression_level(TarCompressionLevel::Default, output_path)?),
}
)
}
fn create_with_compression_level<P: AsRef<Path>>(output_path: P, compression_level: TarCompressionLevel) -> Result<Self> {
Ok(
$name {
inner: TarArchiver::new($encoder::new_with_compression_level(compression_level, output_path)?),
}
)
}
fn add_file<P: AsRef<Path>>(&mut self, file: P, archive_path: P) -> Result<()> {
self.inner.add_file(file, archive_path)?;
Ok(())
|
}
fn add_directory<P: AsRef<Path>>(&mut self, dir_path: P, archive_dir_path: P) -> Result<()> {
self.inner.add_directory(dir_path, archive_dir_path)?;
Ok(())
}
fn finish(&mut self) -> Result<()> {
self.inner.finish()?;
Ok(())
}
}
}
}
make_archiver!(BzArchiver, BzEncoder,
/// Tar archiver using bzip2
);
make_archiver!(GzArchiver, GzEncoder,
/// Tar archiver using gzip
);
make_archiver!(XzArchiver, XzEncoder,
/// Tar archiver using xz (lzma)
);
|
random_line_split
|
|
tararchiver.rs
|
use lzma::LzmaWriter as XzEncoder;
use bzip2::write::BzEncoder;
use flate2::write::GzEncoder;
use tar::Builder;
use std::io::{Write, Result};
use std::path::Path;
use std::convert::AsRef;
use std::fs::File;
use std::marker::PhantomData;
use archiver::FileArchiver;
use tarcompressor::HasTarCompressor;
use tarcompressor::TarCompressor;
pub enum TarCompressionLevel {
None,
Fast,
Best,
Default,
}
struct TarArchiver<W: Write, C: TarCompressor<W>> {
tar_builder: Builder<C>,
phantom: PhantomData<W>,
}
impl<C: TarCompressor<W>, W: Write> TarArchiver<W, C> {
pub fn new(compressor: C) -> Self {
TarArchiver {
tar_builder: Builder::new_with_compressor(compressor),
phantom: PhantomData,
}
}
}
impl<T: TarCompressor<File>> FileArchiver for TarArchiver<File, T> {
fn add_file<P: AsRef<Path>>(&mut self, file_path: P, archive_path: P) -> Result<()> {
let mut f_in = File::open(file_path)?;
self.tar_builder.append_file(archive_path, &mut f_in)?;
Ok(())
}
fn
|
<P: AsRef<Path>>(&mut self, dir_path: P, archive_dir_path: P) -> Result<()> {
self.tar_builder.append_dir(archive_dir_path, dir_path)?;
Ok(())
}
fn finish(&mut self) -> Result<()> {
self.tar_builder.finish()?;
Ok(())
}
}
macro_rules! make_archiver {
($name:ident, $encoder:ident, #[$doc:meta]) => {
#[$doc]
pub struct $name<W: Write> {
inner: TarArchiver<W, $encoder<W>>,
}
impl FileArchiver for $name<File> {
type CompressionEnum = TarCompressionLevel;
fn create<P: AsRef<Path>>(output_path: P) -> Result<Self> {
Ok(
$name {
inner: TarArchiver::new($encoder::new_with_compression_level(TarCompressionLevel::Default, output_path)?),
}
)
}
fn create_with_compression_level<P: AsRef<Path>>(output_path: P, compression_level: TarCompressionLevel) -> Result<Self> {
Ok(
$name {
inner: TarArchiver::new($encoder::new_with_compression_level(compression_level, output_path)?),
}
)
}
fn add_file<P: AsRef<Path>>(&mut self, file: P, archive_path: P) -> Result<()> {
self.inner.add_file(file, archive_path)?;
Ok(())
}
fn add_directory<P: AsRef<Path>>(&mut self, dir_path: P, archive_dir_path: P) -> Result<()> {
self.inner.add_directory(dir_path, archive_dir_path)?;
Ok(())
}
fn finish(&mut self) -> Result<()> {
self.inner.finish()?;
Ok(())
}
}
}
}
make_archiver!(BzArchiver, BzEncoder,
/// Tar archiver using bzip2
);
make_archiver!(GzArchiver, GzEncoder,
/// Tar archiver using gzip
);
make_archiver!(XzArchiver, XzEncoder,
/// Tar archiver using xz (lzma)
);
|
add_directory
|
identifier_name
|
utils.rs
|
// Copyright 2021 Google LLC
//
// 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
//
// https://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 crate::fetcher::Fetcher;
use crate::header_integrity;
use crate::headers::Headers;
use crate::http_cache::HttpCache;
use anyhow::{anyhow, Result};
use std::collections::BTreeSet;
use url::Url;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
pub fn console_log(msg: &str) {
web_sys::console::log_1(&msg.into());
}
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
pub fn console_log(msg: &str) {
println!("{}", msg);
}
pub fn get_sha(bytes: &[u8]) -> Vec<u8>
|
#[cfg(feature = "wasm")]
pub fn to_js_error<E: std::fmt::Debug>(e: E) -> wasm_bindgen::JsValue {
// TODO: The `JsValue::from_str()` constructs a `string` in JavaScript.
// We should switch to `js_sys::Error::new()`
// so that JavaScript's `try catch` can catch an `Error` object.
wasm_bindgen::JsValue::from_str(&format!("{:?}", e))
}
pub async fn signed_headers_and_payload<F: Fetcher, C: HttpCache>(
fallback_url: &Url,
status_code: u16,
payload_headers: &Headers,
payload_body: &[u8],
subresource_fetcher: F,
header_integrity_cache: C,
strip_response_headers: &BTreeSet<String>,
) -> Result<(Vec<u8>, Vec<u8>)> {
if status_code!= 200 {
return Err(anyhow!("The resource status code is {}.", status_code));
}
// 16384 is the max mice record size allowed by SXG spec.
// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#section-3.5-7.9.1
let (mice_digest, payload_body) = crate::mice::calculate(payload_body, 16384);
let mut header_integrity_fetcher = header_integrity::new_fetcher(
subresource_fetcher,
header_integrity_cache,
strip_response_headers,
);
let signed_headers = payload_headers
.get_signed_headers_bytes(
fallback_url,
status_code,
&mice_digest,
&mut header_integrity_fetcher,
)
.await;
Ok((signed_headers, payload_body))
}
#[cfg(test)]
pub mod tests {
use futures::{
future::{BoxFuture, Future},
task::{Context, Poll, Waker},
};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
// Generated with:
// KEY=`mktemp` && CSR=`mktemp` &&
// openssl ecparam -out "$KEY" -name prime256v1 -genkey &&
// openssl req -new -sha256 -key "$KEY" -out "$CSR" -subj '/CN=example.org/O=Test/C=US' &&
// openssl x509 -req -days 90 -in "$CSR" -signkey "$KEY" -out - -extfile <(echo -e "1.3.6.1.4.1.11129.2.1.22 = ASN1:NULL\nsubjectAltName=DNS:example.org") &&
// rm "$KEY" "$CSR"
pub const SELF_SIGNED_CERT_PEM: &str = "
-----BEGIN CERTIFICATE-----
MIIBkTCCATigAwIBAgIUL/D6t/l3OrSRCI0KlCP7zH1U5/swCgYIKoZIzj0EAwIw
MjEUMBIGA1UEAwwLZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYT
AlVTMB4XDTIxMDgyMDAwMTc1MFoXDTIxMTExODAwMTc1MFowMjEUMBIGA1UEAwwL
ZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYTAlVTMFkwEwYHKoZI
zj0CAQYIKoZIzj0DAQcDQgAE3jibTycCk9tifTFg6CyiUirdSlblqLoofEC7B0I4
IO9A52fwDYjZfwGSdu/6ji0MQ1+19Ovr3d9DvXSa7pN1j6MsMCowEAYKKwYBBAHW
eQIBFgQCBQAwFgYDVR0RBA8wDYILZXhhbXBsZS5vcmcwCgYIKoZIzj0EAwIDRwAw
RAIgdTuJ4IXs6LeXQ15TxIsRtfma4F8ypUk0bpBLLbVPbyACIFYul0BjPa2qVd/l
SFfkmh8Fc2QXpbbaK5AQfnQpkDHV
-----END CERTIFICATE-----
";
// Generated from above cert using:
// openssl x509 -in - -outform DER | openssl dgst -sha256 -binary | base64 | tr /+ _- | tr -d =
pub const SELF_SIGNED_CERT_SHA256: &str = "Lz2EMcys4NR9FP0yYnuS5Uw8xM3gbVAOM2lwSBU9qX0";
// Returns a future for the given state object. If multiple futures are created from the same
// shared state, the first to be polled resolves after the second.
pub fn out_of_order<'a, T: 'a, F: 'a + Fn() -> T + Send>(
state: Arc<Mutex<OutOfOrderState>>,
value: F,
) -> BoxFuture<'a, T> {
Box::pin(OutOfOrderFuture { value, state })
}
pub struct OutOfOrderState {
first: bool,
waker: Option<Waker>,
}
impl OutOfOrderState {
pub fn new() -> Arc<Mutex<Self>> {
Arc::new(Mutex::new(OutOfOrderState {
first: true,
waker: None,
}))
}
}
struct OutOfOrderFuture<T, F: Fn() -> T> {
value: F,
state: Arc<Mutex<OutOfOrderState>>,
}
impl<T, F: Fn() -> T> Future for OutOfOrderFuture<T, F> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = &mut *self.state.lock().unwrap();
let first = state.first;
state.first = false;
println!("first = {}", first);
if first {
state.waker = Some(cx.waker().clone());
Poll::Pending
} else {
if let Some(waker) = &state.waker {
println!("waking!");
waker.wake_by_ref();
}
Poll::Ready((self.value)())
}
}
}
}
|
{
use ::sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
hasher.finalize().to_vec()
}
|
identifier_body
|
utils.rs
|
// Copyright 2021 Google LLC
//
// 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
//
// https://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 crate::fetcher::Fetcher;
use crate::header_integrity;
use crate::headers::Headers;
use crate::http_cache::HttpCache;
use anyhow::{anyhow, Result};
use std::collections::BTreeSet;
use url::Url;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
pub fn console_log(msg: &str) {
web_sys::console::log_1(&msg.into());
}
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
pub fn console_log(msg: &str) {
println!("{}", msg);
}
pub fn get_sha(bytes: &[u8]) -> Vec<u8> {
use ::sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
hasher.finalize().to_vec()
}
#[cfg(feature = "wasm")]
pub fn to_js_error<E: std::fmt::Debug>(e: E) -> wasm_bindgen::JsValue {
// TODO: The `JsValue::from_str()` constructs a `string` in JavaScript.
// We should switch to `js_sys::Error::new()`
// so that JavaScript's `try catch` can catch an `Error` object.
wasm_bindgen::JsValue::from_str(&format!("{:?}", e))
}
pub async fn signed_headers_and_payload<F: Fetcher, C: HttpCache>(
fallback_url: &Url,
status_code: u16,
payload_headers: &Headers,
payload_body: &[u8],
subresource_fetcher: F,
header_integrity_cache: C,
strip_response_headers: &BTreeSet<String>,
) -> Result<(Vec<u8>, Vec<u8>)> {
if status_code!= 200 {
return Err(anyhow!("The resource status code is {}.", status_code));
}
// 16384 is the max mice record size allowed by SXG spec.
// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#section-3.5-7.9.1
let (mice_digest, payload_body) = crate::mice::calculate(payload_body, 16384);
let mut header_integrity_fetcher = header_integrity::new_fetcher(
subresource_fetcher,
header_integrity_cache,
strip_response_headers,
);
let signed_headers = payload_headers
.get_signed_headers_bytes(
fallback_url,
status_code,
&mice_digest,
&mut header_integrity_fetcher,
)
.await;
Ok((signed_headers, payload_body))
}
#[cfg(test)]
pub mod tests {
use futures::{
future::{BoxFuture, Future},
task::{Context, Poll, Waker},
};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
// Generated with:
// KEY=`mktemp` && CSR=`mktemp` &&
// openssl ecparam -out "$KEY" -name prime256v1 -genkey &&
// openssl req -new -sha256 -key "$KEY" -out "$CSR" -subj '/CN=example.org/O=Test/C=US' &&
// openssl x509 -req -days 90 -in "$CSR" -signkey "$KEY" -out - -extfile <(echo -e "1.3.6.1.4.1.11129.2.1.22 = ASN1:NULL\nsubjectAltName=DNS:example.org") &&
// rm "$KEY" "$CSR"
pub const SELF_SIGNED_CERT_PEM: &str = "
-----BEGIN CERTIFICATE-----
MIIBkTCCATigAwIBAgIUL/D6t/l3OrSRCI0KlCP7zH1U5/swCgYIKoZIzj0EAwIw
MjEUMBIGA1UEAwwLZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYT
AlVTMB4XDTIxMDgyMDAwMTc1MFoXDTIxMTExODAwMTc1MFowMjEUMBIGA1UEAwwL
ZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYTAlVTMFkwEwYHKoZI
zj0CAQYIKoZIzj0DAQcDQgAE3jibTycCk9tifTFg6CyiUirdSlblqLoofEC7B0I4
IO9A52fwDYjZfwGSdu/6ji0MQ1+19Ovr3d9DvXSa7pN1j6MsMCowEAYKKwYBBAHW
eQIBFgQCBQAwFgYDVR0RBA8wDYILZXhhbXBsZS5vcmcwCgYIKoZIzj0EAwIDRwAw
RAIgdTuJ4IXs6LeXQ15TxIsRtfma4F8ypUk0bpBLLbVPbyACIFYul0BjPa2qVd/l
SFfkmh8Fc2QXpbbaK5AQfnQpkDHV
-----END CERTIFICATE-----
";
// Generated from above cert using:
// openssl x509 -in - -outform DER | openssl dgst -sha256 -binary | base64 | tr /+ _- | tr -d =
pub const SELF_SIGNED_CERT_SHA256: &str = "Lz2EMcys4NR9FP0yYnuS5Uw8xM3gbVAOM2lwSBU9qX0";
// Returns a future for the given state object. If multiple futures are created from the same
// shared state, the first to be polled resolves after the second.
pub fn out_of_order<'a, T: 'a, F: 'a + Fn() -> T + Send>(
state: Arc<Mutex<OutOfOrderState>>,
value: F,
) -> BoxFuture<'a, T> {
Box::pin(OutOfOrderFuture { value, state })
}
pub struct
|
{
first: bool,
waker: Option<Waker>,
}
impl OutOfOrderState {
pub fn new() -> Arc<Mutex<Self>> {
Arc::new(Mutex::new(OutOfOrderState {
first: true,
waker: None,
}))
}
}
struct OutOfOrderFuture<T, F: Fn() -> T> {
value: F,
state: Arc<Mutex<OutOfOrderState>>,
}
impl<T, F: Fn() -> T> Future for OutOfOrderFuture<T, F> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = &mut *self.state.lock().unwrap();
let first = state.first;
state.first = false;
println!("first = {}", first);
if first {
state.waker = Some(cx.waker().clone());
Poll::Pending
} else {
if let Some(waker) = &state.waker {
println!("waking!");
waker.wake_by_ref();
}
Poll::Ready((self.value)())
}
}
}
}
|
OutOfOrderState
|
identifier_name
|
utils.rs
|
// Copyright 2021 Google LLC
//
// 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
//
// https://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 crate::fetcher::Fetcher;
use crate::header_integrity;
use crate::headers::Headers;
use crate::http_cache::HttpCache;
use anyhow::{anyhow, Result};
use std::collections::BTreeSet;
use url::Url;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
pub fn console_log(msg: &str) {
web_sys::console::log_1(&msg.into());
}
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
pub fn console_log(msg: &str) {
println!("{}", msg);
}
pub fn get_sha(bytes: &[u8]) -> Vec<u8> {
use ::sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
hasher.finalize().to_vec()
}
#[cfg(feature = "wasm")]
pub fn to_js_error<E: std::fmt::Debug>(e: E) -> wasm_bindgen::JsValue {
// TODO: The `JsValue::from_str()` constructs a `string` in JavaScript.
// We should switch to `js_sys::Error::new()`
// so that JavaScript's `try catch` can catch an `Error` object.
wasm_bindgen::JsValue::from_str(&format!("{:?}", e))
}
pub async fn signed_headers_and_payload<F: Fetcher, C: HttpCache>(
fallback_url: &Url,
status_code: u16,
payload_headers: &Headers,
payload_body: &[u8],
subresource_fetcher: F,
header_integrity_cache: C,
strip_response_headers: &BTreeSet<String>,
) -> Result<(Vec<u8>, Vec<u8>)> {
if status_code!= 200 {
return Err(anyhow!("The resource status code is {}.", status_code));
}
// 16384 is the max mice record size allowed by SXG spec.
// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#section-3.5-7.9.1
let (mice_digest, payload_body) = crate::mice::calculate(payload_body, 16384);
let mut header_integrity_fetcher = header_integrity::new_fetcher(
subresource_fetcher,
header_integrity_cache,
strip_response_headers,
);
let signed_headers = payload_headers
.get_signed_headers_bytes(
fallback_url,
status_code,
&mice_digest,
&mut header_integrity_fetcher,
)
.await;
Ok((signed_headers, payload_body))
}
#[cfg(test)]
pub mod tests {
use futures::{
future::{BoxFuture, Future},
task::{Context, Poll, Waker},
};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
|
// Generated with:
// KEY=`mktemp` && CSR=`mktemp` &&
// openssl ecparam -out "$KEY" -name prime256v1 -genkey &&
// openssl req -new -sha256 -key "$KEY" -out "$CSR" -subj '/CN=example.org/O=Test/C=US' &&
// openssl x509 -req -days 90 -in "$CSR" -signkey "$KEY" -out - -extfile <(echo -e "1.3.6.1.4.1.11129.2.1.22 = ASN1:NULL\nsubjectAltName=DNS:example.org") &&
// rm "$KEY" "$CSR"
pub const SELF_SIGNED_CERT_PEM: &str = "
-----BEGIN CERTIFICATE-----
MIIBkTCCATigAwIBAgIUL/D6t/l3OrSRCI0KlCP7zH1U5/swCgYIKoZIzj0EAwIw
MjEUMBIGA1UEAwwLZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYT
AlVTMB4XDTIxMDgyMDAwMTc1MFoXDTIxMTExODAwMTc1MFowMjEUMBIGA1UEAwwL
ZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYTAlVTMFkwEwYHKoZI
zj0CAQYIKoZIzj0DAQcDQgAE3jibTycCk9tifTFg6CyiUirdSlblqLoofEC7B0I4
IO9A52fwDYjZfwGSdu/6ji0MQ1+19Ovr3d9DvXSa7pN1j6MsMCowEAYKKwYBBAHW
eQIBFgQCBQAwFgYDVR0RBA8wDYILZXhhbXBsZS5vcmcwCgYIKoZIzj0EAwIDRwAw
RAIgdTuJ4IXs6LeXQ15TxIsRtfma4F8ypUk0bpBLLbVPbyACIFYul0BjPa2qVd/l
SFfkmh8Fc2QXpbbaK5AQfnQpkDHV
-----END CERTIFICATE-----
";
// Generated from above cert using:
// openssl x509 -in - -outform DER | openssl dgst -sha256 -binary | base64 | tr /+ _- | tr -d =
pub const SELF_SIGNED_CERT_SHA256: &str = "Lz2EMcys4NR9FP0yYnuS5Uw8xM3gbVAOM2lwSBU9qX0";
// Returns a future for the given state object. If multiple futures are created from the same
// shared state, the first to be polled resolves after the second.
pub fn out_of_order<'a, T: 'a, F: 'a + Fn() -> T + Send>(
state: Arc<Mutex<OutOfOrderState>>,
value: F,
) -> BoxFuture<'a, T> {
Box::pin(OutOfOrderFuture { value, state })
}
pub struct OutOfOrderState {
first: bool,
waker: Option<Waker>,
}
impl OutOfOrderState {
pub fn new() -> Arc<Mutex<Self>> {
Arc::new(Mutex::new(OutOfOrderState {
first: true,
waker: None,
}))
}
}
struct OutOfOrderFuture<T, F: Fn() -> T> {
value: F,
state: Arc<Mutex<OutOfOrderState>>,
}
impl<T, F: Fn() -> T> Future for OutOfOrderFuture<T, F> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = &mut *self.state.lock().unwrap();
let first = state.first;
state.first = false;
println!("first = {}", first);
if first {
state.waker = Some(cx.waker().clone());
Poll::Pending
} else {
if let Some(waker) = &state.waker {
println!("waking!");
waker.wake_by_ref();
}
Poll::Ready((self.value)())
}
}
}
}
|
random_line_split
|
|
utils.rs
|
// Copyright 2021 Google LLC
//
// 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
//
// https://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 crate::fetcher::Fetcher;
use crate::header_integrity;
use crate::headers::Headers;
use crate::http_cache::HttpCache;
use anyhow::{anyhow, Result};
use std::collections::BTreeSet;
use url::Url;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
pub fn console_log(msg: &str) {
web_sys::console::log_1(&msg.into());
}
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
pub fn console_log(msg: &str) {
println!("{}", msg);
}
pub fn get_sha(bytes: &[u8]) -> Vec<u8> {
use ::sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
hasher.finalize().to_vec()
}
#[cfg(feature = "wasm")]
pub fn to_js_error<E: std::fmt::Debug>(e: E) -> wasm_bindgen::JsValue {
// TODO: The `JsValue::from_str()` constructs a `string` in JavaScript.
// We should switch to `js_sys::Error::new()`
// so that JavaScript's `try catch` can catch an `Error` object.
wasm_bindgen::JsValue::from_str(&format!("{:?}", e))
}
pub async fn signed_headers_and_payload<F: Fetcher, C: HttpCache>(
fallback_url: &Url,
status_code: u16,
payload_headers: &Headers,
payload_body: &[u8],
subresource_fetcher: F,
header_integrity_cache: C,
strip_response_headers: &BTreeSet<String>,
) -> Result<(Vec<u8>, Vec<u8>)> {
if status_code!= 200 {
return Err(anyhow!("The resource status code is {}.", status_code));
}
// 16384 is the max mice record size allowed by SXG spec.
// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#section-3.5-7.9.1
let (mice_digest, payload_body) = crate::mice::calculate(payload_body, 16384);
let mut header_integrity_fetcher = header_integrity::new_fetcher(
subresource_fetcher,
header_integrity_cache,
strip_response_headers,
);
let signed_headers = payload_headers
.get_signed_headers_bytes(
fallback_url,
status_code,
&mice_digest,
&mut header_integrity_fetcher,
)
.await;
Ok((signed_headers, payload_body))
}
#[cfg(test)]
pub mod tests {
use futures::{
future::{BoxFuture, Future},
task::{Context, Poll, Waker},
};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
// Generated with:
// KEY=`mktemp` && CSR=`mktemp` &&
// openssl ecparam -out "$KEY" -name prime256v1 -genkey &&
// openssl req -new -sha256 -key "$KEY" -out "$CSR" -subj '/CN=example.org/O=Test/C=US' &&
// openssl x509 -req -days 90 -in "$CSR" -signkey "$KEY" -out - -extfile <(echo -e "1.3.6.1.4.1.11129.2.1.22 = ASN1:NULL\nsubjectAltName=DNS:example.org") &&
// rm "$KEY" "$CSR"
pub const SELF_SIGNED_CERT_PEM: &str = "
-----BEGIN CERTIFICATE-----
MIIBkTCCATigAwIBAgIUL/D6t/l3OrSRCI0KlCP7zH1U5/swCgYIKoZIzj0EAwIw
MjEUMBIGA1UEAwwLZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYT
AlVTMB4XDTIxMDgyMDAwMTc1MFoXDTIxMTExODAwMTc1MFowMjEUMBIGA1UEAwwL
ZXhhbXBsZS5vcmcxDTALBgNVBAoMBFRlc3QxCzAJBgNVBAYTAlVTMFkwEwYHKoZI
zj0CAQYIKoZIzj0DAQcDQgAE3jibTycCk9tifTFg6CyiUirdSlblqLoofEC7B0I4
IO9A52fwDYjZfwGSdu/6ji0MQ1+19Ovr3d9DvXSa7pN1j6MsMCowEAYKKwYBBAHW
eQIBFgQCBQAwFgYDVR0RBA8wDYILZXhhbXBsZS5vcmcwCgYIKoZIzj0EAwIDRwAw
RAIgdTuJ4IXs6LeXQ15TxIsRtfma4F8ypUk0bpBLLbVPbyACIFYul0BjPa2qVd/l
SFfkmh8Fc2QXpbbaK5AQfnQpkDHV
-----END CERTIFICATE-----
";
// Generated from above cert using:
// openssl x509 -in - -outform DER | openssl dgst -sha256 -binary | base64 | tr /+ _- | tr -d =
pub const SELF_SIGNED_CERT_SHA256: &str = "Lz2EMcys4NR9FP0yYnuS5Uw8xM3gbVAOM2lwSBU9qX0";
// Returns a future for the given state object. If multiple futures are created from the same
// shared state, the first to be polled resolves after the second.
pub fn out_of_order<'a, T: 'a, F: 'a + Fn() -> T + Send>(
state: Arc<Mutex<OutOfOrderState>>,
value: F,
) -> BoxFuture<'a, T> {
Box::pin(OutOfOrderFuture { value, state })
}
pub struct OutOfOrderState {
first: bool,
waker: Option<Waker>,
}
impl OutOfOrderState {
pub fn new() -> Arc<Mutex<Self>> {
Arc::new(Mutex::new(OutOfOrderState {
first: true,
waker: None,
}))
}
}
struct OutOfOrderFuture<T, F: Fn() -> T> {
value: F,
state: Arc<Mutex<OutOfOrderState>>,
}
impl<T, F: Fn() -> T> Future for OutOfOrderFuture<T, F> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = &mut *self.state.lock().unwrap();
let first = state.first;
state.first = false;
println!("first = {}", first);
if first
|
else {
if let Some(waker) = &state.waker {
println!("waking!");
waker.wake_by_ref();
}
Poll::Ready((self.value)())
}
}
}
}
|
{
state.waker = Some(cx.waker().clone());
Poll::Pending
}
|
conditional_block
|
main.rs
|
extern crate clap;
extern crate serde_json;
extern crate jmespath;
use std::rc::Rc;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::process::exit;
use clap::{Arg, App};
use jmespath::Rcvar;
use jmespath::{Variable, compile};
macro_rules! die(
($msg:expr) => (
match writeln!(&mut ::std::io::stderr(), "{}", $msg) {
Ok(_) => exit(1),
Err(x) => panic!("Unable to write to stderr: {}", x),
}
)
);
fn main() {
let matches = App::new("jp")
.version("0.0.1")
.about("JMESPath command line interface")
.arg(Arg::with_name("filename")
.help("Read input JSON from a file instead of stdin.")
.short("f")
.takes_value(true)
.long("filename"))
.arg(Arg::with_name("unquoted")
.help("If the final result is a string, it will be printed without quotes.")
.short("u")
.long("unquoted")
.multiple(false))
.arg(Arg::with_name("ast")
.help("Only print the AST of the parsed expression. Do not rely on this output, \
only useful for debugging purposes.")
.long("ast")
.multiple(false))
.arg(Arg::with_name("expr-file")
.help("Read JMESPath expression from the specified file.")
.short("e")
.takes_value(true)
.long("expr-file")
.conflicts_with("expression")
.required(true))
.arg(Arg::with_name("expression")
.help("JMESPath expression to evaluate")
.index(1)
.conflicts_with("expr-file")
.required(true))
.get_matches();
let file_expression = matches.value_of("expr-file")
.map(|f| read_file("expression", f));
let expr = if let Some(ref e) = file_expression {
compile(e)
} else {
compile(matches.value_of("expression").unwrap())
}
.map_err(|e| die!(e.to_string()))
.unwrap();
if matches.is_present("ast") {
println!("{:#?}", expr.as_ast());
exit(0);
}
let json = Rc::new(get_json(matches.value_of("filename")));
match expr.search(&json) {
Err(e) => die!(e.to_string()),
Ok(result) => show_result(result, matches.is_present("unquoted")),
}
}
fn
|
(result: Rcvar, unquoted: bool) {
if unquoted && result.is_string() {
println!("{}", result.as_string().unwrap());
} else {
let mut out = io::stdout();
serde_json::to_writer_pretty(&mut out, &result)
.map(|_| out.write(&['\n' as u8]))
.map_err(|e| die!(format!("Error converting result to string: {}", e)))
.ok();
}
}
fn read_file(label: &str, filename: &str) -> String {
match File::open(filename) {
Err(e) => die!(format!("Error opening {} file at {}: {}", label, filename, e)),
Ok(mut file) => {
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.map_err(|e| die!(format!("Error reading {} from {}: {}", label, filename, e)))
.map(|_| buffer)
.unwrap()
}
}
}
fn get_json(filename: Option<&str>) -> Variable {
let buffer = match filename {
Some(f) => read_file("JSON", f),
None => {
let mut buffer = String::new();
match io::stdin().read_to_string(&mut buffer) {
Ok(_) => buffer,
Err(e) => die!(format!("Error reading JSON from stdin: {}", e)),
}
}
};
Variable::from_json(&buffer)
.map_err(|e| die!(format!("Error parsing JSON: {}", e)))
.unwrap()
}
|
show_result
|
identifier_name
|
main.rs
|
extern crate clap;
extern crate serde_json;
extern crate jmespath;
use std::rc::Rc;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::process::exit;
use clap::{Arg, App};
use jmespath::Rcvar;
use jmespath::{Variable, compile};
macro_rules! die(
($msg:expr) => (
match writeln!(&mut ::std::io::stderr(), "{}", $msg) {
Ok(_) => exit(1),
Err(x) => panic!("Unable to write to stderr: {}", x),
}
)
);
fn main() {
let matches = App::new("jp")
.version("0.0.1")
.about("JMESPath command line interface")
.arg(Arg::with_name("filename")
.help("Read input JSON from a file instead of stdin.")
.short("f")
.takes_value(true)
.long("filename"))
.arg(Arg::with_name("unquoted")
.help("If the final result is a string, it will be printed without quotes.")
.short("u")
.long("unquoted")
.multiple(false))
.arg(Arg::with_name("ast")
.help("Only print the AST of the parsed expression. Do not rely on this output, \
only useful for debugging purposes.")
.long("ast")
.multiple(false))
.arg(Arg::with_name("expr-file")
.help("Read JMESPath expression from the specified file.")
.short("e")
.takes_value(true)
.long("expr-file")
.conflicts_with("expression")
.required(true))
.arg(Arg::with_name("expression")
.help("JMESPath expression to evaluate")
.index(1)
.conflicts_with("expr-file")
.required(true))
.get_matches();
let file_expression = matches.value_of("expr-file")
.map(|f| read_file("expression", f));
let expr = if let Some(ref e) = file_expression {
compile(e)
} else {
compile(matches.value_of("expression").unwrap())
}
.map_err(|e| die!(e.to_string()))
.unwrap();
if matches.is_present("ast") {
println!("{:#?}", expr.as_ast());
exit(0);
}
let json = Rc::new(get_json(matches.value_of("filename")));
match expr.search(&json) {
Err(e) => die!(e.to_string()),
Ok(result) => show_result(result, matches.is_present("unquoted")),
}
}
fn show_result(result: Rcvar, unquoted: bool) {
if unquoted && result.is_string() {
println!("{}", result.as_string().unwrap());
} else {
let mut out = io::stdout();
serde_json::to_writer_pretty(&mut out, &result)
.map(|_| out.write(&['\n' as u8]))
.map_err(|e| die!(format!("Error converting result to string: {}", e)))
.ok();
}
}
fn read_file(label: &str, filename: &str) -> String {
match File::open(filename) {
Err(e) => die!(format!("Error opening {} file at {}: {}", label, filename, e)),
Ok(mut file) => {
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.map_err(|e| die!(format!("Error reading {} from {}: {}", label, filename, e)))
.map(|_| buffer)
.unwrap()
}
}
}
fn get_json(filename: Option<&str>) -> Variable {
let buffer = match filename {
|
Some(f) => read_file("JSON", f),
None => {
let mut buffer = String::new();
match io::stdin().read_to_string(&mut buffer) {
Ok(_) => buffer,
Err(e) => die!(format!("Error reading JSON from stdin: {}", e)),
}
}
};
Variable::from_json(&buffer)
.map_err(|e| die!(format!("Error parsing JSON: {}", e)))
.unwrap()
}
|
random_line_split
|
|
main.rs
|
extern crate clap;
extern crate serde_json;
extern crate jmespath;
use std::rc::Rc;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::process::exit;
use clap::{Arg, App};
use jmespath::Rcvar;
use jmespath::{Variable, compile};
macro_rules! die(
($msg:expr) => (
match writeln!(&mut ::std::io::stderr(), "{}", $msg) {
Ok(_) => exit(1),
Err(x) => panic!("Unable to write to stderr: {}", x),
}
)
);
fn main() {
let matches = App::new("jp")
.version("0.0.1")
.about("JMESPath command line interface")
.arg(Arg::with_name("filename")
.help("Read input JSON from a file instead of stdin.")
.short("f")
.takes_value(true)
.long("filename"))
.arg(Arg::with_name("unquoted")
.help("If the final result is a string, it will be printed without quotes.")
.short("u")
.long("unquoted")
.multiple(false))
.arg(Arg::with_name("ast")
.help("Only print the AST of the parsed expression. Do not rely on this output, \
only useful for debugging purposes.")
.long("ast")
.multiple(false))
.arg(Arg::with_name("expr-file")
.help("Read JMESPath expression from the specified file.")
.short("e")
.takes_value(true)
.long("expr-file")
.conflicts_with("expression")
.required(true))
.arg(Arg::with_name("expression")
.help("JMESPath expression to evaluate")
.index(1)
.conflicts_with("expr-file")
.required(true))
.get_matches();
let file_expression = matches.value_of("expr-file")
.map(|f| read_file("expression", f));
let expr = if let Some(ref e) = file_expression {
compile(e)
} else {
compile(matches.value_of("expression").unwrap())
}
.map_err(|e| die!(e.to_string()))
.unwrap();
if matches.is_present("ast") {
println!("{:#?}", expr.as_ast());
exit(0);
}
let json = Rc::new(get_json(matches.value_of("filename")));
match expr.search(&json) {
Err(e) => die!(e.to_string()),
Ok(result) => show_result(result, matches.is_present("unquoted")),
}
}
fn show_result(result: Rcvar, unquoted: bool) {
if unquoted && result.is_string() {
println!("{}", result.as_string().unwrap());
} else {
let mut out = io::stdout();
serde_json::to_writer_pretty(&mut out, &result)
.map(|_| out.write(&['\n' as u8]))
.map_err(|e| die!(format!("Error converting result to string: {}", e)))
.ok();
}
}
fn read_file(label: &str, filename: &str) -> String
|
fn get_json(filename: Option<&str>) -> Variable {
let buffer = match filename {
Some(f) => read_file("JSON", f),
None => {
let mut buffer = String::new();
match io::stdin().read_to_string(&mut buffer) {
Ok(_) => buffer,
Err(e) => die!(format!("Error reading JSON from stdin: {}", e)),
}
}
};
Variable::from_json(&buffer)
.map_err(|e| die!(format!("Error parsing JSON: {}", e)))
.unwrap()
}
|
{
match File::open(filename) {
Err(e) => die!(format!("Error opening {} file at {}: {}", label, filename, e)),
Ok(mut file) => {
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.map_err(|e| die!(format!("Error reading {} from {}: {}", label, filename, e)))
.map(|_| buffer)
.unwrap()
}
}
}
|
identifier_body
|
main.rs
|
extern crate rand;
use std::fmt::{self, Display};
const NUMBER_OF_DIGITS: usize = 4;
/// generates a random `NUMBER_OF_DIGITS`
fn generate_digits() -> Vec<u32> {
use rand;
let mut rng = rand::thread_rng();
rand::sample(&mut rng, (1u32..10), 4)
}
/// types of errors we can have when parsing a malformed guess
enum
|
{
NotValidDigit,
ExpectedNumberOfDigits(usize),
NoDuplicates,
}
/// printable description for each `ParseError`
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseError::NotValidDigit => Display::fmt("only digits from 1 to 9, please", f),
ParseError::ExpectedNumberOfDigits(exp) => {
write!(f, "you need to guess with {} digits", exp)
}
ParseError::NoDuplicates => Display::fmt("no duplicates, please", f),
}
}
}
/// a well-formed guess string should be like "1543", with `NUMBER_OF_DIGITS` digits, no
/// repetitions, no separators or other characters. Parse the guess string as a `Vec<usize>` or
/// return a `ParseError`. This could trivially return a `[usize; NUMBER_OF_DIGITS]` instead of a
/// `Vec<usize>` and avoid dynamic allocations. However, in the more general case,
/// `NUMBER_OF_DIGITS` would not be a constant, but a runtime configuration (which would make using
/// a stack-allocated array more difficult)
fn parse_guess_string(guess: &str) -> Result<Vec<u32>, ParseError> {
let mut ret = Vec::with_capacity(NUMBER_OF_DIGITS);
for (i, c) in guess.char_indices() {
// check that our guess contains the right number of digits
if i >= NUMBER_OF_DIGITS {
return Err(ParseError::ExpectedNumberOfDigits(NUMBER_OF_DIGITS));
}
match c.to_digit(10) {
Some(d) if d > 0 => {
// the guess should not contain duplicate digits
if ret.contains(&d) {
return Err(ParseError::NoDuplicates);
}
ret.push(d);
}
_ => return Err(ParseError::NotValidDigit),
}
}
Ok(ret)
}
/// returns a tuple with the count of Bulls and Cows in the guess
fn calculate_score(given_digits: &[u32], guessed_digits: &[u32]) -> (usize, usize) {
let mut bulls = 0;
let mut cows = 0;
for (i, given_digit) in given_digits.iter().enumerate().take(NUMBER_OF_DIGITS) {
let pos = guessed_digits.iter()
.position(|&a| a == *given_digit);
match pos {
None => (),
Some(p) if p == i => bulls += 1,
Some(_) => cows += 1,
}
}
(bulls, cows)
}
fn main() {
let reader = std::io::stdin();
loop {
let given_digits = generate_digits();
println!("I have chosen my {} digits. Please guess what they are",
NUMBER_OF_DIGITS);
loop {
let mut guess_string = String::new();
let _ = reader.read_line(&mut guess_string).unwrap();
let digits_maybe = parse_guess_string(guess_string.trim());
match digits_maybe {
Err(msg) => {
println!("{}", msg);
}
Ok(guess_digits) => {
match calculate_score(&given_digits, &guess_digits) {
(NUMBER_OF_DIGITS, _) => {
println!("you win!");
break;
}
(bulls, cows) => println!("bulls: {}, cows: {}", bulls, cows),
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::ParseError;
/// test we generate `NUMBER_OF_DIGITS` unique digits between 1 and 9
#[test]
fn generate_digits() {
let mut digits = super::generate_digits();
assert!(digits.iter().all(|&d| d > 0u32));
digits.sort();
digits.dedup();
assert_eq!(digits.len(), super::NUMBER_OF_DIGITS)
}
#[test]
fn parse_guess_string() {
match super::parse_guess_string("1234") {
Ok(p) => assert_eq!(p, vec![1, 2, 3, 4]),
_ => panic!("Failed parsing a valid string"),
}
match super::parse_guess_string("0123") {
Ok(_) => panic!("parsed a string containing a 0"),
Err(err) => {
if let ParseError::NotValidDigit = err {
()
} else {
panic!("Expected a NotValidDigit error")
}
}
}
match super::parse_guess_string("1213") {
Ok(_) => panic!("parsed a string containing a repeated digit"),
Err(err) => {
if let ParseError::NoDuplicates = err {
()
} else {
panic!("Expected a NoDuplicates error")
}
}
}
match super::parse_guess_string("12354") {
Ok(_) => panic!("parsed a string longer than 4 digits"),
Err(err) => {
if let ParseError::ExpectedNumberOfDigits(4) = err {
()
} else {
panic!("Expected a ExpectedNumberOfDigits error")
}
}
}
}
#[test]
fn calculate_score() {
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[1, 2, 3, 4]), (4, 0));
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[1, 2, 4, 3]), (2, 2));
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[5, 6, 7, 8]), (0, 0));
}
}
|
ParseError
|
identifier_name
|
main.rs
|
extern crate rand;
use std::fmt::{self, Display};
const NUMBER_OF_DIGITS: usize = 4;
/// generates a random `NUMBER_OF_DIGITS`
fn generate_digits() -> Vec<u32> {
use rand;
let mut rng = rand::thread_rng();
rand::sample(&mut rng, (1u32..10), 4)
}
/// types of errors we can have when parsing a malformed guess
enum ParseError {
NotValidDigit,
ExpectedNumberOfDigits(usize),
NoDuplicates,
}
/// printable description for each `ParseError`
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseError::NotValidDigit => Display::fmt("only digits from 1 to 9, please", f),
ParseError::ExpectedNumberOfDigits(exp) => {
write!(f, "you need to guess with {} digits", exp)
}
ParseError::NoDuplicates => Display::fmt("no duplicates, please", f),
}
}
}
/// a well-formed guess string should be like "1543", with `NUMBER_OF_DIGITS` digits, no
/// repetitions, no separators or other characters. Parse the guess string as a `Vec<usize>` or
/// return a `ParseError`. This could trivially return a `[usize; NUMBER_OF_DIGITS]` instead of a
/// `Vec<usize>` and avoid dynamic allocations. However, in the more general case,
/// `NUMBER_OF_DIGITS` would not be a constant, but a runtime configuration (which would make using
/// a stack-allocated array more difficult)
fn parse_guess_string(guess: &str) -> Result<Vec<u32>, ParseError> {
let mut ret = Vec::with_capacity(NUMBER_OF_DIGITS);
for (i, c) in guess.char_indices() {
// check that our guess contains the right number of digits
if i >= NUMBER_OF_DIGITS {
return Err(ParseError::ExpectedNumberOfDigits(NUMBER_OF_DIGITS));
}
match c.to_digit(10) {
Some(d) if d > 0 => {
// the guess should not contain duplicate digits
if ret.contains(&d) {
return Err(ParseError::NoDuplicates);
}
ret.push(d);
}
_ => return Err(ParseError::NotValidDigit),
}
}
Ok(ret)
}
/// returns a tuple with the count of Bulls and Cows in the guess
fn calculate_score(given_digits: &[u32], guessed_digits: &[u32]) -> (usize, usize) {
let mut bulls = 0;
let mut cows = 0;
for (i, given_digit) in given_digits.iter().enumerate().take(NUMBER_OF_DIGITS) {
let pos = guessed_digits.iter()
.position(|&a| a == *given_digit);
match pos {
None => (),
Some(p) if p == i => bulls += 1,
Some(_) => cows += 1,
}
}
(bulls, cows)
}
fn main()
|
(bulls, cows) => println!("bulls: {}, cows: {}", bulls, cows),
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::ParseError;
/// test we generate `NUMBER_OF_DIGITS` unique digits between 1 and 9
#[test]
fn generate_digits() {
let mut digits = super::generate_digits();
assert!(digits.iter().all(|&d| d > 0u32));
digits.sort();
digits.dedup();
assert_eq!(digits.len(), super::NUMBER_OF_DIGITS)
}
#[test]
fn parse_guess_string() {
match super::parse_guess_string("1234") {
Ok(p) => assert_eq!(p, vec![1, 2, 3, 4]),
_ => panic!("Failed parsing a valid string"),
}
match super::parse_guess_string("0123") {
Ok(_) => panic!("parsed a string containing a 0"),
Err(err) => {
if let ParseError::NotValidDigit = err {
()
} else {
panic!("Expected a NotValidDigit error")
}
}
}
match super::parse_guess_string("1213") {
Ok(_) => panic!("parsed a string containing a repeated digit"),
Err(err) => {
if let ParseError::NoDuplicates = err {
()
} else {
panic!("Expected a NoDuplicates error")
}
}
}
match super::parse_guess_string("12354") {
Ok(_) => panic!("parsed a string longer than 4 digits"),
Err(err) => {
if let ParseError::ExpectedNumberOfDigits(4) = err {
()
} else {
panic!("Expected a ExpectedNumberOfDigits error")
}
}
}
}
#[test]
fn calculate_score() {
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[1, 2, 3, 4]), (4, 0));
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[1, 2, 4, 3]), (2, 2));
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[5, 6, 7, 8]), (0, 0));
}
}
|
{
let reader = std::io::stdin();
loop {
let given_digits = generate_digits();
println!("I have chosen my {} digits. Please guess what they are",
NUMBER_OF_DIGITS);
loop {
let mut guess_string = String::new();
let _ = reader.read_line(&mut guess_string).unwrap();
let digits_maybe = parse_guess_string(guess_string.trim());
match digits_maybe {
Err(msg) => {
println!("{}", msg);
}
Ok(guess_digits) => {
match calculate_score(&given_digits, &guess_digits) {
(NUMBER_OF_DIGITS, _) => {
println!("you win!");
break;
}
|
identifier_body
|
main.rs
|
extern crate rand;
|
const NUMBER_OF_DIGITS: usize = 4;
/// generates a random `NUMBER_OF_DIGITS`
fn generate_digits() -> Vec<u32> {
use rand;
let mut rng = rand::thread_rng();
rand::sample(&mut rng, (1u32..10), 4)
}
/// types of errors we can have when parsing a malformed guess
enum ParseError {
NotValidDigit,
ExpectedNumberOfDigits(usize),
NoDuplicates,
}
/// printable description for each `ParseError`
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseError::NotValidDigit => Display::fmt("only digits from 1 to 9, please", f),
ParseError::ExpectedNumberOfDigits(exp) => {
write!(f, "you need to guess with {} digits", exp)
}
ParseError::NoDuplicates => Display::fmt("no duplicates, please", f),
}
}
}
/// a well-formed guess string should be like "1543", with `NUMBER_OF_DIGITS` digits, no
/// repetitions, no separators or other characters. Parse the guess string as a `Vec<usize>` or
/// return a `ParseError`. This could trivially return a `[usize; NUMBER_OF_DIGITS]` instead of a
/// `Vec<usize>` and avoid dynamic allocations. However, in the more general case,
/// `NUMBER_OF_DIGITS` would not be a constant, but a runtime configuration (which would make using
/// a stack-allocated array more difficult)
fn parse_guess_string(guess: &str) -> Result<Vec<u32>, ParseError> {
let mut ret = Vec::with_capacity(NUMBER_OF_DIGITS);
for (i, c) in guess.char_indices() {
// check that our guess contains the right number of digits
if i >= NUMBER_OF_DIGITS {
return Err(ParseError::ExpectedNumberOfDigits(NUMBER_OF_DIGITS));
}
match c.to_digit(10) {
Some(d) if d > 0 => {
// the guess should not contain duplicate digits
if ret.contains(&d) {
return Err(ParseError::NoDuplicates);
}
ret.push(d);
}
_ => return Err(ParseError::NotValidDigit),
}
}
Ok(ret)
}
/// returns a tuple with the count of Bulls and Cows in the guess
fn calculate_score(given_digits: &[u32], guessed_digits: &[u32]) -> (usize, usize) {
let mut bulls = 0;
let mut cows = 0;
for (i, given_digit) in given_digits.iter().enumerate().take(NUMBER_OF_DIGITS) {
let pos = guessed_digits.iter()
.position(|&a| a == *given_digit);
match pos {
None => (),
Some(p) if p == i => bulls += 1,
Some(_) => cows += 1,
}
}
(bulls, cows)
}
fn main() {
let reader = std::io::stdin();
loop {
let given_digits = generate_digits();
println!("I have chosen my {} digits. Please guess what they are",
NUMBER_OF_DIGITS);
loop {
let mut guess_string = String::new();
let _ = reader.read_line(&mut guess_string).unwrap();
let digits_maybe = parse_guess_string(guess_string.trim());
match digits_maybe {
Err(msg) => {
println!("{}", msg);
}
Ok(guess_digits) => {
match calculate_score(&given_digits, &guess_digits) {
(NUMBER_OF_DIGITS, _) => {
println!("you win!");
break;
}
(bulls, cows) => println!("bulls: {}, cows: {}", bulls, cows),
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::ParseError;
/// test we generate `NUMBER_OF_DIGITS` unique digits between 1 and 9
#[test]
fn generate_digits() {
let mut digits = super::generate_digits();
assert!(digits.iter().all(|&d| d > 0u32));
digits.sort();
digits.dedup();
assert_eq!(digits.len(), super::NUMBER_OF_DIGITS)
}
#[test]
fn parse_guess_string() {
match super::parse_guess_string("1234") {
Ok(p) => assert_eq!(p, vec![1, 2, 3, 4]),
_ => panic!("Failed parsing a valid string"),
}
match super::parse_guess_string("0123") {
Ok(_) => panic!("parsed a string containing a 0"),
Err(err) => {
if let ParseError::NotValidDigit = err {
()
} else {
panic!("Expected a NotValidDigit error")
}
}
}
match super::parse_guess_string("1213") {
Ok(_) => panic!("parsed a string containing a repeated digit"),
Err(err) => {
if let ParseError::NoDuplicates = err {
()
} else {
panic!("Expected a NoDuplicates error")
}
}
}
match super::parse_guess_string("12354") {
Ok(_) => panic!("parsed a string longer than 4 digits"),
Err(err) => {
if let ParseError::ExpectedNumberOfDigits(4) = err {
()
} else {
panic!("Expected a ExpectedNumberOfDigits error")
}
}
}
}
#[test]
fn calculate_score() {
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[1, 2, 3, 4]), (4, 0));
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[1, 2, 4, 3]), (2, 2));
assert_eq!(super::calculate_score(&[1, 2, 3, 4], &[5, 6, 7, 8]), (0, 0));
}
}
|
use std::fmt::{self, Display};
|
random_line_split
|
run.rs
|
use std::collections::HashMap;
use std::vec::IntoIter;
use std::iter::Iterator;
use transit::StopTime;
#[derive(Debug, PartialEq)]
pub struct Run<'a> {
pub trip: String,
// TODO: StopTime is very verbose
// redundant info removed from StopTime (trip id, sequence) (maybe make a trait?)
pub sequence: Vec<&'a StopTime>,
}
pub struct RunIterator<'a> {
runs: IntoIter<Run<'a>>,
}
impl<'a> RunIterator<'a> {
// TODO: return value isn't generic forcing users to specify types, very ugly
/// Creates a RunIterator from an Iterator of StopTimes
///
/// The StopTimes Iterator will be consumed so that they can be grouped and sorted
pub fn new<U: Iterator<Item = &'a StopTime>>(stop_times: U) -> RunIterator<'a> {
let mut run_groups = HashMap::<String, Run>::new();
// group StopTimes by trip
for stop_time in stop_times {
let run = run_groups.entry(stop_time.trip_id.clone()).or_insert(Run {
trip: stop_time.trip_id.clone(),
sequence: vec![],
});
run.sequence.push(stop_time);
}
// sort StopTimes within each Run
for run in run_groups.values_mut() {
run.sequence
.sort_by(|a, b| a.stop_sequence.cmp(&b.stop_sequence));
}
let runs = run_groups.drain().map(|e| e.1).collect::<Vec<Run>>();
RunIterator {
runs: runs.into_iter(),
}
}
// TODO: Write a version that trusts that the stop_times iterator is already sorted
// And panics if it does not (keep a list of completed trip_ids)
}
impl<'a> Iterator for RunIterator<'a> {
type Item = Run<'a>;
fn next(&mut self) -> Option<Run<'a>> {
self.runs.next()
}
}
#[cfg(test)]
mod test {
use super::*;
use transit::{StopServiceType, TimeOffset, Timepoint};
#[test]
fn test_form_runs_from_unsorted_sequences() {
let times = vec![
stop_time("A", 3, None, None),
stop_time("A", 2, None, None),
stop_time("B", 1, None, None),
stop_time("B", 2, None, None),
stop_time("A", 1, None, None),
stop_time("B", 3, None, None),
];
let runs = RunIterator::new(times.iter());
let mut result = runs.collect::<Vec<Run>>();
result.sort_by(|a, b| a.sequence[0].trip_id.cmp(&b.sequence[0].trip_id));
let expected = vec![
Run {
trip: String::from("A"),
sequence: vec![×[4], ×[1], ×[0]],
},
Run {
trip: String::from("B"),
sequence: vec![×[2], ×[3], ×[5]],
},
];
assert_eq!(expected, result);
}
fn stop_time(
trip: &str,
sequence: u64,
arrival: Option<[u32; 3]>,
departure: Option<[u32; 3]>,
) -> StopTime {
return StopTime {
trip_id: String::from(trip),
departure_time: match departure {
None => TimeOffset::from_hms(0, 0, 0),
Some(hms) => TimeOffset::from_hms(hms[0], hms[1], hms[2]),
},
arrival_time: match arrival {
None => TimeOffset::from_hms(0, 0, 0),
Some(hms) => TimeOffset::from_hms(hms[0], hms[1], hms[2]),
|
pickup_type: StopServiceType::RegularlyScheduled,
dropoff_type: StopServiceType::RegularlyScheduled,
timepoint: Timepoint::Exact,
shape_dist_traveled: None,
};
}
}
|
},
stop_id: format!("{}.{}", trip, sequence),
stop_sequence: sequence,
stop_headsign: None,
|
random_line_split
|
run.rs
|
use std::collections::HashMap;
use std::vec::IntoIter;
use std::iter::Iterator;
use transit::StopTime;
#[derive(Debug, PartialEq)]
pub struct Run<'a> {
pub trip: String,
// TODO: StopTime is very verbose
// redundant info removed from StopTime (trip id, sequence) (maybe make a trait?)
pub sequence: Vec<&'a StopTime>,
}
pub struct RunIterator<'a> {
runs: IntoIter<Run<'a>>,
}
impl<'a> RunIterator<'a> {
// TODO: return value isn't generic forcing users to specify types, very ugly
/// Creates a RunIterator from an Iterator of StopTimes
///
/// The StopTimes Iterator will be consumed so that they can be grouped and sorted
pub fn new<U: Iterator<Item = &'a StopTime>>(stop_times: U) -> RunIterator<'a> {
let mut run_groups = HashMap::<String, Run>::new();
// group StopTimes by trip
for stop_time in stop_times {
let run = run_groups.entry(stop_time.trip_id.clone()).or_insert(Run {
trip: stop_time.trip_id.clone(),
sequence: vec![],
});
run.sequence.push(stop_time);
}
// sort StopTimes within each Run
for run in run_groups.values_mut() {
run.sequence
.sort_by(|a, b| a.stop_sequence.cmp(&b.stop_sequence));
}
let runs = run_groups.drain().map(|e| e.1).collect::<Vec<Run>>();
RunIterator {
runs: runs.into_iter(),
}
}
// TODO: Write a version that trusts that the stop_times iterator is already sorted
// And panics if it does not (keep a list of completed trip_ids)
}
impl<'a> Iterator for RunIterator<'a> {
type Item = Run<'a>;
fn next(&mut self) -> Option<Run<'a>>
|
}
#[cfg(test)]
mod test {
use super::*;
use transit::{StopServiceType, TimeOffset, Timepoint};
#[test]
fn test_form_runs_from_unsorted_sequences() {
let times = vec![
stop_time("A", 3, None, None),
stop_time("A", 2, None, None),
stop_time("B", 1, None, None),
stop_time("B", 2, None, None),
stop_time("A", 1, None, None),
stop_time("B", 3, None, None),
];
let runs = RunIterator::new(times.iter());
let mut result = runs.collect::<Vec<Run>>();
result.sort_by(|a, b| a.sequence[0].trip_id.cmp(&b.sequence[0].trip_id));
let expected = vec![
Run {
trip: String::from("A"),
sequence: vec![×[4], ×[1], ×[0]],
},
Run {
trip: String::from("B"),
sequence: vec![×[2], ×[3], ×[5]],
},
];
assert_eq!(expected, result);
}
fn stop_time(
trip: &str,
sequence: u64,
arrival: Option<[u32; 3]>,
departure: Option<[u32; 3]>,
) -> StopTime {
return StopTime {
trip_id: String::from(trip),
departure_time: match departure {
None => TimeOffset::from_hms(0, 0, 0),
Some(hms) => TimeOffset::from_hms(hms[0], hms[1], hms[2]),
},
arrival_time: match arrival {
None => TimeOffset::from_hms(0, 0, 0),
Some(hms) => TimeOffset::from_hms(hms[0], hms[1], hms[2]),
},
stop_id: format!("{}.{}", trip, sequence),
stop_sequence: sequence,
stop_headsign: None,
pickup_type: StopServiceType::RegularlyScheduled,
dropoff_type: StopServiceType::RegularlyScheduled,
timepoint: Timepoint::Exact,
shape_dist_traveled: None,
};
}
}
|
{
self.runs.next()
}
|
identifier_body
|
run.rs
|
use std::collections::HashMap;
use std::vec::IntoIter;
use std::iter::Iterator;
use transit::StopTime;
#[derive(Debug, PartialEq)]
pub struct Run<'a> {
pub trip: String,
// TODO: StopTime is very verbose
// redundant info removed from StopTime (trip id, sequence) (maybe make a trait?)
pub sequence: Vec<&'a StopTime>,
}
pub struct RunIterator<'a> {
runs: IntoIter<Run<'a>>,
}
impl<'a> RunIterator<'a> {
// TODO: return value isn't generic forcing users to specify types, very ugly
/// Creates a RunIterator from an Iterator of StopTimes
///
/// The StopTimes Iterator will be consumed so that they can be grouped and sorted
pub fn
|
<U: Iterator<Item = &'a StopTime>>(stop_times: U) -> RunIterator<'a> {
let mut run_groups = HashMap::<String, Run>::new();
// group StopTimes by trip
for stop_time in stop_times {
let run = run_groups.entry(stop_time.trip_id.clone()).or_insert(Run {
trip: stop_time.trip_id.clone(),
sequence: vec![],
});
run.sequence.push(stop_time);
}
// sort StopTimes within each Run
for run in run_groups.values_mut() {
run.sequence
.sort_by(|a, b| a.stop_sequence.cmp(&b.stop_sequence));
}
let runs = run_groups.drain().map(|e| e.1).collect::<Vec<Run>>();
RunIterator {
runs: runs.into_iter(),
}
}
// TODO: Write a version that trusts that the stop_times iterator is already sorted
// And panics if it does not (keep a list of completed trip_ids)
}
impl<'a> Iterator for RunIterator<'a> {
type Item = Run<'a>;
fn next(&mut self) -> Option<Run<'a>> {
self.runs.next()
}
}
#[cfg(test)]
mod test {
use super::*;
use transit::{StopServiceType, TimeOffset, Timepoint};
#[test]
fn test_form_runs_from_unsorted_sequences() {
let times = vec![
stop_time("A", 3, None, None),
stop_time("A", 2, None, None),
stop_time("B", 1, None, None),
stop_time("B", 2, None, None),
stop_time("A", 1, None, None),
stop_time("B", 3, None, None),
];
let runs = RunIterator::new(times.iter());
let mut result = runs.collect::<Vec<Run>>();
result.sort_by(|a, b| a.sequence[0].trip_id.cmp(&b.sequence[0].trip_id));
let expected = vec![
Run {
trip: String::from("A"),
sequence: vec![×[4], ×[1], ×[0]],
},
Run {
trip: String::from("B"),
sequence: vec![×[2], ×[3], ×[5]],
},
];
assert_eq!(expected, result);
}
fn stop_time(
trip: &str,
sequence: u64,
arrival: Option<[u32; 3]>,
departure: Option<[u32; 3]>,
) -> StopTime {
return StopTime {
trip_id: String::from(trip),
departure_time: match departure {
None => TimeOffset::from_hms(0, 0, 0),
Some(hms) => TimeOffset::from_hms(hms[0], hms[1], hms[2]),
},
arrival_time: match arrival {
None => TimeOffset::from_hms(0, 0, 0),
Some(hms) => TimeOffset::from_hms(hms[0], hms[1], hms[2]),
},
stop_id: format!("{}.{}", trip, sequence),
stop_sequence: sequence,
stop_headsign: None,
pickup_type: StopServiceType::RegularlyScheduled,
dropoff_type: StopServiceType::RegularlyScheduled,
timepoint: Timepoint::Exact,
shape_dist_traveled: None,
};
}
}
|
new
|
identifier_name
|
array.rs
|
extern crate libc;
use self::libc::c_void;
use self::libc::memcpy;
use containers::{Ref, Vector};
use memory::Page;
use std::mem::{align_of, size_of};
use std::ops::{Deref, DerefMut, Index};
use std::ptr::{null_mut, write};
#[derive(Copy, Clone)]
pub struct Array<T: Copy> {
vector: Vector<T>,
length: usize,
}
impl<T: Copy> Array<T> {
pub fn new() -> Array<T> {
Array {
vector: Vector {
data: null_mut(),
length: 0,
},
length: 0,
}
}
pub fn get_buffer(&self) -> *const T {
self.vector.data
}
pub fn get_length(&self) -> usize {
self.length
}
pub fn get_capacity(&self) -> usize {
self.vector.length
}
pub fn add(&mut self, item: T) {
if self.length == self.vector.length {
self.reallocate();
}
unsafe {
let location = self.vector.data.offset(self.length as isize);
write(location, item);
}
self.length += 1;
}
pub fn reallocate(&mut self) {
let _own_page = Page::own(Ref::from(self as *mut Array<T>));
let size = size_of::<T>();
unsafe {
if self.vector.length == 0 {
let exclusive_page = (*_own_page).allocate_exclusive_page();
let capacity = (*exclusive_page).get_capacity::<T>();
self.vector.length = capacity / size;
self.vector.data = (*exclusive_page)
.allocate_raw(self.vector.length * size, align_of::<T>())
as *mut T;
} else
|
}
}
}
impl<T: Copy> Index<usize> for Array<T> {
type Output = T;
fn index(&self, offset: usize) -> &Self::Output {
unsafe { &*self.vector.data.offset(offset as isize) }
}
}
impl<T: Copy> Deref for Array<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe { ::std::slice::from_raw_parts(self.vector.data, self.length) }
}
}
impl<T: Copy> DerefMut for Array<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe { ::std::slice::from_raw_parts_mut(self.vector.data, self.length) }
}
}
|
{
let old_length = self.vector.length;
self.vector.length *= 2;
let old_data = self.vector.data;
self.vector.data =
(*_own_page).allocate_raw(self.vector.length * size, align_of::<T>()) as *mut T;
memcpy(
self.vector.data as *mut c_void,
old_data as *mut c_void,
old_length * size,
);
let old_exclusive_page = Page::get(old_data as usize);
(*old_exclusive_page).forget();
}
|
conditional_block
|
array.rs
|
extern crate libc;
use self::libc::c_void;
use self::libc::memcpy;
use containers::{Ref, Vector};
use memory::Page;
use std::mem::{align_of, size_of};
use std::ops::{Deref, DerefMut, Index};
use std::ptr::{null_mut, write};
#[derive(Copy, Clone)]
pub struct Array<T: Copy> {
vector: Vector<T>,
length: usize,
}
impl<T: Copy> Array<T> {
pub fn new() -> Array<T> {
Array {
vector: Vector {
data: null_mut(),
length: 0,
},
length: 0,
}
}
pub fn get_buffer(&self) -> *const T {
self.vector.data
}
pub fn get_length(&self) -> usize {
self.length
}
pub fn get_capacity(&self) -> usize {
self.vector.length
}
pub fn add(&mut self, item: T) {
if self.length == self.vector.length {
self.reallocate();
}
unsafe {
let location = self.vector.data.offset(self.length as isize);
write(location, item);
}
self.length += 1;
}
pub fn reallocate(&mut self) {
let _own_page = Page::own(Ref::from(self as *mut Array<T>));
let size = size_of::<T>();
unsafe {
if self.vector.length == 0 {
let exclusive_page = (*_own_page).allocate_exclusive_page();
let capacity = (*exclusive_page).get_capacity::<T>();
|
as *mut T;
} else {
let old_length = self.vector.length;
self.vector.length *= 2;
let old_data = self.vector.data;
self.vector.data =
(*_own_page).allocate_raw(self.vector.length * size, align_of::<T>()) as *mut T;
memcpy(
self.vector.data as *mut c_void,
old_data as *mut c_void,
old_length * size,
);
let old_exclusive_page = Page::get(old_data as usize);
(*old_exclusive_page).forget();
}
}
}
}
impl<T: Copy> Index<usize> for Array<T> {
type Output = T;
fn index(&self, offset: usize) -> &Self::Output {
unsafe { &*self.vector.data.offset(offset as isize) }
}
}
impl<T: Copy> Deref for Array<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe { ::std::slice::from_raw_parts(self.vector.data, self.length) }
}
}
impl<T: Copy> DerefMut for Array<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe { ::std::slice::from_raw_parts_mut(self.vector.data, self.length) }
}
}
|
self.vector.length = capacity / size;
self.vector.data = (*exclusive_page)
.allocate_raw(self.vector.length * size, align_of::<T>())
|
random_line_split
|
array.rs
|
extern crate libc;
use self::libc::c_void;
use self::libc::memcpy;
use containers::{Ref, Vector};
use memory::Page;
use std::mem::{align_of, size_of};
use std::ops::{Deref, DerefMut, Index};
use std::ptr::{null_mut, write};
#[derive(Copy, Clone)]
pub struct Array<T: Copy> {
vector: Vector<T>,
length: usize,
}
impl<T: Copy> Array<T> {
pub fn new() -> Array<T> {
Array {
vector: Vector {
data: null_mut(),
length: 0,
},
length: 0,
}
}
pub fn get_buffer(&self) -> *const T {
self.vector.data
}
pub fn get_length(&self) -> usize {
self.length
}
pub fn get_capacity(&self) -> usize {
self.vector.length
}
pub fn add(&mut self, item: T) {
if self.length == self.vector.length {
self.reallocate();
}
unsafe {
let location = self.vector.data.offset(self.length as isize);
write(location, item);
}
self.length += 1;
}
pub fn reallocate(&mut self)
|
old_length * size,
);
let old_exclusive_page = Page::get(old_data as usize);
(*old_exclusive_page).forget();
}
}
}
}
impl<T: Copy> Index<usize> for Array<T> {
type Output = T;
fn index(&self, offset: usize) -> &Self::Output {
unsafe { &*self.vector.data.offset(offset as isize) }
}
}
impl<T: Copy> Deref for Array<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe { ::std::slice::from_raw_parts(self.vector.data, self.length) }
}
}
impl<T: Copy> DerefMut for Array<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe { ::std::slice::from_raw_parts_mut(self.vector.data, self.length) }
}
}
|
{
let _own_page = Page::own(Ref::from(self as *mut Array<T>));
let size = size_of::<T>();
unsafe {
if self.vector.length == 0 {
let exclusive_page = (*_own_page).allocate_exclusive_page();
let capacity = (*exclusive_page).get_capacity::<T>();
self.vector.length = capacity / size;
self.vector.data = (*exclusive_page)
.allocate_raw(self.vector.length * size, align_of::<T>())
as *mut T;
} else {
let old_length = self.vector.length;
self.vector.length *= 2;
let old_data = self.vector.data;
self.vector.data =
(*_own_page).allocate_raw(self.vector.length * size, align_of::<T>()) as *mut T;
memcpy(
self.vector.data as *mut c_void,
old_data as *mut c_void,
|
identifier_body
|
array.rs
|
extern crate libc;
use self::libc::c_void;
use self::libc::memcpy;
use containers::{Ref, Vector};
use memory::Page;
use std::mem::{align_of, size_of};
use std::ops::{Deref, DerefMut, Index};
use std::ptr::{null_mut, write};
#[derive(Copy, Clone)]
pub struct Array<T: Copy> {
vector: Vector<T>,
length: usize,
}
impl<T: Copy> Array<T> {
pub fn new() -> Array<T> {
Array {
vector: Vector {
data: null_mut(),
length: 0,
},
length: 0,
}
}
pub fn
|
(&self) -> *const T {
self.vector.data
}
pub fn get_length(&self) -> usize {
self.length
}
pub fn get_capacity(&self) -> usize {
self.vector.length
}
pub fn add(&mut self, item: T) {
if self.length == self.vector.length {
self.reallocate();
}
unsafe {
let location = self.vector.data.offset(self.length as isize);
write(location, item);
}
self.length += 1;
}
pub fn reallocate(&mut self) {
let _own_page = Page::own(Ref::from(self as *mut Array<T>));
let size = size_of::<T>();
unsafe {
if self.vector.length == 0 {
let exclusive_page = (*_own_page).allocate_exclusive_page();
let capacity = (*exclusive_page).get_capacity::<T>();
self.vector.length = capacity / size;
self.vector.data = (*exclusive_page)
.allocate_raw(self.vector.length * size, align_of::<T>())
as *mut T;
} else {
let old_length = self.vector.length;
self.vector.length *= 2;
let old_data = self.vector.data;
self.vector.data =
(*_own_page).allocate_raw(self.vector.length * size, align_of::<T>()) as *mut T;
memcpy(
self.vector.data as *mut c_void,
old_data as *mut c_void,
old_length * size,
);
let old_exclusive_page = Page::get(old_data as usize);
(*old_exclusive_page).forget();
}
}
}
}
impl<T: Copy> Index<usize> for Array<T> {
type Output = T;
fn index(&self, offset: usize) -> &Self::Output {
unsafe { &*self.vector.data.offset(offset as isize) }
}
}
impl<T: Copy> Deref for Array<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe { ::std::slice::from_raw_parts(self.vector.data, self.length) }
}
}
impl<T: Copy> DerefMut for Array<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe { ::std::slice::from_raw_parts_mut(self.vector.data, self.length) }
}
}
|
get_buffer
|
identifier_name
|
rs_trigger.rs
|
#![allow(dead_code)]
extern crate rs_logic;
mod simple_logic;
use rs_logic::element::*;
use simple_logic::{init_or, init_not};
// X OR-NOT Y = NOT (X OR Y)
fn init_or_not() -> Element {
let mut or_not = Element::init("OR-NOT", 2, 1);
let or = or_not.push_element(init_or());
let not = or_not.push_element(init_not());
or_not.connect_wire(Wire::InputSelf(0), Wire::Input(or, 0));
or_not.connect_wire(Wire::InputSelf(1), Wire::Input(or, 1));
or_not.connect_wire(Wire::Output(or, 0), Wire::Input(not, 0));
or_not.connect_wire(Wire::Output(not, 0), Wire::OutputSelf(0));
or_not
}
fn init_rs_trigger() -> Element {
let mut rs = Element::init("RS", 2, 2);
rs.set_initial_data(vec![0, 0], vec![0, 1]);
let o1 = rs.push_element(init_or_not());
let o2 = rs.push_element(init_or_not());
// RS
|
rs.connect_wire(Wire::Output(o1, 0), Wire::Input(o2, 0));
rs.connect_wire(Wire::Output(o2, 0), Wire::Input(o1, 1));
// Q and NOT Q
rs.connect_wire(Wire::Output(o1, 0), Wire::OutputSelf(0));
rs.connect_wire(Wire::Output(o2, 0), Wire::OutputSelf(1));
rs
}
fn main() {
// RS initial output is (0, 0)
let mut rs = init_rs_trigger();
let input_data = vec![(1, 0), (1, 1), (0, 1)];
let output_data = vec![(0, 1), (0, 0), (1, 0)];
println!("RS trigger\n R S Q nQ | Q nQ");
// R S Q nQ
for (&(v1, v2), (r1, r2)) in input_data.iter().zip(output_data) {
let state = (rs.get_output_wire(0), rs.get_output_wire(1));
rs.set_input(vec![v1, v2]);
rs.execute();
let r = rs.get_output();
println!("{:?} --> {:?} {:?}", &[v1, v2], state, r);
}
}
|
rs.connect_wire(Wire::InputSelf(0), Wire::Input(o1, 0));
rs.connect_wire(Wire::InputSelf(1), Wire::Input(o2, 1));
// feedback
|
random_line_split
|
rs_trigger.rs
|
#![allow(dead_code)]
extern crate rs_logic;
mod simple_logic;
use rs_logic::element::*;
use simple_logic::{init_or, init_not};
// X OR-NOT Y = NOT (X OR Y)
fn init_or_not() -> Element {
let mut or_not = Element::init("OR-NOT", 2, 1);
let or = or_not.push_element(init_or());
let not = or_not.push_element(init_not());
or_not.connect_wire(Wire::InputSelf(0), Wire::Input(or, 0));
or_not.connect_wire(Wire::InputSelf(1), Wire::Input(or, 1));
or_not.connect_wire(Wire::Output(or, 0), Wire::Input(not, 0));
or_not.connect_wire(Wire::Output(not, 0), Wire::OutputSelf(0));
or_not
}
fn init_rs_trigger() -> Element {
let mut rs = Element::init("RS", 2, 2);
rs.set_initial_data(vec![0, 0], vec![0, 1]);
let o1 = rs.push_element(init_or_not());
let o2 = rs.push_element(init_or_not());
// RS
rs.connect_wire(Wire::InputSelf(0), Wire::Input(o1, 0));
rs.connect_wire(Wire::InputSelf(1), Wire::Input(o2, 1));
// feedback
rs.connect_wire(Wire::Output(o1, 0), Wire::Input(o2, 0));
rs.connect_wire(Wire::Output(o2, 0), Wire::Input(o1, 1));
// Q and NOT Q
rs.connect_wire(Wire::Output(o1, 0), Wire::OutputSelf(0));
rs.connect_wire(Wire::Output(o2, 0), Wire::OutputSelf(1));
rs
}
fn main()
|
{
// RS initial output is (0, 0)
let mut rs = init_rs_trigger();
let input_data = vec![(1, 0), (1, 1), (0, 1)];
let output_data = vec![(0, 1), (0, 0), (1, 0)];
println!("RS trigger\n R S Q nQ | Q nQ");
// R S Q nQ
for (&(v1, v2), (r1, r2)) in input_data.iter().zip(output_data) {
let state = (rs.get_output_wire(0), rs.get_output_wire(1));
rs.set_input(vec![v1, v2]);
rs.execute();
let r = rs.get_output();
println!("{:?} --> {:?} {:?}", &[v1, v2], state, r);
}
}
|
identifier_body
|
|
rs_trigger.rs
|
#![allow(dead_code)]
extern crate rs_logic;
mod simple_logic;
use rs_logic::element::*;
use simple_logic::{init_or, init_not};
// X OR-NOT Y = NOT (X OR Y)
fn init_or_not() -> Element {
let mut or_not = Element::init("OR-NOT", 2, 1);
let or = or_not.push_element(init_or());
let not = or_not.push_element(init_not());
or_not.connect_wire(Wire::InputSelf(0), Wire::Input(or, 0));
or_not.connect_wire(Wire::InputSelf(1), Wire::Input(or, 1));
or_not.connect_wire(Wire::Output(or, 0), Wire::Input(not, 0));
or_not.connect_wire(Wire::Output(not, 0), Wire::OutputSelf(0));
or_not
}
fn init_rs_trigger() -> Element {
let mut rs = Element::init("RS", 2, 2);
rs.set_initial_data(vec![0, 0], vec![0, 1]);
let o1 = rs.push_element(init_or_not());
let o2 = rs.push_element(init_or_not());
// RS
rs.connect_wire(Wire::InputSelf(0), Wire::Input(o1, 0));
rs.connect_wire(Wire::InputSelf(1), Wire::Input(o2, 1));
// feedback
rs.connect_wire(Wire::Output(o1, 0), Wire::Input(o2, 0));
rs.connect_wire(Wire::Output(o2, 0), Wire::Input(o1, 1));
// Q and NOT Q
rs.connect_wire(Wire::Output(o1, 0), Wire::OutputSelf(0));
rs.connect_wire(Wire::Output(o2, 0), Wire::OutputSelf(1));
rs
}
fn
|
() {
// RS initial output is (0, 0)
let mut rs = init_rs_trigger();
let input_data = vec![(1, 0), (1, 1), (0, 1)];
let output_data = vec![(0, 1), (0, 0), (1, 0)];
println!("RS trigger\n R S Q nQ | Q nQ");
// R S Q nQ
for (&(v1, v2), (r1, r2)) in input_data.iter().zip(output_data) {
let state = (rs.get_output_wire(0), rs.get_output_wire(1));
rs.set_input(vec![v1, v2]);
rs.execute();
let r = rs.get_output();
println!("{:?} --> {:?} {:?}", &[v1, v2], state, r);
}
}
|
main
|
identifier_name
|
uint_macros.rs
|
// Copyright 2012-2014 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.
#![experimental]
#![macro_escape]
#![doc(hidden)]
#![allow(unsigned_negate)]
macro_rules! uint_module (($T:ty) => (
// String conversion functions and impl str -> num
/// Parse a byte slice as a number in the given base
///
/// Yields an `Option` because `buf` may or may not actually be parseable.
///
/// # Examples
///
/// ```
/// let num = std::uint::parse_bytes([49,50,51,52,53,54,55,56,57], 10);
/// assert!(num == Some(123456789));
/// ```
#[inline]
#[experimental = "might need to return Result"]
pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> {
strconv::from_str_bytes_common(buf, radix, false, false, false,
strconv::ExpNone, false, false)
|
#[experimental = "might need to return Result"]
impl FromStr for $T {
#[inline]
fn from_str(s: &str) -> Option<$T> {
strconv::from_str_common(s, 10u, false, false, false,
strconv::ExpNone, false, false)
}
}
#[experimental = "might need to return Result"]
impl FromStrRadix for $T {
#[inline]
fn from_str_radix(s: &str, radix: uint) -> Option<$T> {
strconv::from_str_common(s, radix, false, false, false,
strconv::ExpNone, false, false)
}
}
// String conversion functions and impl num -> str
/// Convert to a string as a byte slice in a given base.
///
/// Use in place of x.to_string() when you do not need to store the string permanently
///
/// # Examples
///
/// ```
/// #![allow(deprecated)]
///
/// std::uint::to_str_bytes(123, 10, |v| {
/// assert!(v == "123".as_bytes());
/// });
/// ```
#[inline]
#[deprecated = "just use.to_string(), or a BufWriter with write! if you mustn't allocate"]
pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
use io::{Writer, Seek};
// The radix can be as low as 2, so we need at least 64 characters for a
// base 2 number, and then we need another for a possible '-' character.
let mut buf = [0u8,..65];
let amt = {
let mut wr = ::io::BufWriter::new(buf);
(write!(&mut wr, "{}", ::fmt::radix(n, radix as u8))).unwrap();
wr.tell().unwrap() as uint
};
f(buf.slice(0, amt))
}
#[deprecated = "use fmt::radix"]
impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
fn to_str_radix(&self, radix: uint) -> String {
format!("{}", ::fmt::radix(*self, radix as u8))
}
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
use num::ToStrRadix;
use str::StrSlice;
use u16;
#[test]
pub fn test_to_string() {
assert_eq!((0 as $T).to_str_radix(10u), "0".to_string());
assert_eq!((1 as $T).to_str_radix(10u), "1".to_string());
assert_eq!((2 as $T).to_str_radix(10u), "2".to_string());
assert_eq!((11 as $T).to_str_radix(10u), "11".to_string());
assert_eq!((11 as $T).to_str_radix(16u), "b".to_string());
assert_eq!((255 as $T).to_str_radix(16u), "ff".to_string());
assert_eq!((0xff as $T).to_str_radix(10u), "255".to_string());
}
#[test]
pub fn test_from_str() {
assert_eq!(from_str::<$T>("0"), Some(0u as $T));
assert_eq!(from_str::<$T>("3"), Some(3u as $T));
assert_eq!(from_str::<$T>("10"), Some(10u as $T));
assert_eq!(from_str::<u32>("123456789"), Some(123456789 as u32));
assert_eq!(from_str::<$T>("00100"), Some(100u as $T));
assert!(from_str::<$T>("").is_none());
assert!(from_str::<$T>(" ").is_none());
assert!(from_str::<$T>("x").is_none());
}
#[test]
pub fn test_parse_bytes() {
use str::StrSlice;
assert_eq!(parse_bytes("123".as_bytes(), 10u), Some(123u as $T));
assert_eq!(parse_bytes("1001".as_bytes(), 2u), Some(9u as $T));
assert_eq!(parse_bytes("123".as_bytes(), 8u), Some(83u as $T));
assert_eq!(u16::parse_bytes("123".as_bytes(), 16u), Some(291u as u16));
assert_eq!(u16::parse_bytes("ffff".as_bytes(), 16u), Some(65535u as u16));
assert_eq!(parse_bytes("z".as_bytes(), 36u), Some(35u as $T));
assert!(parse_bytes("Z".as_bytes(), 10u).is_none());
assert!(parse_bytes("_".as_bytes(), 2u).is_none());
}
#[test]
fn test_uint_to_str_overflow() {
let mut u8_val: u8 = 255_u8;
assert_eq!(u8_val.to_string(), "255".to_string());
u8_val += 1 as u8;
assert_eq!(u8_val.to_string(), "0".to_string());
let mut u16_val: u16 = 65_535_u16;
assert_eq!(u16_val.to_string(), "65535".to_string());
u16_val += 1 as u16;
assert_eq!(u16_val.to_string(), "0".to_string());
let mut u32_val: u32 = 4_294_967_295_u32;
assert_eq!(u32_val.to_string(), "4294967295".to_string());
u32_val += 1 as u32;
assert_eq!(u32_val.to_string(), "0".to_string());
let mut u64_val: u64 = 18_446_744_073_709_551_615_u64;
assert_eq!(u64_val.to_string(), "18446744073709551615".to_string());
u64_val += 1 as u64;
assert_eq!(u64_val.to_string(), "0".to_string());
}
#[test]
fn test_uint_from_str_overflow() {
let mut u8_val: u8 = 255_u8;
assert_eq!(from_str::<u8>("255"), Some(u8_val));
assert!(from_str::<u8>("256").is_none());
u8_val += 1 as u8;
assert_eq!(from_str::<u8>("0"), Some(u8_val));
assert!(from_str::<u8>("-1").is_none());
let mut u16_val: u16 = 65_535_u16;
assert_eq!(from_str::<u16>("65535"), Some(u16_val));
assert!(from_str::<u16>("65536").is_none());
u16_val += 1 as u16;
assert_eq!(from_str::<u16>("0"), Some(u16_val));
assert!(from_str::<u16>("-1").is_none());
let mut u32_val: u32 = 4_294_967_295_u32;
assert_eq!(from_str::<u32>("4294967295"), Some(u32_val));
assert!(from_str::<u32>("4294967296").is_none());
u32_val += 1 as u32;
assert_eq!(from_str::<u32>("0"), Some(u32_val));
assert!(from_str::<u32>("-1").is_none());
let mut u64_val: u64 = 18_446_744_073_709_551_615_u64;
assert_eq!(from_str::<u64>("18446744073709551615"), Some(u64_val));
assert!(from_str::<u64>("18446744073709551616").is_none());
u64_val += 1 as u64;
assert_eq!(from_str::<u64>("0"), Some(u64_val));
assert!(from_str::<u64>("-1").is_none());
}
#[test]
#[should_fail]
pub fn to_str_radix1() {
100u.to_str_radix(1u);
}
#[test]
#[should_fail]
pub fn to_str_radix37() {
100u.to_str_radix(37u);
}
}
))
|
}
|
random_line_split
|
overload-index-operator.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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use std::ops::Index;
|
pairs: Vec<AssociationPair<K,V>> }
#[deriving(Clone)]
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Clone> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for pair in self.pairs.iter() {
if pair.key == *index {
return pair.value.clone();
}
}
fail!("No value found for key: {:?}", index);
}
}
pub fn main() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: Vec::new()};
list.push(foo.clone(), 22);
list.push(bar.clone(), 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
struct AssociationList<K,V> {
|
random_line_split
|
overload-index-operator.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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use std::ops::Index;
struct AssociationList<K,V> {
pairs: Vec<AssociationPair<K,V>> }
#[deriving(Clone)]
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Clone> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for pair in self.pairs.iter() {
if pair.key == *index {
return pair.value.clone();
}
}
fail!("No value found for key: {:?}", index);
}
}
pub fn main()
|
{
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: Vec::new()};
list.push(foo.clone(), 22);
list.push(bar.clone(), 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
identifier_body
|
|
overload-index-operator.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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use std::ops::Index;
struct AssociationList<K,V> {
pairs: Vec<AssociationPair<K,V>> }
#[deriving(Clone)]
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Clone> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for pair in self.pairs.iter() {
if pair.key == *index
|
}
fail!("No value found for key: {:?}", index);
}
}
pub fn main() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: Vec::new()};
list.push(foo.clone(), 22);
list.push(bar.clone(), 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
{
return pair.value.clone();
}
|
conditional_block
|
overload-index-operator.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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use std::ops::Index;
struct AssociationList<K,V> {
pairs: Vec<AssociationPair<K,V>> }
#[deriving(Clone)]
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Clone> Index<K,V> for AssociationList<K,V> {
fn
|
(&self, index: &K) -> V {
for pair in self.pairs.iter() {
if pair.key == *index {
return pair.value.clone();
}
}
fail!("No value found for key: {:?}", index);
}
}
pub fn main() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: Vec::new()};
list.push(foo.clone(), 22);
list.push(bar.clone(), 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
index
|
identifier_name
|
lib.rs
|
//! Rust bindings to `libui`.
//!
//! Main C source repository: https://github.com/andlabs/libui
//!
//! Copyright © 2016 Mozilla Foundation
#[macro_use]
extern crate bitflags;
extern crate libc;
extern crate ui_sys;
pub use controls::{Area, AreaDrawParams, AreaHandler, BoxControl, Button, Checkbox, ColorButton};
pub use controls::{Combobox, Control, DateTimePicker, Entry, FontButton, Group, Label};
pub use controls::{MultilineEntry, ProgressBar, RadioButtons, Separator, Slider, Spinbox, Tab};
pub use ffi_utils::Text;
pub use menus::{Menu, MenuItem};
pub use ui::{InitError, InitOptions, init, main, msg_box, msg_box_error, on_should_quit};
pub use ui::{open_file, queue_main, quit, save_file, uninit};
pub use windows::Window;
#[macro_use]
mod controls;
pub mod draw;
|
pub mod ffi_utils;
mod menus;
mod ui;
mod windows;
|
random_line_split
|
|
hello.rs
|
use std::env;
use std::ffi::OsStr;
use std::time::{Duration, UNIX_EPOCH};
use libc::ENOENT;
use fuse::{FileType, FileAttr, Filesystem, Request, ReplyData, ReplyEntry, ReplyAttr, ReplyDirectory};
const TTL: Duration = Duration::from_secs(1); // 1 second
const HELLO_DIR_ATTR: FileAttr = FileAttr {
ino: 1,
size: 0,
blocks: 0,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: FileType::Directory,
perm: 0o755,
nlink: 2,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
};
const HELLO_TXT_CONTENT: &str = "Hello World!\n";
const HELLO_TXT_ATTR: FileAttr = FileAttr {
ino: 2,
size: 13,
blocks: 1,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: FileType::RegularFile,
perm: 0o644,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
};
struct HelloFS;
impl Filesystem for HelloFS {
fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) {
if parent == 1 && name.to_str() == Some("hello.txt") {
reply.entry(&TTL, &HELLO_TXT_ATTR, 0);
} else {
reply.error(ENOENT);
}
}
fn
|
(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
match ino {
1 => reply.attr(&TTL, &HELLO_DIR_ATTR),
2 => reply.attr(&TTL, &HELLO_TXT_ATTR),
_ => reply.error(ENOENT),
}
}
fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, _size: u32, reply: ReplyData) {
if ino == 2 {
reply.data(&HELLO_TXT_CONTENT.as_bytes()[offset as usize..]);
} else {
reply.error(ENOENT);
}
}
fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory) {
if ino!= 1 {
reply.error(ENOENT);
return;
}
let entries = vec![
(1, FileType::Directory, "."),
(1, FileType::Directory, ".."),
(2, FileType::RegularFile, "hello.txt"),
];
for (i, entry) in entries.into_iter().enumerate().skip(offset as usize) {
// i + 1 means the index of the next entry
reply.add(entry.0, (i + 1) as i64, entry.1, entry.2);
}
reply.ok();
}
}
fn main() {
env_logger::init();
let mountpoint = env::args_os().nth(1).unwrap();
let options = ["-o", "ro", "-o", "fsname=hello"]
.iter()
.map(|o| o.as_ref())
.collect::<Vec<&OsStr>>();
fuse::mount(HelloFS, mountpoint, &options).unwrap();
}
|
getattr
|
identifier_name
|
hello.rs
|
use std::env;
use std::ffi::OsStr;
use std::time::{Duration, UNIX_EPOCH};
use libc::ENOENT;
use fuse::{FileType, FileAttr, Filesystem, Request, ReplyData, ReplyEntry, ReplyAttr, ReplyDirectory};
const TTL: Duration = Duration::from_secs(1); // 1 second
const HELLO_DIR_ATTR: FileAttr = FileAttr {
ino: 1,
size: 0,
blocks: 0,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: FileType::Directory,
perm: 0o755,
nlink: 2,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
};
const HELLO_TXT_CONTENT: &str = "Hello World!\n";
const HELLO_TXT_ATTR: FileAttr = FileAttr {
ino: 2,
size: 13,
blocks: 1,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: FileType::RegularFile,
perm: 0o644,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
};
struct HelloFS;
impl Filesystem for HelloFS {
fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) {
if parent == 1 && name.to_str() == Some("hello.txt") {
reply.entry(&TTL, &HELLO_TXT_ATTR, 0);
} else {
reply.error(ENOENT);
}
}
fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
match ino {
1 => reply.attr(&TTL, &HELLO_DIR_ATTR),
2 => reply.attr(&TTL, &HELLO_TXT_ATTR),
_ => reply.error(ENOENT),
}
}
fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, _size: u32, reply: ReplyData) {
if ino == 2 {
reply.data(&HELLO_TXT_CONTENT.as_bytes()[offset as usize..]);
} else {
reply.error(ENOENT);
}
}
fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory)
|
}
fn main() {
env_logger::init();
let mountpoint = env::args_os().nth(1).unwrap();
let options = ["-o", "ro", "-o", "fsname=hello"]
.iter()
.map(|o| o.as_ref())
.collect::<Vec<&OsStr>>();
fuse::mount(HelloFS, mountpoint, &options).unwrap();
}
|
{
if ino != 1 {
reply.error(ENOENT);
return;
}
let entries = vec![
(1, FileType::Directory, "."),
(1, FileType::Directory, ".."),
(2, FileType::RegularFile, "hello.txt"),
];
for (i, entry) in entries.into_iter().enumerate().skip(offset as usize) {
// i + 1 means the index of the next entry
reply.add(entry.0, (i + 1) as i64, entry.1, entry.2);
}
reply.ok();
}
|
identifier_body
|
hello.rs
|
use std::env;
use std::ffi::OsStr;
use std::time::{Duration, UNIX_EPOCH};
use libc::ENOENT;
use fuse::{FileType, FileAttr, Filesystem, Request, ReplyData, ReplyEntry, ReplyAttr, ReplyDirectory};
const TTL: Duration = Duration::from_secs(1); // 1 second
const HELLO_DIR_ATTR: FileAttr = FileAttr {
ino: 1,
size: 0,
blocks: 0,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: FileType::Directory,
perm: 0o755,
nlink: 2,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
};
const HELLO_TXT_CONTENT: &str = "Hello World!\n";
const HELLO_TXT_ATTR: FileAttr = FileAttr {
ino: 2,
size: 13,
blocks: 1,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: FileType::RegularFile,
perm: 0o644,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
};
struct HelloFS;
impl Filesystem for HelloFS {
fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) {
if parent == 1 && name.to_str() == Some("hello.txt") {
reply.entry(&TTL, &HELLO_TXT_ATTR, 0);
} else {
reply.error(ENOENT);
}
}
fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
match ino {
1 => reply.attr(&TTL, &HELLO_DIR_ATTR),
2 => reply.attr(&TTL, &HELLO_TXT_ATTR),
_ => reply.error(ENOENT),
}
}
fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, _size: u32, reply: ReplyData) {
if ino == 2 {
|
reply.data(&HELLO_TXT_CONTENT.as_bytes()[offset as usize..]);
} else {
reply.error(ENOENT);
}
}
fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory) {
if ino!= 1 {
reply.error(ENOENT);
return;
}
let entries = vec![
(1, FileType::Directory, "."),
(1, FileType::Directory, ".."),
(2, FileType::RegularFile, "hello.txt"),
];
for (i, entry) in entries.into_iter().enumerate().skip(offset as usize) {
// i + 1 means the index of the next entry
reply.add(entry.0, (i + 1) as i64, entry.1, entry.2);
}
reply.ok();
}
}
fn main() {
env_logger::init();
let mountpoint = env::args_os().nth(1).unwrap();
let options = ["-o", "ro", "-o", "fsname=hello"]
.iter()
.map(|o| o.as_ref())
.collect::<Vec<&OsStr>>();
fuse::mount(HelloFS, mountpoint, &options).unwrap();
}
|
random_line_split
|
|
result-types.rs
|
// cdb-only
// min-cdb-version: 10.0.18317.1001
// compile-flags:-g
// === CDB TESTS ==================================================================================
// cdb-command: g
// cdb-command: dx x,d
// cdb-check:x,d : Ok [Type: enum$<core::result::Result<i32,str> >]
// cdb-check: [...] __0 : -3 [Type: int]
// cdb-command: dx y
// cdb-check:y : Err [Type: enum$<core::result::Result<i32,str> >]
// cdb-check: [...] __0 : "Some error message" [Type: str]
fn main()
{
let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_ok(), true);
|
assert_eq!(y.is_ok(), false);
zzz(); // #break.
}
fn zzz() { () }
|
let y: Result<i32, &str> = Err("Some error message");
|
random_line_split
|
result-types.rs
|
// cdb-only
// min-cdb-version: 10.0.18317.1001
// compile-flags:-g
// === CDB TESTS ==================================================================================
// cdb-command: g
// cdb-command: dx x,d
// cdb-check:x,d : Ok [Type: enum$<core::result::Result<i32,str> >]
// cdb-check: [...] __0 : -3 [Type: int]
// cdb-command: dx y
// cdb-check:y : Err [Type: enum$<core::result::Result<i32,str> >]
// cdb-check: [...] __0 : "Some error message" [Type: str]
fn main()
{
let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_ok(), true);
let y: Result<i32, &str> = Err("Some error message");
assert_eq!(y.is_ok(), false);
zzz(); // #break.
}
fn zzz()
|
{ () }
|
identifier_body
|
|
result-types.rs
|
// cdb-only
// min-cdb-version: 10.0.18317.1001
// compile-flags:-g
// === CDB TESTS ==================================================================================
// cdb-command: g
// cdb-command: dx x,d
// cdb-check:x,d : Ok [Type: enum$<core::result::Result<i32,str> >]
// cdb-check: [...] __0 : -3 [Type: int]
// cdb-command: dx y
// cdb-check:y : Err [Type: enum$<core::result::Result<i32,str> >]
// cdb-check: [...] __0 : "Some error message" [Type: str]
fn main()
{
let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_ok(), true);
let y: Result<i32, &str> = Err("Some error message");
assert_eq!(y.is_ok(), false);
zzz(); // #break.
}
fn
|
() { () }
|
zzz
|
identifier_name
|
enum_variants.rs
|
//! lint on enum variants that are prefixed or suffixed by the same characters
use clippy_utils::camel_case;
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::source::is_present_in_source;
use rustc_hir::{EnumDef, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
declare_clippy_lint! {
/// ### What it does
/// Detects enumeration variants that are prefixed or suffixed
/// by the same characters.
///
/// ### Why is this bad?
/// Enumeration variant names should specify their variant,
/// not repeat the enumeration name.
///
/// ### Example
/// ```rust
/// enum Cake {
/// BlackForestCake,
/// HummingbirdCake,
/// BattenbergCake,
/// }
/// ```
/// Could be written as:
/// ```rust
/// enum Cake {
/// BlackForest,
/// Hummingbird,
/// Battenberg,
/// }
/// ```
pub ENUM_VARIANT_NAMES,
style,
"enums where all variants share a prefix/postfix"
}
declare_clippy_lint! {
/// ### What it does
/// Detects type names that are prefixed or suffixed by the
/// containing module's name.
///
/// ### Why is this bad?
/// It requires the user to type the module name twice.
///
/// ### Example
/// ```rust
/// mod cake {
/// struct BlackForestCake;
/// }
/// ```
/// Could be written as:
/// ```rust
/// mod cake {
/// struct BlackForest;
/// }
/// ```
pub MODULE_NAME_REPETITIONS,
pedantic,
"type names prefixed/postfixed with their containing module's name"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for modules that have the same name as their
/// parent module
///
/// ### Why is this bad?
/// A typical beginner mistake is to have `mod foo;` and
/// again `mod foo {..
/// }` in `foo.rs`.
/// The expectation is that items inside the inner `mod foo {.. }` are then
/// available
/// through `foo::x`, but they are only available through
/// `foo::foo::x`.
/// If this is done on purpose, it would be better to choose a more
/// representative module name.
///
/// ### Example
/// ```ignore
/// // lib.rs
/// mod foo;
/// // foo.rs
/// mod foo {
/// ...
/// }
/// ```
pub MODULE_INCEPTION,
style,
"modules that have the same name as their parent module"
}
pub struct EnumVariantNames {
modules: Vec<(Symbol, String)>,
threshold: u64,
avoid_breaking_exported_api: bool,
}
impl EnumVariantNames {
#[must_use]
pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
Self {
modules: Vec::new(),
threshold,
avoid_breaking_exported_api,
}
}
}
impl_lint_pass!(EnumVariantNames => [
ENUM_VARIANT_NAMES,
MODULE_NAME_REPETITIONS,
MODULE_INCEPTION
]);
/// Returns the number of chars that match from the start
#[must_use]
fn partial_match(pre: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next_back(); // make sure the name is never fully matched
pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
}
/// Returns the number of chars that match from the end
#[must_use]
fn partial_rmatch(post: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next(); // make sure the name is never fully matched
post.chars()
.rev()
.zip(name_iter.rev())
.take_while(|&(l, r)| l == r)
.count()
}
fn
|
(
cx: &LateContext<'_>,
threshold: u64,
def: &EnumDef<'_>,
item_name: &str,
item_name_chars: usize,
span: Span,
) {
if (def.variants.len() as u64) < threshold {
return;
}
for var in def.variants {
let name = var.ident.name.as_str();
if partial_match(item_name, &name) == item_name_chars
&& name.chars().nth(item_name_chars).map_or(false, |c|!c.is_lowercase())
&& name.chars().nth(item_name_chars + 1).map_or(false, |c|!c.is_numeric())
{
span_lint(
cx,
ENUM_VARIANT_NAMES,
var.span,
"variant name starts with the enum's name",
);
}
if partial_rmatch(item_name, &name) == item_name_chars {
span_lint(
cx,
ENUM_VARIANT_NAMES,
var.span,
"variant name ends with the enum's name",
);
}
}
let first = &def.variants[0].ident.name.as_str();
let mut pre = &first[..camel_case::until(&*first)];
let mut post = &first[camel_case::from(&*first)..];
for var in def.variants {
let name = var.ident.name.as_str();
let pre_match = partial_match(pre, &name);
pre = &pre[..pre_match];
let pre_camel = camel_case::until(pre);
pre = &pre[..pre_camel];
while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
if next.is_numeric() {
return;
}
if next.is_lowercase() {
let last = pre.len() - last.len_utf8();
let last_camel = camel_case::until(&pre[..last]);
pre = &pre[..last_camel];
} else {
break;
}
}
let post_match = partial_rmatch(post, &name);
let post_end = post.len() - post_match;
post = &post[post_end..];
let post_camel = camel_case::from(post);
post = &post[post_camel..];
}
let (what, value) = match (pre.is_empty(), post.is_empty()) {
(true, true) => return,
(false, _) => ("pre", pre),
(true, false) => ("post", post),
};
span_lint_and_help(
cx,
ENUM_VARIANT_NAMES,
span,
&format!("all variants have the same {}fix: `{}`", what, value),
None,
&format!(
"remove the {}fixes and use full paths to \
the variants instead of glob imports",
what
),
);
}
#[must_use]
fn to_camel_case(item_name: &str) -> String {
let mut s = String::new();
let mut up = true;
for c in item_name.chars() {
if c.is_uppercase() {
// we only turn snake case text into CamelCase
return item_name.to_string();
}
if c == '_' {
up = true;
continue;
}
if up {
up = false;
s.extend(c.to_uppercase());
} else {
s.push(c);
}
}
s
}
impl LateLintPass<'_> for EnumVariantNames {
fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
let last = self.modules.pop();
assert!(last.is_some());
}
#[allow(clippy::similar_names)]
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
let item_name = item.ident.name.as_str();
let item_name_chars = item_name.chars().count();
let item_camel = to_camel_case(&item_name);
if!item.span.from_expansion() && is_present_in_source(cx, item.span) {
if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
// constants don't have surrounding modules
if!mod_camel.is_empty() {
if mod_name == &item.ident.name {
if let ItemKind::Mod(..) = item.kind {
span_lint(
cx,
MODULE_INCEPTION,
item.span,
"module has the same name as its containing module",
);
}
}
if item.vis.node.is_pub() {
let matching = partial_match(mod_camel, &item_camel);
let rmatching = partial_rmatch(mod_camel, &item_camel);
let nchars = mod_camel.chars().count();
let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
if matching == nchars {
match item_camel.chars().nth(nchars) {
Some(c) if is_word_beginning(c) => span_lint(
cx,
MODULE_NAME_REPETITIONS,
item.span,
"item name starts with its containing module's name",
),
_ => (),
}
}
if rmatching == nchars {
span_lint(
cx,
MODULE_NAME_REPETITIONS,
item.span,
"item name ends with its containing module's name",
);
}
}
}
}
}
if let ItemKind::Enum(ref def, _) = item.kind {
if!(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) {
check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span);
}
}
self.modules.push((item.ident.name, item_camel));
}
}
|
check_variant
|
identifier_name
|
enum_variants.rs
|
//! lint on enum variants that are prefixed or suffixed by the same characters
use clippy_utils::camel_case;
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::source::is_present_in_source;
use rustc_hir::{EnumDef, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
declare_clippy_lint! {
/// ### What it does
/// Detects enumeration variants that are prefixed or suffixed
/// by the same characters.
///
/// ### Why is this bad?
/// Enumeration variant names should specify their variant,
/// not repeat the enumeration name.
///
/// ### Example
/// ```rust
/// enum Cake {
/// BlackForestCake,
/// HummingbirdCake,
/// BattenbergCake,
/// }
/// ```
/// Could be written as:
/// ```rust
/// enum Cake {
/// BlackForest,
/// Hummingbird,
/// Battenberg,
/// }
/// ```
pub ENUM_VARIANT_NAMES,
style,
"enums where all variants share a prefix/postfix"
}
declare_clippy_lint! {
/// ### What it does
/// Detects type names that are prefixed or suffixed by the
/// containing module's name.
///
/// ### Why is this bad?
/// It requires the user to type the module name twice.
///
/// ### Example
/// ```rust
/// mod cake {
/// struct BlackForestCake;
/// }
/// ```
/// Could be written as:
/// ```rust
/// mod cake {
/// struct BlackForest;
/// }
/// ```
pub MODULE_NAME_REPETITIONS,
pedantic,
"type names prefixed/postfixed with their containing module's name"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for modules that have the same name as their
/// parent module
///
/// ### Why is this bad?
/// A typical beginner mistake is to have `mod foo;` and
/// again `mod foo {..
/// }` in `foo.rs`.
/// The expectation is that items inside the inner `mod foo {.. }` are then
/// available
/// through `foo::x`, but they are only available through
/// `foo::foo::x`.
/// If this is done on purpose, it would be better to choose a more
/// representative module name.
///
/// ### Example
/// ```ignore
/// // lib.rs
/// mod foo;
/// // foo.rs
/// mod foo {
/// ...
/// }
/// ```
pub MODULE_INCEPTION,
style,
"modules that have the same name as their parent module"
}
pub struct EnumVariantNames {
modules: Vec<(Symbol, String)>,
threshold: u64,
avoid_breaking_exported_api: bool,
}
impl EnumVariantNames {
#[must_use]
pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
Self {
modules: Vec::new(),
threshold,
avoid_breaking_exported_api,
}
}
}
impl_lint_pass!(EnumVariantNames => [
ENUM_VARIANT_NAMES,
MODULE_NAME_REPETITIONS,
MODULE_INCEPTION
]);
/// Returns the number of chars that match from the start
#[must_use]
fn partial_match(pre: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next_back(); // make sure the name is never fully matched
pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
}
/// Returns the number of chars that match from the end
#[must_use]
fn partial_rmatch(post: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next(); // make sure the name is never fully matched
post.chars()
.rev()
.zip(name_iter.rev())
.take_while(|&(l, r)| l == r)
.count()
}
fn check_variant(
cx: &LateContext<'_>,
threshold: u64,
def: &EnumDef<'_>,
item_name: &str,
item_name_chars: usize,
span: Span,
) {
if (def.variants.len() as u64) < threshold {
return;
}
for var in def.variants {
let name = var.ident.name.as_str();
if partial_match(item_name, &name) == item_name_chars
&& name.chars().nth(item_name_chars).map_or(false, |c|!c.is_lowercase())
&& name.chars().nth(item_name_chars + 1).map_or(false, |c|!c.is_numeric())
{
span_lint(
cx,
ENUM_VARIANT_NAMES,
var.span,
"variant name starts with the enum's name",
);
}
if partial_rmatch(item_name, &name) == item_name_chars {
span_lint(
cx,
ENUM_VARIANT_NAMES,
var.span,
"variant name ends with the enum's name",
);
}
}
let first = &def.variants[0].ident.name.as_str();
let mut pre = &first[..camel_case::until(&*first)];
let mut post = &first[camel_case::from(&*first)..];
for var in def.variants {
let name = var.ident.name.as_str();
let pre_match = partial_match(pre, &name);
pre = &pre[..pre_match];
let pre_camel = camel_case::until(pre);
pre = &pre[..pre_camel];
while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
if next.is_numeric() {
return;
}
if next.is_lowercase() {
let last = pre.len() - last.len_utf8();
let last_camel = camel_case::until(&pre[..last]);
pre = &pre[..last_camel];
} else {
break;
}
}
let post_match = partial_rmatch(post, &name);
let post_end = post.len() - post_match;
post = &post[post_end..];
let post_camel = camel_case::from(post);
post = &post[post_camel..];
}
let (what, value) = match (pre.is_empty(), post.is_empty()) {
(true, true) => return,
(false, _) => ("pre", pre),
(true, false) => ("post", post),
};
span_lint_and_help(
cx,
ENUM_VARIANT_NAMES,
span,
&format!("all variants have the same {}fix: `{}`", what, value),
None,
&format!(
"remove the {}fixes and use full paths to \
the variants instead of glob imports",
what
),
);
}
#[must_use]
fn to_camel_case(item_name: &str) -> String
|
}
impl LateLintPass<'_> for EnumVariantNames {
fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
let last = self.modules.pop();
assert!(last.is_some());
}
#[allow(clippy::similar_names)]
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
let item_name = item.ident.name.as_str();
let item_name_chars = item_name.chars().count();
let item_camel = to_camel_case(&item_name);
if!item.span.from_expansion() && is_present_in_source(cx, item.span) {
if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
// constants don't have surrounding modules
if!mod_camel.is_empty() {
if mod_name == &item.ident.name {
if let ItemKind::Mod(..) = item.kind {
span_lint(
cx,
MODULE_INCEPTION,
item.span,
"module has the same name as its containing module",
);
}
}
if item.vis.node.is_pub() {
let matching = partial_match(mod_camel, &item_camel);
let rmatching = partial_rmatch(mod_camel, &item_camel);
let nchars = mod_camel.chars().count();
let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
if matching == nchars {
match item_camel.chars().nth(nchars) {
Some(c) if is_word_beginning(c) => span_lint(
cx,
MODULE_NAME_REPETITIONS,
item.span,
"item name starts with its containing module's name",
),
_ => (),
}
}
if rmatching == nchars {
span_lint(
cx,
MODULE_NAME_REPETITIONS,
item.span,
"item name ends with its containing module's name",
);
}
}
}
}
}
if let ItemKind::Enum(ref def, _) = item.kind {
if!(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) {
check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span);
}
}
self.modules.push((item.ident.name, item_camel));
}
}
|
{
let mut s = String::new();
let mut up = true;
for c in item_name.chars() {
if c.is_uppercase() {
// we only turn snake case text into CamelCase
return item_name.to_string();
}
if c == '_' {
up = true;
continue;
}
if up {
up = false;
s.extend(c.to_uppercase());
} else {
s.push(c);
}
}
s
|
identifier_body
|
enum_variants.rs
|
//! lint on enum variants that are prefixed or suffixed by the same characters
use clippy_utils::camel_case;
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::source::is_present_in_source;
use rustc_hir::{EnumDef, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
declare_clippy_lint! {
/// ### What it does
/// Detects enumeration variants that are prefixed or suffixed
/// by the same characters.
///
/// ### Why is this bad?
/// Enumeration variant names should specify their variant,
/// not repeat the enumeration name.
///
/// ### Example
/// ```rust
/// enum Cake {
/// BlackForestCake,
/// HummingbirdCake,
/// BattenbergCake,
/// }
/// ```
/// Could be written as:
/// ```rust
/// enum Cake {
/// BlackForest,
/// Hummingbird,
/// Battenberg,
/// }
/// ```
pub ENUM_VARIANT_NAMES,
style,
"enums where all variants share a prefix/postfix"
}
declare_clippy_lint! {
/// ### What it does
/// Detects type names that are prefixed or suffixed by the
/// containing module's name.
///
/// ### Why is this bad?
/// It requires the user to type the module name twice.
///
/// ### Example
/// ```rust
/// mod cake {
/// struct BlackForestCake;
/// }
/// ```
/// Could be written as:
/// ```rust
/// mod cake {
/// struct BlackForest;
/// }
/// ```
pub MODULE_NAME_REPETITIONS,
pedantic,
"type names prefixed/postfixed with their containing module's name"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for modules that have the same name as their
/// parent module
///
/// ### Why is this bad?
/// A typical beginner mistake is to have `mod foo;` and
/// again `mod foo {..
/// }` in `foo.rs`.
/// The expectation is that items inside the inner `mod foo {.. }` are then
/// available
/// through `foo::x`, but they are only available through
/// `foo::foo::x`.
/// If this is done on purpose, it would be better to choose a more
/// representative module name.
///
/// ### Example
/// ```ignore
/// // lib.rs
/// mod foo;
/// // foo.rs
/// mod foo {
/// ...
/// }
/// ```
pub MODULE_INCEPTION,
style,
"modules that have the same name as their parent module"
}
pub struct EnumVariantNames {
modules: Vec<(Symbol, String)>,
threshold: u64,
avoid_breaking_exported_api: bool,
}
impl EnumVariantNames {
#[must_use]
pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
Self {
modules: Vec::new(),
threshold,
avoid_breaking_exported_api,
}
}
}
impl_lint_pass!(EnumVariantNames => [
ENUM_VARIANT_NAMES,
MODULE_NAME_REPETITIONS,
MODULE_INCEPTION
]);
/// Returns the number of chars that match from the start
#[must_use]
fn partial_match(pre: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next_back(); // make sure the name is never fully matched
pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
}
/// Returns the number of chars that match from the end
#[must_use]
fn partial_rmatch(post: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next(); // make sure the name is never fully matched
post.chars()
.rev()
.zip(name_iter.rev())
.take_while(|&(l, r)| l == r)
.count()
}
fn check_variant(
cx: &LateContext<'_>,
threshold: u64,
def: &EnumDef<'_>,
item_name: &str,
item_name_chars: usize,
span: Span,
) {
if (def.variants.len() as u64) < threshold {
return;
}
for var in def.variants {
let name = var.ident.name.as_str();
if partial_match(item_name, &name) == item_name_chars
&& name.chars().nth(item_name_chars).map_or(false, |c|!c.is_lowercase())
&& name.chars().nth(item_name_chars + 1).map_or(false, |c|!c.is_numeric())
{
span_lint(
cx,
ENUM_VARIANT_NAMES,
var.span,
"variant name starts with the enum's name",
);
}
if partial_rmatch(item_name, &name) == item_name_chars {
span_lint(
cx,
ENUM_VARIANT_NAMES,
var.span,
"variant name ends with the enum's name",
);
}
}
let first = &def.variants[0].ident.name.as_str();
let mut pre = &first[..camel_case::until(&*first)];
let mut post = &first[camel_case::from(&*first)..];
for var in def.variants {
let name = var.ident.name.as_str();
let pre_match = partial_match(pre, &name);
pre = &pre[..pre_match];
let pre_camel = camel_case::until(pre);
pre = &pre[..pre_camel];
while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
if next.is_numeric() {
return;
}
if next.is_lowercase() {
let last = pre.len() - last.len_utf8();
let last_camel = camel_case::until(&pre[..last]);
pre = &pre[..last_camel];
} else {
break;
}
}
let post_match = partial_rmatch(post, &name);
let post_end = post.len() - post_match;
post = &post[post_end..];
let post_camel = camel_case::from(post);
post = &post[post_camel..];
}
let (what, value) = match (pre.is_empty(), post.is_empty()) {
(true, true) => return,
(false, _) => ("pre", pre),
(true, false) => ("post", post),
};
span_lint_and_help(
cx,
ENUM_VARIANT_NAMES,
span,
&format!("all variants have the same {}fix: `{}`", what, value),
None,
&format!(
"remove the {}fixes and use full paths to \
the variants instead of glob imports",
what
),
);
}
#[must_use]
fn to_camel_case(item_name: &str) -> String {
let mut s = String::new();
let mut up = true;
for c in item_name.chars() {
if c.is_uppercase() {
// we only turn snake case text into CamelCase
return item_name.to_string();
}
if c == '_' {
up = true;
continue;
}
if up {
up = false;
s.extend(c.to_uppercase());
} else {
s.push(c);
}
}
s
}
impl LateLintPass<'_> for EnumVariantNames {
fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
let last = self.modules.pop();
assert!(last.is_some());
}
#[allow(clippy::similar_names)]
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
let item_name = item.ident.name.as_str();
let item_name_chars = item_name.chars().count();
let item_camel = to_camel_case(&item_name);
if!item.span.from_expansion() && is_present_in_source(cx, item.span) {
if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
// constants don't have surrounding modules
if!mod_camel.is_empty() {
if mod_name == &item.ident.name {
if let ItemKind::Mod(..) = item.kind {
span_lint(
cx,
MODULE_INCEPTION,
item.span,
"module has the same name as its containing module",
);
}
}
if item.vis.node.is_pub() {
let matching = partial_match(mod_camel, &item_camel);
let rmatching = partial_rmatch(mod_camel, &item_camel);
let nchars = mod_camel.chars().count();
let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
|
Some(c) if is_word_beginning(c) => span_lint(
cx,
MODULE_NAME_REPETITIONS,
item.span,
"item name starts with its containing module's name",
),
_ => (),
}
}
if rmatching == nchars {
span_lint(
cx,
MODULE_NAME_REPETITIONS,
item.span,
"item name ends with its containing module's name",
);
}
}
}
}
}
if let ItemKind::Enum(ref def, _) = item.kind {
if!(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) {
check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span);
}
}
self.modules.push((item.ident.name, item_camel));
}
}
|
if matching == nchars {
match item_camel.chars().nth(nchars) {
|
random_line_split
|
shootout-meteor.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.
//
// Utilities.
//
// returns an infinite iterator of repeated applications of f to x,
// i.e. [x, f(x), f(f(x)),...], as haskell iterate function.
fn iterate<'a, T>(x: T, f: |&T|: 'a -> T) -> Iterate<'a, T> {
Iterate {f: f, next: x}
}
struct Iterate<'a, T> {
f: |&T|: 'a -> T,
next: T
}
impl<'a, T> Iterator<T> for Iterate<'a, T> {
fn next(&mut self) -> Option<T> {
let mut res = (self.f)(&self.next);
std::mem::swap(&mut res, &mut self.next);
Some(res)
}
}
// a linked list using borrowed next.
enum List<'a, T> {
Nil,
Cons(T, &'a List<'a, T>)
}
struct ListIterator<'a, T> {
cur: &'a List<'a, T>
}
impl<'a, T> List<'a, T> {
fn iter(&'a self) -> ListIterator<'a, T> {
ListIterator{cur: self}
}
}
impl<'a, T> Iterator<&'a T> for ListIterator<'a, T> {
fn next(&mut self) -> Option<&'a T> {
match *self.cur {
Nil => None,
Cons(ref elt, next) => {
self.cur = next;
Some(elt)
}
}
}
}
//
// preprocess
//
// Takes a pieces p on the form [(y1, x1), (y2, x2),...] and returns
// every possible transformations (the 6 rotations with their
// corresponding mirrored piece), with, as minimum coordinates, (0,
// 0). If all is false, only generate half of the possibilities (used
// to break the symetry of the board).
fn transform(piece: Vec<(int, int)>, all: bool) -> Vec<Vec<(int, int)>> {
let mut res: Vec<Vec<(int, int)>> =
// rotations
iterate(piece, |rot| rot.iter().map(|&(y, x)| (x + y, -y)).collect())
.take(if all {6} else {3})
// mirror
.flat_map(|cur_piece| {
iterate(cur_piece, |mir| mir.iter().map(|&(y, x)| (x, y)).collect())
.take(2)
}).collect();
// translating to (0, 0) as minimum coordinates.
for cur_piece in res.mut_iter() {
let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap();
for &(ref mut y, ref mut x) in cur_piece.mut_iter() {
*y -= dy; *x -= dx;
}
}
res
}
// A mask is a piece somewere on the board. It is represented as a
// u64: for i in the first 50 bits, m[i] = 1 if the cell at (i/5, i%5)
// is occuped. m[50 + id] = 1 if the identifier of the piece is id.
// Takes a piece with minimum coordinate (0, 0) (as generated by
// transform). Returns the corresponding mask if p translated by (dy,
// dx) is on the board.
fn mask(dy: int, dx: int, id: uint, p: &[(int, int)]) -> Option<u64>
|
// Makes every possible masks. masks[id][i] correspond to every
// possible masks for piece with identifier id with minimum coordinate
// (i/5, i%5).
fn make_masks() -> Vec<Vec<Vec<u64> > > {
let pieces = vec!(
vec!((0,0),(0,1),(0,2),(0,3),(1,3)),
vec!((0,0),(0,2),(0,3),(1,0),(1,1)),
vec!((0,0),(0,1),(0,2),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(2,1)),
vec!((0,0),(0,2),(1,0),(1,1),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(1,2)),
vec!((0,0),(0,1),(1,1),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,0),(1,2)),
vec!((0,0),(0,1),(0,2),(1,2),(1,3)),
vec!((0,0),(0,1),(0,2),(0,3),(1,2)));
let mut res = Vec::new();
for (id, p) in pieces.move_iter().enumerate() {
// To break the central symetry of the problem, every
// transformation must be taken except for one piece (piece 3
// here).
let trans = transform(p, id!= 3);
let mut cur_piece = Vec::new();
for dy in range(0, 10) {
for dx in range(0, 5) {
let masks =
trans.iter()
.filter_map(|t| mask(dy, dx, id, t.as_slice()))
.collect();
cur_piece.push(masks);
}
}
res.push(cur_piece);
}
res
}
// Check if all coordinates can be covered by an unused piece and that
// all unused piece can be placed on the board.
fn is_board_unfeasible(board: u64, masks: &[Vec<Vec<u64> > ]) -> bool {
let mut coverable = board;
for i in range(0, 50).filter(|&i| board & 1 << i == 0) {
for (cur_id, pos_masks) in masks.iter().enumerate() {
if board & 1 << (50 + cur_id)!= 0 {continue;}
for &cur_m in pos_masks.get(i as uint).iter() {
if cur_m & board == 0 {coverable |= cur_m;}
}
}
if coverable & (1 << i) == 0 {return true;}
}
// check if every coordinates can be covered and every piece can
// be used.
coverable!= (1 << 60) - 1
}
// Filter the masks that we can prove to result to unfeasible board.
fn filter_masks(masks: &[Vec<Vec<u64> > ]) -> Vec<Vec<Vec<u64> > > {
masks.iter().map(
|p| p.iter().map(
|p| p.iter()
.map(|&m| m)
.filter(|&m|!is_board_unfeasible(m, masks))
.collect())
.collect())
.collect()
}
// Gets the identifier of a mask.
fn get_id(m: u64) -> u8 {
for id in range(0, 10) {
if m & (1 << (id + 50))!= 0 {return id as u8;}
}
fail!("{:016x} does not have a valid identifier", m);
}
// Converts a list of mask to a ~str.
fn to_utf8(raw_sol: &List<u64>) -> ~str {
let mut sol: Vec<u8> = Vec::from_elem(50, '.' as u8);
for &m in raw_sol.iter() {
let id = get_id(m);
for i in range(0, 50) {
if m & 1 << i!= 0 {
*sol.get_mut(i as uint) = '0' as u8 + id;
}
}
}
std::str::from_utf8_owned(sol.move_iter().collect()).unwrap()
}
// Prints a solution in ~str form.
fn print_sol(sol: &str) {
for (i, c) in sol.chars().enumerate() {
if (i) % 5 == 0 { println!(""); }
if (i + 5) % 10 == 0 { print!(" "); }
print!("{} ", c);
}
println!("");
}
// The data managed during the search
struct Data {
// If more than stop_after is found, stop the search.
stop_after: int,
// Number of solution found.
nb: int,
// Lexicographically minimal solution found.
min: ~str,
// Lexicographically maximal solution found.
max: ~str
}
// Records a new found solution. Returns false if the search must be
// stopped.
fn handle_sol(raw_sol: &List<u64>, data: &mut Data) -> bool {
// because we break the symetry, 2 solutions correspond to a call
// to this method: the normal solution, and the same solution in
// reverse order, i.e. the board rotated by half a turn.
data.nb += 2;
let sol1 = to_utf8(raw_sol);
let sol2: ~str = sol1.chars().rev().collect();
if data.nb == 2 {
data.min = sol1.clone();
data.max = sol1.clone();
}
if sol1 < data.min {data.min = sol1.clone();}
if sol2 < data.min {data.min = sol2.clone();}
if sol1 > data.max {data.max = sol1;}
if sol2 > data.max {data.max = sol2;}
data.nb < data.stop_after
}
// Search for every solutions. Returns false if the search was
// stopped before the end.
fn search(
masks: &[Vec<Vec<u64> > ],
board: u64,
mut i: int,
cur: List<u64>,
data: &mut Data)
-> bool
{
// Search for the lesser empty coordinate.
while board & (1 << i) != 0 && i < 50 {i += 1;}
// the board is full: a solution is found.
if i >= 50 {return handle_sol(&cur, data);}
// for every unused piece
for id in range(0, 10).filter(|id| board & (1 << (id + 50)) == 0) {
// for each mask that fits on the board
for &m in masks[id as uint].get(i as uint)
.iter()
.filter(|&m| board & *m == 0) {
// This check is too costy.
//if is_board_unfeasible(board | m, masks) {continue;}
if!search(masks, board | m, i + 1, Cons(m, &cur), data) {
return false;
}
}
}
return true;
}
fn main () {
let args = std::os::args();
let stop_after = if args.len() <= 1 {
2098
} else {
from_str(args[1]).unwrap()
};
let masks = make_masks();
let masks = filter_masks(masks.as_slice());
let mut data = Data {stop_after: stop_after, nb: 0, min: ~"", max: ~""};
search(masks.as_slice(), 0, 0, Nil, &mut data);
println!("{} solutions found", data.nb);
print_sol(data.min);
print_sol(data.max);
println!("");
}
|
{
let mut m = 1 << (50 + id);
for &(y, x) in p.iter() {
let x = x + dx + (y + (dy % 2)) / 2;
if x < 0 || x > 4 {return None;}
let y = y + dy;
if y < 0 || y > 9 {return None;}
m |= 1 << (y * 5 + x);
}
Some(m)
}
|
identifier_body
|
shootout-meteor.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.
//
// Utilities.
//
// returns an infinite iterator of repeated applications of f to x,
// i.e. [x, f(x), f(f(x)),...], as haskell iterate function.
fn iterate<'a, T>(x: T, f: |&T|: 'a -> T) -> Iterate<'a, T> {
Iterate {f: f, next: x}
}
struct Iterate<'a, T> {
f: |&T|: 'a -> T,
next: T
}
impl<'a, T> Iterator<T> for Iterate<'a, T> {
fn next(&mut self) -> Option<T> {
let mut res = (self.f)(&self.next);
std::mem::swap(&mut res, &mut self.next);
Some(res)
}
}
// a linked list using borrowed next.
enum List<'a, T> {
Nil,
Cons(T, &'a List<'a, T>)
}
struct ListIterator<'a, T> {
cur: &'a List<'a, T>
}
impl<'a, T> List<'a, T> {
fn iter(&'a self) -> ListIterator<'a, T> {
ListIterator{cur: self}
}
}
impl<'a, T> Iterator<&'a T> for ListIterator<'a, T> {
fn next(&mut self) -> Option<&'a T> {
match *self.cur {
Nil => None,
Cons(ref elt, next) => {
self.cur = next;
Some(elt)
}
}
}
}
//
// preprocess
//
// Takes a pieces p on the form [(y1, x1), (y2, x2),...] and returns
// every possible transformations (the 6 rotations with their
// corresponding mirrored piece), with, as minimum coordinates, (0,
// 0). If all is false, only generate half of the possibilities (used
// to break the symetry of the board).
fn transform(piece: Vec<(int, int)>, all: bool) -> Vec<Vec<(int, int)>> {
let mut res: Vec<Vec<(int, int)>> =
// rotations
iterate(piece, |rot| rot.iter().map(|&(y, x)| (x + y, -y)).collect())
.take(if all {6} else {3})
// mirror
.flat_map(|cur_piece| {
iterate(cur_piece, |mir| mir.iter().map(|&(y, x)| (x, y)).collect())
.take(2)
}).collect();
// translating to (0, 0) as minimum coordinates.
for cur_piece in res.mut_iter() {
let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap();
for &(ref mut y, ref mut x) in cur_piece.mut_iter() {
*y -= dy; *x -= dx;
}
}
res
}
// A mask is a piece somewere on the board. It is represented as a
// u64: for i in the first 50 bits, m[i] = 1 if the cell at (i/5, i%5)
// is occuped. m[50 + id] = 1 if the identifier of the piece is id.
// Takes a piece with minimum coordinate (0, 0) (as generated by
// transform). Returns the corresponding mask if p translated by (dy,
// dx) is on the board.
fn mask(dy: int, dx: int, id: uint, p: &[(int, int)]) -> Option<u64> {
let mut m = 1 << (50 + id);
for &(y, x) in p.iter() {
let x = x + dx + (y + (dy % 2)) / 2;
if x < 0 || x > 4 {return None;}
let y = y + dy;
if y < 0 || y > 9
|
m |= 1 << (y * 5 + x);
}
Some(m)
}
// Makes every possible masks. masks[id][i] correspond to every
// possible masks for piece with identifier id with minimum coordinate
// (i/5, i%5).
fn make_masks() -> Vec<Vec<Vec<u64> > > {
let pieces = vec!(
vec!((0,0),(0,1),(0,2),(0,3),(1,3)),
vec!((0,0),(0,2),(0,3),(1,0),(1,1)),
vec!((0,0),(0,1),(0,2),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(2,1)),
vec!((0,0),(0,2),(1,0),(1,1),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(1,2)),
vec!((0,0),(0,1),(1,1),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,0),(1,2)),
vec!((0,0),(0,1),(0,2),(1,2),(1,3)),
vec!((0,0),(0,1),(0,2),(0,3),(1,2)));
let mut res = Vec::new();
for (id, p) in pieces.move_iter().enumerate() {
// To break the central symetry of the problem, every
// transformation must be taken except for one piece (piece 3
// here).
let trans = transform(p, id!= 3);
let mut cur_piece = Vec::new();
for dy in range(0, 10) {
for dx in range(0, 5) {
let masks =
trans.iter()
.filter_map(|t| mask(dy, dx, id, t.as_slice()))
.collect();
cur_piece.push(masks);
}
}
res.push(cur_piece);
}
res
}
// Check if all coordinates can be covered by an unused piece and that
// all unused piece can be placed on the board.
fn is_board_unfeasible(board: u64, masks: &[Vec<Vec<u64> > ]) -> bool {
let mut coverable = board;
for i in range(0, 50).filter(|&i| board & 1 << i == 0) {
for (cur_id, pos_masks) in masks.iter().enumerate() {
if board & 1 << (50 + cur_id)!= 0 {continue;}
for &cur_m in pos_masks.get(i as uint).iter() {
if cur_m & board == 0 {coverable |= cur_m;}
}
}
if coverable & (1 << i) == 0 {return true;}
}
// check if every coordinates can be covered and every piece can
// be used.
coverable!= (1 << 60) - 1
}
// Filter the masks that we can prove to result to unfeasible board.
fn filter_masks(masks: &[Vec<Vec<u64> > ]) -> Vec<Vec<Vec<u64> > > {
masks.iter().map(
|p| p.iter().map(
|p| p.iter()
.map(|&m| m)
.filter(|&m|!is_board_unfeasible(m, masks))
.collect())
.collect())
.collect()
}
// Gets the identifier of a mask.
fn get_id(m: u64) -> u8 {
for id in range(0, 10) {
if m & (1 << (id + 50))!= 0 {return id as u8;}
}
fail!("{:016x} does not have a valid identifier", m);
}
// Converts a list of mask to a ~str.
fn to_utf8(raw_sol: &List<u64>) -> ~str {
let mut sol: Vec<u8> = Vec::from_elem(50, '.' as u8);
for &m in raw_sol.iter() {
let id = get_id(m);
for i in range(0, 50) {
if m & 1 << i!= 0 {
*sol.get_mut(i as uint) = '0' as u8 + id;
}
}
}
std::str::from_utf8_owned(sol.move_iter().collect()).unwrap()
}
// Prints a solution in ~str form.
fn print_sol(sol: &str) {
for (i, c) in sol.chars().enumerate() {
if (i) % 5 == 0 { println!(""); }
if (i + 5) % 10 == 0 { print!(" "); }
print!("{} ", c);
}
println!("");
}
// The data managed during the search
struct Data {
// If more than stop_after is found, stop the search.
stop_after: int,
// Number of solution found.
nb: int,
// Lexicographically minimal solution found.
min: ~str,
// Lexicographically maximal solution found.
max: ~str
}
// Records a new found solution. Returns false if the search must be
// stopped.
fn handle_sol(raw_sol: &List<u64>, data: &mut Data) -> bool {
// because we break the symetry, 2 solutions correspond to a call
// to this method: the normal solution, and the same solution in
// reverse order, i.e. the board rotated by half a turn.
data.nb += 2;
let sol1 = to_utf8(raw_sol);
let sol2: ~str = sol1.chars().rev().collect();
if data.nb == 2 {
data.min = sol1.clone();
data.max = sol1.clone();
}
if sol1 < data.min {data.min = sol1.clone();}
if sol2 < data.min {data.min = sol2.clone();}
if sol1 > data.max {data.max = sol1;}
if sol2 > data.max {data.max = sol2;}
data.nb < data.stop_after
}
// Search for every solutions. Returns false if the search was
// stopped before the end.
fn search(
masks: &[Vec<Vec<u64> > ],
board: u64,
mut i: int,
cur: List<u64>,
data: &mut Data)
-> bool
{
// Search for the lesser empty coordinate.
while board & (1 << i) != 0 && i < 50 {i += 1;}
// the board is full: a solution is found.
if i >= 50 {return handle_sol(&cur, data);}
// for every unused piece
for id in range(0, 10).filter(|id| board & (1 << (id + 50)) == 0) {
// for each mask that fits on the board
for &m in masks[id as uint].get(i as uint)
.iter()
.filter(|&m| board & *m == 0) {
// This check is too costy.
//if is_board_unfeasible(board | m, masks) {continue;}
if!search(masks, board | m, i + 1, Cons(m, &cur), data) {
return false;
}
}
}
return true;
}
fn main () {
let args = std::os::args();
let stop_after = if args.len() <= 1 {
2098
} else {
from_str(args[1]).unwrap()
};
let masks = make_masks();
let masks = filter_masks(masks.as_slice());
let mut data = Data {stop_after: stop_after, nb: 0, min: ~"", max: ~""};
search(masks.as_slice(), 0, 0, Nil, &mut data);
println!("{} solutions found", data.nb);
print_sol(data.min);
print_sol(data.max);
println!("");
}
|
{return None;}
|
conditional_block
|
shootout-meteor.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.
//
// Utilities.
//
// returns an infinite iterator of repeated applications of f to x,
// i.e. [x, f(x), f(f(x)),...], as haskell iterate function.
fn iterate<'a, T>(x: T, f: |&T|: 'a -> T) -> Iterate<'a, T> {
Iterate {f: f, next: x}
}
struct Iterate<'a, T> {
f: |&T|: 'a -> T,
next: T
}
impl<'a, T> Iterator<T> for Iterate<'a, T> {
fn next(&mut self) -> Option<T> {
let mut res = (self.f)(&self.next);
std::mem::swap(&mut res, &mut self.next);
Some(res)
}
}
// a linked list using borrowed next.
enum List<'a, T> {
Nil,
Cons(T, &'a List<'a, T>)
}
struct ListIterator<'a, T> {
cur: &'a List<'a, T>
}
impl<'a, T> List<'a, T> {
fn iter(&'a self) -> ListIterator<'a, T> {
ListIterator{cur: self}
}
}
impl<'a, T> Iterator<&'a T> for ListIterator<'a, T> {
fn next(&mut self) -> Option<&'a T> {
match *self.cur {
Nil => None,
Cons(ref elt, next) => {
self.cur = next;
Some(elt)
}
}
}
}
//
// preprocess
//
// Takes a pieces p on the form [(y1, x1), (y2, x2),...] and returns
// every possible transformations (the 6 rotations with their
// corresponding mirrored piece), with, as minimum coordinates, (0,
// 0). If all is false, only generate half of the possibilities (used
// to break the symetry of the board).
fn transform(piece: Vec<(int, int)>, all: bool) -> Vec<Vec<(int, int)>> {
let mut res: Vec<Vec<(int, int)>> =
// rotations
iterate(piece, |rot| rot.iter().map(|&(y, x)| (x + y, -y)).collect())
.take(if all {6} else {3})
// mirror
.flat_map(|cur_piece| {
iterate(cur_piece, |mir| mir.iter().map(|&(y, x)| (x, y)).collect())
.take(2)
}).collect();
// translating to (0, 0) as minimum coordinates.
for cur_piece in res.mut_iter() {
let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap();
for &(ref mut y, ref mut x) in cur_piece.mut_iter() {
*y -= dy; *x -= dx;
}
}
res
}
// A mask is a piece somewere on the board. It is represented as a
// u64: for i in the first 50 bits, m[i] = 1 if the cell at (i/5, i%5)
// is occuped. m[50 + id] = 1 if the identifier of the piece is id.
// Takes a piece with minimum coordinate (0, 0) (as generated by
// transform). Returns the corresponding mask if p translated by (dy,
// dx) is on the board.
fn mask(dy: int, dx: int, id: uint, p: &[(int, int)]) -> Option<u64> {
let mut m = 1 << (50 + id);
for &(y, x) in p.iter() {
let x = x + dx + (y + (dy % 2)) / 2;
if x < 0 || x > 4 {return None;}
let y = y + dy;
if y < 0 || y > 9 {return None;}
m |= 1 << (y * 5 + x);
}
Some(m)
}
// Makes every possible masks. masks[id][i] correspond to every
// possible masks for piece with identifier id with minimum coordinate
// (i/5, i%5).
fn make_masks() -> Vec<Vec<Vec<u64> > > {
let pieces = vec!(
vec!((0,0),(0,1),(0,2),(0,3),(1,3)),
vec!((0,0),(0,2),(0,3),(1,0),(1,1)),
vec!((0,0),(0,1),(0,2),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(2,1)),
vec!((0,0),(0,2),(1,0),(1,1),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(1,2)),
vec!((0,0),(0,1),(1,1),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,0),(1,2)),
vec!((0,0),(0,1),(0,2),(1,2),(1,3)),
vec!((0,0),(0,1),(0,2),(0,3),(1,2)));
let mut res = Vec::new();
for (id, p) in pieces.move_iter().enumerate() {
// To break the central symetry of the problem, every
// transformation must be taken except for one piece (piece 3
// here).
let trans = transform(p, id!= 3);
let mut cur_piece = Vec::new();
for dy in range(0, 10) {
for dx in range(0, 5) {
let masks =
trans.iter()
.filter_map(|t| mask(dy, dx, id, t.as_slice()))
.collect();
cur_piece.push(masks);
}
}
res.push(cur_piece);
}
res
}
// Check if all coordinates can be covered by an unused piece and that
// all unused piece can be placed on the board.
fn is_board_unfeasible(board: u64, masks: &[Vec<Vec<u64> > ]) -> bool {
let mut coverable = board;
for i in range(0, 50).filter(|&i| board & 1 << i == 0) {
for (cur_id, pos_masks) in masks.iter().enumerate() {
if board & 1 << (50 + cur_id)!= 0 {continue;}
|
}
// check if every coordinates can be covered and every piece can
// be used.
coverable!= (1 << 60) - 1
}
// Filter the masks that we can prove to result to unfeasible board.
fn filter_masks(masks: &[Vec<Vec<u64> > ]) -> Vec<Vec<Vec<u64> > > {
masks.iter().map(
|p| p.iter().map(
|p| p.iter()
.map(|&m| m)
.filter(|&m|!is_board_unfeasible(m, masks))
.collect())
.collect())
.collect()
}
// Gets the identifier of a mask.
fn get_id(m: u64) -> u8 {
for id in range(0, 10) {
if m & (1 << (id + 50))!= 0 {return id as u8;}
}
fail!("{:016x} does not have a valid identifier", m);
}
// Converts a list of mask to a ~str.
fn to_utf8(raw_sol: &List<u64>) -> ~str {
let mut sol: Vec<u8> = Vec::from_elem(50, '.' as u8);
for &m in raw_sol.iter() {
let id = get_id(m);
for i in range(0, 50) {
if m & 1 << i!= 0 {
*sol.get_mut(i as uint) = '0' as u8 + id;
}
}
}
std::str::from_utf8_owned(sol.move_iter().collect()).unwrap()
}
// Prints a solution in ~str form.
fn print_sol(sol: &str) {
for (i, c) in sol.chars().enumerate() {
if (i) % 5 == 0 { println!(""); }
if (i + 5) % 10 == 0 { print!(" "); }
print!("{} ", c);
}
println!("");
}
// The data managed during the search
struct Data {
// If more than stop_after is found, stop the search.
stop_after: int,
// Number of solution found.
nb: int,
// Lexicographically minimal solution found.
min: ~str,
// Lexicographically maximal solution found.
max: ~str
}
// Records a new found solution. Returns false if the search must be
// stopped.
fn handle_sol(raw_sol: &List<u64>, data: &mut Data) -> bool {
// because we break the symetry, 2 solutions correspond to a call
// to this method: the normal solution, and the same solution in
// reverse order, i.e. the board rotated by half a turn.
data.nb += 2;
let sol1 = to_utf8(raw_sol);
let sol2: ~str = sol1.chars().rev().collect();
if data.nb == 2 {
data.min = sol1.clone();
data.max = sol1.clone();
}
if sol1 < data.min {data.min = sol1.clone();}
if sol2 < data.min {data.min = sol2.clone();}
if sol1 > data.max {data.max = sol1;}
if sol2 > data.max {data.max = sol2;}
data.nb < data.stop_after
}
// Search for every solutions. Returns false if the search was
// stopped before the end.
fn search(
masks: &[Vec<Vec<u64> > ],
board: u64,
mut i: int,
cur: List<u64>,
data: &mut Data)
-> bool
{
// Search for the lesser empty coordinate.
while board & (1 << i) != 0 && i < 50 {i += 1;}
// the board is full: a solution is found.
if i >= 50 {return handle_sol(&cur, data);}
// for every unused piece
for id in range(0, 10).filter(|id| board & (1 << (id + 50)) == 0) {
// for each mask that fits on the board
for &m in masks[id as uint].get(i as uint)
.iter()
.filter(|&m| board & *m == 0) {
// This check is too costy.
//if is_board_unfeasible(board | m, masks) {continue;}
if!search(masks, board | m, i + 1, Cons(m, &cur), data) {
return false;
}
}
}
return true;
}
fn main () {
let args = std::os::args();
let stop_after = if args.len() <= 1 {
2098
} else {
from_str(args[1]).unwrap()
};
let masks = make_masks();
let masks = filter_masks(masks.as_slice());
let mut data = Data {stop_after: stop_after, nb: 0, min: ~"", max: ~""};
search(masks.as_slice(), 0, 0, Nil, &mut data);
println!("{} solutions found", data.nb);
print_sol(data.min);
print_sol(data.max);
println!("");
}
|
for &cur_m in pos_masks.get(i as uint).iter() {
if cur_m & board == 0 {coverable |= cur_m;}
}
}
if coverable & (1 << i) == 0 {return true;}
|
random_line_split
|
shootout-meteor.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.
//
// Utilities.
//
// returns an infinite iterator of repeated applications of f to x,
// i.e. [x, f(x), f(f(x)),...], as haskell iterate function.
fn iterate<'a, T>(x: T, f: |&T|: 'a -> T) -> Iterate<'a, T> {
Iterate {f: f, next: x}
}
struct Iterate<'a, T> {
f: |&T|: 'a -> T,
next: T
}
impl<'a, T> Iterator<T> for Iterate<'a, T> {
fn next(&mut self) -> Option<T> {
let mut res = (self.f)(&self.next);
std::mem::swap(&mut res, &mut self.next);
Some(res)
}
}
// a linked list using borrowed next.
enum List<'a, T> {
Nil,
Cons(T, &'a List<'a, T>)
}
struct
|
<'a, T> {
cur: &'a List<'a, T>
}
impl<'a, T> List<'a, T> {
fn iter(&'a self) -> ListIterator<'a, T> {
ListIterator{cur: self}
}
}
impl<'a, T> Iterator<&'a T> for ListIterator<'a, T> {
fn next(&mut self) -> Option<&'a T> {
match *self.cur {
Nil => None,
Cons(ref elt, next) => {
self.cur = next;
Some(elt)
}
}
}
}
//
// preprocess
//
// Takes a pieces p on the form [(y1, x1), (y2, x2),...] and returns
// every possible transformations (the 6 rotations with their
// corresponding mirrored piece), with, as minimum coordinates, (0,
// 0). If all is false, only generate half of the possibilities (used
// to break the symetry of the board).
fn transform(piece: Vec<(int, int)>, all: bool) -> Vec<Vec<(int, int)>> {
let mut res: Vec<Vec<(int, int)>> =
// rotations
iterate(piece, |rot| rot.iter().map(|&(y, x)| (x + y, -y)).collect())
.take(if all {6} else {3})
// mirror
.flat_map(|cur_piece| {
iterate(cur_piece, |mir| mir.iter().map(|&(y, x)| (x, y)).collect())
.take(2)
}).collect();
// translating to (0, 0) as minimum coordinates.
for cur_piece in res.mut_iter() {
let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap();
for &(ref mut y, ref mut x) in cur_piece.mut_iter() {
*y -= dy; *x -= dx;
}
}
res
}
// A mask is a piece somewere on the board. It is represented as a
// u64: for i in the first 50 bits, m[i] = 1 if the cell at (i/5, i%5)
// is occuped. m[50 + id] = 1 if the identifier of the piece is id.
// Takes a piece with minimum coordinate (0, 0) (as generated by
// transform). Returns the corresponding mask if p translated by (dy,
// dx) is on the board.
fn mask(dy: int, dx: int, id: uint, p: &[(int, int)]) -> Option<u64> {
let mut m = 1 << (50 + id);
for &(y, x) in p.iter() {
let x = x + dx + (y + (dy % 2)) / 2;
if x < 0 || x > 4 {return None;}
let y = y + dy;
if y < 0 || y > 9 {return None;}
m |= 1 << (y * 5 + x);
}
Some(m)
}
// Makes every possible masks. masks[id][i] correspond to every
// possible masks for piece with identifier id with minimum coordinate
// (i/5, i%5).
fn make_masks() -> Vec<Vec<Vec<u64> > > {
let pieces = vec!(
vec!((0,0),(0,1),(0,2),(0,3),(1,3)),
vec!((0,0),(0,2),(0,3),(1,0),(1,1)),
vec!((0,0),(0,1),(0,2),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(2,1)),
vec!((0,0),(0,2),(1,0),(1,1),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(1,2)),
vec!((0,0),(0,1),(1,1),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,0),(1,2)),
vec!((0,0),(0,1),(0,2),(1,2),(1,3)),
vec!((0,0),(0,1),(0,2),(0,3),(1,2)));
let mut res = Vec::new();
for (id, p) in pieces.move_iter().enumerate() {
// To break the central symetry of the problem, every
// transformation must be taken except for one piece (piece 3
// here).
let trans = transform(p, id!= 3);
let mut cur_piece = Vec::new();
for dy in range(0, 10) {
for dx in range(0, 5) {
let masks =
trans.iter()
.filter_map(|t| mask(dy, dx, id, t.as_slice()))
.collect();
cur_piece.push(masks);
}
}
res.push(cur_piece);
}
res
}
// Check if all coordinates can be covered by an unused piece and that
// all unused piece can be placed on the board.
fn is_board_unfeasible(board: u64, masks: &[Vec<Vec<u64> > ]) -> bool {
let mut coverable = board;
for i in range(0, 50).filter(|&i| board & 1 << i == 0) {
for (cur_id, pos_masks) in masks.iter().enumerate() {
if board & 1 << (50 + cur_id)!= 0 {continue;}
for &cur_m in pos_masks.get(i as uint).iter() {
if cur_m & board == 0 {coverable |= cur_m;}
}
}
if coverable & (1 << i) == 0 {return true;}
}
// check if every coordinates can be covered and every piece can
// be used.
coverable!= (1 << 60) - 1
}
// Filter the masks that we can prove to result to unfeasible board.
fn filter_masks(masks: &[Vec<Vec<u64> > ]) -> Vec<Vec<Vec<u64> > > {
masks.iter().map(
|p| p.iter().map(
|p| p.iter()
.map(|&m| m)
.filter(|&m|!is_board_unfeasible(m, masks))
.collect())
.collect())
.collect()
}
// Gets the identifier of a mask.
fn get_id(m: u64) -> u8 {
for id in range(0, 10) {
if m & (1 << (id + 50))!= 0 {return id as u8;}
}
fail!("{:016x} does not have a valid identifier", m);
}
// Converts a list of mask to a ~str.
fn to_utf8(raw_sol: &List<u64>) -> ~str {
let mut sol: Vec<u8> = Vec::from_elem(50, '.' as u8);
for &m in raw_sol.iter() {
let id = get_id(m);
for i in range(0, 50) {
if m & 1 << i!= 0 {
*sol.get_mut(i as uint) = '0' as u8 + id;
}
}
}
std::str::from_utf8_owned(sol.move_iter().collect()).unwrap()
}
// Prints a solution in ~str form.
fn print_sol(sol: &str) {
for (i, c) in sol.chars().enumerate() {
if (i) % 5 == 0 { println!(""); }
if (i + 5) % 10 == 0 { print!(" "); }
print!("{} ", c);
}
println!("");
}
// The data managed during the search
struct Data {
// If more than stop_after is found, stop the search.
stop_after: int,
// Number of solution found.
nb: int,
// Lexicographically minimal solution found.
min: ~str,
// Lexicographically maximal solution found.
max: ~str
}
// Records a new found solution. Returns false if the search must be
// stopped.
fn handle_sol(raw_sol: &List<u64>, data: &mut Data) -> bool {
// because we break the symetry, 2 solutions correspond to a call
// to this method: the normal solution, and the same solution in
// reverse order, i.e. the board rotated by half a turn.
data.nb += 2;
let sol1 = to_utf8(raw_sol);
let sol2: ~str = sol1.chars().rev().collect();
if data.nb == 2 {
data.min = sol1.clone();
data.max = sol1.clone();
}
if sol1 < data.min {data.min = sol1.clone();}
if sol2 < data.min {data.min = sol2.clone();}
if sol1 > data.max {data.max = sol1;}
if sol2 > data.max {data.max = sol2;}
data.nb < data.stop_after
}
// Search for every solutions. Returns false if the search was
// stopped before the end.
fn search(
masks: &[Vec<Vec<u64> > ],
board: u64,
mut i: int,
cur: List<u64>,
data: &mut Data)
-> bool
{
// Search for the lesser empty coordinate.
while board & (1 << i) != 0 && i < 50 {i += 1;}
// the board is full: a solution is found.
if i >= 50 {return handle_sol(&cur, data);}
// for every unused piece
for id in range(0, 10).filter(|id| board & (1 << (id + 50)) == 0) {
// for each mask that fits on the board
for &m in masks[id as uint].get(i as uint)
.iter()
.filter(|&m| board & *m == 0) {
// This check is too costy.
//if is_board_unfeasible(board | m, masks) {continue;}
if!search(masks, board | m, i + 1, Cons(m, &cur), data) {
return false;
}
}
}
return true;
}
fn main () {
let args = std::os::args();
let stop_after = if args.len() <= 1 {
2098
} else {
from_str(args[1]).unwrap()
};
let masks = make_masks();
let masks = filter_masks(masks.as_slice());
let mut data = Data {stop_after: stop_after, nb: 0, min: ~"", max: ~""};
search(masks.as_slice(), 0, 0, Nil, &mut data);
println!("{} solutions found", data.nb);
print_sol(data.min);
print_sol(data.max);
println!("");
}
|
ListIterator
|
identifier_name
|
trait-inheritance-num2.rs
|
// Copyright 2012-2014 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.
|
impl TypeExt for u16 {}
impl TypeExt for u32 {}
impl TypeExt for u64 {}
impl TypeExt for usize {}
impl TypeExt for i8 {}
impl TypeExt for i16 {}
impl TypeExt for i32 {}
impl TypeExt for i64 {}
impl TypeExt for isize {}
impl TypeExt for f32 {}
impl TypeExt for f64 {}
pub trait NumExt: TypeExt + PartialEq + PartialOrd {}
impl NumExt for u8 {}
impl NumExt for u16 {}
impl NumExt for u32 {}
impl NumExt for u64 {}
impl NumExt for usize {}
impl NumExt for i8 {}
impl NumExt for i16 {}
impl NumExt for i32 {}
impl NumExt for i64 {}
impl NumExt for isize {}
impl NumExt for f32 {}
impl NumExt for f64 {}
pub trait UnSignedExt: NumExt {}
impl UnSignedExt for u8 {}
impl UnSignedExt for u16 {}
impl UnSignedExt for u32 {}
impl UnSignedExt for u64 {}
impl UnSignedExt for usize {}
pub trait SignedExt: NumExt {}
impl SignedExt for i8 {}
impl SignedExt for i16 {}
impl SignedExt for i32 {}
impl SignedExt for i64 {}
impl SignedExt for isize {}
impl SignedExt for f32 {}
impl SignedExt for f64 {}
pub trait IntegerExt: NumExt {}
impl IntegerExt for u8 {}
impl IntegerExt for u16 {}
impl IntegerExt for u32 {}
impl IntegerExt for u64 {}
impl IntegerExt for usize {}
impl IntegerExt for i8 {}
impl IntegerExt for i16 {}
impl IntegerExt for i32 {}
impl IntegerExt for i64 {}
impl IntegerExt for isize {}
pub trait FloatExt: NumExt {}
impl FloatExt for f32 {}
impl FloatExt for f64 {}
fn test_float_ext<T:FloatExt>(n: T) { println!("{}", n < n) }
pub fn main() {
test_float_ext(1f32);
}
|
// A more complex example of numeric extensions
pub trait TypeExt {}
impl TypeExt for u8 {}
|
random_line_split
|
trait-inheritance-num2.rs
|
// Copyright 2012-2014 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.
// A more complex example of numeric extensions
pub trait TypeExt {}
impl TypeExt for u8 {}
impl TypeExt for u16 {}
impl TypeExt for u32 {}
impl TypeExt for u64 {}
impl TypeExt for usize {}
impl TypeExt for i8 {}
impl TypeExt for i16 {}
impl TypeExt for i32 {}
impl TypeExt for i64 {}
impl TypeExt for isize {}
impl TypeExt for f32 {}
impl TypeExt for f64 {}
pub trait NumExt: TypeExt + PartialEq + PartialOrd {}
impl NumExt for u8 {}
impl NumExt for u16 {}
impl NumExt for u32 {}
impl NumExt for u64 {}
impl NumExt for usize {}
impl NumExt for i8 {}
impl NumExt for i16 {}
impl NumExt for i32 {}
impl NumExt for i64 {}
impl NumExt for isize {}
impl NumExt for f32 {}
impl NumExt for f64 {}
pub trait UnSignedExt: NumExt {}
impl UnSignedExt for u8 {}
impl UnSignedExt for u16 {}
impl UnSignedExt for u32 {}
impl UnSignedExt for u64 {}
impl UnSignedExt for usize {}
pub trait SignedExt: NumExt {}
impl SignedExt for i8 {}
impl SignedExt for i16 {}
impl SignedExt for i32 {}
impl SignedExt for i64 {}
impl SignedExt for isize {}
impl SignedExt for f32 {}
impl SignedExt for f64 {}
pub trait IntegerExt: NumExt {}
impl IntegerExt for u8 {}
impl IntegerExt for u16 {}
impl IntegerExt for u32 {}
impl IntegerExt for u64 {}
impl IntegerExt for usize {}
impl IntegerExt for i8 {}
impl IntegerExt for i16 {}
impl IntegerExt for i32 {}
impl IntegerExt for i64 {}
impl IntegerExt for isize {}
pub trait FloatExt: NumExt {}
impl FloatExt for f32 {}
impl FloatExt for f64 {}
fn test_float_ext<T:FloatExt>(n: T) { println!("{}", n < n) }
pub fn main()
|
{
test_float_ext(1f32);
}
|
identifier_body
|
|
trait-inheritance-num2.rs
|
// Copyright 2012-2014 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.
// A more complex example of numeric extensions
pub trait TypeExt {}
impl TypeExt for u8 {}
impl TypeExt for u16 {}
impl TypeExt for u32 {}
impl TypeExt for u64 {}
impl TypeExt for usize {}
impl TypeExt for i8 {}
impl TypeExt for i16 {}
impl TypeExt for i32 {}
impl TypeExt for i64 {}
impl TypeExt for isize {}
impl TypeExt for f32 {}
impl TypeExt for f64 {}
pub trait NumExt: TypeExt + PartialEq + PartialOrd {}
impl NumExt for u8 {}
impl NumExt for u16 {}
impl NumExt for u32 {}
impl NumExt for u64 {}
impl NumExt for usize {}
impl NumExt for i8 {}
impl NumExt for i16 {}
impl NumExt for i32 {}
impl NumExt for i64 {}
impl NumExt for isize {}
impl NumExt for f32 {}
impl NumExt for f64 {}
pub trait UnSignedExt: NumExt {}
impl UnSignedExt for u8 {}
impl UnSignedExt for u16 {}
impl UnSignedExt for u32 {}
impl UnSignedExt for u64 {}
impl UnSignedExt for usize {}
pub trait SignedExt: NumExt {}
impl SignedExt for i8 {}
impl SignedExt for i16 {}
impl SignedExt for i32 {}
impl SignedExt for i64 {}
impl SignedExt for isize {}
impl SignedExt for f32 {}
impl SignedExt for f64 {}
pub trait IntegerExt: NumExt {}
impl IntegerExt for u8 {}
impl IntegerExt for u16 {}
impl IntegerExt for u32 {}
impl IntegerExt for u64 {}
impl IntegerExt for usize {}
impl IntegerExt for i8 {}
impl IntegerExt for i16 {}
impl IntegerExt for i32 {}
impl IntegerExt for i64 {}
impl IntegerExt for isize {}
pub trait FloatExt: NumExt {}
impl FloatExt for f32 {}
impl FloatExt for f64 {}
fn test_float_ext<T:FloatExt>(n: T) { println!("{}", n < n) }
pub fn
|
() {
test_float_ext(1f32);
}
|
main
|
identifier_name
|
rational.rs
|
// http://rosettacode.org/wiki/Arithmetic/Rational
#![feature(zero_one)]
use std::num::{Zero, One};
use std::fmt;
use std::cmp::Ordering;
use std::ops::{Add, Mul, Neg, Sub, Div};
fn main() {
for p in perfect_numbers(1 << 19) {
println!("{} is perfect", p);
}
}
fn perfect_numbers(max: i64) -> Vec<i64> {
let mut ret = Vec::new();
for candidate in 2..max {
let mut sum = Frac::secure_new(1, candidate).unwrap();
let max2 = ((candidate as f64).sqrt().floor()) as i64;
for factor in 2..max2 + 1 {
if candidate % factor == 0 {
sum = sum + Frac::new(1, factor) + Frac::new(factor, candidate);
}
}
if sum == Frac::new(1, 1) {
ret.push(candidate);
}
}
ret
}
#[derive(Copy, Clone)]
struct Frac {
num: i64,
den: i64,
}
fn gcd(m: i64, n: i64) -> i64 {
let mut t: i64;
let (mut m, mut n) = (m.abs(), n.abs());
while n > 0 {
t = n;
n = m % n;
m = t;
}
m
}
fn lcm(m: i64, n: i64) -> i64 {
m.abs() / gcd(m, n) * n.abs()
}
impl Frac {
/// fails on den=0
fn new(num: i64, den: i64) -> Frac {
let (n, d) = match (num, den) {
(0, _) => (0, 0),
(n, d) if d < 0 => (-n, -d),
a => a,
};
Frac { num: n, den: d }
}
/// does not fail (returns Err on den=0)
fn secure_new(num: i64, den: i64) -> Result<Frac, String> {
if den == 0 {
Err("Error: Division by zero".to_string())
} else {
Ok(Frac::new(num, den))
}
}
/// fails on den=0, returns frac already in its reduced form
fn new_reduced(num: i64, den: i64) -> Frac {
Frac::new(num, den).reduce()
}
/// reduces the fraction to lowest terms
fn reduce(mut self) -> Frac {
match self {
z @ Frac { num: 0, den: 0 } => z,
_ =>
|
}
}
}
impl fmt::Debug for Frac {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match (self.num, self.den) {
(_, 1) | (0, 0) => write!(f, "{}", self.num),
(_, _) => write!(f, "{}/{}", self.num, self.den),
}
}
}
impl PartialEq for Frac {
fn eq(&self, other: &Frac) -> bool {
let (red_a, red_b) = (self.reduce(), other.reduce());
red_a.num == red_b.num && red_a.den == red_b.den
}
}
impl Eq for Frac {}
impl PartialOrd for Frac {
fn partial_cmp(&self, other: &Frac) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Frac {
fn cmp(&self, other: &Frac) -> Ordering {
(self.num * other.den).cmp(&(self.den * other.num))
}
}
impl Neg for Frac {
type Output = Frac;
fn neg(self) -> Frac {
Frac {
num: -self.num,
den: self.den,
}
}
}
impl Add for Frac {
type Output = Frac;
fn add(self, other: Frac) -> Frac {
let (a, b) = (self.reduce(), other.reduce());
let m = lcm(a.den, b.den);
let na = a.num * m / a.den;
let nb = b.num * m / b.den;
Frac::new_reduced(na + nb, m)
}
}
impl Sub for Frac {
type Output = Frac;
fn sub(self, other: Frac) -> Frac {
self + (-other)
}
}
impl Mul for Frac {
type Output = Frac;
fn mul(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.num, self.den * other.den)
}
}
impl Div for Frac {
type Output = Frac;
fn div(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.den, self.den * other.num)
}
}
impl Zero for Frac {
fn zero() -> Frac {
Frac::new(0, 1)
}
}
impl One for Frac {
fn one() -> Frac {
Frac::new(1, 1)
}
}
#[test]
fn operators() {
let (a, b) = (Frac::new(1, 2), Frac::new(12, 15));
assert_eq!(a + b, Frac::secure_new(13, 10).unwrap());
assert_eq!(b - a, Frac::new(3, 10));
assert_eq!(a - b, Frac::new(-3, 10));
assert_eq!(a * b, Frac::new(2, 5));
assert_eq!(a / b, Frac::new(5, 8));
let (a, b) = (Frac::new(1, 2), Frac::new(1, 2));
assert_eq!(a + b, One::one());
assert_eq!(b - a, Zero::zero());
assert_eq!(a - b, Zero::zero());
assert_eq!(a * b, Frac::new(1, 4));
assert_eq!(a / b, Frac::new(1, 1));
}
#[test]
fn first_perfect_numbers() {
assert_eq!(perfect_numbers(8150), vec![6, 28, 496, 8128]);
}
|
{
let gcd = gcd(self.num, self.den);
self.num /= gcd;
self.den /= gcd;
self
}
|
conditional_block
|
rational.rs
|
// http://rosettacode.org/wiki/Arithmetic/Rational
#![feature(zero_one)]
use std::num::{Zero, One};
use std::fmt;
use std::cmp::Ordering;
use std::ops::{Add, Mul, Neg, Sub, Div};
fn main() {
for p in perfect_numbers(1 << 19) {
println!("{} is perfect", p);
}
}
fn perfect_numbers(max: i64) -> Vec<i64> {
let mut ret = Vec::new();
for candidate in 2..max {
let mut sum = Frac::secure_new(1, candidate).unwrap();
let max2 = ((candidate as f64).sqrt().floor()) as i64;
for factor in 2..max2 + 1 {
if candidate % factor == 0 {
sum = sum + Frac::new(1, factor) + Frac::new(factor, candidate);
}
}
if sum == Frac::new(1, 1) {
ret.push(candidate);
}
}
ret
}
#[derive(Copy, Clone)]
struct Frac {
num: i64,
den: i64,
}
fn gcd(m: i64, n: i64) -> i64 {
let mut t: i64;
let (mut m, mut n) = (m.abs(), n.abs());
while n > 0 {
t = n;
n = m % n;
m = t;
}
m
}
fn lcm(m: i64, n: i64) -> i64 {
m.abs() / gcd(m, n) * n.abs()
}
impl Frac {
/// fails on den=0
fn new(num: i64, den: i64) -> Frac {
let (n, d) = match (num, den) {
(0, _) => (0, 0),
(n, d) if d < 0 => (-n, -d),
a => a,
};
Frac { num: n, den: d }
}
/// does not fail (returns Err on den=0)
fn secure_new(num: i64, den: i64) -> Result<Frac, String> {
if den == 0 {
Err("Error: Division by zero".to_string())
} else {
Ok(Frac::new(num, den))
}
}
/// fails on den=0, returns frac already in its reduced form
fn new_reduced(num: i64, den: i64) -> Frac {
Frac::new(num, den).reduce()
}
/// reduces the fraction to lowest terms
fn reduce(mut self) -> Frac {
match self {
z @ Frac { num: 0, den: 0 } => z,
_ => {
let gcd = gcd(self.num, self.den);
self.num /= gcd;
self.den /= gcd;
self
}
}
}
}
impl fmt::Debug for Frac {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match (self.num, self.den) {
(_, 1) | (0, 0) => write!(f, "{}", self.num),
(_, _) => write!(f, "{}/{}", self.num, self.den),
}
}
}
impl PartialEq for Frac {
fn eq(&self, other: &Frac) -> bool {
let (red_a, red_b) = (self.reduce(), other.reduce());
red_a.num == red_b.num && red_a.den == red_b.den
}
}
impl Eq for Frac {}
impl PartialOrd for Frac {
fn partial_cmp(&self, other: &Frac) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Frac {
fn cmp(&self, other: &Frac) -> Ordering
|
}
impl Neg for Frac {
type Output = Frac;
fn neg(self) -> Frac {
Frac {
num: -self.num,
den: self.den,
}
}
}
impl Add for Frac {
type Output = Frac;
fn add(self, other: Frac) -> Frac {
let (a, b) = (self.reduce(), other.reduce());
let m = lcm(a.den, b.den);
let na = a.num * m / a.den;
let nb = b.num * m / b.den;
Frac::new_reduced(na + nb, m)
}
}
impl Sub for Frac {
type Output = Frac;
fn sub(self, other: Frac) -> Frac {
self + (-other)
}
}
impl Mul for Frac {
type Output = Frac;
fn mul(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.num, self.den * other.den)
}
}
impl Div for Frac {
type Output = Frac;
fn div(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.den, self.den * other.num)
}
}
impl Zero for Frac {
fn zero() -> Frac {
Frac::new(0, 1)
}
}
impl One for Frac {
fn one() -> Frac {
Frac::new(1, 1)
}
}
#[test]
fn operators() {
let (a, b) = (Frac::new(1, 2), Frac::new(12, 15));
assert_eq!(a + b, Frac::secure_new(13, 10).unwrap());
assert_eq!(b - a, Frac::new(3, 10));
assert_eq!(a - b, Frac::new(-3, 10));
assert_eq!(a * b, Frac::new(2, 5));
assert_eq!(a / b, Frac::new(5, 8));
let (a, b) = (Frac::new(1, 2), Frac::new(1, 2));
assert_eq!(a + b, One::one());
assert_eq!(b - a, Zero::zero());
assert_eq!(a - b, Zero::zero());
assert_eq!(a * b, Frac::new(1, 4));
assert_eq!(a / b, Frac::new(1, 1));
}
#[test]
fn first_perfect_numbers() {
assert_eq!(perfect_numbers(8150), vec![6, 28, 496, 8128]);
}
|
{
(self.num * other.den).cmp(&(self.den * other.num))
}
|
identifier_body
|
rational.rs
|
// http://rosettacode.org/wiki/Arithmetic/Rational
#![feature(zero_one)]
use std::num::{Zero, One};
use std::fmt;
use std::cmp::Ordering;
use std::ops::{Add, Mul, Neg, Sub, Div};
fn main() {
for p in perfect_numbers(1 << 19) {
println!("{} is perfect", p);
}
}
fn perfect_numbers(max: i64) -> Vec<i64> {
let mut ret = Vec::new();
for candidate in 2..max {
let mut sum = Frac::secure_new(1, candidate).unwrap();
let max2 = ((candidate as f64).sqrt().floor()) as i64;
for factor in 2..max2 + 1 {
if candidate % factor == 0 {
sum = sum + Frac::new(1, factor) + Frac::new(factor, candidate);
}
}
if sum == Frac::new(1, 1) {
ret.push(candidate);
}
}
ret
}
#[derive(Copy, Clone)]
struct Frac {
num: i64,
den: i64,
}
fn gcd(m: i64, n: i64) -> i64 {
let mut t: i64;
let (mut m, mut n) = (m.abs(), n.abs());
while n > 0 {
t = n;
n = m % n;
m = t;
}
m
}
fn lcm(m: i64, n: i64) -> i64 {
m.abs() / gcd(m, n) * n.abs()
}
impl Frac {
/// fails on den=0
fn new(num: i64, den: i64) -> Frac {
let (n, d) = match (num, den) {
(0, _) => (0, 0),
(n, d) if d < 0 => (-n, -d),
a => a,
};
Frac { num: n, den: d }
}
/// does not fail (returns Err on den=0)
fn secure_new(num: i64, den: i64) -> Result<Frac, String> {
if den == 0 {
Err("Error: Division by zero".to_string())
} else {
Ok(Frac::new(num, den))
}
}
/// fails on den=0, returns frac already in its reduced form
fn new_reduced(num: i64, den: i64) -> Frac {
Frac::new(num, den).reduce()
}
/// reduces the fraction to lowest terms
fn reduce(mut self) -> Frac {
match self {
z @ Frac { num: 0, den: 0 } => z,
_ => {
let gcd = gcd(self.num, self.den);
self.num /= gcd;
self.den /= gcd;
self
}
}
}
}
impl fmt::Debug for Frac {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match (self.num, self.den) {
(_, 1) | (0, 0) => write!(f, "{}", self.num),
(_, _) => write!(f, "{}/{}", self.num, self.den),
}
}
}
impl PartialEq for Frac {
fn eq(&self, other: &Frac) -> bool {
let (red_a, red_b) = (self.reduce(), other.reduce());
red_a.num == red_b.num && red_a.den == red_b.den
}
}
impl Eq for Frac {}
impl PartialOrd for Frac {
fn partial_cmp(&self, other: &Frac) -> Option<Ordering> {
Some(self.cmp(other))
}
|
(self.num * other.den).cmp(&(self.den * other.num))
}
}
impl Neg for Frac {
type Output = Frac;
fn neg(self) -> Frac {
Frac {
num: -self.num,
den: self.den,
}
}
}
impl Add for Frac {
type Output = Frac;
fn add(self, other: Frac) -> Frac {
let (a, b) = (self.reduce(), other.reduce());
let m = lcm(a.den, b.den);
let na = a.num * m / a.den;
let nb = b.num * m / b.den;
Frac::new_reduced(na + nb, m)
}
}
impl Sub for Frac {
type Output = Frac;
fn sub(self, other: Frac) -> Frac {
self + (-other)
}
}
impl Mul for Frac {
type Output = Frac;
fn mul(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.num, self.den * other.den)
}
}
impl Div for Frac {
type Output = Frac;
fn div(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.den, self.den * other.num)
}
}
impl Zero for Frac {
fn zero() -> Frac {
Frac::new(0, 1)
}
}
impl One for Frac {
fn one() -> Frac {
Frac::new(1, 1)
}
}
#[test]
fn operators() {
let (a, b) = (Frac::new(1, 2), Frac::new(12, 15));
assert_eq!(a + b, Frac::secure_new(13, 10).unwrap());
assert_eq!(b - a, Frac::new(3, 10));
assert_eq!(a - b, Frac::new(-3, 10));
assert_eq!(a * b, Frac::new(2, 5));
assert_eq!(a / b, Frac::new(5, 8));
let (a, b) = (Frac::new(1, 2), Frac::new(1, 2));
assert_eq!(a + b, One::one());
assert_eq!(b - a, Zero::zero());
assert_eq!(a - b, Zero::zero());
assert_eq!(a * b, Frac::new(1, 4));
assert_eq!(a / b, Frac::new(1, 1));
}
#[test]
fn first_perfect_numbers() {
assert_eq!(perfect_numbers(8150), vec![6, 28, 496, 8128]);
}
|
}
impl Ord for Frac {
fn cmp(&self, other: &Frac) -> Ordering {
|
random_line_split
|
rational.rs
|
// http://rosettacode.org/wiki/Arithmetic/Rational
#![feature(zero_one)]
use std::num::{Zero, One};
use std::fmt;
use std::cmp::Ordering;
use std::ops::{Add, Mul, Neg, Sub, Div};
fn main() {
for p in perfect_numbers(1 << 19) {
println!("{} is perfect", p);
}
}
fn perfect_numbers(max: i64) -> Vec<i64> {
let mut ret = Vec::new();
for candidate in 2..max {
let mut sum = Frac::secure_new(1, candidate).unwrap();
let max2 = ((candidate as f64).sqrt().floor()) as i64;
for factor in 2..max2 + 1 {
if candidate % factor == 0 {
sum = sum + Frac::new(1, factor) + Frac::new(factor, candidate);
}
}
if sum == Frac::new(1, 1) {
ret.push(candidate);
}
}
ret
}
#[derive(Copy, Clone)]
struct Frac {
num: i64,
den: i64,
}
fn gcd(m: i64, n: i64) -> i64 {
let mut t: i64;
let (mut m, mut n) = (m.abs(), n.abs());
while n > 0 {
t = n;
n = m % n;
m = t;
}
m
}
fn lcm(m: i64, n: i64) -> i64 {
m.abs() / gcd(m, n) * n.abs()
}
impl Frac {
/// fails on den=0
fn new(num: i64, den: i64) -> Frac {
let (n, d) = match (num, den) {
(0, _) => (0, 0),
(n, d) if d < 0 => (-n, -d),
a => a,
};
Frac { num: n, den: d }
}
/// does not fail (returns Err on den=0)
fn secure_new(num: i64, den: i64) -> Result<Frac, String> {
if den == 0 {
Err("Error: Division by zero".to_string())
} else {
Ok(Frac::new(num, den))
}
}
/// fails on den=0, returns frac already in its reduced form
fn new_reduced(num: i64, den: i64) -> Frac {
Frac::new(num, den).reduce()
}
/// reduces the fraction to lowest terms
fn reduce(mut self) -> Frac {
match self {
z @ Frac { num: 0, den: 0 } => z,
_ => {
let gcd = gcd(self.num, self.den);
self.num /= gcd;
self.den /= gcd;
self
}
}
}
}
impl fmt::Debug for Frac {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match (self.num, self.den) {
(_, 1) | (0, 0) => write!(f, "{}", self.num),
(_, _) => write!(f, "{}/{}", self.num, self.den),
}
}
}
impl PartialEq for Frac {
fn eq(&self, other: &Frac) -> bool {
let (red_a, red_b) = (self.reduce(), other.reduce());
red_a.num == red_b.num && red_a.den == red_b.den
}
}
impl Eq for Frac {}
impl PartialOrd for Frac {
fn partial_cmp(&self, other: &Frac) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Frac {
fn cmp(&self, other: &Frac) -> Ordering {
(self.num * other.den).cmp(&(self.den * other.num))
}
}
impl Neg for Frac {
type Output = Frac;
fn neg(self) -> Frac {
Frac {
num: -self.num,
den: self.den,
}
}
}
impl Add for Frac {
type Output = Frac;
fn add(self, other: Frac) -> Frac {
let (a, b) = (self.reduce(), other.reduce());
let m = lcm(a.den, b.den);
let na = a.num * m / a.den;
let nb = b.num * m / b.den;
Frac::new_reduced(na + nb, m)
}
}
impl Sub for Frac {
type Output = Frac;
fn sub(self, other: Frac) -> Frac {
self + (-other)
}
}
impl Mul for Frac {
type Output = Frac;
fn
|
(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.num, self.den * other.den)
}
}
impl Div for Frac {
type Output = Frac;
fn div(self, other: Frac) -> Frac {
Frac::new_reduced(self.num * other.den, self.den * other.num)
}
}
impl Zero for Frac {
fn zero() -> Frac {
Frac::new(0, 1)
}
}
impl One for Frac {
fn one() -> Frac {
Frac::new(1, 1)
}
}
#[test]
fn operators() {
let (a, b) = (Frac::new(1, 2), Frac::new(12, 15));
assert_eq!(a + b, Frac::secure_new(13, 10).unwrap());
assert_eq!(b - a, Frac::new(3, 10));
assert_eq!(a - b, Frac::new(-3, 10));
assert_eq!(a * b, Frac::new(2, 5));
assert_eq!(a / b, Frac::new(5, 8));
let (a, b) = (Frac::new(1, 2), Frac::new(1, 2));
assert_eq!(a + b, One::one());
assert_eq!(b - a, Zero::zero());
assert_eq!(a - b, Zero::zero());
assert_eq!(a * b, Frac::new(1, 4));
assert_eq!(a / b, Frac::new(1, 1));
}
#[test]
fn first_perfect_numbers() {
assert_eq!(perfect_numbers(8150), vec![6, 28, 496, 8128]);
}
|
mul
|
identifier_name
|
reflect.rs
|
::ty;
use util::ppaux::ty_to_str;
use std::libc::c_uint;
use std::option::None;
use std::vec;
use syntax::ast::def_id;
use syntax::ast;
use syntax::ast_map::path_name;
use syntax::parse::token::special_idents;
use middle::trans::type_::Type;
pub struct Reflector {
visitor_val: ValueRef,
visitor_methods: @~[@ty::Method],
final_bcx: block,
tydesc_ty: Type,
bcx: block
}
impl Reflector {
pub fn c_uint(&mut self, u: uint) -> ValueRef {
C_uint(self.bcx.ccx(), u)
}
pub fn c_int(&mut self, i: int) -> ValueRef {
C_int(self.bcx.ccx(), i)
}
pub fn c_slice(&mut self, s: @str) -> ValueRef {
// We're careful to not use first class aggregates here because that
// will kick us off fast isel. (Issue #4352.)
let bcx = self.bcx;
let str_vstore = ty::vstore_slice(ty::re_static);
let str_ty = ty::mk_estr(bcx.tcx(), str_vstore);
let scratch = scratch_datum(bcx, str_ty, "", false);
let len = C_uint(bcx.ccx(), s.len() + 1);
let c_str = PointerCast(bcx, C_cstr(bcx.ccx(), s), Type::i8p());
|
Store(bcx, len, GEPi(bcx, scratch.val, [ 0, 1 ]));
scratch.val
}
pub fn c_size_and_align(&mut self, t: ty::t) -> ~[ValueRef] {
let tr = type_of(self.bcx.ccx(), t);
let s = machine::llsize_of_real(self.bcx.ccx(), tr);
let a = machine::llalign_of_min(self.bcx.ccx(), tr);
return ~[self.c_uint(s),
self.c_uint(a)];
}
pub fn c_tydesc(&mut self, t: ty::t) -> ValueRef {
let bcx = self.bcx;
let static_ti = get_tydesc(bcx.ccx(), t);
glue::lazily_emit_all_tydesc_glue(bcx.ccx(), static_ti);
PointerCast(bcx, static_ti.tydesc, self.tydesc_ty.ptr_to())
}
pub fn c_mt(&mut self, mt: &ty::mt) -> ~[ValueRef] {
~[self.c_uint(mt.mutbl as uint),
self.c_tydesc(mt.ty)]
}
pub fn visit(&mut self, ty_name: &str, args: &[ValueRef]) {
let tcx = self.bcx.tcx();
let mth_idx = ty::method_idx(
tcx.sess.ident_of(~"visit_" + ty_name),
*self.visitor_methods).expect(fmt!("Couldn't find visit method \
for %s", ty_name));
let mth_ty =
ty::mk_bare_fn(tcx, copy self.visitor_methods[mth_idx].fty);
let v = self.visitor_val;
debug!("passing %u args:", args.len());
let mut bcx = self.bcx;
for args.iter().enumerate().advance |(i, a)| {
debug!("arg %u: %s", i, bcx.val_to_str(*a));
}
let bool_ty = ty::mk_bool();
// XXX: Should not be BoxTraitStore!
let result = unpack_result!(bcx, callee::trans_call_inner(
self.bcx, None, mth_ty, bool_ty,
|bcx| meth::trans_trait_callee_from_llval(bcx,
mth_ty,
mth_idx,
v,
ty::BoxTraitStore,
ast::sty_region(
None,
ast::m_imm)),
ArgVals(args), None, DontAutorefArg));
let result = bool_to_i1(bcx, result);
let next_bcx = sub_block(bcx, "next");
CondBr(bcx, result, next_bcx.llbb, self.final_bcx.llbb);
self.bcx = next_bcx
}
pub fn bracketed(&mut self,
bracket_name: &str,
extra: &[ValueRef],
inner: &fn(&mut Reflector)) {
self.visit(~"enter_" + bracket_name, extra);
inner(self);
self.visit(~"leave_" + bracket_name, extra);
}
pub fn vstore_name_and_extra(&mut self,
t: ty::t,
vstore: ty::vstore)
-> (~str, ~[ValueRef]) {
match vstore {
ty::vstore_fixed(n) => {
let extra = vec::append(~[self.c_uint(n)],
self.c_size_and_align(t));
(~"fixed", extra)
}
ty::vstore_slice(_) => (~"slice", ~[]),
ty::vstore_uniq => (~"uniq", ~[]),
ty::vstore_box => (~"box", ~[])
}
}
pub fn leaf(&mut self, name: &str) {
self.visit(name, []);
}
// Entrypoint
pub fn visit_ty(&mut self, t: ty::t) {
let bcx = self.bcx;
debug!("reflect::visit_ty %s", ty_to_str(bcx.ccx().tcx, t));
match ty::get(t).sty {
ty::ty_bot => self.leaf("bot"),
ty::ty_nil => self.leaf("nil"),
ty::ty_bool => self.leaf("bool"),
ty::ty_int(ast::ty_i) => self.leaf("int"),
ty::ty_int(ast::ty_char) => self.leaf("char"),
ty::ty_int(ast::ty_i8) => self.leaf("i8"),
ty::ty_int(ast::ty_i16) => self.leaf("i16"),
ty::ty_int(ast::ty_i32) => self.leaf("i32"),
ty::ty_int(ast::ty_i64) => self.leaf("i64"),
ty::ty_uint(ast::ty_u) => self.leaf("uint"),
ty::ty_uint(ast::ty_u8) => self.leaf("u8"),
ty::ty_uint(ast::ty_u16) => self.leaf("u16"),
ty::ty_uint(ast::ty_u32) => self.leaf("u32"),
ty::ty_uint(ast::ty_u64) => self.leaf("u64"),
ty::ty_float(ast::ty_f) => self.leaf("float"),
ty::ty_float(ast::ty_f32) => self.leaf("f32"),
ty::ty_float(ast::ty_f64) => self.leaf("f64"),
ty::ty_unboxed_vec(ref mt) => {
let values = self.c_mt(mt);
self.visit("vec", values)
}
ty::ty_estr(vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
self.visit(~"estr_" + name, extra)
}
ty::ty_evec(ref mt, vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
let extra = extra + self.c_mt(mt);
self.visit(~"evec_" + name, extra)
}
ty::ty_box(ref mt) => {
let extra = self.c_mt(mt);
self.visit("box", extra)
}
ty::ty_uniq(ref mt) => {
let extra = self.c_mt(mt);
if ty::type_contents(bcx.tcx(), t).contains_managed() {
self.visit("uniq_managed", extra)
} else {
self.visit("uniq", extra)
}
}
ty::ty_ptr(ref mt) => {
let extra = self.c_mt(mt);
self.visit("ptr", extra)
}
ty::ty_rptr(_, ref mt) => {
let extra = self.c_mt(mt);
self.visit("rptr", extra)
}
ty::ty_tup(ref tys) => {
let extra = ~[self.c_uint(tys.len())]
+ self.c_size_and_align(t);
do self.bracketed("tup", extra) |this| {
for tys.iter().enumerate().advance |(i, t)| {
let extra = ~[this.c_uint(i), this.c_tydesc(*t)];
this.visit("tup_field", extra);
}
}
}
// FIXME (#2594): fetch constants out of intrinsic
// FIXME (#4809): visitor should break out bare fns from other fns
ty::ty_closure(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let sigilval = ast_sigil_constant(fty.sigil);
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = ~[self.c_uint(pureval),
self.c_uint(sigilval),
self.c_uint(fty.sig.inputs.len()),
self.c_uint(retval)];
self.visit("enter_fn", extra);
self.visit_sig(retval, &fty.sig);
self.visit("leave_fn", extra);
}
// FIXME (#2594): fetch constants out of intrinsic:: for the
// numbers.
ty::ty_bare_fn(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let sigilval = 0u;
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = ~[self.c_uint(pureval),
self.c_uint(sigilval),
self.c_uint(fty.sig.inputs.len()),
self.c_uint(retval)];
self.visit("enter_fn", extra);
self.visit_sig(retval, &fty.sig);
self.visit("leave_fn", extra);
}
ty::ty_struct(did, ref substs) => {
let bcx = self.bcx;
let tcx = bcx.ccx().tcx;
let fields = ty::struct_fields(tcx, did, substs);
let extra = ~[self.c_uint(fields.len())]
+ self.c_size_and_align(t);
do self.bracketed("class", extra) |this| {
for fields.iter().enumerate().advance |(i, field)| {
let extra = ~[this.c_uint(i),
this.c_slice(
bcx.ccx().sess.str_of(field.ident))]
+ this.c_mt(&field.mt);
this.visit("class_field", extra);
}
}
}
// FIXME (#2595): visiting all the variants in turn is probably
// not ideal. It'll work but will get costly on big enums. Maybe
// let the visitor tell us if it wants to visit only a particular
// variant?
ty::ty_enum(did, ref substs) => {
let bcx = self.bcx;
let ccx = bcx.ccx();
let repr = adt::represent_type(bcx.ccx(), t);
let variants = ty::substd_enum_variants(ccx.tcx, did, substs);
let llptrty = type_of(ccx, t).ptr_to();
let opaquety = ty::get_opaque_ty(ccx.tcx);
let opaqueptrty = ty::mk_ptr(ccx.tcx, ty::mt { ty: opaquety, mutbl: ast::m_imm });
let make_get_disr = || {
let sub_path = bcx.fcx.path + &[path_name(special_idents::anon)];
let sym = mangle_internal_name_by_path_and_seq(ccx,
sub_path,
"get_disr");
let llfty = type_of_fn(ccx, [opaqueptrty], ty::mk_int());
let llfdecl = decl_internal_cdecl_fn(ccx.llmod, sym, llfty);
let fcx = new_fn_ctxt(ccx,
~[],
llfdecl,
ty::mk_uint(),
None);
let arg = unsafe {
//
// we know the return type of llfdecl is an int here, so
// no need for a special check to see if the return type
// is immediate.
//
llvm::LLVMGetParam(llfdecl, fcx.arg_pos(0u) as c_uint)
};
let bcx = top_scope_block(fcx, None);
let arg = BitCast(bcx, arg, llptrty);
let ret = adt::trans_get_discr(bcx, repr, arg);
Store(bcx, ret, fcx.llretptr.get());
cleanup_and_Br(bcx, bcx, fcx.llreturn);
finish_fn(fcx, bcx.llbb);
llfdecl
};
let enum_args = ~[self.c_uint(variants.len()), make_get_disr()]
+ self.c_size_and_align(t);
do self.bracketed("enum", enum_args) |this| {
for variants.iter().enumerate().advance |(i, v)| {
let name = ccx.sess.str_of(v.name);
let variant_args = ~[this.c_uint(i),
this.c_int(v.disr_val),
this.c_uint(v.args.len()),
this.c_slice(name)];
do this.bracketed("enum_variant", variant_args) |this| {
for v.args.iter().enumerate().advance |(j, a)| {
let bcx = this.bcx;
let null = C_null(llptrty);
let ptr = adt::trans_field_ptr(bcx, repr, null, v.disr_val, j);
let offset = p2i(ccx, ptr);
let field_args = ~[this.c_uint(j),
offset,
this.c_tydesc(*a)];
this.visit("enum_variant_field", field_args);
}
}
}
}
}
// Miscallaneous extra types
ty::ty_trait(_, _, _, _, _) => self.leaf("trait"),
ty::ty_infer(_) => self.leaf("infer"),
ty::ty_err => self.leaf("err"),
ty::ty_param(ref p) => {
let extra = ~[self.c_uint(p.idx)];
self.visit("param", extra)
}
ty::ty_self(*) => self.leaf("self"),
ty::ty_type => self.leaf("type"),
ty::ty_opaque_box => self.leaf("opaque_box"),
ty::ty_opaque_closure_ptr(ck) => {
let ckval = ast_sigil_constant(ck);
let extra = ~[self.c_uint(ckval)];
self.visit("closure_ptr", extra)
}
}
}
pub fn visit_sig(&mut self, retval: uint, sig: &ty::FnSig) {
for sig.inputs.iter().enumerate().advance |(i, arg)| {
let modeval = 5u; // "by copy"
let extra = ~[self.c_uint(i),
self.c_uint(modeval),
self.c_tydesc(*arg)];
self.visit("fn_input", extra);
}
let extra = ~[self.c_uint(retval),
self.c_tydesc(sig.output)];
self.visit("fn_output", extra);
}
}
|
Store(bcx, c_str, GEPi(bcx, scratch.val, [ 0, 0 ]));
|
random_line_split
|
reflect.rs
|
x, c_str, GEPi(bcx, scratch.val, [ 0, 0 ]));
Store(bcx, len, GEPi(bcx, scratch.val, [ 0, 1 ]));
scratch.val
}
pub fn c_size_and_align(&mut self, t: ty::t) -> ~[ValueRef] {
let tr = type_of(self.bcx.ccx(), t);
let s = machine::llsize_of_real(self.bcx.ccx(), tr);
let a = machine::llalign_of_min(self.bcx.ccx(), tr);
return ~[self.c_uint(s),
self.c_uint(a)];
}
pub fn c_tydesc(&mut self, t: ty::t) -> ValueRef {
let bcx = self.bcx;
let static_ti = get_tydesc(bcx.ccx(), t);
glue::lazily_emit_all_tydesc_glue(bcx.ccx(), static_ti);
PointerCast(bcx, static_ti.tydesc, self.tydesc_ty.ptr_to())
}
pub fn c_mt(&mut self, mt: &ty::mt) -> ~[ValueRef] {
~[self.c_uint(mt.mutbl as uint),
self.c_tydesc(mt.ty)]
}
pub fn visit(&mut self, ty_name: &str, args: &[ValueRef]) {
let tcx = self.bcx.tcx();
let mth_idx = ty::method_idx(
tcx.sess.ident_of(~"visit_" + ty_name),
*self.visitor_methods).expect(fmt!("Couldn't find visit method \
for %s", ty_name));
let mth_ty =
ty::mk_bare_fn(tcx, copy self.visitor_methods[mth_idx].fty);
let v = self.visitor_val;
debug!("passing %u args:", args.len());
let mut bcx = self.bcx;
for args.iter().enumerate().advance |(i, a)| {
debug!("arg %u: %s", i, bcx.val_to_str(*a));
}
let bool_ty = ty::mk_bool();
// XXX: Should not be BoxTraitStore!
let result = unpack_result!(bcx, callee::trans_call_inner(
self.bcx, None, mth_ty, bool_ty,
|bcx| meth::trans_trait_callee_from_llval(bcx,
mth_ty,
mth_idx,
v,
ty::BoxTraitStore,
ast::sty_region(
None,
ast::m_imm)),
ArgVals(args), None, DontAutorefArg));
let result = bool_to_i1(bcx, result);
let next_bcx = sub_block(bcx, "next");
CondBr(bcx, result, next_bcx.llbb, self.final_bcx.llbb);
self.bcx = next_bcx
}
pub fn bracketed(&mut self,
bracket_name: &str,
extra: &[ValueRef],
inner: &fn(&mut Reflector)) {
self.visit(~"enter_" + bracket_name, extra);
inner(self);
self.visit(~"leave_" + bracket_name, extra);
}
pub fn vstore_name_and_extra(&mut self,
t: ty::t,
vstore: ty::vstore)
-> (~str, ~[ValueRef]) {
match vstore {
ty::vstore_fixed(n) => {
let extra = vec::append(~[self.c_uint(n)],
self.c_size_and_align(t));
(~"fixed", extra)
}
ty::vstore_slice(_) => (~"slice", ~[]),
ty::vstore_uniq => (~"uniq", ~[]),
ty::vstore_box => (~"box", ~[])
}
}
pub fn leaf(&mut self, name: &str) {
self.visit(name, []);
}
// Entrypoint
pub fn visit_ty(&mut self, t: ty::t) {
let bcx = self.bcx;
debug!("reflect::visit_ty %s", ty_to_str(bcx.ccx().tcx, t));
match ty::get(t).sty {
ty::ty_bot => self.leaf("bot"),
ty::ty_nil => self.leaf("nil"),
ty::ty_bool => self.leaf("bool"),
ty::ty_int(ast::ty_i) => self.leaf("int"),
ty::ty_int(ast::ty_char) => self.leaf("char"),
ty::ty_int(ast::ty_i8) => self.leaf("i8"),
ty::ty_int(ast::ty_i16) => self.leaf("i16"),
ty::ty_int(ast::ty_i32) => self.leaf("i32"),
ty::ty_int(ast::ty_i64) => self.leaf("i64"),
ty::ty_uint(ast::ty_u) => self.leaf("uint"),
ty::ty_uint(ast::ty_u8) => self.leaf("u8"),
ty::ty_uint(ast::ty_u16) => self.leaf("u16"),
ty::ty_uint(ast::ty_u32) => self.leaf("u32"),
ty::ty_uint(ast::ty_u64) => self.leaf("u64"),
ty::ty_float(ast::ty_f) => self.leaf("float"),
ty::ty_float(ast::ty_f32) => self.leaf("f32"),
ty::ty_float(ast::ty_f64) => self.leaf("f64"),
ty::ty_unboxed_vec(ref mt) => {
let values = self.c_mt(mt);
self.visit("vec", values)
}
ty::ty_estr(vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
self.visit(~"estr_" + name, extra)
}
ty::ty_evec(ref mt, vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
let extra = extra + self.c_mt(mt);
self.visit(~"evec_" + name, extra)
}
ty::ty_box(ref mt) => {
let extra = self.c_mt(mt);
self.visit("box", extra)
}
ty::ty_uniq(ref mt) => {
let extra = self.c_mt(mt);
if ty::type_contents(bcx.tcx(), t).contains_managed() {
self.visit("uniq_managed", extra)
} else {
self.visit("uniq", extra)
}
}
ty::ty_ptr(ref mt) => {
let extra = self.c_mt(mt);
self.visit("ptr", extra)
}
ty::ty_rptr(_, ref mt) => {
let extra = self.c_mt(mt);
self.visit("rptr", extra)
}
ty::ty_tup(ref tys) => {
let extra = ~[self.c_uint(tys.len())]
+ self.c_size_and_align(t);
do self.bracketed("tup", extra) |this| {
for tys.iter().enumerate().advance |(i, t)| {
let extra = ~[this.c_uint(i), this.c_tydesc(*t)];
this.visit("tup_field", extra);
}
}
}
// FIXME (#2594): fetch constants out of intrinsic
// FIXME (#4809): visitor should break out bare fns from other fns
ty::ty_closure(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let sigilval = ast_sigil_constant(fty.sigil);
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = ~[self.c_uint(pureval),
self.c_uint(sigilval),
self.c_uint(fty.sig.inputs.len()),
self.c_uint(retval)];
self.visit("enter_fn", extra);
self.visit_sig(retval, &fty.sig);
self.visit("leave_fn", extra);
}
// FIXME (#2594): fetch constants out of intrinsic:: for the
// numbers.
ty::ty_bare_fn(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let sigilval = 0u;
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = ~[self.c_uint(pureval),
self.c_uint(sigilval),
self.c_uint(fty.sig.inputs.len()),
self.c_uint(retval)];
self.visit("enter_fn", extra);
self.visit_sig(retval, &fty.sig);
self.visit("leave_fn", extra);
}
ty::ty_struct(did, ref substs) => {
let bcx = self.bcx;
let tcx = bcx.ccx().tcx;
let fields = ty::struct_fields(tcx, did, substs);
let extra = ~[self.c_uint(fields.len())]
+ self.c_size_and_align(t);
do self.bracketed("class", extra) |this| {
for fields.iter().enumerate().advance |(i, field)| {
let extra = ~[this.c_uint(i),
this.c_slice(
bcx.ccx().sess.str_of(field.ident))]
+ this.c_mt(&field.mt);
this.visit("class_field", extra);
}
}
}
// FIXME (#2595): visiting all the variants in turn is probably
// not ideal. It'll work but will get costly on big enums. Maybe
// let the visitor tell us if it wants to visit only a particular
// variant?
ty::ty_enum(did, ref substs) => {
let bcx = self.bcx;
let ccx = bcx.ccx();
let repr = adt::represent_type(bcx.ccx(), t);
let variants = ty::substd_enum_variants(ccx.tcx, did, substs);
let llptrty = type_of(ccx, t).ptr_to();
let opaquety = ty::get_opaque_ty(ccx.tcx);
let opaqueptrty = ty::mk_ptr(ccx.tcx, ty::mt { ty: opaquety, mutbl: ast::m_imm });
let make_get_disr = || {
let sub_path = bcx.fcx.path + &[path_name(special_idents::anon)];
let sym = mangle_internal_name_by_path_and_seq(ccx,
sub_path,
"get_disr");
let llfty = type_of_fn(ccx, [opaqueptrty], ty::mk_int());
let llfdecl = decl_internal_cdecl_fn(ccx.llmod, sym, llfty);
let fcx = new_fn_ctxt(ccx,
~[],
llfdecl,
ty::mk_uint(),
None);
let arg = unsafe {
//
// we know the return type of llfdecl is an int here, so
// no need for a special check to see if the return type
// is immediate.
//
llvm::LLVMGetParam(llfdecl, fcx.arg_pos(0u) as c_uint)
};
let bcx = top_scope_block(fcx, None);
let arg = BitCast(bcx, arg, llptrty);
let ret = adt::trans_get_discr(bcx, repr, arg);
Store(bcx, ret, fcx.llretptr.get());
cleanup_and_Br(bcx, bcx, fcx.llreturn);
finish_fn(fcx, bcx.llbb);
llfdecl
};
let enum_args = ~[self.c_uint(variants.len()), make_get_disr()]
+ self.c_size_and_align(t);
do self.bracketed("enum", enum_args) |this| {
for variants.iter().enumerate().advance |(i, v)| {
let name = ccx.sess.str_of(v.name);
let variant_args = ~[this.c_uint(i),
this.c_int(v.disr_val),
this.c_uint(v.args.len()),
this.c_slice(name)];
do this.bracketed("enum_variant", variant_args) |this| {
for v.args.iter().enumerate().advance |(j, a)| {
let bcx = this.bcx;
let null = C_null(llptrty);
let ptr = adt::trans_field_ptr(bcx, repr, null, v.disr_val, j);
let offset = p2i(ccx, ptr);
let field_args = ~[this.c_uint(j),
offset,
this.c_tydesc(*a)];
this.visit("enum_variant_field", field_args);
}
}
}
}
}
// Miscallaneous extra types
ty::ty_trait(_, _, _, _, _) => self.leaf("trait"),
ty::ty_infer(_) => self.leaf("infer"),
ty::ty_err => self.leaf("err"),
ty::ty_param(ref p) => {
let extra = ~[self.c_uint(p.idx)];
self.visit("param", extra)
}
ty::ty_self(*) => self.leaf("self"),
ty::ty_type => self.leaf("type"),
ty::ty_opaque_box => self.leaf("opaque_box"),
ty::ty_opaque_closure_ptr(ck) => {
let ckval = ast_sigil_constant(ck);
let extra = ~[self.c_uint(ckval)];
self.visit("closure_ptr", extra)
}
}
}
pub fn visit_sig(&mut self, retval: uint, sig: &ty::FnSig) {
for sig.inputs.iter().enumerate().advance |(i, arg)| {
let modeval = 5u; // "by copy"
let extra = ~[self.c_uint(i),
self.c_uint(modeval),
self.c_tydesc(*arg)];
self.visit("fn_input", extra);
}
let extra = ~[self.c_uint(retval),
self.c_tydesc(sig.output)];
self.visit("fn_output", extra);
}
}
// Emit a sequence of calls to visit_ty::visit_foo
pub fn emit_calls_to_trait_visit_ty(bcx: block,
t: ty::t,
visitor_val: ValueRef,
visitor_trait_id: def_id)
-> block {
let final = sub_block(bcx, "final");
let tydesc_ty = ty::get_tydesc_ty(bcx.ccx().tcx);
let tydesc_ty = type_of(bcx.ccx(), tydesc_ty);
let mut r = Reflector {
visitor_val: visitor_val,
visitor_methods: ty::trait_methods(bcx.tcx(), visitor_trait_id),
final_bcx: final,
tydesc_ty: tydesc_ty,
bcx: bcx
};
r.visit_ty(t);
Br(r.bcx, final.llbb);
return final;
}
pub fn ast_sigil_constant(sigil: ast::Sigil) -> uint
|
{
match sigil {
ast::OwnedSigil => 2u,
ast::ManagedSigil => 3u,
ast::BorrowedSigil => 4u,
}
}
|
identifier_body
|
|
reflect.rs
|
ty;
use util::ppaux::ty_to_str;
use std::libc::c_uint;
use std::option::None;
use std::vec;
use syntax::ast::def_id;
use syntax::ast;
use syntax::ast_map::path_name;
use syntax::parse::token::special_idents;
use middle::trans::type_::Type;
pub struct Reflector {
visitor_val: ValueRef,
visitor_methods: @~[@ty::Method],
final_bcx: block,
tydesc_ty: Type,
bcx: block
}
impl Reflector {
pub fn c_uint(&mut self, u: uint) -> ValueRef {
C_uint(self.bcx.ccx(), u)
}
pub fn c_int(&mut self, i: int) -> ValueRef {
C_int(self.bcx.ccx(), i)
}
pub fn c_slice(&mut self, s: @str) -> ValueRef {
// We're careful to not use first class aggregates here because that
// will kick us off fast isel. (Issue #4352.)
let bcx = self.bcx;
let str_vstore = ty::vstore_slice(ty::re_static);
let str_ty = ty::mk_estr(bcx.tcx(), str_vstore);
let scratch = scratch_datum(bcx, str_ty, "", false);
let len = C_uint(bcx.ccx(), s.len() + 1);
let c_str = PointerCast(bcx, C_cstr(bcx.ccx(), s), Type::i8p());
Store(bcx, c_str, GEPi(bcx, scratch.val, [ 0, 0 ]));
Store(bcx, len, GEPi(bcx, scratch.val, [ 0, 1 ]));
scratch.val
}
pub fn c_size_and_align(&mut self, t: ty::t) -> ~[ValueRef] {
let tr = type_of(self.bcx.ccx(), t);
let s = machine::llsize_of_real(self.bcx.ccx(), tr);
let a = machine::llalign_of_min(self.bcx.ccx(), tr);
return ~[self.c_uint(s),
self.c_uint(a)];
}
pub fn c_tydesc(&mut self, t: ty::t) -> ValueRef {
let bcx = self.bcx;
let static_ti = get_tydesc(bcx.ccx(), t);
glue::lazily_emit_all_tydesc_glue(bcx.ccx(), static_ti);
PointerCast(bcx, static_ti.tydesc, self.tydesc_ty.ptr_to())
}
pub fn c_mt(&mut self, mt: &ty::mt) -> ~[ValueRef] {
~[self.c_uint(mt.mutbl as uint),
self.c_tydesc(mt.ty)]
}
pub fn visit(&mut self, ty_name: &str, args: &[ValueRef]) {
let tcx = self.bcx.tcx();
let mth_idx = ty::method_idx(
tcx.sess.ident_of(~"visit_" + ty_name),
*self.visitor_methods).expect(fmt!("Couldn't find visit method \
for %s", ty_name));
let mth_ty =
ty::mk_bare_fn(tcx, copy self.visitor_methods[mth_idx].fty);
let v = self.visitor_val;
debug!("passing %u args:", args.len());
let mut bcx = self.bcx;
for args.iter().enumerate().advance |(i, a)| {
debug!("arg %u: %s", i, bcx.val_to_str(*a));
}
let bool_ty = ty::mk_bool();
// XXX: Should not be BoxTraitStore!
let result = unpack_result!(bcx, callee::trans_call_inner(
self.bcx, None, mth_ty, bool_ty,
|bcx| meth::trans_trait_callee_from_llval(bcx,
mth_ty,
mth_idx,
v,
ty::BoxTraitStore,
ast::sty_region(
None,
ast::m_imm)),
ArgVals(args), None, DontAutorefArg));
let result = bool_to_i1(bcx, result);
let next_bcx = sub_block(bcx, "next");
CondBr(bcx, result, next_bcx.llbb, self.final_bcx.llbb);
self.bcx = next_bcx
}
pub fn bracketed(&mut self,
bracket_name: &str,
extra: &[ValueRef],
inner: &fn(&mut Reflector)) {
self.visit(~"enter_" + bracket_name, extra);
inner(self);
self.visit(~"leave_" + bracket_name, extra);
}
pub fn
|
(&mut self,
t: ty::t,
vstore: ty::vstore)
-> (~str, ~[ValueRef]) {
match vstore {
ty::vstore_fixed(n) => {
let extra = vec::append(~[self.c_uint(n)],
self.c_size_and_align(t));
(~"fixed", extra)
}
ty::vstore_slice(_) => (~"slice", ~[]),
ty::vstore_uniq => (~"uniq", ~[]),
ty::vstore_box => (~"box", ~[])
}
}
pub fn leaf(&mut self, name: &str) {
self.visit(name, []);
}
// Entrypoint
pub fn visit_ty(&mut self, t: ty::t) {
let bcx = self.bcx;
debug!("reflect::visit_ty %s", ty_to_str(bcx.ccx().tcx, t));
match ty::get(t).sty {
ty::ty_bot => self.leaf("bot"),
ty::ty_nil => self.leaf("nil"),
ty::ty_bool => self.leaf("bool"),
ty::ty_int(ast::ty_i) => self.leaf("int"),
ty::ty_int(ast::ty_char) => self.leaf("char"),
ty::ty_int(ast::ty_i8) => self.leaf("i8"),
ty::ty_int(ast::ty_i16) => self.leaf("i16"),
ty::ty_int(ast::ty_i32) => self.leaf("i32"),
ty::ty_int(ast::ty_i64) => self.leaf("i64"),
ty::ty_uint(ast::ty_u) => self.leaf("uint"),
ty::ty_uint(ast::ty_u8) => self.leaf("u8"),
ty::ty_uint(ast::ty_u16) => self.leaf("u16"),
ty::ty_uint(ast::ty_u32) => self.leaf("u32"),
ty::ty_uint(ast::ty_u64) => self.leaf("u64"),
ty::ty_float(ast::ty_f) => self.leaf("float"),
ty::ty_float(ast::ty_f32) => self.leaf("f32"),
ty::ty_float(ast::ty_f64) => self.leaf("f64"),
ty::ty_unboxed_vec(ref mt) => {
let values = self.c_mt(mt);
self.visit("vec", values)
}
ty::ty_estr(vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
self.visit(~"estr_" + name, extra)
}
ty::ty_evec(ref mt, vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
let extra = extra + self.c_mt(mt);
self.visit(~"evec_" + name, extra)
}
ty::ty_box(ref mt) => {
let extra = self.c_mt(mt);
self.visit("box", extra)
}
ty::ty_uniq(ref mt) => {
let extra = self.c_mt(mt);
if ty::type_contents(bcx.tcx(), t).contains_managed() {
self.visit("uniq_managed", extra)
} else {
self.visit("uniq", extra)
}
}
ty::ty_ptr(ref mt) => {
let extra = self.c_mt(mt);
self.visit("ptr", extra)
}
ty::ty_rptr(_, ref mt) => {
let extra = self.c_mt(mt);
self.visit("rptr", extra)
}
ty::ty_tup(ref tys) => {
let extra = ~[self.c_uint(tys.len())]
+ self.c_size_and_align(t);
do self.bracketed("tup", extra) |this| {
for tys.iter().enumerate().advance |(i, t)| {
let extra = ~[this.c_uint(i), this.c_tydesc(*t)];
this.visit("tup_field", extra);
}
}
}
// FIXME (#2594): fetch constants out of intrinsic
// FIXME (#4809): visitor should break out bare fns from other fns
ty::ty_closure(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let sigilval = ast_sigil_constant(fty.sigil);
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = ~[self.c_uint(pureval),
self.c_uint(sigilval),
self.c_uint(fty.sig.inputs.len()),
self.c_uint(retval)];
self.visit("enter_fn", extra);
self.visit_sig(retval, &fty.sig);
self.visit("leave_fn", extra);
}
// FIXME (#2594): fetch constants out of intrinsic:: for the
// numbers.
ty::ty_bare_fn(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let sigilval = 0u;
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = ~[self.c_uint(pureval),
self.c_uint(sigilval),
self.c_uint(fty.sig.inputs.len()),
self.c_uint(retval)];
self.visit("enter_fn", extra);
self.visit_sig(retval, &fty.sig);
self.visit("leave_fn", extra);
}
ty::ty_struct(did, ref substs) => {
let bcx = self.bcx;
let tcx = bcx.ccx().tcx;
let fields = ty::struct_fields(tcx, did, substs);
let extra = ~[self.c_uint(fields.len())]
+ self.c_size_and_align(t);
do self.bracketed("class", extra) |this| {
for fields.iter().enumerate().advance |(i, field)| {
let extra = ~[this.c_uint(i),
this.c_slice(
bcx.ccx().sess.str_of(field.ident))]
+ this.c_mt(&field.mt);
this.visit("class_field", extra);
}
}
}
// FIXME (#2595): visiting all the variants in turn is probably
// not ideal. It'll work but will get costly on big enums. Maybe
// let the visitor tell us if it wants to visit only a particular
// variant?
ty::ty_enum(did, ref substs) => {
let bcx = self.bcx;
let ccx = bcx.ccx();
let repr = adt::represent_type(bcx.ccx(), t);
let variants = ty::substd_enum_variants(ccx.tcx, did, substs);
let llptrty = type_of(ccx, t).ptr_to();
let opaquety = ty::get_opaque_ty(ccx.tcx);
let opaqueptrty = ty::mk_ptr(ccx.tcx, ty::mt { ty: opaquety, mutbl: ast::m_imm });
let make_get_disr = || {
let sub_path = bcx.fcx.path + &[path_name(special_idents::anon)];
let sym = mangle_internal_name_by_path_and_seq(ccx,
sub_path,
"get_disr");
let llfty = type_of_fn(ccx, [opaqueptrty], ty::mk_int());
let llfdecl = decl_internal_cdecl_fn(ccx.llmod, sym, llfty);
let fcx = new_fn_ctxt(ccx,
~[],
llfdecl,
ty::mk_uint(),
None);
let arg = unsafe {
//
// we know the return type of llfdecl is an int here, so
// no need for a special check to see if the return type
// is immediate.
//
llvm::LLVMGetParam(llfdecl, fcx.arg_pos(0u) as c_uint)
};
let bcx = top_scope_block(fcx, None);
let arg = BitCast(bcx, arg, llptrty);
let ret = adt::trans_get_discr(bcx, repr, arg);
Store(bcx, ret, fcx.llretptr.get());
cleanup_and_Br(bcx, bcx, fcx.llreturn);
finish_fn(fcx, bcx.llbb);
llfdecl
};
let enum_args = ~[self.c_uint(variants.len()), make_get_disr()]
+ self.c_size_and_align(t);
do self.bracketed("enum", enum_args) |this| {
for variants.iter().enumerate().advance |(i, v)| {
let name = ccx.sess.str_of(v.name);
let variant_args = ~[this.c_uint(i),
this.c_int(v.disr_val),
this.c_uint(v.args.len()),
this.c_slice(name)];
do this.bracketed("enum_variant", variant_args) |this| {
for v.args.iter().enumerate().advance |(j, a)| {
let bcx = this.bcx;
let null = C_null(llptrty);
let ptr = adt::trans_field_ptr(bcx, repr, null, v.disr_val, j);
let offset = p2i(ccx, ptr);
let field_args = ~[this.c_uint(j),
offset,
this.c_tydesc(*a)];
this.visit("enum_variant_field", field_args);
}
}
}
}
}
// Miscallaneous extra types
ty::ty_trait(_, _, _, _, _) => self.leaf("trait"),
ty::ty_infer(_) => self.leaf("infer"),
ty::ty_err => self.leaf("err"),
ty::ty_param(ref p) => {
let extra = ~[self.c_uint(p.idx)];
self.visit("param", extra)
}
ty::ty_self(*) => self.leaf("self"),
ty::ty_type => self.leaf("type"),
ty::ty_opaque_box => self.leaf("opaque_box"),
ty::ty_opaque_closure_ptr(ck) => {
let ckval = ast_sigil_constant(ck);
let extra = ~[self.c_uint(ckval)];
self.visit("closure_ptr", extra)
}
}
}
pub fn visit_sig(&mut self, retval: uint, sig: &ty::FnSig) {
for sig.inputs.iter().enumerate().advance |(i, arg)| {
let modeval = 5u; // "by copy"
let extra = ~[self.c_uint(i),
self.c_uint(modeval),
self.c_tydesc(*arg)];
self.visit("fn_input", extra);
}
let extra = ~[self.c_uint(retval),
self.c_tydesc(sig.output)];
self.visit("fn_output", extra);
}
|
vstore_name_and_extra
|
identifier_name
|
hygienic-labels-in-let.rs
|
// Copyright 2012-2014 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.
#[feature(macro_rules)];
macro_rules! loop_x {
($e: expr) => {
// $e shouldn't be able to interact with this 'x
'x: loop { $e }
}
}
macro_rules! run_once {
($e: expr) => {
// ditto
'x: for _ in range(0, 1) { $e }
}
}
pub fn main()
|
};
assert_eq!(k, 1i);
let n = {
'x: for _ in range(0, 1) {
// ditto
run_once!(continue 'x);
i += 1;
}
i + 1
};
assert_eq!(n, 1i);
}
|
{
let mut i = 0i;
let j = {
'x: loop {
// this 'x should refer to the outer loop, lexically
loop_x!(break 'x);
i += 1;
}
i + 1
};
assert_eq!(j, 1i);
let k = {
'x: for _ in range(0, 1) {
// ditto
loop_x!(break 'x);
i += 1;
}
i + 1
|
identifier_body
|
hygienic-labels-in-let.rs
|
// Copyright 2012-2014 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.
#[feature(macro_rules)];
macro_rules! loop_x {
($e: expr) => {
// $e shouldn't be able to interact with this 'x
'x: loop { $e }
}
}
macro_rules! run_once {
($e: expr) => {
// ditto
'x: for _ in range(0, 1) { $e }
}
}
pub fn
|
() {
let mut i = 0i;
let j = {
'x: loop {
// this 'x should refer to the outer loop, lexically
loop_x!(break 'x);
i += 1;
}
i + 1
};
assert_eq!(j, 1i);
let k = {
'x: for _ in range(0, 1) {
// ditto
loop_x!(break 'x);
i += 1;
}
i + 1
};
assert_eq!(k, 1i);
let n = {
'x: for _ in range(0, 1) {
// ditto
run_once!(continue 'x);
i += 1;
}
i + 1
};
assert_eq!(n, 1i);
}
|
main
|
identifier_name
|
hygienic-labels-in-let.rs
|
// Copyright 2012-2014 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.
#[feature(macro_rules)];
macro_rules! loop_x {
($e: expr) => {
// $e shouldn't be able to interact with this 'x
'x: loop { $e }
}
|
// ditto
'x: for _ in range(0, 1) { $e }
}
}
pub fn main() {
let mut i = 0i;
let j = {
'x: loop {
// this 'x should refer to the outer loop, lexically
loop_x!(break 'x);
i += 1;
}
i + 1
};
assert_eq!(j, 1i);
let k = {
'x: for _ in range(0, 1) {
// ditto
loop_x!(break 'x);
i += 1;
}
i + 1
};
assert_eq!(k, 1i);
let n = {
'x: for _ in range(0, 1) {
// ditto
run_once!(continue 'x);
i += 1;
}
i + 1
};
assert_eq!(n, 1i);
}
|
}
macro_rules! run_once {
($e: expr) => {
|
random_line_split
|
sem.rs
|
//! A rewrite of uapi/linux/sem.h
pub const SEM_UNDO: ::c_int = 0x1000; //TODO Check this to make sure it's a c_int
///Get sempid
pub const GETPID: ::c_int = 11;
///Get semval
pub const GETVAL: ::c_int = 12;
///Get all semvals
pub const GETALL: ::c_int = 13;
///Get semncnt
pub const GETNCNT: ::c_int = 14;
///Get semzcnt
pub const GETZCNT: ::c_int = 15;
///Set semval
pub const SETVAL: ::c_int = 16;
///Set all semvals
pub const SETALL: ::c_int = 17;
pub const SEM_STAT: ::c_int = 18;
pub const SEM_INFO: ::c_int = 19;
/*///Obsolete, used for backwards compatibility and libc5 compiles
pub struct semid_ds {
pub sem_perm: ::ipc_perm,
|
pub sem_ctime: ::__kernel_time_t,
pub sem_base: *mut ::sem,
pub sem_pending: *mut ::sem_queue,
pub sem_pending_last: *mut ::sem_queue,
pub undo: *mut ::sem_undo,
pub sem_nsems: ::c_ushort
} TODO: Complete enough to enable this */
///The semop system call takes an array of these
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct sembuf {
///The semaphore's index in the array
pub sem_num: ::c_ushort,
///The semaphore operation
pub sem_op: ::c_short,
///The operation's flags
pub sem_flg: ::c_short
}
///The argument for semctl system calls
#[repr(C)]
pub enum semun {
val(::c_int),
//buf(*mut semid_ds),
array(*mut ::c_ushort),
__buf(*mut seminfo),
__pad
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct seminfo {
pub semmap: ::c_int,
pub semmni: ::c_int,
pub semmns: ::c_int,
pub semmnu: ::c_int,
pub semmsl: ::c_int,
pub semopm: ::c_int,
pub semume: ::c_int,
pub semusz: ::c_int,
pub semvmx: ::c_int,
pub semaem: ::c_int
}
/// <= IPCMNI: Max number of semaphore identifiers
pub const SEMMNI: ::c_int = 32000;
/// <= INT_MAX: Max number of semaphores per ID
pub const SEMMSL: ::c_int = 32000;
/// <= INT_MAX: Max nubmer of semaphores in the system
pub const SEMMNS: ::c_int = SEMMNI * SEMMSL;
/// <= 1000: Max number of operations per semop call
pub const SEMOPM: ::c_int = 500;
/// <= 32767: Semaphore maximum value
pub const SEMVMX: ::c_int = 32767;
/// Adjust on exit max value
pub const SEMAEM: ::c_int = SEMVMX;
///Max number of undo entries per process
pub const SEMUME: ::c_int = SEMOPM;
///Number of undo structures system wide
pub const SEMMNU: ::c_int = SEMMNS;
///Number of entries in the semaphore map
pub const SEMMAP: ::c_int = SEMMNS;
///Sizeof struct sem_undo
pub const SEMUSZ: ::c_int = 20;
|
pub sem_otime: ::__kernel_time_t,
|
random_line_split
|
sem.rs
|
//! A rewrite of uapi/linux/sem.h
pub const SEM_UNDO: ::c_int = 0x1000; //TODO Check this to make sure it's a c_int
///Get sempid
pub const GETPID: ::c_int = 11;
///Get semval
pub const GETVAL: ::c_int = 12;
///Get all semvals
pub const GETALL: ::c_int = 13;
///Get semncnt
pub const GETNCNT: ::c_int = 14;
///Get semzcnt
pub const GETZCNT: ::c_int = 15;
///Set semval
pub const SETVAL: ::c_int = 16;
///Set all semvals
pub const SETALL: ::c_int = 17;
pub const SEM_STAT: ::c_int = 18;
pub const SEM_INFO: ::c_int = 19;
/*///Obsolete, used for backwards compatibility and libc5 compiles
pub struct semid_ds {
pub sem_perm: ::ipc_perm,
pub sem_otime: ::__kernel_time_t,
pub sem_ctime: ::__kernel_time_t,
pub sem_base: *mut ::sem,
pub sem_pending: *mut ::sem_queue,
pub sem_pending_last: *mut ::sem_queue,
pub undo: *mut ::sem_undo,
pub sem_nsems: ::c_ushort
} TODO: Complete enough to enable this */
///The semop system call takes an array of these
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct
|
{
///The semaphore's index in the array
pub sem_num: ::c_ushort,
///The semaphore operation
pub sem_op: ::c_short,
///The operation's flags
pub sem_flg: ::c_short
}
///The argument for semctl system calls
#[repr(C)]
pub enum semun {
val(::c_int),
//buf(*mut semid_ds),
array(*mut ::c_ushort),
__buf(*mut seminfo),
__pad
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct seminfo {
pub semmap: ::c_int,
pub semmni: ::c_int,
pub semmns: ::c_int,
pub semmnu: ::c_int,
pub semmsl: ::c_int,
pub semopm: ::c_int,
pub semume: ::c_int,
pub semusz: ::c_int,
pub semvmx: ::c_int,
pub semaem: ::c_int
}
/// <= IPCMNI: Max number of semaphore identifiers
pub const SEMMNI: ::c_int = 32000;
/// <= INT_MAX: Max number of semaphores per ID
pub const SEMMSL: ::c_int = 32000;
/// <= INT_MAX: Max nubmer of semaphores in the system
pub const SEMMNS: ::c_int = SEMMNI * SEMMSL;
/// <= 1000: Max number of operations per semop call
pub const SEMOPM: ::c_int = 500;
/// <= 32767: Semaphore maximum value
pub const SEMVMX: ::c_int = 32767;
/// Adjust on exit max value
pub const SEMAEM: ::c_int = SEMVMX;
///Max number of undo entries per process
pub const SEMUME: ::c_int = SEMOPM;
///Number of undo structures system wide
pub const SEMMNU: ::c_int = SEMMNS;
///Number of entries in the semaphore map
pub const SEMMAP: ::c_int = SEMMNS;
///Sizeof struct sem_undo
pub const SEMUSZ: ::c_int = 20;
|
sembuf
|
identifier_name
|
uievent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, UIEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::js::{JS, MutNullableHeap, RootedReference};
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId, EventBubbles, EventCancelable};
use dom::window::Window;
use util::str::DOMString;
use std::cell::Cell;
use std::default::Default;
#[derive(JSTraceable, PartialEq, HeapSizeOf)]
pub enum UIEventTypeId {
MouseEvent,
KeyboardEvent,
UIEvent,
}
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#interface-UIEvent
#[dom_struct]
pub struct UIEvent {
event: Event,
view: MutNullableHeap<JS<Window>>,
detail: Cell<i32>
}
impl UIEventDerived for Event {
fn is_uievent(&self) -> bool {
match *self.type_id() {
EventTypeId::UIEvent(_) => true,
_ => false
}
}
}
impl UIEvent {
pub fn new_inherited(type_id: UIEventTypeId) -> UIEvent {
UIEvent {
event: Event::new_inherited(EventTypeId::UIEvent(type_id)),
view: Default::default(),
detail: Cell::new(0),
}
}
pub fn new_uninitialized(window: &Window) -> Root<UIEvent> {
reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId::UIEvent),
GlobalRef::Window(window),
UIEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: DOMString,
can_bubble: EventBubbles,
cancelable: EventCancelable,
view: Option<&Window>,
detail: i32) -> Root<UIEvent> {
|
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> {
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
let event = UIEvent::new(global.as_window(), type_,
bubbles, cancelable,
init.view.r(), init.detail);
Ok(event)
}
}
impl UIEventMethods for UIEvent {
// https://w3c.github.io/uievents/#widl-UIEvent-view
fn GetView(&self) -> Option<Root<Window>> {
self.view.get().map(Root::from_rooted)
}
// https://w3c.github.io/uievents/#widl-UIEvent-detail
fn Detail(&self) -> i32 {
self.detail.get()
}
// https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent
fn InitUIEvent(&self,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Option<&Window>,
detail: i32) {
let event: &Event = EventCast::from_ref(self);
if event.dispatching() {
return;
}
event.InitEvent(type_, can_bubble, cancelable);
self.view.set(view.map(JS::from_ref));
self.detail.set(detail);
}
}
|
let ev = UIEvent::new_uninitialized(window);
ev.r().InitUIEvent(type_, can_bubble == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable, view, detail);
ev
}
|
random_line_split
|
uievent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, UIEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::js::{JS, MutNullableHeap, RootedReference};
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId, EventBubbles, EventCancelable};
use dom::window::Window;
use util::str::DOMString;
use std::cell::Cell;
use std::default::Default;
#[derive(JSTraceable, PartialEq, HeapSizeOf)]
pub enum UIEventTypeId {
MouseEvent,
KeyboardEvent,
UIEvent,
}
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#interface-UIEvent
#[dom_struct]
pub struct UIEvent {
event: Event,
view: MutNullableHeap<JS<Window>>,
detail: Cell<i32>
}
impl UIEventDerived for Event {
fn is_uievent(&self) -> bool {
match *self.type_id() {
EventTypeId::UIEvent(_) => true,
_ => false
}
}
}
impl UIEvent {
pub fn new_inherited(type_id: UIEventTypeId) -> UIEvent {
UIEvent {
event: Event::new_inherited(EventTypeId::UIEvent(type_id)),
view: Default::default(),
detail: Cell::new(0),
}
}
pub fn new_uninitialized(window: &Window) -> Root<UIEvent> {
reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId::UIEvent),
GlobalRef::Window(window),
UIEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: DOMString,
can_bubble: EventBubbles,
cancelable: EventCancelable,
view: Option<&Window>,
detail: i32) -> Root<UIEvent> {
let ev = UIEvent::new_uninitialized(window);
ev.r().InitUIEvent(type_, can_bubble == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable, view, detail);
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> {
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else
|
;
let event = UIEvent::new(global.as_window(), type_,
bubbles, cancelable,
init.view.r(), init.detail);
Ok(event)
}
}
impl UIEventMethods for UIEvent {
// https://w3c.github.io/uievents/#widl-UIEvent-view
fn GetView(&self) -> Option<Root<Window>> {
self.view.get().map(Root::from_rooted)
}
// https://w3c.github.io/uievents/#widl-UIEvent-detail
fn Detail(&self) -> i32 {
self.detail.get()
}
// https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent
fn InitUIEvent(&self,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Option<&Window>,
detail: i32) {
let event: &Event = EventCast::from_ref(self);
if event.dispatching() {
return;
}
event.InitEvent(type_, can_bubble, cancelable);
self.view.set(view.map(JS::from_ref));
self.detail.set(detail);
}
}
|
{
EventCancelable::NotCancelable
}
|
conditional_block
|
uievent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, UIEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::js::{JS, MutNullableHeap, RootedReference};
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId, EventBubbles, EventCancelable};
use dom::window::Window;
use util::str::DOMString;
use std::cell::Cell;
use std::default::Default;
#[derive(JSTraceable, PartialEq, HeapSizeOf)]
pub enum UIEventTypeId {
MouseEvent,
KeyboardEvent,
UIEvent,
}
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#interface-UIEvent
#[dom_struct]
pub struct UIEvent {
event: Event,
view: MutNullableHeap<JS<Window>>,
detail: Cell<i32>
}
impl UIEventDerived for Event {
fn is_uievent(&self) -> bool {
match *self.type_id() {
EventTypeId::UIEvent(_) => true,
_ => false
}
}
}
impl UIEvent {
pub fn new_inherited(type_id: UIEventTypeId) -> UIEvent {
UIEvent {
event: Event::new_inherited(EventTypeId::UIEvent(type_id)),
view: Default::default(),
detail: Cell::new(0),
}
}
pub fn new_uninitialized(window: &Window) -> Root<UIEvent> {
reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId::UIEvent),
GlobalRef::Window(window),
UIEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: DOMString,
can_bubble: EventBubbles,
cancelable: EventCancelable,
view: Option<&Window>,
detail: i32) -> Root<UIEvent> {
let ev = UIEvent::new_uninitialized(window);
ev.r().InitUIEvent(type_, can_bubble == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable, view, detail);
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> {
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
let event = UIEvent::new(global.as_window(), type_,
bubbles, cancelable,
init.view.r(), init.detail);
Ok(event)
}
}
impl UIEventMethods for UIEvent {
// https://w3c.github.io/uievents/#widl-UIEvent-view
fn GetView(&self) -> Option<Root<Window>> {
self.view.get().map(Root::from_rooted)
}
// https://w3c.github.io/uievents/#widl-UIEvent-detail
fn
|
(&self) -> i32 {
self.detail.get()
}
// https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent
fn InitUIEvent(&self,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Option<&Window>,
detail: i32) {
let event: &Event = EventCast::from_ref(self);
if event.dispatching() {
return;
}
event.InitEvent(type_, can_bubble, cancelable);
self.view.set(view.map(JS::from_ref));
self.detail.set(detail);
}
}
|
Detail
|
identifier_name
|
board.rs
|
use std::fmt;
use std::ops::{Not,Mul};
use pattern::Pattern;
pub struct GameBoard {
field: [[State;3];3]
}
impl GameBoard {
pub fn new() -> GameBoard {
GameBoard {
field: [[State::Empty;3];3]
}
}
pub fn set_at(& mut self, who: State, at: (usize, usize)) {
self.field[at.0][at.1] = who;
}
pub fn get_at(&self, at: (usize, usize)) -> State {
self.field[at.0][at.1]
}
pub fn empty_count(&self) -> usize {
let mut counter = 0usize;
for i in self.field.iter() {
for j in i.iter() {
match *j {
State::Empty => counter += 1,
_ => {},
}
}
}
counter
}
}
#[derive(Copy,Clone,PartialEq)]
pub enum State {
Empty, X, O
}
impl Not for State {
type Output = State;
fn not(self) -> State {
match self {
State::X => State::O,
State::O => State::X,
State::Empty => State::Empty
}
}
}
impl Mul<usize> for State {
type Output = Pattern;
fn mul(self, rhs: usize) -> Pattern {
let mut p = Pattern::new();
p.set(self, rhs);
p
}
}
impl fmt::Debug for State {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
fmt.pad(out)
}
}
|
let out = match *self {
State::Empty => "_",
State::X => "X",
State::O => "O"
};
|
random_line_split
|
board.rs
|
use std::fmt;
use std::ops::{Not,Mul};
use pattern::Pattern;
pub struct GameBoard {
field: [[State;3];3]
}
impl GameBoard {
pub fn new() -> GameBoard {
GameBoard {
field: [[State::Empty;3];3]
}
}
pub fn set_at(& mut self, who: State, at: (usize, usize)) {
self.field[at.0][at.1] = who;
}
pub fn get_at(&self, at: (usize, usize)) -> State {
self.field[at.0][at.1]
}
pub fn
|
(&self) -> usize {
let mut counter = 0usize;
for i in self.field.iter() {
for j in i.iter() {
match *j {
State::Empty => counter += 1,
_ => {},
}
}
}
counter
}
}
#[derive(Copy,Clone,PartialEq)]
pub enum State {
Empty, X, O
}
impl Not for State {
type Output = State;
fn not(self) -> State {
match self {
State::X => State::O,
State::O => State::X,
State::Empty => State::Empty
}
}
}
impl Mul<usize> for State {
type Output = Pattern;
fn mul(self, rhs: usize) -> Pattern {
let mut p = Pattern::new();
p.set(self, rhs);
p
}
}
impl fmt::Debug for State {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let out = match *self {
State::Empty => "_",
State::X => "X",
State::O => "O"
};
fmt.pad(out)
}
}
|
empty_count
|
identifier_name
|
board.rs
|
use std::fmt;
use std::ops::{Not,Mul};
use pattern::Pattern;
pub struct GameBoard {
field: [[State;3];3]
}
impl GameBoard {
pub fn new() -> GameBoard {
GameBoard {
field: [[State::Empty;3];3]
}
}
pub fn set_at(& mut self, who: State, at: (usize, usize)) {
self.field[at.0][at.1] = who;
}
pub fn get_at(&self, at: (usize, usize)) -> State {
self.field[at.0][at.1]
}
pub fn empty_count(&self) -> usize {
let mut counter = 0usize;
for i in self.field.iter() {
for j in i.iter() {
match *j {
State::Empty => counter += 1,
_ => {},
}
}
}
counter
}
}
#[derive(Copy,Clone,PartialEq)]
pub enum State {
Empty, X, O
}
impl Not for State {
type Output = State;
fn not(self) -> State
|
}
impl Mul<usize> for State {
type Output = Pattern;
fn mul(self, rhs: usize) -> Pattern {
let mut p = Pattern::new();
p.set(self, rhs);
p
}
}
impl fmt::Debug for State {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let out = match *self {
State::Empty => "_",
State::X => "X",
State::O => "O"
};
fmt.pad(out)
}
}
|
{
match self {
State::X => State::O,
State::O => State::X,
State::Empty => State::Empty
}
}
|
identifier_body
|
ed25519.rs
|
use super::CryptoType;
use utils::crypto::ed25519::ED25519;
use errors::common::CommonError;
pub struct ED25519Signus {}
impl ED25519Signus {
pub fn new() -> ED25519Signus {
ED25519Signus {}
}
}
impl CryptoType for ED25519Signus {
fn encrypt(&self, private_key: &[u8], public_key: &[u8], doc: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::encrypt(private_key, public_key, doc, nonce)
}
fn decrypt(&self, private_key: &[u8], public_key: &[u8], doc: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::decrypt(private_key, public_key, doc, nonce)
}
fn gen_nonce(&self) -> Vec<u8> {
ED25519::gen_nonce()
}
fn create_key_pair_for_signature(&self, seed: Option<&[u8]>) -> Result<(Vec<u8>, Vec<u8>), CommonError> {
ED25519::create_key_pair_for_signature(seed)
}
fn sign(&self, private_key: &[u8], doc: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::sign(private_key, doc)
}
fn verify(&self, public_key: &[u8], doc: &[u8], signature: &[u8]) -> Result<bool, CommonError> {
ED25519::verify(public_key, doc, signature)
}
fn verkey_to_public_key(&self, vk: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::vk_to_curve25519(vk)
}
fn
|
(&self, sk: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::sk_to_curve25519(sk)
}
}
|
signkey_to_private_key
|
identifier_name
|
ed25519.rs
|
use super::CryptoType;
use utils::crypto::ed25519::ED25519;
use errors::common::CommonError;
pub struct ED25519Signus {}
|
impl ED25519Signus {
pub fn new() -> ED25519Signus {
ED25519Signus {}
}
}
impl CryptoType for ED25519Signus {
fn encrypt(&self, private_key: &[u8], public_key: &[u8], doc: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::encrypt(private_key, public_key, doc, nonce)
}
fn decrypt(&self, private_key: &[u8], public_key: &[u8], doc: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::decrypt(private_key, public_key, doc, nonce)
}
fn gen_nonce(&self) -> Vec<u8> {
ED25519::gen_nonce()
}
fn create_key_pair_for_signature(&self, seed: Option<&[u8]>) -> Result<(Vec<u8>, Vec<u8>), CommonError> {
ED25519::create_key_pair_for_signature(seed)
}
fn sign(&self, private_key: &[u8], doc: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::sign(private_key, doc)
}
fn verify(&self, public_key: &[u8], doc: &[u8], signature: &[u8]) -> Result<bool, CommonError> {
ED25519::verify(public_key, doc, signature)
}
fn verkey_to_public_key(&self, vk: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::vk_to_curve25519(vk)
}
fn signkey_to_private_key(&self, sk: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::sk_to_curve25519(sk)
}
}
|
random_line_split
|
|
ed25519.rs
|
use super::CryptoType;
use utils::crypto::ed25519::ED25519;
use errors::common::CommonError;
pub struct ED25519Signus {}
impl ED25519Signus {
pub fn new() -> ED25519Signus {
ED25519Signus {}
}
}
impl CryptoType for ED25519Signus {
fn encrypt(&self, private_key: &[u8], public_key: &[u8], doc: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::encrypt(private_key, public_key, doc, nonce)
}
fn decrypt(&self, private_key: &[u8], public_key: &[u8], doc: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::decrypt(private_key, public_key, doc, nonce)
}
fn gen_nonce(&self) -> Vec<u8>
|
fn create_key_pair_for_signature(&self, seed: Option<&[u8]>) -> Result<(Vec<u8>, Vec<u8>), CommonError> {
ED25519::create_key_pair_for_signature(seed)
}
fn sign(&self, private_key: &[u8], doc: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::sign(private_key, doc)
}
fn verify(&self, public_key: &[u8], doc: &[u8], signature: &[u8]) -> Result<bool, CommonError> {
ED25519::verify(public_key, doc, signature)
}
fn verkey_to_public_key(&self, vk: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::vk_to_curve25519(vk)
}
fn signkey_to_private_key(&self, sk: &[u8]) -> Result<Vec<u8>, CommonError> {
ED25519::sk_to_curve25519(sk)
}
}
|
{
ED25519::gen_nonce()
}
|
identifier_body
|
pipe.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use ffi::CString;
use libc;
use mem;
use sync::{Arc, Mutex};
use sync::atomic::{AtomicBool, Ordering};
use old_io::{self, IoResult, IoError};
use sys::{self, timer, retry, c, set_nonblocking, wouldblock};
use sys::fs::{fd_t, FileDesc};
use sys_common::net::*;
use sys_common::net::SocketStatus::*;
use sys_common::{eof, mkerr_libc};
fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> {
match unsafe { libc::socket(libc::AF_UNIX, ty, 0) } {
-1 => Err(super::last_error()),
fd => Ok(fd)
}
}
fn addr_to_sockaddr_un(addr: &CString,
storage: &mut libc::sockaddr_storage)
-> IoResult<libc::socklen_t> {
// the sun_path length is limited to SUN_LEN (with null)
assert!(mem::size_of::<libc::sockaddr_storage>() >=
mem::size_of::<libc::sockaddr_un>());
let s = unsafe { &mut *(storage as *mut _ as *mut libc::sockaddr_un) };
let len = addr.as_bytes().len();
if len > s.sun_path.len() - 1 {
return Err(IoError {
kind: old_io::InvalidInput,
desc: "invalid argument: path must be smaller than SUN_LEN",
detail: None,
})
}
s.sun_family = libc::AF_UNIX as libc::sa_family_t;
for (slot, value) in s.sun_path.iter_mut().zip(addr.as_bytes().iter()) {
*slot = *value as libc::c_char;
}
// count the null terminator
let len = mem::size_of::<libc::sa_family_t>() + len + 1;
return Ok(len as libc::socklen_t);
}
struct Inner {
fd: fd_t,
// Unused on Linux, where this lock is not necessary.
#[allow(dead_code)]
lock: Mutex<()>,
}
impl Inner {
fn new(fd: fd_t) -> Inner {
Inner { fd: fd, lock: Mutex::new(()) }
}
}
impl Drop for Inner {
fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } }
}
fn connect(addr: &CString, ty: libc::c_int,
timeout: Option<u64>) -> IoResult<Inner> {
let mut storage = unsafe { mem::zeroed() };
let len = try!(addr_to_sockaddr_un(addr, &mut storage));
let inner = Inner::new(try!(unix_socket(ty)));
let addrp = &storage as *const _ as *const libc::sockaddr;
match timeout {
None => {
match retry(|| unsafe { libc::connect(inner.fd, addrp, len) }) {
-1 => Err(super::last_error()),
_ => Ok(inner)
}
}
Some(timeout_ms) => {
try!(connect_timeout(inner.fd, addrp, len, timeout_ms));
Ok(inner)
}
}
}
fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> {
let mut storage = unsafe { mem::zeroed() };
let len = try!(addr_to_sockaddr_un(addr, &mut storage));
let inner = Inner::new(try!(unix_socket(ty)));
let addrp = &storage as *const _ as *const libc::sockaddr;
match unsafe {
libc::bind(inner.fd, addrp, len)
} {
-1 => Err(super::last_error()),
_ => Ok(inner)
}
}
////////////////////////////////////////////////////////////////////////////////
// Unix Streams
////////////////////////////////////////////////////////////////////////////////
pub struct UnixStream {
inner: Arc<Inner>,
read_deadline: u64,
write_deadline: u64,
}
impl UnixStream {
pub fn connect(addr: &CString,
timeout: Option<u64>) -> IoResult<UnixStream> {
connect(addr, libc::SOCK_STREAM, timeout).map(|inner| {
UnixStream::new(Arc::new(inner))
})
}
fn new(inner: Arc<Inner>) -> UnixStream {
UnixStream {
inner: inner,
read_deadline: 0,
write_deadline: 0,
}
}
pub fn fd(&self) -> fd_t { self.inner.fd }
#[cfg(target_os = "linux")]
fn lock_nonblocking(&self) {}
#[cfg(not(target_os = "linux"))]
fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
let ret = Guard {
fd: self.fd(),
guard: unsafe { self.inner.lock.lock().unwrap() },
};
assert!(set_nonblocking(self.fd(), true).is_ok());
ret
}
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let fd = self.fd();
let dolock = || self.lock_nonblocking();
let doread = |nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recv(fd,
buf.as_mut_ptr() as *mut libc::c_void,
buf.len() as libc::size_t,
flags) as libc::c_int
};
read(fd, self.read_deadline, dolock, doread)
}
pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let fd = self.fd();
let dolock = || self.lock_nonblocking();
let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *const _,
len as libc::size_t,
flags) as i64
};
match write(fd, self.write_deadline, buf, true, dolock, dowrite) {
Ok(_) => Ok(()),
Err(e) => Err(e)
}
}
pub fn close_write(&mut self) -> IoResult<()> {
mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) })
}
pub fn close_read(&mut self) -> IoResult<()> {
mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_RD) })
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
let deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
self.read_deadline = deadline;
self.write_deadline = deadline;
}
pub fn set_read_timeout(&mut self, timeout: Option<u64>) {
self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn set_write_timeout(&mut self, timeout: Option<u64>) {
self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
}
impl Clone for UnixStream {
fn clone(&self) -> UnixStream {
UnixStream::new(self.inner.clone())
}
}
////////////////////////////////////////////////////////////////////////////////
// Unix Listener
////////////////////////////////////////////////////////////////////////////////
pub struct UnixListener {
inner: Inner,
path: CString,
}
// we currently own the CString, so these impls should be safe
unsafe impl Send for UnixListener {}
unsafe impl Sync for UnixListener {}
impl UnixListener {
pub fn bind(addr: &CString) -> IoResult<UnixListener> {
bind(addr, libc::SOCK_STREAM).map(|fd| {
UnixListener { inner: fd, path: addr.clone() }
})
}
pub fn fd(&self) -> fd_t { self.inner.fd }
pub fn listen(self) -> IoResult<UnixAcceptor> {
match unsafe { libc::listen(self.fd(), 128) } {
-1 => Err(super::last_error()),
_ => {
let (reader, writer) = try!(unsafe { sys::os::pipe() });
try!(set_nonblocking(reader.fd(), true));
try!(set_nonblocking(writer.fd(), true));
try!(set_nonblocking(self.fd(), true));
Ok(UnixAcceptor {
inner: Arc::new(AcceptorInner {
listener: self,
reader: reader,
writer: writer,
closed: AtomicBool::new(false),
}),
deadline: 0,
})
}
}
}
}
pub struct UnixAcceptor {
inner: Arc<AcceptorInner>,
deadline: u64,
}
struct AcceptorInner {
listener: UnixListener,
reader: FileDesc,
writer: FileDesc,
closed: AtomicBool,
}
impl UnixAcceptor {
pub fn fd(&self) -> fd_t { self.inner.listener.fd() }
pub fn accept(&mut self) -> IoResult<UnixStream> {
let deadline = if self.deadline == 0 {None} else {Some(self.deadline)};
while!self.inner.closed.load(Ordering::SeqCst) {
unsafe {
let mut storage: libc::sockaddr_storage = mem::zeroed();
let storagep = &mut storage as *mut libc::sockaddr_storage;
let size = mem::size_of::<libc::sockaddr_storage>();
let mut size = size as libc::socklen_t;
match retry(|| {
libc::accept(self.fd(),
storagep as *mut libc::sockaddr,
&mut size as *mut libc::socklen_t) as libc::c_int
}) {
-1 if wouldblock() => {}
-1 => return Err(super::last_error()),
fd => return Ok(UnixStream::new(Arc::new(Inner::new(fd)))),
}
}
try!(await(&[self.fd(), self.inner.reader.fd()],
deadline, Readable));
}
Err(eof())
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
|
let fd = FileDesc::new(self.inner.writer.fd(), false);
match fd.write(&[0]) {
Ok(..) => Ok(()),
Err(..) if wouldblock() => Ok(()),
Err(e) => Err(e),
}
}
}
impl Clone for UnixAcceptor {
fn clone(&self) -> UnixAcceptor {
UnixAcceptor { inner: self.inner.clone(), deadline: 0 }
}
}
impl Drop for UnixListener {
fn drop(&mut self) {
// Unlink the path to the socket to ensure that it doesn't linger. We're
// careful to unlink the path before we close the file descriptor to
// prevent races where we unlink someone else's path.
unsafe {
let _ = libc::unlink(self.path.as_ptr());
}
}
}
|
pub fn close_accept(&mut self) -> IoResult<()> {
self.inner.closed.store(true, Ordering::SeqCst);
|
random_line_split
|
pipe.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use ffi::CString;
use libc;
use mem;
use sync::{Arc, Mutex};
use sync::atomic::{AtomicBool, Ordering};
use old_io::{self, IoResult, IoError};
use sys::{self, timer, retry, c, set_nonblocking, wouldblock};
use sys::fs::{fd_t, FileDesc};
use sys_common::net::*;
use sys_common::net::SocketStatus::*;
use sys_common::{eof, mkerr_libc};
fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> {
match unsafe { libc::socket(libc::AF_UNIX, ty, 0) } {
-1 => Err(super::last_error()),
fd => Ok(fd)
}
}
fn addr_to_sockaddr_un(addr: &CString,
storage: &mut libc::sockaddr_storage)
-> IoResult<libc::socklen_t> {
// the sun_path length is limited to SUN_LEN (with null)
assert!(mem::size_of::<libc::sockaddr_storage>() >=
mem::size_of::<libc::sockaddr_un>());
let s = unsafe { &mut *(storage as *mut _ as *mut libc::sockaddr_un) };
let len = addr.as_bytes().len();
if len > s.sun_path.len() - 1 {
return Err(IoError {
kind: old_io::InvalidInput,
desc: "invalid argument: path must be smaller than SUN_LEN",
detail: None,
})
}
s.sun_family = libc::AF_UNIX as libc::sa_family_t;
for (slot, value) in s.sun_path.iter_mut().zip(addr.as_bytes().iter()) {
*slot = *value as libc::c_char;
}
// count the null terminator
let len = mem::size_of::<libc::sa_family_t>() + len + 1;
return Ok(len as libc::socklen_t);
}
struct Inner {
fd: fd_t,
// Unused on Linux, where this lock is not necessary.
#[allow(dead_code)]
lock: Mutex<()>,
}
impl Inner {
fn new(fd: fd_t) -> Inner {
Inner { fd: fd, lock: Mutex::new(()) }
}
}
impl Drop for Inner {
fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } }
}
fn connect(addr: &CString, ty: libc::c_int,
timeout: Option<u64>) -> IoResult<Inner> {
let mut storage = unsafe { mem::zeroed() };
let len = try!(addr_to_sockaddr_un(addr, &mut storage));
let inner = Inner::new(try!(unix_socket(ty)));
let addrp = &storage as *const _ as *const libc::sockaddr;
match timeout {
None => {
match retry(|| unsafe { libc::connect(inner.fd, addrp, len) }) {
-1 => Err(super::last_error()),
_ => Ok(inner)
}
}
Some(timeout_ms) => {
try!(connect_timeout(inner.fd, addrp, len, timeout_ms));
Ok(inner)
}
}
}
fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> {
let mut storage = unsafe { mem::zeroed() };
let len = try!(addr_to_sockaddr_un(addr, &mut storage));
let inner = Inner::new(try!(unix_socket(ty)));
let addrp = &storage as *const _ as *const libc::sockaddr;
match unsafe {
libc::bind(inner.fd, addrp, len)
} {
-1 => Err(super::last_error()),
_ => Ok(inner)
}
}
////////////////////////////////////////////////////////////////////////////////
// Unix Streams
////////////////////////////////////////////////////////////////////////////////
pub struct UnixStream {
inner: Arc<Inner>,
read_deadline: u64,
write_deadline: u64,
}
impl UnixStream {
pub fn
|
(addr: &CString,
timeout: Option<u64>) -> IoResult<UnixStream> {
connect(addr, libc::SOCK_STREAM, timeout).map(|inner| {
UnixStream::new(Arc::new(inner))
})
}
fn new(inner: Arc<Inner>) -> UnixStream {
UnixStream {
inner: inner,
read_deadline: 0,
write_deadline: 0,
}
}
pub fn fd(&self) -> fd_t { self.inner.fd }
#[cfg(target_os = "linux")]
fn lock_nonblocking(&self) {}
#[cfg(not(target_os = "linux"))]
fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
let ret = Guard {
fd: self.fd(),
guard: unsafe { self.inner.lock.lock().unwrap() },
};
assert!(set_nonblocking(self.fd(), true).is_ok());
ret
}
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let fd = self.fd();
let dolock = || self.lock_nonblocking();
let doread = |nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recv(fd,
buf.as_mut_ptr() as *mut libc::c_void,
buf.len() as libc::size_t,
flags) as libc::c_int
};
read(fd, self.read_deadline, dolock, doread)
}
pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let fd = self.fd();
let dolock = || self.lock_nonblocking();
let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *const _,
len as libc::size_t,
flags) as i64
};
match write(fd, self.write_deadline, buf, true, dolock, dowrite) {
Ok(_) => Ok(()),
Err(e) => Err(e)
}
}
pub fn close_write(&mut self) -> IoResult<()> {
mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) })
}
pub fn close_read(&mut self) -> IoResult<()> {
mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_RD) })
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
let deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
self.read_deadline = deadline;
self.write_deadline = deadline;
}
pub fn set_read_timeout(&mut self, timeout: Option<u64>) {
self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn set_write_timeout(&mut self, timeout: Option<u64>) {
self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
}
impl Clone for UnixStream {
fn clone(&self) -> UnixStream {
UnixStream::new(self.inner.clone())
}
}
////////////////////////////////////////////////////////////////////////////////
// Unix Listener
////////////////////////////////////////////////////////////////////////////////
pub struct UnixListener {
inner: Inner,
path: CString,
}
// we currently own the CString, so these impls should be safe
unsafe impl Send for UnixListener {}
unsafe impl Sync for UnixListener {}
impl UnixListener {
pub fn bind(addr: &CString) -> IoResult<UnixListener> {
bind(addr, libc::SOCK_STREAM).map(|fd| {
UnixListener { inner: fd, path: addr.clone() }
})
}
pub fn fd(&self) -> fd_t { self.inner.fd }
pub fn listen(self) -> IoResult<UnixAcceptor> {
match unsafe { libc::listen(self.fd(), 128) } {
-1 => Err(super::last_error()),
_ => {
let (reader, writer) = try!(unsafe { sys::os::pipe() });
try!(set_nonblocking(reader.fd(), true));
try!(set_nonblocking(writer.fd(), true));
try!(set_nonblocking(self.fd(), true));
Ok(UnixAcceptor {
inner: Arc::new(AcceptorInner {
listener: self,
reader: reader,
writer: writer,
closed: AtomicBool::new(false),
}),
deadline: 0,
})
}
}
}
}
pub struct UnixAcceptor {
inner: Arc<AcceptorInner>,
deadline: u64,
}
struct AcceptorInner {
listener: UnixListener,
reader: FileDesc,
writer: FileDesc,
closed: AtomicBool,
}
impl UnixAcceptor {
pub fn fd(&self) -> fd_t { self.inner.listener.fd() }
pub fn accept(&mut self) -> IoResult<UnixStream> {
let deadline = if self.deadline == 0 {None} else {Some(self.deadline)};
while!self.inner.closed.load(Ordering::SeqCst) {
unsafe {
let mut storage: libc::sockaddr_storage = mem::zeroed();
let storagep = &mut storage as *mut libc::sockaddr_storage;
let size = mem::size_of::<libc::sockaddr_storage>();
let mut size = size as libc::socklen_t;
match retry(|| {
libc::accept(self.fd(),
storagep as *mut libc::sockaddr,
&mut size as *mut libc::socklen_t) as libc::c_int
}) {
-1 if wouldblock() => {}
-1 => return Err(super::last_error()),
fd => return Ok(UnixStream::new(Arc::new(Inner::new(fd)))),
}
}
try!(await(&[self.fd(), self.inner.reader.fd()],
deadline, Readable));
}
Err(eof())
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn close_accept(&mut self) -> IoResult<()> {
self.inner.closed.store(true, Ordering::SeqCst);
let fd = FileDesc::new(self.inner.writer.fd(), false);
match fd.write(&[0]) {
Ok(..) => Ok(()),
Err(..) if wouldblock() => Ok(()),
Err(e) => Err(e),
}
}
}
impl Clone for UnixAcceptor {
fn clone(&self) -> UnixAcceptor {
UnixAcceptor { inner: self.inner.clone(), deadline: 0 }
}
}
impl Drop for UnixListener {
fn drop(&mut self) {
// Unlink the path to the socket to ensure that it doesn't linger. We're
// careful to unlink the path before we close the file descriptor to
// prevent races where we unlink someone else's path.
unsafe {
let _ = libc::unlink(self.path.as_ptr());
}
}
}
|
connect
|
identifier_name
|
pipe.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use ffi::CString;
use libc;
use mem;
use sync::{Arc, Mutex};
use sync::atomic::{AtomicBool, Ordering};
use old_io::{self, IoResult, IoError};
use sys::{self, timer, retry, c, set_nonblocking, wouldblock};
use sys::fs::{fd_t, FileDesc};
use sys_common::net::*;
use sys_common::net::SocketStatus::*;
use sys_common::{eof, mkerr_libc};
fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> {
match unsafe { libc::socket(libc::AF_UNIX, ty, 0) } {
-1 => Err(super::last_error()),
fd => Ok(fd)
}
}
fn addr_to_sockaddr_un(addr: &CString,
storage: &mut libc::sockaddr_storage)
-> IoResult<libc::socklen_t> {
// the sun_path length is limited to SUN_LEN (with null)
assert!(mem::size_of::<libc::sockaddr_storage>() >=
mem::size_of::<libc::sockaddr_un>());
let s = unsafe { &mut *(storage as *mut _ as *mut libc::sockaddr_un) };
let len = addr.as_bytes().len();
if len > s.sun_path.len() - 1 {
return Err(IoError {
kind: old_io::InvalidInput,
desc: "invalid argument: path must be smaller than SUN_LEN",
detail: None,
})
}
s.sun_family = libc::AF_UNIX as libc::sa_family_t;
for (slot, value) in s.sun_path.iter_mut().zip(addr.as_bytes().iter()) {
*slot = *value as libc::c_char;
}
// count the null terminator
let len = mem::size_of::<libc::sa_family_t>() + len + 1;
return Ok(len as libc::socklen_t);
}
struct Inner {
fd: fd_t,
// Unused on Linux, where this lock is not necessary.
#[allow(dead_code)]
lock: Mutex<()>,
}
impl Inner {
fn new(fd: fd_t) -> Inner {
Inner { fd: fd, lock: Mutex::new(()) }
}
}
impl Drop for Inner {
fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } }
}
fn connect(addr: &CString, ty: libc::c_int,
timeout: Option<u64>) -> IoResult<Inner> {
let mut storage = unsafe { mem::zeroed() };
let len = try!(addr_to_sockaddr_un(addr, &mut storage));
let inner = Inner::new(try!(unix_socket(ty)));
let addrp = &storage as *const _ as *const libc::sockaddr;
match timeout {
None => {
match retry(|| unsafe { libc::connect(inner.fd, addrp, len) }) {
-1 => Err(super::last_error()),
_ => Ok(inner)
}
}
Some(timeout_ms) => {
try!(connect_timeout(inner.fd, addrp, len, timeout_ms));
Ok(inner)
}
}
}
fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> {
let mut storage = unsafe { mem::zeroed() };
let len = try!(addr_to_sockaddr_un(addr, &mut storage));
let inner = Inner::new(try!(unix_socket(ty)));
let addrp = &storage as *const _ as *const libc::sockaddr;
match unsafe {
libc::bind(inner.fd, addrp, len)
} {
-1 => Err(super::last_error()),
_ => Ok(inner)
}
}
////////////////////////////////////////////////////////////////////////////////
// Unix Streams
////////////////////////////////////////////////////////////////////////////////
pub struct UnixStream {
inner: Arc<Inner>,
read_deadline: u64,
write_deadline: u64,
}
impl UnixStream {
pub fn connect(addr: &CString,
timeout: Option<u64>) -> IoResult<UnixStream> {
connect(addr, libc::SOCK_STREAM, timeout).map(|inner| {
UnixStream::new(Arc::new(inner))
})
}
fn new(inner: Arc<Inner>) -> UnixStream {
UnixStream {
inner: inner,
read_deadline: 0,
write_deadline: 0,
}
}
pub fn fd(&self) -> fd_t { self.inner.fd }
#[cfg(target_os = "linux")]
fn lock_nonblocking(&self) {}
#[cfg(not(target_os = "linux"))]
fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
let ret = Guard {
fd: self.fd(),
guard: unsafe { self.inner.lock.lock().unwrap() },
};
assert!(set_nonblocking(self.fd(), true).is_ok());
ret
}
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let fd = self.fd();
let dolock = || self.lock_nonblocking();
let doread = |nb| unsafe {
let flags = if nb
|
else {0};
libc::recv(fd,
buf.as_mut_ptr() as *mut libc::c_void,
buf.len() as libc::size_t,
flags) as libc::c_int
};
read(fd, self.read_deadline, dolock, doread)
}
pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let fd = self.fd();
let dolock = || self.lock_nonblocking();
let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *const _,
len as libc::size_t,
flags) as i64
};
match write(fd, self.write_deadline, buf, true, dolock, dowrite) {
Ok(_) => Ok(()),
Err(e) => Err(e)
}
}
pub fn close_write(&mut self) -> IoResult<()> {
mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) })
}
pub fn close_read(&mut self) -> IoResult<()> {
mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_RD) })
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
let deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
self.read_deadline = deadline;
self.write_deadline = deadline;
}
pub fn set_read_timeout(&mut self, timeout: Option<u64>) {
self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn set_write_timeout(&mut self, timeout: Option<u64>) {
self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
}
impl Clone for UnixStream {
fn clone(&self) -> UnixStream {
UnixStream::new(self.inner.clone())
}
}
////////////////////////////////////////////////////////////////////////////////
// Unix Listener
////////////////////////////////////////////////////////////////////////////////
pub struct UnixListener {
inner: Inner,
path: CString,
}
// we currently own the CString, so these impls should be safe
unsafe impl Send for UnixListener {}
unsafe impl Sync for UnixListener {}
impl UnixListener {
pub fn bind(addr: &CString) -> IoResult<UnixListener> {
bind(addr, libc::SOCK_STREAM).map(|fd| {
UnixListener { inner: fd, path: addr.clone() }
})
}
pub fn fd(&self) -> fd_t { self.inner.fd }
pub fn listen(self) -> IoResult<UnixAcceptor> {
match unsafe { libc::listen(self.fd(), 128) } {
-1 => Err(super::last_error()),
_ => {
let (reader, writer) = try!(unsafe { sys::os::pipe() });
try!(set_nonblocking(reader.fd(), true));
try!(set_nonblocking(writer.fd(), true));
try!(set_nonblocking(self.fd(), true));
Ok(UnixAcceptor {
inner: Arc::new(AcceptorInner {
listener: self,
reader: reader,
writer: writer,
closed: AtomicBool::new(false),
}),
deadline: 0,
})
}
}
}
}
pub struct UnixAcceptor {
inner: Arc<AcceptorInner>,
deadline: u64,
}
struct AcceptorInner {
listener: UnixListener,
reader: FileDesc,
writer: FileDesc,
closed: AtomicBool,
}
impl UnixAcceptor {
pub fn fd(&self) -> fd_t { self.inner.listener.fd() }
pub fn accept(&mut self) -> IoResult<UnixStream> {
let deadline = if self.deadline == 0 {None} else {Some(self.deadline)};
while!self.inner.closed.load(Ordering::SeqCst) {
unsafe {
let mut storage: libc::sockaddr_storage = mem::zeroed();
let storagep = &mut storage as *mut libc::sockaddr_storage;
let size = mem::size_of::<libc::sockaddr_storage>();
let mut size = size as libc::socklen_t;
match retry(|| {
libc::accept(self.fd(),
storagep as *mut libc::sockaddr,
&mut size as *mut libc::socklen_t) as libc::c_int
}) {
-1 if wouldblock() => {}
-1 => return Err(super::last_error()),
fd => return Ok(UnixStream::new(Arc::new(Inner::new(fd)))),
}
}
try!(await(&[self.fd(), self.inner.reader.fd()],
deadline, Readable));
}
Err(eof())
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn close_accept(&mut self) -> IoResult<()> {
self.inner.closed.store(true, Ordering::SeqCst);
let fd = FileDesc::new(self.inner.writer.fd(), false);
match fd.write(&[0]) {
Ok(..) => Ok(()),
Err(..) if wouldblock() => Ok(()),
Err(e) => Err(e),
}
}
}
impl Clone for UnixAcceptor {
fn clone(&self) -> UnixAcceptor {
UnixAcceptor { inner: self.inner.clone(), deadline: 0 }
}
}
impl Drop for UnixListener {
fn drop(&mut self) {
// Unlink the path to the socket to ensure that it doesn't linger. We're
// careful to unlink the path before we close the file descriptor to
// prevent races where we unlink someone else's path.
unsafe {
let _ = libc::unlink(self.path.as_ptr());
}
}
}
|
{c::MSG_DONTWAIT}
|
conditional_block
|
main.rs
|
fn main() {
fn sum_vec (v: &Vec<i32>) -> i32 {
return v.iter().fold(0, |a, &b| a + b);
}
fn foo (v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
let s1 = sum_vec(v1);
let s2 = sum_vec(v2);
s1 + s2
}
fn
|
(v: &Vec<i32>) {
// v.push(5); // will cause error as not a mutable reference
}
let v = vec![];
foo1(&v);
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
let answer = foo(&v1, &v2);
println!("{}", answer);
// mutable reference
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
// thinking in scope
let mut x2 = 5;
{
let y2 = &mut x2;
*y2 += 1;
// println!("{}", x); // not okay to be in the scope
}
println!("{}", x); // okay here as scope ended
}
|
foo1
|
identifier_name
|
main.rs
|
fn main() {
fn sum_vec (v: &Vec<i32>) -> i32 {
return v.iter().fold(0, |a, &b| a + b);
}
fn foo (v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
let s1 = sum_vec(v1);
let s2 = sum_vec(v2);
s1 + s2
}
fn foo1 (v: &Vec<i32>) {
// v.push(5); // will cause error as not a mutable reference
}
let v = vec![];
foo1(&v);
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
let answer = foo(&v1, &v2);
println!("{}", answer);
// mutable reference
let mut x = 5;
{
let y = &mut x;
|
*y += 1;
}
println!("{}", x);
// thinking in scope
let mut x2 = 5;
{
let y2 = &mut x2;
*y2 += 1;
// println!("{}", x); // not okay to be in the scope
}
println!("{}", x); // okay here as scope ended
}
|
random_line_split
|
|
main.rs
|
fn main() {
fn sum_vec (v: &Vec<i32>) -> i32 {
return v.iter().fold(0, |a, &b| a + b);
}
fn foo (v1: &Vec<i32>, v2: &Vec<i32>) -> i32
|
fn foo1 (v: &Vec<i32>) {
// v.push(5); // will cause error as not a mutable reference
}
let v = vec![];
foo1(&v);
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
let answer = foo(&v1, &v2);
println!("{}", answer);
// mutable reference
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
// thinking in scope
let mut x2 = 5;
{
let y2 = &mut x2;
*y2 += 1;
// println!("{}", x); // not okay to be in the scope
}
println!("{}", x); // okay here as scope ended
}
|
{
let s1 = sum_vec(v1);
let s2 = sum_vec(v2);
s1 + s2
}
|
identifier_body
|
pause.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::LockManager;
use crate::storage::txn::commands::{
Command, CommandExt, ResponsePolicy, TypedCommand, WriteCommand, WriteContext, WriteResult,
};
use crate::storage::txn::Result;
use crate::storage::{ProcessResult, Snapshot};
use std::thread;
use std::time::Duration;
use txn_types::Key;
command! {
/// **Testing functionality:** Latch the given keys for given duration.
///
/// This means other write operations that involve these keys will be blocked.
Pause:
cmd_ty => (),
display => "kv::command::pause keys:({}) {} ms | {:?}", (keys.len, duration, ctx),
content => {
/// The keys to hold latches on.
keys: Vec<Key>,
/// The amount of time in milliseconds to latch for.
duration: u64,
}
}
impl CommandExt for Pause {
ctx!();
tag!(pause);
write_bytes!(keys: multiple);
gen_lock!(keys: multiple);
}
impl<S: Snapshot, L: LockManager> WriteCommand<S, L> for Pause {
fn
|
(self, _snapshot: S, _context: WriteContext<'_, L>) -> Result<WriteResult> {
thread::sleep(Duration::from_millis(self.duration));
Ok(WriteResult {
ctx: self.ctx,
to_be_write: WriteData::default(),
rows: 0,
pr: ProcessResult::Res,
lock_info: None,
lock_guards: vec![],
response_policy: ResponsePolicy::OnApplied,
})
}
}
|
process_write
|
identifier_name
|
pause.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::LockManager;
use crate::storage::txn::commands::{
Command, CommandExt, ResponsePolicy, TypedCommand, WriteCommand, WriteContext, WriteResult,
};
use crate::storage::txn::Result;
use crate::storage::{ProcessResult, Snapshot};
use std::thread;
use std::time::Duration;
use txn_types::Key;
command! {
/// **Testing functionality:** Latch the given keys for given duration.
///
/// This means other write operations that involve these keys will be blocked.
Pause:
cmd_ty => (),
display => "kv::command::pause keys:({}) {} ms | {:?}", (keys.len, duration, ctx),
content => {
/// The keys to hold latches on.
keys: Vec<Key>,
/// The amount of time in milliseconds to latch for.
duration: u64,
}
}
impl CommandExt for Pause {
ctx!();
tag!(pause);
write_bytes!(keys: multiple);
gen_lock!(keys: multiple);
}
impl<S: Snapshot, L: LockManager> WriteCommand<S, L> for Pause {
fn process_write(self, _snapshot: S, _context: WriteContext<'_, L>) -> Result<WriteResult>
|
}
|
{
thread::sleep(Duration::from_millis(self.duration));
Ok(WriteResult {
ctx: self.ctx,
to_be_write: WriteData::default(),
rows: 0,
pr: ProcessResult::Res,
lock_info: None,
lock_guards: vec![],
response_policy: ResponsePolicy::OnApplied,
})
}
|
identifier_body
|
pause.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::LockManager;
use crate::storage::txn::commands::{
Command, CommandExt, ResponsePolicy, TypedCommand, WriteCommand, WriteContext, WriteResult,
};
use crate::storage::txn::Result;
use crate::storage::{ProcessResult, Snapshot};
use std::thread;
use std::time::Duration;
use txn_types::Key;
command! {
/// **Testing functionality:** Latch the given keys for given duration.
///
/// This means other write operations that involve these keys will be blocked.
Pause:
cmd_ty => (),
display => "kv::command::pause keys:({}) {} ms | {:?}", (keys.len, duration, ctx),
content => {
/// The keys to hold latches on.
keys: Vec<Key>,
/// The amount of time in milliseconds to latch for.
duration: u64,
}
}
impl CommandExt for Pause {
ctx!();
tag!(pause);
write_bytes!(keys: multiple);
gen_lock!(keys: multiple);
}
|
Ok(WriteResult {
ctx: self.ctx,
to_be_write: WriteData::default(),
rows: 0,
pr: ProcessResult::Res,
lock_info: None,
lock_guards: vec![],
response_policy: ResponsePolicy::OnApplied,
})
}
}
|
impl<S: Snapshot, L: LockManager> WriteCommand<S, L> for Pause {
fn process_write(self, _snapshot: S, _context: WriteContext<'_, L>) -> Result<WriteResult> {
thread::sleep(Duration::from_millis(self.duration));
|
random_line_split
|
probe_pins.rs
|
extern crate serial;
use std::env;
use std::thread;
use std::time::Duration;
use serial::prelude::*;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
};
fn main() {
for arg in env::args_os().skip(1) {
let mut port = serial::open(&arg).unwrap();
println!("opened device {:?}", arg);
probe_pins(&mut port).unwrap();
}
}
fn probe_pins<T: SerialPort>(port: &mut T) -> serial::Result<()>
|
try!(port.set_dtr(dtr));
}
println!("RTS={:5?} DTR={:5?} CTS={:5?} DSR={:5?} RI={:5?} CD={:?}",
rts,
dtr,
try!(port.read_cts()),
try!(port.read_dsr()),
try!(port.read_ri()),
try!(port.read_cd()));
toggle =!toggle;
}
}
|
{
try!(port.configure(&SETTINGS));
try!(port.set_timeout(Duration::from_millis(100)));
try!(port.set_rts(false));
try!(port.set_dtr(false));
let mut rts = false;
let mut dtr = false;
let mut toggle = true;
loop {
thread::sleep(Duration::from_secs(1));
if toggle {
rts = !rts;
try!(port.set_rts(rts));
}
else {
dtr = !dtr;
|
identifier_body
|
probe_pins.rs
|
extern crate serial;
use std::env;
use std::thread;
use std::time::Duration;
use serial::prelude::*;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
};
fn main() {
for arg in env::args_os().skip(1) {
let mut port = serial::open(&arg).unwrap();
println!("opened device {:?}", arg);
probe_pins(&mut port).unwrap();
}
}
fn probe_pins<T: SerialPort>(port: &mut T) -> serial::Result<()> {
try!(port.configure(&SETTINGS));
try!(port.set_timeout(Duration::from_millis(100)));
try!(port.set_rts(false));
try!(port.set_dtr(false));
let mut rts = false;
let mut dtr = false;
let mut toggle = true;
|
loop {
thread::sleep(Duration::from_secs(1));
if toggle {
rts =!rts;
try!(port.set_rts(rts));
}
else {
dtr =!dtr;
try!(port.set_dtr(dtr));
}
println!("RTS={:5?} DTR={:5?} CTS={:5?} DSR={:5?} RI={:5?} CD={:?}",
rts,
dtr,
try!(port.read_cts()),
try!(port.read_dsr()),
try!(port.read_ri()),
try!(port.read_cd()));
toggle =!toggle;
}
}
|
random_line_split
|
|
probe_pins.rs
|
extern crate serial;
use std::env;
use std::thread;
use std::time::Duration;
use serial::prelude::*;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
};
fn
|
() {
for arg in env::args_os().skip(1) {
let mut port = serial::open(&arg).unwrap();
println!("opened device {:?}", arg);
probe_pins(&mut port).unwrap();
}
}
fn probe_pins<T: SerialPort>(port: &mut T) -> serial::Result<()> {
try!(port.configure(&SETTINGS));
try!(port.set_timeout(Duration::from_millis(100)));
try!(port.set_rts(false));
try!(port.set_dtr(false));
let mut rts = false;
let mut dtr = false;
let mut toggle = true;
loop {
thread::sleep(Duration::from_secs(1));
if toggle {
rts =!rts;
try!(port.set_rts(rts));
}
else {
dtr =!dtr;
try!(port.set_dtr(dtr));
}
println!("RTS={:5?} DTR={:5?} CTS={:5?} DSR={:5?} RI={:5?} CD={:?}",
rts,
dtr,
try!(port.read_cts()),
try!(port.read_dsr()),
try!(port.read_ri()),
try!(port.read_cd()));
toggle =!toggle;
}
}
|
main
|
identifier_name
|
probe_pins.rs
|
extern crate serial;
use std::env;
use std::thread;
use std::time::Duration;
use serial::prelude::*;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
};
fn main() {
for arg in env::args_os().skip(1) {
let mut port = serial::open(&arg).unwrap();
println!("opened device {:?}", arg);
probe_pins(&mut port).unwrap();
}
}
fn probe_pins<T: SerialPort>(port: &mut T) -> serial::Result<()> {
try!(port.configure(&SETTINGS));
try!(port.set_timeout(Duration::from_millis(100)));
try!(port.set_rts(false));
try!(port.set_dtr(false));
let mut rts = false;
let mut dtr = false;
let mut toggle = true;
loop {
thread::sleep(Duration::from_secs(1));
if toggle
|
else {
dtr =!dtr;
try!(port.set_dtr(dtr));
}
println!("RTS={:5?} DTR={:5?} CTS={:5?} DSR={:5?} RI={:5?} CD={:?}",
rts,
dtr,
try!(port.read_cts()),
try!(port.read_dsr()),
try!(port.read_ri()),
try!(port.read_cd()));
toggle =!toggle;
}
}
|
{
rts = !rts;
try!(port.set_rts(rts));
}
|
conditional_block
|
htmlbaseelement.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::HTMLBaseElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBaseElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBaseElement {
htmlelement: HTMLElement
}
impl HTMLBaseElementDerived for EventTarget {
fn is_htmlbaseelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBaseElement)))
}
}
impl HTMLBaseElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBaseElement, localName, prefix, document)
}
|
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
}
|
}
|
random_line_split
|
htmlbaseelement.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::HTMLBaseElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBaseElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBaseElement {
htmlelement: HTMLElement
}
impl HTMLBaseElementDerived for EventTarget {
fn is_htmlbaseelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBaseElement)))
}
}
impl HTMLBaseElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBaseElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn
|
(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
}
|
new
|
identifier_name
|
htmlbaseelement.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::HTMLBaseElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBaseElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBaseElement {
htmlelement: HTMLElement
}
impl HTMLBaseElementDerived for EventTarget {
fn is_htmlbaseelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBaseElement)))
}
}
impl HTMLBaseElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement
|
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
}
|
{
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBaseElement, localName, prefix, document)
}
}
|
identifier_body
|
simd-generics.rs
|
// Copyright 2013-2014 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.
#![feature(simd)]
use std::ops;
#[simd] struct f32x4(f32, f32, f32, f32);
fn add<T: ops::Add<T, T>>(lhs: T, rhs: T) -> T {
lhs + rhs
}
impl ops::Add<f32x4, f32x4> for f32x4 {
fn add(&self, rhs: &f32x4) -> f32x4 {
*self + *rhs
}
}
pub fn main()
|
{
let lr = f32x4(1.0f32, 2.0f32, 3.0f32, 4.0f32);
// lame-o
let f32x4(x, y, z, w) = add(lr, lr);
assert_eq!(x, 2.0f32);
assert_eq!(y, 4.0f32);
assert_eq!(z, 6.0f32);
assert_eq!(w, 8.0f32);
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.