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 |
---|---|---|---|---|
issue-11192.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.
#![feature(box_syntax)]
struct Foo {
x: isize
}
impl Drop for Foo {
fn drop(&mut self) {
println!("drop {}", self.x);
}
}
fn main() {
let mut ptr: Box<_> = box Foo { x: 0 };
|
ptr = box Foo { x: ptr.x + 1 };
println!("access {}", foo.x);
};
test(&*ptr);
//~^ ERROR: cannot borrow `*ptr` as immutable
}
|
let mut test = |foo: &Foo| {
println!("access {}", foo.x);
|
random_line_split
|
issue-11192.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.
#![feature(box_syntax)]
struct Foo {
x: isize
}
impl Drop for Foo {
fn
|
(&mut self) {
println!("drop {}", self.x);
}
}
fn main() {
let mut ptr: Box<_> = box Foo { x: 0 };
let mut test = |foo: &Foo| {
println!("access {}", foo.x);
ptr = box Foo { x: ptr.x + 1 };
println!("access {}", foo.x);
};
test(&*ptr);
//~^ ERROR: cannot borrow `*ptr` as immutable
}
|
drop
|
identifier_name
|
textedit.rs
|
extern crate rustty;
use rustty::{
Terminal,
Cell,
Event,
Style,
Color,
Attr,
};
struct
|
{
pos: Position,
lpos: Position,
style: Style,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position { x: 0, y: 0 },
lpos: Position { x: 0, y: 0 },
style: Style::with_color(Color::Red),
};
let mut term = Terminal::new().unwrap();
term[cursor.pos.y][cursor.pos.x].set_bg(cursor.style);
term.swap_buffers().unwrap();
loop {
let evt = term.get_event(100).unwrap();
if let Some(Event::Key(ch)) = evt {
match ch {
'`' => {
break;
},
'\x7f' => {
cursor.lpos = cursor.pos;
if cursor.pos.x == 0 {
cursor.pos.y = cursor.pos.y.saturating_sub(1);
} else {
cursor.pos.x -= 1;
}
term[cursor.pos.y][cursor.pos.x].set_ch(' ');
},
'\r' => {
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
},
c @ _ => {
term[cursor.pos.y][cursor.pos.x].set_ch(c);
cursor.lpos = cursor.pos;
cursor.pos.x += 1;
},
}
if cursor.pos.x >= term.cols()-1 {
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
}
if cursor.pos.y >= term.rows()-1 {
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y = 0;
}
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
term[cursor.pos.y][cursor.pos.x].set_bg(cursor.style);
term.swap_buffers().unwrap();
}
}
}
|
Cursor
|
identifier_name
|
textedit.rs
|
extern crate rustty;
use rustty::{
Terminal,
Cell,
Event,
Style,
Color,
Attr,
};
|
pos: Position,
lpos: Position,
style: Style,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position { x: 0, y: 0 },
lpos: Position { x: 0, y: 0 },
style: Style::with_color(Color::Red),
};
let mut term = Terminal::new().unwrap();
term[cursor.pos.y][cursor.pos.x].set_bg(cursor.style);
term.swap_buffers().unwrap();
loop {
let evt = term.get_event(100).unwrap();
if let Some(Event::Key(ch)) = evt {
match ch {
'`' => {
break;
},
'\x7f' => {
cursor.lpos = cursor.pos;
if cursor.pos.x == 0 {
cursor.pos.y = cursor.pos.y.saturating_sub(1);
} else {
cursor.pos.x -= 1;
}
term[cursor.pos.y][cursor.pos.x].set_ch(' ');
},
'\r' => {
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
},
c @ _ => {
term[cursor.pos.y][cursor.pos.x].set_ch(c);
cursor.lpos = cursor.pos;
cursor.pos.x += 1;
},
}
if cursor.pos.x >= term.cols()-1 {
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
}
if cursor.pos.y >= term.rows()-1 {
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y = 0;
}
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
term[cursor.pos.y][cursor.pos.x].set_bg(cursor.style);
term.swap_buffers().unwrap();
}
}
}
|
struct Cursor {
|
random_line_split
|
textedit.rs
|
extern crate rustty;
use rustty::{
Terminal,
Cell,
Event,
Style,
Color,
Attr,
};
struct Cursor {
pos: Position,
lpos: Position,
style: Style,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position { x: 0, y: 0 },
lpos: Position { x: 0, y: 0 },
style: Style::with_color(Color::Red),
};
let mut term = Terminal::new().unwrap();
term[cursor.pos.y][cursor.pos.x].set_bg(cursor.style);
term.swap_buffers().unwrap();
loop {
let evt = term.get_event(100).unwrap();
if let Some(Event::Key(ch)) = evt {
match ch {
'`' => {
break;
},
'\x7f' => {
cursor.lpos = cursor.pos;
if cursor.pos.x == 0 {
cursor.pos.y = cursor.pos.y.saturating_sub(1);
} else {
cursor.pos.x -= 1;
}
term[cursor.pos.y][cursor.pos.x].set_ch(' ');
},
'\r' => {
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
},
c @ _ => {
term[cursor.pos.y][cursor.pos.x].set_ch(c);
cursor.lpos = cursor.pos;
cursor.pos.x += 1;
},
}
if cursor.pos.x >= term.cols()-1 {
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
}
if cursor.pos.y >= term.rows()-1
|
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
term[cursor.pos.y][cursor.pos.x].set_bg(cursor.style);
term.swap_buffers().unwrap();
}
}
}
|
{
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y = 0;
}
|
conditional_block
|
fmt.rs
|
//! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro is intended to be familiar to those coming from C's
//! `printf`/`fprintf` functions or Python's `str.format` function.
//!
//! Some examples of the [`format!`] extension are:
//!
//! ```
//! format!("Hello"); // => "Hello"
//! format!("Hello, {}!", "world"); // => "Hello, world!"
//! format!("The number is {}", 1); // => "The number is 1"
//! format!("{:?}", (3, 4)); // => "(3, 4)"
//! format!("{value}", value=4); // => "4"
//! format!("{} {}", 1, 2); // => "1 2"
//! format!("{:04}", 42); // => "0042" with leading zeros
//! format!("{:#?}", (100, 200)); // => "(
//! // 100,
//! // 200,
//! // )"
//! ```
//!
//! From these, you can see that the first argument is a format string. It is
//! required by the compiler for this to be a string literal; it cannot be a
//! variable passed in (in order to perform validity checking). The compiler
//! will then parse the format string and determine if the list of arguments
//! provided is suitable to pass to this format string.
//!
//! To convert a single value to a string, use the [`to_string`] method. This
//! will use the [`Display`] formatting trait.
//!
//! ## Positional parameters
//!
//! Each formatting argument is allowed to specify which value argument it's
//! referencing, and if omitted it is assumed to be "the next argument". For
//! example, the format string `{} {} {}` would take three parameters, and they
//! would be formatted in the same order as they're given. The format string
//! `{2} {1} {0}`, however, would format arguments in reverse order.
//!
//! Things can get a little tricky once you start intermingling the two types of
//! positional specifiers. The "next argument" specifier can be thought of as an
//! iterator over the argument. Each time a "next argument" specifier is seen,
//! the iterator advances. This leads to behavior like this:
//!
//! ```
//! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
//! ```
//!
//! The internal iterator over the argument has not been advanced by the time
//! the first `{}` is seen, so it prints the first argument. Then upon reaching
//! the second `{}`, the iterator has advanced forward to the second argument.
//! Essentially, parameters that explicitly name their argument do not affect
//! parameters that do not name an argument in terms of positional specifiers.
//!
//! A format string is required to use all of its arguments, otherwise it is a
//! compile-time error. You may refer to the same argument more than once in the
//! format string.
//!
//! ## Named parameters
//!
//! Rust itself does not have a Python-like equivalent of named parameters to a
//! function, but the [`format!`] macro is a syntax extension that allows it to
//! leverage named parameters. Named parameters are listed at the end of the
//! argument list and have the syntax:
//!
//! ```text
//! identifier '=' expression
//! ```
//!
//! For example, the following [`format!`] expressions all use named argument:
//!
//! ```
//! format!("{argument}", argument = "test"); // => "test"
//! format!("{name} {}", 1, name = 2); // => "2 1"
//! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
//! ```
//!
//! It is not valid to put positional parameters (those without names) after
//! arguments that have names. Like with positional parameters, it is not
//! valid to provide named parameters that are unused by the format string.
//!
//! # Formatting Parameters
//!
//! Each argument being formatted can be transformed by a number of formatting
//! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These
//! parameters affect the string representation of what's being formatted.
//!
//! ## Width
//!
//! ```
//! // All of these print "Hello x !"
//! println!("Hello {:5}!", "x");
//! println!("Hello {:1$}!", "x", 5);
//! println!("Hello {1:0$}!", 5, "x");
//! println!("Hello {:width$}!", "x", width = 5);
//! ```
//!
//! This is a parameter for the "minimum width" that the format should take up.
//! If the value's string does not fill up this many characters, then the
//! padding specified by fill/alignment will be used to take up the required
//! space (see below).
//!
//! The value for the width can also be provided as a [`usize`] in the list of
//! parameters by adding a postfix `$`, indicating that the second argument is
//! a [`usize`] specifying the width.
//!
//! Referring to an argument with the dollar syntax does not affect the "next
//! argument" counter, so it's usually a good idea to refer to arguments by
//! position, or use named arguments.
//!
//! ## Fill/Alignment
//!
//! ```
//! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !");
//! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!");
//! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !");
//! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!");
//! ```
//!
//! The optional fill character and alignment is provided normally in conjunction with the
//! [`width`](#width) parameter. It must be defined before `width`, right after the `:`.
//! This indicates that if the value being formatted is smaller than
//! `width` some extra characters will be printed around it.
//! Filling comes in the following variants for different alignments:
//!
//! * `[fill]<` - the argument is left-aligned in `width` columns
//! * `[fill]^` - the argument is center-aligned in `width` columns
//! * `[fill]>` - the argument is right-aligned in `width` columns
//!
//! The default [fill/alignment](#fillalignment) for non-numerics is a space and
//! left-aligned. The
//! default for numeric formatters is also a space character but with right-alignment. If
//! the `0` flag (see below) is specified for numerics, then the implicit fill character is
//! `0`.
//!
//! Note that alignment might not be implemented by some types. In particular, it
//! is not generally implemented for the `Debug` trait. A good way to ensure
//! padding is applied is to format your input, then pad this resulting string
//! to obtain your output:
//!
//! ```
//! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !"
//! ```
//!
//! ## Sign/`#`/`0`
//!
//! ```
//! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!");
//! assert_eq!(format!("{:#x}!", 27), "0x1b!");
//! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!");
//! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!");
//! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!");
//! ```
//!
//! These are all flags altering the behavior of the formatter.
//!
//! * `+` - This is intended for numeric types and indicates that the sign
//! should always be printed. Positive signs are never printed by
//! default, and the negative sign is only printed by default for signed values.
//! This flag indicates that the correct sign (`+` or `-`) should always be printed.
//! * `-` - Currently not used
//! * `#` - This flag indicates that the "alternate" form of printing should
//! be used. The alternate forms are:
//! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
//! * `#x` - precedes the argument with a `0x`
//! * `#X` - precedes the argument with a `0x`
//! * `#b` - precedes the argument with a `0b`
//! * `#o` - precedes the argument with a `0o`
//! * `0` - This is used to indicate for integer formats that the padding to `width` should
//! both be done with a `0` character as well as be sign-aware. A format
//! like `{:08}` would yield `00000001` for the integer `1`, while the
//! same format would yield `-0000001` for the integer `-1`. Notice that
//! the negative version has one fewer zero than the positive version.
//! Note that padding zeros are always placed after the sign (if any)
//! and before the digits. When used together with the `#` flag, a similar
//! rule applies: padding zeros are inserted after the prefix but before
//! the digits. The prefix is included in the total width.
//!
//! ## Precision
//!
//! For non-numeric types, this can be considered a "maximum width". If the resulting string is
//! longer than this width, then it is truncated down to this many characters and that truncated
//! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set.
//!
//! For integral types, this is ignored.
//!
//! For floating-point types, this indicates how many digits after the decimal point should be
//! printed.
//!
//! There are three possible ways to specify the desired `precision`:
//!
//! 1. An integer `.N`:
//!
//! the integer `N` itself is the precision.
//!
//! 2. An integer or name followed by dollar sign `.N$`:
//!
//! use format *argument* `N` (which must be a `usize`) as the precision.
//!
//! 3. An asterisk `.*`:
//!
//! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the
//! first input holds the `usize` precision, and the second holds the value to print. Note that
//! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers
//! to the *value* to print, and the `precision` must come in the input preceding `<arg>`.
//!
//! For example, the following calls all print the same thing `Hello x is 0.01000`:
//!
//! ```
//! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)}
//! println!("Hello {0} is {1:.5}", "x", 0.01);
//!
//! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)}
//! println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
//!
//! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)}
//! println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {second of next two args (0.01) with precision
//! // specified in first of next two args (5)}
//! println!("Hello {} is {:.*}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {arg 2 (0.01) with precision
//! // specified in its predecessor (5)}
//! println!("Hello {} is {2:.*}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified
//! // in arg "prec" (5)}
//! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
//! ```
//!
//! While these:
//!
//! ```
//! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
//! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
//! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
//! ```
//!
//! print three significantly different things:
//!
//! ```text
//! Hello, `1234.560` has 3 fractional digits
//! Hello, `123` has 3 characters
//! Hello, ` 123` has 3 right-aligned characters
//! ```
//!
//! ## Localization
//!
//! In some programming languages, the behavior of string formatting functions
//! depends on the operating system's locale setting. The format functions
//! provided by Rust's standard library do not have any concept of locale and
//! will produce the same results on all systems regardless of user
//! configuration.
//!
//! For example, the following code will always print `1.5` even if the system
//! locale uses a decimal separator other than a dot.
//!
//! ```
//! println!("The value is {}", 1.5);
//! ```
//!
//! # Escaping
//!
//! The literal characters `{` and `}` may be included in a string by preceding
//! them with the same character. For example, the `{` character is escaped with
//! `{{` and the `}` character is escaped with `}}`.
//!
//! ```
//! assert_eq!(format!("Hello {{}}"), "Hello {}");
//! assert_eq!(format!("{{ Hello"), "{ Hello");
//! ```
//!
//! # Syntax
//!
//! To summarize, here you can find the full grammar of format strings.
//! The syntax for the formatting language used is drawn from other languages,
//! so it should not be too alien. Arguments are formatted with Python-like
//! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
//! `%`. The actual grammar for the formatting syntax is:
//!
//! ```text
//! format_string := text [ maybe_format text ] *
//! maybe_format := '{' '{' | '}' '}' | format
//! format := '{' [ argument ] [ ':' format_spec ] '}'
//! argument := integer | identifier
//!
//! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
//! fill := character
//! align := '<' | '^' | '>'
//! sign := '+' | '-'
//! width := count
//! precision := count | '*'
//! type := '' | '?' | 'x?' | 'X?' | identifier
//! count := parameter | integer
//! parameter := argument '$'
//! ```
//! In the above grammar, `text` must not contain any `'{'` or `'}'` characters.
//!
//! # Formatting traits
//!
//! When requesting that an argument be formatted with a particular type, you
//! are actually requesting that an argument ascribes to a particular trait.
//! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as
//! well as [`isize`]). The current mapping of types to traits is:
//!
//! * *nothing* β [`Display`]
//! * `?` β [`Debug`]
//! * `x?` β [`Debug`] with lower-case hexadecimal integers
//! * `X?` β [`Debug`] with upper-case hexadecimal integers
//! * `o` β [`Octal`]
//! * `x` β [`LowerHex`]
//! * `X` β [`UpperHex`]
//! * `p` β [`Pointer`]
//! * `b` β [`Binary`]
//! * `e` β [`LowerExp`]
//! * `E` β [`UpperExp`]
//!
//! What this means is that any type of argument which implements the
//! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations
//! are provided for these traits for a number of primitive types by the
//! standard library as well. If no format is specified (as in `{}` or `{:6}`),
//! then the format trait used is the [`Display`] trait.
//!
//! When implementing a format trait for your own type, you will have to
//! implement a method of the signature:
//!
//! ```
//! # #![allow(dead_code)]
//! # use std::fmt;
//! # struct Foo; // our custom type
//! # impl fmt::Display for Foo {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! # write!(f, "testing, testing")
//! # } }
//! ```
//!
//! Your type will be passed as `self` by-reference, and then the function
//! should emit output into the `f.buf` stream. It is up to each format trait
//! implementation to correctly adhere to the requested formatting parameters.
//! The values of these parameters will be listed in the fields of the
//! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also
//! provides some helper methods.
//!
//! Additionally, the return value of this function is [`fmt::Result`] which is a
//! type alias of [`Result`]`<(), `[`std::fmt::Error`]`>`. Formatting implementations
//! should ensure that they propagate errors from the [`Formatter`] (e.g., when
//! calling [`write!`]). However, they should never return errors spuriously. That
//! is, a formatting implementation must and may only return an error if the
//! passed-in [`Formatter`] returns an error. This is because, contrary to what
//! the function signature might suggest, string formatting is an infallible
//! operation. This function only returns a result because writing to the
//! underlying stream might fail and it must provide a way to propagate the fact
//! that an error has occurred back up the stack.
//!
//! An example of implementing the formatting traits would look
//! like:
//!
//! ```
//! use std::fmt;
//!
//! #[derive(Debug)]
//! struct Vector2D {
//! x: isize,
//! y: isize,
//! }
//!
//! impl fmt::Display for Vector2D {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! // The `f` value implements the `Write` trait, which is what the
//! // write! macro is expecting. Note that this formatting ignores the
//! // various flags provided to format strings.
//! write!(f, "({}, {})", self.x, self.y)
//! }
//! }
//!
//! // Different traits allow different forms of output of a type. The meaning
//! // of this format is to print the magnitude of a vector.
//! impl fmt::Binary for Vector2D {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! let magnitude = (self.x * self.x + self.y * self.y) as f64;
//! let magnitude = magnitude.sqrt();
//!
//! // Respect the formatting flags by using the helper method
//! // `pad_integral` on the Formatter object. See the method
//! // documentation for details, and the function `pad` can be used
//! // to pad strings.
//! let decimals = f.precision().unwrap_or(3);
//! let string = format!("{:.*}", decimals, magnitude);
//! f.pad_integral(true, "", &string)
//! }
//! }
//!
//! fn main() {
//! let myvector = Vector2D { x: 3, y: 4 };
//!
//! println!("{}", myvector); // => "(3, 4)"
//! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}"
//! println!("{:10.3b}", myvector); // => " 5.000"
//! }
//! ```
//!
//! ### `fmt::Display` vs `fmt::Debug`
//!
//! These two formatting traits have distinct purposes:
//!
//! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully
//! represented as a UTF-8 string at all times. It is **not** expected that
//! all types implement the [`Display`] trait.
//! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types.
//! Output will typically represent the internal state as faithfully as possible.
//! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In
//! most cases, using `#[derive(Debug)]` is sufficient and recommended.
//!
//! Some examples of the output from both traits:
//!
//! ```
//! assert_eq!(format!("{} {:?}", 3, 4), "3 4");
//! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
//! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
//! ```
//!
//! # Related macros
//!
//! There are a number of related macros in the [`format!`] family. The ones that
//! are currently implemented are:
//!
//! ```ignore (only-for-syntax-highlight)
//! format! // described above
//! write! // first argument is a &mut io::Write, the destination
//! writeln! // same as write but appends a newline
//! print! // the format string is printed to the standard output
//! println! // same as print but appends a newline
//! eprint! // the format string is printed to the standard error
//! eprintln! // same as eprint but appends a newline
//! format_args! // described below.
//! ```
//!
//! ### `write!`
//!
//! This and [`writeln!`] are two macros which are used to emit the format string
//! to a specified stream. This is used to prevent intermediate allocations of
//! format strings and instead directly write the output. Under the hood, this
//! function is actually invoking the [`write_fmt`] function defined on the
//! [`std::io::Write`] trait. Example usage is:
//!
//! ```
//! # #![allow(unused_must_use)]
//! use std::io::Write;
//! let mut w = Vec::new();
//! write!(&mut w, "Hello {}!", "world");
//! ```
//!
//! ### `print!`
//!
//! This and [`println!`] emit their output to stdout. Similarly to the [`write!`]
//! macro, the goal of these macros is to avoid intermediate allocations when
//! printing output. Example usage is:
//!
//! ```
//! print!("Hello {}!", "world");
//! println!("I have a newline {}", "character at the end");
//! ```
//! ### `eprint!`
//!
//! The [`eprint!`] and [`eprintln!`] macros are identical to
//! [`print!`] and [`println!`], respectively, except they emit their
//! output to stderr.
//!
//! ### `format_args!`
//!
//! This is a curious macro used to safely pass around
//! an opaque object describing the format string. This object
//! does not require any heap allocations to create, and it only
//! references information on the stack. Under the hood, all of
//! the related macros are implemented in terms of this. First
//! off, some example usage is:
//!
//! ```
//! # #![allow(unused_must_use)]
//! use std::fmt;
//! use std::io::{self, Write};
//!
//! let mut some_writer = io::stdout();
//! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
//!
//! fn my_fmt_fn(args: fmt::Arguments) {
//! write!(&mut io::stdout(), "{}", args);
//! }
//! my_fmt_fn(format_args!(", or a {} too", "function"));
//! ```
//!
//! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`].
//! This structure can then be passed to the [`write`] and [`format`] functions
//! inside this module in order to process the format string.
//! The goal of this macro is to even further prevent intermediate allocations
//! when dealing with formatting strings.
//!
//! For example, a logging library could use the standard formatting syntax, but
//! it would internally pass around this structure until it has been determined
//! where output should go to.
//!
//! [`fmt::Result`]: Result
//! [`Result`]: core::result::Result
//! [`std::fmt::Error`]: Error
//! [`write!`]: core::write
//! [`write`]: core::write
//! [`format!`]: crate::format
//! [`to_string`]: crate::string::ToString
//! [`writeln!`]: core::writeln
//! [`write_fmt`]:../../std/io/trait.Write.html#method.write_fmt
//! [`std::io::Write`]:../../std/io/trait.Write.html
//! [`print!`]:../../std/macro.print.html
//! [`println!`]:../../std/macro.println.html
//! [`eprint!`]:../../std/macro.eprint.html
//! [`eprintln!`]:../../std/macro.eprintln.html
//! [`format_args!`]: core::format_args
//! [`fmt::Arguments`]: Arguments
//! [`format`]: crate::format
#![stable(feature = "rust1", since = "1.0.0")]
#[unstable(feature = "fmt_internals", issue = "none")]
pub use core::fmt::rt;
#[stable(feature = "fmt_flags_align", since = "1.28.0")]
pub use core::fmt::Alignment;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::Error;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{write, ArgumentV1, Arguments};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Binary, Octal};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Debug, Display};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Formatter, Result, Write};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{LowerExp, UpperExp};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{LowerHex, Pointer, UpperHex};
#[cfg(not(no_global_oom_handling))]
use crate::string;
/// The `format` function takes an [`Arguments`] struct and returns the resulting
/// formatted string.
///
/// The [`Arguments`] instance can be created with the [`format_args!`] macro.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::fmt;
///
/// let s = fmt::format(format_args!("Hello, {}!", "world"));
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// Please note that using [`format!`] might be preferable.
/// Example:
///
/// ```
/// let s = format!("Hello, {}!", "world");
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// [`format_args!`]: core::format_args
/// [`format!`]: crate::format
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn format(args: Arguments<'_>) -> string::String {
let capacity = a
|
rgs.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}
|
identifier_body
|
|
fmt.rs
|
//! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro is intended to be familiar to those coming from C's
//! `printf`/`fprintf` functions or Python's `str.format` function.
//!
//! Some examples of the [`format!`] extension are:
//!
//! ```
//! format!("Hello"); // => "Hello"
//! format!("Hello, {}!", "world"); // => "Hello, world!"
//! format!("The number is {}", 1); // => "The number is 1"
//! format!("{:?}", (3, 4)); // => "(3, 4)"
//! format!("{value}", value=4); // => "4"
//! format!("{} {}", 1, 2); // => "1 2"
//! format!("{:04}", 42); // => "0042" with leading zeros
//! format!("{:#?}", (100, 200)); // => "(
//! // 100,
//! // 200,
//! // )"
//! ```
//!
//! From these, you can see that the first argument is a format string. It is
//! required by the compiler for this to be a string literal; it cannot be a
//! variable passed in (in order to perform validity checking). The compiler
//! will then parse the format string and determine if the list of arguments
//! provided is suitable to pass to this format string.
//!
//! To convert a single value to a string, use the [`to_string`] method. This
//! will use the [`Display`] formatting trait.
//!
//! ## Positional parameters
//!
//! Each formatting argument is allowed to specify which value argument it's
//! referencing, and if omitted it is assumed to be "the next argument". For
//! example, the format string `{} {} {}` would take three parameters, and they
//! would be formatted in the same order as they're given. The format string
//! `{2} {1} {0}`, however, would format arguments in reverse order.
//!
//! Things can get a little tricky once you start intermingling the two types of
//! positional specifiers. The "next argument" specifier can be thought of as an
//! iterator over the argument. Each time a "next argument" specifier is seen,
//! the iterator advances. This leads to behavior like this:
//!
//! ```
//! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
//! ```
//!
//! The internal iterator over the argument has not been advanced by the time
//! the first `{}` is seen, so it prints the first argument. Then upon reaching
//! the second `{}`, the iterator has advanced forward to the second argument.
//! Essentially, parameters that explicitly name their argument do not affect
//! parameters that do not name an argument in terms of positional specifiers.
//!
//! A format string is required to use all of its arguments, otherwise it is a
//! compile-time error. You may refer to the same argument more than once in the
//! format string.
//!
//! ## Named parameters
//!
//! Rust itself does not have a Python-like equivalent of named parameters to a
//! function, but the [`format!`] macro is a syntax extension that allows it to
//! leverage named parameters. Named parameters are listed at the end of the
//! argument list and have the syntax:
//!
//! ```text
//! identifier '=' expression
//! ```
//!
//! For example, the following [`format!`] expressions all use named argument:
//!
//! ```
//! format!("{argument}", argument = "test"); // => "test"
//! format!("{name} {}", 1, name = 2); // => "2 1"
//! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
//! ```
//!
//! It is not valid to put positional parameters (those without names) after
//! arguments that have names. Like with positional parameters, it is not
//! valid to provide named parameters that are unused by the format string.
//!
//! # Formatting Parameters
//!
//! Each argument being formatted can be transformed by a number of formatting
//! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These
//! parameters affect the string representation of what's being formatted.
//!
//! ## Width
//!
//! ```
//! // All of these print "Hello x !"
//! println!("Hello {:5}!", "x");
//! println!("Hello {:1$}!", "x", 5);
//! println!("Hello {1:0$}!", 5, "x");
//! println!("Hello {:width$}!", "x", width = 5);
//! ```
//!
//! This is a parameter for the "minimum width" that the format should take up.
//! If the value's string does not fill up this many characters, then the
//! padding specified by fill/alignment will be used to take up the required
//! space (see below).
//!
//! The value for the width can also be provided as a [`usize`] in the list of
//! parameters by adding a postfix `$`, indicating that the second argument is
//! a [`usize`] specifying the width.
//!
//! Referring to an argument with the dollar syntax does not affect the "next
//! argument" counter, so it's usually a good idea to refer to arguments by
//! position, or use named arguments.
//!
//! ## Fill/Alignment
//!
//! ```
//! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !");
//! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!");
//! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !");
//! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!");
//! ```
//!
//! The optional fill character and alignment is provided normally in conjunction with the
//! [`width`](#width) parameter. It must be defined before `width`, right after the `:`.
//! This indicates that if the value being formatted is smaller than
//! `width` some extra characters will be printed around it.
//! Filling comes in the following variants for different alignments:
//!
//! * `[fill]<` - the argument is left-aligned in `width` columns
//! * `[fill]^` - the argument is center-aligned in `width` columns
//! * `[fill]>` - the argument is right-aligned in `width` columns
//!
//! The default [fill/alignment](#fillalignment) for non-numerics is a space and
//! left-aligned. The
//! default for numeric formatters is also a space character but with right-alignment. If
//! the `0` flag (see below) is specified for numerics, then the implicit fill character is
//! `0`.
//!
//! Note that alignment might not be implemented by some types. In particular, it
//! is not generally implemented for the `Debug` trait. A good way to ensure
//! padding is applied is to format your input, then pad this resulting string
//! to obtain your output:
//!
//! ```
//! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !"
//! ```
//!
//! ## Sign/`#`/`0`
//!
//! ```
//! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!");
//! assert_eq!(format!("{:#x}!", 27), "0x1b!");
//! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!");
//! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!");
//! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!");
//! ```
//!
//! These are all flags altering the behavior of the formatter.
//!
//! * `+` - This is intended for numeric types and indicates that the sign
//! should always be printed. Positive signs are never printed by
//! default, and the negative sign is only printed by default for signed values.
//! This flag indicates that the correct sign (`+` or `-`) should always be printed.
//! * `-` - Currently not used
//! * `#` - This flag indicates that the "alternate" form of printing should
//! be used. The alternate forms are:
//! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
//! * `#x` - precedes the argument with a `0x`
//! * `#X` - precedes the argument with a `0x`
//! * `#b` - precedes the argument with a `0b`
//! * `#o` - precedes the argument with a `0o`
//! * `0` - This is used to indicate for integer formats that the padding to `width` should
//! both be done with a `0` character as well as be sign-aware. A format
//! like `{:08}` would yield `00000001` for the integer `1`, while the
//! same format would yield `-0000001` for the integer `-1`. Notice that
//! the negative version has one fewer zero than the positive version.
//! Note that padding zeros are always placed after the sign (if any)
//! and before the digits. When used together with the `#` flag, a similar
//! rule applies: padding zeros are inserted after the prefix but before
//! the digits. The prefix is included in the total width.
//!
//! ## Precision
//!
//! For non-numeric types, this can be considered a "maximum width". If the resulting string is
//! longer than this width, then it is truncated down to this many characters and that truncated
//! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set.
//!
//! For integral types, this is ignored.
//!
//! For floating-point types, this indicates how many digits after the decimal point should be
//! printed.
//!
//! There are three possible ways to specify the desired `precision`:
//!
//! 1. An integer `.N`:
//!
//! the integer `N` itself is the precision.
//!
//! 2. An integer or name followed by dollar sign `.N$`:
//!
//! use format *argument* `N` (which must be a `usize`) as the precision.
//!
//! 3. An asterisk `.*`:
//!
//! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the
//! first input holds the `usize` precision, and the second holds the value to print. Note that
//! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers
//! to the *value* to print, and the `precision` must come in the input preceding `<arg>`.
//!
//! For example, the following calls all print the same thing `Hello x is 0.01000`:
//!
//! ```
//! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)}
//! println!("Hello {0} is {1:.5}", "x", 0.01);
//!
//! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)}
//! println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
//!
//! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)}
//! println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {second of next two args (0.01) with precision
//! // specified in first of next two args (5)}
//! println!("Hello {} is {:.*}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {arg 2 (0.01) with precision
//! // specified in its predecessor (5)}
//! println!("Hello {} is {2:.*}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified
//! // in arg "prec" (5)}
//! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
//! ```
//!
//! While these:
//!
//! ```
//! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
//! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
//! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
//! ```
//!
//! print three significantly different things:
//!
//! ```text
//! Hello, `1234.560` has 3 fractional digits
//! Hello, `123` has 3 characters
//! Hello, ` 123` has 3 right-aligned characters
//! ```
//!
//! ## Localization
//!
//! In some programming languages, the behavior of string formatting functions
//! depends on the operating system's locale setting. The format functions
//! provided by Rust's standard library do not have any concept of locale and
//! will produce the same results on all systems regardless of user
//! configuration.
//!
//! For example, the following code will always print `1.5` even if the system
//! locale uses a decimal separator other than a dot.
//!
//! ```
//! println!("The value is {}", 1.5);
//! ```
//!
//! # Escaping
//!
//! The literal characters `{` and `}` may be included in a string by preceding
//! them with the same character. For example, the `{` character is escaped with
//! `{{` and the `}` character is escaped with `}}`.
//!
//! ```
//! assert_eq!(format!("Hello {{}}"), "Hello {}");
//! assert_eq!(format!("{{ Hello"), "{ Hello");
//! ```
//!
//! # Syntax
//!
//! To summarize, here you can find the full grammar of format strings.
//! The syntax for the formatting language used is drawn from other languages,
//! so it should not be too alien. Arguments are formatted with Python-like
//! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
//! `%`. The actual grammar for the formatting syntax is:
//!
//! ```text
//! format_string := text [ maybe_format text ] *
//! maybe_format := '{' '{' | '}' '}' | format
//! format := '{' [ argument ] [ ':' format_spec ] '}'
//! argument := integer | identifier
//!
//! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
//! fill := character
//! align := '<' | '^' | '>'
//! sign := '+' | '-'
//! width := count
//! precision := count | '*'
//! type := '' | '?' | 'x?' | 'X?' | identifier
//! count := parameter | integer
//! parameter := argument '$'
//! ```
//! In the above grammar, `text` must not contain any `'{'` or `'}'` characters.
//!
//! # Formatting traits
//!
//! When requesting that an argument be formatted with a particular type, you
//! are actually requesting that an argument ascribes to a particular trait.
//! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as
//! well as [`isize`]). The current mapping of types to traits is:
//!
//! * *nothing* β [`Display`]
//! * `?` β [`Debug`]
//! * `x?` β [`Debug`] with lower-case hexadecimal integers
//! * `X?` β [`Debug`] with upper-case hexadecimal integers
//! * `o` β [`Octal`]
//! * `x` β [`LowerHex`]
//! * `X` β [`UpperHex`]
//! * `p` β [`Pointer`]
//! * `b` β [`Binary`]
//! * `e` β [`LowerExp`]
//! * `E` β [`UpperExp`]
//!
//! What this means is that any type of argument which implements the
//! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations
//! are provided for these traits for a number of primitive types by the
//! standard library as well. If no format is specified (as in `{}` or `{:6}`),
//! then the format trait used is the [`Display`] trait.
//!
//! When implementing a format trait for your own type, you will have to
//! implement a method of the signature:
//!
//! ```
//! # #![allow(dead_code)]
//! # use std::fmt;
//! # struct Foo; // our custom type
//! # impl fmt::Display for Foo {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! # write!(f, "testing, testing")
//! # } }
//! ```
//!
//! Your type will be passed as `self` by-reference, and then the function
//! should emit output into the `f.buf` stream. It is up to each format trait
//! implementation to correctly adhere to the requested formatting parameters.
//! The values of these parameters will be listed in the fields of the
//! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also
//! provides some helper methods.
//!
//! Additionally, the return value of this function is [`fmt::Result`] which is a
//! type alias of [`Result`]`<(), `[`std::fmt::Error`]`>`. Formatting implementations
//! should ensure that they propagate errors from the [`Formatter`] (e.g., when
//! calling [`write!`]). However, they should never return errors spuriously. That
//! is, a formatting implementation must and may only return an error if the
//! passed-in [`Formatter`] returns an error. This is because, contrary to what
//! the function signature might suggest, string formatting is an infallible
//! operation. This function only returns a result because writing to the
//! underlying stream might fail and it must provide a way to propagate the fact
//! that an error has occurred back up the stack.
//!
//! An example of implementing the formatting traits would look
//! like:
//!
//! ```
//! use std::fmt;
//!
//! #[derive(Debug)]
//! struct Vector2D {
//! x: isize,
//! y: isize,
//! }
//!
//! impl fmt::Display for Vector2D {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! // The `f` value implements the `Write` trait, which is what the
//! // write! macro is expecting. Note that this formatting ignores the
//! // various flags provided to format strings.
//! write!(f, "({}, {})", self.x, self.y)
//! }
//! }
//!
//! // Different traits allow different forms of output of a type. The meaning
//! // of this format is to print the magnitude of a vector.
//! impl fmt::Binary for Vector2D {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! let magnitude = (self.x * self.x + self.y * self.y) as f64;
//! let magnitude = magnitude.sqrt();
//!
//! // Respect the formatting flags by using the helper method
//! // `pad_integral` on the Formatter object. See the method
//! // documentation for details, and the function `pad` can be used
//! // to pad strings.
//! let decimals = f.precision().unwrap_or(3);
//! let string = format!("{:.*}", decimals, magnitude);
//! f.pad_integral(true, "", &string)
//! }
//! }
//!
//! fn main() {
//! let myvector = Vector2D { x: 3, y: 4 };
//!
//! println!("{}", myvector); // => "(3, 4)"
//! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}"
//! println!("{:10.3b}", myvector); // => " 5.000"
//! }
//! ```
//!
//! ### `fmt::Display` vs `fmt::Debug`
//!
//! These two formatting traits have distinct purposes:
//!
//! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully
//! represented as a UTF-8 string at all times. It is **not** expected that
//! all types implement the [`Display`] trait.
//! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types.
//! Output will typically represent the internal state as faithfully as possible.
//! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In
//! most cases, using `#[derive(Debug)]` is sufficient and recommended.
//!
//! Some examples of the output from both traits:
//!
//! ```
//! assert_eq!(format!("{} {:?}", 3, 4), "3 4");
//! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
//! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
//! ```
//!
//! # Related macros
//!
//! There are a number of related macros in the [`format!`] family. The ones that
//! are currently implemented are:
//!
//! ```ignore (only-for-syntax-highlight)
//! format! // described above
//! write! // first argument is a &mut io::Write, the destination
//! writeln! // same as write but appends a newline
//! print! // the format string is printed to the standard output
//! println! // same as print but appends a newline
//! eprint! // the format string is printed to the standard error
//! eprintln! // same as eprint but appends a newline
//! format_args! // described below.
//! ```
//!
//! ### `write!`
//!
//! This and [`writeln!`] are two macros which are used to emit the format string
//! to a specified stream. This is used to prevent intermediate allocations of
//! format strings and instead directly write the output. Under the hood, this
//! function is actually invoking the [`write_fmt`] function defined on the
//! [`std::io::Write`] trait. Example usage is:
//!
//! ```
//! # #![allow(unused_must_use)]
//! use std::io::Write;
//! let mut w = Vec::new();
//! write!(&mut w, "Hello {}!", "world");
//! ```
//!
//! ### `print!`
//!
//! This and [`println!`] emit their output to stdout. Similarly to the [`write!`]
//! macro, the goal of these macros is to avoid intermediate allocations when
//! printing output. Example usage is:
//!
//! ```
//! print!("Hello {}!", "world");
//! println!("I have a newline {}", "character at the end");
//! ```
//! ### `eprint!`
//!
//! The [`eprint!`] and [`eprintln!`] macros are identical to
//! [`print!`] and [`println!`], respectively, except they emit their
//! output to stderr.
//!
//! ### `format_args!`
//!
//! This is a curious macro used to safely pass around
//! an opaque object describing the format string. This object
//! does not require any heap allocations to create, and it only
//! references information on the stack. Under the hood, all of
//! the related macros are implemented in terms of this. First
//! off, some example usage is:
//!
//! ```
//! # #![allow(unused_must_use)]
//! use std::fmt;
//! use std::io::{self, Write};
//!
//! let mut some_writer = io::stdout();
//! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
//!
//! fn my_fmt_fn(args: fmt::Arguments) {
//! write!(&mut io::stdout(), "{}", args);
//! }
//! my_fmt_fn(format_args!(", or a {} too", "function"));
//! ```
//!
//! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`].
//! This structure can then be passed to the [`write`] and [`format`] functions
//! inside this module in order to process the format string.
//! The goal of this macro is to even further prevent intermediate allocations
//! when dealing with formatting strings.
//!
//! For example, a logging library could use the standard formatting syntax, but
//! it would internally pass around this structure until it has been determined
//! where output should go to.
//!
//! [`fmt::Result`]: Result
//! [`Result`]: core::result::Result
//! [`std::fmt::Error`]: Error
//! [`write!`]: core::write
//! [`write`]: core::write
//! [`format!`]: crate::format
//! [`to_string`]: crate::string::ToString
//! [`writeln!`]: core::writeln
//! [`write_fmt`]:../../std/io/trait.Write.html#method.write_fmt
//! [`std::io::Write`]:../../std/io/trait.Write.html
//! [`print!`]:../../std/macro.print.html
//! [`println!`]:../../std/macro.println.html
//! [`eprint!`]:../../std/macro.eprint.html
//! [`eprintln!`]:../../std/macro.eprintln.html
//! [`format_args!`]: core::format_args
//! [`fmt::Arguments`]: Arguments
//! [`format`]: crate::format
#![stable(feature = "rust1", since = "1.0.0")]
#[unstable(feature = "fmt_internals", issue = "none")]
pub use core::fmt::rt;
#[stable(feature = "fmt_flags_align", since = "1.28.0")]
pub use core::fmt::Alignment;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::Error;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{write, ArgumentV1, Arguments};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Binary, Octal};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Debug, Display};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Formatter, Result, Write};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{LowerExp, UpperExp};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{LowerHex, Pointer, UpperHex};
#[cfg(not(no_global_oom_handling))]
use crate::string;
/// The `format` function takes an [`Arguments`] struct and returns the resulting
/// formatted string.
///
/// The [`Arguments`] instance can be created with the [`format_args!`] macro.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::fmt;
///
/// let s = fmt::format(format_args!("Hello, {}!", "world"));
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// Please note that using [`format!`] might be preferable.
/// Example:
///
/// ```
/// let s = format!("Hello, {}!", "world");
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// [`format_args!`]: core::format_args
/// [`format!`]: crate::format
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn format(args: Arguments
|
-> string::String {
let capacity = args.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}
|
<'_>)
|
identifier_name
|
fmt.rs
|
//! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro is intended to be familiar to those coming from C's
//! `printf`/`fprintf` functions or Python's `str.format` function.
//!
//! Some examples of the [`format!`] extension are:
//!
//! ```
//! format!("Hello"); // => "Hello"
//! format!("Hello, {}!", "world"); // => "Hello, world!"
//! format!("The number is {}", 1); // => "The number is 1"
//! format!("{:?}", (3, 4)); // => "(3, 4)"
//! format!("{value}", value=4); // => "4"
//! format!("{} {}", 1, 2); // => "1 2"
//! format!("{:04}", 42); // => "0042" with leading zeros
//! format!("{:#?}", (100, 200)); // => "(
//! // 100,
//! // 200,
//! // )"
//! ```
//!
//! From these, you can see that the first argument is a format string. It is
//! required by the compiler for this to be a string literal; it cannot be a
//! variable passed in (in order to perform validity checking). The compiler
//! will then parse the format string and determine if the list of arguments
//! provided is suitable to pass to this format string.
//!
//! To convert a single value to a string, use the [`to_string`] method. This
//! will use the [`Display`] formatting trait.
//!
//! ## Positional parameters
//!
//! Each formatting argument is allowed to specify which value argument it's
//! referencing, and if omitted it is assumed to be "the next argument". For
//! example, the format string `{} {} {}` would take three parameters, and they
//! would be formatted in the same order as they're given. The format string
//! `{2} {1} {0}`, however, would format arguments in reverse order.
//!
//! Things can get a little tricky once you start intermingling the two types of
//! positional specifiers. The "next argument" specifier can be thought of as an
//! iterator over the argument. Each time a "next argument" specifier is seen,
//! the iterator advances. This leads to behavior like this:
//!
//! ```
//! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
//! ```
//!
//! The internal iterator over the argument has not been advanced by the time
//! the first `{}` is seen, so it prints the first argument. Then upon reaching
//! the second `{}`, the iterator has advanced forward to the second argument.
//! Essentially, parameters that explicitly name their argument do not affect
//! parameters that do not name an argument in terms of positional specifiers.
//!
//! A format string is required to use all of its arguments, otherwise it is a
//! compile-time error. You may refer to the same argument more than once in the
//! format string.
//!
//! ## Named parameters
//!
//! Rust itself does not have a Python-like equivalent of named parameters to a
//! function, but the [`format!`] macro is a syntax extension that allows it to
//! leverage named parameters. Named parameters are listed at the end of the
//! argument list and have the syntax:
//!
//! ```text
//! identifier '=' expression
//! ```
//!
//! For example, the following [`format!`] expressions all use named argument:
//!
//! ```
//! format!("{argument}", argument = "test"); // => "test"
//! format!("{name} {}", 1, name = 2); // => "2 1"
//! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
//! ```
//!
//! It is not valid to put positional parameters (those without names) after
//! arguments that have names. Like with positional parameters, it is not
//! valid to provide named parameters that are unused by the format string.
//!
//! # Formatting Parameters
//!
//! Each argument being formatted can be transformed by a number of formatting
//! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These
//! parameters affect the string representation of what's being formatted.
//!
//! ## Width
//!
//! ```
//! // All of these print "Hello x !"
//! println!("Hello {:5}!", "x");
//! println!("Hello {:1$}!", "x", 5);
//! println!("Hello {1:0$}!", 5, "x");
//! println!("Hello {:width$}!", "x", width = 5);
//! ```
//!
//! This is a parameter for the "minimum width" that the format should take up.
//! If the value's string does not fill up this many characters, then the
//! padding specified by fill/alignment will be used to take up the required
//! space (see below).
//!
//! The value for the width can also be provided as a [`usize`] in the list of
//! parameters by adding a postfix `$`, indicating that the second argument is
//! a [`usize`] specifying the width.
//!
//! Referring to an argument with the dollar syntax does not affect the "next
//! argument" counter, so it's usually a good idea to refer to arguments by
//! position, or use named arguments.
//!
//! ## Fill/Alignment
//!
//! ```
//! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !");
//! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!");
//! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !");
//! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!");
//! ```
//!
//! The optional fill character and alignment is provided normally in conjunction with the
//! [`width`](#width) parameter. It must be defined before `width`, right after the `:`.
//! This indicates that if the value being formatted is smaller than
//! `width` some extra characters will be printed around it.
//! Filling comes in the following variants for different alignments:
//!
//! * `[fill]<` - the argument is left-aligned in `width` columns
//! * `[fill]^` - the argument is center-aligned in `width` columns
//! * `[fill]>` - the argument is right-aligned in `width` columns
//!
//! The default [fill/alignment](#fillalignment) for non-numerics is a space and
//! left-aligned. The
//! default for numeric formatters is also a space character but with right-alignment. If
//! the `0` flag (see below) is specified for numerics, then the implicit fill character is
//! `0`.
//!
//! Note that alignment might not be implemented by some types. In particular, it
//! is not generally implemented for the `Debug` trait. A good way to ensure
//! padding is applied is to format your input, then pad this resulting string
//! to obtain your output:
//!
//! ```
//! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !"
//! ```
//!
//! ## Sign/`#`/`0`
//!
//! ```
//! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!");
//! assert_eq!(format!("{:#x}!", 27), "0x1b!");
//! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!");
//! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!");
//! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!");
//! ```
//!
//! These are all flags altering the behavior of the formatter.
//!
//! * `+` - This is intended for numeric types and indicates that the sign
//! should always be printed. Positive signs are never printed by
//! default, and the negative sign is only printed by default for signed values.
//! This flag indicates that the correct sign (`+` or `-`) should always be printed.
//! * `-` - Currently not used
//! * `#` - This flag indicates that the "alternate" form of printing should
//! be used. The alternate forms are:
//! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
//! * `#x` - precedes the argument with a `0x`
//! * `#X` - precedes the argument with a `0x`
//! * `#b` - precedes the argument with a `0b`
//! * `#o` - precedes the argument with a `0o`
//! * `0` - This is used to indicate for integer formats that the padding to `width` should
//! both be done with a `0` character as well as be sign-aware. A format
//! like `{:08}` would yield `00000001` for the integer `1`, while the
//! same format would yield `-0000001` for the integer `-1`. Notice that
//! the negative version has one fewer zero than the positive version.
//! Note that padding zeros are always placed after the sign (if any)
//! and before the digits. When used together with the `#` flag, a similar
//! rule applies: padding zeros are inserted after the prefix but before
//! the digits. The prefix is included in the total width.
//!
//! ## Precision
//!
//! For non-numeric types, this can be considered a "maximum width". If the resulting string is
//! longer than this width, then it is truncated down to this many characters and that truncated
//! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set.
//!
//! For integral types, this is ignored.
//!
//! For floating-point types, this indicates how many digits after the decimal point should be
//! printed.
//!
//! There are three possible ways to specify the desired `precision`:
//!
//! 1. An integer `.N`:
//!
//! the integer `N` itself is the precision.
//!
//! 2. An integer or name followed by dollar sign `.N$`:
//!
//! use format *argument* `N` (which must be a `usize`) as the precision.
//!
//! 3. An asterisk `.*`:
//!
//! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the
//! first input holds the `usize` precision, and the second holds the value to print. Note that
//! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers
//! to the *value* to print, and the `precision` must come in the input preceding `<arg>`.
//!
//! For example, the following calls all print the same thing `Hello x is 0.01000`:
//!
//! ```
//! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)}
//! println!("Hello {0} is {1:.5}", "x", 0.01);
//!
//! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)}
//! println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
//!
//! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)}
//! println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {second of next two args (0.01) with precision
//! // specified in first of next two args (5)}
//! println!("Hello {} is {:.*}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {arg 2 (0.01) with precision
//! // specified in its predecessor (5)}
//! println!("Hello {} is {2:.*}", "x", 5, 0.01);
//!
//! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified
//! // in arg "prec" (5)}
//! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
//! ```
//!
//! While these:
//!
//! ```
//! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
//! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
//! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
//! ```
//!
//! print three significantly different things:
//!
//! ```text
//! Hello, `1234.560` has 3 fractional digits
//! Hello, `123` has 3 characters
//! Hello, ` 123` has 3 right-aligned characters
//! ```
//!
//! ## Localization
//!
//! In some programming languages, the behavior of string formatting functions
//! depends on the operating system's locale setting. The format functions
//! provided by Rust's standard library do not have any concept of locale and
//! will produce the same results on all systems regardless of user
//! configuration.
//!
//! For example, the following code will always print `1.5` even if the system
//! locale uses a decimal separator other than a dot.
//!
//! ```
//! println!("The value is {}", 1.5);
//! ```
//!
//! # Escaping
//!
//! The literal characters `{` and `}` may be included in a string by preceding
//! them with the same character. For example, the `{` character is escaped with
//! `{{` and the `}` character is escaped with `}}`.
//!
//! ```
//! assert_eq!(format!("Hello {{}}"), "Hello {}");
//! assert_eq!(format!("{{ Hello"), "{ Hello");
//! ```
//!
//! # Syntax
//!
//! To summarize, here you can find the full grammar of format strings.
//! The syntax for the formatting language used is drawn from other languages,
//! so it should not be too alien. Arguments are formatted with Python-like
//! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
//! `%`. The actual grammar for the formatting syntax is:
//!
//! ```text
//! format_string := text [ maybe_format text ] *
//! maybe_format := '{' '{' | '}' '}' | format
//! format := '{' [ argument ] [ ':' format_spec ] '}'
//! argument := integer | identifier
//!
//! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
//! fill := character
//! align := '<' | '^' | '>'
//! sign := '+' | '-'
//! width := count
//! precision := count | '*'
//! type := '' | '?' | 'x?' | 'X?' | identifier
//! count := parameter | integer
//! parameter := argument '$'
//! ```
//! In the above grammar, `text` must not contain any `'{'` or `'}'` characters.
//!
//! # Formatting traits
//!
//! When requesting that an argument be formatted with a particular type, you
//! are actually requesting that an argument ascribes to a particular trait.
//! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as
//! well as [`isize`]). The current mapping of types to traits is:
//!
//! * *nothing* β [`Display`]
//! * `?` β [`Debug`]
//! * `x?` β [`Debug`] with lower-case hexadecimal integers
//! * `X?` β [`Debug`] with upper-case hexadecimal integers
//! * `o` β [`Octal`]
//! * `x` β [`LowerHex`]
//! * `X` β [`UpperHex`]
//! * `p` β [`Pointer`]
//! * `b` β [`Binary`]
//! * `e` β [`LowerExp`]
//! * `E` β [`UpperExp`]
//!
//! What this means is that any type of argument which implements the
//! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations
//! are provided for these traits for a number of primitive types by the
//! standard library as well. If no format is specified (as in `{}` or `{:6}`),
//! then the format trait used is the [`Display`] trait.
//!
//! When implementing a format trait for your own type, you will have to
//! implement a method of the signature:
//!
//! ```
//! # #![allow(dead_code)]
//! # use std::fmt;
//! # struct Foo; // our custom type
//! # impl fmt::Display for Foo {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! # write!(f, "testing, testing")
//! # } }
//! ```
|
//! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also
//! provides some helper methods.
//!
//! Additionally, the return value of this function is [`fmt::Result`] which is a
//! type alias of [`Result`]`<(), `[`std::fmt::Error`]`>`. Formatting implementations
//! should ensure that they propagate errors from the [`Formatter`] (e.g., when
//! calling [`write!`]). However, they should never return errors spuriously. That
//! is, a formatting implementation must and may only return an error if the
//! passed-in [`Formatter`] returns an error. This is because, contrary to what
//! the function signature might suggest, string formatting is an infallible
//! operation. This function only returns a result because writing to the
//! underlying stream might fail and it must provide a way to propagate the fact
//! that an error has occurred back up the stack.
//!
//! An example of implementing the formatting traits would look
//! like:
//!
//! ```
//! use std::fmt;
//!
//! #[derive(Debug)]
//! struct Vector2D {
//! x: isize,
//! y: isize,
//! }
//!
//! impl fmt::Display for Vector2D {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! // The `f` value implements the `Write` trait, which is what the
//! // write! macro is expecting. Note that this formatting ignores the
//! // various flags provided to format strings.
//! write!(f, "({}, {})", self.x, self.y)
//! }
//! }
//!
//! // Different traits allow different forms of output of a type. The meaning
//! // of this format is to print the magnitude of a vector.
//! impl fmt::Binary for Vector2D {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! let magnitude = (self.x * self.x + self.y * self.y) as f64;
//! let magnitude = magnitude.sqrt();
//!
//! // Respect the formatting flags by using the helper method
//! // `pad_integral` on the Formatter object. See the method
//! // documentation for details, and the function `pad` can be used
//! // to pad strings.
//! let decimals = f.precision().unwrap_or(3);
//! let string = format!("{:.*}", decimals, magnitude);
//! f.pad_integral(true, "", &string)
//! }
//! }
//!
//! fn main() {
//! let myvector = Vector2D { x: 3, y: 4 };
//!
//! println!("{}", myvector); // => "(3, 4)"
//! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}"
//! println!("{:10.3b}", myvector); // => " 5.000"
//! }
//! ```
//!
//! ### `fmt::Display` vs `fmt::Debug`
//!
//! These two formatting traits have distinct purposes:
//!
//! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully
//! represented as a UTF-8 string at all times. It is **not** expected that
//! all types implement the [`Display`] trait.
//! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types.
//! Output will typically represent the internal state as faithfully as possible.
//! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In
//! most cases, using `#[derive(Debug)]` is sufficient and recommended.
//!
//! Some examples of the output from both traits:
//!
//! ```
//! assert_eq!(format!("{} {:?}", 3, 4), "3 4");
//! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
//! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
//! ```
//!
//! # Related macros
//!
//! There are a number of related macros in the [`format!`] family. The ones that
//! are currently implemented are:
//!
//! ```ignore (only-for-syntax-highlight)
//! format! // described above
//! write! // first argument is a &mut io::Write, the destination
//! writeln! // same as write but appends a newline
//! print! // the format string is printed to the standard output
//! println! // same as print but appends a newline
//! eprint! // the format string is printed to the standard error
//! eprintln! // same as eprint but appends a newline
//! format_args! // described below.
//! ```
//!
//! ### `write!`
//!
//! This and [`writeln!`] are two macros which are used to emit the format string
//! to a specified stream. This is used to prevent intermediate allocations of
//! format strings and instead directly write the output. Under the hood, this
//! function is actually invoking the [`write_fmt`] function defined on the
//! [`std::io::Write`] trait. Example usage is:
//!
//! ```
//! # #![allow(unused_must_use)]
//! use std::io::Write;
//! let mut w = Vec::new();
//! write!(&mut w, "Hello {}!", "world");
//! ```
//!
//! ### `print!`
//!
//! This and [`println!`] emit their output to stdout. Similarly to the [`write!`]
//! macro, the goal of these macros is to avoid intermediate allocations when
//! printing output. Example usage is:
//!
//! ```
//! print!("Hello {}!", "world");
//! println!("I have a newline {}", "character at the end");
//! ```
//! ### `eprint!`
//!
//! The [`eprint!`] and [`eprintln!`] macros are identical to
//! [`print!`] and [`println!`], respectively, except they emit their
//! output to stderr.
//!
//! ### `format_args!`
//!
//! This is a curious macro used to safely pass around
//! an opaque object describing the format string. This object
//! does not require any heap allocations to create, and it only
//! references information on the stack. Under the hood, all of
//! the related macros are implemented in terms of this. First
//! off, some example usage is:
//!
//! ```
//! # #![allow(unused_must_use)]
//! use std::fmt;
//! use std::io::{self, Write};
//!
//! let mut some_writer = io::stdout();
//! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
//!
//! fn my_fmt_fn(args: fmt::Arguments) {
//! write!(&mut io::stdout(), "{}", args);
//! }
//! my_fmt_fn(format_args!(", or a {} too", "function"));
//! ```
//!
//! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`].
//! This structure can then be passed to the [`write`] and [`format`] functions
//! inside this module in order to process the format string.
//! The goal of this macro is to even further prevent intermediate allocations
//! when dealing with formatting strings.
//!
//! For example, a logging library could use the standard formatting syntax, but
//! it would internally pass around this structure until it has been determined
//! where output should go to.
//!
//! [`fmt::Result`]: Result
//! [`Result`]: core::result::Result
//! [`std::fmt::Error`]: Error
//! [`write!`]: core::write
//! [`write`]: core::write
//! [`format!`]: crate::format
//! [`to_string`]: crate::string::ToString
//! [`writeln!`]: core::writeln
//! [`write_fmt`]:../../std/io/trait.Write.html#method.write_fmt
//! [`std::io::Write`]:../../std/io/trait.Write.html
//! [`print!`]:../../std/macro.print.html
//! [`println!`]:../../std/macro.println.html
//! [`eprint!`]:../../std/macro.eprint.html
//! [`eprintln!`]:../../std/macro.eprintln.html
//! [`format_args!`]: core::format_args
//! [`fmt::Arguments`]: Arguments
//! [`format`]: crate::format
#![stable(feature = "rust1", since = "1.0.0")]
#[unstable(feature = "fmt_internals", issue = "none")]
pub use core::fmt::rt;
#[stable(feature = "fmt_flags_align", since = "1.28.0")]
pub use core::fmt::Alignment;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::Error;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{write, ArgumentV1, Arguments};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Binary, Octal};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Debug, Display};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Formatter, Result, Write};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{LowerExp, UpperExp};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{LowerHex, Pointer, UpperHex};
#[cfg(not(no_global_oom_handling))]
use crate::string;
/// The `format` function takes an [`Arguments`] struct and returns the resulting
/// formatted string.
///
/// The [`Arguments`] instance can be created with the [`format_args!`] macro.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::fmt;
///
/// let s = fmt::format(format_args!("Hello, {}!", "world"));
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// Please note that using [`format!`] might be preferable.
/// Example:
///
/// ```
/// let s = format!("Hello, {}!", "world");
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// [`format_args!`]: core::format_args
/// [`format!`]: crate::format
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn format(args: Arguments<'_>) -> string::String {
let capacity = args.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}
|
//!
//! Your type will be passed as `self` by-reference, and then the function
//! should emit output into the `f.buf` stream. It is up to each format trait
//! implementation to correctly adhere to the requested formatting parameters.
//! The values of these parameters will be listed in the fields of the
|
random_line_split
|
maps.rs
|
// #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>) -> Result<(), CassError>
|
print_error(future);
}
cass_future_free(future);
cass_statement_free(statement);
Ok(())
}
}
fn select_from_maps(session: &mut CassSession, key: &str) -> Result<(), CassError> {
unsafe {
let query = "SELECT items FROM examples.maps WHERE key =?";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let result = match cass_future_error_code(future) {
CASS_OK => {
let result = cass_future_get_result(future);
if cass_result_row_count(result) > 0 {
let row = cass_result_first_row(result);
let iterator = cass_iterator_from_map(cass_row_get_column(row, 0));
while cass_iterator_next(iterator) == cass_true {
let mut item_key = mem::zeroed();
let mut item_key_length = mem::zeroed();
let mut value = mem::zeroed();
cass_value_get_string(cass_iterator_get_map_key(iterator),
&mut item_key,
&mut item_key_length);
cass_value_get_int32(cass_iterator_get_map_value(iterator), &mut value);
println!("item: '{:?}' : {:?}",
raw2utf8(item_key, item_key_length),
value);
}
cass_iterator_free(iterator);
cass_result_free(result);
}
Ok(())
}
rc => Err(rc),
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn main() {
unsafe {
let items = vec![Pair {
key: "apple".to_owned(),
value: 1,
},
Pair {
key: "orange".to_owned(),
value: 2,
},
Pair {
key: "banana".to_owned(),
value: 3,
},
Pair {
key: "mango".to_owned(),
value: 4,
}];
let cluster = create_cluster();
let session = &mut *cass_session_new();
connect_session(session, &cluster).unwrap();
execute_query(session,
"CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': 'SimpleStrategy', \
'replication_factor': '3' };")
.unwrap();
execute_query(session,
"CREATE TABLE IF NOT EXISTS examples.maps (key text, items map<text, int>, PRIMARY KEY (key))")
.unwrap();
insert_into_maps(session, "test", items).unwrap();
select_from_maps(session, "test").unwrap();
let close_future = cass_session_close(session);
cass_future_wait(close_future);
cass_future_free(close_future);
cass_cluster_free(cluster);
cass_session_free(session);
}
}
|
{
unsafe {
let query = "INSERT INTO examples.maps (key, items) VALUES (?, ?);";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 2);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let collection = cass_collection_new(CASS_COLLECTION_TYPE_MAP, 5);
for item in items {
cass_collection_append_string(collection, CString::new(item.key).unwrap().as_ptr());
cass_collection_append_int32(collection, item.value);
}
cass_statement_bind_collection(statement, 1, collection);
cass_collection_free(collection);
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let rc = cass_future_error_code(future);
if rc != CASS_OK {
|
identifier_body
|
maps.rs
|
// #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>) -> Result<(), CassError> {
unsafe {
let query = "INSERT INTO examples.maps (key, items) VALUES (?,?);";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 2);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let collection = cass_collection_new(CASS_COLLECTION_TYPE_MAP, 5);
for item in items {
cass_collection_append_string(collection, CString::new(item.key).unwrap().as_ptr());
|
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let rc = cass_future_error_code(future);
if rc!= CASS_OK {
print_error(future);
}
cass_future_free(future);
cass_statement_free(statement);
Ok(())
}
}
fn select_from_maps(session: &mut CassSession, key: &str) -> Result<(), CassError> {
unsafe {
let query = "SELECT items FROM examples.maps WHERE key =?";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let result = match cass_future_error_code(future) {
CASS_OK => {
let result = cass_future_get_result(future);
if cass_result_row_count(result) > 0 {
let row = cass_result_first_row(result);
let iterator = cass_iterator_from_map(cass_row_get_column(row, 0));
while cass_iterator_next(iterator) == cass_true {
let mut item_key = mem::zeroed();
let mut item_key_length = mem::zeroed();
let mut value = mem::zeroed();
cass_value_get_string(cass_iterator_get_map_key(iterator),
&mut item_key,
&mut item_key_length);
cass_value_get_int32(cass_iterator_get_map_value(iterator), &mut value);
println!("item: '{:?}' : {:?}",
raw2utf8(item_key, item_key_length),
value);
}
cass_iterator_free(iterator);
cass_result_free(result);
}
Ok(())
}
rc => Err(rc),
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn main() {
unsafe {
let items = vec![Pair {
key: "apple".to_owned(),
value: 1,
},
Pair {
key: "orange".to_owned(),
value: 2,
},
Pair {
key: "banana".to_owned(),
value: 3,
},
Pair {
key: "mango".to_owned(),
value: 4,
}];
let cluster = create_cluster();
let session = &mut *cass_session_new();
connect_session(session, &cluster).unwrap();
execute_query(session,
"CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': 'SimpleStrategy', \
'replication_factor': '3' };")
.unwrap();
execute_query(session,
"CREATE TABLE IF NOT EXISTS examples.maps (key text, items map<text, int>, PRIMARY KEY (key))")
.unwrap();
insert_into_maps(session, "test", items).unwrap();
select_from_maps(session, "test").unwrap();
let close_future = cass_session_close(session);
cass_future_wait(close_future);
cass_future_free(close_future);
cass_cluster_free(cluster);
cass_session_free(session);
}
}
|
cass_collection_append_int32(collection, item.value);
}
cass_statement_bind_collection(statement, 1, collection);
cass_collection_free(collection);
|
random_line_split
|
maps.rs
|
// #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>) -> Result<(), CassError> {
unsafe {
let query = "INSERT INTO examples.maps (key, items) VALUES (?,?);";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 2);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let collection = cass_collection_new(CASS_COLLECTION_TYPE_MAP, 5);
for item in items {
cass_collection_append_string(collection, CString::new(item.key).unwrap().as_ptr());
cass_collection_append_int32(collection, item.value);
}
cass_statement_bind_collection(statement, 1, collection);
cass_collection_free(collection);
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let rc = cass_future_error_code(future);
if rc!= CASS_OK {
print_error(future);
}
cass_future_free(future);
cass_statement_free(statement);
Ok(())
}
}
fn select_from_maps(session: &mut CassSession, key: &str) -> Result<(), CassError> {
unsafe {
let query = "SELECT items FROM examples.maps WHERE key =?";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let result = match cass_future_error_code(future) {
CASS_OK => {
let result = cass_future_get_result(future);
if cass_result_row_count(result) > 0
|
}
Ok(())
}
rc => Err(rc),
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn main() {
unsafe {
let items = vec![Pair {
key: "apple".to_owned(),
value: 1,
},
Pair {
key: "orange".to_owned(),
value: 2,
},
Pair {
key: "banana".to_owned(),
value: 3,
},
Pair {
key: "mango".to_owned(),
value: 4,
}];
let cluster = create_cluster();
let session = &mut *cass_session_new();
connect_session(session, &cluster).unwrap();
execute_query(session,
"CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': 'SimpleStrategy', \
'replication_factor': '3' };")
.unwrap();
execute_query(session,
"CREATE TABLE IF NOT EXISTS examples.maps (key text, items map<text, int>, PRIMARY KEY (key))")
.unwrap();
insert_into_maps(session, "test", items).unwrap();
select_from_maps(session, "test").unwrap();
let close_future = cass_session_close(session);
cass_future_wait(close_future);
cass_future_free(close_future);
cass_cluster_free(cluster);
cass_session_free(session);
}
}
|
{
let row = cass_result_first_row(result);
let iterator = cass_iterator_from_map(cass_row_get_column(row, 0));
while cass_iterator_next(iterator) == cass_true {
let mut item_key = mem::zeroed();
let mut item_key_length = mem::zeroed();
let mut value = mem::zeroed();
cass_value_get_string(cass_iterator_get_map_key(iterator),
&mut item_key,
&mut item_key_length);
cass_value_get_int32(cass_iterator_get_map_value(iterator), &mut value);
println!("item: '{:?}' : {:?}",
raw2utf8(item_key, item_key_length),
value);
}
cass_iterator_free(iterator);
cass_result_free(result);
|
conditional_block
|
maps.rs
|
// #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct
|
{
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>) -> Result<(), CassError> {
unsafe {
let query = "INSERT INTO examples.maps (key, items) VALUES (?,?);";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 2);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let collection = cass_collection_new(CASS_COLLECTION_TYPE_MAP, 5);
for item in items {
cass_collection_append_string(collection, CString::new(item.key).unwrap().as_ptr());
cass_collection_append_int32(collection, item.value);
}
cass_statement_bind_collection(statement, 1, collection);
cass_collection_free(collection);
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let rc = cass_future_error_code(future);
if rc!= CASS_OK {
print_error(future);
}
cass_future_free(future);
cass_statement_free(statement);
Ok(())
}
}
fn select_from_maps(session: &mut CassSession, key: &str) -> Result<(), CassError> {
unsafe {
let query = "SELECT items FROM examples.maps WHERE key =?";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let result = match cass_future_error_code(future) {
CASS_OK => {
let result = cass_future_get_result(future);
if cass_result_row_count(result) > 0 {
let row = cass_result_first_row(result);
let iterator = cass_iterator_from_map(cass_row_get_column(row, 0));
while cass_iterator_next(iterator) == cass_true {
let mut item_key = mem::zeroed();
let mut item_key_length = mem::zeroed();
let mut value = mem::zeroed();
cass_value_get_string(cass_iterator_get_map_key(iterator),
&mut item_key,
&mut item_key_length);
cass_value_get_int32(cass_iterator_get_map_value(iterator), &mut value);
println!("item: '{:?}' : {:?}",
raw2utf8(item_key, item_key_length),
value);
}
cass_iterator_free(iterator);
cass_result_free(result);
}
Ok(())
}
rc => Err(rc),
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn main() {
unsafe {
let items = vec![Pair {
key: "apple".to_owned(),
value: 1,
},
Pair {
key: "orange".to_owned(),
value: 2,
},
Pair {
key: "banana".to_owned(),
value: 3,
},
Pair {
key: "mango".to_owned(),
value: 4,
}];
let cluster = create_cluster();
let session = &mut *cass_session_new();
connect_session(session, &cluster).unwrap();
execute_query(session,
"CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': 'SimpleStrategy', \
'replication_factor': '3' };")
.unwrap();
execute_query(session,
"CREATE TABLE IF NOT EXISTS examples.maps (key text, items map<text, int>, PRIMARY KEY (key))")
.unwrap();
insert_into_maps(session, "test", items).unwrap();
select_from_maps(session, "test").unwrap();
let close_future = cass_session_close(session);
cass_future_wait(close_future);
cass_future_free(close_future);
cass_cluster_free(cluster);
cass_session_free(session);
}
}
|
Pair
|
identifier_name
|
edition-keywords-2018-2018.rs
|
// run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
// if passes_ident!(async) == 1 {} // ERROR, reserved
if passes_ident!(r#async) == 1
|
// OK
// one_async::async(); // ERROR, reserved
// one_async::r#async(); // ERROR, unresolved name
// two_async::async(); // ERROR, reserved
two_async::r#async(); // OK
}
mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {}
|
{}
|
conditional_block
|
edition-keywords-2018-2018.rs
|
// run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
// if passes_ident!(async) == 1 {} // ERROR, reserved
if passes_ident!(r#async) == 1 {} // OK
// one_async::async(); // ERROR, reserved
// one_async::r#async(); // ERROR, unresolved name
// two_async::async(); // ERROR, reserved
two_async::r#async(); // OK
|
mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {}
|
}
|
random_line_split
|
edition-keywords-2018-2018.rs
|
// run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
// if passes_ident!(async) == 1 {} // ERROR, reserved
if passes_ident!(r#async) == 1 {} // OK
// one_async::async(); // ERROR, reserved
// one_async::r#async(); // ERROR, unresolved name
// two_async::async(); // ERROR, reserved
two_async::r#async(); // OK
}
mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn
|
() {}
|
main
|
identifier_name
|
edition-keywords-2018-2018.rs
|
// run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
// if passes_ident!(async) == 1 {} // ERROR, reserved
if passes_ident!(r#async) == 1 {} // OK
// one_async::async(); // ERROR, reserved
// one_async::r#async(); // ERROR, unresolved name
// two_async::async(); // ERROR, reserved
two_async::r#async(); // OK
}
mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn main()
|
{}
|
identifier_body
|
|
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
use servo_config::opts;
use signpost;
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
if let Err(e) = self.0.send(msg) {
warn!("Error communicating with the time profiler thread: {}", e);
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerData {
NoRecords,
Record(Vec<f64>),
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to get time spend entries for a particular ProfilerBuckets (in nanoseconds)
Get((ProfilerCategory, Option<TimerMetadata>), IpcSender<ProfilerData>),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum ProfilerCategory {
Compositing = 0x00,
LayoutPerform = 0x10,
LayoutStyleRecalc = 0x11,
LayoutTextShaping = 0x12,
LayoutRestyleDamagePropagation = 0x13,
LayoutNonIncrementalReset = 0x14,
LayoutSelectorMatch = 0x15,
LayoutTreeBuilder = 0x16,
LayoutDamagePropagate = 0x17,
LayoutGeneratedContent = 0x18,
LayoutDisplayListSorting = 0x19,
LayoutFloatPlacementSpeculation = 0x1a,
LayoutMain = 0x1b,
LayoutStoreOverflow = 0x1c,
LayoutParallelWarmup = 0x1d,
LayoutDispListBuild = 0x1e,
NetHTTPRequestResponse = 0x30,
PaintingPerTile = 0x41,
PaintingPrepBuff = 0x42,
Painting = 0x43,
ImageDecoding = 0x50,
ImageSaving = 0x51,
ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0x6a,
ScriptParseHTML = 0x6b,
ScriptPlannedNavigation = 0x6c,
ScriptResize = 0x6d,
ScriptSetScrollState = 0x6e,
ScriptSetViewport = 0x6f,
ScriptTimerEvent = 0x70,
ScriptStylesheetLoad = 0x71,
ScriptUpdateReplacedElement = 0x72,
ScriptWebSocketEvent = 0x73,
ScriptWorkerEvent = 0x74,
ScriptServiceWorkerEvent = 0x75,
ScriptParseXML = 0x76,
ScriptEnterFullscreen = 0x77,
ScriptExitFullscreen = 0x78,
ScriptWebVREvent = 0x79,
ScriptWorkletEvent = 0x7a,
ScriptPerformanceEvent = 0x7b,
TimeToFirstPaint = 0x80,
TimeToFirstContentfulPaint = 0x81,
TimeToInteractive = 0x82,
IpcReceiver = 0x83,
ApplicationHeartbeat = 0x90,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T,
{
if opts::get().signpost {
signpost::start(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
if opts::get().signpost
|
send_profile_data(category,
meta,
&profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: &ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
|
{
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
|
conditional_block
|
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
use servo_config::opts;
use signpost;
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
if let Err(e) = self.0.send(msg) {
warn!("Error communicating with the time profiler thread: {}", e);
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerData {
NoRecords,
Record(Vec<f64>),
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to get time spend entries for a particular ProfilerBuckets (in nanoseconds)
Get((ProfilerCategory, Option<TimerMetadata>), IpcSender<ProfilerData>),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum ProfilerCategory {
Compositing = 0x00,
LayoutPerform = 0x10,
LayoutStyleRecalc = 0x11,
LayoutTextShaping = 0x12,
LayoutRestyleDamagePropagation = 0x13,
LayoutNonIncrementalReset = 0x14,
LayoutSelectorMatch = 0x15,
LayoutTreeBuilder = 0x16,
LayoutDamagePropagate = 0x17,
LayoutGeneratedContent = 0x18,
LayoutDisplayListSorting = 0x19,
LayoutFloatPlacementSpeculation = 0x1a,
LayoutMain = 0x1b,
LayoutStoreOverflow = 0x1c,
LayoutParallelWarmup = 0x1d,
LayoutDispListBuild = 0x1e,
NetHTTPRequestResponse = 0x30,
PaintingPerTile = 0x41,
PaintingPrepBuff = 0x42,
Painting = 0x43,
|
ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0x6a,
ScriptParseHTML = 0x6b,
ScriptPlannedNavigation = 0x6c,
ScriptResize = 0x6d,
ScriptSetScrollState = 0x6e,
ScriptSetViewport = 0x6f,
ScriptTimerEvent = 0x70,
ScriptStylesheetLoad = 0x71,
ScriptUpdateReplacedElement = 0x72,
ScriptWebSocketEvent = 0x73,
ScriptWorkerEvent = 0x74,
ScriptServiceWorkerEvent = 0x75,
ScriptParseXML = 0x76,
ScriptEnterFullscreen = 0x77,
ScriptExitFullscreen = 0x78,
ScriptWebVREvent = 0x79,
ScriptWorkletEvent = 0x7a,
ScriptPerformanceEvent = 0x7b,
TimeToFirstPaint = 0x80,
TimeToFirstContentfulPaint = 0x81,
TimeToInteractive = 0x82,
IpcReceiver = 0x83,
ApplicationHeartbeat = 0x90,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T,
{
if opts::get().signpost {
signpost::start(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
if opts::get().signpost {
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
send_profile_data(category,
meta,
&profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: &ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
|
ImageDecoding = 0x50,
ImageSaving = 0x51,
|
random_line_split
|
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
use servo_config::opts;
use signpost;
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
if let Err(e) = self.0.send(msg) {
warn!("Error communicating with the time profiler thread: {}", e);
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerData {
NoRecords,
Record(Vec<f64>),
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to get time spend entries for a particular ProfilerBuckets (in nanoseconds)
Get((ProfilerCategory, Option<TimerMetadata>), IpcSender<ProfilerData>),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum ProfilerCategory {
Compositing = 0x00,
LayoutPerform = 0x10,
LayoutStyleRecalc = 0x11,
LayoutTextShaping = 0x12,
LayoutRestyleDamagePropagation = 0x13,
LayoutNonIncrementalReset = 0x14,
LayoutSelectorMatch = 0x15,
LayoutTreeBuilder = 0x16,
LayoutDamagePropagate = 0x17,
LayoutGeneratedContent = 0x18,
LayoutDisplayListSorting = 0x19,
LayoutFloatPlacementSpeculation = 0x1a,
LayoutMain = 0x1b,
LayoutStoreOverflow = 0x1c,
LayoutParallelWarmup = 0x1d,
LayoutDispListBuild = 0x1e,
NetHTTPRequestResponse = 0x30,
PaintingPerTile = 0x41,
PaintingPrepBuff = 0x42,
Painting = 0x43,
ImageDecoding = 0x50,
ImageSaving = 0x51,
ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0x6a,
ScriptParseHTML = 0x6b,
ScriptPlannedNavigation = 0x6c,
ScriptResize = 0x6d,
ScriptSetScrollState = 0x6e,
ScriptSetViewport = 0x6f,
ScriptTimerEvent = 0x70,
ScriptStylesheetLoad = 0x71,
ScriptUpdateReplacedElement = 0x72,
ScriptWebSocketEvent = 0x73,
ScriptWorkerEvent = 0x74,
ScriptServiceWorkerEvent = 0x75,
ScriptParseXML = 0x76,
ScriptEnterFullscreen = 0x77,
ScriptExitFullscreen = 0x78,
ScriptWebVREvent = 0x79,
ScriptWorkletEvent = 0x7a,
ScriptPerformanceEvent = 0x7b,
TimeToFirstPaint = 0x80,
TimeToFirstContentfulPaint = 0x81,
TimeToInteractive = 0x82,
IpcReceiver = 0x83,
ApplicationHeartbeat = 0x90,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum
|
{
RootWindow,
IFrame,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T,
{
if opts::get().signpost {
signpost::start(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
if opts::get().signpost {
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
send_profile_data(category,
meta,
&profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: &ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
|
TimerMetadataFrameType
|
identifier_name
|
lib.rs
|
//! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.
//!
//! For the purpose of future feature-tracking, once a feature gate is added,
//! even if it is stabilized or removed, *do not remove it*. Instead, move the
//! symbol to the `accepted` or `removed` modules respectively.
#![feature(derive_default_enum)]
#![feature(once_cell)]
mod accepted;
mod active;
mod builtin_attrs;
mod removed;
|
use std::num::NonZeroU32;
#[derive(Clone, Copy)]
pub enum State {
Accepted,
Active { set: fn(&mut Features, Span) },
Removed { reason: Option<&'static str> },
Stabilized { reason: Option<&'static str> },
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
State::Accepted {.. } => write!(f, "accepted"),
State::Active {.. } => write!(f, "active"),
State::Removed {.. } => write!(f, "removed"),
State::Stabilized {.. } => write!(f, "stabilized"),
}
}
}
#[derive(Debug, Clone)]
pub struct Feature {
pub state: State,
pub name: Symbol,
pub since: &'static str,
issue: Option<NonZeroU32>,
pub edition: Option<Edition>,
}
#[derive(Copy, Clone, Debug)]
pub enum Stability {
Unstable,
// First argument is tracking issue link; second argument is an optional
// help message, which defaults to "remove this attribute".
Deprecated(&'static str, Option<&'static str>),
}
#[derive(Clone, Copy, Debug, Hash)]
pub enum UnstableFeatures {
/// Hard errors for unstable features are active, as on beta/stable channels.
Disallow,
/// Allow features to be activated, as on nightly.
Allow,
/// Errors are bypassed for bootstrapping. This is required any time
/// during the build that feature-related lints are set to warn or above
/// because the build turns on warnings-as-errors and uses lots of unstable
/// features. As a result, this is always required for building Rust itself.
Cheat,
}
impl UnstableFeatures {
/// This takes into account `RUSTC_BOOTSTRAP`.
///
/// If `krate` is [`Some`], then setting `RUSTC_BOOTSTRAP=krate` will enable the nightly features.
/// Otherwise, only `RUSTC_BOOTSTRAP=1` will work.
pub fn from_environment(krate: Option<&str>) -> Self {
// `true` if this is a feature-staged build, i.e., on the beta or stable channel.
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Returns whether `krate` should be counted as unstable
let is_unstable_crate = |var: &str| {
krate.map_or(false, |name| var.split(',').any(|new_krate| new_krate == name))
};
// `true` if we should enable unstable features for bootstrapping.
let bootstrap = std::env::var("RUSTC_BOOTSTRAP")
.map_or(false, |var| var == "1" || is_unstable_crate(&var));
match (disable_unstable_features, bootstrap) {
(_, true) => UnstableFeatures::Cheat,
(true, _) => UnstableFeatures::Disallow,
(false, _) => UnstableFeatures::Allow,
}
}
pub fn is_nightly_build(&self) -> bool {
match *self {
UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
UnstableFeatures::Disallow => false,
}
}
}
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
// FIXME (#28244): enforce that active features have issue numbers
// assert!(info.issue.is_some())
info.issue
} else {
// search in Accepted, Removed, or Stable Removed features
let found = ACCEPTED_FEATURES
.iter()
.chain(REMOVED_FEATURES)
.chain(STABLE_REMOVED_FEATURES)
.find(|t| t.name == feature);
match found {
Some(found) => found.issue,
None => panic!("feature `{}` is not declared anywhere", feature),
}
}
}
const fn to_nonzero(n: Option<u32>) -> Option<NonZeroU32> {
// Can be replaced with `n.and_then(NonZeroU32::new)` if that is ever usable
// in const context. Requires https://github.com/rust-lang/rfcs/pull/2632.
match n {
None => None,
Some(n) => NonZeroU32::new(n),
}
}
pub enum GateIssue {
Language,
Library(Option<NonZeroU32>),
}
pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZeroU32> {
match issue {
GateIssue::Language => find_lang_feature_issue(feature),
GateIssue::Library(lib) => lib,
}
}
pub use accepted::ACCEPTED_FEATURES;
pub use active::{Features, ACTIVE_FEATURES, INCOMPATIBLE_FEATURES};
pub use builtin_attrs::AttributeDuplicates;
pub use builtin_attrs::{
deprecated_attributes, find_gated_cfg, is_builtin_attr_name, AttributeGate, AttributeTemplate,
AttributeType, BuiltinAttribute, GatedCfg, BUILTIN_ATTRIBUTES, BUILTIN_ATTRIBUTE_MAP,
};
pub use removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
|
#[cfg(test)]
mod tests;
use rustc_span::{edition::Edition, symbol::Symbol, Span};
use std::fmt;
|
random_line_split
|
lib.rs
|
//! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.
//!
//! For the purpose of future feature-tracking, once a feature gate is added,
//! even if it is stabilized or removed, *do not remove it*. Instead, move the
//! symbol to the `accepted` or `removed` modules respectively.
#![feature(derive_default_enum)]
#![feature(once_cell)]
mod accepted;
mod active;
mod builtin_attrs;
mod removed;
#[cfg(test)]
mod tests;
use rustc_span::{edition::Edition, symbol::Symbol, Span};
use std::fmt;
use std::num::NonZeroU32;
#[derive(Clone, Copy)]
pub enum State {
Accepted,
Active { set: fn(&mut Features, Span) },
Removed { reason: Option<&'static str> },
Stabilized { reason: Option<&'static str> },
}
impl fmt::Debug for State {
fn
|
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
State::Accepted {.. } => write!(f, "accepted"),
State::Active {.. } => write!(f, "active"),
State::Removed {.. } => write!(f, "removed"),
State::Stabilized {.. } => write!(f, "stabilized"),
}
}
}
#[derive(Debug, Clone)]
pub struct Feature {
pub state: State,
pub name: Symbol,
pub since: &'static str,
issue: Option<NonZeroU32>,
pub edition: Option<Edition>,
}
#[derive(Copy, Clone, Debug)]
pub enum Stability {
Unstable,
// First argument is tracking issue link; second argument is an optional
// help message, which defaults to "remove this attribute".
Deprecated(&'static str, Option<&'static str>),
}
#[derive(Clone, Copy, Debug, Hash)]
pub enum UnstableFeatures {
/// Hard errors for unstable features are active, as on beta/stable channels.
Disallow,
/// Allow features to be activated, as on nightly.
Allow,
/// Errors are bypassed for bootstrapping. This is required any time
/// during the build that feature-related lints are set to warn or above
/// because the build turns on warnings-as-errors and uses lots of unstable
/// features. As a result, this is always required for building Rust itself.
Cheat,
}
impl UnstableFeatures {
/// This takes into account `RUSTC_BOOTSTRAP`.
///
/// If `krate` is [`Some`], then setting `RUSTC_BOOTSTRAP=krate` will enable the nightly features.
/// Otherwise, only `RUSTC_BOOTSTRAP=1` will work.
pub fn from_environment(krate: Option<&str>) -> Self {
// `true` if this is a feature-staged build, i.e., on the beta or stable channel.
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Returns whether `krate` should be counted as unstable
let is_unstable_crate = |var: &str| {
krate.map_or(false, |name| var.split(',').any(|new_krate| new_krate == name))
};
// `true` if we should enable unstable features for bootstrapping.
let bootstrap = std::env::var("RUSTC_BOOTSTRAP")
.map_or(false, |var| var == "1" || is_unstable_crate(&var));
match (disable_unstable_features, bootstrap) {
(_, true) => UnstableFeatures::Cheat,
(true, _) => UnstableFeatures::Disallow,
(false, _) => UnstableFeatures::Allow,
}
}
pub fn is_nightly_build(&self) -> bool {
match *self {
UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
UnstableFeatures::Disallow => false,
}
}
}
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
// FIXME (#28244): enforce that active features have issue numbers
// assert!(info.issue.is_some())
info.issue
} else {
// search in Accepted, Removed, or Stable Removed features
let found = ACCEPTED_FEATURES
.iter()
.chain(REMOVED_FEATURES)
.chain(STABLE_REMOVED_FEATURES)
.find(|t| t.name == feature);
match found {
Some(found) => found.issue,
None => panic!("feature `{}` is not declared anywhere", feature),
}
}
}
const fn to_nonzero(n: Option<u32>) -> Option<NonZeroU32> {
// Can be replaced with `n.and_then(NonZeroU32::new)` if that is ever usable
// in const context. Requires https://github.com/rust-lang/rfcs/pull/2632.
match n {
None => None,
Some(n) => NonZeroU32::new(n),
}
}
pub enum GateIssue {
Language,
Library(Option<NonZeroU32>),
}
pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZeroU32> {
match issue {
GateIssue::Language => find_lang_feature_issue(feature),
GateIssue::Library(lib) => lib,
}
}
pub use accepted::ACCEPTED_FEATURES;
pub use active::{Features, ACTIVE_FEATURES, INCOMPATIBLE_FEATURES};
pub use builtin_attrs::AttributeDuplicates;
pub use builtin_attrs::{
deprecated_attributes, find_gated_cfg, is_builtin_attr_name, AttributeGate, AttributeTemplate,
AttributeType, BuiltinAttribute, GatedCfg, BUILTIN_ATTRIBUTES, BUILTIN_ATTRIBUTE_MAP,
};
pub use removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
|
fmt
|
identifier_name
|
lib.rs
|
//! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.
//!
//! For the purpose of future feature-tracking, once a feature gate is added,
//! even if it is stabilized or removed, *do not remove it*. Instead, move the
//! symbol to the `accepted` or `removed` modules respectively.
#![feature(derive_default_enum)]
#![feature(once_cell)]
mod accepted;
mod active;
mod builtin_attrs;
mod removed;
#[cfg(test)]
mod tests;
use rustc_span::{edition::Edition, symbol::Symbol, Span};
use std::fmt;
use std::num::NonZeroU32;
#[derive(Clone, Copy)]
pub enum State {
Accepted,
Active { set: fn(&mut Features, Span) },
Removed { reason: Option<&'static str> },
Stabilized { reason: Option<&'static str> },
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
State::Accepted {.. } => write!(f, "accepted"),
State::Active {.. } => write!(f, "active"),
State::Removed {.. } => write!(f, "removed"),
State::Stabilized {.. } => write!(f, "stabilized"),
}
}
}
#[derive(Debug, Clone)]
pub struct Feature {
pub state: State,
pub name: Symbol,
pub since: &'static str,
issue: Option<NonZeroU32>,
pub edition: Option<Edition>,
}
#[derive(Copy, Clone, Debug)]
pub enum Stability {
Unstable,
// First argument is tracking issue link; second argument is an optional
// help message, which defaults to "remove this attribute".
Deprecated(&'static str, Option<&'static str>),
}
#[derive(Clone, Copy, Debug, Hash)]
pub enum UnstableFeatures {
/// Hard errors for unstable features are active, as on beta/stable channels.
Disallow,
/// Allow features to be activated, as on nightly.
Allow,
/// Errors are bypassed for bootstrapping. This is required any time
/// during the build that feature-related lints are set to warn or above
/// because the build turns on warnings-as-errors and uses lots of unstable
/// features. As a result, this is always required for building Rust itself.
Cheat,
}
impl UnstableFeatures {
/// This takes into account `RUSTC_BOOTSTRAP`.
///
/// If `krate` is [`Some`], then setting `RUSTC_BOOTSTRAP=krate` will enable the nightly features.
/// Otherwise, only `RUSTC_BOOTSTRAP=1` will work.
pub fn from_environment(krate: Option<&str>) -> Self
|
pub fn is_nightly_build(&self) -> bool {
match *self {
UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
UnstableFeatures::Disallow => false,
}
}
}
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
// FIXME (#28244): enforce that active features have issue numbers
// assert!(info.issue.is_some())
info.issue
} else {
// search in Accepted, Removed, or Stable Removed features
let found = ACCEPTED_FEATURES
.iter()
.chain(REMOVED_FEATURES)
.chain(STABLE_REMOVED_FEATURES)
.find(|t| t.name == feature);
match found {
Some(found) => found.issue,
None => panic!("feature `{}` is not declared anywhere", feature),
}
}
}
const fn to_nonzero(n: Option<u32>) -> Option<NonZeroU32> {
// Can be replaced with `n.and_then(NonZeroU32::new)` if that is ever usable
// in const context. Requires https://github.com/rust-lang/rfcs/pull/2632.
match n {
None => None,
Some(n) => NonZeroU32::new(n),
}
}
pub enum GateIssue {
Language,
Library(Option<NonZeroU32>),
}
pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZeroU32> {
match issue {
GateIssue::Language => find_lang_feature_issue(feature),
GateIssue::Library(lib) => lib,
}
}
pub use accepted::ACCEPTED_FEATURES;
pub use active::{Features, ACTIVE_FEATURES, INCOMPATIBLE_FEATURES};
pub use builtin_attrs::AttributeDuplicates;
pub use builtin_attrs::{
deprecated_attributes, find_gated_cfg, is_builtin_attr_name, AttributeGate, AttributeTemplate,
AttributeType, BuiltinAttribute, GatedCfg, BUILTIN_ATTRIBUTES, BUILTIN_ATTRIBUTE_MAP,
};
pub use removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
|
{
// `true` if this is a feature-staged build, i.e., on the beta or stable channel.
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Returns whether `krate` should be counted as unstable
let is_unstable_crate = |var: &str| {
krate.map_or(false, |name| var.split(',').any(|new_krate| new_krate == name))
};
// `true` if we should enable unstable features for bootstrapping.
let bootstrap = std::env::var("RUSTC_BOOTSTRAP")
.map_or(false, |var| var == "1" || is_unstable_crate(&var));
match (disable_unstable_features, bootstrap) {
(_, true) => UnstableFeatures::Cheat,
(true, _) => UnstableFeatures::Disallow,
(false, _) => UnstableFeatures::Allow,
}
}
|
identifier_body
|
const-bound.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.
// run-pass
#![allow(dead_code)]
// Make sure const bounds work on things, and test that a few types
// are const.
// pretty-expanded FIXME #23616
fn foo<T: Sync>(x: T) -> T { x }
struct F { field: isize }
pub fn main()
|
{
/*foo(1);
foo("hi".to_string());
foo(vec![1, 2, 3]);
foo(F{field: 42});
foo((1, 2));
foo(@1);*/
foo(Box::new(1));
}
|
identifier_body
|
|
const-bound.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.
// run-pass
#![allow(dead_code)]
// Make sure const bounds work on things, and test that a few types
// are const.
// pretty-expanded FIXME #23616
fn foo<T: Sync>(x: T) -> T { x }
struct
|
{ field: isize }
pub fn main() {
/*foo(1);
foo("hi".to_string());
foo(vec![1, 2, 3]);
foo(F{field: 42});
foo((1, 2));
foo(@1);*/
foo(Box::new(1));
}
|
F
|
identifier_name
|
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::refcounted::Trusted;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeDamage, document_from_node, window_from_node};
use dom::values::UNSIGNED_LONG_MAX;
use dom::virtualmethods::VirtualMethods;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image::base::{Image, ImageMetadata};
use net_traits::image_cache_thread::{ImageResponder, ImageResponse};
use script_thread::ScriptThreadEventCategory::UpdateReplacedElement;
use script_thread::{CommonScriptMsg, Runnable, ScriptChan};
use std::sync::Arc;
use string_cache::Atom;
use url::Url;
use util::str::{DOMString, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Url>>,
image: DOMRefCell<Option<Arc<Image>>>,
metadata: DOMRefCell<Option<ImageMetadata>>,
}
impl HTMLImageElement {
pub fn get_url(&self) -> Option<Url>{
self.url.borrow().clone()
}
}
struct ImageResponseHandlerRunnable {
element: Trusted<HTMLImageElement>,
image: ImageResponse,
}
impl ImageResponseHandlerRunnable {
fn new(element: Trusted<HTMLImageElement>, image: ImageResponse)
-> ImageResponseHandlerRunnable {
ImageResponseHandlerRunnable {
element: element,
image: image,
}
}
}
impl Runnable for ImageResponseHandlerRunnable {
fn handler(self: Box<Self>) {
// Update the image field
let element = self.element.root();
let element_ref = element.r();
let (image, metadata, trigger_image_load) = match self.image {
ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => {
(Some(image.clone()), Some(ImageMetadata { height: image.height, width: image.width } ), true)
}
ImageResponse::MetadataLoaded(meta) => {
(None, Some(meta), false)
}
ImageResponse::None => (None, None, true)
};
*element_ref.image.borrow_mut() = image;
*element_ref.metadata.borrow_mut() = metadata;
// Mark the node dirty
let document = document_from_node(&*element);
document.content_changed(element.upcast(), NodeDamage::OtherNodeDamage);
// Fire image.onload
if trigger_image_load {
element.upcast::<EventTarget>().fire_simple_event("load");
}
// Trigger reflow
let window = window_from_node(document.r());
window.add_pending_reflow();
}
}
impl HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(&self, value: Option<(DOMString, Url)>) {
let document = document_from_node(self);
let window = document.window();
let image_cache = window.image_cache_thread();
match value {
None => {
*self.url.borrow_mut() = None;
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = base_url.join(&src);
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.url.borrow_mut() = Some(img_url.clone());
let trusted_node = Trusted::new(self, window.networking_task_source());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.networking_task_source();
let wrapper = window.get_runnable_wrapper();
ROUTER.add_route(responder_receiver.to_opaque(), box move |message| {
// Return the image via a message to the script thread, which marks the element
// as dirty and triggers a reflow.
let image_response = message.to().unwrap();
let runnable = ImageResponseHandlerRunnable::new(
trusted_node.clone(), image_response);
let runnable = wrapper.wrap_runnable(runnable);
let _ = script_chan.send(CommonScriptMsg::RunnableMsg(
UpdateReplacedElement, runnable));
});
image_cache.request_image_and_metadata(img_url,
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
}
}
}
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
url: DOMRefCell::new(None),
image: DOMRefCell::new(None),
metadata: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
pub fn Image(global: GlobalRef,
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new(atom!("img"), None, document.r());
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
fn get_height(&self) -> LengthOrPercentageOrAuto;
}
impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>> {
(*self.unsafe_get()).image.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>
|
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
#[allow(unsafe_code)]
fn get_height(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("height"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_getter!(Alt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_setter!(SetAlt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_url_getter!(Src, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_setter!(SetSrc, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_getter!(UseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_setter!(SetUseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_getter!(IsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_setter!(SetIsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn Width(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.width.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("width"), value);
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn Height(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("height"), value);
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
fn NaturalWidth(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.width,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
fn NaturalHeight(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.height,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-complete
fn Complete(&self) -> bool {
let image = self.image.borrow();
image.is_some()
}
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_atomic_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_getter!(Hspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_setter!(SetHspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_getter!(Vspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_setter!(SetVspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_getter!(LongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_setter!(SetLongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_getter!(Border, "border");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_setter!(SetBorder, "border");
}
impl VirtualMethods for HTMLImageElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("src") => {
self.update_image(mutation.new_value(attr).map(|value| {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
(DOMString::from(&**value), window_from_node(self).get_url())
}));
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atomic(value),
&atom!("width") | &atom!("height") => AttrValue::from_dimension(value),
&atom!("hspace") | &atom!("vspace") => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
fn image_dimension_setter(element: &Element, attr: Atom, value: u32) {
// This setter is a bit weird: the IDL type is unsigned long, but it's parsed as
// a dimension for rendering.
let value = if value > UNSIGNED_LONG_MAX {
0
} else {
value
};
let dim = LengthOrPercentageOrAuto::Length(Au::from_px(value as i32));
let value = AttrValue::Dimension(DOMString::from(value.to_string()), dim);
element.set_attribute(&attr, value);
}
|
{
(*self.unsafe_get()).url.borrow_for_layout().clone()
}
|
identifier_body
|
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::refcounted::Trusted;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeDamage, document_from_node, window_from_node};
use dom::values::UNSIGNED_LONG_MAX;
use dom::virtualmethods::VirtualMethods;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image::base::{Image, ImageMetadata};
use net_traits::image_cache_thread::{ImageResponder, ImageResponse};
use script_thread::ScriptThreadEventCategory::UpdateReplacedElement;
use script_thread::{CommonScriptMsg, Runnable, ScriptChan};
use std::sync::Arc;
use string_cache::Atom;
use url::Url;
use util::str::{DOMString, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Url>>,
image: DOMRefCell<Option<Arc<Image>>>,
metadata: DOMRefCell<Option<ImageMetadata>>,
}
impl HTMLImageElement {
pub fn get_url(&self) -> Option<Url>{
self.url.borrow().clone()
}
}
struct ImageResponseHandlerRunnable {
element: Trusted<HTMLImageElement>,
image: ImageResponse,
}
impl ImageResponseHandlerRunnable {
fn new(element: Trusted<HTMLImageElement>, image: ImageResponse)
-> ImageResponseHandlerRunnable {
ImageResponseHandlerRunnable {
element: element,
image: image,
}
}
}
impl Runnable for ImageResponseHandlerRunnable {
fn handler(self: Box<Self>) {
// Update the image field
let element = self.element.root();
let element_ref = element.r();
let (image, metadata, trigger_image_load) = match self.image {
ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => {
(Some(image.clone()), Some(ImageMetadata { height: image.height, width: image.width } ), true)
}
ImageResponse::MetadataLoaded(meta) => {
(None, Some(meta), false)
}
ImageResponse::None => (None, None, true)
};
*element_ref.image.borrow_mut() = image;
*element_ref.metadata.borrow_mut() = metadata;
// Mark the node dirty
let document = document_from_node(&*element);
document.content_changed(element.upcast(), NodeDamage::OtherNodeDamage);
// Fire image.onload
if trigger_image_load {
element.upcast::<EventTarget>().fire_simple_event("load");
}
// Trigger reflow
let window = window_from_node(document.r());
window.add_pending_reflow();
}
}
impl HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(&self, value: Option<(DOMString, Url)>) {
let document = document_from_node(self);
let window = document.window();
let image_cache = window.image_cache_thread();
match value {
None => {
*self.url.borrow_mut() = None;
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = base_url.join(&src);
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.url.borrow_mut() = Some(img_url.clone());
let trusted_node = Trusted::new(self, window.networking_task_source());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.networking_task_source();
let wrapper = window.get_runnable_wrapper();
ROUTER.add_route(responder_receiver.to_opaque(), box move |message| {
// Return the image via a message to the script thread, which marks the element
// as dirty and triggers a reflow.
let image_response = message.to().unwrap();
let runnable = ImageResponseHandlerRunnable::new(
trusted_node.clone(), image_response);
let runnable = wrapper.wrap_runnable(runnable);
let _ = script_chan.send(CommonScriptMsg::RunnableMsg(
UpdateReplacedElement, runnable));
});
image_cache.request_image_and_metadata(img_url,
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
}
}
}
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
url: DOMRefCell::new(None),
image: DOMRefCell::new(None),
metadata: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
pub fn Image(global: GlobalRef,
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new(atom!("img"), None, document.r());
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
fn get_height(&self) -> LengthOrPercentageOrAuto;
}
impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>> {
(*self.unsafe_get()).image.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url> {
(*self.unsafe_get()).url.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
#[allow(unsafe_code)]
fn get_height(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("height"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_getter!(Alt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_setter!(SetAlt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_url_getter!(Src, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_setter!(SetSrc, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_getter!(UseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_setter!(SetUseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_getter!(IsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_setter!(SetIsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn Width(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.width.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("width"), value);
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn Height(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("height"), value);
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
fn NaturalWidth(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.width,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
fn NaturalHeight(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.height,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-complete
fn Complete(&self) -> bool {
let image = self.image.borrow();
image.is_some()
}
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_atomic_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_getter!(Hspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_setter!(SetHspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_getter!(Vspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_setter!(SetVspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_getter!(LongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_setter!(SetLongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_getter!(Border, "border");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_setter!(SetBorder, "border");
}
impl VirtualMethods for HTMLImageElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("src") => {
self.update_image(mutation.new_value(attr).map(|value| {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
(DOMString::from(&**value), window_from_node(self).get_url())
}));
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atomic(value),
&atom!("width") | &atom!("height") => AttrValue::from_dimension(value),
&atom!("hspace") | &atom!("vspace") => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
fn
|
(element: &Element, attr: Atom, value: u32) {
// This setter is a bit weird: the IDL type is unsigned long, but it's parsed as
// a dimension for rendering.
let value = if value > UNSIGNED_LONG_MAX {
0
} else {
value
};
let dim = LengthOrPercentageOrAuto::Length(Au::from_px(value as i32));
let value = AttrValue::Dimension(DOMString::from(value.to_string()), dim);
element.set_attribute(&attr, value);
}
|
image_dimension_setter
|
identifier_name
|
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::refcounted::Trusted;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeDamage, document_from_node, window_from_node};
use dom::values::UNSIGNED_LONG_MAX;
use dom::virtualmethods::VirtualMethods;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image::base::{Image, ImageMetadata};
use net_traits::image_cache_thread::{ImageResponder, ImageResponse};
use script_thread::ScriptThreadEventCategory::UpdateReplacedElement;
use script_thread::{CommonScriptMsg, Runnable, ScriptChan};
use std::sync::Arc;
use string_cache::Atom;
use url::Url;
use util::str::{DOMString, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Url>>,
image: DOMRefCell<Option<Arc<Image>>>,
metadata: DOMRefCell<Option<ImageMetadata>>,
}
impl HTMLImageElement {
pub fn get_url(&self) -> Option<Url>{
self.url.borrow().clone()
}
}
struct ImageResponseHandlerRunnable {
element: Trusted<HTMLImageElement>,
image: ImageResponse,
}
impl ImageResponseHandlerRunnable {
fn new(element: Trusted<HTMLImageElement>, image: ImageResponse)
-> ImageResponseHandlerRunnable {
ImageResponseHandlerRunnable {
element: element,
image: image,
}
}
}
impl Runnable for ImageResponseHandlerRunnable {
fn handler(self: Box<Self>) {
// Update the image field
let element = self.element.root();
let element_ref = element.r();
let (image, metadata, trigger_image_load) = match self.image {
ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => {
(Some(image.clone()), Some(ImageMetadata { height: image.height, width: image.width } ), true)
}
ImageResponse::MetadataLoaded(meta) => {
(None, Some(meta), false)
}
ImageResponse::None => (None, None, true)
};
*element_ref.image.borrow_mut() = image;
*element_ref.metadata.borrow_mut() = metadata;
// Mark the node dirty
let document = document_from_node(&*element);
document.content_changed(element.upcast(), NodeDamage::OtherNodeDamage);
// Fire image.onload
if trigger_image_load {
element.upcast::<EventTarget>().fire_simple_event("load");
}
// Trigger reflow
let window = window_from_node(document.r());
window.add_pending_reflow();
}
}
impl HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(&self, value: Option<(DOMString, Url)>) {
let document = document_from_node(self);
let window = document.window();
let image_cache = window.image_cache_thread();
match value {
None => {
*self.url.borrow_mut() = None;
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = base_url.join(&src);
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.url.borrow_mut() = Some(img_url.clone());
let trusted_node = Trusted::new(self, window.networking_task_source());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.networking_task_source();
let wrapper = window.get_runnable_wrapper();
ROUTER.add_route(responder_receiver.to_opaque(), box move |message| {
// Return the image via a message to the script thread, which marks the element
// as dirty and triggers a reflow.
let image_response = message.to().unwrap();
let runnable = ImageResponseHandlerRunnable::new(
trusted_node.clone(), image_response);
let runnable = wrapper.wrap_runnable(runnable);
let _ = script_chan.send(CommonScriptMsg::RunnableMsg(
UpdateReplacedElement, runnable));
});
image_cache.request_image_and_metadata(img_url,
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
}
}
}
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
url: DOMRefCell::new(None),
image: DOMRefCell::new(None),
metadata: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
pub fn Image(global: GlobalRef,
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new(atom!("img"), None, document.r());
if let Some(w) = width
|
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
fn get_height(&self) -> LengthOrPercentageOrAuto;
}
impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>> {
(*self.unsafe_get()).image.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url> {
(*self.unsafe_get()).url.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
#[allow(unsafe_code)]
fn get_height(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("height"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_getter!(Alt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_setter!(SetAlt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_url_getter!(Src, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_setter!(SetSrc, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_getter!(UseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_setter!(SetUseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_getter!(IsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_setter!(SetIsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn Width(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.width.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("width"), value);
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn Height(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("height"), value);
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
fn NaturalWidth(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.width,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
fn NaturalHeight(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.height,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-complete
fn Complete(&self) -> bool {
let image = self.image.borrow();
image.is_some()
}
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_atomic_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_getter!(Hspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_setter!(SetHspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_getter!(Vspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_setter!(SetVspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_getter!(LongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_setter!(SetLongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_getter!(Border, "border");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_setter!(SetBorder, "border");
}
impl VirtualMethods for HTMLImageElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("src") => {
self.update_image(mutation.new_value(attr).map(|value| {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
(DOMString::from(&**value), window_from_node(self).get_url())
}));
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atomic(value),
&atom!("width") | &atom!("height") => AttrValue::from_dimension(value),
&atom!("hspace") | &atom!("vspace") => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
fn image_dimension_setter(element: &Element, attr: Atom, value: u32) {
// This setter is a bit weird: the IDL type is unsigned long, but it's parsed as
// a dimension for rendering.
let value = if value > UNSIGNED_LONG_MAX {
0
} else {
value
};
let dim = LengthOrPercentageOrAuto::Length(Au::from_px(value as i32));
let value = AttrValue::Dimension(DOMString::from(value.to_string()), dim);
element.set_attribute(&attr, value);
}
|
{
image.SetWidth(w);
}
|
conditional_block
|
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::refcounted::Trusted;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeDamage, document_from_node, window_from_node};
use dom::values::UNSIGNED_LONG_MAX;
use dom::virtualmethods::VirtualMethods;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image::base::{Image, ImageMetadata};
use net_traits::image_cache_thread::{ImageResponder, ImageResponse};
use script_thread::ScriptThreadEventCategory::UpdateReplacedElement;
use script_thread::{CommonScriptMsg, Runnable, ScriptChan};
use std::sync::Arc;
use string_cache::Atom;
use url::Url;
use util::str::{DOMString, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Url>>,
image: DOMRefCell<Option<Arc<Image>>>,
metadata: DOMRefCell<Option<ImageMetadata>>,
}
impl HTMLImageElement {
pub fn get_url(&self) -> Option<Url>{
self.url.borrow().clone()
}
}
struct ImageResponseHandlerRunnable {
element: Trusted<HTMLImageElement>,
image: ImageResponse,
}
impl ImageResponseHandlerRunnable {
fn new(element: Trusted<HTMLImageElement>, image: ImageResponse)
-> ImageResponseHandlerRunnable {
ImageResponseHandlerRunnable {
element: element,
image: image,
}
}
}
impl Runnable for ImageResponseHandlerRunnable {
fn handler(self: Box<Self>) {
// Update the image field
let element = self.element.root();
let element_ref = element.r();
let (image, metadata, trigger_image_load) = match self.image {
ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => {
(Some(image.clone()), Some(ImageMetadata { height: image.height, width: image.width } ), true)
}
ImageResponse::MetadataLoaded(meta) => {
(None, Some(meta), false)
}
ImageResponse::None => (None, None, true)
};
*element_ref.image.borrow_mut() = image;
*element_ref.metadata.borrow_mut() = metadata;
// Mark the node dirty
let document = document_from_node(&*element);
document.content_changed(element.upcast(), NodeDamage::OtherNodeDamage);
// Fire image.onload
if trigger_image_load {
element.upcast::<EventTarget>().fire_simple_event("load");
}
// Trigger reflow
let window = window_from_node(document.r());
window.add_pending_reflow();
}
}
impl HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(&self, value: Option<(DOMString, Url)>) {
let document = document_from_node(self);
let window = document.window();
let image_cache = window.image_cache_thread();
match value {
None => {
*self.url.borrow_mut() = None;
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = base_url.join(&src);
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.url.borrow_mut() = Some(img_url.clone());
let trusted_node = Trusted::new(self, window.networking_task_source());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.networking_task_source();
let wrapper = window.get_runnable_wrapper();
ROUTER.add_route(responder_receiver.to_opaque(), box move |message| {
// Return the image via a message to the script thread, which marks the element
// as dirty and triggers a reflow.
let image_response = message.to().unwrap();
let runnable = ImageResponseHandlerRunnable::new(
trusted_node.clone(), image_response);
let runnable = wrapper.wrap_runnable(runnable);
let _ = script_chan.send(CommonScriptMsg::RunnableMsg(
UpdateReplacedElement, runnable));
});
image_cache.request_image_and_metadata(img_url,
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
}
}
}
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
url: DOMRefCell::new(None),
image: DOMRefCell::new(None),
metadata: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
pub fn Image(global: GlobalRef,
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new(atom!("img"), None, document.r());
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
fn get_height(&self) -> LengthOrPercentageOrAuto;
}
impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>> {
(*self.unsafe_get()).image.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url> {
(*self.unsafe_get()).url.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
#[allow(unsafe_code)]
fn get_height(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("height"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_getter!(Alt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_setter!(SetAlt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_url_getter!(Src, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-src
make_setter!(SetSrc, "src");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_getter!(UseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-usemap
make_setter!(SetUseMap, "usemap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_getter!(IsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
make_bool_setter!(SetIsMap, "ismap");
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn Width(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.width.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("width"), value);
}
|
fn Height(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(&self, value: u32) {
image_dimension_setter(self.upcast(), atom!("height"), value);
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
fn NaturalWidth(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.width,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
fn NaturalHeight(&self) -> u32 {
let metadata = self.metadata.borrow();
match *metadata {
Some(ref metadata) => metadata.height,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-complete
fn Complete(&self) -> bool {
let image = self.image.borrow();
image.is_some()
}
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-name
make_atomic_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-align
make_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_getter!(Hspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-hspace
make_uint_setter!(SetHspace, "hspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_getter!(Vspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-vspace
make_uint_setter!(SetVspace, "vspace");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_getter!(LongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-longdesc
make_setter!(SetLongDesc, "longdesc");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_getter!(Border, "border");
// https://html.spec.whatwg.org/multipage/#dom-img-border
make_setter!(SetBorder, "border");
}
impl VirtualMethods for HTMLImageElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("src") => {
self.update_image(mutation.new_value(attr).map(|value| {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
(DOMString::from(&**value), window_from_node(self).get_url())
}));
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atomic(value),
&atom!("width") | &atom!("height") => AttrValue::from_dimension(value),
&atom!("hspace") | &atom!("vspace") => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
fn image_dimension_setter(element: &Element, attr: Atom, value: u32) {
// This setter is a bit weird: the IDL type is unsigned long, but it's parsed as
// a dimension for rendering.
let value = if value > UNSIGNED_LONG_MAX {
0
} else {
value
};
let dim = LengthOrPercentageOrAuto::Length(Au::from_px(value as i32));
let value = AttrValue::Dimension(DOMString::from(value.to_string()), dim);
element.set_attribute(&attr, value);
}
|
// https://html.spec.whatwg.org/multipage/#dom-img-height
|
random_line_split
|
manager.rs
|
use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct Manager {
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
) -> Self
|
pub fn apply(&self, config: &Config) -> Result<(), Error> {
if let Some(new_settings) = &config.settings {
self.settings_manager
.amend(new_settings)
.map_err(|_| Error::Unspecified)?;
}
if let Some(mount_dirs) = &config.mount_dirs {
self.vfs_manager
.set_mount_dirs(&mount_dirs)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ddns_config) = &config.ydns {
self.ddns_manager
.set_config(&ddns_config)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ref users) = config.users {
let old_users: Vec<user::User> =
self.user_manager.list().map_err(|_| Error::Unspecified)?;
// Delete users that are not in new list
for old_user in old_users
.iter()
.filter(|old_user|!users.iter().any(|u| u.name == old_user.name))
{
self.user_manager
.delete(&old_user.name)
.map_err(|_| Error::Unspecified)?;
}
// Insert new users
for new_user in users
.iter()
.filter(|u|!old_users.iter().any(|old_user| old_user.name == u.name))
{
self.user_manager
.create(new_user)
.map_err(|_| Error::Unspecified)?;
}
// Update users
for user in users {
self.user_manager
.set_password(&user.name, &user.password)
.map_err(|_| Error::Unspecified)?;
self.user_manager
.set_is_admin(&user.name, user.admin)
.map_err(|_| Error::Unspecified)?;
}
}
Ok(())
}
}
|
{
Self {
settings_manager,
user_manager,
vfs_manager,
ddns_manager,
}
}
|
identifier_body
|
manager.rs
|
use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct Manager {
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
) -> Self {
Self {
settings_manager,
user_manager,
vfs_manager,
ddns_manager,
}
}
pub fn apply(&self, config: &Config) -> Result<(), Error> {
if let Some(new_settings) = &config.settings {
self.settings_manager
.amend(new_settings)
.map_err(|_| Error::Unspecified)?;
}
if let Some(mount_dirs) = &config.mount_dirs {
self.vfs_manager
.set_mount_dirs(&mount_dirs)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ddns_config) = &config.ydns {
self.ddns_manager
.set_config(&ddns_config)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ref users) = config.users {
let old_users: Vec<user::User> =
self.user_manager.list().map_err(|_| Error::Unspecified)?;
|
for old_user in old_users
.iter()
.filter(|old_user|!users.iter().any(|u| u.name == old_user.name))
{
self.user_manager
.delete(&old_user.name)
.map_err(|_| Error::Unspecified)?;
}
// Insert new users
for new_user in users
.iter()
.filter(|u|!old_users.iter().any(|old_user| old_user.name == u.name))
{
self.user_manager
.create(new_user)
.map_err(|_| Error::Unspecified)?;
}
// Update users
for user in users {
self.user_manager
.set_password(&user.name, &user.password)
.map_err(|_| Error::Unspecified)?;
self.user_manager
.set_is_admin(&user.name, user.admin)
.map_err(|_| Error::Unspecified)?;
}
}
Ok(())
}
}
|
// Delete users that are not in new list
|
random_line_split
|
manager.rs
|
use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct
|
{
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
) -> Self {
Self {
settings_manager,
user_manager,
vfs_manager,
ddns_manager,
}
}
pub fn apply(&self, config: &Config) -> Result<(), Error> {
if let Some(new_settings) = &config.settings {
self.settings_manager
.amend(new_settings)
.map_err(|_| Error::Unspecified)?;
}
if let Some(mount_dirs) = &config.mount_dirs {
self.vfs_manager
.set_mount_dirs(&mount_dirs)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ddns_config) = &config.ydns {
self.ddns_manager
.set_config(&ddns_config)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ref users) = config.users {
let old_users: Vec<user::User> =
self.user_manager.list().map_err(|_| Error::Unspecified)?;
// Delete users that are not in new list
for old_user in old_users
.iter()
.filter(|old_user|!users.iter().any(|u| u.name == old_user.name))
{
self.user_manager
.delete(&old_user.name)
.map_err(|_| Error::Unspecified)?;
}
// Insert new users
for new_user in users
.iter()
.filter(|u|!old_users.iter().any(|old_user| old_user.name == u.name))
{
self.user_manager
.create(new_user)
.map_err(|_| Error::Unspecified)?;
}
// Update users
for user in users {
self.user_manager
.set_password(&user.name, &user.password)
.map_err(|_| Error::Unspecified)?;
self.user_manager
.set_is_admin(&user.name, user.admin)
.map_err(|_| Error::Unspecified)?;
}
}
Ok(())
}
}
|
Manager
|
identifier_name
|
manager.rs
|
use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct Manager {
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
) -> Self {
Self {
settings_manager,
user_manager,
vfs_manager,
ddns_manager,
}
}
pub fn apply(&self, config: &Config) -> Result<(), Error> {
if let Some(new_settings) = &config.settings {
self.settings_manager
.amend(new_settings)
.map_err(|_| Error::Unspecified)?;
}
if let Some(mount_dirs) = &config.mount_dirs
|
if let Some(ddns_config) = &config.ydns {
self.ddns_manager
.set_config(&ddns_config)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ref users) = config.users {
let old_users: Vec<user::User> =
self.user_manager.list().map_err(|_| Error::Unspecified)?;
// Delete users that are not in new list
for old_user in old_users
.iter()
.filter(|old_user|!users.iter().any(|u| u.name == old_user.name))
{
self.user_manager
.delete(&old_user.name)
.map_err(|_| Error::Unspecified)?;
}
// Insert new users
for new_user in users
.iter()
.filter(|u|!old_users.iter().any(|old_user| old_user.name == u.name))
{
self.user_manager
.create(new_user)
.map_err(|_| Error::Unspecified)?;
}
// Update users
for user in users {
self.user_manager
.set_password(&user.name, &user.password)
.map_err(|_| Error::Unspecified)?;
self.user_manager
.set_is_admin(&user.name, user.admin)
.map_err(|_| Error::Unspecified)?;
}
}
Ok(())
}
}
|
{
self.vfs_manager
.set_mount_dirs(&mount_dirs)
.map_err(|_| Error::Unspecified)?;
}
|
conditional_block
|
insert_usage_mysql.rs
|
use chrono::{offset::Utc, DateTime};
use rustorm::{pool, DbError, FromDao, Pool, ToColumnNames, ToDao, ToTableName};
/// Run using:
/// ```sh
/// cargo run --example insert_usage_mysql --features "with-mysql"
/// ```
fn main() {
mod for_insert {
use super::*;
#[derive(Debug, PartialEq, ToDao, ToColumnNames, ToTableName)]
pub struct Actor {
pub first_name: String,
pub last_name: String,
}
}
mod for_retrieve {
use super::*;
#[derive(Debug, FromDao, ToColumnNames, ToTableName)]
pub struct Actor {
pub actor_id: i32,
pub first_name: String,
pub last_name: String,
pub last_update: DateTime<Utc>,
}
}
let db_url = "mysql://root:r00tpwdh3r3@localhost/sakila";
let mut pool = Pool::new();
pool.ensure(db_url);
let mut em = pool.em(db_url).expect("Can not connect");
let tom_cruise = for_insert::Actor {
first_name: "TOM".into(),
last_name: "CRUISE".to_string(),
|
};
let tom_hanks = for_insert::Actor {
first_name: "TOM".into(),
last_name: "HANKS".to_string(),
};
println!("tom_cruise: {:#?}", tom_cruise);
println!("tom_hanks: {:#?}", tom_hanks);
let actors: Result<Vec<for_retrieve::Actor>, DbError> = em.insert(&[&tom_cruise, &tom_hanks]);
println!("Actor: {:#?}", actors);
assert!(actors.is_ok());
let actors = actors.unwrap();
let today = Utc::now().date();
assert_eq!(tom_cruise.first_name, actors[0].first_name);
assert_eq!(tom_cruise.last_name, actors[0].last_name);
assert_eq!(today, actors[0].last_update.date());
assert_eq!(tom_hanks.first_name, actors[1].first_name);
assert_eq!(tom_hanks.last_name, actors[1].last_name);
assert_eq!(today, actors[1].last_update.date());
}
|
random_line_split
|
|
insert_usage_mysql.rs
|
use chrono::{offset::Utc, DateTime};
use rustorm::{pool, DbError, FromDao, Pool, ToColumnNames, ToDao, ToTableName};
/// Run using:
/// ```sh
/// cargo run --example insert_usage_mysql --features "with-mysql"
/// ```
fn
|
() {
mod for_insert {
use super::*;
#[derive(Debug, PartialEq, ToDao, ToColumnNames, ToTableName)]
pub struct Actor {
pub first_name: String,
pub last_name: String,
}
}
mod for_retrieve {
use super::*;
#[derive(Debug, FromDao, ToColumnNames, ToTableName)]
pub struct Actor {
pub actor_id: i32,
pub first_name: String,
pub last_name: String,
pub last_update: DateTime<Utc>,
}
}
let db_url = "mysql://root:r00tpwdh3r3@localhost/sakila";
let mut pool = Pool::new();
pool.ensure(db_url);
let mut em = pool.em(db_url).expect("Can not connect");
let tom_cruise = for_insert::Actor {
first_name: "TOM".into(),
last_name: "CRUISE".to_string(),
};
let tom_hanks = for_insert::Actor {
first_name: "TOM".into(),
last_name: "HANKS".to_string(),
};
println!("tom_cruise: {:#?}", tom_cruise);
println!("tom_hanks: {:#?}", tom_hanks);
let actors: Result<Vec<for_retrieve::Actor>, DbError> = em.insert(&[&tom_cruise, &tom_hanks]);
println!("Actor: {:#?}", actors);
assert!(actors.is_ok());
let actors = actors.unwrap();
let today = Utc::now().date();
assert_eq!(tom_cruise.first_name, actors[0].first_name);
assert_eq!(tom_cruise.last_name, actors[0].last_name);
assert_eq!(today, actors[0].last_update.date());
assert_eq!(tom_hanks.first_name, actors[1].first_name);
assert_eq!(tom_hanks.last_name, actors[1].last_name);
assert_eq!(today, actors[1].last_update.date());
}
|
main
|
identifier_name
|
randomplay.rs
|
//! A bot playing randomly, but still following the rules.
|
pub fn genmove(goban: &mut board::Board, player: board::Colour) -> board::Vertex {
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < 10 {
let (x, y) = (rng.gen_range(1u, size+1), rng.gen_range(1u, size+1));
if goban.play(player, x, y){
return board::Put(x,y);
}
i = i+1;
}
// if we reach this point, random failed, we go for a more deterministic
// approach
for x in range(1u, size+1) {
for y in range(1u, size+1) {
if goban.play(player, x, y){
return board::Put(x,y);
}
}
}
// can play nothing?
board::Pass
}
|
use std::rand::{task_rng, Rng};
use board;
|
random_line_split
|
randomplay.rs
|
//! A bot playing randomly, but still following the rules.
use std::rand::{task_rng, Rng};
use board;
pub fn genmove(goban: &mut board::Board, player: board::Colour) -> board::Vertex {
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < 10 {
let (x, y) = (rng.gen_range(1u, size+1), rng.gen_range(1u, size+1));
if goban.play(player, x, y)
|
i = i+1;
}
// if we reach this point, random failed, we go for a more deterministic
// approach
for x in range(1u, size+1) {
for y in range(1u, size+1) {
if goban.play(player, x, y){
return board::Put(x,y);
}
}
}
// can play nothing?
board::Pass
}
|
{
return board::Put(x,y);
}
|
conditional_block
|
randomplay.rs
|
//! A bot playing randomly, but still following the rules.
use std::rand::{task_rng, Rng};
use board;
pub fn
|
(goban: &mut board::Board, player: board::Colour) -> board::Vertex {
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < 10 {
let (x, y) = (rng.gen_range(1u, size+1), rng.gen_range(1u, size+1));
if goban.play(player, x, y){
return board::Put(x,y);
}
i = i+1;
}
// if we reach this point, random failed, we go for a more deterministic
// approach
for x in range(1u, size+1) {
for y in range(1u, size+1) {
if goban.play(player, x, y){
return board::Put(x,y);
}
}
}
// can play nothing?
board::Pass
}
|
genmove
|
identifier_name
|
randomplay.rs
|
//! A bot playing randomly, but still following the rules.
use std::rand::{task_rng, Rng};
use board;
pub fn genmove(goban: &mut board::Board, player: board::Colour) -> board::Vertex
|
}
// can play nothing?
board::Pass
}
|
{
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < 10 {
let (x, y) = (rng.gen_range(1u, size+1), rng.gen_range(1u, size+1));
if goban.play(player, x, y){
return board::Put(x,y);
}
i = i+1;
}
// if we reach this point, random failed, we go for a more deterministic
// approach
for x in range(1u, size+1) {
for y in range(1u, size+1) {
if goban.play(player, x, y){
return board::Put(x,y);
}
}
|
identifier_body
|
performancetiming.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::PerformanceTimingBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::window::Window;
#[deriving(Encodable)]
pub struct
|
{
reflector_: Reflector,
navigationStart: u64,
navigationStartPrecise: f64,
}
impl PerformanceTiming {
pub fn new_inherited(navStart: u64, navStartPrecise: f64)
-> PerformanceTiming {
PerformanceTiming {
reflector_: Reflector::new(),
navigationStart: navStart,
navigationStartPrecise: navStartPrecise,
}
}
pub fn new(window: &JSRef<Window>) -> Temporary<PerformanceTiming> {
let timing = PerformanceTiming::new_inherited(window.navigationStart,
window.navigationStartPrecise);
reflect_dom_object(box timing, window, PerformanceTimingBinding::Wrap)
}
}
pub trait PerformanceTimingMethods {
fn NavigationStart(&self) -> u64;
fn NavigationStartPrecise(&self) -> f64;
}
impl<'a> PerformanceTimingMethods for JSRef<'a, PerformanceTiming> {
fn NavigationStart(&self) -> u64 {
self.navigationStart
}
fn NavigationStartPrecise(&self) -> f64 {
self.navigationStartPrecise
}
}
impl Reflectable for PerformanceTiming {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
}
|
PerformanceTiming
|
identifier_name
|
performancetiming.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::PerformanceTimingBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::window::Window;
#[deriving(Encodable)]
pub struct PerformanceTiming {
reflector_: Reflector,
navigationStart: u64,
navigationStartPrecise: f64,
}
impl PerformanceTiming {
pub fn new_inherited(navStart: u64, navStartPrecise: f64)
-> PerformanceTiming {
PerformanceTiming {
reflector_: Reflector::new(),
navigationStart: navStart,
navigationStartPrecise: navStartPrecise,
}
}
pub fn new(window: &JSRef<Window>) -> Temporary<PerformanceTiming> {
let timing = PerformanceTiming::new_inherited(window.navigationStart,
window.navigationStartPrecise);
reflect_dom_object(box timing, window, PerformanceTimingBinding::Wrap)
}
|
}
impl<'a> PerformanceTimingMethods for JSRef<'a, PerformanceTiming> {
fn NavigationStart(&self) -> u64 {
self.navigationStart
}
fn NavigationStartPrecise(&self) -> f64 {
self.navigationStartPrecise
}
}
impl Reflectable for PerformanceTiming {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
}
|
}
pub trait PerformanceTimingMethods {
fn NavigationStart(&self) -> u64;
fn NavigationStartPrecise(&self) -> f64;
|
random_line_split
|
key.rs
|
use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Key(KeyEvent);
impl Key {
pub fn new(event: KeyEvent) -> Self {
Self(event)
}
pub fn from_code(code: KeyCode) -> Self {
Self(KeyEvent::new(code, KeyModifiers::NONE))
}
pub fn ctrl_pressed(&self) -> bool {
self.0.modifiers.contains(KeyModifiers::CONTROL)
}
}
impl Deref for Key {
type Target = KeyCode;
fn deref(&self) -> &Self::Target {
&self.0.code
}
}
impl TryFrom<&str> for Key {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let value = value.to_ascii_lowercase();
let modifier_split = value
.splitn(2, '+')
.map(str::trim)
.collect::<SmallVec<[_; 2]>>();
let (modifier, key) = match modifier_split.as_slice() {
["ctrl", key] => (KeyModifiers::CONTROL, key),
["shift", key] => (KeyModifiers::SHIFT, key),
["alt", key] => (KeyModifiers::ALT, key),
[_, key] | [key] => (KeyModifiers::NONE, key),
[] => return Err(anyhow!("no key specified")),
_ => return Err(anyhow!("malformed key")),
};
let code = match *key {
"backspace" => KeyCode::Backspace,
"enter" => KeyCode::Enter,
"left" => KeyCode::Left,
"right" => KeyCode::Right,
"up" => KeyCode::Up,
"down" => KeyCode::Down,
"home" => KeyCode::Home,
"end" => KeyCode::End,
"pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"tab" => KeyCode::Tab,
"backtab" => KeyCode::BackTab,
"delete" => KeyCode::Delete,
"insert" => KeyCode::Insert,
"unknown" => KeyCode::Null,
"escape" => KeyCode::Esc,
key if key.len() == 1 && key.is_ascii() =>
|
key if key.starts_with('f') => {
let num = key[1..].parse().context("invalid F key")?;
if!(1..=12).contains(&num) {
return Err(anyhow!("F key must be between 1-12"));
}
KeyCode::F(num)
}
unknown => return Err(anyhow!("unknown key: {}", unknown)),
};
let event = KeyEvent::new(code, modifier);
Ok(Self(event))
}
}
impl<'de> Deserialize<'de> for Key {
fn deserialize<D>(de: D) -> result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use std::fmt;
struct KeyVisitor;
impl<'de> Visitor<'de> for KeyVisitor {
type Value = Key;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a key")
}
fn visit_str<E>(self, value: &str) -> result::Result<Self::Value, E>
where
E: de::Error,
{
value.try_into().map_err(E::custom)
}
}
de.deserialize_str(KeyVisitor)
}
}
impl Serialize for Key {
fn serialize<S>(&self, se: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.0.code {
KeyCode::Backspace => se.serialize_str("backspace"),
KeyCode::Enter => se.serialize_str("enter"),
KeyCode::Left => se.serialize_str("left"),
KeyCode::Right => se.serialize_str("right"),
KeyCode::Up => se.serialize_str("up"),
KeyCode::Down => se.serialize_str("down"),
KeyCode::Home => se.serialize_str("home"),
KeyCode::End => se.serialize_str("end"),
KeyCode::PageUp => se.serialize_str("pageup"),
KeyCode::PageDown => se.serialize_str("pagedown"),
KeyCode::Tab => se.serialize_str("tab"),
KeyCode::BackTab => se.serialize_str("backtab"),
KeyCode::Delete => se.serialize_str("delete"),
KeyCode::Insert => se.serialize_str("insert"),
KeyCode::F(key) => se.serialize_str(&format!("f{}", key)),
KeyCode::Char(key) => se.serialize_char(key),
KeyCode::Null => se.serialize_str("unknown"),
KeyCode::Esc => se.serialize_str("escape"),
}
}
}
#[cfg(test)]
mod tests {
use super::Key;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::convert::TryInto;
macro_rules! test_key {
($key:expr, $expected_code:expr => $modifier:expr) => {{
let value = $key.try_into().map_err(|e: anyhow::Error| e.to_string());
let expected = Key::new(KeyEvent::new($expected_code, $modifier));
assert_eq!(value, Ok(expected));
}};
}
#[test]
fn valid_keys() {
test_key!("j", KeyCode::Char('j') => KeyModifiers::NONE);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
test_key!("K", KeyCode::Char('k') => KeyModifiers::NONE);
test_key!("ctrl+b", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("CTRL+B", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("shift+enter", KeyCode::Enter => KeyModifiers::SHIFT);
test_key!("alt+tab", KeyCode::Tab => KeyModifiers::ALT);
test_key!("ctrl + backspace", KeyCode::Backspace => KeyModifiers::CONTROL);
test_key!(" shift + f12", KeyCode::F(12) => KeyModifiers::SHIFT);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
}
#[test]
#[should_panic]
fn invalid_keys() {
test_key!("a", KeyCode::Char('b') => KeyModifiers::NONE);
test_key!("j", KeyCode::Char('j') => KeyModifiers::CONTROL);
test_key!("f0", KeyCode::F(0) => KeyModifiers::NONE);
test_key!("f13", KeyCode::F(13) => KeyModifiers::NONE);
test_key!("ctrl++a", KeyCode::Char('a') => KeyModifiers::CONTROL);
test_key!("shift", KeyCode::Null => KeyModifiers::SHIFT);
test_key!("", KeyCode::Null => KeyModifiers::NONE);
}
}
|
{
let bytes = key.as_bytes();
KeyCode::Char(bytes[0] as char)
}
|
conditional_block
|
key.rs
|
use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Key(KeyEvent);
impl Key {
pub fn new(event: KeyEvent) -> Self {
Self(event)
}
pub fn from_code(code: KeyCode) -> Self {
Self(KeyEvent::new(code, KeyModifiers::NONE))
}
pub fn ctrl_pressed(&self) -> bool
|
}
impl Deref for Key {
type Target = KeyCode;
fn deref(&self) -> &Self::Target {
&self.0.code
}
}
impl TryFrom<&str> for Key {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let value = value.to_ascii_lowercase();
let modifier_split = value
.splitn(2, '+')
.map(str::trim)
.collect::<SmallVec<[_; 2]>>();
let (modifier, key) = match modifier_split.as_slice() {
["ctrl", key] => (KeyModifiers::CONTROL, key),
["shift", key] => (KeyModifiers::SHIFT, key),
["alt", key] => (KeyModifiers::ALT, key),
[_, key] | [key] => (KeyModifiers::NONE, key),
[] => return Err(anyhow!("no key specified")),
_ => return Err(anyhow!("malformed key")),
};
let code = match *key {
"backspace" => KeyCode::Backspace,
"enter" => KeyCode::Enter,
"left" => KeyCode::Left,
"right" => KeyCode::Right,
"up" => KeyCode::Up,
"down" => KeyCode::Down,
"home" => KeyCode::Home,
"end" => KeyCode::End,
"pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"tab" => KeyCode::Tab,
"backtab" => KeyCode::BackTab,
"delete" => KeyCode::Delete,
"insert" => KeyCode::Insert,
"unknown" => KeyCode::Null,
"escape" => KeyCode::Esc,
key if key.len() == 1 && key.is_ascii() => {
let bytes = key.as_bytes();
KeyCode::Char(bytes[0] as char)
}
key if key.starts_with('f') => {
let num = key[1..].parse().context("invalid F key")?;
if!(1..=12).contains(&num) {
return Err(anyhow!("F key must be between 1-12"));
}
KeyCode::F(num)
}
unknown => return Err(anyhow!("unknown key: {}", unknown)),
};
let event = KeyEvent::new(code, modifier);
Ok(Self(event))
}
}
impl<'de> Deserialize<'de> for Key {
fn deserialize<D>(de: D) -> result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use std::fmt;
struct KeyVisitor;
impl<'de> Visitor<'de> for KeyVisitor {
type Value = Key;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a key")
}
fn visit_str<E>(self, value: &str) -> result::Result<Self::Value, E>
where
E: de::Error,
{
value.try_into().map_err(E::custom)
}
}
de.deserialize_str(KeyVisitor)
}
}
impl Serialize for Key {
fn serialize<S>(&self, se: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.0.code {
KeyCode::Backspace => se.serialize_str("backspace"),
KeyCode::Enter => se.serialize_str("enter"),
KeyCode::Left => se.serialize_str("left"),
KeyCode::Right => se.serialize_str("right"),
KeyCode::Up => se.serialize_str("up"),
KeyCode::Down => se.serialize_str("down"),
KeyCode::Home => se.serialize_str("home"),
KeyCode::End => se.serialize_str("end"),
KeyCode::PageUp => se.serialize_str("pageup"),
KeyCode::PageDown => se.serialize_str("pagedown"),
KeyCode::Tab => se.serialize_str("tab"),
KeyCode::BackTab => se.serialize_str("backtab"),
KeyCode::Delete => se.serialize_str("delete"),
KeyCode::Insert => se.serialize_str("insert"),
KeyCode::F(key) => se.serialize_str(&format!("f{}", key)),
KeyCode::Char(key) => se.serialize_char(key),
KeyCode::Null => se.serialize_str("unknown"),
KeyCode::Esc => se.serialize_str("escape"),
}
}
}
#[cfg(test)]
mod tests {
use super::Key;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::convert::TryInto;
macro_rules! test_key {
($key:expr, $expected_code:expr => $modifier:expr) => {{
let value = $key.try_into().map_err(|e: anyhow::Error| e.to_string());
let expected = Key::new(KeyEvent::new($expected_code, $modifier));
assert_eq!(value, Ok(expected));
}};
}
#[test]
fn valid_keys() {
test_key!("j", KeyCode::Char('j') => KeyModifiers::NONE);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
test_key!("K", KeyCode::Char('k') => KeyModifiers::NONE);
test_key!("ctrl+b", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("CTRL+B", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("shift+enter", KeyCode::Enter => KeyModifiers::SHIFT);
test_key!("alt+tab", KeyCode::Tab => KeyModifiers::ALT);
test_key!("ctrl + backspace", KeyCode::Backspace => KeyModifiers::CONTROL);
test_key!(" shift + f12", KeyCode::F(12) => KeyModifiers::SHIFT);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
}
#[test]
#[should_panic]
fn invalid_keys() {
test_key!("a", KeyCode::Char('b') => KeyModifiers::NONE);
test_key!("j", KeyCode::Char('j') => KeyModifiers::CONTROL);
test_key!("f0", KeyCode::F(0) => KeyModifiers::NONE);
test_key!("f13", KeyCode::F(13) => KeyModifiers::NONE);
test_key!("ctrl++a", KeyCode::Char('a') => KeyModifiers::CONTROL);
test_key!("shift", KeyCode::Null => KeyModifiers::SHIFT);
test_key!("", KeyCode::Null => KeyModifiers::NONE);
}
}
|
{
self.0.modifiers.contains(KeyModifiers::CONTROL)
}
|
identifier_body
|
key.rs
|
use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Key(KeyEvent);
impl Key {
pub fn new(event: KeyEvent) -> Self {
Self(event)
}
pub fn from_code(code: KeyCode) -> Self {
Self(KeyEvent::new(code, KeyModifiers::NONE))
}
pub fn ctrl_pressed(&self) -> bool {
self.0.modifiers.contains(KeyModifiers::CONTROL)
}
}
impl Deref for Key {
type Target = KeyCode;
fn deref(&self) -> &Self::Target {
&self.0.code
}
}
impl TryFrom<&str> for Key {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let value = value.to_ascii_lowercase();
let modifier_split = value
.splitn(2, '+')
.map(str::trim)
.collect::<SmallVec<[_; 2]>>();
let (modifier, key) = match modifier_split.as_slice() {
["ctrl", key] => (KeyModifiers::CONTROL, key),
["shift", key] => (KeyModifiers::SHIFT, key),
["alt", key] => (KeyModifiers::ALT, key),
[_, key] | [key] => (KeyModifiers::NONE, key),
[] => return Err(anyhow!("no key specified")),
_ => return Err(anyhow!("malformed key")),
};
let code = match *key {
"backspace" => KeyCode::Backspace,
"enter" => KeyCode::Enter,
"left" => KeyCode::Left,
"right" => KeyCode::Right,
"up" => KeyCode::Up,
"down" => KeyCode::Down,
"home" => KeyCode::Home,
"end" => KeyCode::End,
"pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"tab" => KeyCode::Tab,
"backtab" => KeyCode::BackTab,
"delete" => KeyCode::Delete,
"insert" => KeyCode::Insert,
"unknown" => KeyCode::Null,
"escape" => KeyCode::Esc,
key if key.len() == 1 && key.is_ascii() => {
let bytes = key.as_bytes();
KeyCode::Char(bytes[0] as char)
}
key if key.starts_with('f') => {
let num = key[1..].parse().context("invalid F key")?;
if!(1..=12).contains(&num) {
return Err(anyhow!("F key must be between 1-12"));
}
KeyCode::F(num)
}
unknown => return Err(anyhow!("unknown key: {}", unknown)),
};
let event = KeyEvent::new(code, modifier);
Ok(Self(event))
}
}
impl<'de> Deserialize<'de> for Key {
fn deserialize<D>(de: D) -> result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use std::fmt;
struct KeyVisitor;
impl<'de> Visitor<'de> for KeyVisitor {
type Value = Key;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a key")
}
fn visit_str<E>(self, value: &str) -> result::Result<Self::Value, E>
where
E: de::Error,
{
value.try_into().map_err(E::custom)
}
}
de.deserialize_str(KeyVisitor)
}
}
impl Serialize for Key {
fn serialize<S>(&self, se: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.0.code {
KeyCode::Backspace => se.serialize_str("backspace"),
KeyCode::Enter => se.serialize_str("enter"),
KeyCode::Left => se.serialize_str("left"),
KeyCode::Right => se.serialize_str("right"),
KeyCode::Up => se.serialize_str("up"),
KeyCode::Down => se.serialize_str("down"),
KeyCode::Home => se.serialize_str("home"),
KeyCode::End => se.serialize_str("end"),
KeyCode::PageUp => se.serialize_str("pageup"),
KeyCode::PageDown => se.serialize_str("pagedown"),
KeyCode::Tab => se.serialize_str("tab"),
KeyCode::BackTab => se.serialize_str("backtab"),
KeyCode::Delete => se.serialize_str("delete"),
KeyCode::Insert => se.serialize_str("insert"),
KeyCode::F(key) => se.serialize_str(&format!("f{}", key)),
KeyCode::Char(key) => se.serialize_char(key),
KeyCode::Null => se.serialize_str("unknown"),
KeyCode::Esc => se.serialize_str("escape"),
}
}
}
#[cfg(test)]
mod tests {
use super::Key;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::convert::TryInto;
macro_rules! test_key {
($key:expr, $expected_code:expr => $modifier:expr) => {{
let value = $key.try_into().map_err(|e: anyhow::Error| e.to_string());
let expected = Key::new(KeyEvent::new($expected_code, $modifier));
assert_eq!(value, Ok(expected));
}};
}
#[test]
fn
|
() {
test_key!("j", KeyCode::Char('j') => KeyModifiers::NONE);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
test_key!("K", KeyCode::Char('k') => KeyModifiers::NONE);
test_key!("ctrl+b", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("CTRL+B", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("shift+enter", KeyCode::Enter => KeyModifiers::SHIFT);
test_key!("alt+tab", KeyCode::Tab => KeyModifiers::ALT);
test_key!("ctrl + backspace", KeyCode::Backspace => KeyModifiers::CONTROL);
test_key!(" shift + f12", KeyCode::F(12) => KeyModifiers::SHIFT);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
}
#[test]
#[should_panic]
fn invalid_keys() {
test_key!("a", KeyCode::Char('b') => KeyModifiers::NONE);
test_key!("j", KeyCode::Char('j') => KeyModifiers::CONTROL);
test_key!("f0", KeyCode::F(0) => KeyModifiers::NONE);
test_key!("f13", KeyCode::F(13) => KeyModifiers::NONE);
test_key!("ctrl++a", KeyCode::Char('a') => KeyModifiers::CONTROL);
test_key!("shift", KeyCode::Null => KeyModifiers::SHIFT);
test_key!("", KeyCode::Null => KeyModifiers::NONE);
}
}
|
valid_keys
|
identifier_name
|
key.rs
|
use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Key(KeyEvent);
impl Key {
pub fn new(event: KeyEvent) -> Self {
Self(event)
}
pub fn from_code(code: KeyCode) -> Self {
Self(KeyEvent::new(code, KeyModifiers::NONE))
}
pub fn ctrl_pressed(&self) -> bool {
self.0.modifiers.contains(KeyModifiers::CONTROL)
}
}
impl Deref for Key {
type Target = KeyCode;
fn deref(&self) -> &Self::Target {
&self.0.code
}
}
impl TryFrom<&str> for Key {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let value = value.to_ascii_lowercase();
let modifier_split = value
.splitn(2, '+')
.map(str::trim)
.collect::<SmallVec<[_; 2]>>();
let (modifier, key) = match modifier_split.as_slice() {
["ctrl", key] => (KeyModifiers::CONTROL, key),
["shift", key] => (KeyModifiers::SHIFT, key),
["alt", key] => (KeyModifiers::ALT, key),
[_, key] | [key] => (KeyModifiers::NONE, key),
[] => return Err(anyhow!("no key specified")),
_ => return Err(anyhow!("malformed key")),
};
let code = match *key {
"backspace" => KeyCode::Backspace,
"enter" => KeyCode::Enter,
"left" => KeyCode::Left,
"right" => KeyCode::Right,
"up" => KeyCode::Up,
"down" => KeyCode::Down,
"home" => KeyCode::Home,
|
"pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"tab" => KeyCode::Tab,
"backtab" => KeyCode::BackTab,
"delete" => KeyCode::Delete,
"insert" => KeyCode::Insert,
"unknown" => KeyCode::Null,
"escape" => KeyCode::Esc,
key if key.len() == 1 && key.is_ascii() => {
let bytes = key.as_bytes();
KeyCode::Char(bytes[0] as char)
}
key if key.starts_with('f') => {
let num = key[1..].parse().context("invalid F key")?;
if!(1..=12).contains(&num) {
return Err(anyhow!("F key must be between 1-12"));
}
KeyCode::F(num)
}
unknown => return Err(anyhow!("unknown key: {}", unknown)),
};
let event = KeyEvent::new(code, modifier);
Ok(Self(event))
}
}
impl<'de> Deserialize<'de> for Key {
fn deserialize<D>(de: D) -> result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use std::fmt;
struct KeyVisitor;
impl<'de> Visitor<'de> for KeyVisitor {
type Value = Key;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a key")
}
fn visit_str<E>(self, value: &str) -> result::Result<Self::Value, E>
where
E: de::Error,
{
value.try_into().map_err(E::custom)
}
}
de.deserialize_str(KeyVisitor)
}
}
impl Serialize for Key {
fn serialize<S>(&self, se: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.0.code {
KeyCode::Backspace => se.serialize_str("backspace"),
KeyCode::Enter => se.serialize_str("enter"),
KeyCode::Left => se.serialize_str("left"),
KeyCode::Right => se.serialize_str("right"),
KeyCode::Up => se.serialize_str("up"),
KeyCode::Down => se.serialize_str("down"),
KeyCode::Home => se.serialize_str("home"),
KeyCode::End => se.serialize_str("end"),
KeyCode::PageUp => se.serialize_str("pageup"),
KeyCode::PageDown => se.serialize_str("pagedown"),
KeyCode::Tab => se.serialize_str("tab"),
KeyCode::BackTab => se.serialize_str("backtab"),
KeyCode::Delete => se.serialize_str("delete"),
KeyCode::Insert => se.serialize_str("insert"),
KeyCode::F(key) => se.serialize_str(&format!("f{}", key)),
KeyCode::Char(key) => se.serialize_char(key),
KeyCode::Null => se.serialize_str("unknown"),
KeyCode::Esc => se.serialize_str("escape"),
}
}
}
#[cfg(test)]
mod tests {
use super::Key;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::convert::TryInto;
macro_rules! test_key {
($key:expr, $expected_code:expr => $modifier:expr) => {{
let value = $key.try_into().map_err(|e: anyhow::Error| e.to_string());
let expected = Key::new(KeyEvent::new($expected_code, $modifier));
assert_eq!(value, Ok(expected));
}};
}
#[test]
fn valid_keys() {
test_key!("j", KeyCode::Char('j') => KeyModifiers::NONE);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
test_key!("K", KeyCode::Char('k') => KeyModifiers::NONE);
test_key!("ctrl+b", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("CTRL+B", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("shift+enter", KeyCode::Enter => KeyModifiers::SHIFT);
test_key!("alt+tab", KeyCode::Tab => KeyModifiers::ALT);
test_key!("ctrl + backspace", KeyCode::Backspace => KeyModifiers::CONTROL);
test_key!(" shift + f12", KeyCode::F(12) => KeyModifiers::SHIFT);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
}
#[test]
#[should_panic]
fn invalid_keys() {
test_key!("a", KeyCode::Char('b') => KeyModifiers::NONE);
test_key!("j", KeyCode::Char('j') => KeyModifiers::CONTROL);
test_key!("f0", KeyCode::F(0) => KeyModifiers::NONE);
test_key!("f13", KeyCode::F(13) => KeyModifiers::NONE);
test_key!("ctrl++a", KeyCode::Char('a') => KeyModifiers::CONTROL);
test_key!("shift", KeyCode::Null => KeyModifiers::SHIFT);
test_key!("", KeyCode::Null => KeyModifiers::NONE);
}
}
|
"end" => KeyCode::End,
|
random_line_split
|
lang_items.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.
// Detecting language items.
//
// Language items are items that represent concepts intrinsic to the language
// itself. Examples are:
//
// * Traits that specify "kinds"; e.g. "Sync", "Send".
//
// * Traits that represent operators; e.g. "Add", "Sub", "Index".
//
// * Functions called by the compiler itself.
pub use self::LangItem::*;
use session::Session;
use metadata::csearch::each_lang_item;
use middle::ty;
use middle::weak_lang_items;
use util::nodemap::FnvHashMap;
use syntax::ast;
use syntax::ast_util::local_def;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::parse::token::InternedString;
use syntax::visit::Visitor;
use syntax::visit;
use std::iter::Enumerate;
use std::slice;
// The actual lang items defined come at the end of this file in one handy table.
// So you probably just want to nip down to the end.
macro_rules! lets_do_this {
(
$( $variant:ident, $name:expr, $method:ident; )*
) => {
enum_from_u32! {
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum LangItem {
$($variant,)*
}
}
pub struct LanguageItems {
pub items: Vec<Option<ast::DefId>>,
pub missing: Vec<LangItem>,
}
impl LanguageItems {
pub fn new() -> LanguageItems {
fn foo(_: LangItem) -> Option<ast::DefId> { None }
LanguageItems {
items: vec!($(foo($variant)),*),
missing: Vec::new(),
}
}
pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<ast::DefId>>> {
self.items.iter().enumerate()
}
pub fn item_name(index: usize) -> &'static str {
let item: Option<LangItem> = LangItem::from_u32(index as u32);
match item {
$( Some($variant) => $name, )*
None => "???"
}
}
pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
match self.items[it as usize] {
Some(id) => Ok(id),
None => {
Err(format!("requires `{}` lang_item",
LanguageItems::item_name(it as usize)))
}
}
}
pub fn from_builtin_kind(&self, bound: ty::BuiltinBound)
-> Result<ast::DefId, String>
{
match bound {
ty::BoundSend => self.require(SendTraitLangItem),
ty::BoundSized => self.require(SizedTraitLangItem),
ty::BoundCopy => self.require(CopyTraitLangItem),
ty::BoundSync => self.require(SyncTraitLangItem),
}
}
pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
if Some(id) == self.send_trait() {
Some(ty::BoundSend)
} else if Some(id) == self.sized_trait() {
Some(ty::BoundSized)
} else if Some(id) == self.copy_trait() {
Some(ty::BoundCopy)
} else if Some(id) == self.sync_trait() {
Some(ty::BoundSync)
} else {
None
}
}
pub fn fn_trait_kind(&self, id: ast::DefId) -> Option<ty::ClosureKind> {
let def_id_kinds = [
(self.fn_trait(), ty::FnClosureKind),
(self.fn_mut_trait(), ty::FnMutClosureKind),
(self.fn_once_trait(), ty::FnOnceClosureKind),
];
for &(opt_def_id, kind) in &def_id_kinds {
if Some(id) == opt_def_id {
return Some(kind);
}
}
None
}
$(
#[allow(dead_code)]
pub fn $method(&self) -> Option<ast::DefId> {
self.items[$variant as usize]
}
)*
}
struct LanguageItemCollector<'a> {
items: LanguageItems,
session: &'a Session,
item_refs: FnvHashMap<&'static str, usize>,
}
impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
fn visit_item(&mut self, item: &ast::Item) {
if let Some(value) = extract(&item.attrs) {
let item_index = self.item_refs.get(&value[..]).cloned();
if let Some(item_index) = item_index {
self.collect_item(item_index, local_def(item.id), item.span)
}
}
visit::walk_item(self, item);
}
}
impl<'a> LanguageItemCollector<'a> {
pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
let mut item_refs = FnvHashMap();
$( item_refs.insert($name, $variant as usize); )*
LanguageItemCollector {
session: session,
items: LanguageItems::new(),
item_refs: item_refs
}
}
pub fn collect_item(&mut self, item_index: usize,
item_def_id: ast::DefId, span: Span) {
// Check for duplicates.
match self.items.items[item_index] {
Some(original_def_id) if original_def_id!= item_def_id => {
span_err!(self.session, span, E0152,
"duplicate entry for `{}`", LanguageItems::item_name(item_index));
}
Some(_) | None => {
// OK.
}
}
// Matched.
self.items.items[item_index] = Some(item_def_id);
}
pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
visit::walk_crate(self, krate);
}
pub fn collect_external_language_items(&mut self) {
let crate_store = &self.session.cstore;
crate_store.iter_crate_data(|crate_number, _crate_metadata| {
each_lang_item(crate_store, crate_number, |node_id, item_index| {
let def_id = ast::DefId { krate: crate_number, node: node_id };
self.collect_item(item_index, def_id, DUMMY_SP);
true
});
})
}
pub fn collect(&mut self, krate: &ast::Crate) {
self.collect_local_language_items(krate);
self.collect_external_language_items();
}
}
pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
for attribute in attrs {
match attribute.value_str() {
Some(ref value) if attribute.check_name("lang") => {
return Some(value.clone());
}
_ => {}
}
}
return None;
}
pub fn collect_language_items(krate: &ast::Crate,
session: &Session) -> LanguageItems {
let mut collector = LanguageItemCollector::new(session);
collector.collect(krate);
let LanguageItemCollector { mut items,.. } = collector;
weak_lang_items::check_crate(krate, session, &mut items);
session.abort_if_errors();
items
}
// End of the macro
}
}
lets_do_this! {
// Variant name, Name, Method name;
CharImplItem, "char", char_impl;
StrImplItem, "str", str_impl;
SliceImplItem, "slice", slice_impl;
ConstPtrImplItem, "const_ptr", const_ptr_impl;
MutPtrImplItem, "mut_ptr", mut_ptr_impl;
I8ImplItem, "i8", i8_impl;
I16ImplItem, "i16", i16_impl;
I32ImplItem, "i32", i32_impl;
I64ImplItem, "i64", i64_impl;
IsizeImplItem, "isize", isize_impl;
U8ImplItem, "u8", u8_impl;
U16ImplItem, "u16", u16_impl;
U32ImplItem, "u32", u32_impl;
U64ImplItem, "u64", u64_impl;
UsizeImplItem, "usize", usize_impl;
F32ImplItem, "f32", f32_impl;
F64ImplItem, "f64", f64_impl;
SendTraitLangItem, "send", send_trait;
SizedTraitLangItem, "sized", sized_trait;
UnsizeTraitLangItem, "unsize", unsize_trait;
CopyTraitLangItem, "copy", copy_trait;
SyncTraitLangItem, "sync", sync_trait;
DropTraitLangItem, "drop", drop_trait;
CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait;
AddTraitLangItem, "add", add_trait;
SubTraitLangItem, "sub", sub_trait;
MulTraitLangItem, "mul", mul_trait;
DivTraitLangItem, "div", div_trait;
RemTraitLangItem, "rem", rem_trait;
NegTraitLangItem, "neg", neg_trait;
NotTraitLangItem, "not", not_trait;
BitXorTraitLangItem, "bitxor", bitxor_trait;
BitAndTraitLangItem, "bitand", bitand_trait;
BitOrTraitLangItem, "bitor", bitor_trait;
ShlTraitLangItem, "shl", shl_trait;
ShrTraitLangItem, "shr", shr_trait;
IndexTraitLangItem, "index", index_trait;
IndexMutTraitLangItem, "index_mut", index_mut_trait;
RangeStructLangItem, "range", range_struct;
RangeFromStructLangItem, "range_from", range_from_struct;
RangeToStructLangItem, "range_to", range_to_struct;
RangeFullStructLangItem, "range_full", range_full_struct;
UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type;
|
FnTraitLangItem, "fn", fn_trait;
FnMutTraitLangItem, "fn_mut", fn_mut_trait;
FnOnceTraitLangItem, "fn_once", fn_once_trait;
EqTraitLangItem, "eq", eq_trait;
OrdTraitLangItem, "ord", ord_trait;
StrEqFnLangItem, "str_eq", str_eq_fn;
// A number of panic-related lang items. The `panic` item corresponds to
// divide-by-zero and various panic cases with `match`. The
// `panic_bounds_check` item is for indexing arrays.
//
// The `begin_unwind` lang item has a predefined symbol name and is sort of
// a "weak lang item" in the sense that a crate is not required to have it
// defined to use it, but a final product is required to define it
// somewhere. Additionally, there are restrictions on crates that use a weak
// lang item, but do not have it defined.
PanicFnLangItem, "panic", panic_fn;
PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
PanicFmtLangItem, "panic_fmt", panic_fmt;
ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn;
StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn;
StartFnLangItem, "start", start_fn;
EhPersonalityLangItem, "eh_personality", eh_personality;
ExchangeHeapLangItem, "exchange_heap", exchange_heap;
OwnedBoxLangItem, "owned_box", owned_box;
PhantomDataItem, "phantom_data", phantom_data;
// Deprecated:
CovariantTypeItem, "covariant_type", covariant_type;
ContravariantTypeItem, "contravariant_type", contravariant_type;
InvariantTypeItem, "invariant_type", invariant_type;
CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime;
ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime;
InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime;
NoCopyItem, "no_copy_bound", no_copy_bound;
NonZeroItem, "non_zero", non_zero;
StackExhaustedLangItem, "stack_exhausted", stack_exhausted;
DebugTraitLangItem, "debug_trait", debug_trait;
}
|
DerefTraitLangItem, "deref", deref_trait;
DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
|
random_line_split
|
issue-2311-2.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.
trait clam<A> {
fn get(self) -> A;
}
struct foo<A> {
x: A,
}
impl<A> foo<A> {
pub fn bar<B,C:clam<A>>(&self, _c: C) -> B {
panic!();
}
}
fn
|
<A>(b: A) -> foo<A> {
foo {
x: b
}
}
pub fn main() { }
|
foo
|
identifier_name
|
issue-2311-2.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
|
trait clam<A> {
fn get(self) -> A;
}
struct foo<A> {
x: A,
}
impl<A> foo<A> {
pub fn bar<B,C:clam<A>>(&self, _c: C) -> B {
panic!();
}
}
fn foo<A>(b: A) -> foo<A> {
foo {
x: b
}
}
pub fn main() { }
|
// except according to those terms.
|
random_line_split
|
main.rs
|
use std::error::Error;
use std::path::{Path, PathBuf};
use yaml_rust::{Yaml, YamlEmitter, YamlLoader};
/// List of directories containing files to expand. The first tuple element is the source
/// directory, while the second tuple element is the destination directory.
#[rustfmt::skip]
static TO_EXPAND: &[(&str, &str)] = &[
("src/ci/github-actions", ".github/workflows"),
];
/// Name of a special key that will be removed from all the maps in expanded configuration files.
/// This key can then be used to contain shared anchors.
static REMOVE_MAP_KEY: &str = "x--expand-yaml-anchors--remove";
/// Message that will be included at the top of all the expanded files. {source} will be replaced
/// with the source filename relative to the base path.
static HEADER_MESSAGE: &str = "\
#############################################################
# WARNING: automatically generated file, DO NOT CHANGE! #
#############################################################
# This file was automatically generated by the expand-yaml-anchors tool. The
# source file that generated this one is:
#
# {source}
#
# Once you make changes to that file you need to run:
#
# ./x.py run src/tools/expand-yaml-anchors/
#
# The CI build will fail if the tool is not run after changes to this file.
";
enum Mode {
Check,
Generate,
}
struct App {
mode: Mode,
base: PathBuf,
}
impl App {
fn from_args() -> Result<Self, Box<dyn Error>> {
// Parse CLI arguments
let args = std::env::args().skip(1).collect::<Vec<_>>();
let (mode, base) = match args.iter().map(|s| s.as_str()).collect::<Vec<_>>().as_slice() {
["generate", ref base] => (Mode::Generate, PathBuf::from(base)),
["check", ref base] => (Mode::Check, PathBuf::from(base)),
_ => {
eprintln!("usage: expand-yaml-anchors <source-dir> <dest-dir>");
std::process::exit(1);
}
};
Ok(App { mode, base })
}
fn run(&self) -> Result<(), Box<dyn Error>> {
for (source, dest) in TO_EXPAND {
let source = self.base.join(source);
let dest = self.base.join(dest);
for entry in std::fs::read_dir(&source)? {
let path = entry?.path();
if!path.is_file() || path.extension().and_then(|e| e.to_str())!= Some("yml") {
continue;
}
let dest_path = dest.join(path.file_name().unwrap());
self.expand(&path, &dest_path).with_context(|| match self.mode {
Mode::Generate => format!(
"failed to expand {} into {}",
self.path(&path),
self.path(&dest_path)
),
Mode::Check => format!(
"{} is not up to date; please run \
`x.py run src/tools/expand-yaml-anchors`.",
self.path(&dest_path)
),
})?;
}
}
Ok(())
}
fn expand(&self, source: &Path, dest: &Path) -> Result<(), Box<dyn Error>> {
let content = std::fs::read_to_string(source)
.with_context(|| format!("failed to read {}", self.path(source)))?;
let mut buf =
HEADER_MESSAGE.replace("{source}", &self.path(source).to_string().replace("\\", "/"));
let documents = YamlLoader::load_from_str(&content)
.with_context(|| format!("failed to parse {}", self.path(source)))?;
for mut document in documents.into_iter() {
document = yaml_merge_keys::merge_keys(document)
.with_context(|| format!("failed to expand {}", self.path(source)))?;
document = filter_document(document);
YamlEmitter::new(&mut buf).dump(&document).map_err(|err| WithContext {
context: "failed to serialize the expanded yaml".into(),
source: Box::new(err),
})?;
buf.push('\n');
}
match self.mode {
Mode::Check => {
let old = std::fs::read_to_string(dest)
.with_context(|| format!("failed to read {}", self.path(dest)))?;
if old!= buf {
return Err(Box::new(StrError(format!(
"{} and {} are different",
self.path(source),
self.path(dest),
))));
}
|
}
Mode::Generate => {
std::fs::write(dest, buf.as_bytes())
.with_context(|| format!("failed to write to {}", self.path(dest)))?;
}
}
Ok(())
}
fn path<'a>(&self, path: &'a Path) -> impl std::fmt::Display + 'a {
path.strip_prefix(&self.base).unwrap_or(path).display()
}
}
fn filter_document(document: Yaml) -> Yaml {
match document {
Yaml::Hash(map) => Yaml::Hash(
map.into_iter()
.filter(|(key, _)| {
if let Yaml::String(string) = &key { string!= REMOVE_MAP_KEY } else { true }
})
.map(|(key, value)| (filter_document(key), filter_document(value)))
.collect(),
),
Yaml::Array(vec) => Yaml::Array(vec.into_iter().map(filter_document).collect()),
other => other,
}
}
fn main() {
if let Err(err) = App::from_args().and_then(|app| app.run()) {
eprintln!("error: {}", err);
let mut source = err.as_ref() as &dyn Error;
while let Some(err) = source.source() {
eprintln!("caused by: {}", err);
source = err;
}
std::process::exit(1);
}
}
#[derive(Debug)]
struct StrError(String);
impl Error for StrError {}
impl std::fmt::Display for StrError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
#[derive(Debug)]
struct WithContext {
context: String,
source: Box<dyn Error>,
}
impl std::fmt::Display for WithContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.context)
}
}
impl Error for WithContext {
fn source(&self) -> Option<&(dyn Error +'static)> {
Some(self.source.as_ref())
}
}
pub(crate) trait ResultExt<T> {
fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T, Box<dyn Error>>;
}
impl<T, E: Into<Box<dyn Error>>> ResultExt<T> for Result<T, E> {
fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T, Box<dyn Error>> {
match self {
Ok(ok) => Ok(ok),
Err(err) => Err(WithContext { source: err.into(), context: f() }.into()),
}
}
}
|
random_line_split
|
|
main.rs
|
use std::error::Error;
use std::path::{Path, PathBuf};
use yaml_rust::{Yaml, YamlEmitter, YamlLoader};
/// List of directories containing files to expand. The first tuple element is the source
/// directory, while the second tuple element is the destination directory.
#[rustfmt::skip]
static TO_EXPAND: &[(&str, &str)] = &[
("src/ci/github-actions", ".github/workflows"),
];
/// Name of a special key that will be removed from all the maps in expanded configuration files.
/// This key can then be used to contain shared anchors.
static REMOVE_MAP_KEY: &str = "x--expand-yaml-anchors--remove";
/// Message that will be included at the top of all the expanded files. {source} will be replaced
/// with the source filename relative to the base path.
static HEADER_MESSAGE: &str = "\
#############################################################
# WARNING: automatically generated file, DO NOT CHANGE! #
#############################################################
# This file was automatically generated by the expand-yaml-anchors tool. The
# source file that generated this one is:
#
# {source}
#
# Once you make changes to that file you need to run:
#
# ./x.py run src/tools/expand-yaml-anchors/
#
# The CI build will fail if the tool is not run after changes to this file.
";
enum Mode {
Check,
Generate,
}
struct App {
mode: Mode,
base: PathBuf,
}
impl App {
fn from_args() -> Result<Self, Box<dyn Error>> {
// Parse CLI arguments
let args = std::env::args().skip(1).collect::<Vec<_>>();
let (mode, base) = match args.iter().map(|s| s.as_str()).collect::<Vec<_>>().as_slice() {
["generate", ref base] => (Mode::Generate, PathBuf::from(base)),
["check", ref base] => (Mode::Check, PathBuf::from(base)),
_ => {
eprintln!("usage: expand-yaml-anchors <source-dir> <dest-dir>");
std::process::exit(1);
}
};
Ok(App { mode, base })
}
fn run(&self) -> Result<(), Box<dyn Error>> {
for (source, dest) in TO_EXPAND {
let source = self.base.join(source);
let dest = self.base.join(dest);
for entry in std::fs::read_dir(&source)? {
let path = entry?.path();
if!path.is_file() || path.extension().and_then(|e| e.to_str())!= Some("yml") {
continue;
}
let dest_path = dest.join(path.file_name().unwrap());
self.expand(&path, &dest_path).with_context(|| match self.mode {
Mode::Generate => format!(
"failed to expand {} into {}",
self.path(&path),
self.path(&dest_path)
),
Mode::Check => format!(
"{} is not up to date; please run \
`x.py run src/tools/expand-yaml-anchors`.",
self.path(&dest_path)
),
})?;
}
}
Ok(())
}
fn expand(&self, source: &Path, dest: &Path) -> Result<(), Box<dyn Error>> {
let content = std::fs::read_to_string(source)
.with_context(|| format!("failed to read {}", self.path(source)))?;
let mut buf =
HEADER_MESSAGE.replace("{source}", &self.path(source).to_string().replace("\\", "/"));
let documents = YamlLoader::load_from_str(&content)
.with_context(|| format!("failed to parse {}", self.path(source)))?;
for mut document in documents.into_iter() {
document = yaml_merge_keys::merge_keys(document)
.with_context(|| format!("failed to expand {}", self.path(source)))?;
document = filter_document(document);
YamlEmitter::new(&mut buf).dump(&document).map_err(|err| WithContext {
context: "failed to serialize the expanded yaml".into(),
source: Box::new(err),
})?;
buf.push('\n');
}
match self.mode {
Mode::Check => {
let old = std::fs::read_to_string(dest)
.with_context(|| format!("failed to read {}", self.path(dest)))?;
if old!= buf {
return Err(Box::new(StrError(format!(
"{} and {} are different",
self.path(source),
self.path(dest),
))));
}
}
Mode::Generate => {
std::fs::write(dest, buf.as_bytes())
.with_context(|| format!("failed to write to {}", self.path(dest)))?;
}
}
Ok(())
}
fn path<'a>(&self, path: &'a Path) -> impl std::fmt::Display + 'a {
path.strip_prefix(&self.base).unwrap_or(path).display()
}
}
fn filter_document(document: Yaml) -> Yaml {
match document {
Yaml::Hash(map) => Yaml::Hash(
map.into_iter()
.filter(|(key, _)| {
if let Yaml::String(string) = &key { string!= REMOVE_MAP_KEY } else { true }
})
.map(|(key, value)| (filter_document(key), filter_document(value)))
.collect(),
),
Yaml::Array(vec) => Yaml::Array(vec.into_iter().map(filter_document).collect()),
other => other,
}
}
fn
|
() {
if let Err(err) = App::from_args().and_then(|app| app.run()) {
eprintln!("error: {}", err);
let mut source = err.as_ref() as &dyn Error;
while let Some(err) = source.source() {
eprintln!("caused by: {}", err);
source = err;
}
std::process::exit(1);
}
}
#[derive(Debug)]
struct StrError(String);
impl Error for StrError {}
impl std::fmt::Display for StrError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
#[derive(Debug)]
struct WithContext {
context: String,
source: Box<dyn Error>,
}
impl std::fmt::Display for WithContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.context)
}
}
impl Error for WithContext {
fn source(&self) -> Option<&(dyn Error +'static)> {
Some(self.source.as_ref())
}
}
pub(crate) trait ResultExt<T> {
fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T, Box<dyn Error>>;
}
impl<T, E: Into<Box<dyn Error>>> ResultExt<T> for Result<T, E> {
fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T, Box<dyn Error>> {
match self {
Ok(ok) => Ok(ok),
Err(err) => Err(WithContext { source: err.into(), context: f() }.into()),
}
}
}
|
main
|
identifier_name
|
mod.rs
|
#![allow(dead_code, unused_macros)]
pub mod callback;
#[macro_use]
#[path = "../../src/utils/memzeroize.rs"]
pub mod zeroize;
#[path = "../../src/utils/environment.rs"]
pub mod environment;
pub mod pool;
pub mod crypto;
pub mod did;
pub mod wallet;
pub mod ledger;
pub mod anoncreds;
pub mod types;
pub mod pairwise;
pub mod constants;
pub mod blob_storage;
pub mod non_secrets;
pub mod results;
pub mod payments;
pub mod rand_utils;
pub mod logger;
#[macro_use]
#[allow(unused_macros)]
#[path = "../../src/utils/test.rs"]
pub mod test;
pub mod timeout;
#[path = "../../src/utils/sequence.rs"]
pub mod sequence;
#[macro_use]
#[allow(unused_macros)]
#[path = "../../src/utils/ctypes.rs"]
pub mod ctypes;
#[path = "../../src/utils/inmem_wallet.rs"]
pub mod inmem_wallet;
#[path = "../../src/domain/mod.rs"]
pub mod domain;
pub fn setup() {
test::cleanup_storage();
logger::set_default_logger();
}
pub fn tear_down() {
test::cleanup_storage();
}
pub fn setup_with_wallet() -> i32 {
setup();
wallet::create_and_open_default_wallet().unwrap()
}
pub fn setup_with_plugged_wallet() -> i32 {
setup();
wallet::create_and_open_plugged_wallet().unwrap()
}
pub fn tear_down_with_wallet(wallet_handle: i32) {
wallet::close_wallet(wallet_handle).unwrap();
tear_down();
}
pub fn
|
() -> i32 {
setup();
pool::create_and_open_pool_ledger(constants::POOL).unwrap()
}
pub fn tear_down_with_pool(pool_handle: i32) {
pool::close(pool_handle).unwrap();
tear_down();
}
pub fn setup_with_wallet_and_pool() -> (i32, i32) {
let wallet_handle = setup_with_wallet();
let pool_handle = pool::create_and_open_pool_ledger(constants::POOL).unwrap();
(wallet_handle, pool_handle)
}
pub fn tear_down_with_wallet_and_pool(wallet_handle: i32, pool_handle: i32) {
pool::close(pool_handle).unwrap();
tear_down_with_wallet(wallet_handle);
}
pub fn setup_trustee() -> (i32, i32, String) {
let (wallet_handle, pool_handle) = setup_with_wallet_and_pool();
let (did, _) = did::create_and_store_my_did(wallet_handle, Some(constants::TRUSTEE_SEED)).unwrap();
(wallet_handle, pool_handle, did)
}
pub fn setup_steward() -> (i32, i32, String) {
let (wallet_handle, pool_handle) = setup_with_wallet_and_pool();
let (did, _) = did::create_and_store_my_did(wallet_handle, Some(constants::STEWARD_SEED)).unwrap();
(wallet_handle, pool_handle, did)
}
pub fn setup_did() -> (i32, String) {
let wallet_handle = setup_with_wallet();
let (did, _) = did::create_and_store_my_did(wallet_handle, None).unwrap();
(wallet_handle, did)
}
pub fn setup_new_identity() -> (i32, i32, String, String) {
let (wallet_handle, pool_handle, trustee_did) = setup_trustee();
let (my_did, my_vk) = did::create_and_store_my_did(wallet_handle, None).unwrap();
let nym = ledger::build_nym_request(&trustee_did, &my_did, Some(&my_vk), None, Some("TRUSTEE")).unwrap();
let response = ledger::sign_and_submit_request(pool_handle, wallet_handle, &trustee_did, &nym).unwrap();
pool::check_response_type(&response, types::ResponseType::REPLY);
(wallet_handle, pool_handle, my_did, my_vk)
}
|
setup_with_pool
|
identifier_name
|
mod.rs
|
#![allow(dead_code, unused_macros)]
pub mod callback;
#[macro_use]
#[path = "../../src/utils/memzeroize.rs"]
pub mod zeroize;
#[path = "../../src/utils/environment.rs"]
pub mod environment;
pub mod pool;
pub mod crypto;
pub mod did;
pub mod wallet;
pub mod ledger;
pub mod anoncreds;
pub mod types;
pub mod pairwise;
pub mod constants;
pub mod blob_storage;
pub mod non_secrets;
pub mod results;
pub mod payments;
pub mod rand_utils;
pub mod logger;
#[macro_use]
#[allow(unused_macros)]
#[path = "../../src/utils/test.rs"]
pub mod test;
pub mod timeout;
#[path = "../../src/utils/sequence.rs"]
pub mod sequence;
#[macro_use]
#[allow(unused_macros)]
#[path = "../../src/utils/ctypes.rs"]
pub mod ctypes;
#[path = "../../src/utils/inmem_wallet.rs"]
pub mod inmem_wallet;
#[path = "../../src/domain/mod.rs"]
pub mod domain;
pub fn setup() {
test::cleanup_storage();
logger::set_default_logger();
}
pub fn tear_down() {
test::cleanup_storage();
}
pub fn setup_with_wallet() -> i32 {
setup();
wallet::create_and_open_default_wallet().unwrap()
}
pub fn setup_with_plugged_wallet() -> i32 {
setup();
wallet::create_and_open_plugged_wallet().unwrap()
}
pub fn tear_down_with_wallet(wallet_handle: i32) {
wallet::close_wallet(wallet_handle).unwrap();
tear_down();
}
pub fn setup_with_pool() -> i32 {
setup();
pool::create_and_open_pool_ledger(constants::POOL).unwrap()
}
pub fn tear_down_with_pool(pool_handle: i32) {
pool::close(pool_handle).unwrap();
tear_down();
}
pub fn setup_with_wallet_and_pool() -> (i32, i32) {
let wallet_handle = setup_with_wallet();
let pool_handle = pool::create_and_open_pool_ledger(constants::POOL).unwrap();
(wallet_handle, pool_handle)
}
pub fn tear_down_with_wallet_and_pool(wallet_handle: i32, pool_handle: i32) {
pool::close(pool_handle).unwrap();
tear_down_with_wallet(wallet_handle);
}
pub fn setup_trustee() -> (i32, i32, String) {
let (wallet_handle, pool_handle) = setup_with_wallet_and_pool();
let (did, _) = did::create_and_store_my_did(wallet_handle, Some(constants::TRUSTEE_SEED)).unwrap();
(wallet_handle, pool_handle, did)
}
pub fn setup_steward() -> (i32, i32, String) {
let (wallet_handle, pool_handle) = setup_with_wallet_and_pool();
let (did, _) = did::create_and_store_my_did(wallet_handle, Some(constants::STEWARD_SEED)).unwrap();
(wallet_handle, pool_handle, did)
}
pub fn setup_did() -> (i32, String) {
let wallet_handle = setup_with_wallet();
let (did, _) = did::create_and_store_my_did(wallet_handle, None).unwrap();
(wallet_handle, did)
}
pub fn setup_new_identity() -> (i32, i32, String, String) {
let (wallet_handle, pool_handle, trustee_did) = setup_trustee();
let (my_did, my_vk) = did::create_and_store_my_did(wallet_handle, None).unwrap();
let nym = ledger::build_nym_request(&trustee_did, &my_did, Some(&my_vk), None, Some("TRUSTEE")).unwrap();
let response = ledger::sign_and_submit_request(pool_handle, wallet_handle, &trustee_did, &nym).unwrap();
pool::check_response_type(&response, types::ResponseType::REPLY);
(wallet_handle, pool_handle, my_did, my_vk)
|
}
|
random_line_split
|
|
mod.rs
|
#![allow(dead_code, unused_macros)]
pub mod callback;
#[macro_use]
#[path = "../../src/utils/memzeroize.rs"]
pub mod zeroize;
#[path = "../../src/utils/environment.rs"]
pub mod environment;
pub mod pool;
pub mod crypto;
pub mod did;
pub mod wallet;
pub mod ledger;
pub mod anoncreds;
pub mod types;
pub mod pairwise;
pub mod constants;
pub mod blob_storage;
pub mod non_secrets;
pub mod results;
pub mod payments;
pub mod rand_utils;
pub mod logger;
#[macro_use]
#[allow(unused_macros)]
#[path = "../../src/utils/test.rs"]
pub mod test;
pub mod timeout;
#[path = "../../src/utils/sequence.rs"]
pub mod sequence;
#[macro_use]
#[allow(unused_macros)]
#[path = "../../src/utils/ctypes.rs"]
pub mod ctypes;
#[path = "../../src/utils/inmem_wallet.rs"]
pub mod inmem_wallet;
#[path = "../../src/domain/mod.rs"]
pub mod domain;
pub fn setup()
|
pub fn tear_down() {
test::cleanup_storage();
}
pub fn setup_with_wallet() -> i32 {
setup();
wallet::create_and_open_default_wallet().unwrap()
}
pub fn setup_with_plugged_wallet() -> i32 {
setup();
wallet::create_and_open_plugged_wallet().unwrap()
}
pub fn tear_down_with_wallet(wallet_handle: i32) {
wallet::close_wallet(wallet_handle).unwrap();
tear_down();
}
pub fn setup_with_pool() -> i32 {
setup();
pool::create_and_open_pool_ledger(constants::POOL).unwrap()
}
pub fn tear_down_with_pool(pool_handle: i32) {
pool::close(pool_handle).unwrap();
tear_down();
}
pub fn setup_with_wallet_and_pool() -> (i32, i32) {
let wallet_handle = setup_with_wallet();
let pool_handle = pool::create_and_open_pool_ledger(constants::POOL).unwrap();
(wallet_handle, pool_handle)
}
pub fn tear_down_with_wallet_and_pool(wallet_handle: i32, pool_handle: i32) {
pool::close(pool_handle).unwrap();
tear_down_with_wallet(wallet_handle);
}
pub fn setup_trustee() -> (i32, i32, String) {
let (wallet_handle, pool_handle) = setup_with_wallet_and_pool();
let (did, _) = did::create_and_store_my_did(wallet_handle, Some(constants::TRUSTEE_SEED)).unwrap();
(wallet_handle, pool_handle, did)
}
pub fn setup_steward() -> (i32, i32, String) {
let (wallet_handle, pool_handle) = setup_with_wallet_and_pool();
let (did, _) = did::create_and_store_my_did(wallet_handle, Some(constants::STEWARD_SEED)).unwrap();
(wallet_handle, pool_handle, did)
}
pub fn setup_did() -> (i32, String) {
let wallet_handle = setup_with_wallet();
let (did, _) = did::create_and_store_my_did(wallet_handle, None).unwrap();
(wallet_handle, did)
}
pub fn setup_new_identity() -> (i32, i32, String, String) {
let (wallet_handle, pool_handle, trustee_did) = setup_trustee();
let (my_did, my_vk) = did::create_and_store_my_did(wallet_handle, None).unwrap();
let nym = ledger::build_nym_request(&trustee_did, &my_did, Some(&my_vk), None, Some("TRUSTEE")).unwrap();
let response = ledger::sign_and_submit_request(pool_handle, wallet_handle, &trustee_did, &nym).unwrap();
pool::check_response_type(&response, types::ResponseType::REPLY);
(wallet_handle, pool_handle, my_did, my_vk)
}
|
{
test::cleanup_storage();
logger::set_default_logger();
}
|
identifier_body
|
cstore.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.
// The crate store - a central repo for information collected about external
// crates and libraries
use metadata::cstore;
use metadata::decoder;
use std::hashmap::HashMap;
use extra;
use syntax::ast;
use syntax::parse::token::ident_interner;
// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = @mut HashMap<ast::CrateNum, ast::CrateNum>;
pub struct crate_metadata {
name: @str,
data: @~[u8],
cnum_map: cnum_map,
cnum: ast::CrateNum
}
#[deriving(Eq)]
pub enum LinkagePreference {
RequireDynamic,
RequireStatic,
}
#[deriving(Eq, FromPrimitive)]
pub enum NativeLibaryKind {
NativeStatic, // native static library (.a archive)
NativeFramework, // OSX-specific
NativeUnknown, // default way to specify a dynamic library
}
// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
#[deriving(Eq)]
pub struct CrateSource {
dylib: Option<Path>,
rlib: Option<Path>,
cnum: ast::CrateNum,
}
pub struct CStore {
priv metas: HashMap <ast::CrateNum, @crate_metadata>,
priv extern_mod_crate_map: extern_mod_crate_map,
priv used_crate_sources: ~[CrateSource],
priv used_libraries: ~[(~str, NativeLibaryKind)],
priv used_link_args: ~[~str],
intr: @ident_interner
}
// Map from NodeId's of local extern mod statements to crate numbers
type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>;
pub fn mk_cstore(intr: @ident_interner) -> CStore {
return CStore {
metas: HashMap::new(),
extern_mod_crate_map: HashMap::new(),
used_crate_sources: ~[],
used_libraries: ~[],
used_link_args: ~[],
intr: intr
|
-> @crate_metadata {
return *cstore.metas.get(&cnum);
}
pub fn get_crate_hash(cstore: &CStore, cnum: ast::CrateNum) -> @str {
let cdata = get_crate_data(cstore, cnum);
decoder::get_crate_hash(cdata.data)
}
pub fn get_crate_vers(cstore: &CStore, cnum: ast::CrateNum) -> @str {
let cdata = get_crate_data(cstore, cnum);
decoder::get_crate_vers(cdata.data)
}
pub fn set_crate_data(cstore: &mut CStore,
cnum: ast::CrateNum,
data: @crate_metadata) {
cstore.metas.insert(cnum, data);
}
pub fn have_crate_data(cstore: &CStore, cnum: ast::CrateNum) -> bool {
cstore.metas.contains_key(&cnum)
}
pub fn iter_crate_data(cstore: &CStore, i: |ast::CrateNum, @crate_metadata|) {
for (&k, &v) in cstore.metas.iter() {
i(k, v);
}
}
pub fn add_used_crate_source(cstore: &mut CStore, src: CrateSource) {
if!cstore.used_crate_sources.contains(&src) {
cstore.used_crate_sources.push(src);
}
}
pub fn get_used_crate_sources<'a>(cstore: &'a CStore) -> &'a [CrateSource] {
cstore.used_crate_sources.as_slice()
}
pub fn get_used_crates(cstore: &CStore, prefer: LinkagePreference)
-> ~[(ast::CrateNum, Option<Path>)]
{
let mut ret = ~[];
for src in cstore.used_crate_sources.iter() {
ret.push((src.cnum, match prefer {
RequireDynamic => src.dylib.clone(),
RequireStatic => src.rlib.clone(),
}));
}
return ret;
}
pub fn add_used_library(cstore: &mut CStore,
lib: ~str, kind: NativeLibaryKind) -> bool {
assert!(!lib.is_empty());
if cstore.used_libraries.iter().any(|&(ref x, _)| x == &lib) { return false; }
cstore.used_libraries.push((lib, kind));
true
}
pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [(~str, NativeLibaryKind)] {
cstore.used_libraries.as_slice()
}
pub fn add_used_link_args(cstore: &mut CStore, args: &str) {
for s in args.split(' ') {
cstore.used_link_args.push(s.to_owned());
}
}
pub fn get_used_link_args<'a>(cstore: &'a CStore) -> &'a [~str] {
cstore.used_link_args.as_slice()
}
pub fn add_extern_mod_stmt_cnum(cstore: &mut CStore,
emod_id: ast::NodeId,
cnum: ast::CrateNum) {
cstore.extern_mod_crate_map.insert(emod_id, cnum);
}
pub fn find_extern_mod_stmt_cnum(cstore: &CStore,
emod_id: ast::NodeId)
-> Option<ast::CrateNum> {
cstore.extern_mod_crate_map.find(&emod_id).map(|x| *x)
}
#[deriving(Clone)]
struct crate_hash {
name: @str,
vers: @str,
hash: @str,
}
// returns hashes of crates directly used by this crate. Hashes are sorted by
// (crate name, crate version, crate hash) in lexicographic order (not semver)
pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] {
let mut result = ~[];
for (_, &cnum) in cstore.extern_mod_crate_map.iter() {
let cdata = cstore::get_crate_data(cstore, cnum);
let hash = decoder::get_crate_hash(cdata.data);
let vers = decoder::get_crate_vers(cdata.data);
debug!("Add hash[{}]: {} {}", cdata.name, vers, hash);
result.push(crate_hash {
name: cdata.name,
vers: vers,
hash: hash
});
}
let sorted = extra::sort::merge_sort(result, |a, b| {
(a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash)
});
debug!("sorted:");
for x in sorted.iter() {
debug!(" hash[{}]: {}", x.name, x.hash);
}
sorted.map(|ch| ch.hash)
}
|
};
}
pub fn get_crate_data(cstore: &CStore, cnum: ast::CrateNum)
|
random_line_split
|
cstore.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.
// The crate store - a central repo for information collected about external
// crates and libraries
use metadata::cstore;
use metadata::decoder;
use std::hashmap::HashMap;
use extra;
use syntax::ast;
use syntax::parse::token::ident_interner;
// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = @mut HashMap<ast::CrateNum, ast::CrateNum>;
pub struct crate_metadata {
name: @str,
data: @~[u8],
cnum_map: cnum_map,
cnum: ast::CrateNum
}
#[deriving(Eq)]
pub enum LinkagePreference {
RequireDynamic,
RequireStatic,
}
#[deriving(Eq, FromPrimitive)]
pub enum NativeLibaryKind {
NativeStatic, // native static library (.a archive)
NativeFramework, // OSX-specific
NativeUnknown, // default way to specify a dynamic library
}
// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
#[deriving(Eq)]
pub struct CrateSource {
dylib: Option<Path>,
rlib: Option<Path>,
cnum: ast::CrateNum,
}
pub struct CStore {
priv metas: HashMap <ast::CrateNum, @crate_metadata>,
priv extern_mod_crate_map: extern_mod_crate_map,
priv used_crate_sources: ~[CrateSource],
priv used_libraries: ~[(~str, NativeLibaryKind)],
priv used_link_args: ~[~str],
intr: @ident_interner
}
// Map from NodeId's of local extern mod statements to crate numbers
type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>;
pub fn mk_cstore(intr: @ident_interner) -> CStore {
return CStore {
metas: HashMap::new(),
extern_mod_crate_map: HashMap::new(),
used_crate_sources: ~[],
used_libraries: ~[],
used_link_args: ~[],
intr: intr
};
}
pub fn get_crate_data(cstore: &CStore, cnum: ast::CrateNum)
-> @crate_metadata {
return *cstore.metas.get(&cnum);
}
pub fn get_crate_hash(cstore: &CStore, cnum: ast::CrateNum) -> @str {
let cdata = get_crate_data(cstore, cnum);
decoder::get_crate_hash(cdata.data)
}
pub fn get_crate_vers(cstore: &CStore, cnum: ast::CrateNum) -> @str {
let cdata = get_crate_data(cstore, cnum);
decoder::get_crate_vers(cdata.data)
}
pub fn set_crate_data(cstore: &mut CStore,
cnum: ast::CrateNum,
data: @crate_metadata) {
cstore.metas.insert(cnum, data);
}
pub fn have_crate_data(cstore: &CStore, cnum: ast::CrateNum) -> bool {
cstore.metas.contains_key(&cnum)
}
pub fn iter_crate_data(cstore: &CStore, i: |ast::CrateNum, @crate_metadata|) {
for (&k, &v) in cstore.metas.iter() {
i(k, v);
}
}
pub fn add_used_crate_source(cstore: &mut CStore, src: CrateSource) {
if!cstore.used_crate_sources.contains(&src) {
cstore.used_crate_sources.push(src);
}
}
pub fn
|
<'a>(cstore: &'a CStore) -> &'a [CrateSource] {
cstore.used_crate_sources.as_slice()
}
pub fn get_used_crates(cstore: &CStore, prefer: LinkagePreference)
-> ~[(ast::CrateNum, Option<Path>)]
{
let mut ret = ~[];
for src in cstore.used_crate_sources.iter() {
ret.push((src.cnum, match prefer {
RequireDynamic => src.dylib.clone(),
RequireStatic => src.rlib.clone(),
}));
}
return ret;
}
pub fn add_used_library(cstore: &mut CStore,
lib: ~str, kind: NativeLibaryKind) -> bool {
assert!(!lib.is_empty());
if cstore.used_libraries.iter().any(|&(ref x, _)| x == &lib) { return false; }
cstore.used_libraries.push((lib, kind));
true
}
pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [(~str, NativeLibaryKind)] {
cstore.used_libraries.as_slice()
}
pub fn add_used_link_args(cstore: &mut CStore, args: &str) {
for s in args.split(' ') {
cstore.used_link_args.push(s.to_owned());
}
}
pub fn get_used_link_args<'a>(cstore: &'a CStore) -> &'a [~str] {
cstore.used_link_args.as_slice()
}
pub fn add_extern_mod_stmt_cnum(cstore: &mut CStore,
emod_id: ast::NodeId,
cnum: ast::CrateNum) {
cstore.extern_mod_crate_map.insert(emod_id, cnum);
}
pub fn find_extern_mod_stmt_cnum(cstore: &CStore,
emod_id: ast::NodeId)
-> Option<ast::CrateNum> {
cstore.extern_mod_crate_map.find(&emod_id).map(|x| *x)
}
#[deriving(Clone)]
struct crate_hash {
name: @str,
vers: @str,
hash: @str,
}
// returns hashes of crates directly used by this crate. Hashes are sorted by
// (crate name, crate version, crate hash) in lexicographic order (not semver)
pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] {
let mut result = ~[];
for (_, &cnum) in cstore.extern_mod_crate_map.iter() {
let cdata = cstore::get_crate_data(cstore, cnum);
let hash = decoder::get_crate_hash(cdata.data);
let vers = decoder::get_crate_vers(cdata.data);
debug!("Add hash[{}]: {} {}", cdata.name, vers, hash);
result.push(crate_hash {
name: cdata.name,
vers: vers,
hash: hash
});
}
let sorted = extra::sort::merge_sort(result, |a, b| {
(a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash)
});
debug!("sorted:");
for x in sorted.iter() {
debug!(" hash[{}]: {}", x.name, x.hash);
}
sorted.map(|ch| ch.hash)
}
|
get_used_crate_sources
|
identifier_name
|
relay.rs
|
// Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! This module handle all connections that are not managed by the routing table.
//!
//! As such the relay module handles messages that need to flow in or out of the SAFE network.
//! These messages include bootstrap actions by starting nodes or relay messages for clients.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use time::{SteadyTime};
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use NameType;
use sodiumoxide::crypto::sign;
const MAX_RELAY : usize = 100;
/// The relay map is used to maintain a list of contacts for whom
/// we are relaying messages, when we are ourselves connected to the network.
/// These have to identify as Client(sign::PublicKey)
pub struct RelayMap {
relay_map: BTreeMap<Address, (PublicId, BTreeSet<Endpoint>)>,
lookup_map: HashMap<Endpoint, Address>,
// FIXME : we don't want to store a value; but LRUcache can clear itself out
// however, we want the explicit timestamp stored and clear it at routing,
// to drop the connection on clearing; for now CM will just keep all these connections
unknown_connections: HashMap<Endpoint, SteadyTime>,
our_name: NameType,
}
impl RelayMap {
/// This creates a new RelayMap.
pub fn new(our_id: &Id) -> RelayMap {
RelayMap {
relay_map: BTreeMap::new(),
lookup_map: HashMap::new(),
unknown_connections: HashMap::new(),
our_name: our_id.name(),
}
}
/// Adds an IP Node info to the relay map if the relay map has open
/// slots. This returns true if Info was addded.
/// Returns true is the endpoint is newly added, or was already present.
/// Returns false if the threshold was reached or name is our name.
/// Returns false if the endpoint is already assigned to a different name.
pub fn add_client(&mut self, relay_info: PublicId, relay_endpoint: Endpoint) -> bool {
// always reject our own id
if self.our_name == relay_info.name() {
return false;
}
// impose limit on number of relay nodes active
if!self.relay_map.contains_key(&Address::Client(relay_info.signing_public_key()))
&& self.relay_map.len() >= MAX_RELAY {
return false;
}
if self.lookup_map.contains_key(&relay_endpoint) {
return false; }
// only add Client
self.lookup_map.entry(relay_endpoint.clone())
.or_insert(Address::Client(relay_info.signing_public_key()));
let new_set = || { (relay_info.clone(), BTreeSet::<Endpoint>::new()) };
self.relay_map.entry(Address::Client(relay_info.signing_public_key()))
.or_insert_with(new_set).1
.insert(relay_endpoint);
true
}
/// This removes the provided endpoint and returns a NameType if this endpoint
/// was the last endpoint assocoiated with this Name; otherwise returns None.
pub fn drop_endpoint(&mut self, endpoint_to_drop: &Endpoint) -> Option<Address> {
let mut old_entry = match self.lookup_map.remove(endpoint_to_drop) {
Some(name) => {
match self.relay_map.remove(&name) {
Some(entry) => Some((name, entry)),
None => None
}
},
None => None
};
let new_entry = match old_entry {
Some((ref name, (ref public_id, ref mut endpoints))) => {
endpoints.remove(endpoint_to_drop);
Some((name, (public_id, endpoints)))
},
None => None
};
match new_entry {
Some((name, (public_id, endpoints))) => {
if endpoints.is_empty() {
println!("Connection {:?} lost for relayed node {:?}", endpoint_to_drop, name);
Some(name.clone())
} else {
self.relay_map.insert(name.clone(), (public_id.clone(), endpoints.clone()));
None
}
},
None => None
}
}
/// Returns true if we keep relay endpoints for given name.
// FIXME(ben) this needs to be used 16/07/2015
#[allow(dead_code)]
pub fn contains_relay_for(&self, relay_name: &Address) -> bool {
self.relay_map.contains_key(relay_name)
}
/// Returns true if we already have a name associated with this endpoint.
pub fn contains_endpoint(&self, relay_endpoint: &Endpoint) -> bool {
self.lookup_map.contains_key(relay_endpoint)
}
/// Returns Option<NameType> if an endpoint is found
pub fn lookup_endpoint(&self, relay_endpoint: &Endpoint) -> Option<Address> {
match self.lookup_map.get(relay_endpoint) {
Some(name) => Some(name.clone()),
None => None
}
}
/// This returns a pair of the stored PublicId and a BTreeSet of the stored Endpoints.
pub fn get_endpoints(&self, relay_name: &Address) -> Option<&(PublicId, BTreeSet<Endpoint>)> {
self.relay_map.get(relay_name)
}
/// On unknown NewConnection, register the endpoint we are connected to.
pub fn register_unknown_connection(&mut self, endpoint: Endpoint) {
// TODO: later prune and drop old unknown connections
self.unknown_connections.insert(endpoint, SteadyTime::now());
}
/// When we receive an "I am" message on this connection, drop it
pub fn remove_unknown_connection(&mut self, endpoint: &Endpoint) -> Option<Endpoint> {
match self.unknown_connections.remove(endpoint) {
Some(_) => Some(endpoint.clone()), // return the endpoint
None => None
}
}
/// Returns true if the endpoint has been registered as an unknown NewConnection
pub fn lookup_unknown_connection(&self, endpoint: &Endpoint) -> bool {
self.unknown_connections.contains_key(endpoint)
}
}
#[cfg(test)]
mod test {
use super::*;
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use std::net::SocketAddr;
use std::str::FromStr;
use rand::random;
fn generate_random_endpoint() -> Endpoint {
Endpoint::Tcp(SocketAddr::from_str(&format!("127.0.0.1:{}", random::<u16>())).unwrap())
}
fn drop_ip_node(relay_map: &mut RelayMap, ip_node_to_drop: &Address) {
match relay_map.relay_map.get(&ip_node_to_drop) {
Some(relay_entry) => {
for endpoint in relay_entry.1.iter() {
relay_map.lookup_map.remove(endpoint);
}
},
None => return
};
relay_map.relay_map.remove(ip_node_to_drop);
}
#[test]
fn add() {
let our_id : Id = Id::new();
let our_public_id = PublicId::new(&our_id);
let mut relay_map = RelayMap::new(&our_id);
assert_eq!(false, relay_map.add_client(our_public_id.clone(), generate_random_endpoint()));
assert_eq!(0, relay_map.relay_map.len());
assert_eq!(0, relay_map.lookup_map.len());
while relay_map.relay_map.len() < super::MAX_RELAY {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
assert_eq!(false, relay_map.add_client(PublicId::new(&Id::new()),
generate_random_endpoint()));
}
#[test]
fn drop() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
drop_ip_node(&mut relay_map, &test_id);
assert_eq!(false, relay_map.contains_relay_for(&test_id));
assert_eq!(false, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(None, relay_map.get_endpoints(&test_id));
}
#[test]
fn add_conflicting_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
let test_conflicting_public_id = PublicId::new(&Id::new());
let test_conflicting_id = Address::Client(test_conflicting_public_id.signing_public_key());
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(false, relay_map.add_client(test_conflicting_public_id.clone(),
test_endpoint.clone()));
assert_eq!(false, relay_map.contains_relay_for(&test_conflicting_id))
}
#[test]
fn add_multiple_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
assert!(super::MAX_RELAY - 1 > 0);
// ensure relay_map is all but full, so multiple endpoints are not counted as different
// relays.
while relay_map.relay_map.len() < super::MAX_RELAY - 1 {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let mut test_endpoint_1 = generate_random_endpoint();
let mut test_endpoint_2 = generate_random_endpoint();
loop {
if!relay_map.contains_endpoint(&test_endpoint_1) { break; }
test_endpoint_1 = generate_random_endpoint(); };
loop {
if!relay_map.contains_endpoint(&test_endpoint_2)
|
test_endpoint_2 = generate_random_endpoint(); };
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint_1));
assert_eq!(false, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_2.clone()));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_1));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_2));
}
// TODO: add test for drop_endpoint
// TODO: add tests for unknown_connections
}
|
{ break; }
|
conditional_block
|
relay.rs
|
// Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! This module handle all connections that are not managed by the routing table.
//!
//! As such the relay module handles messages that need to flow in or out of the SAFE network.
//! These messages include bootstrap actions by starting nodes or relay messages for clients.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use time::{SteadyTime};
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use NameType;
use sodiumoxide::crypto::sign;
const MAX_RELAY : usize = 100;
/// The relay map is used to maintain a list of contacts for whom
/// we are relaying messages, when we are ourselves connected to the network.
/// These have to identify as Client(sign::PublicKey)
pub struct RelayMap {
relay_map: BTreeMap<Address, (PublicId, BTreeSet<Endpoint>)>,
lookup_map: HashMap<Endpoint, Address>,
// FIXME : we don't want to store a value; but LRUcache can clear itself out
// however, we want the explicit timestamp stored and clear it at routing,
// to drop the connection on clearing; for now CM will just keep all these connections
unknown_connections: HashMap<Endpoint, SteadyTime>,
our_name: NameType,
}
impl RelayMap {
/// This creates a new RelayMap.
pub fn
|
(our_id: &Id) -> RelayMap {
RelayMap {
relay_map: BTreeMap::new(),
lookup_map: HashMap::new(),
unknown_connections: HashMap::new(),
our_name: our_id.name(),
}
}
/// Adds an IP Node info to the relay map if the relay map has open
/// slots. This returns true if Info was addded.
/// Returns true is the endpoint is newly added, or was already present.
/// Returns false if the threshold was reached or name is our name.
/// Returns false if the endpoint is already assigned to a different name.
pub fn add_client(&mut self, relay_info: PublicId, relay_endpoint: Endpoint) -> bool {
// always reject our own id
if self.our_name == relay_info.name() {
return false;
}
// impose limit on number of relay nodes active
if!self.relay_map.contains_key(&Address::Client(relay_info.signing_public_key()))
&& self.relay_map.len() >= MAX_RELAY {
return false;
}
if self.lookup_map.contains_key(&relay_endpoint) {
return false; }
// only add Client
self.lookup_map.entry(relay_endpoint.clone())
.or_insert(Address::Client(relay_info.signing_public_key()));
let new_set = || { (relay_info.clone(), BTreeSet::<Endpoint>::new()) };
self.relay_map.entry(Address::Client(relay_info.signing_public_key()))
.or_insert_with(new_set).1
.insert(relay_endpoint);
true
}
/// This removes the provided endpoint and returns a NameType if this endpoint
/// was the last endpoint assocoiated with this Name; otherwise returns None.
pub fn drop_endpoint(&mut self, endpoint_to_drop: &Endpoint) -> Option<Address> {
let mut old_entry = match self.lookup_map.remove(endpoint_to_drop) {
Some(name) => {
match self.relay_map.remove(&name) {
Some(entry) => Some((name, entry)),
None => None
}
},
None => None
};
let new_entry = match old_entry {
Some((ref name, (ref public_id, ref mut endpoints))) => {
endpoints.remove(endpoint_to_drop);
Some((name, (public_id, endpoints)))
},
None => None
};
match new_entry {
Some((name, (public_id, endpoints))) => {
if endpoints.is_empty() {
println!("Connection {:?} lost for relayed node {:?}", endpoint_to_drop, name);
Some(name.clone())
} else {
self.relay_map.insert(name.clone(), (public_id.clone(), endpoints.clone()));
None
}
},
None => None
}
}
/// Returns true if we keep relay endpoints for given name.
// FIXME(ben) this needs to be used 16/07/2015
#[allow(dead_code)]
pub fn contains_relay_for(&self, relay_name: &Address) -> bool {
self.relay_map.contains_key(relay_name)
}
/// Returns true if we already have a name associated with this endpoint.
pub fn contains_endpoint(&self, relay_endpoint: &Endpoint) -> bool {
self.lookup_map.contains_key(relay_endpoint)
}
/// Returns Option<NameType> if an endpoint is found
pub fn lookup_endpoint(&self, relay_endpoint: &Endpoint) -> Option<Address> {
match self.lookup_map.get(relay_endpoint) {
Some(name) => Some(name.clone()),
None => None
}
}
/// This returns a pair of the stored PublicId and a BTreeSet of the stored Endpoints.
pub fn get_endpoints(&self, relay_name: &Address) -> Option<&(PublicId, BTreeSet<Endpoint>)> {
self.relay_map.get(relay_name)
}
/// On unknown NewConnection, register the endpoint we are connected to.
pub fn register_unknown_connection(&mut self, endpoint: Endpoint) {
// TODO: later prune and drop old unknown connections
self.unknown_connections.insert(endpoint, SteadyTime::now());
}
/// When we receive an "I am" message on this connection, drop it
pub fn remove_unknown_connection(&mut self, endpoint: &Endpoint) -> Option<Endpoint> {
match self.unknown_connections.remove(endpoint) {
Some(_) => Some(endpoint.clone()), // return the endpoint
None => None
}
}
/// Returns true if the endpoint has been registered as an unknown NewConnection
pub fn lookup_unknown_connection(&self, endpoint: &Endpoint) -> bool {
self.unknown_connections.contains_key(endpoint)
}
}
#[cfg(test)]
mod test {
use super::*;
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use std::net::SocketAddr;
use std::str::FromStr;
use rand::random;
fn generate_random_endpoint() -> Endpoint {
Endpoint::Tcp(SocketAddr::from_str(&format!("127.0.0.1:{}", random::<u16>())).unwrap())
}
fn drop_ip_node(relay_map: &mut RelayMap, ip_node_to_drop: &Address) {
match relay_map.relay_map.get(&ip_node_to_drop) {
Some(relay_entry) => {
for endpoint in relay_entry.1.iter() {
relay_map.lookup_map.remove(endpoint);
}
},
None => return
};
relay_map.relay_map.remove(ip_node_to_drop);
}
#[test]
fn add() {
let our_id : Id = Id::new();
let our_public_id = PublicId::new(&our_id);
let mut relay_map = RelayMap::new(&our_id);
assert_eq!(false, relay_map.add_client(our_public_id.clone(), generate_random_endpoint()));
assert_eq!(0, relay_map.relay_map.len());
assert_eq!(0, relay_map.lookup_map.len());
while relay_map.relay_map.len() < super::MAX_RELAY {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
assert_eq!(false, relay_map.add_client(PublicId::new(&Id::new()),
generate_random_endpoint()));
}
#[test]
fn drop() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
drop_ip_node(&mut relay_map, &test_id);
assert_eq!(false, relay_map.contains_relay_for(&test_id));
assert_eq!(false, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(None, relay_map.get_endpoints(&test_id));
}
#[test]
fn add_conflicting_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
let test_conflicting_public_id = PublicId::new(&Id::new());
let test_conflicting_id = Address::Client(test_conflicting_public_id.signing_public_key());
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(false, relay_map.add_client(test_conflicting_public_id.clone(),
test_endpoint.clone()));
assert_eq!(false, relay_map.contains_relay_for(&test_conflicting_id))
}
#[test]
fn add_multiple_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
assert!(super::MAX_RELAY - 1 > 0);
// ensure relay_map is all but full, so multiple endpoints are not counted as different
// relays.
while relay_map.relay_map.len() < super::MAX_RELAY - 1 {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let mut test_endpoint_1 = generate_random_endpoint();
let mut test_endpoint_2 = generate_random_endpoint();
loop {
if!relay_map.contains_endpoint(&test_endpoint_1) { break; }
test_endpoint_1 = generate_random_endpoint(); };
loop {
if!relay_map.contains_endpoint(&test_endpoint_2) { break; }
test_endpoint_2 = generate_random_endpoint(); };
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint_1));
assert_eq!(false, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_2.clone()));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_1));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_2));
}
// TODO: add test for drop_endpoint
// TODO: add tests for unknown_connections
}
|
new
|
identifier_name
|
relay.rs
|
// Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! This module handle all connections that are not managed by the routing table.
//!
//! As such the relay module handles messages that need to flow in or out of the SAFE network.
//! These messages include bootstrap actions by starting nodes or relay messages for clients.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use time::{SteadyTime};
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use NameType;
use sodiumoxide::crypto::sign;
const MAX_RELAY : usize = 100;
/// The relay map is used to maintain a list of contacts for whom
/// we are relaying messages, when we are ourselves connected to the network.
/// These have to identify as Client(sign::PublicKey)
pub struct RelayMap {
relay_map: BTreeMap<Address, (PublicId, BTreeSet<Endpoint>)>,
lookup_map: HashMap<Endpoint, Address>,
// FIXME : we don't want to store a value; but LRUcache can clear itself out
// however, we want the explicit timestamp stored and clear it at routing,
// to drop the connection on clearing; for now CM will just keep all these connections
unknown_connections: HashMap<Endpoint, SteadyTime>,
our_name: NameType,
}
impl RelayMap {
/// This creates a new RelayMap.
pub fn new(our_id: &Id) -> RelayMap {
RelayMap {
relay_map: BTreeMap::new(),
lookup_map: HashMap::new(),
unknown_connections: HashMap::new(),
our_name: our_id.name(),
}
}
/// Adds an IP Node info to the relay map if the relay map has open
/// slots. This returns true if Info was addded.
/// Returns true is the endpoint is newly added, or was already present.
/// Returns false if the threshold was reached or name is our name.
|
/// Returns false if the endpoint is already assigned to a different name.
pub fn add_client(&mut self, relay_info: PublicId, relay_endpoint: Endpoint) -> bool {
// always reject our own id
if self.our_name == relay_info.name() {
return false;
}
// impose limit on number of relay nodes active
if!self.relay_map.contains_key(&Address::Client(relay_info.signing_public_key()))
&& self.relay_map.len() >= MAX_RELAY {
return false;
}
if self.lookup_map.contains_key(&relay_endpoint) {
return false; }
// only add Client
self.lookup_map.entry(relay_endpoint.clone())
.or_insert(Address::Client(relay_info.signing_public_key()));
let new_set = || { (relay_info.clone(), BTreeSet::<Endpoint>::new()) };
self.relay_map.entry(Address::Client(relay_info.signing_public_key()))
.or_insert_with(new_set).1
.insert(relay_endpoint);
true
}
/// This removes the provided endpoint and returns a NameType if this endpoint
/// was the last endpoint assocoiated with this Name; otherwise returns None.
pub fn drop_endpoint(&mut self, endpoint_to_drop: &Endpoint) -> Option<Address> {
let mut old_entry = match self.lookup_map.remove(endpoint_to_drop) {
Some(name) => {
match self.relay_map.remove(&name) {
Some(entry) => Some((name, entry)),
None => None
}
},
None => None
};
let new_entry = match old_entry {
Some((ref name, (ref public_id, ref mut endpoints))) => {
endpoints.remove(endpoint_to_drop);
Some((name, (public_id, endpoints)))
},
None => None
};
match new_entry {
Some((name, (public_id, endpoints))) => {
if endpoints.is_empty() {
println!("Connection {:?} lost for relayed node {:?}", endpoint_to_drop, name);
Some(name.clone())
} else {
self.relay_map.insert(name.clone(), (public_id.clone(), endpoints.clone()));
None
}
},
None => None
}
}
/// Returns true if we keep relay endpoints for given name.
// FIXME(ben) this needs to be used 16/07/2015
#[allow(dead_code)]
pub fn contains_relay_for(&self, relay_name: &Address) -> bool {
self.relay_map.contains_key(relay_name)
}
/// Returns true if we already have a name associated with this endpoint.
pub fn contains_endpoint(&self, relay_endpoint: &Endpoint) -> bool {
self.lookup_map.contains_key(relay_endpoint)
}
/// Returns Option<NameType> if an endpoint is found
pub fn lookup_endpoint(&self, relay_endpoint: &Endpoint) -> Option<Address> {
match self.lookup_map.get(relay_endpoint) {
Some(name) => Some(name.clone()),
None => None
}
}
/// This returns a pair of the stored PublicId and a BTreeSet of the stored Endpoints.
pub fn get_endpoints(&self, relay_name: &Address) -> Option<&(PublicId, BTreeSet<Endpoint>)> {
self.relay_map.get(relay_name)
}
/// On unknown NewConnection, register the endpoint we are connected to.
pub fn register_unknown_connection(&mut self, endpoint: Endpoint) {
// TODO: later prune and drop old unknown connections
self.unknown_connections.insert(endpoint, SteadyTime::now());
}
/// When we receive an "I am" message on this connection, drop it
pub fn remove_unknown_connection(&mut self, endpoint: &Endpoint) -> Option<Endpoint> {
match self.unknown_connections.remove(endpoint) {
Some(_) => Some(endpoint.clone()), // return the endpoint
None => None
}
}
/// Returns true if the endpoint has been registered as an unknown NewConnection
pub fn lookup_unknown_connection(&self, endpoint: &Endpoint) -> bool {
self.unknown_connections.contains_key(endpoint)
}
}
#[cfg(test)]
mod test {
use super::*;
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use std::net::SocketAddr;
use std::str::FromStr;
use rand::random;
fn generate_random_endpoint() -> Endpoint {
Endpoint::Tcp(SocketAddr::from_str(&format!("127.0.0.1:{}", random::<u16>())).unwrap())
}
fn drop_ip_node(relay_map: &mut RelayMap, ip_node_to_drop: &Address) {
match relay_map.relay_map.get(&ip_node_to_drop) {
Some(relay_entry) => {
for endpoint in relay_entry.1.iter() {
relay_map.lookup_map.remove(endpoint);
}
},
None => return
};
relay_map.relay_map.remove(ip_node_to_drop);
}
#[test]
fn add() {
let our_id : Id = Id::new();
let our_public_id = PublicId::new(&our_id);
let mut relay_map = RelayMap::new(&our_id);
assert_eq!(false, relay_map.add_client(our_public_id.clone(), generate_random_endpoint()));
assert_eq!(0, relay_map.relay_map.len());
assert_eq!(0, relay_map.lookup_map.len());
while relay_map.relay_map.len() < super::MAX_RELAY {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
assert_eq!(false, relay_map.add_client(PublicId::new(&Id::new()),
generate_random_endpoint()));
}
#[test]
fn drop() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
drop_ip_node(&mut relay_map, &test_id);
assert_eq!(false, relay_map.contains_relay_for(&test_id));
assert_eq!(false, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(None, relay_map.get_endpoints(&test_id));
}
#[test]
fn add_conflicting_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
let test_conflicting_public_id = PublicId::new(&Id::new());
let test_conflicting_id = Address::Client(test_conflicting_public_id.signing_public_key());
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(false, relay_map.add_client(test_conflicting_public_id.clone(),
test_endpoint.clone()));
assert_eq!(false, relay_map.contains_relay_for(&test_conflicting_id))
}
#[test]
fn add_multiple_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
assert!(super::MAX_RELAY - 1 > 0);
// ensure relay_map is all but full, so multiple endpoints are not counted as different
// relays.
while relay_map.relay_map.len() < super::MAX_RELAY - 1 {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let mut test_endpoint_1 = generate_random_endpoint();
let mut test_endpoint_2 = generate_random_endpoint();
loop {
if!relay_map.contains_endpoint(&test_endpoint_1) { break; }
test_endpoint_1 = generate_random_endpoint(); };
loop {
if!relay_map.contains_endpoint(&test_endpoint_2) { break; }
test_endpoint_2 = generate_random_endpoint(); };
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint_1));
assert_eq!(false, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_2.clone()));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_1));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_2));
}
// TODO: add test for drop_endpoint
// TODO: add tests for unknown_connections
}
|
random_line_split
|
|
relay.rs
|
// Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! This module handle all connections that are not managed by the routing table.
//!
//! As such the relay module handles messages that need to flow in or out of the SAFE network.
//! These messages include bootstrap actions by starting nodes or relay messages for clients.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use time::{SteadyTime};
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use NameType;
use sodiumoxide::crypto::sign;
const MAX_RELAY : usize = 100;
/// The relay map is used to maintain a list of contacts for whom
/// we are relaying messages, when we are ourselves connected to the network.
/// These have to identify as Client(sign::PublicKey)
pub struct RelayMap {
relay_map: BTreeMap<Address, (PublicId, BTreeSet<Endpoint>)>,
lookup_map: HashMap<Endpoint, Address>,
// FIXME : we don't want to store a value; but LRUcache can clear itself out
// however, we want the explicit timestamp stored and clear it at routing,
// to drop the connection on clearing; for now CM will just keep all these connections
unknown_connections: HashMap<Endpoint, SteadyTime>,
our_name: NameType,
}
impl RelayMap {
/// This creates a new RelayMap.
pub fn new(our_id: &Id) -> RelayMap {
RelayMap {
relay_map: BTreeMap::new(),
lookup_map: HashMap::new(),
unknown_connections: HashMap::new(),
our_name: our_id.name(),
}
}
/// Adds an IP Node info to the relay map if the relay map has open
/// slots. This returns true if Info was addded.
/// Returns true is the endpoint is newly added, or was already present.
/// Returns false if the threshold was reached or name is our name.
/// Returns false if the endpoint is already assigned to a different name.
pub fn add_client(&mut self, relay_info: PublicId, relay_endpoint: Endpoint) -> bool {
// always reject our own id
if self.our_name == relay_info.name() {
return false;
}
// impose limit on number of relay nodes active
if!self.relay_map.contains_key(&Address::Client(relay_info.signing_public_key()))
&& self.relay_map.len() >= MAX_RELAY {
return false;
}
if self.lookup_map.contains_key(&relay_endpoint) {
return false; }
// only add Client
self.lookup_map.entry(relay_endpoint.clone())
.or_insert(Address::Client(relay_info.signing_public_key()));
let new_set = || { (relay_info.clone(), BTreeSet::<Endpoint>::new()) };
self.relay_map.entry(Address::Client(relay_info.signing_public_key()))
.or_insert_with(new_set).1
.insert(relay_endpoint);
true
}
/// This removes the provided endpoint and returns a NameType if this endpoint
/// was the last endpoint assocoiated with this Name; otherwise returns None.
pub fn drop_endpoint(&mut self, endpoint_to_drop: &Endpoint) -> Option<Address> {
let mut old_entry = match self.lookup_map.remove(endpoint_to_drop) {
Some(name) => {
match self.relay_map.remove(&name) {
Some(entry) => Some((name, entry)),
None => None
}
},
None => None
};
let new_entry = match old_entry {
Some((ref name, (ref public_id, ref mut endpoints))) => {
endpoints.remove(endpoint_to_drop);
Some((name, (public_id, endpoints)))
},
None => None
};
match new_entry {
Some((name, (public_id, endpoints))) => {
if endpoints.is_empty() {
println!("Connection {:?} lost for relayed node {:?}", endpoint_to_drop, name);
Some(name.clone())
} else {
self.relay_map.insert(name.clone(), (public_id.clone(), endpoints.clone()));
None
}
},
None => None
}
}
/// Returns true if we keep relay endpoints for given name.
// FIXME(ben) this needs to be used 16/07/2015
#[allow(dead_code)]
pub fn contains_relay_for(&self, relay_name: &Address) -> bool {
self.relay_map.contains_key(relay_name)
}
/// Returns true if we already have a name associated with this endpoint.
pub fn contains_endpoint(&self, relay_endpoint: &Endpoint) -> bool
|
/// Returns Option<NameType> if an endpoint is found
pub fn lookup_endpoint(&self, relay_endpoint: &Endpoint) -> Option<Address> {
match self.lookup_map.get(relay_endpoint) {
Some(name) => Some(name.clone()),
None => None
}
}
/// This returns a pair of the stored PublicId and a BTreeSet of the stored Endpoints.
pub fn get_endpoints(&self, relay_name: &Address) -> Option<&(PublicId, BTreeSet<Endpoint>)> {
self.relay_map.get(relay_name)
}
/// On unknown NewConnection, register the endpoint we are connected to.
pub fn register_unknown_connection(&mut self, endpoint: Endpoint) {
// TODO: later prune and drop old unknown connections
self.unknown_connections.insert(endpoint, SteadyTime::now());
}
/// When we receive an "I am" message on this connection, drop it
pub fn remove_unknown_connection(&mut self, endpoint: &Endpoint) -> Option<Endpoint> {
match self.unknown_connections.remove(endpoint) {
Some(_) => Some(endpoint.clone()), // return the endpoint
None => None
}
}
/// Returns true if the endpoint has been registered as an unknown NewConnection
pub fn lookup_unknown_connection(&self, endpoint: &Endpoint) -> bool {
self.unknown_connections.contains_key(endpoint)
}
}
#[cfg(test)]
mod test {
use super::*;
use crust::Endpoint;
use id::Id;
use public_id::PublicId;
use types::Address;
use std::net::SocketAddr;
use std::str::FromStr;
use rand::random;
fn generate_random_endpoint() -> Endpoint {
Endpoint::Tcp(SocketAddr::from_str(&format!("127.0.0.1:{}", random::<u16>())).unwrap())
}
fn drop_ip_node(relay_map: &mut RelayMap, ip_node_to_drop: &Address) {
match relay_map.relay_map.get(&ip_node_to_drop) {
Some(relay_entry) => {
for endpoint in relay_entry.1.iter() {
relay_map.lookup_map.remove(endpoint);
}
},
None => return
};
relay_map.relay_map.remove(ip_node_to_drop);
}
#[test]
fn add() {
let our_id : Id = Id::new();
let our_public_id = PublicId::new(&our_id);
let mut relay_map = RelayMap::new(&our_id);
assert_eq!(false, relay_map.add_client(our_public_id.clone(), generate_random_endpoint()));
assert_eq!(0, relay_map.relay_map.len());
assert_eq!(0, relay_map.lookup_map.len());
while relay_map.relay_map.len() < super::MAX_RELAY {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
assert_eq!(false, relay_map.add_client(PublicId::new(&Id::new()),
generate_random_endpoint()));
}
#[test]
fn drop() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
drop_ip_node(&mut relay_map, &test_id);
assert_eq!(false, relay_map.contains_relay_for(&test_id));
assert_eq!(false, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(None, relay_map.get_endpoints(&test_id));
}
#[test]
fn add_conflicting_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let test_endpoint = generate_random_endpoint();
let test_conflicting_public_id = PublicId::new(&Id::new());
let test_conflicting_id = Address::Client(test_conflicting_public_id.signing_public_key());
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint));
assert_eq!(false, relay_map.add_client(test_conflicting_public_id.clone(),
test_endpoint.clone()));
assert_eq!(false, relay_map.contains_relay_for(&test_conflicting_id))
}
#[test]
fn add_multiple_endpoints() {
let our_id : Id = Id::new();
let mut relay_map = RelayMap::new(&our_id);
assert!(super::MAX_RELAY - 1 > 0);
// ensure relay_map is all but full, so multiple endpoints are not counted as different
// relays.
while relay_map.relay_map.len() < super::MAX_RELAY - 1 {
let new_endpoint = generate_random_endpoint();
if!relay_map.contains_endpoint(&new_endpoint) {
assert_eq!(true, relay_map.add_client(PublicId::new(&Id::new()),
new_endpoint)); };
}
let test_public_id = PublicId::new(&Id::new());
let test_id = Address::Client(test_public_id.signing_public_key());
let mut test_endpoint_1 = generate_random_endpoint();
let mut test_endpoint_2 = generate_random_endpoint();
loop {
if!relay_map.contains_endpoint(&test_endpoint_1) { break; }
test_endpoint_1 = generate_random_endpoint(); };
loop {
if!relay_map.contains_endpoint(&test_endpoint_2) { break; }
test_endpoint_2 = generate_random_endpoint(); };
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endpoint(&test_endpoint_1));
assert_eq!(false, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_2.clone()));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_1));
assert!(relay_map.get_endpoints(&test_id).unwrap().1
.contains(&test_endpoint_2));
}
// TODO: add test for drop_endpoint
// TODO: add tests for unknown_connections
}
|
{
self.lookup_map.contains_key(relay_endpoint)
}
|
identifier_body
|
bgmacro.rs
|
use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, self};
pub fn bindgen_macro(cx: &mut base::ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
let mut visit = BindgenArgsVisitor {
options: Default::default(),
seen_named: false
};
visit.options.builtins = true;
if!parse_macro_opts(cx, tts, &mut visit) {
return base::DummyResult::any(sp);
}
// Reparse clang_args as it is passed in string form
let clang_args = visit.options.clang_args.connect(" ");
visit.options.clang_args = parse_process_args(&clang_args[..]);
if let Some(path) = bindgen::get_include_dir() {
visit.options.clang_args.push("-I".to_owned());
visit.options.clang_args.push(path);
}
// Set the working dir to the directory containing the invoking rs file so
// that clang searches for headers relative to it rather than the crate root
let filename = cx.codemap().span_to_filename(sp);
let mod_dir = Path::new(&filename).parent().unwrap();
let cwd = match env::current_dir() {
Ok(d) => d,
Err(e) => panic!("Invalid current working directory: {}", e),
};
let p = Path::new(mod_dir);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to change to directory {}: {}", p.display(), e);
};
// We want the span for errors to just match the bindgen! symbol
// instead of the whole invocation which can span multiple lines
let mut short_span = sp;
short_span.hi = short_span.lo + codemap::BytePos(8);
let logger = MacroLogger { sp: short_span, cx: cx };
let ret = match Bindings::generate(&visit.options, Some(&logger as &Logger), None) {
Ok(bindings) => {
// syntex_syntax is not compatible with libsyntax so convert to string and reparse
let bindings_str = bindings.to_string();
// Unfortunately we lose span information due to reparsing
let mut parser = parse::new_parser_from_source_str(cx.parse_sess(), cx.cfg(), "(Auto-generated bindings)".to_string(), bindings_str);
let mut items = Vec::new();
while let Some(item) = parser.parse_item() {
items.push(item);
}
Box::new(BindgenResult { items: Some(SmallVector::many(items)) }) as Box<base::MacResult>
}
Err(_) => base::DummyResult::any(sp)
};
let p = Path::new(&cwd);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to return to directory {}: {}", p.display(), e);
}
ret
}
trait MacroArgsVisitor {
fn visit_str(&mut self, name: Option<&str>, val: &str) -> bool;
fn visit_int(&mut self, name: Option<&str>, val: i64) -> bool;
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool;
fn visit_ident(&mut self, name: Option<&str>, ident: &str) -> bool;
}
struct BindgenArgsVisitor {
pub options: BindgenOptions,
seen_named: bool
}
impl MacroArgsVisitor for BindgenArgsVisitor {
fn visit_str(&mut self, mut name: Option<&str>, val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
else if!self.seen_named { name = Some("clang_args") }
match name {
Some("link") => self.options.links.push((val.to_string(), LinkType::Default)),
Some("link_static") => self.options.links.push((val.to_string(), LinkType::Static)),
Some("link_framework") => self.options.links.push((val.to_string(), LinkType::Framework)),
Some("match") => self.options.match_pat.push(val.to_string()),
Some("clang_args") => self.options.clang_args.push(val.to_string()),
Some("enum_type") => self.options.override_enum_ty = val.to_string(),
_ => return false
}
true
}
fn visit_int(&mut self, name: Option<&str>, _val: i64) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool {
if name.is_some() { self.seen_named = true; }
match name {
Some("allow_unknown_types") => self.options.fail_on_unknown_type =!val,
Some("emit_builtins") => self.options.builtins = val,
_ => return false
}
true
}
fn visit_ident(&mut self, name: Option<&str>, _val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
}
// Parses macro invocations in the form [ident=|:]value where value is an ident or literal
// e.g. bindgen!(module_name, "header.h", emit_builtins=false, clang_args:"-I /usr/local/include")
fn parse_macro_opts(cx: &mut base::ExtCtxt, tts: &[ast::TokenTree], visit: &mut MacroArgsVisitor) -> bool
|
}
}
match parser.token {
// Match [ident]
token::Ident(val, _) => {
let val = parser.id_to_interned_str(val);
span.hi = parser.span.hi;
parser.bump();
// Bools are simply encoded as idents
let ret = match &*val {
"true" => visit.visit_bool(as_str(&name), true),
"false" => visit.visit_bool(as_str(&name), false),
val => visit.visit_ident(as_str(&name), val)
};
if!ret {
cx.span_err(span, "invalid argument");
args_good = false;
}
}
// Match [literal] and parse as an expression so we can expand macros
_ => {
let expr = cx.expander().fold_expr(parser.parse_expr());
span.hi = expr.span.hi;
match expr.node {
ast::ExprLit(ref lit) => {
let ret = match lit.node {
ast::LitStr(ref s, _) => visit.visit_str(as_str(&name), &*s),
ast::LitBool(b) => visit.visit_bool(as_str(&name), b),
ast::LitInt(i, ast::SignedIntLit(_, sign)) |
ast::LitInt(i, ast::UnsuffixedIntLit(sign)) => {
let i = i as i64;
let i = if sign == ast::Minus { -i } else { i };
visit.visit_int(as_str(&name), i)
},
ast::LitInt(i, ast::UnsignedIntLit(_)) => visit.visit_int(as_str(&name), i as i64),
_ => {
cx.span_err(span, "invalid argument format");
return false
}
};
if!ret {
cx.span_err(span, "invalid argument");
args_good = false;
}
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
}
}
if parser.check(&token::Eof) {
return args_good
}
if parser.eat(&token::Comma).is_err() {
cx.span_err(parser.span, "invalid argument format");
return false
}
}
}
// I'm sure there's a nicer way of doing it
fn as_str<'a>(owned: &'a Option<String>) -> Option<&'a str> {
match owned {
&Some(ref s) => Some(&s[..]),
&None => None
}
}
#[derive(PartialEq, Eq)]
enum QuoteState {
InNone,
InSingleQuotes,
InDoubleQuotes
}
fn parse_process_args(s: &str) -> Vec<String> {
let s = s.trim();
let mut parts = Vec::new();
let mut quote_state = QuoteState::InNone;
let mut positions = vec!(0);
let mut last ='';
for (i, c) in s.chars().chain(" ".chars()).enumerate() {
match (last, c) {
// Match \" set has_escaped and skip
('\\', '\"') => (),
// Match \'
('\\', '\'') => (),
// Match \<space>
// Check we don't escape the final added space
('\\','') if i < s.len() => (),
// Match \\
('\\', '\\') => (),
// Match <any>"
(_, '\"') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InDoubleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\"') if quote_state == QuoteState::InDoubleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any>'
(_, '\'') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InSingleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\'') if quote_state == QuoteState::InSingleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any><space>
// If we are at the end of the string close any open quotes
(_,'') if quote_state == QuoteState::InNone || i >= s.len() => {
{
positions.push(i);
let starts = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 0);
let ends = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 1);
let part: Vec<String> = starts.zip(ends).map(|((_, start), (_, end))| s[*start..*end].to_string()).collect();
let part = part.connect("");
if part.len() > 0 {
// Remove any extra whitespace outside the quotes
let part = &part[..].trim();
// Replace quoted characters
let part = part.replace("\\\"", "\"");
let part = part.replace("\\\'", "\'");
let part = part.replace("\\ ", " ");
let part = part.replace("\\\\", "\\");
parts.push(part);
}
}
positions.clear();
positions.push(i + 1);
},
(_, _) => ()
}
last = c;
}
parts
}
struct MacroLogger<'a, 'b:'a> {
sp: codemap::Span,
cx: &'a base::ExtCtxt<'b>
}
impl<'a, 'b> Logger for MacroLogger<'a, 'b> {
fn error(&self, msg: &str) {
self.cx.span_err(self.sp, msg)
}
fn warn(&self, msg: &str) {
self.cx.span_warn(self.sp, msg)
}
}
struct BindgenResult {
items: Option<SmallVector<P<ast::Item>>>
}
impl base::MacResult for BindgenResult {
fn make_items(mut self: Box<BindgenResult>) -> Option<SmallVector<P<ast::Item>>> {
self.items.take()
}
}
#[test]
fn test_parse_process_args() {
assert_eq!(parse_process_args("a b c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b\" c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \'b\' c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b c\""), vec!("a", "b c"));
assert_eq!(parse_process_args("a \'\"b\"\' c"), vec!("a", "\"b\"", "c"));
assert_eq!(parse_process_args("a b\\ c"), vec!("a", "b c"));
assert_eq!(parse_process_args("a b c\\"), vec!("a", "b", "c\\"));
}
|
{
let mut parser = cx.new_parser_from_tts(tts);
let mut args_good = true;
loop {
let mut name: Option<String> = None;
let mut span = parser.span;
// Check for [ident=]value and if found save ident to name
if parser.look_ahead(1, |t| t == &token::Eq) {
match parser.bump_and_get() {
Ok(token::Ident(ident, _)) => {
let ident = parser.id_to_interned_str(ident);
name = Some(ident.to_string());
parser.expect(&token::Eq);
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
|
identifier_body
|
bgmacro.rs
|
use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, self};
pub fn bindgen_macro(cx: &mut base::ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
let mut visit = BindgenArgsVisitor {
options: Default::default(),
seen_named: false
};
visit.options.builtins = true;
if!parse_macro_opts(cx, tts, &mut visit) {
return base::DummyResult::any(sp);
}
// Reparse clang_args as it is passed in string form
let clang_args = visit.options.clang_args.connect(" ");
visit.options.clang_args = parse_process_args(&clang_args[..]);
if let Some(path) = bindgen::get_include_dir() {
visit.options.clang_args.push("-I".to_owned());
visit.options.clang_args.push(path);
}
// Set the working dir to the directory containing the invoking rs file so
// that clang searches for headers relative to it rather than the crate root
let filename = cx.codemap().span_to_filename(sp);
let mod_dir = Path::new(&filename).parent().unwrap();
let cwd = match env::current_dir() {
Ok(d) => d,
Err(e) => panic!("Invalid current working directory: {}", e),
};
let p = Path::new(mod_dir);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to change to directory {}: {}", p.display(), e);
};
// We want the span for errors to just match the bindgen! symbol
// instead of the whole invocation which can span multiple lines
let mut short_span = sp;
short_span.hi = short_span.lo + codemap::BytePos(8);
let logger = MacroLogger { sp: short_span, cx: cx };
let ret = match Bindings::generate(&visit.options, Some(&logger as &Logger), None) {
Ok(bindings) => {
// syntex_syntax is not compatible with libsyntax so convert to string and reparse
let bindings_str = bindings.to_string();
// Unfortunately we lose span information due to reparsing
let mut parser = parse::new_parser_from_source_str(cx.parse_sess(), cx.cfg(), "(Auto-generated bindings)".to_string(), bindings_str);
let mut items = Vec::new();
while let Some(item) = parser.parse_item() {
items.push(item);
}
Box::new(BindgenResult { items: Some(SmallVector::many(items)) }) as Box<base::MacResult>
}
Err(_) => base::DummyResult::any(sp)
};
let p = Path::new(&cwd);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to return to directory {}: {}", p.display(), e);
}
ret
}
trait MacroArgsVisitor {
fn visit_str(&mut self, name: Option<&str>, val: &str) -> bool;
fn visit_int(&mut self, name: Option<&str>, val: i64) -> bool;
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool;
fn visit_ident(&mut self, name: Option<&str>, ident: &str) -> bool;
}
struct BindgenArgsVisitor {
pub options: BindgenOptions,
seen_named: bool
}
impl MacroArgsVisitor for BindgenArgsVisitor {
fn visit_str(&mut self, mut name: Option<&str>, val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
else if!self.seen_named { name = Some("clang_args") }
match name {
Some("link") => self.options.links.push((val.to_string(), LinkType::Default)),
Some("link_static") => self.options.links.push((val.to_string(), LinkType::Static)),
Some("link_framework") => self.options.links.push((val.to_string(), LinkType::Framework)),
Some("match") => self.options.match_pat.push(val.to_string()),
Some("clang_args") => self.options.clang_args.push(val.to_string()),
Some("enum_type") => self.options.override_enum_ty = val.to_string(),
_ => return false
}
true
}
fn visit_int(&mut self, name: Option<&str>, _val: i64) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool {
if name.is_some() { self.seen_named = true; }
match name {
Some("allow_unknown_types") => self.options.fail_on_unknown_type =!val,
Some("emit_builtins") => self.options.builtins = val,
_ => return false
}
true
}
fn visit_ident(&mut self, name: Option<&str>, _val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
}
// Parses macro invocations in the form [ident=|:]value where value is an ident or literal
// e.g. bindgen!(module_name, "header.h", emit_builtins=false, clang_args:"-I /usr/local/include")
fn parse_macro_opts(cx: &mut base::ExtCtxt, tts: &[ast::TokenTree], visit: &mut MacroArgsVisitor) -> bool {
let mut parser = cx.new_parser_from_tts(tts);
let mut args_good = true;
loop {
let mut name: Option<String> = None;
let mut span = parser.span;
// Check for [ident=]value and if found save ident to name
if parser.look_ahead(1, |t| t == &token::Eq) {
match parser.bump_and_get() {
Ok(token::Ident(ident, _)) => {
let ident = parser.id_to_interned_str(ident);
name = Some(ident.to_string());
parser.expect(&token::Eq);
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
}
match parser.token {
// Match [ident]
token::Ident(val, _) => {
let val = parser.id_to_interned_str(val);
span.hi = parser.span.hi;
parser.bump();
// Bools are simply encoded as idents
let ret = match &*val {
"true" => visit.visit_bool(as_str(&name), true),
"false" => visit.visit_bool(as_str(&name), false),
val => visit.visit_ident(as_str(&name), val)
};
if!ret {
cx.span_err(span, "invalid argument");
args_good = false;
}
}
// Match [literal] and parse as an expression so we can expand macros
_ => {
let expr = cx.expander().fold_expr(parser.parse_expr());
span.hi = expr.span.hi;
match expr.node {
ast::ExprLit(ref lit) => {
let ret = match lit.node {
ast::LitStr(ref s, _) => visit.visit_str(as_str(&name), &*s),
ast::LitBool(b) => visit.visit_bool(as_str(&name), b),
ast::LitInt(i, ast::SignedIntLit(_, sign)) |
ast::LitInt(i, ast::UnsuffixedIntLit(sign)) => {
let i = i as i64;
let i = if sign == ast::Minus { -i } else { i };
visit.visit_int(as_str(&name), i)
},
ast::LitInt(i, ast::UnsignedIntLit(_)) => visit.visit_int(as_str(&name), i as i64),
_ => {
cx.span_err(span, "invalid argument format");
return false
}
};
if!ret {
cx.span_err(span, "invalid argument");
args_good = false;
}
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
|
}
}
if parser.check(&token::Eof) {
return args_good
}
if parser.eat(&token::Comma).is_err() {
cx.span_err(parser.span, "invalid argument format");
return false
}
}
}
// I'm sure there's a nicer way of doing it
fn as_str<'a>(owned: &'a Option<String>) -> Option<&'a str> {
match owned {
&Some(ref s) => Some(&s[..]),
&None => None
}
}
#[derive(PartialEq, Eq)]
enum QuoteState {
InNone,
InSingleQuotes,
InDoubleQuotes
}
fn parse_process_args(s: &str) -> Vec<String> {
let s = s.trim();
let mut parts = Vec::new();
let mut quote_state = QuoteState::InNone;
let mut positions = vec!(0);
let mut last ='';
for (i, c) in s.chars().chain(" ".chars()).enumerate() {
match (last, c) {
// Match \" set has_escaped and skip
('\\', '\"') => (),
// Match \'
('\\', '\'') => (),
// Match \<space>
// Check we don't escape the final added space
('\\','') if i < s.len() => (),
// Match \\
('\\', '\\') => (),
// Match <any>"
(_, '\"') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InDoubleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\"') if quote_state == QuoteState::InDoubleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any>'
(_, '\'') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InSingleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\'') if quote_state == QuoteState::InSingleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any><space>
// If we are at the end of the string close any open quotes
(_,'') if quote_state == QuoteState::InNone || i >= s.len() => {
{
positions.push(i);
let starts = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 0);
let ends = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 1);
let part: Vec<String> = starts.zip(ends).map(|((_, start), (_, end))| s[*start..*end].to_string()).collect();
let part = part.connect("");
if part.len() > 0 {
// Remove any extra whitespace outside the quotes
let part = &part[..].trim();
// Replace quoted characters
let part = part.replace("\\\"", "\"");
let part = part.replace("\\\'", "\'");
let part = part.replace("\\ ", " ");
let part = part.replace("\\\\", "\\");
parts.push(part);
}
}
positions.clear();
positions.push(i + 1);
},
(_, _) => ()
}
last = c;
}
parts
}
struct MacroLogger<'a, 'b:'a> {
sp: codemap::Span,
cx: &'a base::ExtCtxt<'b>
}
impl<'a, 'b> Logger for MacroLogger<'a, 'b> {
fn error(&self, msg: &str) {
self.cx.span_err(self.sp, msg)
}
fn warn(&self, msg: &str) {
self.cx.span_warn(self.sp, msg)
}
}
struct BindgenResult {
items: Option<SmallVector<P<ast::Item>>>
}
impl base::MacResult for BindgenResult {
fn make_items(mut self: Box<BindgenResult>) -> Option<SmallVector<P<ast::Item>>> {
self.items.take()
}
}
#[test]
fn test_parse_process_args() {
assert_eq!(parse_process_args("a b c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b\" c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \'b\' c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b c\""), vec!("a", "b c"));
assert_eq!(parse_process_args("a \'\"b\"\' c"), vec!("a", "\"b\"", "c"));
assert_eq!(parse_process_args("a b\\ c"), vec!("a", "b c"));
assert_eq!(parse_process_args("a b c\\"), vec!("a", "b", "c\\"));
}
|
random_line_split
|
|
bgmacro.rs
|
use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, self};
pub fn bindgen_macro(cx: &mut base::ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
let mut visit = BindgenArgsVisitor {
options: Default::default(),
seen_named: false
};
visit.options.builtins = true;
if!parse_macro_opts(cx, tts, &mut visit) {
return base::DummyResult::any(sp);
}
// Reparse clang_args as it is passed in string form
let clang_args = visit.options.clang_args.connect(" ");
visit.options.clang_args = parse_process_args(&clang_args[..]);
if let Some(path) = bindgen::get_include_dir() {
visit.options.clang_args.push("-I".to_owned());
visit.options.clang_args.push(path);
}
// Set the working dir to the directory containing the invoking rs file so
// that clang searches for headers relative to it rather than the crate root
let filename = cx.codemap().span_to_filename(sp);
let mod_dir = Path::new(&filename).parent().unwrap();
let cwd = match env::current_dir() {
Ok(d) => d,
Err(e) => panic!("Invalid current working directory: {}", e),
};
let p = Path::new(mod_dir);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to change to directory {}: {}", p.display(), e);
};
// We want the span for errors to just match the bindgen! symbol
// instead of the whole invocation which can span multiple lines
let mut short_span = sp;
short_span.hi = short_span.lo + codemap::BytePos(8);
let logger = MacroLogger { sp: short_span, cx: cx };
let ret = match Bindings::generate(&visit.options, Some(&logger as &Logger), None) {
Ok(bindings) => {
// syntex_syntax is not compatible with libsyntax so convert to string and reparse
let bindings_str = bindings.to_string();
// Unfortunately we lose span information due to reparsing
let mut parser = parse::new_parser_from_source_str(cx.parse_sess(), cx.cfg(), "(Auto-generated bindings)".to_string(), bindings_str);
let mut items = Vec::new();
while let Some(item) = parser.parse_item() {
items.push(item);
}
Box::new(BindgenResult { items: Some(SmallVector::many(items)) }) as Box<base::MacResult>
}
Err(_) => base::DummyResult::any(sp)
};
let p = Path::new(&cwd);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to return to directory {}: {}", p.display(), e);
}
ret
}
trait MacroArgsVisitor {
fn visit_str(&mut self, name: Option<&str>, val: &str) -> bool;
fn visit_int(&mut self, name: Option<&str>, val: i64) -> bool;
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool;
fn visit_ident(&mut self, name: Option<&str>, ident: &str) -> bool;
}
struct BindgenArgsVisitor {
pub options: BindgenOptions,
seen_named: bool
}
impl MacroArgsVisitor for BindgenArgsVisitor {
fn visit_str(&mut self, mut name: Option<&str>, val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
else if!self.seen_named { name = Some("clang_args") }
match name {
Some("link") => self.options.links.push((val.to_string(), LinkType::Default)),
Some("link_static") => self.options.links.push((val.to_string(), LinkType::Static)),
Some("link_framework") => self.options.links.push((val.to_string(), LinkType::Framework)),
Some("match") => self.options.match_pat.push(val.to_string()),
Some("clang_args") => self.options.clang_args.push(val.to_string()),
Some("enum_type") => self.options.override_enum_ty = val.to_string(),
_ => return false
}
true
}
fn visit_int(&mut self, name: Option<&str>, _val: i64) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool {
if name.is_some() { self.seen_named = true; }
match name {
Some("allow_unknown_types") => self.options.fail_on_unknown_type =!val,
Some("emit_builtins") => self.options.builtins = val,
_ => return false
}
true
}
fn visit_ident(&mut self, name: Option<&str>, _val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
}
// Parses macro invocations in the form [ident=|:]value where value is an ident or literal
// e.g. bindgen!(module_name, "header.h", emit_builtins=false, clang_args:"-I /usr/local/include")
fn parse_macro_opts(cx: &mut base::ExtCtxt, tts: &[ast::TokenTree], visit: &mut MacroArgsVisitor) -> bool {
let mut parser = cx.new_parser_from_tts(tts);
let mut args_good = true;
loop {
let mut name: Option<String> = None;
let mut span = parser.span;
// Check for [ident=]value and if found save ident to name
if parser.look_ahead(1, |t| t == &token::Eq) {
match parser.bump_and_get() {
Ok(token::Ident(ident, _)) => {
let ident = parser.id_to_interned_str(ident);
name = Some(ident.to_string());
parser.expect(&token::Eq);
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
}
match parser.token {
// Match [ident]
token::Ident(val, _) => {
let val = parser.id_to_interned_str(val);
span.hi = parser.span.hi;
parser.bump();
// Bools are simply encoded as idents
let ret = match &*val {
"true" => visit.visit_bool(as_str(&name), true),
"false" => visit.visit_bool(as_str(&name), false),
val => visit.visit_ident(as_str(&name), val)
};
if!ret {
cx.span_err(span, "invalid argument");
args_good = false;
}
}
// Match [literal] and parse as an expression so we can expand macros
_ => {
let expr = cx.expander().fold_expr(parser.parse_expr());
span.hi = expr.span.hi;
match expr.node {
ast::ExprLit(ref lit) => {
let ret = match lit.node {
ast::LitStr(ref s, _) => visit.visit_str(as_str(&name), &*s),
ast::LitBool(b) => visit.visit_bool(as_str(&name), b),
ast::LitInt(i, ast::SignedIntLit(_, sign)) |
ast::LitInt(i, ast::UnsuffixedIntLit(sign)) => {
let i = i as i64;
let i = if sign == ast::Minus { -i } else { i };
visit.visit_int(as_str(&name), i)
},
ast::LitInt(i, ast::UnsignedIntLit(_)) => visit.visit_int(as_str(&name), i as i64),
_ => {
cx.span_err(span, "invalid argument format");
return false
}
};
if!ret {
cx.span_err(span, "invalid argument");
args_good = false;
}
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
}
}
if parser.check(&token::Eof) {
return args_good
}
if parser.eat(&token::Comma).is_err() {
cx.span_err(parser.span, "invalid argument format");
return false
}
}
}
// I'm sure there's a nicer way of doing it
fn as_str<'a>(owned: &'a Option<String>) -> Option<&'a str> {
match owned {
&Some(ref s) => Some(&s[..]),
&None => None
}
}
#[derive(PartialEq, Eq)]
enum QuoteState {
InNone,
InSingleQuotes,
InDoubleQuotes
}
fn parse_process_args(s: &str) -> Vec<String> {
let s = s.trim();
let mut parts = Vec::new();
let mut quote_state = QuoteState::InNone;
let mut positions = vec!(0);
let mut last ='';
for (i, c) in s.chars().chain(" ".chars()).enumerate() {
match (last, c) {
// Match \" set has_escaped and skip
('\\', '\"') => (),
// Match \'
('\\', '\'') => (),
// Match \<space>
// Check we don't escape the final added space
('\\','') if i < s.len() => (),
// Match \\
('\\', '\\') => (),
// Match <any>"
(_, '\"') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InDoubleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\"') if quote_state == QuoteState::InDoubleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any>'
(_, '\'') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InSingleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\'') if quote_state == QuoteState::InSingleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any><space>
// If we are at the end of the string close any open quotes
(_,'') if quote_state == QuoteState::InNone || i >= s.len() => {
{
positions.push(i);
let starts = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 0);
let ends = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 1);
let part: Vec<String> = starts.zip(ends).map(|((_, start), (_, end))| s[*start..*end].to_string()).collect();
let part = part.connect("");
if part.len() > 0 {
// Remove any extra whitespace outside the quotes
let part = &part[..].trim();
// Replace quoted characters
let part = part.replace("\\\"", "\"");
let part = part.replace("\\\'", "\'");
let part = part.replace("\\ ", " ");
let part = part.replace("\\\\", "\\");
parts.push(part);
}
}
positions.clear();
positions.push(i + 1);
},
(_, _) => ()
}
last = c;
}
parts
}
struct
|
<'a, 'b:'a> {
sp: codemap::Span,
cx: &'a base::ExtCtxt<'b>
}
impl<'a, 'b> Logger for MacroLogger<'a, 'b> {
fn error(&self, msg: &str) {
self.cx.span_err(self.sp, msg)
}
fn warn(&self, msg: &str) {
self.cx.span_warn(self.sp, msg)
}
}
struct BindgenResult {
items: Option<SmallVector<P<ast::Item>>>
}
impl base::MacResult for BindgenResult {
fn make_items(mut self: Box<BindgenResult>) -> Option<SmallVector<P<ast::Item>>> {
self.items.take()
}
}
#[test]
fn test_parse_process_args() {
assert_eq!(parse_process_args("a b c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b\" c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \'b\' c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b c\""), vec!("a", "b c"));
assert_eq!(parse_process_args("a \'\"b\"\' c"), vec!("a", "\"b\"", "c"));
assert_eq!(parse_process_args("a b\\ c"), vec!("a", "b c"));
assert_eq!(parse_process_args("a b c\\"), vec!("a", "b", "c\\"));
}
|
MacroLogger
|
identifier_name
|
bgmacro.rs
|
use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, self};
pub fn bindgen_macro(cx: &mut base::ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
let mut visit = BindgenArgsVisitor {
options: Default::default(),
seen_named: false
};
visit.options.builtins = true;
if!parse_macro_opts(cx, tts, &mut visit) {
return base::DummyResult::any(sp);
}
// Reparse clang_args as it is passed in string form
let clang_args = visit.options.clang_args.connect(" ");
visit.options.clang_args = parse_process_args(&clang_args[..]);
if let Some(path) = bindgen::get_include_dir() {
visit.options.clang_args.push("-I".to_owned());
visit.options.clang_args.push(path);
}
// Set the working dir to the directory containing the invoking rs file so
// that clang searches for headers relative to it rather than the crate root
let filename = cx.codemap().span_to_filename(sp);
let mod_dir = Path::new(&filename).parent().unwrap();
let cwd = match env::current_dir() {
Ok(d) => d,
Err(e) => panic!("Invalid current working directory: {}", e),
};
let p = Path::new(mod_dir);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to change to directory {}: {}", p.display(), e);
};
// We want the span for errors to just match the bindgen! symbol
// instead of the whole invocation which can span multiple lines
let mut short_span = sp;
short_span.hi = short_span.lo + codemap::BytePos(8);
let logger = MacroLogger { sp: short_span, cx: cx };
let ret = match Bindings::generate(&visit.options, Some(&logger as &Logger), None) {
Ok(bindings) => {
// syntex_syntax is not compatible with libsyntax so convert to string and reparse
let bindings_str = bindings.to_string();
// Unfortunately we lose span information due to reparsing
let mut parser = parse::new_parser_from_source_str(cx.parse_sess(), cx.cfg(), "(Auto-generated bindings)".to_string(), bindings_str);
let mut items = Vec::new();
while let Some(item) = parser.parse_item() {
items.push(item);
}
Box::new(BindgenResult { items: Some(SmallVector::many(items)) }) as Box<base::MacResult>
}
Err(_) => base::DummyResult::any(sp)
};
let p = Path::new(&cwd);
if let Err(e) = env::set_current_dir(&p) {
panic!("Failed to return to directory {}: {}", p.display(), e);
}
ret
}
trait MacroArgsVisitor {
fn visit_str(&mut self, name: Option<&str>, val: &str) -> bool;
fn visit_int(&mut self, name: Option<&str>, val: i64) -> bool;
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool;
fn visit_ident(&mut self, name: Option<&str>, ident: &str) -> bool;
}
struct BindgenArgsVisitor {
pub options: BindgenOptions,
seen_named: bool
}
impl MacroArgsVisitor for BindgenArgsVisitor {
fn visit_str(&mut self, mut name: Option<&str>, val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
else if!self.seen_named { name = Some("clang_args") }
match name {
Some("link") => self.options.links.push((val.to_string(), LinkType::Default)),
Some("link_static") => self.options.links.push((val.to_string(), LinkType::Static)),
Some("link_framework") => self.options.links.push((val.to_string(), LinkType::Framework)),
Some("match") => self.options.match_pat.push(val.to_string()),
Some("clang_args") => self.options.clang_args.push(val.to_string()),
Some("enum_type") => self.options.override_enum_ty = val.to_string(),
_ => return false
}
true
}
fn visit_int(&mut self, name: Option<&str>, _val: i64) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
fn visit_bool(&mut self, name: Option<&str>, val: bool) -> bool {
if name.is_some() { self.seen_named = true; }
match name {
Some("allow_unknown_types") => self.options.fail_on_unknown_type =!val,
Some("emit_builtins") => self.options.builtins = val,
_ => return false
}
true
}
fn visit_ident(&mut self, name: Option<&str>, _val: &str) -> bool {
if name.is_some() { self.seen_named = true; }
false
}
}
// Parses macro invocations in the form [ident=|:]value where value is an ident or literal
// e.g. bindgen!(module_name, "header.h", emit_builtins=false, clang_args:"-I /usr/local/include")
fn parse_macro_opts(cx: &mut base::ExtCtxt, tts: &[ast::TokenTree], visit: &mut MacroArgsVisitor) -> bool {
let mut parser = cx.new_parser_from_tts(tts);
let mut args_good = true;
loop {
let mut name: Option<String> = None;
let mut span = parser.span;
// Check for [ident=]value and if found save ident to name
if parser.look_ahead(1, |t| t == &token::Eq) {
match parser.bump_and_get() {
Ok(token::Ident(ident, _)) => {
let ident = parser.id_to_interned_str(ident);
name = Some(ident.to_string());
parser.expect(&token::Eq);
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
}
match parser.token {
// Match [ident]
token::Ident(val, _) => {
let val = parser.id_to_interned_str(val);
span.hi = parser.span.hi;
parser.bump();
// Bools are simply encoded as idents
let ret = match &*val {
"true" => visit.visit_bool(as_str(&name), true),
"false" => visit.visit_bool(as_str(&name), false),
val => visit.visit_ident(as_str(&name), val)
};
if!ret {
cx.span_err(span, "invalid argument");
args_good = false;
}
}
// Match [literal] and parse as an expression so we can expand macros
_ => {
let expr = cx.expander().fold_expr(parser.parse_expr());
span.hi = expr.span.hi;
match expr.node {
ast::ExprLit(ref lit) => {
let ret = match lit.node {
ast::LitStr(ref s, _) => visit.visit_str(as_str(&name), &*s),
ast::LitBool(b) => visit.visit_bool(as_str(&name), b),
ast::LitInt(i, ast::SignedIntLit(_, sign)) |
ast::LitInt(i, ast::UnsuffixedIntLit(sign)) => {
let i = i as i64;
let i = if sign == ast::Minus { -i } else { i };
visit.visit_int(as_str(&name), i)
},
ast::LitInt(i, ast::UnsignedIntLit(_)) => visit.visit_int(as_str(&name), i as i64),
_ => {
cx.span_err(span, "invalid argument format");
return false
}
};
if!ret
|
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
}
}
if parser.check(&token::Eof) {
return args_good
}
if parser.eat(&token::Comma).is_err() {
cx.span_err(parser.span, "invalid argument format");
return false
}
}
}
// I'm sure there's a nicer way of doing it
fn as_str<'a>(owned: &'a Option<String>) -> Option<&'a str> {
match owned {
&Some(ref s) => Some(&s[..]),
&None => None
}
}
#[derive(PartialEq, Eq)]
enum QuoteState {
InNone,
InSingleQuotes,
InDoubleQuotes
}
fn parse_process_args(s: &str) -> Vec<String> {
let s = s.trim();
let mut parts = Vec::new();
let mut quote_state = QuoteState::InNone;
let mut positions = vec!(0);
let mut last ='';
for (i, c) in s.chars().chain(" ".chars()).enumerate() {
match (last, c) {
// Match \" set has_escaped and skip
('\\', '\"') => (),
// Match \'
('\\', '\'') => (),
// Match \<space>
// Check we don't escape the final added space
('\\','') if i < s.len() => (),
// Match \\
('\\', '\\') => (),
// Match <any>"
(_, '\"') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InDoubleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\"') if quote_state == QuoteState::InDoubleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any>'
(_, '\'') if quote_state == QuoteState::InNone => {
quote_state = QuoteState::InSingleQuotes;
positions.push(i);
positions.push(i + 1);
},
(_, '\'') if quote_state == QuoteState::InSingleQuotes => {
quote_state = QuoteState::InNone;
positions.push(i);
positions.push(i + 1);
},
// Match <any><space>
// If we are at the end of the string close any open quotes
(_,'') if quote_state == QuoteState::InNone || i >= s.len() => {
{
positions.push(i);
let starts = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 0);
let ends = positions.iter().enumerate().filter(|&(i, _)| i % 2 == 1);
let part: Vec<String> = starts.zip(ends).map(|((_, start), (_, end))| s[*start..*end].to_string()).collect();
let part = part.connect("");
if part.len() > 0 {
// Remove any extra whitespace outside the quotes
let part = &part[..].trim();
// Replace quoted characters
let part = part.replace("\\\"", "\"");
let part = part.replace("\\\'", "\'");
let part = part.replace("\\ ", " ");
let part = part.replace("\\\\", "\\");
parts.push(part);
}
}
positions.clear();
positions.push(i + 1);
},
(_, _) => ()
}
last = c;
}
parts
}
struct MacroLogger<'a, 'b:'a> {
sp: codemap::Span,
cx: &'a base::ExtCtxt<'b>
}
impl<'a, 'b> Logger for MacroLogger<'a, 'b> {
fn error(&self, msg: &str) {
self.cx.span_err(self.sp, msg)
}
fn warn(&self, msg: &str) {
self.cx.span_warn(self.sp, msg)
}
}
struct BindgenResult {
items: Option<SmallVector<P<ast::Item>>>
}
impl base::MacResult for BindgenResult {
fn make_items(mut self: Box<BindgenResult>) -> Option<SmallVector<P<ast::Item>>> {
self.items.take()
}
}
#[test]
fn test_parse_process_args() {
assert_eq!(parse_process_args("a b c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b\" c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \'b\' c"), vec!("a", "b", "c"));
assert_eq!(parse_process_args("a \"b c\""), vec!("a", "b c"));
assert_eq!(parse_process_args("a \'\"b\"\' c"), vec!("a", "\"b\"", "c"));
assert_eq!(parse_process_args("a b\\ c"), vec!("a", "b c"));
assert_eq!(parse_process_args("a b c\\"), vec!("a", "b", "c\\"));
}
|
{
cx.span_err(span, "invalid argument");
args_good = false;
}
|
conditional_block
|
item.rs
|
// Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use model::ErrorModel;
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TodoListItemModel {
pub text: String,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
|
pub struct TodoListItemExternalModel {
pub text: String,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AddItemTodoListRequestModel {
pub token: String,
pub todo_list_id: String,
pub todo_list_item: TodoListItemExternalModel,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AddItemTodoListResponseModel {
pub error: Option<ErrorModel>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AddItemTodoListModel {
pub user_id: String,
pub todo_list_id: String,
pub todo_list_item: TodoListItemModel,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct UpdateItemTodoListRequestModel {
pub token: String,
pub todo_list_id: String,
pub item_index: i32,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct UpdateItemTodoListResponseModel {
pub error: Option<ErrorModel>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UpdateTodoListItemModel {
pub user_id: String,
pub todo_list_id: String,
pub item_index: i32,
pub is_done: bool,
}
|
random_line_split
|
|
item.rs
|
// Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use model::ErrorModel;
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct
|
{
pub text: String,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct TodoListItemExternalModel {
pub text: String,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AddItemTodoListRequestModel {
pub token: String,
pub todo_list_id: String,
pub todo_list_item: TodoListItemExternalModel,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AddItemTodoListResponseModel {
pub error: Option<ErrorModel>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AddItemTodoListModel {
pub user_id: String,
pub todo_list_id: String,
pub todo_list_item: TodoListItemModel,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct UpdateItemTodoListRequestModel {
pub token: String,
pub todo_list_id: String,
pub item_index: i32,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct UpdateItemTodoListResponseModel {
pub error: Option<ErrorModel>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UpdateTodoListItemModel {
pub user_id: String,
pub todo_list_id: String,
pub item_index: i32,
pub is_done: bool,
}
|
TodoListItemModel
|
identifier_name
|
overloaded-calls-bad.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.
#![feature(unboxed_closures)]
use std::ops::FnMut;
struct S {
x: isize,
y: isize,
}
impl FnMut<(isize,),isize> for S {
extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize {
self.x * self.y * z
}
}
fn main()
|
{
let mut s = S {
x: 3,
y: 3,
};
let ans = s("what"); //~ ERROR mismatched types
let ans = s(); //~ ERROR this function takes 1 parameter but 0 parameters were supplied
let ans = s("burma", "shave");
//~^ ERROR this function takes 1 parameter but 2 parameters were supplied
}
|
identifier_body
|
|
overloaded-calls-bad.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.
#![feature(unboxed_closures)]
use std::ops::FnMut;
struct S {
x: isize,
|
extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize {
self.x * self.y * z
}
}
fn main() {
let mut s = S {
x: 3,
y: 3,
};
let ans = s("what"); //~ ERROR mismatched types
let ans = s(); //~ ERROR this function takes 1 parameter but 0 parameters were supplied
let ans = s("burma", "shave");
//~^ ERROR this function takes 1 parameter but 2 parameters were supplied
}
|
y: isize,
}
impl FnMut<(isize,),isize> for S {
|
random_line_split
|
overloaded-calls-bad.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.
#![feature(unboxed_closures)]
use std::ops::FnMut;
struct S {
x: isize,
y: isize,
}
impl FnMut<(isize,),isize> for S {
extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize {
self.x * self.y * z
}
}
fn
|
() {
let mut s = S {
x: 3,
y: 3,
};
let ans = s("what"); //~ ERROR mismatched types
let ans = s(); //~ ERROR this function takes 1 parameter but 0 parameters were supplied
let ans = s("burma", "shave");
//~^ ERROR this function takes 1 parameter but 2 parameters were supplied
}
|
main
|
identifier_name
|
trailing_zeros.rs
|
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::conversion::traits::WrappingFrom;
use malachite_base::num::logic::traits::TrailingZeros;
use malachite_base::slices::slice_leading_zeros;
use natural::InnerNatural::{Large, Small};
use natural::Natural;
use platform::Limb;
/// Interpreting a slice of `Limb`s as the limbs of a `Natural` in ascending order, returns the
/// number of trailing zeros in the binary expansion of a `Natural` (equivalently, the multiplicity
/// of 2 in its prime factorization). The limbs cannot be empty or all zero.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `xs.len()`
///
/// # Panics
/// Panics if `xs` only contains zeros.
///
/// # Examples
/// ```
/// use malachite_nz::natural::logic::trailing_zeros::limbs_trailing_zeros;
///
/// assert_eq!(limbs_trailing_zeros(&[4]), 2);
/// assert_eq!(limbs_trailing_zeros(&[0, 4]), 34);
/// ```
#[doc(hidden)]
pub fn limbs_trailing_zeros(xs: &[Limb]) -> u64 {
let zeros = slice_leading_zeros(xs);
let remaining_zeros = TrailingZeros::trailing_zeros(xs[zeros]);
(u64::wrapping_from(zeros) << Limb::LOG_WIDTH) + remaining_zeros
}
impl Natural {
/// Returns the number of trailing zeros in the binary expansion of a `Natural` (equivalently,
/// the multiplicity of 2 in its prime factorization) or `None` is the `Natural` is 0.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::natural::Natural;
///
/// assert_eq!(Natural::ZERO.trailing_zeros(), None);
/// assert_eq!(Natural::from(3u32).trailing_zeros(), Some(0));
/// assert_eq!(Natural::from(72u32).trailing_zeros(), Some(3));
/// assert_eq!(Natural::from(100u32).trailing_zeros(), Some(2));
/// assert_eq!(Natural::trillion().trailing_zeros(), Some(12));
/// ```
pub fn trailing_zeros(&self) -> Option<u64>
|
}
|
{
match *self {
natural_zero!() => None,
Natural(Small(small)) => Some(TrailingZeros::trailing_zeros(small)),
Natural(Large(ref limbs)) => Some(limbs_trailing_zeros(limbs)),
}
}
|
identifier_body
|
trailing_zeros.rs
|
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::conversion::traits::WrappingFrom;
use malachite_base::num::logic::traits::TrailingZeros;
use malachite_base::slices::slice_leading_zeros;
use natural::InnerNatural::{Large, Small};
use natural::Natural;
use platform::Limb;
/// Interpreting a slice of `Limb`s as the limbs of a `Natural` in ascending order, returns the
/// number of trailing zeros in the binary expansion of a `Natural` (equivalently, the multiplicity
/// of 2 in its prime factorization). The limbs cannot be empty or all zero.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `xs.len()`
///
/// # Panics
/// Panics if `xs` only contains zeros.
///
/// # Examples
/// ```
/// use malachite_nz::natural::logic::trailing_zeros::limbs_trailing_zeros;
///
/// assert_eq!(limbs_trailing_zeros(&[4]), 2);
/// assert_eq!(limbs_trailing_zeros(&[0, 4]), 34);
/// ```
#[doc(hidden)]
pub fn limbs_trailing_zeros(xs: &[Limb]) -> u64 {
let zeros = slice_leading_zeros(xs);
let remaining_zeros = TrailingZeros::trailing_zeros(xs[zeros]);
(u64::wrapping_from(zeros) << Limb::LOG_WIDTH) + remaining_zeros
}
|
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::natural::Natural;
///
/// assert_eq!(Natural::ZERO.trailing_zeros(), None);
/// assert_eq!(Natural::from(3u32).trailing_zeros(), Some(0));
/// assert_eq!(Natural::from(72u32).trailing_zeros(), Some(3));
/// assert_eq!(Natural::from(100u32).trailing_zeros(), Some(2));
/// assert_eq!(Natural::trillion().trailing_zeros(), Some(12));
/// ```
pub fn trailing_zeros(&self) -> Option<u64> {
match *self {
natural_zero!() => None,
Natural(Small(small)) => Some(TrailingZeros::trailing_zeros(small)),
Natural(Large(ref limbs)) => Some(limbs_trailing_zeros(limbs)),
}
}
}
|
impl Natural {
/// Returns the number of trailing zeros in the binary expansion of a `Natural` (equivalently,
/// the multiplicity of 2 in its prime factorization) or `None` is the `Natural` is 0.
///
|
random_line_split
|
trailing_zeros.rs
|
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::conversion::traits::WrappingFrom;
use malachite_base::num::logic::traits::TrailingZeros;
use malachite_base::slices::slice_leading_zeros;
use natural::InnerNatural::{Large, Small};
use natural::Natural;
use platform::Limb;
/// Interpreting a slice of `Limb`s as the limbs of a `Natural` in ascending order, returns the
/// number of trailing zeros in the binary expansion of a `Natural` (equivalently, the multiplicity
/// of 2 in its prime factorization). The limbs cannot be empty or all zero.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `xs.len()`
///
/// # Panics
/// Panics if `xs` only contains zeros.
///
/// # Examples
/// ```
/// use malachite_nz::natural::logic::trailing_zeros::limbs_trailing_zeros;
///
/// assert_eq!(limbs_trailing_zeros(&[4]), 2);
/// assert_eq!(limbs_trailing_zeros(&[0, 4]), 34);
/// ```
#[doc(hidden)]
pub fn
|
(xs: &[Limb]) -> u64 {
let zeros = slice_leading_zeros(xs);
let remaining_zeros = TrailingZeros::trailing_zeros(xs[zeros]);
(u64::wrapping_from(zeros) << Limb::LOG_WIDTH) + remaining_zeros
}
impl Natural {
/// Returns the number of trailing zeros in the binary expansion of a `Natural` (equivalently,
/// the multiplicity of 2 in its prime factorization) or `None` is the `Natural` is 0.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::natural::Natural;
///
/// assert_eq!(Natural::ZERO.trailing_zeros(), None);
/// assert_eq!(Natural::from(3u32).trailing_zeros(), Some(0));
/// assert_eq!(Natural::from(72u32).trailing_zeros(), Some(3));
/// assert_eq!(Natural::from(100u32).trailing_zeros(), Some(2));
/// assert_eq!(Natural::trillion().trailing_zeros(), Some(12));
/// ```
pub fn trailing_zeros(&self) -> Option<u64> {
match *self {
natural_zero!() => None,
Natural(Small(small)) => Some(TrailingZeros::trailing_zeros(small)),
Natural(Large(ref limbs)) => Some(limbs_trailing_zeros(limbs)),
}
}
}
|
limbs_trailing_zeros
|
identifier_name
|
foo.rs
|
// Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things and anyone sripting rustc's linker
// is probably using a `*.bat` script and is likely to hit this limit.
//
// This test uses a `foo.bat` script as the linker which just simply
// delegates back to this program. The compiler should use a lower
// limit for arguments before passing everything via `@`, which
// means that everything should still succeed here.
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write, Read};
use std::path::PathBuf;
use std::process::Command;
fn main()
|
let me = env::current_exe().unwrap();
let bat = me.parent()
.unwrap()
.join("foo.bat");
let bat_linker = format!("linker={}", bat.display());
for i in (1..).map(|i| i * 10) {
println!("attempt: {}", i);
let file = tmpdir.join("bar.rs");
let mut f = BufWriter::new(File::create(&file).unwrap());
let mut lib_name = String::new();
for _ in 0..i {
lib_name.push_str("foo");
}
for j in 0..i {
writeln!(f, "#[link(name = \"{}{}\")]", lib_name, j).unwrap();
}
writeln!(f, "extern {{}}\nfn main() {{}}").unwrap();
f.into_inner().unwrap();
drop(fs::remove_file(&ok));
drop(fs::remove_file(¬_ok));
let status = Command::new(&rustc)
.arg(&file)
.arg("-C").arg(&bat_linker)
.arg("--out-dir").arg(&tmpdir)
.env("YOU_ARE_A_LINKER", "1")
.env("MY_LINKER", &me)
.status()
.unwrap();
if!status.success() {
panic!("rustc didn't succeed: {}", status);
}
if!ok.exists() {
assert!(not_ok.exists());
continue
}
let mut contents = Vec::new();
File::open(&ok).unwrap().read_to_end(&mut contents).unwrap();
for j in 0..i {
let exp = format!("{}{}", lib_name, j);
let exp = if cfg!(target_env = "msvc") {
let mut out = Vec::with_capacity(exp.len() * 2);
for c in exp.encode_utf16() {
// encode in little endian
out.push(c as u8);
out.push((c >> 8) as u8);
}
out
} else {
exp.into_bytes()
};
assert!(contents.windows(exp.len()).any(|w| w == &exp[..]));
}
break
}
}
|
{
if !cfg!(windows) {
return
}
let tmpdir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let ok = tmpdir.join("ok");
let not_ok = tmpdir.join("not_ok");
if env::var("YOU_ARE_A_LINKER").is_ok() {
match env::args_os().find(|a| a.to_string_lossy().contains("@")) {
Some(file) => {
let file = file.to_str().unwrap();
fs::copy(&file[1..], &ok).unwrap();
}
None => { File::create(¬_ok).unwrap(); }
}
return
}
let rustc = env::var_os("RUSTC").unwrap_or("rustc".into());
|
identifier_body
|
foo.rs
|
// Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things and anyone sripting rustc's linker
// is probably using a `*.bat` script and is likely to hit this limit.
//
// This test uses a `foo.bat` script as the linker which just simply
// delegates back to this program. The compiler should use a lower
// limit for arguments before passing everything via `@`, which
// means that everything should still succeed here.
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write, Read};
use std::path::PathBuf;
use std::process::Command;
fn
|
() {
if!cfg!(windows) {
return
}
let tmpdir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let ok = tmpdir.join("ok");
let not_ok = tmpdir.join("not_ok");
if env::var("YOU_ARE_A_LINKER").is_ok() {
match env::args_os().find(|a| a.to_string_lossy().contains("@")) {
Some(file) => {
let file = file.to_str().unwrap();
fs::copy(&file[1..], &ok).unwrap();
}
None => { File::create(¬_ok).unwrap(); }
}
return
}
let rustc = env::var_os("RUSTC").unwrap_or("rustc".into());
let me = env::current_exe().unwrap();
let bat = me.parent()
.unwrap()
.join("foo.bat");
let bat_linker = format!("linker={}", bat.display());
for i in (1..).map(|i| i * 10) {
println!("attempt: {}", i);
let file = tmpdir.join("bar.rs");
let mut f = BufWriter::new(File::create(&file).unwrap());
let mut lib_name = String::new();
for _ in 0..i {
lib_name.push_str("foo");
}
for j in 0..i {
writeln!(f, "#[link(name = \"{}{}\")]", lib_name, j).unwrap();
}
writeln!(f, "extern {{}}\nfn main() {{}}").unwrap();
f.into_inner().unwrap();
drop(fs::remove_file(&ok));
drop(fs::remove_file(¬_ok));
let status = Command::new(&rustc)
.arg(&file)
.arg("-C").arg(&bat_linker)
.arg("--out-dir").arg(&tmpdir)
.env("YOU_ARE_A_LINKER", "1")
.env("MY_LINKER", &me)
.status()
.unwrap();
if!status.success() {
panic!("rustc didn't succeed: {}", status);
}
if!ok.exists() {
assert!(not_ok.exists());
continue
}
let mut contents = Vec::new();
File::open(&ok).unwrap().read_to_end(&mut contents).unwrap();
for j in 0..i {
let exp = format!("{}{}", lib_name, j);
let exp = if cfg!(target_env = "msvc") {
let mut out = Vec::with_capacity(exp.len() * 2);
for c in exp.encode_utf16() {
// encode in little endian
out.push(c as u8);
out.push((c >> 8) as u8);
}
out
} else {
exp.into_bytes()
};
assert!(contents.windows(exp.len()).any(|w| w == &exp[..]));
}
break
}
}
|
main
|
identifier_name
|
foo.rs
|
// Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things and anyone sripting rustc's linker
// is probably using a `*.bat` script and is likely to hit this limit.
//
// This test uses a `foo.bat` script as the linker which just simply
// delegates back to this program. The compiler should use a lower
// limit for arguments before passing everything via `@`, which
// means that everything should still succeed here.
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write, Read};
use std::path::PathBuf;
use std::process::Command;
fn main() {
if!cfg!(windows) {
return
}
let tmpdir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let ok = tmpdir.join("ok");
let not_ok = tmpdir.join("not_ok");
if env::var("YOU_ARE_A_LINKER").is_ok() {
match env::args_os().find(|a| a.to_string_lossy().contains("@")) {
Some(file) => {
let file = file.to_str().unwrap();
fs::copy(&file[1..], &ok).unwrap();
}
None => { File::create(¬_ok).unwrap(); }
}
return
}
let rustc = env::var_os("RUSTC").unwrap_or("rustc".into());
let me = env::current_exe().unwrap();
let bat = me.parent()
.unwrap()
.join("foo.bat");
let bat_linker = format!("linker={}", bat.display());
for i in (1..).map(|i| i * 10) {
println!("attempt: {}", i);
let file = tmpdir.join("bar.rs");
let mut f = BufWriter::new(File::create(&file).unwrap());
let mut lib_name = String::new();
for _ in 0..i {
lib_name.push_str("foo");
}
for j in 0..i {
writeln!(f, "#[link(name = \"{}{}\")]", lib_name, j).unwrap();
}
writeln!(f, "extern {{}}\nfn main() {{}}").unwrap();
f.into_inner().unwrap();
drop(fs::remove_file(&ok));
drop(fs::remove_file(¬_ok));
let status = Command::new(&rustc)
.arg(&file)
.arg("-C").arg(&bat_linker)
.arg("--out-dir").arg(&tmpdir)
.env("YOU_ARE_A_LINKER", "1")
.env("MY_LINKER", &me)
.status()
.unwrap();
if!status.success() {
panic!("rustc didn't succeed: {}", status);
}
if!ok.exists() {
assert!(not_ok.exists());
continue
}
let mut contents = Vec::new();
File::open(&ok).unwrap().read_to_end(&mut contents).unwrap();
for j in 0..i {
let exp = format!("{}{}", lib_name, j);
let exp = if cfg!(target_env = "msvc") {
let mut out = Vec::with_capacity(exp.len() * 2);
for c in exp.encode_utf16() {
// encode in little endian
out.push(c as u8);
out.push((c >> 8) as u8);
}
out
} else {
exp.into_bytes()
};
assert!(contents.windows(exp.len()).any(|w| w == &exp[..]));
|
}
}
|
}
break
|
random_line_split
|
foo.rs
|
// Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things and anyone sripting rustc's linker
// is probably using a `*.bat` script and is likely to hit this limit.
//
// This test uses a `foo.bat` script as the linker which just simply
// delegates back to this program. The compiler should use a lower
// limit for arguments before passing everything via `@`, which
// means that everything should still succeed here.
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write, Read};
use std::path::PathBuf;
use std::process::Command;
fn main() {
if!cfg!(windows)
|
let tmpdir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let ok = tmpdir.join("ok");
let not_ok = tmpdir.join("not_ok");
if env::var("YOU_ARE_A_LINKER").is_ok() {
match env::args_os().find(|a| a.to_string_lossy().contains("@")) {
Some(file) => {
let file = file.to_str().unwrap();
fs::copy(&file[1..], &ok).unwrap();
}
None => { File::create(¬_ok).unwrap(); }
}
return
}
let rustc = env::var_os("RUSTC").unwrap_or("rustc".into());
let me = env::current_exe().unwrap();
let bat = me.parent()
.unwrap()
.join("foo.bat");
let bat_linker = format!("linker={}", bat.display());
for i in (1..).map(|i| i * 10) {
println!("attempt: {}", i);
let file = tmpdir.join("bar.rs");
let mut f = BufWriter::new(File::create(&file).unwrap());
let mut lib_name = String::new();
for _ in 0..i {
lib_name.push_str("foo");
}
for j in 0..i {
writeln!(f, "#[link(name = \"{}{}\")]", lib_name, j).unwrap();
}
writeln!(f, "extern {{}}\nfn main() {{}}").unwrap();
f.into_inner().unwrap();
drop(fs::remove_file(&ok));
drop(fs::remove_file(¬_ok));
let status = Command::new(&rustc)
.arg(&file)
.arg("-C").arg(&bat_linker)
.arg("--out-dir").arg(&tmpdir)
.env("YOU_ARE_A_LINKER", "1")
.env("MY_LINKER", &me)
.status()
.unwrap();
if!status.success() {
panic!("rustc didn't succeed: {}", status);
}
if!ok.exists() {
assert!(not_ok.exists());
continue
}
let mut contents = Vec::new();
File::open(&ok).unwrap().read_to_end(&mut contents).unwrap();
for j in 0..i {
let exp = format!("{}{}", lib_name, j);
let exp = if cfg!(target_env = "msvc") {
let mut out = Vec::with_capacity(exp.len() * 2);
for c in exp.encode_utf16() {
// encode in little endian
out.push(c as u8);
out.push((c >> 8) as u8);
}
out
} else {
exp.into_bytes()
};
assert!(contents.windows(exp.len()).any(|w| w == &exp[..]));
}
break
}
}
|
{
return
}
|
conditional_block
|
standard.rs
|
use std::sync::Arc;
use std::marker::PhantomData;
use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::PopulationFit;
use super::super::individual::IndividualManager;
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;
pub trait RetrieveFitsManager {
type FitsM;
fn retrieve(&mut self) -> &mut Self::FitsM;
}
pub trait RetrieveIndividualManager {
type IM;
fn retrieve(&mut self) -> &mut Self::IM;
}
pub trait Policy {
type LocalContext: RetrieveFitsManager<FitsM = Self::FitsM> + RetrieveIndividualManager<IM = Self::IndivM>;
type Exec: Executor<LC = Self::LocalContext>;
type Indiv;
type Fit;
type IndivME: Send +'static;
type IndivM: IndividualManager<I = Self::Indiv, FI = Self::Fit, E = Self::IndivME>;
type PopE: Send +'static;
type Pop: Set<T = Self::Indiv, E = Self::PopE> + Sync + Send +'static;
type FitsE: Send +'static;
type Fits: Set<T = (Self::Fit, usize), E = Self::FitsE> + Send +'static;
type FitsME: Send +'static;
type FitsM: SetManager<S = Self::Fits, E = Self::FitsME>;
}
pub struct StandardPopulationFit<P> where P: Policy {
_marker: PhantomData<P>,
}
impl<P> StandardPopulationFit<P> where P: Policy {
pub fn new() -> StandardPopulationFit<P> {
StandardPopulationFit {
_marker: PhantomData,
}
}
}
#[derive(Debug)]
pub enum FitnessError<PE, FE, FME, IME> {
Population(PE),
FitsSet(FE),
FitsSetManager(FME),
IndividualManager(IME),
}
#[derive(Debug)]
pub enum Error<ExecE, PopE, FitsE, FitsME, IndivME> {
NoOutputFitnessValues,
Executor(ExecutorJobError<ExecE, JobExecuteError<FitnessError<PopE, FitsE, FitsME, IndivME>, union::Error<FitsE, FitsME>>>),
}
pub type ErrorP<P> where P: Policy = Error<<P::Exec as Executor>::E, P::PopE, P::FitsE, P::FitsME, P::IndivME>;
impl<P> PopulationFit for StandardPopulationFit<P> where P: Policy {
type Exec = P::Exec;
type Indiv = P::Indiv;
type Pop = P::Pop;
type Fit = P::Fit;
type Fits = P::Fits;
type Err = ErrorP<P>;
fn
|
<WA>(&self, population: Arc<Self::Pop>, exec: &mut Self::Exec) -> Result<Self::Fits, Self::Err>
where WA: WorkAmount, <Self::Exec as Executor>::JIB: JobIterBuild<WA>
{
let population_size = population.size();
match exec.try_execute_job(
WA::new(population_size),
move |local_context, input_indices| {
let mut fitness_results = {
let mut set_manager = <P::LocalContext as RetrieveFitsManager>::retrieve(local_context);
try!(set_manager.make_set(Some(population_size)).map_err(FitnessError::FitsSetManager))
};
let mut indiv_manager = <P::LocalContext as RetrieveIndividualManager>::retrieve(local_context);
for index in input_indices {
let indiv = try!(population.get(index).map_err(FitnessError::Population));
let fitness = try!(indiv_manager.fitness(indiv).map_err(FitnessError::IndividualManager));
try!(fitness_results.add((fitness, index)).map_err(FitnessError::FitsSet));
}
Ok(fitness_results)
},
move |local_context, fits_a, fits_b| union::union(<P::LocalContext as RetrieveFitsManager>::retrieve(local_context), fits_a, fits_b))
{
Ok(None) => Err(Error::NoOutputFitnessValues),
Ok(Some(fitness_results)) => Ok(fitness_results),
Err(e) => Err(Error::Executor(e)),
}
}
}
#[cfg(test)]
mod tests {
use par_exec::Executor;
use par_exec::par::{ParallelExecutor, Alternately};
use super::super::super::super::set;
use super::super::PopulationFit;
use super::super::super::individual::IndividualManager;
use super::{Policy, StandardPopulationFit, RetrieveFitsManager, RetrieveIndividualManager};
struct IndivManager;
impl IndividualManager for IndivManager {
type I = usize;
type FI = f64;
type E = ();
fn generate(&mut self, index: usize) -> Result<Self::I, Self::E> {
Ok(index)
}
fn fitness(&mut self, indiv: &Self::I) -> Result<Self::FI, Self::E> {
Ok(1.0 / *indiv as f64)
}
}
struct LocalContext {
set_manager: set::vec::Manager<(f64, usize)>,
indiv_manager: IndivManager,
}
impl RetrieveFitsManager for LocalContext {
type FitsM = set::vec::Manager<(f64, usize)>;
fn retrieve(&mut self) -> &mut Self::FitsM {
&mut self.set_manager
}
}
impl RetrieveIndividualManager for LocalContext {
type IM = IndivManager;
fn retrieve(&mut self) -> &mut Self::IM {
&mut self.indiv_manager
}
}
struct TestPolicy;
impl Policy for TestPolicy {
type LocalContext = LocalContext;
type Exec = ParallelExecutor<LocalContext>;
type Indiv = usize;
type Fit = f64;
type IndivME = ();
type IndivM = IndivManager;
type PopE = set::vec::Error;
type Pop = Vec<usize>;
type FitsE = set::vec::Error;
type Fits = Vec<(f64, usize)>;
type FitsME = ();
type FitsM = set::vec::Manager<(f64, usize)>;
}
#[test]
fn parallel_fitness() {
let exec: ParallelExecutor<_> = Default::default();
let mut exec = exec.start(|| LocalContext {
set_manager: set::vec::Manager::new(),
indiv_manager: IndivManager,
}).unwrap();
use std::sync::Arc;
let population = Arc::new((0.. 1024).collect::<Vec<_>>());
let fitness_calculator: StandardPopulationFit<TestPolicy> =
StandardPopulationFit::new();
let mut fit_results =
fitness_calculator.fit::<Alternately>(population.clone(), &mut exec).unwrap();
fit_results.sort_by_key(|v| v.1);
assert_eq!(Arc::new(fit_results.into_iter().map(|(_, i)| i).collect::<Vec<_>>()), population);
}
}
|
fit
|
identifier_name
|
standard.rs
|
use std::sync::Arc;
use std::marker::PhantomData;
use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::PopulationFit;
use super::super::individual::IndividualManager;
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;
pub trait RetrieveFitsManager {
type FitsM;
fn retrieve(&mut self) -> &mut Self::FitsM;
}
pub trait RetrieveIndividualManager {
type IM;
fn retrieve(&mut self) -> &mut Self::IM;
}
pub trait Policy {
type LocalContext: RetrieveFitsManager<FitsM = Self::FitsM> + RetrieveIndividualManager<IM = Self::IndivM>;
type Exec: Executor<LC = Self::LocalContext>;
type Indiv;
type Fit;
type IndivME: Send +'static;
type IndivM: IndividualManager<I = Self::Indiv, FI = Self::Fit, E = Self::IndivME>;
type PopE: Send +'static;
type Pop: Set<T = Self::Indiv, E = Self::PopE> + Sync + Send +'static;
type FitsE: Send +'static;
type Fits: Set<T = (Self::Fit, usize), E = Self::FitsE> + Send +'static;
type FitsME: Send +'static;
type FitsM: SetManager<S = Self::Fits, E = Self::FitsME>;
}
pub struct StandardPopulationFit<P> where P: Policy {
_marker: PhantomData<P>,
}
impl<P> StandardPopulationFit<P> where P: Policy {
pub fn new() -> StandardPopulationFit<P> {
StandardPopulationFit {
_marker: PhantomData,
}
}
}
#[derive(Debug)]
pub enum FitnessError<PE, FE, FME, IME> {
Population(PE),
FitsSet(FE),
FitsSetManager(FME),
IndividualManager(IME),
}
#[derive(Debug)]
pub enum Error<ExecE, PopE, FitsE, FitsME, IndivME> {
NoOutputFitnessValues,
Executor(ExecutorJobError<ExecE, JobExecuteError<FitnessError<PopE, FitsE, FitsME, IndivME>, union::Error<FitsE, FitsME>>>),
}
pub type ErrorP<P> where P: Policy = Error<<P::Exec as Executor>::E, P::PopE, P::FitsE, P::FitsME, P::IndivME>;
impl<P> PopulationFit for StandardPopulationFit<P> where P: Policy {
type Exec = P::Exec;
type Indiv = P::Indiv;
type Pop = P::Pop;
type Fit = P::Fit;
type Fits = P::Fits;
type Err = ErrorP<P>;
fn fit<WA>(&self, population: Arc<Self::Pop>, exec: &mut Self::Exec) -> Result<Self::Fits, Self::Err>
where WA: WorkAmount, <Self::Exec as Executor>::JIB: JobIterBuild<WA>
{
let population_size = population.size();
match exec.try_execute_job(
WA::new(population_size),
move |local_context, input_indices| {
let mut fitness_results = {
let mut set_manager = <P::LocalContext as RetrieveFitsManager>::retrieve(local_context);
try!(set_manager.make_set(Some(population_size)).map_err(FitnessError::FitsSetManager))
};
let mut indiv_manager = <P::LocalContext as RetrieveIndividualManager>::retrieve(local_context);
for index in input_indices {
let indiv = try!(population.get(index).map_err(FitnessError::Population));
let fitness = try!(indiv_manager.fitness(indiv).map_err(FitnessError::IndividualManager));
try!(fitness_results.add((fitness, index)).map_err(FitnessError::FitsSet));
}
Ok(fitness_results)
},
move |local_context, fits_a, fits_b| union::union(<P::LocalContext as RetrieveFitsManager>::retrieve(local_context), fits_a, fits_b))
{
Ok(None) => Err(Error::NoOutputFitnessValues),
Ok(Some(fitness_results)) => Ok(fitness_results),
Err(e) => Err(Error::Executor(e)),
}
}
}
#[cfg(test)]
mod tests {
use par_exec::Executor;
use par_exec::par::{ParallelExecutor, Alternately};
use super::super::super::super::set;
use super::super::PopulationFit;
use super::super::super::individual::IndividualManager;
use super::{Policy, StandardPopulationFit, RetrieveFitsManager, RetrieveIndividualManager};
struct IndivManager;
impl IndividualManager for IndivManager {
type I = usize;
type FI = f64;
type E = ();
fn generate(&mut self, index: usize) -> Result<Self::I, Self::E> {
Ok(index)
}
fn fitness(&mut self, indiv: &Self::I) -> Result<Self::FI, Self::E> {
Ok(1.0 / *indiv as f64)
}
}
struct LocalContext {
set_manager: set::vec::Manager<(f64, usize)>,
indiv_manager: IndivManager,
}
impl RetrieveFitsManager for LocalContext {
type FitsM = set::vec::Manager<(f64, usize)>;
fn retrieve(&mut self) -> &mut Self::FitsM {
&mut self.set_manager
}
}
impl RetrieveIndividualManager for LocalContext {
type IM = IndivManager;
fn retrieve(&mut self) -> &mut Self::IM {
&mut self.indiv_manager
}
}
struct TestPolicy;
impl Policy for TestPolicy {
type LocalContext = LocalContext;
type Exec = ParallelExecutor<LocalContext>;
type Indiv = usize;
type Fit = f64;
type IndivME = ();
type IndivM = IndivManager;
type PopE = set::vec::Error;
type Pop = Vec<usize>;
type FitsE = set::vec::Error;
type Fits = Vec<(f64, usize)>;
type FitsME = ();
type FitsM = set::vec::Manager<(f64, usize)>;
}
#[test]
fn parallel_fitness()
|
}
|
{
let exec: ParallelExecutor<_> = Default::default();
let mut exec = exec.start(|| LocalContext {
set_manager: set::vec::Manager::new(),
indiv_manager: IndivManager,
}).unwrap();
use std::sync::Arc;
let population = Arc::new((0 .. 1024).collect::<Vec<_>>());
let fitness_calculator: StandardPopulationFit<TestPolicy> =
StandardPopulationFit::new();
let mut fit_results =
fitness_calculator.fit::<Alternately>(population.clone(), &mut exec).unwrap();
fit_results.sort_by_key(|v| v.1);
assert_eq!(Arc::new(fit_results.into_iter().map(|(_, i)| i).collect::<Vec<_>>()), population);
}
|
identifier_body
|
standard.rs
|
use std::sync::Arc;
use std::marker::PhantomData;
use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::PopulationFit;
use super::super::individual::IndividualManager;
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;
pub trait RetrieveFitsManager {
type FitsM;
fn retrieve(&mut self) -> &mut Self::FitsM;
}
pub trait RetrieveIndividualManager {
type IM;
fn retrieve(&mut self) -> &mut Self::IM;
}
pub trait Policy {
type LocalContext: RetrieveFitsManager<FitsM = Self::FitsM> + RetrieveIndividualManager<IM = Self::IndivM>;
type Exec: Executor<LC = Self::LocalContext>;
type Indiv;
type Fit;
type IndivME: Send +'static;
type IndivM: IndividualManager<I = Self::Indiv, FI = Self::Fit, E = Self::IndivME>;
type PopE: Send +'static;
type Pop: Set<T = Self::Indiv, E = Self::PopE> + Sync + Send +'static;
type FitsE: Send +'static;
type Fits: Set<T = (Self::Fit, usize), E = Self::FitsE> + Send +'static;
type FitsME: Send +'static;
type FitsM: SetManager<S = Self::Fits, E = Self::FitsME>;
}
pub struct StandardPopulationFit<P> where P: Policy {
_marker: PhantomData<P>,
}
impl<P> StandardPopulationFit<P> where P: Policy {
pub fn new() -> StandardPopulationFit<P> {
StandardPopulationFit {
_marker: PhantomData,
}
}
}
#[derive(Debug)]
pub enum FitnessError<PE, FE, FME, IME> {
Population(PE),
FitsSet(FE),
FitsSetManager(FME),
IndividualManager(IME),
}
#[derive(Debug)]
pub enum Error<ExecE, PopE, FitsE, FitsME, IndivME> {
NoOutputFitnessValues,
Executor(ExecutorJobError<ExecE, JobExecuteError<FitnessError<PopE, FitsE, FitsME, IndivME>, union::Error<FitsE, FitsME>>>),
}
pub type ErrorP<P> where P: Policy = Error<<P::Exec as Executor>::E, P::PopE, P::FitsE, P::FitsME, P::IndivME>;
impl<P> PopulationFit for StandardPopulationFit<P> where P: Policy {
type Exec = P::Exec;
type Indiv = P::Indiv;
type Pop = P::Pop;
type Fit = P::Fit;
type Fits = P::Fits;
type Err = ErrorP<P>;
fn fit<WA>(&self, population: Arc<Self::Pop>, exec: &mut Self::Exec) -> Result<Self::Fits, Self::Err>
where WA: WorkAmount, <Self::Exec as Executor>::JIB: JobIterBuild<WA>
{
let population_size = population.size();
match exec.try_execute_job(
WA::new(population_size),
move |local_context, input_indices| {
let mut fitness_results = {
let mut set_manager = <P::LocalContext as RetrieveFitsManager>::retrieve(local_context);
try!(set_manager.make_set(Some(population_size)).map_err(FitnessError::FitsSetManager))
};
let mut indiv_manager = <P::LocalContext as RetrieveIndividualManager>::retrieve(local_context);
for index in input_indices {
let indiv = try!(population.get(index).map_err(FitnessError::Population));
let fitness = try!(indiv_manager.fitness(indiv).map_err(FitnessError::IndividualManager));
try!(fitness_results.add((fitness, index)).map_err(FitnessError::FitsSet));
}
Ok(fitness_results)
},
move |local_context, fits_a, fits_b| union::union(<P::LocalContext as RetrieveFitsManager>::retrieve(local_context), fits_a, fits_b))
{
Ok(None) => Err(Error::NoOutputFitnessValues),
Ok(Some(fitness_results)) => Ok(fitness_results),
Err(e) => Err(Error::Executor(e)),
}
}
}
#[cfg(test)]
mod tests {
use par_exec::Executor;
use par_exec::par::{ParallelExecutor, Alternately};
use super::super::super::super::set;
use super::super::PopulationFit;
use super::super::super::individual::IndividualManager;
use super::{Policy, StandardPopulationFit, RetrieveFitsManager, RetrieveIndividualManager};
struct IndivManager;
impl IndividualManager for IndivManager {
type I = usize;
type FI = f64;
type E = ();
fn generate(&mut self, index: usize) -> Result<Self::I, Self::E> {
Ok(index)
|
}
}
struct LocalContext {
set_manager: set::vec::Manager<(f64, usize)>,
indiv_manager: IndivManager,
}
impl RetrieveFitsManager for LocalContext {
type FitsM = set::vec::Manager<(f64, usize)>;
fn retrieve(&mut self) -> &mut Self::FitsM {
&mut self.set_manager
}
}
impl RetrieveIndividualManager for LocalContext {
type IM = IndivManager;
fn retrieve(&mut self) -> &mut Self::IM {
&mut self.indiv_manager
}
}
struct TestPolicy;
impl Policy for TestPolicy {
type LocalContext = LocalContext;
type Exec = ParallelExecutor<LocalContext>;
type Indiv = usize;
type Fit = f64;
type IndivME = ();
type IndivM = IndivManager;
type PopE = set::vec::Error;
type Pop = Vec<usize>;
type FitsE = set::vec::Error;
type Fits = Vec<(f64, usize)>;
type FitsME = ();
type FitsM = set::vec::Manager<(f64, usize)>;
}
#[test]
fn parallel_fitness() {
let exec: ParallelExecutor<_> = Default::default();
let mut exec = exec.start(|| LocalContext {
set_manager: set::vec::Manager::new(),
indiv_manager: IndivManager,
}).unwrap();
use std::sync::Arc;
let population = Arc::new((0.. 1024).collect::<Vec<_>>());
let fitness_calculator: StandardPopulationFit<TestPolicy> =
StandardPopulationFit::new();
let mut fit_results =
fitness_calculator.fit::<Alternately>(population.clone(), &mut exec).unwrap();
fit_results.sort_by_key(|v| v.1);
assert_eq!(Arc::new(fit_results.into_iter().map(|(_, i)| i).collect::<Vec<_>>()), population);
}
}
|
}
fn fitness(&mut self, indiv: &Self::I) -> Result<Self::FI, Self::E> {
Ok(1.0 / *indiv as f64)
|
random_line_split
|
typeck-default-trait-impl-trait-where-clause.rs
|
// Copyright 2015 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.
// ignore-tidy-linelength
// Test that when a `..` impl applies, we also check that any
// supertrait conditions are met.
#![feature(optin_builtin_traits)]
use std::marker::MarkerTrait;
trait NotImplemented: MarkerTrait { }
trait MyTrait: MarkerTrait
where Option<Self> : NotImplemented
{}
impl NotImplemented for i32 {}
impl MyTrait for.. {}
fn foo<T:MyTrait>() {
bar::<Option<T>>()
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<T>`
//
// This should probably typecheck. This is #20671.
}
fn bar<T:NotImplemented>() { }
fn test() {
bar::<Option<i32>>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
fn main()
|
{
foo::<i32>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
|
identifier_body
|
|
typeck-default-trait-impl-trait-where-clause.rs
|
// Copyright 2015 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.
// ignore-tidy-linelength
// Test that when a `..` impl applies, we also check that any
// supertrait conditions are met.
#![feature(optin_builtin_traits)]
use std::marker::MarkerTrait;
trait NotImplemented: MarkerTrait { }
trait MyTrait: MarkerTrait
where Option<Self> : NotImplemented
{}
impl NotImplemented for i32 {}
impl MyTrait for.. {}
fn foo<T:MyTrait>() {
bar::<Option<T>>()
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<T>`
//
// This should probably typecheck. This is #20671.
}
fn bar<T:NotImplemented>() { }
|
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
fn main() {
foo::<i32>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
|
fn test() {
bar::<Option<i32>>();
|
random_line_split
|
typeck-default-trait-impl-trait-where-clause.rs
|
// Copyright 2015 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.
// ignore-tidy-linelength
// Test that when a `..` impl applies, we also check that any
// supertrait conditions are met.
#![feature(optin_builtin_traits)]
use std::marker::MarkerTrait;
trait NotImplemented: MarkerTrait { }
trait MyTrait: MarkerTrait
where Option<Self> : NotImplemented
{}
impl NotImplemented for i32 {}
impl MyTrait for.. {}
fn foo<T:MyTrait>() {
bar::<Option<T>>()
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<T>`
//
// This should probably typecheck. This is #20671.
}
fn
|
<T:NotImplemented>() { }
fn test() {
bar::<Option<i32>>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
fn main() {
foo::<i32>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
|
bar
|
identifier_name
|
connection.rs
|
use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_connection_t
}
impl Connection {
pub fn new(connection_ptr: *mut ffi::xcb_connection_t) -> Self {
Connection {
ptr: connection_ptr,
}
}
pub fn screen_of_display(&self, screen_id: &ScreenID) -> Result<Screen, RuntimeError> {
let setup = unsafe { ffi::xcb_get_setup(self.ptr) };
if setup == ptr::null() {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Getting XCB connection setup failed".to_string()
));
}
let mut iter = unsafe {
ffi::xcb_setup_roots_iterator(setup)
};
let mut screen_num = screen_id.screen;
while screen_num > 0 && iter.rem!= 0 {
unsafe { ffi::xcb_screen_next(&mut iter) };
screen_num -= 1;
}
Ok(Screen::new(iter.data))
}
pub fn generate_id(&self) -> Result<XID, RuntimeError> {
let id = unsafe {
ffi::xcb_generate_id(self.ptr)
};
if id == 0xffffffff {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Generating XID failed".to_string()
));
}
Ok(XID {
id: id
})
}
pub fn wait_for_event(&self) -> Option<Event> {
let event_ptr = unsafe {
ffi::xcb_wait_for_event(self.ptr)
};
if event_ptr.is_null() {
return None;
}
Some(
Event::new(event_ptr)
)
}
pub fn poll_event_iter(&self) -> EventIterator
|
pub fn flush(&self) {
unsafe {
ffi::xcb_flush(self.ptr);
}
}
pub fn intern_atom(&self, name: &str, existing_only: bool) -> InternAtomCookie {
let c_name = CString::new(name).unwrap();
let xcb_cookie = unsafe {
ffi::xcb_intern_atom(
self.ptr,
existing_only as ffi::c_uchar,
name.len() as ffi::c_ushort,
c_name.as_ptr()
)
};
InternAtomCookie {
xcb_cookie: xcb_cookie
}
}
pub fn intern_atom_reply(&self, cookie: &InternAtomCookie) -> InternAtomReply {
let xcb_reply = unsafe {
ffi::xcb_intern_atom_reply(
self.ptr,
cookie.xcb_cookie,
ptr::null_mut()
)
};
InternAtomReply {
xcb_reply: xcb_reply
}
}
pub fn error_check(&self, cookie: ffi::xcb_void_cookie_t) -> Option<ffi::c_uchar> {
let error = unsafe {
ffi::xcb_request_check(self.ptr, cookie)
};
if error!= ptr::null_mut() {
return Some(
unsafe {
(*error).error_code
}
)
}
None
}
}
|
{
EventIterator::new(self.ptr)
}
|
identifier_body
|
connection.rs
|
use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_connection_t
}
impl Connection {
pub fn new(connection_ptr: *mut ffi::xcb_connection_t) -> Self {
Connection {
ptr: connection_ptr,
}
}
pub fn
|
(&self, screen_id: &ScreenID) -> Result<Screen, RuntimeError> {
let setup = unsafe { ffi::xcb_get_setup(self.ptr) };
if setup == ptr::null() {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Getting XCB connection setup failed".to_string()
));
}
let mut iter = unsafe {
ffi::xcb_setup_roots_iterator(setup)
};
let mut screen_num = screen_id.screen;
while screen_num > 0 && iter.rem!= 0 {
unsafe { ffi::xcb_screen_next(&mut iter) };
screen_num -= 1;
}
Ok(Screen::new(iter.data))
}
pub fn generate_id(&self) -> Result<XID, RuntimeError> {
let id = unsafe {
ffi::xcb_generate_id(self.ptr)
};
if id == 0xffffffff {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Generating XID failed".to_string()
));
}
Ok(XID {
id: id
})
}
pub fn wait_for_event(&self) -> Option<Event> {
let event_ptr = unsafe {
ffi::xcb_wait_for_event(self.ptr)
};
if event_ptr.is_null() {
return None;
}
Some(
Event::new(event_ptr)
)
}
pub fn poll_event_iter(&self) -> EventIterator {
EventIterator::new(self.ptr)
}
pub fn flush(&self) {
unsafe {
ffi::xcb_flush(self.ptr);
}
}
pub fn intern_atom(&self, name: &str, existing_only: bool) -> InternAtomCookie {
let c_name = CString::new(name).unwrap();
let xcb_cookie = unsafe {
ffi::xcb_intern_atom(
self.ptr,
existing_only as ffi::c_uchar,
name.len() as ffi::c_ushort,
c_name.as_ptr()
)
};
InternAtomCookie {
xcb_cookie: xcb_cookie
}
}
pub fn intern_atom_reply(&self, cookie: &InternAtomCookie) -> InternAtomReply {
let xcb_reply = unsafe {
ffi::xcb_intern_atom_reply(
self.ptr,
cookie.xcb_cookie,
ptr::null_mut()
)
};
InternAtomReply {
xcb_reply: xcb_reply
}
}
pub fn error_check(&self, cookie: ffi::xcb_void_cookie_t) -> Option<ffi::c_uchar> {
let error = unsafe {
ffi::xcb_request_check(self.ptr, cookie)
};
if error!= ptr::null_mut() {
return Some(
unsafe {
(*error).error_code
}
)
}
None
}
}
|
screen_of_display
|
identifier_name
|
connection.rs
|
use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_connection_t
}
impl Connection {
pub fn new(connection_ptr: *mut ffi::xcb_connection_t) -> Self {
Connection {
ptr: connection_ptr,
}
}
pub fn screen_of_display(&self, screen_id: &ScreenID) -> Result<Screen, RuntimeError> {
let setup = unsafe { ffi::xcb_get_setup(self.ptr) };
if setup == ptr::null() {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Getting XCB connection setup failed".to_string()
));
}
let mut iter = unsafe {
ffi::xcb_setup_roots_iterator(setup)
};
let mut screen_num = screen_id.screen;
while screen_num > 0 && iter.rem!= 0 {
unsafe { ffi::xcb_screen_next(&mut iter) };
screen_num -= 1;
}
Ok(Screen::new(iter.data))
}
pub fn generate_id(&self) -> Result<XID, RuntimeError> {
let id = unsafe {
ffi::xcb_generate_id(self.ptr)
};
if id == 0xffffffff {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Generating XID failed".to_string()
));
}
Ok(XID {
id: id
})
}
pub fn wait_for_event(&self) -> Option<Event> {
let event_ptr = unsafe {
ffi::xcb_wait_for_event(self.ptr)
};
if event_ptr.is_null() {
return None;
}
Some(
Event::new(event_ptr)
)
}
pub fn poll_event_iter(&self) -> EventIterator {
EventIterator::new(self.ptr)
}
pub fn flush(&self) {
unsafe {
ffi::xcb_flush(self.ptr);
}
}
pub fn intern_atom(&self, name: &str, existing_only: bool) -> InternAtomCookie {
let c_name = CString::new(name).unwrap();
let xcb_cookie = unsafe {
ffi::xcb_intern_atom(
self.ptr,
existing_only as ffi::c_uchar,
name.len() as ffi::c_ushort,
c_name.as_ptr()
)
};
InternAtomCookie {
xcb_cookie: xcb_cookie
}
}
pub fn intern_atom_reply(&self, cookie: &InternAtomCookie) -> InternAtomReply {
let xcb_reply = unsafe {
ffi::xcb_intern_atom_reply(
self.ptr,
cookie.xcb_cookie,
ptr::null_mut()
)
};
InternAtomReply {
xcb_reply: xcb_reply
}
}
pub fn error_check(&self, cookie: ffi::xcb_void_cookie_t) -> Option<ffi::c_uchar> {
let error = unsafe {
ffi::xcb_request_check(self.ptr, cookie)
};
if error!= ptr::null_mut()
|
None
}
}
|
{
return Some(
unsafe {
(*error).error_code
}
)
}
|
conditional_block
|
connection.rs
|
use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_connection_t
}
impl Connection {
pub fn new(connection_ptr: *mut ffi::xcb_connection_t) -> Self {
Connection {
ptr: connection_ptr,
}
}
pub fn screen_of_display(&self, screen_id: &ScreenID) -> Result<Screen, RuntimeError> {
let setup = unsafe { ffi::xcb_get_setup(self.ptr) };
if setup == ptr::null() {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Getting XCB connection setup failed".to_string()
));
}
let mut iter = unsafe {
ffi::xcb_setup_roots_iterator(setup)
};
let mut screen_num = screen_id.screen;
while screen_num > 0 && iter.rem!= 0 {
unsafe { ffi::xcb_screen_next(&mut iter) };
screen_num -= 1;
}
Ok(Screen::new(iter.data))
}
pub fn generate_id(&self) -> Result<XID, RuntimeError> {
let id = unsafe {
ffi::xcb_generate_id(self.ptr)
};
if id == 0xffffffff {
return Err(RuntimeError::new(
|
Ok(XID {
id: id
})
}
pub fn wait_for_event(&self) -> Option<Event> {
let event_ptr = unsafe {
ffi::xcb_wait_for_event(self.ptr)
};
if event_ptr.is_null() {
return None;
}
Some(
Event::new(event_ptr)
)
}
pub fn poll_event_iter(&self) -> EventIterator {
EventIterator::new(self.ptr)
}
pub fn flush(&self) {
unsafe {
ffi::xcb_flush(self.ptr);
}
}
pub fn intern_atom(&self, name: &str, existing_only: bool) -> InternAtomCookie {
let c_name = CString::new(name).unwrap();
let xcb_cookie = unsafe {
ffi::xcb_intern_atom(
self.ptr,
existing_only as ffi::c_uchar,
name.len() as ffi::c_ushort,
c_name.as_ptr()
)
};
InternAtomCookie {
xcb_cookie: xcb_cookie
}
}
pub fn intern_atom_reply(&self, cookie: &InternAtomCookie) -> InternAtomReply {
let xcb_reply = unsafe {
ffi::xcb_intern_atom_reply(
self.ptr,
cookie.xcb_cookie,
ptr::null_mut()
)
};
InternAtomReply {
xcb_reply: xcb_reply
}
}
pub fn error_check(&self, cookie: ffi::xcb_void_cookie_t) -> Option<ffi::c_uchar> {
let error = unsafe {
ffi::xcb_request_check(self.ptr, cookie)
};
if error!= ptr::null_mut() {
return Some(
unsafe {
(*error).error_code
}
)
}
None
}
}
|
ErrorKind::XCB,
"Generating XID failed".to_string()
));
}
|
random_line_split
|
resource_thread.rs
|
auth_cache: Arc<RwLock<AuthCache>>,
hsts_list: Arc<RwLock<HstsList>>,
connector: Arc<Pool<Connector>>,
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()),
ProgressSender::Listener(ref b) => {
let action = match msg {
ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf),
ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status),
};
b.invoke_with_listener(action);
Ok(())
}
}
}
}
pub fn send_error(url: Url, err: NetworkError, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
if let Ok(p) = start_sending_opt(start_chan, metadata, Some(err.clone())) {
p.send(Done(Err(err))).unwrap();
}
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &[u8],
context: LoadContext)
-> ProgressSender {
start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body, context).ok().unwrap()
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &[u8],
context: LoadContext)
-> Result<ProgressSender, ()> {
if prefs::get_pref("network.mime.sniff").as_boolean().unwrap_or(false) {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut no_sniff = NoSniffFlag::OFF;
let mut check_for_apache_bug = ApacheBugFlag::OFF;
if let Some(ref headers) = metadata.headers {
if let Some(ref content_type) = headers.get_raw("content-type").and_then(|c| c.last()) {
check_for_apache_bug = ApacheBugFlag::from_content_type(content_type)
}
if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") {
if raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff") {
no_sniff = NoSniffFlag::ON
}
}
}
let supplied_type =
metadata.content_type.as_ref().map(|&ContentType(Mime(ref toplevel, ref sublevel, _))| {
(format!("{}", toplevel), format!("{}", sublevel))
});
let (toplevel, sublevel) = classifier.classify(context,
no_sniff,
check_for_apache_bug,
&supplied_type,
&partial_body);
let mime_tp: TopLevel = toplevel.parse().unwrap();
let mime_sb: SubLevel = sublevel.parse().unwrap();
metadata.content_type = Some(ContentType(Mime(mime_tp, mime_sb, vec![])));
}
start_sending_opt(start_chan, metadata, None)
}
/// For use by loaders in responding to a Load message.
/// It takes an optional NetworkError, so that we can extract the SSL Validation errors
/// and take it to the HTML parser
|
network_error: Option<NetworkError>) -> Result<ProgressSender, ()> {
match start_chan {
LoadConsumer::Channel(start_chan) => {
let (progress_chan, progress_port) = ipc::channel().unwrap();
let result = start_chan.send(LoadResponse {
metadata: metadata,
progress_port: progress_port,
});
match result {
Ok(_) => Ok(ProgressSender::Channel(progress_chan)),
Err(_) => Err(())
}
}
LoadConsumer::Listener(target) => {
match network_error {
Some(NetworkError::SslValidation(url)) => {
let error = NetworkError::SslValidation(url);
target.invoke_with_listener(ResponseAction::HeadersAvailable(Err(error)));
}
_ => target.invoke_with_listener(ResponseAction::HeadersAvailable(Ok(metadata))),
}
Ok(ProgressSender::Listener(target))
}
}
}
/// Returns a tuple of (public, private) senders to the new threads.
pub fn new_resource_threads(user_agent: String,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan) -> (ResourceThreads, ResourceThreads) {
let (public_core, private_core) = new_core_resource_thread(user_agent, devtools_chan, profiler_chan);
let storage: IpcSender<StorageThreadMsg> = StorageThreadFactory::new();
let filemanager: IpcSender<FileManagerThreadMsg> = FileManagerThreadFactory::new(TFD_PROVIDER);
(ResourceThreads::new(public_core, storage.clone(), filemanager.clone()),
ResourceThreads::new(private_core, storage, filemanager))
}
/// Create a CoreResourceThread
pub fn new_core_resource_thread(user_agent: String,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan)
-> (CoreResourceThread, CoreResourceThread) {
let (public_setup_chan, public_setup_port) = ipc::channel().unwrap();
let (private_setup_chan, private_setup_port) = ipc::channel().unwrap();
let public_setup_chan_clone = public_setup_chan.clone();
let private_setup_chan_clone = private_setup_chan.clone();
spawn_named("ResourceManager".to_owned(), move || {
let resource_manager = CoreResourceManager::new(
user_agent, devtools_chan, profiler_chan
);
let mut channel_manager = ResourceChannelManager {
resource_manager: resource_manager,
};
channel_manager.start(public_setup_chan_clone,
private_setup_chan_clone,
public_setup_port,
private_setup_port);
});
(public_setup_chan, private_setup_chan)
}
struct ResourceChannelManager {
resource_manager: CoreResourceManager,
}
fn create_resource_groups() -> (ResourceGroup, ResourceGroup) {
let mut hsts_list = HstsList::from_servo_preload();
let mut auth_cache = AuthCache::new();
let mut cookie_jar = CookieStorage::new();
if let Some(ref config_dir) = opts::get().config_dir {
read_json_from_file(&mut auth_cache, config_dir, "auth_cache.json");
read_json_from_file(&mut hsts_list, config_dir, "hsts_list.json");
read_json_from_file(&mut cookie_jar, config_dir, "cookie_jar.json");
}
let resource_group = ResourceGroup {
cookie_jar: Arc::new(RwLock::new(cookie_jar)),
auth_cache: Arc::new(RwLock::new(auth_cache)),
hsts_list: Arc::new(RwLock::new(hsts_list.clone())),
connector: create_http_connector(),
};
let private_resource_group = ResourceGroup {
cookie_jar: Arc::new(RwLock::new(CookieStorage::new())),
auth_cache: Arc::new(RwLock::new(AuthCache::new())),
hsts_list: Arc::new(RwLock::new(HstsList::new())),
connector: create_http_connector(),
};
(resource_group, private_resource_group)
}
impl ResourceChannelManager {
#[allow(unsafe_code)]
fn start(&mut self,
public_control_sender: CoreResourceThread,
private_control_sender: CoreResourceThread,
public_receiver: IpcReceiver<CoreResourceMsg>,
private_receiver: IpcReceiver<CoreResourceMsg>) {
let (public_resource_group, private_resource_group) = create_resource_groups();
let mut rx_set = IpcReceiverSet::new().unwrap();
let private_id = rx_set.add(private_receiver).unwrap();
let public_id = rx_set.add(public_receiver).unwrap();
loop {
for (id, data) in rx_set.select().unwrap().into_iter().map(|m| m.unwrap()) {
let (group, sender) = if id == private_id {
(&private_resource_group, &private_control_sender)
} else {
assert_eq!(id, public_id);
(&public_resource_group, &public_control_sender)
};
if let Ok(msg) = data.to() {
if!self.process_msg(msg, group, &sender) {
break;
}
}
}
}
}
/// Returns false if the thread should exit.
fn process_msg(&mut self,
msg: CoreResourceMsg,
group: &ResourceGroup,
control_sender: &CoreResourceThread) -> bool {
match msg {
CoreResourceMsg::Load(load_data, consumer, id_sender) =>
self.resource_manager.load(load_data, consumer, id_sender, control_sender.clone(), group),
CoreResourceMsg::Fetch(init, sender) =>
self.resource_manager.fetch(init, sender, group),
CoreResourceMsg::WebsocketConnect(connect, connect_data) =>
self.resource_manager.websocket_connect(connect, connect_data, group),
CoreResourceMsg::SetCookiesForUrl(request, cookie_list, source) =>
self.resource_manager.set_cookies_for_url(request, cookie_list, source, group),
CoreResourceMsg::GetCookiesForUrl(url, consumer, source) => {
let mut cookie_jar = group.cookie_jar.write().unwrap();
consumer.send(cookie_jar.cookies_for_url(&url, source)).unwrap();
}
CoreResourceMsg::Cancel(res_id) => {
if let Some(cancel_sender) = self.resource_manager.cancel_load_map.get(&res_id) {
let _ = cancel_sender.send(());
}
self.resource_manager.cancel_load_map.remove(&res_id);
}
CoreResourceMsg::Synchronize(sender) => {
let _ = sender.send(());
}
CoreResourceMsg::Exit(sender) => {
if let Some(ref config_dir) = opts::get().config_dir {
match group.auth_cache.read() {
Ok(auth_cache) => write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"),
Err(_) => warn!("Error writing auth cache to disk"),
}
match group.cookie_jar.read() {
Ok(jar) => write_json_to_file(&*jar, config_dir, "cookie_jar.json"),
Err(_) => warn!("Error writing cookie jar to disk"),
}
match group.hsts_list.read() {
Ok(hsts) => write_json_to_file(&*hsts, config_dir, "hsts_list.json"),
Err(_) => warn!("Error writing hsts list to disk"),
}
}
let _ = sender.send(());
return false;
}
}
true
}
}
pub fn read_json_from_file<T: Decodable>(data: &mut T, config_dir: &str, filename: &str) {
let path = Path::new(config_dir).join(filename);
let display = path.display();
let mut file = match File::open(&path) {
Err(why) => {
warn!("couldn't open {}: {}", display, Error::description(&why));
return;
},
Ok(file) => file,
};
let mut string_buffer: String = String::new();
match file.read_to_string(&mut string_buffer) {
Err(why) => {
panic!("couldn't read from {}: {}", display,
Error::description(&why))
},
Ok(_) => println!("successfully read from {}", display),
}
match json::decode(&string_buffer) {
Ok(decoded_buffer) => *data = decoded_buffer,
Err(why) => warn!("Could not decode buffer{}", why),
}
}
pub fn write_json_to_file<T: Encodable>(data: &T, config_dir: &str, filename: &str) {
let json_encoded: String;
match json::encode(&data) {
Ok(d) => json_encoded = d,
Err(_) => return,
}
let path = Path::new(config_dir).join(filename);
let display = path.display();
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
Error::description(&why)),
Ok(file) => file,
};
match file.write_all(json_encoded.as_bytes()) {
Err(why) => {
panic!("couldn't write to {}: {}", display,
Error::description(&why))
},
Ok(_) => println!("successfully wrote to {}", display),
}
}
/// The optional resources required by the `CancellationListener`
pub struct CancellableResource {
/// The receiver which receives a message on load cancellation
cancel_receiver: Receiver<()>,
/// The `CancellationListener` is unique to this `ResourceId`
resource_id: ResourceId,
/// If we haven't initiated any cancel requests, then the loaders ask
/// the listener to remove the `ResourceId` in the `HashMap` of
/// `CoreResourceManager` once they finish loading
resource_thread: CoreResourceThread,
}
impl CancellableResource {
pub fn new(receiver: Receiver<()>, res_id: ResourceId, res_thread: CoreResourceThread) -> CancellableResource {
CancellableResource {
cancel_receiver: receiver,
resource_id: res_id,
resource_thread: res_thread,
}
}
}
/// A listener which is basically a wrapped optional receiver which looks
/// for the load cancellation message. Some of the loading processes always keep
/// an eye out for this message and stop loading stuff once they receive it.
pub struct CancellationListener {
/// We'll be needing the resources only if we plan to cancel it
cancel_resource: Option<CancellableResource>,
/// This lets us know whether the request has already been cancelled
cancel_status: Cell<bool>,
}
impl CancellationListener {
pub fn new(resources: Option<CancellableResource>) -> CancellationListener {
CancellationListener {
cancel_resource: resources,
cancel_status: Cell::new(false),
}
}
pub fn is_cancelled(&self) -> bool {
let resource = match self.cancel_resource {
Some(ref resource) => resource,
None => return false, // channel doesn't exist!
};
if resource.cancel_receiver.try_recv().is_ok() {
self.cancel_status.set(true);
true
} else {
self.cancel_status.get()
}
}
}
impl Drop for CancellationListener {
fn drop(&mut self) {
if let Some(ref resource) = self.cancel_resource {
// Ensure that the resource manager stops tracking this request now that it's terminated.
let _ = resource.resource_thread.send(CoreResourceMsg::Cancel(resource.resource_id));
}
}
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCacheEntry {
pub user_name: String,
pub password: String,
}
impl AuthCache {
pub fn new() -> AuthCache {
AuthCache {
version: 1,
entries: HashMap::new()
}
}
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCache {
pub version: u32,
pub entries: HashMap<Url, AuthCacheEntry>,
}
pub struct CoreResourceManager {
user_agent: String,
mime_classifier: Arc<MIMEClassifier>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan,
cancel_load_map: HashMap<ResourceId, Sender<()>>,
next_resource_id: ResourceId,
}
impl CoreResourceManager {
pub fn new(user_agent: String,
devtools_channel: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan) -> CoreResourceManager {
CoreResourceManager {
user_agent: user_agent,
mime_classifier: Arc::new(MIMEClassifier::new()),
devtools_chan: devtools_channel,
profiler_chan: profiler_chan,
cancel_load_map: HashMap::new(),
next_resource_id: ResourceId(0),
}
}
fn set_cookies_for_url(&mut self,
request: Url,
cookie_list: String,
source: CookieSource,
resource_group: &ResourceGroup) {
let header = Header::parse_header(&[cookie_list.into_bytes()]);
if let Ok(SetCookie(cookies)) = header {
for bare_cookie in cookies {
if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) {
let mut cookie_jar = resource_group.cookie_jar.write().unwrap();
cookie_jar.push(cookie, source);
}
}
}
}
fn load(&mut self,
load_data: LoadData,
consumer: LoadConsumer,
id_sender: Option<IpcSender<ResourceId>>,
resource_thread: CoreResourceThread,
resource_grp: &ResourceGroup) {
fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>, CancellationListener))
-> Box<FnBox(LoadData,
LoadConsumer,
Arc<MIMEClassifier>,
CancellationListener) + Send> {
box move |load_data, senders, classifier, cancel_listener| {
factory(load_data, senders, classifier, cancel_listener)
}
}
let cancel_resource = id_sender.map(|sender| {
let current_res_id = self.next_resource_id;
let _ = sender.send(current_res_id);
|
fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata,
|
random_line_split
|
resource_thread.rs
|
auth_cache: Arc<RwLock<AuthCache>>,
hsts_list: Arc<RwLock<HstsList>>,
connector: Arc<Pool<Connector>>,
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()),
ProgressSender::Listener(ref b) => {
let action = match msg {
ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf),
ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status),
};
b.invoke_with_listener(action);
Ok(())
}
}
}
}
pub fn send_error(url: Url, err: NetworkError, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
if let Ok(p) = start_sending_opt(start_chan, metadata, Some(err.clone())) {
p.send(Done(Err(err))).unwrap();
}
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &[u8],
context: LoadContext)
-> ProgressSender {
start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body, context).ok().unwrap()
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &[u8],
context: LoadContext)
-> Result<ProgressSender, ()> {
if prefs::get_pref("network.mime.sniff").as_boolean().unwrap_or(false) {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut no_sniff = NoSniffFlag::OFF;
let mut check_for_apache_bug = ApacheBugFlag::OFF;
if let Some(ref headers) = metadata.headers {
if let Some(ref content_type) = headers.get_raw("content-type").and_then(|c| c.last()) {
check_for_apache_bug = ApacheBugFlag::from_content_type(content_type)
}
if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") {
if raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff") {
no_sniff = NoSniffFlag::ON
}
}
}
let supplied_type =
metadata.content_type.as_ref().map(|&ContentType(Mime(ref toplevel, ref sublevel, _))| {
(format!("{}", toplevel), format!("{}", sublevel))
});
let (toplevel, sublevel) = classifier.classify(context,
no_sniff,
check_for_apache_bug,
&supplied_type,
&partial_body);
let mime_tp: TopLevel = toplevel.parse().unwrap();
let mime_sb: SubLevel = sublevel.parse().unwrap();
metadata.content_type = Some(ContentType(Mime(mime_tp, mime_sb, vec![])));
}
start_sending_opt(start_chan, metadata, None)
}
/// For use by loaders in responding to a Load message.
/// It takes an optional NetworkError, so that we can extract the SSL Validation errors
/// and take it to the HTML parser
fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata,
network_error: Option<NetworkError>) -> Result<ProgressSender, ()> {
match start_chan {
LoadConsumer::Channel(start_chan) => {
let (progress_chan, progress_port) = ipc::channel().unwrap();
let result = start_chan.send(LoadResponse {
metadata: metadata,
progress_port: progress_port,
});
match result {
Ok(_) => Ok(ProgressSender::Channel(progress_chan)),
Err(_) => Err(())
}
}
LoadConsumer::Listener(target) => {
match network_error {
Some(NetworkError::SslValidation(url)) => {
let error = NetworkError::SslValidation(url);
target.invoke_with_listener(ResponseAction::HeadersAvailable(Err(error)));
}
_ => target.invoke_with_listener(ResponseAction::HeadersAvailable(Ok(metadata))),
}
Ok(ProgressSender::Listener(target))
}
}
}
/// Returns a tuple of (public, private) senders to the new threads.
pub fn new_resource_threads(user_agent: String,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan) -> (ResourceThreads, ResourceThreads) {
let (public_core, private_core) = new_core_resource_thread(user_agent, devtools_chan, profiler_chan);
let storage: IpcSender<StorageThreadMsg> = StorageThreadFactory::new();
let filemanager: IpcSender<FileManagerThreadMsg> = FileManagerThreadFactory::new(TFD_PROVIDER);
(ResourceThreads::new(public_core, storage.clone(), filemanager.clone()),
ResourceThreads::new(private_core, storage, filemanager))
}
/// Create a CoreResourceThread
pub fn new_core_resource_thread(user_agent: String,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan)
-> (CoreResourceThread, CoreResourceThread) {
let (public_setup_chan, public_setup_port) = ipc::channel().unwrap();
let (private_setup_chan, private_setup_port) = ipc::channel().unwrap();
let public_setup_chan_clone = public_setup_chan.clone();
let private_setup_chan_clone = private_setup_chan.clone();
spawn_named("ResourceManager".to_owned(), move || {
let resource_manager = CoreResourceManager::new(
user_agent, devtools_chan, profiler_chan
);
let mut channel_manager = ResourceChannelManager {
resource_manager: resource_manager,
};
channel_manager.start(public_setup_chan_clone,
private_setup_chan_clone,
public_setup_port,
private_setup_port);
});
(public_setup_chan, private_setup_chan)
}
struct ResourceChannelManager {
resource_manager: CoreResourceManager,
}
fn create_resource_groups() -> (ResourceGroup, ResourceGroup) {
let mut hsts_list = HstsList::from_servo_preload();
let mut auth_cache = AuthCache::new();
let mut cookie_jar = CookieStorage::new();
if let Some(ref config_dir) = opts::get().config_dir {
read_json_from_file(&mut auth_cache, config_dir, "auth_cache.json");
read_json_from_file(&mut hsts_list, config_dir, "hsts_list.json");
read_json_from_file(&mut cookie_jar, config_dir, "cookie_jar.json");
}
let resource_group = ResourceGroup {
cookie_jar: Arc::new(RwLock::new(cookie_jar)),
auth_cache: Arc::new(RwLock::new(auth_cache)),
hsts_list: Arc::new(RwLock::new(hsts_list.clone())),
connector: create_http_connector(),
};
let private_resource_group = ResourceGroup {
cookie_jar: Arc::new(RwLock::new(CookieStorage::new())),
auth_cache: Arc::new(RwLock::new(AuthCache::new())),
hsts_list: Arc::new(RwLock::new(HstsList::new())),
connector: create_http_connector(),
};
(resource_group, private_resource_group)
}
impl ResourceChannelManager {
#[allow(unsafe_code)]
fn start(&mut self,
public_control_sender: CoreResourceThread,
private_control_sender: CoreResourceThread,
public_receiver: IpcReceiver<CoreResourceMsg>,
private_receiver: IpcReceiver<CoreResourceMsg>) {
let (public_resource_group, private_resource_group) = create_resource_groups();
let mut rx_set = IpcReceiverSet::new().unwrap();
let private_id = rx_set.add(private_receiver).unwrap();
let public_id = rx_set.add(public_receiver).unwrap();
loop {
for (id, data) in rx_set.select().unwrap().into_iter().map(|m| m.unwrap()) {
let (group, sender) = if id == private_id {
(&private_resource_group, &private_control_sender)
} else {
assert_eq!(id, public_id);
(&public_resource_group, &public_control_sender)
};
if let Ok(msg) = data.to() {
if!self.process_msg(msg, group, &sender) {
break;
}
}
}
}
}
/// Returns false if the thread should exit.
fn process_msg(&mut self,
msg: CoreResourceMsg,
group: &ResourceGroup,
control_sender: &CoreResourceThread) -> bool {
match msg {
CoreResourceMsg::Load(load_data, consumer, id_sender) =>
self.resource_manager.load(load_data, consumer, id_sender, control_sender.clone(), group),
CoreResourceMsg::Fetch(init, sender) =>
self.resource_manager.fetch(init, sender, group),
CoreResourceMsg::WebsocketConnect(connect, connect_data) =>
self.resource_manager.websocket_connect(connect, connect_data, group),
CoreResourceMsg::SetCookiesForUrl(request, cookie_list, source) =>
self.resource_manager.set_cookies_for_url(request, cookie_list, source, group),
CoreResourceMsg::GetCookiesForUrl(url, consumer, source) => {
let mut cookie_jar = group.cookie_jar.write().unwrap();
consumer.send(cookie_jar.cookies_for_url(&url, source)).unwrap();
}
CoreResourceMsg::Cancel(res_id) => {
if let Some(cancel_sender) = self.resource_manager.cancel_load_map.get(&res_id) {
let _ = cancel_sender.send(());
}
self.resource_manager.cancel_load_map.remove(&res_id);
}
CoreResourceMsg::Synchronize(sender) => {
let _ = sender.send(());
}
CoreResourceMsg::Exit(sender) => {
if let Some(ref config_dir) = opts::get().config_dir {
match group.auth_cache.read() {
Ok(auth_cache) => write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"),
Err(_) => warn!("Error writing auth cache to disk"),
}
match group.cookie_jar.read() {
Ok(jar) => write_json_to_file(&*jar, config_dir, "cookie_jar.json"),
Err(_) => warn!("Error writing cookie jar to disk"),
}
match group.hsts_list.read() {
Ok(hsts) => write_json_to_file(&*hsts, config_dir, "hsts_list.json"),
Err(_) => warn!("Error writing hsts list to disk"),
}
}
let _ = sender.send(());
return false;
}
}
true
}
}
pub fn read_json_from_file<T: Decodable>(data: &mut T, config_dir: &str, filename: &str) {
let path = Path::new(config_dir).join(filename);
let display = path.display();
let mut file = match File::open(&path) {
Err(why) => {
warn!("couldn't open {}: {}", display, Error::description(&why));
return;
},
Ok(file) => file,
};
let mut string_buffer: String = String::new();
match file.read_to_string(&mut string_buffer) {
Err(why) => {
panic!("couldn't read from {}: {}", display,
Error::description(&why))
},
Ok(_) => println!("successfully read from {}", display),
}
match json::decode(&string_buffer) {
Ok(decoded_buffer) => *data = decoded_buffer,
Err(why) => warn!("Could not decode buffer{}", why),
}
}
pub fn write_json_to_file<T: Encodable>(data: &T, config_dir: &str, filename: &str) {
let json_encoded: String;
match json::encode(&data) {
Ok(d) => json_encoded = d,
Err(_) => return,
}
let path = Path::new(config_dir).join(filename);
let display = path.display();
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
Error::description(&why)),
Ok(file) => file,
};
match file.write_all(json_encoded.as_bytes()) {
Err(why) => {
panic!("couldn't write to {}: {}", display,
Error::description(&why))
},
Ok(_) => println!("successfully wrote to {}", display),
}
}
/// The optional resources required by the `CancellationListener`
pub struct
|
{
/// The receiver which receives a message on load cancellation
cancel_receiver: Receiver<()>,
/// The `CancellationListener` is unique to this `ResourceId`
resource_id: ResourceId,
/// If we haven't initiated any cancel requests, then the loaders ask
/// the listener to remove the `ResourceId` in the `HashMap` of
/// `CoreResourceManager` once they finish loading
resource_thread: CoreResourceThread,
}
impl CancellableResource {
pub fn new(receiver: Receiver<()>, res_id: ResourceId, res_thread: CoreResourceThread) -> CancellableResource {
CancellableResource {
cancel_receiver: receiver,
resource_id: res_id,
resource_thread: res_thread,
}
}
}
/// A listener which is basically a wrapped optional receiver which looks
/// for the load cancellation message. Some of the loading processes always keep
/// an eye out for this message and stop loading stuff once they receive it.
pub struct CancellationListener {
/// We'll be needing the resources only if we plan to cancel it
cancel_resource: Option<CancellableResource>,
/// This lets us know whether the request has already been cancelled
cancel_status: Cell<bool>,
}
impl CancellationListener {
pub fn new(resources: Option<CancellableResource>) -> CancellationListener {
CancellationListener {
cancel_resource: resources,
cancel_status: Cell::new(false),
}
}
pub fn is_cancelled(&self) -> bool {
let resource = match self.cancel_resource {
Some(ref resource) => resource,
None => return false, // channel doesn't exist!
};
if resource.cancel_receiver.try_recv().is_ok() {
self.cancel_status.set(true);
true
} else {
self.cancel_status.get()
}
}
}
impl Drop for CancellationListener {
fn drop(&mut self) {
if let Some(ref resource) = self.cancel_resource {
// Ensure that the resource manager stops tracking this request now that it's terminated.
let _ = resource.resource_thread.send(CoreResourceMsg::Cancel(resource.resource_id));
}
}
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCacheEntry {
pub user_name: String,
pub password: String,
}
impl AuthCache {
pub fn new() -> AuthCache {
AuthCache {
version: 1,
entries: HashMap::new()
}
}
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCache {
pub version: u32,
pub entries: HashMap<Url, AuthCacheEntry>,
}
pub struct CoreResourceManager {
user_agent: String,
mime_classifier: Arc<MIMEClassifier>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan,
cancel_load_map: HashMap<ResourceId, Sender<()>>,
next_resource_id: ResourceId,
}
impl CoreResourceManager {
pub fn new(user_agent: String,
devtools_channel: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan) -> CoreResourceManager {
CoreResourceManager {
user_agent: user_agent,
mime_classifier: Arc::new(MIMEClassifier::new()),
devtools_chan: devtools_channel,
profiler_chan: profiler_chan,
cancel_load_map: HashMap::new(),
next_resource_id: ResourceId(0),
}
}
fn set_cookies_for_url(&mut self,
request: Url,
cookie_list: String,
source: CookieSource,
resource_group: &ResourceGroup) {
let header = Header::parse_header(&[cookie_list.into_bytes()]);
if let Ok(SetCookie(cookies)) = header {
for bare_cookie in cookies {
if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) {
let mut cookie_jar = resource_group.cookie_jar.write().unwrap();
cookie_jar.push(cookie, source);
}
}
}
}
fn load(&mut self,
load_data: LoadData,
consumer: LoadConsumer,
id_sender: Option<IpcSender<ResourceId>>,
resource_thread: CoreResourceThread,
resource_grp: &ResourceGroup) {
fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>, CancellationListener))
-> Box<FnBox(LoadData,
LoadConsumer,
Arc<MIMEClassifier>,
CancellationListener) + Send> {
box move |load_data, senders, classifier, cancel_listener| {
factory(load_data, senders, classifier, cancel_listener)
}
}
let cancel_resource = id_sender.map(|sender| {
let current_res_id = self.next_resource_id;
let _ = sender.send(current_res_id
|
CancellableResource
|
identifier_name
|
multi.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
/// Validator set changing at fork blocks.
use std::collections::BTreeMap;
use std::sync::Weak;
use bigint::hash::H256;
use parking_lot::RwLock;
use util::Address;
use bytes::Bytes;
use ids::BlockId;
use header::{BlockNumber, Header};
use client::EngineClient;
use machine::{AuxiliaryData, Call, EthereumMachine};
use super::{SystemCall, ValidatorSet};
type BlockNumberLookup = Box<Fn(BlockId) -> Result<BlockNumber, String> + Send + Sync +'static>;
|
sets: BTreeMap<BlockNumber, Box<ValidatorSet>>,
block_number: RwLock<BlockNumberLookup>,
}
impl Multi {
pub fn new(set_map: BTreeMap<BlockNumber, Box<ValidatorSet>>) -> Self {
assert!(set_map.get(&0u64).is_some(), "ValidatorSet has to be specified from block 0.");
Multi {
sets: set_map,
block_number: RwLock::new(Box::new(move |_| Err("No client!".into()))),
}
}
fn correct_set(&self, id: BlockId) -> Option<&ValidatorSet> {
match self.block_number.read()(id).map(|parent_block| self.correct_set_by_number(parent_block)) {
Ok((_, set)) => Some(set),
Err(e) => {
debug!(target: "engine", "ValidatorSet could not be recovered: {}", e);
None
},
}
}
// get correct set by block number, along with block number at which
// this set was activated.
fn correct_set_by_number(&self, parent_block: BlockNumber) -> (BlockNumber, &ValidatorSet) {
let (block, set) = self.sets.iter()
.rev()
.find(|&(block, _)| *block <= parent_block + 1)
.expect("constructor validation ensures that there is at least one validator set for block 0;
block 0 is less than any uint;
qed");
trace!(target: "engine", "Multi ValidatorSet retrieved for block {}.", block);
(*block, &**set)
}
}
impl ValidatorSet for Multi {
fn default_caller(&self, block_id: BlockId) -> Box<Call> {
self.correct_set(block_id).map(|set| set.default_caller(block_id))
.unwrap_or(Box::new(|_, _| Err("No validator set for given ID.".into())))
}
fn on_epoch_begin(&self, _first: bool, header: &Header, call: &mut SystemCall) -> Result<(), ::error::Error> {
let (set_block, set) = self.correct_set_by_number(header.number());
let first = set_block == header.number();
set.on_epoch_begin(first, header, call)
}
fn genesis_epoch_data(&self, header: &Header, call: &Call) -> Result<Vec<u8>, String> {
self.correct_set_by_number(0).1.genesis_epoch_data(header, call)
}
fn is_epoch_end(&self, _first: bool, chain_head: &Header) -> Option<Vec<u8>> {
let (set_block, set) = self.correct_set_by_number(chain_head.number());
let first = set_block == chain_head.number();
set.is_epoch_end(first, chain_head)
}
fn signals_epoch_end(&self, _first: bool, header: &Header, aux: AuxiliaryData)
-> ::engines::EpochChange<EthereumMachine>
{
let (set_block, set) = self.correct_set_by_number(header.number());
let first = set_block == header.number();
set.signals_epoch_end(first, header, aux)
}
fn epoch_set(&self, _first: bool, machine: &EthereumMachine, number: BlockNumber, proof: &[u8]) -> Result<(super::SimpleList, Option<H256>), ::error::Error> {
let (set_block, set) = self.correct_set_by_number(number);
let first = set_block == number;
set.epoch_set(first, machine, number, proof)
}
fn contains_with_caller(&self, bh: &H256, address: &Address, caller: &Call) -> bool {
self.correct_set(BlockId::Hash(*bh))
.map_or(false, |set| set.contains_with_caller(bh, address, caller))
}
fn get_with_caller(&self, bh: &H256, nonce: usize, caller: &Call) -> Address {
self.correct_set(BlockId::Hash(*bh))
.map_or_else(Default::default, |set| set.get_with_caller(bh, nonce, caller))
}
fn count_with_caller(&self, bh: &H256, caller: &Call) -> usize {
self.correct_set(BlockId::Hash(*bh))
.map_or_else(usize::max_value, |set| set.count_with_caller(bh, caller))
}
fn report_malicious(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber, proof: Bytes) {
self.correct_set_by_number(set_block).1.report_malicious(validator, set_block, block, proof);
}
fn report_benign(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber) {
self.correct_set_by_number(set_block).1.report_benign(validator, set_block, block);
}
fn register_client(&self, client: Weak<EngineClient>) {
for set in self.sets.values() {
set.register_client(client.clone());
}
*self.block_number.write() = Box::new(move |id| client
.upgrade()
.ok_or("No client!".into())
.and_then(|c| c.block_number(id).ok_or("Unknown block".into())));
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::collections::BTreeMap;
use hash::keccak;
use account_provider::AccountProvider;
use client::BlockChainClient;
use engines::EpochChange;
use engines::validator_set::ValidatorSet;
use ethkey::Secret;
use header::Header;
use miner::MinerService;
use spec::Spec;
use tests::helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
use types::ids::BlockId;
use util::*;
use super::Multi;
#[test]
fn uses_current_set() {
let tap = Arc::new(AccountProvider::transient_provider());
let s0: Secret = keccak("0").into();
let v0 = tap.insert_account(s0.clone(), "").unwrap();
let v1 = tap.insert_account(keccak("1").into(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_multi, Some(tap));
client.engine().register_client(Arc::downgrade(&client) as _);
// Make sure txs go through.
client.miner().set_gas_floor_target(1_000_000.into());
// Wrong signer for the first block.
client.miner().set_engine_signer(v1, "".into()).unwrap();
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 0);
// Right signer for the first block.
client.miner().set_engine_signer(v0, "".into()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 1);
// This time v0 is wrong.
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 1);
client.miner().set_engine_signer(v1, "".into()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 2);
// v1 is still good.
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 3);
// Check syncing.
let sync_client = generate_dummy_client_with_spec_and_data(Spec::new_validator_multi, 0, 0, &[]);
sync_client.engine().register_client(Arc::downgrade(&sync_client) as _);
for i in 1..4 {
sync_client.import_block(client.block(BlockId::Number(i)).unwrap().into_inner()).unwrap();
}
sync_client.flush_queue();
assert_eq!(sync_client.chain_info().best_block_number, 3);
}
#[test]
fn transition_to_fixed_list_instant() {
use super::super::SimpleList;
let mut map: BTreeMap<_, Box<ValidatorSet>> = BTreeMap::new();
let list1: Vec<_> = (0..10).map(|_| Address::random()).collect();
let list2 = {
let mut list = list1.clone();
list.push(Address::random());
list
};
map.insert(0, Box::new(SimpleList::new(list1)));
map.insert(500, Box::new(SimpleList::new(list2)));
let multi = Multi::new(map);
let mut header = Header::new();
header.set_number(499);
match multi.signals_epoch_end(false, &header, Default::default()) {
EpochChange::No => {},
_ => panic!("Expected no epoch signal change."),
}
assert!(multi.is_epoch_end(false, &header).is_none());
header.set_number(500);
match multi.signals_epoch_end(false, &header, Default::default()) {
EpochChange::No => {},
_ => panic!("Expected no epoch signal change."),
}
assert!(multi.is_epoch_end(false, &header).is_some());
}
}
|
pub struct Multi {
|
random_line_split
|
multi.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
/// Validator set changing at fork blocks.
use std::collections::BTreeMap;
use std::sync::Weak;
use bigint::hash::H256;
use parking_lot::RwLock;
use util::Address;
use bytes::Bytes;
use ids::BlockId;
use header::{BlockNumber, Header};
use client::EngineClient;
use machine::{AuxiliaryData, Call, EthereumMachine};
use super::{SystemCall, ValidatorSet};
type BlockNumberLookup = Box<Fn(BlockId) -> Result<BlockNumber, String> + Send + Sync +'static>;
pub struct Multi {
sets: BTreeMap<BlockNumber, Box<ValidatorSet>>,
block_number: RwLock<BlockNumberLookup>,
}
impl Multi {
pub fn new(set_map: BTreeMap<BlockNumber, Box<ValidatorSet>>) -> Self {
assert!(set_map.get(&0u64).is_some(), "ValidatorSet has to be specified from block 0.");
Multi {
sets: set_map,
block_number: RwLock::new(Box::new(move |_| Err("No client!".into()))),
}
}
fn correct_set(&self, id: BlockId) -> Option<&ValidatorSet> {
match self.block_number.read()(id).map(|parent_block| self.correct_set_by_number(parent_block)) {
Ok((_, set)) => Some(set),
Err(e) => {
debug!(target: "engine", "ValidatorSet could not be recovered: {}", e);
None
},
}
}
// get correct set by block number, along with block number at which
// this set was activated.
fn correct_set_by_number(&self, parent_block: BlockNumber) -> (BlockNumber, &ValidatorSet) {
let (block, set) = self.sets.iter()
.rev()
.find(|&(block, _)| *block <= parent_block + 1)
.expect("constructor validation ensures that there is at least one validator set for block 0;
block 0 is less than any uint;
qed");
trace!(target: "engine", "Multi ValidatorSet retrieved for block {}.", block);
(*block, &**set)
}
}
impl ValidatorSet for Multi {
fn default_caller(&self, block_id: BlockId) -> Box<Call> {
self.correct_set(block_id).map(|set| set.default_caller(block_id))
.unwrap_or(Box::new(|_, _| Err("No validator set for given ID.".into())))
}
fn on_epoch_begin(&self, _first: bool, header: &Header, call: &mut SystemCall) -> Result<(), ::error::Error> {
let (set_block, set) = self.correct_set_by_number(header.number());
let first = set_block == header.number();
set.on_epoch_begin(first, header, call)
}
fn
|
(&self, header: &Header, call: &Call) -> Result<Vec<u8>, String> {
self.correct_set_by_number(0).1.genesis_epoch_data(header, call)
}
fn is_epoch_end(&self, _first: bool, chain_head: &Header) -> Option<Vec<u8>> {
let (set_block, set) = self.correct_set_by_number(chain_head.number());
let first = set_block == chain_head.number();
set.is_epoch_end(first, chain_head)
}
fn signals_epoch_end(&self, _first: bool, header: &Header, aux: AuxiliaryData)
-> ::engines::EpochChange<EthereumMachine>
{
let (set_block, set) = self.correct_set_by_number(header.number());
let first = set_block == header.number();
set.signals_epoch_end(first, header, aux)
}
fn epoch_set(&self, _first: bool, machine: &EthereumMachine, number: BlockNumber, proof: &[u8]) -> Result<(super::SimpleList, Option<H256>), ::error::Error> {
let (set_block, set) = self.correct_set_by_number(number);
let first = set_block == number;
set.epoch_set(first, machine, number, proof)
}
fn contains_with_caller(&self, bh: &H256, address: &Address, caller: &Call) -> bool {
self.correct_set(BlockId::Hash(*bh))
.map_or(false, |set| set.contains_with_caller(bh, address, caller))
}
fn get_with_caller(&self, bh: &H256, nonce: usize, caller: &Call) -> Address {
self.correct_set(BlockId::Hash(*bh))
.map_or_else(Default::default, |set| set.get_with_caller(bh, nonce, caller))
}
fn count_with_caller(&self, bh: &H256, caller: &Call) -> usize {
self.correct_set(BlockId::Hash(*bh))
.map_or_else(usize::max_value, |set| set.count_with_caller(bh, caller))
}
fn report_malicious(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber, proof: Bytes) {
self.correct_set_by_number(set_block).1.report_malicious(validator, set_block, block, proof);
}
fn report_benign(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber) {
self.correct_set_by_number(set_block).1.report_benign(validator, set_block, block);
}
fn register_client(&self, client: Weak<EngineClient>) {
for set in self.sets.values() {
set.register_client(client.clone());
}
*self.block_number.write() = Box::new(move |id| client
.upgrade()
.ok_or("No client!".into())
.and_then(|c| c.block_number(id).ok_or("Unknown block".into())));
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::collections::BTreeMap;
use hash::keccak;
use account_provider::AccountProvider;
use client::BlockChainClient;
use engines::EpochChange;
use engines::validator_set::ValidatorSet;
use ethkey::Secret;
use header::Header;
use miner::MinerService;
use spec::Spec;
use tests::helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
use types::ids::BlockId;
use util::*;
use super::Multi;
#[test]
fn uses_current_set() {
let tap = Arc::new(AccountProvider::transient_provider());
let s0: Secret = keccak("0").into();
let v0 = tap.insert_account(s0.clone(), "").unwrap();
let v1 = tap.insert_account(keccak("1").into(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_multi, Some(tap));
client.engine().register_client(Arc::downgrade(&client) as _);
// Make sure txs go through.
client.miner().set_gas_floor_target(1_000_000.into());
// Wrong signer for the first block.
client.miner().set_engine_signer(v1, "".into()).unwrap();
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 0);
// Right signer for the first block.
client.miner().set_engine_signer(v0, "".into()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 1);
// This time v0 is wrong.
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 1);
client.miner().set_engine_signer(v1, "".into()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 2);
// v1 is still good.
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 3);
// Check syncing.
let sync_client = generate_dummy_client_with_spec_and_data(Spec::new_validator_multi, 0, 0, &[]);
sync_client.engine().register_client(Arc::downgrade(&sync_client) as _);
for i in 1..4 {
sync_client.import_block(client.block(BlockId::Number(i)).unwrap().into_inner()).unwrap();
}
sync_client.flush_queue();
assert_eq!(sync_client.chain_info().best_block_number, 3);
}
#[test]
fn transition_to_fixed_list_instant() {
use super::super::SimpleList;
let mut map: BTreeMap<_, Box<ValidatorSet>> = BTreeMap::new();
let list1: Vec<_> = (0..10).map(|_| Address::random()).collect();
let list2 = {
let mut list = list1.clone();
list.push(Address::random());
list
};
map.insert(0, Box::new(SimpleList::new(list1)));
map.insert(500, Box::new(SimpleList::new(list2)));
let multi = Multi::new(map);
let mut header = Header::new();
header.set_number(499);
match multi.signals_epoch_end(false, &header, Default::default()) {
EpochChange::No => {},
_ => panic!("Expected no epoch signal change."),
}
assert!(multi.is_epoch_end(false, &header).is_none());
header.set_number(500);
match multi.signals_epoch_end(false, &header, Default::default()) {
EpochChange::No => {},
_ => panic!("Expected no epoch signal change."),
}
assert!(multi.is_epoch_end(false, &header).is_some());
}
}
|
genesis_epoch_data
|
identifier_name
|
multi.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
/// Validator set changing at fork blocks.
use std::collections::BTreeMap;
use std::sync::Weak;
use bigint::hash::H256;
use parking_lot::RwLock;
use util::Address;
use bytes::Bytes;
use ids::BlockId;
use header::{BlockNumber, Header};
use client::EngineClient;
use machine::{AuxiliaryData, Call, EthereumMachine};
use super::{SystemCall, ValidatorSet};
type BlockNumberLookup = Box<Fn(BlockId) -> Result<BlockNumber, String> + Send + Sync +'static>;
pub struct Multi {
sets: BTreeMap<BlockNumber, Box<ValidatorSet>>,
block_number: RwLock<BlockNumberLookup>,
}
impl Multi {
pub fn new(set_map: BTreeMap<BlockNumber, Box<ValidatorSet>>) -> Self {
assert!(set_map.get(&0u64).is_some(), "ValidatorSet has to be specified from block 0.");
Multi {
sets: set_map,
block_number: RwLock::new(Box::new(move |_| Err("No client!".into()))),
}
}
fn correct_set(&self, id: BlockId) -> Option<&ValidatorSet> {
match self.block_number.read()(id).map(|parent_block| self.correct_set_by_number(parent_block)) {
Ok((_, set)) => Some(set),
Err(e) => {
debug!(target: "engine", "ValidatorSet could not be recovered: {}", e);
None
},
}
}
// get correct set by block number, along with block number at which
// this set was activated.
fn correct_set_by_number(&self, parent_block: BlockNumber) -> (BlockNumber, &ValidatorSet) {
let (block, set) = self.sets.iter()
.rev()
.find(|&(block, _)| *block <= parent_block + 1)
.expect("constructor validation ensures that there is at least one validator set for block 0;
block 0 is less than any uint;
qed");
trace!(target: "engine", "Multi ValidatorSet retrieved for block {}.", block);
(*block, &**set)
}
}
impl ValidatorSet for Multi {
fn default_caller(&self, block_id: BlockId) -> Box<Call> {
self.correct_set(block_id).map(|set| set.default_caller(block_id))
.unwrap_or(Box::new(|_, _| Err("No validator set for given ID.".into())))
}
fn on_epoch_begin(&self, _first: bool, header: &Header, call: &mut SystemCall) -> Result<(), ::error::Error> {
let (set_block, set) = self.correct_set_by_number(header.number());
let first = set_block == header.number();
set.on_epoch_begin(first, header, call)
}
fn genesis_epoch_data(&self, header: &Header, call: &Call) -> Result<Vec<u8>, String> {
self.correct_set_by_number(0).1.genesis_epoch_data(header, call)
}
fn is_epoch_end(&self, _first: bool, chain_head: &Header) -> Option<Vec<u8>> {
let (set_block, set) = self.correct_set_by_number(chain_head.number());
let first = set_block == chain_head.number();
set.is_epoch_end(first, chain_head)
}
fn signals_epoch_end(&self, _first: bool, header: &Header, aux: AuxiliaryData)
-> ::engines::EpochChange<EthereumMachine>
{
let (set_block, set) = self.correct_set_by_number(header.number());
let first = set_block == header.number();
set.signals_epoch_end(first, header, aux)
}
fn epoch_set(&self, _first: bool, machine: &EthereumMachine, number: BlockNumber, proof: &[u8]) -> Result<(super::SimpleList, Option<H256>), ::error::Error> {
let (set_block, set) = self.correct_set_by_number(number);
let first = set_block == number;
set.epoch_set(first, machine, number, proof)
}
fn contains_with_caller(&self, bh: &H256, address: &Address, caller: &Call) -> bool {
self.correct_set(BlockId::Hash(*bh))
.map_or(false, |set| set.contains_with_caller(bh, address, caller))
}
fn get_with_caller(&self, bh: &H256, nonce: usize, caller: &Call) -> Address
|
fn count_with_caller(&self, bh: &H256, caller: &Call) -> usize {
self.correct_set(BlockId::Hash(*bh))
.map_or_else(usize::max_value, |set| set.count_with_caller(bh, caller))
}
fn report_malicious(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber, proof: Bytes) {
self.correct_set_by_number(set_block).1.report_malicious(validator, set_block, block, proof);
}
fn report_benign(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber) {
self.correct_set_by_number(set_block).1.report_benign(validator, set_block, block);
}
fn register_client(&self, client: Weak<EngineClient>) {
for set in self.sets.values() {
set.register_client(client.clone());
}
*self.block_number.write() = Box::new(move |id| client
.upgrade()
.ok_or("No client!".into())
.and_then(|c| c.block_number(id).ok_or("Unknown block".into())));
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::collections::BTreeMap;
use hash::keccak;
use account_provider::AccountProvider;
use client::BlockChainClient;
use engines::EpochChange;
use engines::validator_set::ValidatorSet;
use ethkey::Secret;
use header::Header;
use miner::MinerService;
use spec::Spec;
use tests::helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
use types::ids::BlockId;
use util::*;
use super::Multi;
#[test]
fn uses_current_set() {
let tap = Arc::new(AccountProvider::transient_provider());
let s0: Secret = keccak("0").into();
let v0 = tap.insert_account(s0.clone(), "").unwrap();
let v1 = tap.insert_account(keccak("1").into(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_multi, Some(tap));
client.engine().register_client(Arc::downgrade(&client) as _);
// Make sure txs go through.
client.miner().set_gas_floor_target(1_000_000.into());
// Wrong signer for the first block.
client.miner().set_engine_signer(v1, "".into()).unwrap();
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 0);
// Right signer for the first block.
client.miner().set_engine_signer(v0, "".into()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 1);
// This time v0 is wrong.
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 1);
client.miner().set_engine_signer(v1, "".into()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 2);
// v1 is still good.
client.transact_contract(Default::default(), Default::default()).unwrap();
::client::EngineClient::update_sealing(&*client);
assert_eq!(client.chain_info().best_block_number, 3);
// Check syncing.
let sync_client = generate_dummy_client_with_spec_and_data(Spec::new_validator_multi, 0, 0, &[]);
sync_client.engine().register_client(Arc::downgrade(&sync_client) as _);
for i in 1..4 {
sync_client.import_block(client.block(BlockId::Number(i)).unwrap().into_inner()).unwrap();
}
sync_client.flush_queue();
assert_eq!(sync_client.chain_info().best_block_number, 3);
}
#[test]
fn transition_to_fixed_list_instant() {
use super::super::SimpleList;
let mut map: BTreeMap<_, Box<ValidatorSet>> = BTreeMap::new();
let list1: Vec<_> = (0..10).map(|_| Address::random()).collect();
let list2 = {
let mut list = list1.clone();
list.push(Address::random());
list
};
map.insert(0, Box::new(SimpleList::new(list1)));
map.insert(500, Box::new(SimpleList::new(list2)));
let multi = Multi::new(map);
let mut header = Header::new();
header.set_number(499);
match multi.signals_epoch_end(false, &header, Default::default()) {
EpochChange::No => {},
_ => panic!("Expected no epoch signal change."),
}
assert!(multi.is_epoch_end(false, &header).is_none());
header.set_number(500);
match multi.signals_epoch_end(false, &header, Default::default()) {
EpochChange::No => {},
_ => panic!("Expected no epoch signal change."),
}
assert!(multi.is_epoch_end(false, &header).is_some());
}
}
|
{
self.correct_set(BlockId::Hash(*bh))
.map_or_else(Default::default, |set| set.get_with_caller(bh, nonce, caller))
}
|
identifier_body
|
rlptraits.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Common RLP traits
use ::{DecoderError, UntrustedRlp};
use bytes::VecLike;
use rlpstream::RlpStream;
use elastic_array::ElasticArray1024;
/// Type is able to decode RLP.
pub trait Decoder: Sized {
/// Read a value from the RLP into a given type.
fn read_value<T, F>(&self, f: &F) -> Result<T, DecoderError>
where F: Fn(&[u8]) -> Result<T, DecoderError>;
/// Get underlying `UntrustedRLP` object.
fn as_rlp(&self) -> &UntrustedRlp;
/// Get underlying raw bytes slice.
fn as_raw(&self) -> &[u8];
}
/// RLP decodable trait
pub trait Decodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// Internal helper trait. Implement `Decodable` for custom types.
pub trait RlpDecodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// A view into RLP encoded data
pub trait View<'a, 'view>: Sized {
/// RLP prototype type
type Prototype;
/// Payload info type
type PayloadInfo;
/// Data type
type Data;
/// Item type
type Item;
/// Iterator type
type Iter;
/// Creates a new instance of `Rlp` reader
fn new(bytes: &'a [u8]) -> Self;
/// The raw data of the RLP as slice.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let dog = rlp.at(1).as_raw();
/// assert_eq!(dog, &[0x83, b'd', b'o', b'g']);
/// }
/// ```
fn as_raw(&'view self) -> &'a [u8];
/// Get the prototype of the RLP.
fn prototype(&self) -> Self::Prototype;
/// Get payload info.
fn payload_info(&self) -> Self::PayloadInfo;
/// Get underlieing data.
fn data(&'view self) -> Self::Data;
/// Returns number of RLP items.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.item_count(), 2);
/// let view = rlp.at(1);
/// assert_eq!(view.item_count(), 0);
/// }
/// ```
fn item_count(&self) -> usize;
/// Returns the number of bytes in the data, or zero if it isn't data.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.size(), 0);
/// let view = rlp.at(1);
/// assert_eq!(view.size(), 3);
/// }
/// ```
fn size(&self) -> usize;
/// Get view onto RLP-slice at index.
///
/// Caches offset to given index, so access to successive
/// slices is faster.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let dog: String = rlp.at(1).as_val();
/// assert_eq!(dog, "dog".to_string());
/// }
fn at(&'view self, index: usize) -> Self::Item;
/// No value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_null());
/// }
/// ```
fn is_null(&self) -> bool;
/// Contains a zero-length string or zero-length list.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc0];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_empty());
/// }
/// ```
fn is_empty(&self) -> bool;
/// List value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_list());
/// }
/// ```
fn is_list(&self) -> bool;
/// String value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.at(1).is_data());
/// }
/// ```
fn is_data(&self) -> bool;
/// Int value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc1, 0x10];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.is_int(), false);
/// assert_eq!(rlp.at(0).is_int(), true);
/// }
/// ```
fn is_int(&self) -> bool;
/// Get iterator over rlp-slices
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let strings: Vec<String> = rlp.iter().map(| i | i.as_val()).collect();
/// }
/// ```
fn iter(&'view self) -> Self::Iter;
/// Decode data into an object
fn as_val<T>(&self) -> Result<T, DecoderError> where T: RlpDecodable;
/// Decode data at given list index into an object
fn val_at<T>(&self, index: usize) -> Result<T, DecoderError> where T: RlpDecodable;
}
/// Raw RLP encoder
pub trait Encoder {
/// Write a value represented as bytes
fn emit_value<E: ByteEncodable>(&mut self, value: &E);
/// Write raw preencoded data to the output
fn emit_raw(&mut self, bytes: &[u8]) -> ();
}
/// Primitive data type encodable to RLP
pub trait ByteEncodable {
/// Serialize this object to given byte container
fn to_bytes<V: VecLike<u8>>(&self, out: &mut V);
/// Get size of serialised data in bytes
fn bytes_len(&self) -> usize;
}
/// Structure encodable to RLP. Implement this trait for
pub trait Encodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
/// Get rlp-encoded bytes for this instance
fn rlp_bytes(&self) -> ElasticArray1024<u8> {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
}
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
/// RLP encoding stream
pub trait Stream: Sized {
/// Initializes instance of empty `Stream`.
fn new() -> Self;
|
/// Apends value to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat").append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
/// ```
fn append<'a, E>(&'a mut self, value: &E) -> &'a mut Self where E: RlpEncodable;
/// Declare appending the list of given size, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.begin_list(2).append(&"cat").append(&"dog");
/// stream.append(&"");
/// let out = stream.out();
/// assert_eq!(out, vec![0xca, 0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g', 0x80]);
/// }
/// ```
fn begin_list(&mut self, len: usize) -> &mut Self;
/// Apends null to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append_empty_data().append_empty_data();
/// let out = stream.out();
/// assert_eq!(out, vec![0xc2, 0x80, 0x80]);
/// }
/// ```
fn append_empty_data(&mut self) -> &mut Self;
/// Appends raw (pre-serialised) RLP data. Use with caution. Chainable.
fn append_raw<'a>(&'a mut self, bytes: &[u8], item_count: usize) -> &'a mut Self;
/// Clear the output stream so far.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(3);
/// stream.append(&"cat");
/// stream.clear();
/// stream.append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0x83, b'd', b'o', b'g']);
/// }
fn clear(&mut self);
/// Returns true if stream doesnt expect any more items.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat");
/// assert_eq!(stream.is_finished(), false);
/// stream.append(&"dog");
/// assert_eq!(stream.is_finished(), true);
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
fn is_finished(&self) -> bool;
/// Get raw encoded bytes
fn as_raw(&self) -> &[u8];
/// Streams out encoded bytes.
///
/// panic! if stream is not finished.
fn out(self) -> Vec<u8>;
}
/// Trait for compressing and decompressing RLP by replacement of common terms.
pub trait Compressible: Sized {
/// Indicates the origin of RLP to be compressed.
type DataType;
/// Compress given RLP type using appropriate methods.
fn compress(&self, t: Self::DataType) -> ElasticArray1024<u8>;
/// Decompress given RLP type using appropriate methods.
fn decompress(&self, t: Self::DataType) -> ElasticArray1024<u8>;
}
|
/// Initializes the `Stream` as a list.
fn new_list(len: usize) -> Self;
|
random_line_split
|
rlptraits.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Common RLP traits
use ::{DecoderError, UntrustedRlp};
use bytes::VecLike;
use rlpstream::RlpStream;
use elastic_array::ElasticArray1024;
/// Type is able to decode RLP.
pub trait Decoder: Sized {
/// Read a value from the RLP into a given type.
fn read_value<T, F>(&self, f: &F) -> Result<T, DecoderError>
where F: Fn(&[u8]) -> Result<T, DecoderError>;
/// Get underlying `UntrustedRLP` object.
fn as_rlp(&self) -> &UntrustedRlp;
/// Get underlying raw bytes slice.
fn as_raw(&self) -> &[u8];
}
/// RLP decodable trait
pub trait Decodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// Internal helper trait. Implement `Decodable` for custom types.
pub trait RlpDecodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// A view into RLP encoded data
pub trait View<'a, 'view>: Sized {
/// RLP prototype type
type Prototype;
/// Payload info type
type PayloadInfo;
/// Data type
type Data;
/// Item type
type Item;
/// Iterator type
type Iter;
/// Creates a new instance of `Rlp` reader
fn new(bytes: &'a [u8]) -> Self;
/// The raw data of the RLP as slice.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let dog = rlp.at(1).as_raw();
/// assert_eq!(dog, &[0x83, b'd', b'o', b'g']);
/// }
/// ```
fn as_raw(&'view self) -> &'a [u8];
/// Get the prototype of the RLP.
fn prototype(&self) -> Self::Prototype;
/// Get payload info.
fn payload_info(&self) -> Self::PayloadInfo;
/// Get underlieing data.
fn data(&'view self) -> Self::Data;
/// Returns number of RLP items.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.item_count(), 2);
/// let view = rlp.at(1);
/// assert_eq!(view.item_count(), 0);
/// }
/// ```
fn item_count(&self) -> usize;
/// Returns the number of bytes in the data, or zero if it isn't data.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.size(), 0);
/// let view = rlp.at(1);
/// assert_eq!(view.size(), 3);
/// }
/// ```
fn size(&self) -> usize;
/// Get view onto RLP-slice at index.
///
/// Caches offset to given index, so access to successive
/// slices is faster.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let dog: String = rlp.at(1).as_val();
/// assert_eq!(dog, "dog".to_string());
/// }
fn at(&'view self, index: usize) -> Self::Item;
/// No value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_null());
/// }
/// ```
fn is_null(&self) -> bool;
/// Contains a zero-length string or zero-length list.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc0];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_empty());
/// }
/// ```
fn is_empty(&self) -> bool;
/// List value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_list());
/// }
/// ```
fn is_list(&self) -> bool;
/// String value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.at(1).is_data());
/// }
/// ```
fn is_data(&self) -> bool;
/// Int value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc1, 0x10];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.is_int(), false);
/// assert_eq!(rlp.at(0).is_int(), true);
/// }
/// ```
fn is_int(&self) -> bool;
/// Get iterator over rlp-slices
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let strings: Vec<String> = rlp.iter().map(| i | i.as_val()).collect();
/// }
/// ```
fn iter(&'view self) -> Self::Iter;
/// Decode data into an object
fn as_val<T>(&self) -> Result<T, DecoderError> where T: RlpDecodable;
/// Decode data at given list index into an object
fn val_at<T>(&self, index: usize) -> Result<T, DecoderError> where T: RlpDecodable;
}
/// Raw RLP encoder
pub trait Encoder {
/// Write a value represented as bytes
fn emit_value<E: ByteEncodable>(&mut self, value: &E);
/// Write raw preencoded data to the output
fn emit_raw(&mut self, bytes: &[u8]) -> ();
}
/// Primitive data type encodable to RLP
pub trait ByteEncodable {
/// Serialize this object to given byte container
fn to_bytes<V: VecLike<u8>>(&self, out: &mut V);
/// Get size of serialised data in bytes
fn bytes_len(&self) -> usize;
}
/// Structure encodable to RLP. Implement this trait for
pub trait Encodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
/// Get rlp-encoded bytes for this instance
fn
|
(&self) -> ElasticArray1024<u8> {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
}
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
/// RLP encoding stream
pub trait Stream: Sized {
/// Initializes instance of empty `Stream`.
fn new() -> Self;
/// Initializes the `Stream` as a list.
fn new_list(len: usize) -> Self;
/// Apends value to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat").append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
/// ```
fn append<'a, E>(&'a mut self, value: &E) -> &'a mut Self where E: RlpEncodable;
/// Declare appending the list of given size, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.begin_list(2).append(&"cat").append(&"dog");
/// stream.append(&"");
/// let out = stream.out();
/// assert_eq!(out, vec![0xca, 0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g', 0x80]);
/// }
/// ```
fn begin_list(&mut self, len: usize) -> &mut Self;
/// Apends null to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append_empty_data().append_empty_data();
/// let out = stream.out();
/// assert_eq!(out, vec![0xc2, 0x80, 0x80]);
/// }
/// ```
fn append_empty_data(&mut self) -> &mut Self;
/// Appends raw (pre-serialised) RLP data. Use with caution. Chainable.
fn append_raw<'a>(&'a mut self, bytes: &[u8], item_count: usize) -> &'a mut Self;
/// Clear the output stream so far.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(3);
/// stream.append(&"cat");
/// stream.clear();
/// stream.append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0x83, b'd', b'o', b'g']);
/// }
fn clear(&mut self);
/// Returns true if stream doesnt expect any more items.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat");
/// assert_eq!(stream.is_finished(), false);
/// stream.append(&"dog");
/// assert_eq!(stream.is_finished(), true);
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
fn is_finished(&self) -> bool;
/// Get raw encoded bytes
fn as_raw(&self) -> &[u8];
/// Streams out encoded bytes.
///
/// panic! if stream is not finished.
fn out(self) -> Vec<u8>;
}
/// Trait for compressing and decompressing RLP by replacement of common terms.
pub trait Compressible: Sized {
/// Indicates the origin of RLP to be compressed.
type DataType;
/// Compress given RLP type using appropriate methods.
fn compress(&self, t: Self::DataType) -> ElasticArray1024<u8>;
/// Decompress given RLP type using appropriate methods.
fn decompress(&self, t: Self::DataType) -> ElasticArray1024<u8>;
}
|
rlp_bytes
|
identifier_name
|
rlptraits.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Common RLP traits
use ::{DecoderError, UntrustedRlp};
use bytes::VecLike;
use rlpstream::RlpStream;
use elastic_array::ElasticArray1024;
/// Type is able to decode RLP.
pub trait Decoder: Sized {
/// Read a value from the RLP into a given type.
fn read_value<T, F>(&self, f: &F) -> Result<T, DecoderError>
where F: Fn(&[u8]) -> Result<T, DecoderError>;
/// Get underlying `UntrustedRLP` object.
fn as_rlp(&self) -> &UntrustedRlp;
/// Get underlying raw bytes slice.
fn as_raw(&self) -> &[u8];
}
/// RLP decodable trait
pub trait Decodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// Internal helper trait. Implement `Decodable` for custom types.
pub trait RlpDecodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// A view into RLP encoded data
pub trait View<'a, 'view>: Sized {
/// RLP prototype type
type Prototype;
/// Payload info type
type PayloadInfo;
/// Data type
type Data;
/// Item type
type Item;
/// Iterator type
type Iter;
/// Creates a new instance of `Rlp` reader
fn new(bytes: &'a [u8]) -> Self;
/// The raw data of the RLP as slice.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let dog = rlp.at(1).as_raw();
/// assert_eq!(dog, &[0x83, b'd', b'o', b'g']);
/// }
/// ```
fn as_raw(&'view self) -> &'a [u8];
/// Get the prototype of the RLP.
fn prototype(&self) -> Self::Prototype;
/// Get payload info.
fn payload_info(&self) -> Self::PayloadInfo;
/// Get underlieing data.
fn data(&'view self) -> Self::Data;
/// Returns number of RLP items.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.item_count(), 2);
/// let view = rlp.at(1);
/// assert_eq!(view.item_count(), 0);
/// }
/// ```
fn item_count(&self) -> usize;
/// Returns the number of bytes in the data, or zero if it isn't data.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.size(), 0);
/// let view = rlp.at(1);
/// assert_eq!(view.size(), 3);
/// }
/// ```
fn size(&self) -> usize;
/// Get view onto RLP-slice at index.
///
/// Caches offset to given index, so access to successive
/// slices is faster.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let dog: String = rlp.at(1).as_val();
/// assert_eq!(dog, "dog".to_string());
/// }
fn at(&'view self, index: usize) -> Self::Item;
/// No value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_null());
/// }
/// ```
fn is_null(&self) -> bool;
/// Contains a zero-length string or zero-length list.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc0];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_empty());
/// }
/// ```
fn is_empty(&self) -> bool;
/// List value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.is_list());
/// }
/// ```
fn is_list(&self) -> bool;
/// String value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// assert!(rlp.at(1).is_data());
/// }
/// ```
fn is_data(&self) -> bool;
/// Int value
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc1, 0x10];
/// let rlp = Rlp::new(&data);
/// assert_eq!(rlp.is_int(), false);
/// assert_eq!(rlp.at(0).is_int(), true);
/// }
/// ```
fn is_int(&self) -> bool;
/// Get iterator over rlp-slices
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let strings: Vec<String> = rlp.iter().map(| i | i.as_val()).collect();
/// }
/// ```
fn iter(&'view self) -> Self::Iter;
/// Decode data into an object
fn as_val<T>(&self) -> Result<T, DecoderError> where T: RlpDecodable;
/// Decode data at given list index into an object
fn val_at<T>(&self, index: usize) -> Result<T, DecoderError> where T: RlpDecodable;
}
/// Raw RLP encoder
pub trait Encoder {
/// Write a value represented as bytes
fn emit_value<E: ByteEncodable>(&mut self, value: &E);
/// Write raw preencoded data to the output
fn emit_raw(&mut self, bytes: &[u8]) -> ();
}
/// Primitive data type encodable to RLP
pub trait ByteEncodable {
/// Serialize this object to given byte container
fn to_bytes<V: VecLike<u8>>(&self, out: &mut V);
/// Get size of serialised data in bytes
fn bytes_len(&self) -> usize;
}
/// Structure encodable to RLP. Implement this trait for
pub trait Encodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
/// Get rlp-encoded bytes for this instance
fn rlp_bytes(&self) -> ElasticArray1024<u8>
|
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
/// RLP encoding stream
pub trait Stream: Sized {
/// Initializes instance of empty `Stream`.
fn new() -> Self;
/// Initializes the `Stream` as a list.
fn new_list(len: usize) -> Self;
/// Apends value to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat").append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
/// ```
fn append<'a, E>(&'a mut self, value: &E) -> &'a mut Self where E: RlpEncodable;
/// Declare appending the list of given size, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.begin_list(2).append(&"cat").append(&"dog");
/// stream.append(&"");
/// let out = stream.out();
/// assert_eq!(out, vec![0xca, 0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g', 0x80]);
/// }
/// ```
fn begin_list(&mut self, len: usize) -> &mut Self;
/// Apends null to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append_empty_data().append_empty_data();
/// let out = stream.out();
/// assert_eq!(out, vec![0xc2, 0x80, 0x80]);
/// }
/// ```
fn append_empty_data(&mut self) -> &mut Self;
/// Appends raw (pre-serialised) RLP data. Use with caution. Chainable.
fn append_raw<'a>(&'a mut self, bytes: &[u8], item_count: usize) -> &'a mut Self;
/// Clear the output stream so far.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(3);
/// stream.append(&"cat");
/// stream.clear();
/// stream.append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0x83, b'd', b'o', b'g']);
/// }
fn clear(&mut self);
/// Returns true if stream doesnt expect any more items.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat");
/// assert_eq!(stream.is_finished(), false);
/// stream.append(&"dog");
/// assert_eq!(stream.is_finished(), true);
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
fn is_finished(&self) -> bool;
/// Get raw encoded bytes
fn as_raw(&self) -> &[u8];
/// Streams out encoded bytes.
///
/// panic! if stream is not finished.
fn out(self) -> Vec<u8>;
}
/// Trait for compressing and decompressing RLP by replacement of common terms.
pub trait Compressible: Sized {
/// Indicates the origin of RLP to be compressed.
type DataType;
/// Compress given RLP type using appropriate methods.
fn compress(&self, t: Self::DataType) -> ElasticArray1024<u8>;
/// Decompress given RLP type using appropriate methods.
fn decompress(&self, t: Self::DataType) -> ElasticArray1024<u8>;
}
|
{
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
}
|
identifier_body
|
map3one.rs
|
use itertools::izip;
use mli::{Backward, Forward, Train};
use ndarray::{Array, Array3};
use num_traits::Zero;
use std::ops::Add;
#[derive(Clone, Debug)]
pub struct Map3One<G>(pub G);
impl<G> Forward for Map3One<G>
where
G: Forward,
{
type Input = Array3<G::Input>;
type Internal = Array3<G::Internal>;
type Output = Array3<G::Output>;
fn forward(&self, input: &Self::Input) -> (Self::Internal, Self::Output) {
let both = input.iter().map(|input| self.0.forward(input));
let (internal_vec, output_vec) = both.fold(
(vec![], vec![]),
|(mut internal_vec, mut output_vec), (internal, output)| {
internal_vec.push(internal);
output_vec.push(output);
(internal_vec, output_vec)
},
);
let internal_array = Array::from_shape_vec(input.raw_dim(), internal_vec).unwrap();
|
impl<G> Backward for Map3One<G>
where
G: Backward,
G::TrainDelta: Clone + Add + Zero,
{
type OutputDelta = Array3<G::OutputDelta>;
type InputDelta = Array3<G::InputDelta>;
type TrainDelta = G::TrainDelta;
fn backward(
&self,
input: &Self::Input,
internal: &Self::Internal,
output_delta: &Self::OutputDelta,
) -> (Self::InputDelta, Self::TrainDelta) {
let both = izip!(input.iter(), internal.iter(), output_delta.iter(),)
.map(|(input, internal, output_delta)| self.0.backward(input, internal, output_delta));
let (input_delta_vec, train_delta_vec) = both.fold(
(vec![], vec![]),
|(mut input_delta_vec, mut train_delta_vec), (input_delta, train_delta)| {
input_delta_vec.push(input_delta);
train_delta_vec.push(train_delta);
(input_delta_vec, train_delta_vec)
},
);
let input_delta_array = Array::from_shape_vec(input.raw_dim(), input_delta_vec).unwrap();
let train_delta_array = Array::from_shape_vec(input.raw_dim(), train_delta_vec).unwrap();
(input_delta_array, train_delta_array.sum())
}
}
impl<G> Train for Map3One<G>
where
G: Train,
G::TrainDelta: Clone + Add + Zero,
{
fn train(&mut self, train_delta: &Self::TrainDelta) {
self.0.train(train_delta);
}
}
|
let output_array = Array::from_shape_vec(input.raw_dim(), output_vec).unwrap();
(internal_array, output_array)
}
}
|
random_line_split
|
map3one.rs
|
use itertools::izip;
use mli::{Backward, Forward, Train};
use ndarray::{Array, Array3};
use num_traits::Zero;
use std::ops::Add;
#[derive(Clone, Debug)]
pub struct
|
<G>(pub G);
impl<G> Forward for Map3One<G>
where
G: Forward,
{
type Input = Array3<G::Input>;
type Internal = Array3<G::Internal>;
type Output = Array3<G::Output>;
fn forward(&self, input: &Self::Input) -> (Self::Internal, Self::Output) {
let both = input.iter().map(|input| self.0.forward(input));
let (internal_vec, output_vec) = both.fold(
(vec![], vec![]),
|(mut internal_vec, mut output_vec), (internal, output)| {
internal_vec.push(internal);
output_vec.push(output);
(internal_vec, output_vec)
},
);
let internal_array = Array::from_shape_vec(input.raw_dim(), internal_vec).unwrap();
let output_array = Array::from_shape_vec(input.raw_dim(), output_vec).unwrap();
(internal_array, output_array)
}
}
impl<G> Backward for Map3One<G>
where
G: Backward,
G::TrainDelta: Clone + Add + Zero,
{
type OutputDelta = Array3<G::OutputDelta>;
type InputDelta = Array3<G::InputDelta>;
type TrainDelta = G::TrainDelta;
fn backward(
&self,
input: &Self::Input,
internal: &Self::Internal,
output_delta: &Self::OutputDelta,
) -> (Self::InputDelta, Self::TrainDelta) {
let both = izip!(input.iter(), internal.iter(), output_delta.iter(),)
.map(|(input, internal, output_delta)| self.0.backward(input, internal, output_delta));
let (input_delta_vec, train_delta_vec) = both.fold(
(vec![], vec![]),
|(mut input_delta_vec, mut train_delta_vec), (input_delta, train_delta)| {
input_delta_vec.push(input_delta);
train_delta_vec.push(train_delta);
(input_delta_vec, train_delta_vec)
},
);
let input_delta_array = Array::from_shape_vec(input.raw_dim(), input_delta_vec).unwrap();
let train_delta_array = Array::from_shape_vec(input.raw_dim(), train_delta_vec).unwrap();
(input_delta_array, train_delta_array.sum())
}
}
impl<G> Train for Map3One<G>
where
G: Train,
G::TrainDelta: Clone + Add + Zero,
{
fn train(&mut self, train_delta: &Self::TrainDelta) {
self.0.train(train_delta);
}
}
|
Map3One
|
identifier_name
|
map3one.rs
|
use itertools::izip;
use mli::{Backward, Forward, Train};
use ndarray::{Array, Array3};
use num_traits::Zero;
use std::ops::Add;
#[derive(Clone, Debug)]
pub struct Map3One<G>(pub G);
impl<G> Forward for Map3One<G>
where
G: Forward,
{
type Input = Array3<G::Input>;
type Internal = Array3<G::Internal>;
type Output = Array3<G::Output>;
fn forward(&self, input: &Self::Input) -> (Self::Internal, Self::Output) {
let both = input.iter().map(|input| self.0.forward(input));
let (internal_vec, output_vec) = both.fold(
(vec![], vec![]),
|(mut internal_vec, mut output_vec), (internal, output)| {
internal_vec.push(internal);
output_vec.push(output);
(internal_vec, output_vec)
},
);
let internal_array = Array::from_shape_vec(input.raw_dim(), internal_vec).unwrap();
let output_array = Array::from_shape_vec(input.raw_dim(), output_vec).unwrap();
(internal_array, output_array)
}
}
impl<G> Backward for Map3One<G>
where
G: Backward,
G::TrainDelta: Clone + Add + Zero,
{
type OutputDelta = Array3<G::OutputDelta>;
type InputDelta = Array3<G::InputDelta>;
type TrainDelta = G::TrainDelta;
fn backward(
&self,
input: &Self::Input,
internal: &Self::Internal,
output_delta: &Self::OutputDelta,
) -> (Self::InputDelta, Self::TrainDelta) {
let both = izip!(input.iter(), internal.iter(), output_delta.iter(),)
.map(|(input, internal, output_delta)| self.0.backward(input, internal, output_delta));
let (input_delta_vec, train_delta_vec) = both.fold(
(vec![], vec![]),
|(mut input_delta_vec, mut train_delta_vec), (input_delta, train_delta)| {
input_delta_vec.push(input_delta);
train_delta_vec.push(train_delta);
(input_delta_vec, train_delta_vec)
},
);
let input_delta_array = Array::from_shape_vec(input.raw_dim(), input_delta_vec).unwrap();
let train_delta_array = Array::from_shape_vec(input.raw_dim(), train_delta_vec).unwrap();
(input_delta_array, train_delta_array.sum())
}
}
impl<G> Train for Map3One<G>
where
G: Train,
G::TrainDelta: Clone + Add + Zero,
{
fn train(&mut self, train_delta: &Self::TrainDelta)
|
}
|
{
self.0.train(train_delta);
}
|
identifier_body
|
thread.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/.
//! Multi-threading
//!
//! = Examples
//!
//! ----
//! let mut array = [1u8; 1024];
//! {
//! let res = scoped(|| {
//! println!("getting to work");
//! for i in 0..SIZE {
//! array[i] = 2;
//! }
//! println!("done working");
//! });
//! println!("joining");
//! res.unwrap();
//! println!("joined");
//! }
|
//! for i in 0..SIZE {
//! assert!(array[i] == 2);
//! }
//! ----
pub use lrs_thread::{
Builder, spawn, scoped, JoinGuard, cpu_count, CpuMask, cpus, set_cpus, unshare,
current_cpu, join_namespace, thread_id, exit, deschedule, enter_strict_mode,
at_exit,
};
pub use lrs_thread::ids::{
UserIds, GroupIds, drop_user_privileges, drop_group_privileges, set_effective_user_id,
set_effective_group_id, num_supplementary_groups, supplementary_groups,
set_supplementary_groups
};
pub use lrs_thread::sched::{
Scheduler, SchedFlags, SchedAttr, set_scheduler, scheduler, process_niceness,
group_niceness, user_niceness, set_process_niceness, set_group_niceness,
set_user_niceness,
};
pub use lrs_thread::cap::{
Capability, CapSet, capabilities, set_capabilities, has_bounding_cap,
drop_bounding_cap, keeps_caps, set_keeps_caps,
};
pub mod flags {
pub use lrs_thread::sched::{
SCHED_NONE, SCHED_RESET_ON_FORK,
};
}
pub mod sched {
pub use lrs_thread::sched::{
Normal, Fifo, Rr, Batch, Idle, Deadline,
};
}
pub mod capability {
pub use lrs_thread::cap::{
ChangeOwner, ReadWriteExecute, ReadSearch, FileOwner, FileSetId, SendSignals,
SetGroupIds, SetUserIds, SetCapabilities, ImmutableFile, PrivilegedPorts, Network,
RawSockets, LockMemory, IpcOwner, KernelModules, RawIo, ChangeRoot, Trace,
Accounting, Admin, Reboot, Scheduling, Resources, Clock, Tty, DeviceFiles, Lease,
AuditWrite, AuditControl, FileCapabilities, MacOverride, MacAdmin, Syslog, Wakeup,
BlockSuspend, AuditRead,
};
}
|
random_line_split
|
|
borrowck-uniq-via-lend.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.
fn borrow(_v: &int) {}
fn local() {
let mut v = box 3i;
borrow(&*v);
}
fn local_rec() {
struct F { f: Box<int> }
let mut v = F {f: box 3};
borrow(&*v.f);
}
fn local_recs() {
struct F { f: G }
struct G { g: H }
struct H { h: Box<int> }
let mut v = F {f: G {g: H {h: box 3}}};
borrow(&*v.f.g.h);
}
fn aliased_imm() {
let mut v = box 3i;
let _w = &v;
borrow(&*v);
}
fn aliased_mut() {
let mut v = box 3i;
let _w = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn aliased_other() {
let mut v = box 3i;
let mut w = box 4i;
let _x = &mut w;
borrow(&*v);
}
fn aliased_other_reassign() {
let mut v = box 3i;
let mut w = box 4i;
let mut _x = &mut w;
_x = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn main()
|
{
}
|
identifier_body
|
|
borrowck-uniq-via-lend.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.
fn borrow(_v: &int) {}
fn local() {
let mut v = box 3i;
borrow(&*v);
}
fn local_rec() {
struct F { f: Box<int> }
let mut v = F {f: box 3};
borrow(&*v.f);
}
fn local_recs() {
struct F { f: G }
struct
|
{ g: H }
struct H { h: Box<int> }
let mut v = F {f: G {g: H {h: box 3}}};
borrow(&*v.f.g.h);
}
fn aliased_imm() {
let mut v = box 3i;
let _w = &v;
borrow(&*v);
}
fn aliased_mut() {
let mut v = box 3i;
let _w = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn aliased_other() {
let mut v = box 3i;
let mut w = box 4i;
let _x = &mut w;
borrow(&*v);
}
fn aliased_other_reassign() {
let mut v = box 3i;
let mut w = box 4i;
let mut _x = &mut w;
_x = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn main() {
}
|
G
|
identifier_name
|
borrowck-uniq-via-lend.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.
fn borrow(_v: &int) {}
fn local() {
let mut v = box 3i;
borrow(&*v);
}
fn local_rec() {
struct F { f: Box<int> }
let mut v = F {f: box 3};
|
struct G { g: H }
struct H { h: Box<int> }
let mut v = F {f: G {g: H {h: box 3}}};
borrow(&*v.f.g.h);
}
fn aliased_imm() {
let mut v = box 3i;
let _w = &v;
borrow(&*v);
}
fn aliased_mut() {
let mut v = box 3i;
let _w = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn aliased_other() {
let mut v = box 3i;
let mut w = box 4i;
let _x = &mut w;
borrow(&*v);
}
fn aliased_other_reassign() {
let mut v = box 3i;
let mut w = box 4i;
let mut _x = &mut w;
_x = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn main() {
}
|
borrow(&*v.f);
}
fn local_recs() {
struct F { f: G }
|
random_line_split
|
distinct.rs
|
use std::collections::{HashMap, HashSet};
use std::collections::hash_state::DefaultState;
use std::hash::{hash, Hash, SipHasher};
use std::default::Default;
use communication::Data;
use communication::pact::Exchange;
use construction::{Stream, GraphBuilder};
use construction::operators::unary::UnaryNotifyExt;
use serialization::Serializable;
pub trait DistinctExtensionTrait {
fn distinct(&self) -> Self;
fn distinct_batch(&self) -> Self;
}
impl<G: GraphBuilder, D: Data+Hash+Eq+Serializable> DistinctExtensionTrait for Stream<G, D>
where G::Timestamp: Hash {
fn
|
(&self) -> Stream<G, D> {
let mut elements: HashMap<_, HashSet<_, DefaultState<SipHasher>>> = HashMap::new();
let exch = Exchange::new(|x| hash::<_,SipHasher>(&x));
self.unary_notify(exch, "Distinct", vec![], move |input, output, notificator| {
while let Some((time, data)) = input.pull() {
let set = elements.entry(time).or_insert(Default::default());
let mut session = output.session(&time);
for datum in data.drain(..) {
if set.insert(datum.clone()) {
session.give(datum);
}
}
notificator.notify_at(&time);
}
while let Some((time, _count)) = notificator.next() {
elements.remove(&time);
}
})
}
fn distinct_batch(&self) -> Stream<G, D> {
let mut elements: HashMap<_, HashSet<_, DefaultState<SipHasher>>> = HashMap::new();
let exch = Exchange::new(|x| hash::<_,SipHasher>(&x));
self.unary_notify(exch, "DistinctBlock", vec![], move |input, output, notificator| {
while let Some((time, data)) = input.pull() {
let set = elements.entry(time).or_insert(Default::default());
for datum in data.drain(..) { set.insert(datum); }
notificator.notify_at(&time);
}
while let Some((time, _count)) = notificator.next() {
if let Some(mut data) = elements.remove(&time) {
output.give_at(&time, data.drain());
}
}
})
}
}
|
distinct
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.