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 |
---|---|---|---|---|
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are text digits
/// that give the total number of bytes
/// in the Lyrics3 v2.00 tag field.
const LYRICS3V2_SIZE: i64 = 6;
/// Checks whether ape tag exists
pub fn probe_ape<R: Read + Seek>(reader: &mut R, pos: SeekFrom) -> Result<bool> {
let capacity = APE_PREAMBLE.len();
let mut preamble = Vec::<u8>::with_capacity(capacity);
reader.seek(pos)?;
reader.take(capacity as u64).read_to_end(&mut preamble)?;
Ok(preamble == APE_PREAMBLE)
}
/// Whether ID3v1 tag exists
pub fn probe_id3v1<R: Read + Seek>(reader: &mut R) -> Result<bool> |
/// Returns the size of the Lyrics3 v2.00 tag or -1 if the tag does not exists.
/// See http://id3.org/Lyrics3v2 for more details.
pub fn probe_lyrics3v2<R: Read + Seek>(reader: &mut R) -> Result<i64> {
let capacity = LYRICS3V2_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET - capacity as i64))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
reader.seek(SeekFrom::Current(0 - capacity as i64))?;
if header == LYRICS3V2_HEADER {
let mut buf = Vec::<u8>::with_capacity(LYRICS3V2_SIZE as usize);
reader.seek(SeekFrom::Current(-LYRICS3V2_SIZE))?;
reader.take(LYRICS3V2_SIZE as u64).read_to_end(&mut buf)?;
let raw_size = str::from_utf8(&buf)?;
let int_size = raw_size.parse::<i64>()?;
Ok(int_size + LYRICS3V2_SIZE + capacity as i64)
} else {
Ok(-1)
}
}
| {
let capacity = ID3V1_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
Ok(header == ID3V1_HEADER)
} | identifier_body |
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are text digits
/// that give the total number of bytes
/// in the Lyrics3 v2.00 tag field.
const LYRICS3V2_SIZE: i64 = 6;
/// Checks whether ape tag exists
pub fn probe_ape<R: Read + Seek>(reader: &mut R, pos: SeekFrom) -> Result<bool> {
let capacity = APE_PREAMBLE.len();
let mut preamble = Vec::<u8>::with_capacity(capacity);
reader.seek(pos)?;
reader.take(capacity as u64).read_to_end(&mut preamble)?;
Ok(preamble == APE_PREAMBLE)
}
/// Whether ID3v1 tag exists
pub fn probe_id3v1<R: Read + Seek>(reader: &mut R) -> Result<bool> {
let capacity = ID3V1_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
Ok(header == ID3V1_HEADER)
}
/// Returns the size of the Lyrics3 v2.00 tag or -1 if the tag does not exists.
/// See http://id3.org/Lyrics3v2 for more details.
pub fn probe_lyrics3v2<R: Read + Seek>(reader: &mut R) -> Result<i64> {
let capacity = LYRICS3V2_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET - capacity as i64))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
reader.seek(SeekFrom::Current(0 - capacity as i64))?;
if header == LYRICS3V2_HEADER {
let mut buf = Vec::<u8>::with_capacity(LYRICS3V2_SIZE as usize);
reader.seek(SeekFrom::Current(-LYRICS3V2_SIZE))?; | Ok(int_size + LYRICS3V2_SIZE + capacity as i64)
} else {
Ok(-1)
}
} | reader.take(LYRICS3V2_SIZE as u64).read_to_end(&mut buf)?;
let raw_size = str::from_utf8(&buf)?;
let int_size = raw_size.parse::<i64>()?; | random_line_split |
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are text digits
/// that give the total number of bytes
/// in the Lyrics3 v2.00 tag field.
const LYRICS3V2_SIZE: i64 = 6;
/// Checks whether ape tag exists
pub fn | <R: Read + Seek>(reader: &mut R, pos: SeekFrom) -> Result<bool> {
let capacity = APE_PREAMBLE.len();
let mut preamble = Vec::<u8>::with_capacity(capacity);
reader.seek(pos)?;
reader.take(capacity as u64).read_to_end(&mut preamble)?;
Ok(preamble == APE_PREAMBLE)
}
/// Whether ID3v1 tag exists
pub fn probe_id3v1<R: Read + Seek>(reader: &mut R) -> Result<bool> {
let capacity = ID3V1_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
Ok(header == ID3V1_HEADER)
}
/// Returns the size of the Lyrics3 v2.00 tag or -1 if the tag does not exists.
/// See http://id3.org/Lyrics3v2 for more details.
pub fn probe_lyrics3v2<R: Read + Seek>(reader: &mut R) -> Result<i64> {
let capacity = LYRICS3V2_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET - capacity as i64))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
reader.seek(SeekFrom::Current(0 - capacity as i64))?;
if header == LYRICS3V2_HEADER {
let mut buf = Vec::<u8>::with_capacity(LYRICS3V2_SIZE as usize);
reader.seek(SeekFrom::Current(-LYRICS3V2_SIZE))?;
reader.take(LYRICS3V2_SIZE as u64).read_to_end(&mut buf)?;
let raw_size = str::from_utf8(&buf)?;
let int_size = raw_size.parse::<i64>()?;
Ok(int_size + LYRICS3V2_SIZE + capacity as i64)
} else {
Ok(-1)
}
}
| probe_ape | identifier_name |
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are text digits
/// that give the total number of bytes
/// in the Lyrics3 v2.00 tag field.
const LYRICS3V2_SIZE: i64 = 6;
/// Checks whether ape tag exists
pub fn probe_ape<R: Read + Seek>(reader: &mut R, pos: SeekFrom) -> Result<bool> {
let capacity = APE_PREAMBLE.len();
let mut preamble = Vec::<u8>::with_capacity(capacity);
reader.seek(pos)?;
reader.take(capacity as u64).read_to_end(&mut preamble)?;
Ok(preamble == APE_PREAMBLE)
}
/// Whether ID3v1 tag exists
pub fn probe_id3v1<R: Read + Seek>(reader: &mut R) -> Result<bool> {
let capacity = ID3V1_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
Ok(header == ID3V1_HEADER)
}
/// Returns the size of the Lyrics3 v2.00 tag or -1 if the tag does not exists.
/// See http://id3.org/Lyrics3v2 for more details.
pub fn probe_lyrics3v2<R: Read + Seek>(reader: &mut R) -> Result<i64> {
let capacity = LYRICS3V2_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET - capacity as i64))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
reader.seek(SeekFrom::Current(0 - capacity as i64))?;
if header == LYRICS3V2_HEADER | else {
Ok(-1)
}
}
| {
let mut buf = Vec::<u8>::with_capacity(LYRICS3V2_SIZE as usize);
reader.seek(SeekFrom::Current(-LYRICS3V2_SIZE))?;
reader.take(LYRICS3V2_SIZE as u64).read_to_end(&mut buf)?;
let raw_size = str::from_utf8(&buf)?;
let int_size = raw_size.parse::<i64>()?;
Ok(int_size + LYRICS3V2_SIZE + capacity as i64)
} | conditional_block |
lexical-scope-in-match.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$1 = 231
// gdb-command:print not_shadowed
// gdb-check:$2 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$3 = 233
// gdb-command:print not_shadowed
// gdb-check:$4 = 232
// gdb-command:print local_to_arm
// gdb-check:$5 = 234
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$6 = 236
// gdb-command:print not_shadowed
// gdb-check:$7 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$8 = 237
// gdb-command:print not_shadowed
// gdb-check:$9 = 232
// gdb-command:print local_to_arm
// gdb-check:$10 = 238
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$11 = 239
// gdb-command:print not_shadowed
// gdb-check:$12 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$13 = 241
// gdb-command:print not_shadowed
// gdb-check:$14 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$15 = 243
// gdb-command:print *local_to_arm
// gdb-check:$16 = 244
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$17 = 231
// gdb-command:print not_shadowed
// gdb-check:$18 = 232
// gdb-command:continue
struct Struct {
x: int,
y: int
}
fn | () {
let shadowed = 231;
let not_shadowed = 232;
zzz();
sentinel();
match (233, 234) {
(shadowed, local_to_arm) => {
zzz();
sentinel();
}
}
match (235, 236) {
// with literal
(235, shadowed) => {
zzz();
sentinel();
}
_ => {}
}
match Struct { x: 237, y: 238 } {
Struct { x: shadowed, y: local_to_arm } => {
zzz();
sentinel();
}
}
match Struct { x: 239, y: 240 } {
// ignored field
Struct { x: shadowed,.. } => {
zzz();
sentinel();
}
}
match Struct { x: 241, y: 242 } {
// with literal
Struct { x: shadowed, y: 242 } => {
zzz();
sentinel();
}
_ => {}
}
match (243, 244) {
(shadowed, ref local_to_arm) => {
zzz();
sentinel();
}
}
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()}
| main | identifier_name |
lexical-scope-in-match.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$1 = 231
// gdb-command:print not_shadowed
// gdb-check:$2 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$3 = 233
// gdb-command:print not_shadowed
// gdb-check:$4 = 232
// gdb-command:print local_to_arm
// gdb-check:$5 = 234
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$6 = 236
// gdb-command:print not_shadowed
// gdb-check:$7 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$8 = 237
// gdb-command:print not_shadowed
// gdb-check:$9 = 232
// gdb-command:print local_to_arm
// gdb-check:$10 = 238
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$11 = 239
// gdb-command:print not_shadowed
// gdb-check:$12 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$13 = 241
// gdb-command:print not_shadowed
// gdb-check:$14 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$15 = 243
// gdb-command:print *local_to_arm
// gdb-check:$16 = 244
// gdb-command:continue | // gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$17 = 231
// gdb-command:print not_shadowed
// gdb-check:$18 = 232
// gdb-command:continue
struct Struct {
x: int,
y: int
}
fn main() {
let shadowed = 231;
let not_shadowed = 232;
zzz();
sentinel();
match (233, 234) {
(shadowed, local_to_arm) => {
zzz();
sentinel();
}
}
match (235, 236) {
// with literal
(235, shadowed) => {
zzz();
sentinel();
}
_ => {}
}
match Struct { x: 237, y: 238 } {
Struct { x: shadowed, y: local_to_arm } => {
zzz();
sentinel();
}
}
match Struct { x: 239, y: 240 } {
// ignored field
Struct { x: shadowed,.. } => {
zzz();
sentinel();
}
}
match Struct { x: 241, y: 242 } {
// with literal
Struct { x: shadowed, y: 242 } => {
zzz();
sentinel();
}
_ => {}
}
match (243, 244) {
(shadowed, ref local_to_arm) => {
zzz();
sentinel();
}
}
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()} | random_line_split |
|
lexical-scope-in-match.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$1 = 231
// gdb-command:print not_shadowed
// gdb-check:$2 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$3 = 233
// gdb-command:print not_shadowed
// gdb-check:$4 = 232
// gdb-command:print local_to_arm
// gdb-check:$5 = 234
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$6 = 236
// gdb-command:print not_shadowed
// gdb-check:$7 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$8 = 237
// gdb-command:print not_shadowed
// gdb-check:$9 = 232
// gdb-command:print local_to_arm
// gdb-check:$10 = 238
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$11 = 239
// gdb-command:print not_shadowed
// gdb-check:$12 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$13 = 241
// gdb-command:print not_shadowed
// gdb-check:$14 = 232
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$15 = 243
// gdb-command:print *local_to_arm
// gdb-check:$16 = 244
// gdb-command:continue
// gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$17 = 231
// gdb-command:print not_shadowed
// gdb-check:$18 = 232
// gdb-command:continue
struct Struct {
x: int,
y: int
}
fn main() {
let shadowed = 231;
let not_shadowed = 232;
zzz();
sentinel();
match (233, 234) {
(shadowed, local_to_arm) => {
zzz();
sentinel();
}
}
match (235, 236) {
// with literal
(235, shadowed) => {
zzz();
sentinel();
}
_ => {}
}
match Struct { x: 237, y: 238 } {
Struct { x: shadowed, y: local_to_arm } => {
zzz();
sentinel();
}
}
match Struct { x: 239, y: 240 } {
// ignored field
Struct { x: shadowed,.. } => {
zzz();
sentinel();
}
}
match Struct { x: 241, y: 242 } {
// with literal
Struct { x: shadowed, y: 242 } => {
zzz();
sentinel();
}
_ => {}
}
match (243, 244) {
(shadowed, ref local_to_arm) => {
zzz();
sentinel();
}
}
zzz();
sentinel();
}
fn zzz() |
fn sentinel() {()}
| {()} | identifier_body |
mut-in-ident-patterns.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
fn foo(&self, mut x: int) -> int {
let val = x;
x = 37 * x;
val + x
}
}
struct X;
impl Foo for X {}
pub fn | () {
let (a, mut b) = (23i, 4i);
assert_eq!(a, 23);
assert_eq!(b, 4);
b = a + b;
assert_eq!(b, 27);
assert_eq!(X.foo(2), 76);
enum Bar {
Foo(int),
Baz(f32, u8)
}
let (x, mut y) = (32i, Bar::Foo(21));
match x {
mut z @ 32 => {
assert_eq!(z, 32);
z = 34;
assert_eq!(z, 34);
}
_ => {}
}
check_bar(&y);
y = Bar::Baz(10.0, 3);
check_bar(&y);
fn check_bar(y: &Bar) {
match y {
&Bar::Foo(a) => {
assert_eq!(a, 21);
}
&Bar::Baz(a, b) => {
assert_eq!(a, 10.0);
assert_eq!(b, 3);
}
}
}
fn foo1((x, mut y): (f64, int), mut z: int) -> int {
y = 2 * 6;
z = y + (x as int);
y - z
}
struct A {
x: int
}
let A { x: mut x } = A { x: 10 };
assert_eq!(x, 10);
x = 30;
assert_eq!(x, 30);
(|&: A { x: mut t }: A| { t = t+1; t })(A { x: 34 });
}
| main | identifier_name |
mut-in-ident-patterns.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
fn foo(&self, mut x: int) -> int {
let val = x;
x = 37 * x; | impl Foo for X {}
pub fn main() {
let (a, mut b) = (23i, 4i);
assert_eq!(a, 23);
assert_eq!(b, 4);
b = a + b;
assert_eq!(b, 27);
assert_eq!(X.foo(2), 76);
enum Bar {
Foo(int),
Baz(f32, u8)
}
let (x, mut y) = (32i, Bar::Foo(21));
match x {
mut z @ 32 => {
assert_eq!(z, 32);
z = 34;
assert_eq!(z, 34);
}
_ => {}
}
check_bar(&y);
y = Bar::Baz(10.0, 3);
check_bar(&y);
fn check_bar(y: &Bar) {
match y {
&Bar::Foo(a) => {
assert_eq!(a, 21);
}
&Bar::Baz(a, b) => {
assert_eq!(a, 10.0);
assert_eq!(b, 3);
}
}
}
fn foo1((x, mut y): (f64, int), mut z: int) -> int {
y = 2 * 6;
z = y + (x as int);
y - z
}
struct A {
x: int
}
let A { x: mut x } = A { x: 10 };
assert_eq!(x, 10);
x = 30;
assert_eq!(x, 30);
(|&: A { x: mut t }: A| { t = t+1; t })(A { x: 34 });
} | val + x
}
}
struct X; | random_line_split |
mut-in-ident-patterns.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
fn foo(&self, mut x: int) -> int {
let val = x;
x = 37 * x;
val + x
}
}
struct X;
impl Foo for X {}
pub fn main() {
let (a, mut b) = (23i, 4i);
assert_eq!(a, 23);
assert_eq!(b, 4);
b = a + b;
assert_eq!(b, 27);
assert_eq!(X.foo(2), 76);
enum Bar {
Foo(int),
Baz(f32, u8)
}
let (x, mut y) = (32i, Bar::Foo(21));
match x {
mut z @ 32 => |
_ => {}
}
check_bar(&y);
y = Bar::Baz(10.0, 3);
check_bar(&y);
fn check_bar(y: &Bar) {
match y {
&Bar::Foo(a) => {
assert_eq!(a, 21);
}
&Bar::Baz(a, b) => {
assert_eq!(a, 10.0);
assert_eq!(b, 3);
}
}
}
fn foo1((x, mut y): (f64, int), mut z: int) -> int {
y = 2 * 6;
z = y + (x as int);
y - z
}
struct A {
x: int
}
let A { x: mut x } = A { x: 10 };
assert_eq!(x, 10);
x = 30;
assert_eq!(x, 30);
(|&: A { x: mut t }: A| { t = t+1; t })(A { x: 34 });
}
| {
assert_eq!(z, 32);
z = 34;
assert_eq!(z, 34);
} | conditional_block |
fxrstor.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
|
fn fxrstor_2() {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(IndirectScaledIndexedDisplaced(EDI, EDX, Two, 1303234622, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 140, 87, 62, 200, 173, 77], OperandSize::Dword)
}
fn fxrstor_3() {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(IndirectScaledIndexedDisplaced(RBX, RDI, Eight, 468169493, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 140, 251, 21, 179, 231, 27], OperandSize::Qword)
} | fn fxrstor_1() {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(Indirect(DI, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 13], OperandSize::Word)
} | random_line_split |
fxrstor.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(Indirect(DI, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 13], OperandSize::Word)
}
fn fxrstor_2() {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(IndirectScaledIndexedDisplaced(EDI, EDX, Two, 1303234622, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 140, 87, 62, 200, 173, 77], OperandSize::Dword)
}
fn fxrstor_3() {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(IndirectScaledIndexedDisplaced(RBX, RDI, Eight, 468169493, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 140, 251, 21, 179, 231, 27], OperandSize::Qword)
}
| fxrstor_1 | identifier_name |
fxrstor.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn fxrstor_1() {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(Indirect(DI, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 13], OperandSize::Word)
}
fn fxrstor_2() {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(IndirectScaledIndexedDisplaced(EDI, EDX, Two, 1303234622, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 140, 87, 62, 200, 173, 77], OperandSize::Dword)
}
fn fxrstor_3() | {
run_test(&Instruction { mnemonic: Mnemonic::FXRSTOR, operand1: Some(IndirectScaledIndexedDisplaced(RBX, RDI, Eight, 468169493, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 174, 140, 251, 21, 179, 231, 27], OperandSize::Qword)
} | identifier_body |
|
axis.rs | // Copyright 2016 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cmp::Ordering;
/// An axis index.
///
/// An axis one of an array’s “dimensions”; an *n*-dimensional array has *n* axes.
/// Axis *0* is the array’s outermost axis and *n*-1 is the innermost.
///
/// All array axis arguments use this type to make the code easier to write
/// correctly and easier to understand.
#[derive(Eq, Ord, Hash, Debug)]
pub struct Axis(pub | ze);
impl Axis {
/// Return the index of the axis.
#[inline(always)]
pub fn index(&self) -> usize { self.0 }
#[deprecated(note = "Renamed to.index()")]
#[inline(always)]
pub fn axis(&self) -> usize { self.0 }
}
copy_and_clone!{Axis}
macro_rules! derive_cmp {
($traitname:ident for $typename:ident, $method:ident -> $ret:ty) => {
impl $traitname for $typename {
#[inline(always)]
fn $method(&self, rhs: &Self) -> $ret {
(self.0).$method(&rhs.0)
}
}
}
}
derive_cmp!{PartialEq for Axis, eq -> bool}
derive_cmp!{PartialOrd for Axis, partial_cmp -> Option<Ordering>}
| usi | identifier_name |
axis.rs | // Copyright 2016 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cmp::Ordering;
/// An axis index.
///
/// An axis one of an array’s “dimensions”; an *n*-dimensional array has *n* axes. | /// correctly and easier to understand.
#[derive(Eq, Ord, Hash, Debug)]
pub struct Axis(pub usize);
impl Axis {
/// Return the index of the axis.
#[inline(always)]
pub fn index(&self) -> usize { self.0 }
#[deprecated(note = "Renamed to.index()")]
#[inline(always)]
pub fn axis(&self) -> usize { self.0 }
}
copy_and_clone!{Axis}
macro_rules! derive_cmp {
($traitname:ident for $typename:ident, $method:ident -> $ret:ty) => {
impl $traitname for $typename {
#[inline(always)]
fn $method(&self, rhs: &Self) -> $ret {
(self.0).$method(&rhs.0)
}
}
}
}
derive_cmp!{PartialEq for Axis, eq -> bool}
derive_cmp!{PartialOrd for Axis, partial_cmp -> Option<Ordering>} | /// Axis *0* is the array’s outermost axis and *n*-1 is the innermost.
///
/// All array axis arguments use this type to make the code easier to write | random_line_split |
dpar-print-transitions.rs | use std::env::args;
use std::io::{BufRead, BufWriter, Write};
use std::process;
use colored::*;
use conllx::{DisplaySentence, HeadProjectivizer, Projectivize, ReadSentence};
use dpar::guide::Guide;
use dpar::system::{sentence_to_dependencies, ParserState, Transition, TransitionSystem};
use dpar::systems::{
ArcEagerSystem, ArcHybridSystem, ArcStandardSystem, StackProjectiveSystem, StackSwapSystem,
};
use failure::Error;
use getopts::Options;
use stdinout::{Input, OrExit, Output};
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] SYSTEM [INPUT]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
let matches = opts.parse(&args[1..]).or_exit("Cannot parse options", 1);
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if matches.free.is_empty() || matches.free.len() > 3 {
print_usage(&program, opts);
return;
}
let input = Input::from(matches.free.get(1));
let reader = conllx::Reader::new(input.buf_read().or_exit("Cannot open treebank", 1));
let output = Output::from(matches.free.get(2));
let writer = BufWriter::new(output.write().or_exit("Cannot create transition output", 1));
parse(&matches.free[0], reader, writer).or_exit("Cannot print transitions", 1);
}
fn parse<R, W>(system: &str, reader: conllx::Reader<R>, writer: BufWriter<W>) -> Result<(), Error>
where
R: BufRead,
W: Write,
{
match system {
"arceager" => parse_with_system::<R, W, ArcEagerSystem>(reader, writer),
"archybrid" => parse_with_system::<R, W, ArcHybridSystem>(reader, writer),
"arcstandard" => parse_with_system::<R, W, ArcStandardSystem>(reader, writer),
"stackproj" => parse_with_system::<R, W, StackProjectiveSystem>(reader, writer),
"stackswap" => parse_with_system::<R, W, StackSwapSystem>(reader, writer),
_ => {
eprintln!("Unsupported transition system: {}", system);
process::exit(1);
}
}
}
fn parse_with_system<R, W, S>(
reader: conllx::Reader<R>,
mut writer: BufWriter<W>,
) -> Result<(), Error>
where
R: BufRead,
W: Write,
S: TransitionSystem,
{
let projectivizer = HeadProjectivizer::new();
for sentence in reader.sentences() {
let sentence = projectivizer.projectivize(&sentence?)?;
let gold_dependencies = sentence_to_dependencies(&sentence).or_exit(
format!(
"Cannot extract gold dependencies:\n{}",
DisplaySentence(&sentence)
),
1,
);
let mut oracle = S::oracle(&gold_dependencies);
let mut state = ParserState::new(&sentence);
// Print initial state.
print_tokens(&mut writer, &state, Source::Stack)?; | while!S::is_terminal(&state) {
let next_transition = oracle.best_transition(&state);
next_transition.apply(&mut state);
// Print transition and state.
writeln!(writer, "{}", format!("{:?}", next_transition).purple())?;
print_tokens(&mut writer, &state, Source::Stack)?;
print_tokens(&mut writer, &state, Source::Buffer)?;
}
}
Ok(())
}
enum Source {
Buffer,
Stack,
}
fn print_tokens<W>(writer: &mut W, state: &ParserState<'_>, source: Source) -> Result<(), Error>
where
W: Write,
{
let prefix = match source {
Source::Buffer => "Buffer",
Source::Stack => "Stack",
};
let indices = match source {
Source::Buffer => state.buffer(),
Source::Stack => state.stack(),
};
writeln!(
writer,
"{}: {}",
prefix,
indices
.iter()
.map(|&idx| state.tokens()[idx])
.collect::<Vec<_>>()
.join(", ")
)?;
Ok(())
} | print_tokens(&mut writer, &state, Source::Buffer)?;
| random_line_split |
dpar-print-transitions.rs | use std::env::args;
use std::io::{BufRead, BufWriter, Write};
use std::process;
use colored::*;
use conllx::{DisplaySentence, HeadProjectivizer, Projectivize, ReadSentence};
use dpar::guide::Guide;
use dpar::system::{sentence_to_dependencies, ParserState, Transition, TransitionSystem};
use dpar::systems::{
ArcEagerSystem, ArcHybridSystem, ArcStandardSystem, StackProjectiveSystem, StackSwapSystem,
};
use failure::Error;
use getopts::Options;
use stdinout::{Input, OrExit, Output};
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] SYSTEM [INPUT]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
let matches = opts.parse(&args[1..]).or_exit("Cannot parse options", 1);
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if matches.free.is_empty() || matches.free.len() > 3 {
print_usage(&program, opts);
return;
}
let input = Input::from(matches.free.get(1));
let reader = conllx::Reader::new(input.buf_read().or_exit("Cannot open treebank", 1));
let output = Output::from(matches.free.get(2));
let writer = BufWriter::new(output.write().or_exit("Cannot create transition output", 1));
parse(&matches.free[0], reader, writer).or_exit("Cannot print transitions", 1);
}
fn parse<R, W>(system: &str, reader: conllx::Reader<R>, writer: BufWriter<W>) -> Result<(), Error>
where
R: BufRead,
W: Write,
{
match system {
"arceager" => parse_with_system::<R, W, ArcEagerSystem>(reader, writer),
"archybrid" => parse_with_system::<R, W, ArcHybridSystem>(reader, writer),
"arcstandard" => parse_with_system::<R, W, ArcStandardSystem>(reader, writer),
"stackproj" => parse_with_system::<R, W, StackProjectiveSystem>(reader, writer),
"stackswap" => parse_with_system::<R, W, StackSwapSystem>(reader, writer),
_ => {
eprintln!("Unsupported transition system: {}", system);
process::exit(1);
}
}
}
fn parse_with_system<R, W, S>(
reader: conllx::Reader<R>,
mut writer: BufWriter<W>,
) -> Result<(), Error>
where
R: BufRead,
W: Write,
S: TransitionSystem,
{
let projectivizer = HeadProjectivizer::new();
for sentence in reader.sentences() {
let sentence = projectivizer.projectivize(&sentence?)?;
let gold_dependencies = sentence_to_dependencies(&sentence).or_exit(
format!(
"Cannot extract gold dependencies:\n{}",
DisplaySentence(&sentence)
),
1,
);
let mut oracle = S::oracle(&gold_dependencies);
let mut state = ParserState::new(&sentence);
// Print initial state.
print_tokens(&mut writer, &state, Source::Stack)?;
print_tokens(&mut writer, &state, Source::Buffer)?;
while!S::is_terminal(&state) {
let next_transition = oracle.best_transition(&state);
next_transition.apply(&mut state);
// Print transition and state.
writeln!(writer, "{}", format!("{:?}", next_transition).purple())?;
print_tokens(&mut writer, &state, Source::Stack)?;
print_tokens(&mut writer, &state, Source::Buffer)?;
}
}
Ok(())
}
enum Source {
Buffer,
Stack,
}
fn | <W>(writer: &mut W, state: &ParserState<'_>, source: Source) -> Result<(), Error>
where
W: Write,
{
let prefix = match source {
Source::Buffer => "Buffer",
Source::Stack => "Stack",
};
let indices = match source {
Source::Buffer => state.buffer(),
Source::Stack => state.stack(),
};
writeln!(
writer,
"{}: {}",
prefix,
indices
.iter()
.map(|&idx| state.tokens()[idx])
.collect::<Vec<_>>()
.join(", ")
)?;
Ok(())
}
| print_tokens | identifier_name |
dpar-print-transitions.rs | use std::env::args;
use std::io::{BufRead, BufWriter, Write};
use std::process;
use colored::*;
use conllx::{DisplaySentence, HeadProjectivizer, Projectivize, ReadSentence};
use dpar::guide::Guide;
use dpar::system::{sentence_to_dependencies, ParserState, Transition, TransitionSystem};
use dpar::systems::{
ArcEagerSystem, ArcHybridSystem, ArcStandardSystem, StackProjectiveSystem, StackSwapSystem,
};
use failure::Error;
use getopts::Options;
use stdinout::{Input, OrExit, Output};
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] SYSTEM [INPUT]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
let matches = opts.parse(&args[1..]).or_exit("Cannot parse options", 1);
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if matches.free.is_empty() || matches.free.len() > 3 |
let input = Input::from(matches.free.get(1));
let reader = conllx::Reader::new(input.buf_read().or_exit("Cannot open treebank", 1));
let output = Output::from(matches.free.get(2));
let writer = BufWriter::new(output.write().or_exit("Cannot create transition output", 1));
parse(&matches.free[0], reader, writer).or_exit("Cannot print transitions", 1);
}
fn parse<R, W>(system: &str, reader: conllx::Reader<R>, writer: BufWriter<W>) -> Result<(), Error>
where
R: BufRead,
W: Write,
{
match system {
"arceager" => parse_with_system::<R, W, ArcEagerSystem>(reader, writer),
"archybrid" => parse_with_system::<R, W, ArcHybridSystem>(reader, writer),
"arcstandard" => parse_with_system::<R, W, ArcStandardSystem>(reader, writer),
"stackproj" => parse_with_system::<R, W, StackProjectiveSystem>(reader, writer),
"stackswap" => parse_with_system::<R, W, StackSwapSystem>(reader, writer),
_ => {
eprintln!("Unsupported transition system: {}", system);
process::exit(1);
}
}
}
fn parse_with_system<R, W, S>(
reader: conllx::Reader<R>,
mut writer: BufWriter<W>,
) -> Result<(), Error>
where
R: BufRead,
W: Write,
S: TransitionSystem,
{
let projectivizer = HeadProjectivizer::new();
for sentence in reader.sentences() {
let sentence = projectivizer.projectivize(&sentence?)?;
let gold_dependencies = sentence_to_dependencies(&sentence).or_exit(
format!(
"Cannot extract gold dependencies:\n{}",
DisplaySentence(&sentence)
),
1,
);
let mut oracle = S::oracle(&gold_dependencies);
let mut state = ParserState::new(&sentence);
// Print initial state.
print_tokens(&mut writer, &state, Source::Stack)?;
print_tokens(&mut writer, &state, Source::Buffer)?;
while!S::is_terminal(&state) {
let next_transition = oracle.best_transition(&state);
next_transition.apply(&mut state);
// Print transition and state.
writeln!(writer, "{}", format!("{:?}", next_transition).purple())?;
print_tokens(&mut writer, &state, Source::Stack)?;
print_tokens(&mut writer, &state, Source::Buffer)?;
}
}
Ok(())
}
enum Source {
Buffer,
Stack,
}
fn print_tokens<W>(writer: &mut W, state: &ParserState<'_>, source: Source) -> Result<(), Error>
where
W: Write,
{
let prefix = match source {
Source::Buffer => "Buffer",
Source::Stack => "Stack",
};
let indices = match source {
Source::Buffer => state.buffer(),
Source::Stack => state.stack(),
};
writeln!(
writer,
"{}: {}",
prefix,
indices
.iter()
.map(|&idx| state.tokens()[idx])
.collect::<Vec<_>>()
.join(", ")
)?;
Ok(())
}
| {
print_usage(&program, opts);
return;
} | conditional_block |
dpar-print-transitions.rs | use std::env::args;
use std::io::{BufRead, BufWriter, Write};
use std::process;
use colored::*;
use conllx::{DisplaySentence, HeadProjectivizer, Projectivize, ReadSentence};
use dpar::guide::Guide;
use dpar::system::{sentence_to_dependencies, ParserState, Transition, TransitionSystem};
use dpar::systems::{
ArcEagerSystem, ArcHybridSystem, ArcStandardSystem, StackProjectiveSystem, StackSwapSystem,
};
use failure::Error;
use getopts::Options;
use stdinout::{Input, OrExit, Output};
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] SYSTEM [INPUT]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
let matches = opts.parse(&args[1..]).or_exit("Cannot parse options", 1);
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
if matches.free.is_empty() || matches.free.len() > 3 {
print_usage(&program, opts);
return;
}
let input = Input::from(matches.free.get(1));
let reader = conllx::Reader::new(input.buf_read().or_exit("Cannot open treebank", 1));
let output = Output::from(matches.free.get(2));
let writer = BufWriter::new(output.write().or_exit("Cannot create transition output", 1));
parse(&matches.free[0], reader, writer).or_exit("Cannot print transitions", 1);
}
fn parse<R, W>(system: &str, reader: conllx::Reader<R>, writer: BufWriter<W>) -> Result<(), Error>
where
R: BufRead,
W: Write,
|
fn parse_with_system<R, W, S>(
reader: conllx::Reader<R>,
mut writer: BufWriter<W>,
) -> Result<(), Error>
where
R: BufRead,
W: Write,
S: TransitionSystem,
{
let projectivizer = HeadProjectivizer::new();
for sentence in reader.sentences() {
let sentence = projectivizer.projectivize(&sentence?)?;
let gold_dependencies = sentence_to_dependencies(&sentence).or_exit(
format!(
"Cannot extract gold dependencies:\n{}",
DisplaySentence(&sentence)
),
1,
);
let mut oracle = S::oracle(&gold_dependencies);
let mut state = ParserState::new(&sentence);
// Print initial state.
print_tokens(&mut writer, &state, Source::Stack)?;
print_tokens(&mut writer, &state, Source::Buffer)?;
while!S::is_terminal(&state) {
let next_transition = oracle.best_transition(&state);
next_transition.apply(&mut state);
// Print transition and state.
writeln!(writer, "{}", format!("{:?}", next_transition).purple())?;
print_tokens(&mut writer, &state, Source::Stack)?;
print_tokens(&mut writer, &state, Source::Buffer)?;
}
}
Ok(())
}
enum Source {
Buffer,
Stack,
}
fn print_tokens<W>(writer: &mut W, state: &ParserState<'_>, source: Source) -> Result<(), Error>
where
W: Write,
{
let prefix = match source {
Source::Buffer => "Buffer",
Source::Stack => "Stack",
};
let indices = match source {
Source::Buffer => state.buffer(),
Source::Stack => state.stack(),
};
writeln!(
writer,
"{}: {}",
prefix,
indices
.iter()
.map(|&idx| state.tokens()[idx])
.collect::<Vec<_>>()
.join(", ")
)?;
Ok(())
}
| {
match system {
"arceager" => parse_with_system::<R, W, ArcEagerSystem>(reader, writer),
"archybrid" => parse_with_system::<R, W, ArcHybridSystem>(reader, writer),
"arcstandard" => parse_with_system::<R, W, ArcStandardSystem>(reader, writer),
"stackproj" => parse_with_system::<R, W, StackProjectiveSystem>(reader, writer),
"stackswap" => parse_with_system::<R, W, StackSwapSystem>(reader, writer),
_ => {
eprintln!("Unsupported transition system: {}", system);
process::exit(1);
}
}
} | identifier_body |
player.rs | use crate::{
entity::{Character, Entity, EntityId, EntityPersistence, EntityRef, EntityType, StatsItem},
entity_copy_prop, entity_string_prop,
sessions::SignUpData,
};
use pbkdf2::{pbkdf2_check, pbkdf2_simple};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Player {
#[serde(skip)]
id: EntityId,
#[serde(flatten)]
pub character: Character,
description: String,
#[serde(default)]
is_admin: bool,
name: String,
#[serde(skip)]
needs_sync: bool,
password: String,
#[serde(skip)]
session_id: Option<u64>,
#[serde(flatten)]
stats_item: StatsItem,
}
impl Player {
entity_copy_prop!(pub, is_admin, set_is_admin, bool);
entity_copy_prop!(
pub,
session_id,
set_session_id,
Option<u64>,
EntityPersistence::DontSync
);
pub fn hydrate(id: EntityId, json: &str) -> Result<Box<dyn Entity>, String> |
pub fn matches_password(&self, password: &str) -> bool {
matches!(pbkdf2_check(password, &self.password), Ok(()))
}
pub fn new(id: EntityId, sign_up_data: &SignUpData) -> Self {
let character = Character::from_sign_up_data(sign_up_data);
Self {
id,
character,
description: String::new(),
is_admin: false,
name: sign_up_data.user_name.clone(),
needs_sync: true,
password: match pbkdf2_simple(&sign_up_data.password, 10) {
Ok(password) => password,
Err(error) => panic!("Cannot create password hash: {:?}", error),
},
session_id: None,
stats_item: StatsItem::from_stats(sign_up_data.stats.clone()),
}
}
pub fn set_password(&mut self, password: &str) {
match pbkdf2_simple(password, 10) {
Ok(password) => {
self.password = password;
self.set_needs_sync(true);
}
Err(error) => panic!("Cannot create password hash: {:?}", error),
}
}
}
impl Entity for Player {
entity_string_prop!(name, set_name);
entity_string_prop!(description, set_description);
fn as_character(&self) -> Option<&Character> {
Some(&self.character)
}
fn as_character_mut(&mut self) -> Option<&mut Character> {
Some(&mut self.character)
}
fn as_player(&self) -> Option<&Self> {
Some(self)
}
fn as_player_mut(&mut self) -> Option<&mut Self> {
Some(self)
}
fn dehydrate(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_else(|error| {
panic!(
"Failed to serialize entity {:?}: {:?}",
self.entity_ref(),
error
)
})
}
fn entity_ref(&self) -> EntityRef {
EntityRef::new(EntityType::Player, self.id)
}
fn id(&self) -> EntityId {
self.id
}
fn needs_sync(&self) -> bool {
self.needs_sync || self.character.needs_sync() || self.stats_item.needs_sync()
}
fn set_needs_sync(&mut self, needs_sync: bool) {
self.needs_sync = needs_sync;
if!needs_sync {
self.character.set_needs_sync(needs_sync);
self.stats_item.set_needs_sync(needs_sync);
}
}
fn set_property(&mut self, prop_name: &str, value: &str) -> Result<(), String> {
match prop_name {
"description" => self.set_description(value.to_owned()),
"isAdmin" => self.set_is_admin(value == "true"),
"name" => self.set_name(value.to_owned()),
"password" => self.set_password(value),
_ => {
return self
.character
.set_property(prop_name, value)
.or_else(|_| self.stats_item.set_property(prop_name, value))
}
}
Ok(())
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
| {
let mut player = serde_json::from_str::<Player>(json)
.map_err(|error| format!("parse error: {}", error))?;
player.id = id;
Ok(Box::new(player))
} | identifier_body |
player.rs | use crate::{
entity::{Character, Entity, EntityId, EntityPersistence, EntityRef, EntityType, StatsItem},
entity_copy_prop, entity_string_prop,
sessions::SignUpData,
};
use pbkdf2::{pbkdf2_check, pbkdf2_simple};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Player {
#[serde(skip)]
id: EntityId,
#[serde(flatten)]
pub character: Character,
description: String,
#[serde(default)]
is_admin: bool,
name: String,
#[serde(skip)]
needs_sync: bool,
password: String,
#[serde(skip)]
session_id: Option<u64>,
#[serde(flatten)]
stats_item: StatsItem,
}
impl Player {
entity_copy_prop!(pub, is_admin, set_is_admin, bool);
entity_copy_prop!(
pub,
session_id,
set_session_id,
Option<u64>,
EntityPersistence::DontSync
);
pub fn hydrate(id: EntityId, json: &str) -> Result<Box<dyn Entity>, String> {
let mut player = serde_json::from_str::<Player>(json)
.map_err(|error| format!("parse error: {}", error))?;
player.id = id;
Ok(Box::new(player))
}
pub fn matches_password(&self, password: &str) -> bool {
matches!(pbkdf2_check(password, &self.password), Ok(()))
}
pub fn new(id: EntityId, sign_up_data: &SignUpData) -> Self {
let character = Character::from_sign_up_data(sign_up_data);
Self {
id,
character,
description: String::new(),
is_admin: false,
name: sign_up_data.user_name.clone(),
needs_sync: true,
password: match pbkdf2_simple(&sign_up_data.password, 10) {
Ok(password) => password,
Err(error) => panic!("Cannot create password hash: {:?}", error),
},
session_id: None,
stats_item: StatsItem::from_stats(sign_up_data.stats.clone()),
}
}
pub fn | (&mut self, password: &str) {
match pbkdf2_simple(password, 10) {
Ok(password) => {
self.password = password;
self.set_needs_sync(true);
}
Err(error) => panic!("Cannot create password hash: {:?}", error),
}
}
}
impl Entity for Player {
entity_string_prop!(name, set_name);
entity_string_prop!(description, set_description);
fn as_character(&self) -> Option<&Character> {
Some(&self.character)
}
fn as_character_mut(&mut self) -> Option<&mut Character> {
Some(&mut self.character)
}
fn as_player(&self) -> Option<&Self> {
Some(self)
}
fn as_player_mut(&mut self) -> Option<&mut Self> {
Some(self)
}
fn dehydrate(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_else(|error| {
panic!(
"Failed to serialize entity {:?}: {:?}",
self.entity_ref(),
error
)
})
}
fn entity_ref(&self) -> EntityRef {
EntityRef::new(EntityType::Player, self.id)
}
fn id(&self) -> EntityId {
self.id
}
fn needs_sync(&self) -> bool {
self.needs_sync || self.character.needs_sync() || self.stats_item.needs_sync()
}
fn set_needs_sync(&mut self, needs_sync: bool) {
self.needs_sync = needs_sync;
if!needs_sync {
self.character.set_needs_sync(needs_sync);
self.stats_item.set_needs_sync(needs_sync);
}
}
fn set_property(&mut self, prop_name: &str, value: &str) -> Result<(), String> {
match prop_name {
"description" => self.set_description(value.to_owned()),
"isAdmin" => self.set_is_admin(value == "true"),
"name" => self.set_name(value.to_owned()),
"password" => self.set_password(value),
_ => {
return self
.character
.set_property(prop_name, value)
.or_else(|_| self.stats_item.set_property(prop_name, value))
}
}
Ok(())
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
| set_password | identifier_name |
player.rs | use crate::{
entity::{Character, Entity, EntityId, EntityPersistence, EntityRef, EntityType, StatsItem},
entity_copy_prop, entity_string_prop,
sessions::SignUpData,
};
use pbkdf2::{pbkdf2_check, pbkdf2_simple};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Player {
#[serde(skip)]
id: EntityId,
#[serde(flatten)]
pub character: Character,
description: String,
#[serde(default)]
is_admin: bool,
name: String,
#[serde(skip)]
needs_sync: bool,
password: String,
#[serde(skip)]
session_id: Option<u64>,
#[serde(flatten)]
stats_item: StatsItem,
}
impl Player {
entity_copy_prop!(pub, is_admin, set_is_admin, bool);
entity_copy_prop!(
pub,
session_id,
set_session_id,
Option<u64>,
EntityPersistence::DontSync
);
pub fn hydrate(id: EntityId, json: &str) -> Result<Box<dyn Entity>, String> {
let mut player = serde_json::from_str::<Player>(json)
.map_err(|error| format!("parse error: {}", error))?;
player.id = id;
Ok(Box::new(player))
}
pub fn matches_password(&self, password: &str) -> bool {
matches!(pbkdf2_check(password, &self.password), Ok(()))
}
pub fn new(id: EntityId, sign_up_data: &SignUpData) -> Self {
let character = Character::from_sign_up_data(sign_up_data);
Self {
id,
character,
description: String::new(),
is_admin: false,
name: sign_up_data.user_name.clone(),
needs_sync: true,
password: match pbkdf2_simple(&sign_up_data.password, 10) {
Ok(password) => password,
Err(error) => panic!("Cannot create password hash: {:?}", error),
},
session_id: None,
stats_item: StatsItem::from_stats(sign_up_data.stats.clone()),
}
}
pub fn set_password(&mut self, password: &str) {
match pbkdf2_simple(password, 10) {
Ok(password) => {
self.password = password; | }
}
impl Entity for Player {
entity_string_prop!(name, set_name);
entity_string_prop!(description, set_description);
fn as_character(&self) -> Option<&Character> {
Some(&self.character)
}
fn as_character_mut(&mut self) -> Option<&mut Character> {
Some(&mut self.character)
}
fn as_player(&self) -> Option<&Self> {
Some(self)
}
fn as_player_mut(&mut self) -> Option<&mut Self> {
Some(self)
}
fn dehydrate(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_else(|error| {
panic!(
"Failed to serialize entity {:?}: {:?}",
self.entity_ref(),
error
)
})
}
fn entity_ref(&self) -> EntityRef {
EntityRef::new(EntityType::Player, self.id)
}
fn id(&self) -> EntityId {
self.id
}
fn needs_sync(&self) -> bool {
self.needs_sync || self.character.needs_sync() || self.stats_item.needs_sync()
}
fn set_needs_sync(&mut self, needs_sync: bool) {
self.needs_sync = needs_sync;
if!needs_sync {
self.character.set_needs_sync(needs_sync);
self.stats_item.set_needs_sync(needs_sync);
}
}
fn set_property(&mut self, prop_name: &str, value: &str) -> Result<(), String> {
match prop_name {
"description" => self.set_description(value.to_owned()),
"isAdmin" => self.set_is_admin(value == "true"),
"name" => self.set_name(value.to_owned()),
"password" => self.set_password(value),
_ => {
return self
.character
.set_property(prop_name, value)
.or_else(|_| self.stats_item.set_property(prop_name, value))
}
}
Ok(())
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
} | self.set_needs_sync(true);
}
Err(error) => panic!("Cannot create password hash: {:?}", error),
} | random_line_split |
tls_publish.rs | extern crate cloudpubsub;
extern crate pretty_env_logger;
extern crate rand;
use std::thread;
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use rand::{thread_rng, Rng};
use cloudpubsub::{MqttOptions, MqttClient, MqttCallback};
fn main() | for i in 0..100 {
let len: usize = thread_rng().gen_range(0, 100_000);
let mut v = vec![0; len];
thread_rng().fill_bytes(&mut v);
client.publish("hello/world", v);
}
// verifies pingreqs and responses
thread::sleep(Duration::from_secs(30));
// disconnections because of pingreq delays will be know during
// subsequent publishes
for i in 0..100 {
let len: usize = thread_rng().gen_range(0, 100_000);
let mut v = vec![0; len];
thread_rng().fill_bytes(&mut v);
client.publish("hello/world", v);
}
thread::sleep(Duration::from_secs(60));
println!("Total Ack Count = {:?}", count);
}
| {
pretty_env_logger::init().unwrap();
let options = MqttOptions::new().set_client_id("tls-publisher-1")
.set_clean_session(false)
.set_ca("/userdata/certs/dev/ca-chain.cert.pem")
.set_client_certs("/userdata/certs/dev/RAVI-LOCAL-DEV.cert.pem", "/userdata/certs/dev/RAVI-LOCAL-DEV.key.pem")
.set_broker("dev-mqtt-broker.atherengineering.in:5000");
// .set_broker("localhost:8883");
let count = Arc::new(AtomicUsize::new(0));
let callback_count = count.clone();
let counter_cb = move |_| {
callback_count.fetch_add(1, Ordering::SeqCst);
};
let on_publish = MqttCallback::new().on_publish(counter_cb);
let mut client = MqttClient::start(options, Some(on_publish)).expect("Start Error");
| identifier_body |
tls_publish.rs | extern crate cloudpubsub;
extern crate pretty_env_logger;
extern crate rand;
use std::thread;
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use rand::{thread_rng, Rng};
use cloudpubsub::{MqttOptions, MqttClient, MqttCallback};
fn main() {
pretty_env_logger::init().unwrap();
let options = MqttOptions::new().set_client_id("tls-publisher-1")
.set_clean_session(false)
.set_ca("/userdata/certs/dev/ca-chain.cert.pem")
.set_client_certs("/userdata/certs/dev/RAVI-LOCAL-DEV.cert.pem", "/userdata/certs/dev/RAVI-LOCAL-DEV.key.pem")
.set_broker("dev-mqtt-broker.atherengineering.in:5000");
//.set_broker("localhost:8883");
let count = Arc::new(AtomicUsize::new(0));
let callback_count = count.clone();
let counter_cb = move |_| {
callback_count.fetch_add(1, Ordering::SeqCst); |
for i in 0..100 {
let len: usize = thread_rng().gen_range(0, 100_000);
let mut v = vec![0; len];
thread_rng().fill_bytes(&mut v);
client.publish("hello/world", v);
}
// verifies pingreqs and responses
thread::sleep(Duration::from_secs(30));
// disconnections because of pingreq delays will be know during
// subsequent publishes
for i in 0..100 {
let len: usize = thread_rng().gen_range(0, 100_000);
let mut v = vec![0; len];
thread_rng().fill_bytes(&mut v);
client.publish("hello/world", v);
}
thread::sleep(Duration::from_secs(60));
println!("Total Ack Count = {:?}", count);
} | };
let on_publish = MqttCallback::new().on_publish(counter_cb);
let mut client = MqttClient::start(options, Some(on_publish)).expect("Start Error"); | random_line_split |
tls_publish.rs | extern crate cloudpubsub;
extern crate pretty_env_logger;
extern crate rand;
use std::thread;
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use rand::{thread_rng, Rng};
use cloudpubsub::{MqttOptions, MqttClient, MqttCallback};
fn | () {
pretty_env_logger::init().unwrap();
let options = MqttOptions::new().set_client_id("tls-publisher-1")
.set_clean_session(false)
.set_ca("/userdata/certs/dev/ca-chain.cert.pem")
.set_client_certs("/userdata/certs/dev/RAVI-LOCAL-DEV.cert.pem", "/userdata/certs/dev/RAVI-LOCAL-DEV.key.pem")
.set_broker("dev-mqtt-broker.atherengineering.in:5000");
//.set_broker("localhost:8883");
let count = Arc::new(AtomicUsize::new(0));
let callback_count = count.clone();
let counter_cb = move |_| {
callback_count.fetch_add(1, Ordering::SeqCst);
};
let on_publish = MqttCallback::new().on_publish(counter_cb);
let mut client = MqttClient::start(options, Some(on_publish)).expect("Start Error");
for i in 0..100 {
let len: usize = thread_rng().gen_range(0, 100_000);
let mut v = vec![0; len];
thread_rng().fill_bytes(&mut v);
client.publish("hello/world", v);
}
// verifies pingreqs and responses
thread::sleep(Duration::from_secs(30));
// disconnections because of pingreq delays will be know during
// subsequent publishes
for i in 0..100 {
let len: usize = thread_rng().gen_range(0, 100_000);
let mut v = vec![0; len];
thread_rng().fill_bytes(&mut v);
client.publish("hello/world", v);
}
thread::sleep(Duration::from_secs(60));
println!("Total Ack Count = {:?}", count);
}
| main | identifier_name |
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // 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.
//! This module provides constants which are specific to the implementation
//! of the `f64` floating point data type.
//!
//! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
//!
//! Mathematically significant numbers are provided in the `consts` sub-module.
#![stable(feature = "rust1", since = "1.0.0")]
use mem;
use num::FpCategory;
/// The radix or base of the internal representation of `f64`.
#[stable(feature = "rust1", since = "1.0.0")]
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MANTISSA_DIGITS: u32 = 53;
/// Approximate number of significant digits in base 10.
#[stable(feature = "rust1", since = "1.0.0")]
pub const DIGITS: u32 = 15;
/// [Machine epsilon] value for `f64`.
///
/// This is the difference between `1.0` and the next largest representable number.
///
/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
#[stable(feature = "rust1", since = "1.0.0")]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive normal `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
/// One greater than the minimum possible normal power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_EXP: i32 = -1021;
/// Maximum possible power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_EXP: i32 = 1024;
/// Minimum possible normal power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_10_EXP: i32 = -307;
/// Maximum possible power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_10_EXP: i32 = 308;
/// Not a Number (NaN).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NAN: f64 = 0.0_f64 / 0.0_f64;
/// Infinity (∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
/// Negative infinity (-∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
/// Basic mathematical constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant (π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// π/2
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// π/3
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// π/4
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// π/6
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// π/8
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2/sqrt(π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1/sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number (e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log<sub>2</sub>(10)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
/// log<sub>2</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log<sub>10</sub>(2)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
/// log<sub>10</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
#[lang = "f64"]
#[cfg(not(test))]
impl f64 {
/// Returns `true` if this value is `NaN` and false otherwise.
///
/// ```
/// use std::f64;
///
/// let nan = f64::NAN;
/// let f = 7.0_f64;
///
/// assert!(nan.is_nan());
/// assert!(!f.is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_nan(self) -> bool {
self!= self
}
/// Returns `true` if this value is positive infinity or negative infinity and
/// false otherwise.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf = f64::INFINITY;
/// let neg_inf = f64::NEG_INFINITY;
/// let nan = f64::NAN;
///
/// assert!(!f.is_infinite());
/// assert!(!nan.is_infinite());
///
/// assert!(inf.is_infinite());
/// assert!(neg_inf.is_infinite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_infinite(self) -> bool {
self == INFINITY || self == NEG_INFINITY
}
/// Returns `true` if this number is neither infinite nor `NaN`.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf: f64 = f64::INFINITY;
/// let neg_inf: f64 = f64::NEG_INFINITY;
/// let nan: f64 = f64::NAN;
///
/// assert!(f.is_finite());
///
/// assert!(!nan.is_finite());
/// assert!(!inf.is_finite());
/// assert!(!neg_inf.is_finite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite,
/// [subnormal][subnormal], or `NaN`.
///
/// ```
/// use std::f64;
///
/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
/// let max = f64::MAX;
/// let lower_than_min = 1.0e-308_f64;
/// let zero = 0.0f64;
///
/// assert!(min.is_normal());
/// assert!(max.is_normal());
///
/// assert!(!zero.is_normal());
/// assert!(!f64::NAN.is_normal());
/// assert!(!f64::INFINITY.is_normal());
/// // Values between `0` and `min` are Subnormal.
/// assert!(!lower_than_min.is_normal());
/// ```
/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_normal(self) -> bool {
self.classify() == FpCategory::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
///
/// ```
/// use std::num::FpCategory;
/// use std::f64;
///
/// let num = 12.4_f64;
/// let inf = f64::INFINITY;
///
/// assert_eq!(num.classify(), FpCategory::Normal);
/// assert_eq!(inf.classify(), FpCategory::Infinite);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn classify(self) -> FpCategory {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits = self.to_bits();
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => FpCategory::Zero,
(_, 0) => FpCategory::Subnormal,
(0, EXP_MASK) => FpCategory::Infinite,
(_, EXP_MASK) => FpCategory::Nan,
_ => FpCategory::Normal,
}
}
/// Returns `true` if and only if `self` has a positive sign, including `+0.0`, `NaN`s with
/// positive sign bit and positive infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(f.is_sign_positive());
/// assert!(!g.is_sign_positive());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_positive(self) -> bool {
!self.is_sign_negative()
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
#[inline]
#[doc(hidden)]
pub fn is_positive(self) -> bool {
self.is_sign_positive()
}
/// Returns `true` if and only if `self` has a negative sign, including `-0.0`, `NaN`s with
/// negative sign bit and negative infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(!f.is_sign_negative());
/// assert!(g.is_sign_negative());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_negative(self) -> bool {
self.to_bits() & 0x8000_0000_0000_0000!= 0
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
#[inline]
#[doc(hidden)]
pub fn is_negative(self) -> bool {
self.is_sign_negative()
}
/// Takes the reciprocal (inverse) of a number, `1/x`.
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.recip() - (1.0/x)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn recip(self) -> f64 {
1.0 / self
}
/// Converts radians to degrees.
///
/// ```
/// use std::f64::consts;
///
/// let angle = consts::PI;
///
/// let abs_difference = (angle.to_degrees() - 180.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_degrees(self) -> f64 {
// The division here is correctly rounded with respect to the true
// value of 180/π. (This differs from f32, where a constant must be
// used to ensure a correctly rounded result.)
self * (180.0f64 / consts::PI)
}
/// Converts degrees to radians.
///
/// ```
/// use std::f64::consts;
///
/// let angle = 180.0_f64;
///
/// let abs_difference = (angle.to_radians() - consts::PI).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_radians(self) -> f64 {
let value: f64 = consts::PI;
self * (value / 180.0)
}
/// Returns the maximum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.max(y), y);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn max(self, other: f64) -> f64 {
// IEEE754 says: maxNum(x, y) is the canonicalized number y if x < y, x if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if self.is_nan() || self < other { other } else { self }) * 1.0
}
/// Returns the minimum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.min(y), x);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn min(self, other: f64) -> f64 {
// IEEE754 says: minNum(x, y) is the canonicalized number x if x < y, y if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if other.is_nan() || self < other { self } else { other }) * 1.0
}
/// Raw transmutation to `u64`.
///
/// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
///
/// See `from_bits` for some discussion of the portability of this operation
/// (there are almost no issues).
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// assert!((1f64).to_bits()!= 1f64 as u64); // to_bits() is not casting!
/// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
///
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn to_bits(self) -> u64 {
unsafe { mem::transmute(self) }
}
/// Raw transmutation from `u64`.
///
/// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
/// It turns out this is incredibly portable, for two reasons:
///
/// * Floats and Ints have the same endianness on all supported platforms.
/// * IEEE-754 very precisely specifies the bit layout of floats.
///
/// However there is one caveat: prior to the 2008 version of IEEE-754, how
/// to interpret the NaN signaling bit wasn't actually specified. Most platforms
/// (notably x86 and ARM) picked the interpretation that was ultimately
/// standardized in 2008, but some didn't (notably MIPS). As a result, all
/// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
///
/// Rather than trying to preserve signaling-ness cross-platform, this
/// implementation favours preserving the exact bits. This means that
/// any payloads encoded in NaNs will be preserved even if the result of
/// this method is sent over the network from an x86 machine to a MIPS one.
///
/// If the results of this method are only manipulated by the same
/// architecture that produced them, then there is no portability concern.
///
/// If the input isn't NaN, then there is no portability concern.
///
/// If you don't care about signalingness (very likely), then there is no
/// portability concern.
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// use std::f64;
/// let v = f64::from_bits(0x4029000000000000);
/// let difference = (v - 12.5).abs();
/// assert!(difference <= 1e-5);
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn from_bits(v: u64) -> Self {
// It turns out the safety issues with sNaN were overblown! Hooray!
unsafe { mem::transmute(v) }
}
} | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module provides constants which are specific to the implementation
//! of the `f64` floating point data type.
//!
//! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
//!
//! Mathematically significant numbers are provided in the `consts` sub-module.
#![stable(feature = "rust1", since = "1.0.0")]
use mem;
use num::FpCategory;
/// The radix or base of the internal representation of `f64`.
#[stable(feature = "rust1", since = "1.0.0")]
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MANTISSA_DIGITS: u32 = 53;
/// Approximate number of significant digits in base 10.
#[stable(feature = "rust1", since = "1.0.0")]
pub const DIGITS: u32 = 15;
/// [Machine epsilon] value for `f64`.
///
/// This is the difference between `1.0` and the next largest representable number.
///
/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
#[stable(feature = "rust1", since = "1.0.0")]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive normal `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
/// One greater than the minimum possible normal power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_EXP: i32 = -1021;
/// Maximum possible power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_EXP: i32 = 1024;
/// Minimum possible normal power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_10_EXP: i32 = -307;
/// Maximum possible power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_10_EXP: i32 = 308;
/// Not a Number (NaN).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NAN: f64 = 0.0_f64 / 0.0_f64;
/// Infinity (∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
/// Negative infinity (-∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
/// Basic mathematical constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant (π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// π/2
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// π/3
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// π/4
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// π/6
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// π/8
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2/sqrt(π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1/sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number (e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log<sub>2</sub>(10)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
/// log<sub>2</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log<sub>10</sub>(2)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
/// log<sub>10</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
#[lang = "f64"]
#[cfg(not(test))]
impl f64 {
/// Returns `true` if this value is `NaN` and false otherwise.
///
/// ```
/// use std::f64;
///
/// let nan = f64::NAN;
/// let f = 7.0_f64;
///
/// assert!(nan.is_nan());
/// assert!(!f.is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_nan(self) -> bool {
self!= self
}
/// Returns `true` if this value is positive infinity or negative infinity and
/// false otherwise.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf = f64::INFINITY;
/// let neg_inf = f64::NEG_INFINITY;
/// let nan = f64::NAN;
///
/// assert!(!f.is_infinite());
/// assert!(!nan.is_infinite());
///
/// assert!(inf.is_infinite());
/// assert!(neg_inf.is_infinite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_infinite(self) -> bool {
self == INFINITY || self == NEG_INFINITY
}
/// Returns `true` if this number is neither infinite nor `NaN`.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf: f64 = f64::INFINITY;
/// let neg_inf: f64 = f64::NEG_INFINITY;
/// let nan: f64 = f64::NAN;
///
/// assert!(f.is_finite());
///
/// assert!(!nan.is_finite());
/// assert!(!inf.is_finite());
/// assert!(!neg_inf.is_finite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite,
/// [subnormal][subnormal], or `NaN`.
///
/// ```
/// use std::f64;
///
/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
/// let max = f64::MAX;
/// let lower_than_min = 1.0e-308_f64;
/// let zero = 0.0f64;
///
/// assert!(min.is_normal());
/// assert!(max.is_normal());
///
/// assert!(!zero.is_normal());
/// assert!(!f64::NAN.is_normal());
/// assert!(!f64::INFINITY.is_normal());
/// // Values between `0` and `min` are Subnormal.
/// assert!(!lower_than_min.is_normal());
/// ```
/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_normal(self) -> bool {
self.classify() == FpCategory::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
///
/// ```
/// use std::num::FpCategory;
/// use std::f64;
///
/// let num = 12.4_f64;
/// let inf = f64::INFINITY;
///
/// assert_eq!(num.classify(), FpCategory::Normal);
/// assert_eq!(inf.classify(), FpCategory::Infinite);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn classify(self) -> FpCategory {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits = self.to_bits();
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => FpCategory::Zero,
(_, 0) => FpCategory::Subnormal,
(0, EXP_MASK) => FpCategory::Infinite,
(_, EXP_MASK) => FpCategory::Nan,
_ => FpCategory::Normal,
}
}
/// Returns `true` if and only if `self` has a positive sign, including `+0.0`, `NaN`s with
/// positive sign bit and positive infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(f.is_sign_positive());
/// assert!(!g.is_sign_positive());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_positive(self) -> bool {
!self.is_sign_negative()
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
#[inline]
#[doc(hidden)]
pub fn is_positive(self) -> bool {
self.is_sign_positive()
}
/// Returns `true` if and only if `self` has a negative sign, including `-0.0`, `NaN`s with
/// negative sign bit and negative infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(!f.is_sign_negative());
/// assert!(g.is_sign_negative());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_negative(self) -> bool {
self.to_bits() & 0x8000_0000_0000_0000!= 0
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
#[inline]
#[doc(hidden)]
pub fn is_negative(self) -> bool {
self.is_sign_negative()
}
/// Takes the reciprocal (inverse) of a number, `1/x`.
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.recip() - (1.0/x)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn recip(self) -> f64 {
1.0 / self
}
/// Converts radians to degrees.
///
/// ```
/// use std::f64::consts;
///
/// let angle = consts::PI;
///
/// let abs_difference = (angle.to_degrees() - 180.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_degrees(self) -> f64 {
// The division here is correctly rounded with respect to the true
// value of 180/π. (This differs from f32, where a constant must be
// used to ensure a correctly rounded result.)
self * (180.0f64 / consts::PI)
}
/// Converts degrees to radians.
///
/// ```
/// use std::f64::consts;
///
/// let angle = 180.0_f64;
///
/// let abs_difference = (angle.to_radians() - consts::PI).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_radians(self) -> f64 {
let value: f64 = consts::PI;
self * (value / 180.0)
}
/// Returns the maximum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.max(y), y);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn max(self, other: f64) -> f64 {
// IEEE754 says: maxNum(x, y) is the canonicalized number y if x < y, x if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if self.is_nan() || self < other { other } else { self }) * 1.0
}
/// Returns the minimum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.min(y), x);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn min(self, other: f64) -> f64 {
// IEEE754 says: minNum(x, y) is the canonicalized number x if x < y, y if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if other.is_nan() || self < other { self } else { other }) * 1.0
}
/// Raw transmutation to `u64`.
///
/// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
///
/// See `from_bits` for some discussion of the portability of this operation
/// (there are almost no issues).
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// assert!((1f64).to_bits()!= 1f64 as u64); // to_bits() is not casting!
/// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
///
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn to_bits(self) -> u64 {
unsafe { mem::transmute(self) }
}
/// Raw transmutation from `u64`.
///
/// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
/// It turns out this is incredibly portable, for two reasons:
///
/// * Floats and Ints have the same endianness on all supported platforms.
/// * IEEE-754 very precisely specifies the bit layout of floats.
///
/// However there is one caveat: prior to the 2008 version of IEEE-754, how
/// to interpret the NaN signaling bit wasn't actually specified. Most platforms
/// (notably x86 and ARM) picked the interpretation that was ultimately
/// standardized in 2008, but some didn't (notably MIPS). As a result, all
/// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
///
/// Rather than trying to preserve signaling-ness cross-platform, this
/// implementation favours preserving the exact bits. This means that
/// any payloads encoded in NaNs will be preserved even if the result of
/// this method is sent over the network from an x86 machine to a MIPS one.
///
/// If the results of this method are only manipulated by the same
/// architecture that produced them, then there is no portability concern.
///
/// If the input isn't NaN, then there is no portability concern.
///
/// If you don't care about signalingness (very likely), then there is no
/// portability concern.
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// use std::f64;
/// let v = f64::from_bits(0x4029000000000000);
/// let difference = (v - 12.5).abs();
/// assert!(difference <= 1e-5);
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn from_bits(v: u64) -> Self {
// I | t turns out the safety issues with sNaN were overblown! Hooray!
unsafe { mem::transmute(v) }
}
}
| identifier_body |
|
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module provides constants which are specific to the implementation
//! of the `f64` floating point data type.
//!
//! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
//!
//! Mathematically significant numbers are provided in the `consts` sub-module.
#![stable(feature = "rust1", since = "1.0.0")]
use mem;
use num::FpCategory;
/// The radix or base of the internal representation of `f64`.
#[stable(feature = "rust1", since = "1.0.0")]
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MANTISSA_DIGITS: u32 = 53;
/// Approximate number of significant digits in base 10.
#[stable(feature = "rust1", since = "1.0.0")]
pub const DIGITS: u32 = 15;
/// [Machine epsilon] value for `f64`.
///
/// This is the difference between `1.0` and the next largest representable number.
///
/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
#[stable(feature = "rust1", since = "1.0.0")]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive normal `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
/// One greater than the minimum possible normal power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_EXP: i32 = -1021;
/// Maximum possible power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_EXP: i32 = 1024;
/// Minimum possible normal power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_10_EXP: i32 = -307;
/// Maximum possible power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_10_EXP: i32 = 308;
/// Not a Number (NaN).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NAN: f64 = 0.0_f64 / 0.0_f64;
/// Infinity (∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
/// Negative infinity (-∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
/// Basic mathematical constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant (π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// π/2
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// π/3
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// π/4
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// π/6
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// π/8
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2/sqrt(π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1/sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number (e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log<sub>2</sub>(10)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
/// log<sub>2</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log<sub>10</sub>(2)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
/// log<sub>10</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
#[lang = "f64"]
#[cfg(not(test))]
impl f64 {
/// Returns `true` if this value is `NaN` and false otherwise.
///
/// ```
/// use std::f64;
///
/// let nan = f64::NAN;
/// let f = 7.0_f64;
///
/// assert!(nan.is_nan());
/// assert!(!f.is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_nan(self) -> bool {
self!= self
}
/// Returns `true` if this value is positive infinity or negative infinity and
/// false otherwise.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf = f64::INFINITY;
/// let neg_inf = f64::NEG_INFINITY;
/// let nan = f64::NAN;
///
/// assert!(!f.is_infinite());
/// assert!(!nan.is_infinite());
///
/// assert!(inf.is_infinite());
/// assert!(neg_inf.is_infinite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_infinite(self) -> bool {
self == INFINITY || self == NEG_INFINITY
}
/// Returns `true` if this number is neither infinite nor `NaN`.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf: f64 = f64::INFINITY;
/// let neg_inf: f64 = f64::NEG_INFINITY;
/// let nan: f64 = f64::NAN;
///
/// assert!(f.is_finite());
///
/// assert!(!nan.is_finite());
/// assert!(!inf.is_finite());
/// assert!(!neg_inf.is_finite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite,
/// [subnormal][subnormal], or `NaN`.
///
/// ```
/// use std::f64;
///
/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
/// let max = f64::MAX;
/// let lower_than_min = 1.0e-308_f64;
/// let zero = 0.0f64;
///
/// assert!(min.is_normal());
/// assert!(max.is_normal());
///
/// assert!(!zero.is_normal());
/// assert!(!f64::NAN.is_normal());
/// assert!(!f64::INFINITY.is_normal());
/// // Values between `0` and `min` are Subnormal.
/// assert!(!lower_than_min.is_normal());
/// ```
/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_normal(self) -> bool {
self.classify() == FpCategory::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
///
/// ```
/// use std::num::FpCategory;
/// use std::f64;
///
/// let num = 12.4_f64;
/// let inf = f64::INFINITY;
///
/// assert_eq!(num.classify(), FpCategory::Normal);
/// assert_eq!(inf.classify(), FpCategory::Infinite);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn classify(self) -> FpCategory {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits = self.to_bits();
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => FpCategory::Zero,
(_, 0) => FpCategory::Subnormal,
(0, EXP_MASK) => FpCategory::Infinite,
(_, EXP_MASK) => FpCategory::Nan,
_ => FpCategory::Normal,
}
}
/// Returns `true` if and only if `self` has a positive sign, including `+0.0`, `NaN`s with
/// positive sign bit and positive infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(f.is_sign_positive());
/// assert!(!g.is_sign_positive());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_positive(self) -> bool {
!self.is_sign_negative()
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
#[inline]
#[doc(hidden)]
pub fn is_positive(self) -> bool {
self.is_sign_positive()
}
/// Returns `true` if and only if `self` has a negative sign, including `-0.0`, `NaN`s with
/// negative sign bit and negative infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(!f.is_sign_negative());
/// assert!(g.is_sign_negative());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_negative(self) -> bool {
self.to_bits() & 0x8000_0000_0000_0000!= 0
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
#[inline]
#[doc(hidden)]
pub fn is_negative(self) -> bool {
self.is_sign_negative()
}
/// Takes the reciprocal (inverse) of a number, `1/x`.
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.recip() - (1.0/x)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn recip(self) -> f64 {
1.0 / self
}
/// Converts radians to degrees.
///
/// ```
/// use std::f64::consts;
///
/// let angle = consts::PI;
///
/// let abs_difference = (angle.to_degrees() - 180.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_degrees(self) -> f64 {
// The division here is correctly rounded with respect to the true
// value of 180/π. (This differs from f32, where a constant must be
// used to ensure a correctly rounded result.)
self * (180.0f64 / consts::PI)
}
/// Converts degrees to radians.
///
/// ```
/// use std::f64::consts;
///
/// let angle = 180.0_f64;
///
/// let abs_difference = (angle.to_radians() - consts::PI).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_radians(self) -> f64 {
let value: f64 = consts::PI;
self * (value / 180.0)
}
/// Returns the maximum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.max(y), y);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn max(self, other: f64) -> f64 {
// IEEE754 says: maxNum(x, y) is the canonicalized number y if x < y, x if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if self.is_nan() || self < other { other } else | ) * 1.0
}
/// Returns the minimum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.min(y), x);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn min(self, other: f64) -> f64 {
// IEEE754 says: minNum(x, y) is the canonicalized number x if x < y, y if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if other.is_nan() || self < other { self } else { other }) * 1.0
}
/// Raw transmutation to `u64`.
///
/// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
///
/// See `from_bits` for some discussion of the portability of this operation
/// (there are almost no issues).
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// assert!((1f64).to_bits()!= 1f64 as u64); // to_bits() is not casting!
/// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
///
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn to_bits(self) -> u64 {
unsafe { mem::transmute(self) }
}
/// Raw transmutation from `u64`.
///
/// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
/// It turns out this is incredibly portable, for two reasons:
///
/// * Floats and Ints have the same endianness on all supported platforms.
/// * IEEE-754 very precisely specifies the bit layout of floats.
///
/// However there is one caveat: prior to the 2008 version of IEEE-754, how
/// to interpret the NaN signaling bit wasn't actually specified. Most platforms
/// (notably x86 and ARM) picked the interpretation that was ultimately
/// standardized in 2008, but some didn't (notably MIPS). As a result, all
/// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
///
/// Rather than trying to preserve signaling-ness cross-platform, this
/// implementation favours preserving the exact bits. This means that
/// any payloads encoded in NaNs will be preserved even if the result of
/// this method is sent over the network from an x86 machine to a MIPS one.
///
/// If the results of this method are only manipulated by the same
/// architecture that produced them, then there is no portability concern.
///
/// If the input isn't NaN, then there is no portability concern.
///
/// If you don't care about signalingness (very likely), then there is no
/// portability concern.
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// use std::f64;
/// let v = f64::from_bits(0x4029000000000000);
/// let difference = (v - 12.5).abs();
/// assert!(difference <= 1e-5);
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn from_bits(v: u64) -> Self {
// It turns out the safety issues with sNaN were overblown! Hooray!
unsafe { mem::transmute(v) }
}
}
| { self } | conditional_block |
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module provides constants which are specific to the implementation
//! of the `f64` floating point data type.
//!
//! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
//!
//! Mathematically significant numbers are provided in the `consts` sub-module.
#![stable(feature = "rust1", since = "1.0.0")]
use mem;
use num::FpCategory;
/// The radix or base of the internal representation of `f64`.
#[stable(feature = "rust1", since = "1.0.0")]
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MANTISSA_DIGITS: u32 = 53;
/// Approximate number of significant digits in base 10.
#[stable(feature = "rust1", since = "1.0.0")]
pub const DIGITS: u32 = 15;
/// [Machine epsilon] value for `f64`.
///
/// This is the difference between `1.0` and the next largest representable number.
///
/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
#[stable(feature = "rust1", since = "1.0.0")]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive normal `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite `f64` value.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
/// One greater than the minimum possible normal power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_EXP: i32 = -1021;
/// Maximum possible power of 2 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_EXP: i32 = 1024;
/// Minimum possible normal power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_10_EXP: i32 = -307;
/// Maximum possible power of 10 exponent.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX_10_EXP: i32 = 308;
/// Not a Number (NaN).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NAN: f64 = 0.0_f64 / 0.0_f64;
/// Infinity (∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
/// Negative infinity (-∞).
#[stable(feature = "rust1", since = "1.0.0")]
pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
/// Basic mathematical constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant (π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// π/2
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// π/3
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// π/4
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// π/6
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// π/8
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2/π
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2/sqrt(π)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1/sqrt(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number (e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log<sub>2</sub>(10)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
/// log<sub>2</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log<sub>10</sub>(2)
#[unstable(feature = "extra_log_consts", issue = "50540")]
pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
/// log<sub>10</sub>(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
#[lang = "f64"]
#[cfg(not(test))]
impl f64 {
/// Returns `true` if this value is `NaN` and false otherwise.
///
/// ```
/// use std::f64;
///
/// let nan = f64::NAN;
/// let f = 7.0_f64;
///
/// assert!(nan.is_nan());
/// assert!(!f.is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_nan(self) -> bool {
self!= self
}
/// Returns `true` if this value is positive infinity or negative infinity and
/// false otherwise.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf = f64::INFINITY;
/// let neg_inf = f64::NEG_INFINITY;
/// let nan = f64::NAN;
///
/// assert!(!f.is_infinite());
/// assert!(!nan.is_infinite());
///
/// assert!(inf.is_infinite());
/// assert!(neg_inf.is_infinite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_infinite(self) -> bool {
self == INFINITY || self == NEG_INFINITY
}
/// Returns `true` if this number is neither infinite nor `NaN`.
///
/// ```
/// use std::f64;
///
/// let f = 7.0f64;
/// let inf: f64 = f64::INFINITY;
/// let neg_inf: f64 = f64::NEG_INFINITY;
/// let nan: f64 = f64::NAN;
///
/// assert!(f.is_finite());
///
/// assert!(!nan.is_finite());
/// assert!(!inf.is_finite());
/// assert!(!neg_inf.is_finite());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite,
/// [subnormal][subnormal], or `NaN`.
///
/// ```
/// use std::f64;
///
/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
/// let max = f64::MAX;
/// let lower_than_min = 1.0e-308_f64;
/// let zero = 0.0f64;
///
/// assert!(min.is_normal());
/// assert!(max.is_normal());
///
/// assert!(!zero.is_normal());
/// assert!(!f64::NAN.is_normal());
/// assert!(!f64::INFINITY.is_normal());
/// // Values between `0` and `min` are Subnormal.
/// assert!(!lower_than_min.is_normal());
/// ```
/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_normal(self) -> bool {
self.classify() == FpCategory::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
///
/// ```
/// use std::num::FpCategory;
/// use std::f64;
///
/// let num = 12.4_f64;
/// let inf = f64::INFINITY;
///
/// assert_eq!(num.classify(), FpCategory::Normal);
/// assert_eq!(inf.classify(), FpCategory::Infinite);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn classify(self) -> FpCategory {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits = self.to_bits();
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => FpCategory::Zero,
(_, 0) => FpCategory::Subnormal,
(0, EXP_MASK) => FpCategory::Infinite,
(_, EXP_MASK) => FpCategory::Nan,
_ => FpCategory::Normal,
}
}
/// Returns `true` if and only if `self` has a positive sign, including `+0.0`, `NaN`s with
/// positive sign bit and positive infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(f.is_sign_positive());
/// assert!(!g.is_sign_positive());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_positive(self) -> bool {
!self.is_sign_negative()
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
#[inline]
#[doc(hidden)]
pub fn is_positive(self) -> bool {
self.is_sign_positive()
}
/// Returns `true` if and only if `self` has a negative sign, including `-0.0`, `NaN`s with
/// negative sign bit and negative infinity.
///
/// ```
/// let f = 7.0_f64;
/// let g = -7.0_f64;
///
/// assert!(!f.is_sign_negative());
/// assert!(g.is_sign_negative());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_sign_negative(self) -> bool {
self.to_bits() & 0x8000_0000_0000_0000!= 0
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
#[inline]
#[doc(hidden)]
pub fn is_negative(self) -> bool {
self.is_sign_negative()
}
/// Takes the reciprocal (inverse) of a number, `1/x`.
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.recip() - (1.0/x)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn recip(self) -> f64 {
1.0 / self
}
/// Converts radians to degrees.
///
/// ```
/// use std::f64::consts;
///
/// let angle = consts::PI;
///
/// let abs_difference = (angle.to_degrees() - 180.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_degrees(self) -> f64 {
// The division here is correctly rounded with respect to the true
// value of 180/π. (This differs from f32, where a constant must be
// used to ensure a correctly rounded result.)
self * (180.0f64 / consts::PI)
}
/// Converts degrees to radians.
///
/// ```
/// use std::f64::consts;
///
/// let angle = 180.0_f64;
///
/// let abs_difference = (angle.to_radians() - consts::PI).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_radians(sel | {
let value: f64 = consts::PI;
self * (value / 180.0)
}
/// Returns the maximum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.max(y), y);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn max(self, other: f64) -> f64 {
// IEEE754 says: maxNum(x, y) is the canonicalized number y if x < y, x if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if self.is_nan() || self < other { other } else { self }) * 1.0
}
/// Returns the minimum of the two numbers.
///
/// ```
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.min(y), x);
/// ```
///
/// If one of the arguments is NaN, then the other argument is returned.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn min(self, other: f64) -> f64 {
// IEEE754 says: minNum(x, y) is the canonicalized number x if x < y, y if y < x, the
// canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
// is either x or y, canonicalized (this means results might differ among implementations).
// When either x or y is a signalingNaN, then the result is according to 6.2.
//
// Since we do not support sNaN in Rust yet, we do not need to handle them.
// FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
// multiplying by 1.0. Should switch to the `canonicalize` when it works.
(if other.is_nan() || self < other { self } else { other }) * 1.0
}
/// Raw transmutation to `u64`.
///
/// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
///
/// See `from_bits` for some discussion of the portability of this operation
/// (there are almost no issues).
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// assert!((1f64).to_bits()!= 1f64 as u64); // to_bits() is not casting!
/// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
///
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn to_bits(self) -> u64 {
unsafe { mem::transmute(self) }
}
/// Raw transmutation from `u64`.
///
/// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
/// It turns out this is incredibly portable, for two reasons:
///
/// * Floats and Ints have the same endianness on all supported platforms.
/// * IEEE-754 very precisely specifies the bit layout of floats.
///
/// However there is one caveat: prior to the 2008 version of IEEE-754, how
/// to interpret the NaN signaling bit wasn't actually specified. Most platforms
/// (notably x86 and ARM) picked the interpretation that was ultimately
/// standardized in 2008, but some didn't (notably MIPS). As a result, all
/// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
///
/// Rather than trying to preserve signaling-ness cross-platform, this
/// implementation favours preserving the exact bits. This means that
/// any payloads encoded in NaNs will be preserved even if the result of
/// this method is sent over the network from an x86 machine to a MIPS one.
///
/// If the results of this method are only manipulated by the same
/// architecture that produced them, then there is no portability concern.
///
/// If the input isn't NaN, then there is no portability concern.
///
/// If you don't care about signalingness (very likely), then there is no
/// portability concern.
///
/// Note that this function is distinct from `as` casting, which attempts to
/// preserve the *numeric* value, and not the bitwise value.
///
/// # Examples
///
/// ```
/// use std::f64;
/// let v = f64::from_bits(0x4029000000000000);
/// let difference = (v - 12.5).abs();
/// assert!(difference <= 1e-5);
/// ```
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn from_bits(v: u64) -> Self {
// It turns out the safety issues with sNaN were overblown! Hooray!
unsafe { mem::transmute(v) }
}
}
| f) -> f64 | identifier_name |
xul.mako.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 https://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
// Non-standard properties that Gecko uses for XUL elements.
<% data.new_style_struct("XUL", inherited=False) %>
${helpers.single_keyword(
"-moz-box-align",
"stretch start center baseline end",
engines="gecko",
gecko_ffi_name="mBoxAlign",
gecko_enum_prefix="StyleBoxAlign",
animation_value_type="discrete",
alias="-webkit-box-align",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-align)",
)}
${helpers.single_keyword(
"-moz-box-direction",
"normal reverse",
engines="gecko",
gecko_ffi_name="mBoxDirection",
gecko_enum_prefix="StyleBoxDirection",
animation_value_type="discrete",
alias="-webkit-box-direction",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-direction)",
)}
${helpers.predefined_type(
"-moz-box-flex",
"NonNegativeNumber",
"From::from(0.)",
engines="gecko",
gecko_ffi_name="mBoxFlex",
animation_value_type="NonNegativeNumber",
alias="-webkit-box-flex",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-flex)",
)}
${helpers.single_keyword(
"-moz-box-orient",
"horizontal vertical",
engines="gecko",
gecko_ffi_name="mBoxOrient",
gecko_aliases="inline-axis=horizontal block-axis=vertical",
gecko_enum_prefix="StyleBoxOrient",
animation_value_type="discrete",
alias="-webkit-box-orient",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-orient)",
)}
${helpers.single_keyword(
"-moz-box-pack",
"start center end justify",
engines="gecko",
gecko_ffi_name="mBoxPack",
gecko_enum_prefix="StyleBoxPack",
animation_value_type="discrete",
alias="-webkit-box-pack",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-pack)",
)}
${helpers.single_keyword(
"-moz-stack-sizing",
"stretch-to-fit ignore ignore-horizontal ignore-vertical",
engines="gecko",
gecko_ffi_name="mStackSizing",
gecko_enum_prefix="StyleStackSizing",
animation_value_type="discrete",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-stack-sizing)",
)}
${helpers.predefined_type(
"-moz-box-ordinal-group",
"Integer",
"0", | spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-box-ordinal-group)",
)} | engines="gecko",
parse_method="parse_non_negative",
alias="-webkit-box-ordinal-group",
gecko_ffi_name="mBoxOrdinal",
animation_value_type="discrete", | random_line_split |
list_item.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/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an extra inline fragment for the marker. | #![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use display_list_builder::ListItemFlowDisplayListBuilding;
use floats::FloatKind;
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo};
use generated_content;
use incremental::RESOLVE_GENERATED_CONTENT;
use inline::InlineMetrics;
use text;
use wrapper::ThreadSafeLayoutNode;
use geom::{Point2D, Rect};
use gfx::display_list::DisplayList;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
use util::opts;
use style::properties::ComputedValues;
use style::computed_values::list_style_type;
use std::sync::Arc;
/// A block with the CSS `display` property equal to `list-item`.
#[derive(Debug)]
pub struct ListItemFlow {
/// Data common to all block flows.
pub block_flow: BlockFlow,
/// The marker, if outside. (Markers that are inside are instead just fragments on the interior
/// `InlineFlow`.)
pub marker: Option<Fragment>,
}
impl ListItemFlow {
pub fn from_node_fragments_and_flotation(node: &ThreadSafeLayoutNode,
main_fragment: Fragment,
marker_fragment: Option<Fragment>,
flotation: Option<FloatKind>)
-> ListItemFlow {
let mut this = ListItemFlow {
block_flow: BlockFlow::from_node_and_fragment(node, main_fragment, flotation),
marker: marker_fragment,
};
if let Some(ref marker) = this.marker {
match marker.style().get_list().list_style_type {
list_style_type::T::disc |
list_style_type::T::none |
list_style_type::T::circle |
list_style_type::T::square |
list_style_type::T::disclosure_open |
list_style_type::T::disclosure_closed => {}
_ => this.block_flow.base.restyle_damage.insert(RESOLVE_GENERATED_CONTENT),
}
}
this
}
}
impl Flow for ListItemFlow {
fn class(&self) -> FlowClass {
FlowClass::ListItem
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
fn bubble_inline_sizes(&mut self) {
// The marker contributes no intrinsic inline-size, so…
self.block_flow.bubble_inline_sizes()
}
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
self.block_flow.assign_inline_sizes(layout_context);
if let Some(ref mut marker) = self.marker {
let containing_block_inline_size = self.block_flow.base.block_container_inline_size;
marker.assign_replaced_inline_size_if_necessary(containing_block_inline_size);
// Do this now. There's no need to do this in bubble-widths, since markers do not
// contribute to the inline size of this flow.
let intrinsic_inline_sizes = marker.compute_intrinsic_inline_sizes();
marker.border_box.size.inline =
intrinsic_inline_sizes.content_intrinsic_sizes.preferred_inline_size;
marker.border_box.start.i = self.block_flow.fragment.border_box.start.i -
marker.border_box.size.inline;
}
}
fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
self.block_flow.assign_block_size(layout_context);
if let Some(ref mut marker) = self.marker {
let containing_block_block_size =
self.block_flow.base.block_container_explicit_block_size.unwrap_or(Au(0));
marker.assign_replaced_block_size_if_necessary(containing_block_block_size);
let font_metrics =
text::font_metrics_for_style(layout_context.font_context(),
marker.style.get_font_arc());
let line_height = text::line_height_from_style(&*marker.style, &font_metrics);
let item_inline_metrics = InlineMetrics::from_font_metrics(&font_metrics, line_height);
let marker_inline_metrics = marker.inline_metrics(layout_context);
marker.border_box.start.b = item_inline_metrics.block_size_above_baseline -
marker_inline_metrics.block_size_above_baseline;
marker.border_box.size.block = marker_inline_metrics.block_size_above_baseline;
}
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn place_float_if_applicable<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
self.block_flow.place_float_if_applicable(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
self.build_display_list_for_list_item(box DisplayList::new(), layout_context);
if opts::get().validate_display_list_geometry {
self.block_flow.base.validate_display_list_geometry();
}
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position);
if let Some(ref marker) = self.marker {
if iterator.should_process(marker) {
iterator.process(
marker,
&marker.stacking_relative_border_box(&self.block_flow
.base
.stacking_relative_position,
&self.block_flow
.base
.absolute_position_info
.relative_containing_block_size,
self.block_flow
.base
.absolute_position_info
.relative_containing_block_mode,
CoordinateSystem::Own)
.translate(stacking_context_position));
}
}
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator);
if let Some(ref mut marker) = self.marker {
(*mutator)(marker)
}
}
}
/// The kind of content that `list-style-type` results in.
pub enum ListStyleTypeContent {
None,
StaticText(char),
GeneratedContent(Box<GeneratedContentInfo>),
}
impl ListStyleTypeContent {
/// Returns the content to be used for the given value of the `list-style-type` property.
pub fn from_list_style_type(list_style_type: list_style_type::T) -> ListStyleTypeContent {
// Just to keep things simple, use a nonbreaking space (Unicode 0xa0) to provide the marker
// separation.
match list_style_type {
list_style_type::T::none => ListStyleTypeContent::None,
list_style_type::T::disc | list_style_type::T::circle | list_style_type::T::square |
list_style_type::T::disclosure_open | list_style_type::T::disclosure_closed => {
let text = generated_content::static_representation(list_style_type);
ListStyleTypeContent::StaticText(text)
}
_ => ListStyleTypeContent::GeneratedContent(box GeneratedContentInfo::ListItem),
}
}
} | random_line_split |
|
list_item.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/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an extra inline fragment for the marker.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use display_list_builder::ListItemFlowDisplayListBuilding;
use floats::FloatKind;
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo};
use generated_content;
use incremental::RESOLVE_GENERATED_CONTENT;
use inline::InlineMetrics;
use text;
use wrapper::ThreadSafeLayoutNode;
use geom::{Point2D, Rect};
use gfx::display_list::DisplayList;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
use util::opts;
use style::properties::ComputedValues;
use style::computed_values::list_style_type;
use std::sync::Arc;
/// A block with the CSS `display` property equal to `list-item`.
#[derive(Debug)]
pub struct ListItemFlow {
/// Data common to all block flows.
pub block_flow: BlockFlow,
/// The marker, if outside. (Markers that are inside are instead just fragments on the interior
/// `InlineFlow`.)
pub marker: Option<Fragment>,
}
impl ListItemFlow {
pub fn from_node_fragments_and_flotation(node: &ThreadSafeLayoutNode,
main_fragment: Fragment,
marker_fragment: Option<Fragment>,
flotation: Option<FloatKind>)
-> ListItemFlow {
let mut this = ListItemFlow {
block_flow: BlockFlow::from_node_and_fragment(node, main_fragment, flotation),
marker: marker_fragment,
};
if let Some(ref marker) = this.marker {
match marker.style().get_list().list_style_type {
list_style_type::T::disc |
list_style_type::T::none |
list_style_type::T::circle |
list_style_type::T::square |
list_style_type::T::disclosure_open |
list_style_type::T::disclosure_closed => {}
_ => this.block_flow.base.restyle_damage.insert(RESOLVE_GENERATED_CONTENT),
}
}
this
}
}
impl Flow for ListItemFlow {
fn class(&self) -> FlowClass {
FlowClass::ListItem
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
fn bubble_inline_sizes(&mut self) {
// The marker contributes no intrinsic inline-size, so…
self.block_flow.bubble_inline_sizes()
}
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
self.block_flow.assign_inline_sizes(layout_context);
if let Some(ref mut marker) = self.marker {
let containing_block_inline_size = self.block_flow.base.block_container_inline_size;
marker.assign_replaced_inline_size_if_necessary(containing_block_inline_size);
// Do this now. There's no need to do this in bubble-widths, since markers do not
// contribute to the inline size of this flow.
let intrinsic_inline_sizes = marker.compute_intrinsic_inline_sizes();
marker.border_box.size.inline =
intrinsic_inline_sizes.content_intrinsic_sizes.preferred_inline_size;
marker.border_box.start.i = self.block_flow.fragment.border_box.start.i -
marker.border_box.size.inline;
}
}
fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
self.block_flow.assign_block_size(layout_context);
if let Some(ref mut marker) = self.marker {
let containing_block_block_size =
self.block_flow.base.block_container_explicit_block_size.unwrap_or(Au(0));
marker.assign_replaced_block_size_if_necessary(containing_block_block_size);
let font_metrics =
text::font_metrics_for_style(layout_context.font_context(),
marker.style.get_font_arc());
let line_height = text::line_height_from_style(&*marker.style, &font_metrics);
let item_inline_metrics = InlineMetrics::from_font_metrics(&font_metrics, line_height);
let marker_inline_metrics = marker.inline_metrics(layout_context);
marker.border_box.start.b = item_inline_metrics.block_size_above_baseline -
marker_inline_metrics.block_size_above_baseline;
marker.border_box.size.block = marker_inline_metrics.block_size_above_baseline;
}
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn place_float_if_applicable<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
self.block_flow.place_float_if_applicable(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
self.build_display_list_for_list_item(box DisplayList::new(), layout_context);
if opts::get().validate_display_list_geometry {
self.block_flow.base.validate_display_list_geometry();
}
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn it | self,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position);
if let Some(ref marker) = self.marker {
if iterator.should_process(marker) {
iterator.process(
marker,
&marker.stacking_relative_border_box(&self.block_flow
.base
.stacking_relative_position,
&self.block_flow
.base
.absolute_position_info
.relative_containing_block_size,
self.block_flow
.base
.absolute_position_info
.relative_containing_block_mode,
CoordinateSystem::Own)
.translate(stacking_context_position));
}
}
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator);
if let Some(ref mut marker) = self.marker {
(*mutator)(marker)
}
}
}
/// The kind of content that `list-style-type` results in.
pub enum ListStyleTypeContent {
None,
StaticText(char),
GeneratedContent(Box<GeneratedContentInfo>),
}
impl ListStyleTypeContent {
/// Returns the content to be used for the given value of the `list-style-type` property.
pub fn from_list_style_type(list_style_type: list_style_type::T) -> ListStyleTypeContent {
// Just to keep things simple, use a nonbreaking space (Unicode 0xa0) to provide the marker
// separation.
match list_style_type {
list_style_type::T::none => ListStyleTypeContent::None,
list_style_type::T::disc | list_style_type::T::circle | list_style_type::T::square |
list_style_type::T::disclosure_open | list_style_type::T::disclosure_closed => {
let text = generated_content::static_representation(list_style_type);
ListStyleTypeContent::StaticText(text)
}
_ => ListStyleTypeContent::GeneratedContent(box GeneratedContentInfo::ListItem),
}
}
}
| erate_through_fragment_border_boxes(& | identifier_name |
list_item.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/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an extra inline fragment for the marker.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use display_list_builder::ListItemFlowDisplayListBuilding;
use floats::FloatKind;
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo};
use generated_content;
use incremental::RESOLVE_GENERATED_CONTENT;
use inline::InlineMetrics;
use text;
use wrapper::ThreadSafeLayoutNode;
use geom::{Point2D, Rect};
use gfx::display_list::DisplayList;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
use util::opts;
use style::properties::ComputedValues;
use style::computed_values::list_style_type;
use std::sync::Arc;
/// A block with the CSS `display` property equal to `list-item`.
#[derive(Debug)]
pub struct ListItemFlow {
/// Data common to all block flows.
pub block_flow: BlockFlow,
/// The marker, if outside. (Markers that are inside are instead just fragments on the interior
/// `InlineFlow`.)
pub marker: Option<Fragment>,
}
impl ListItemFlow {
pub fn from_node_fragments_and_flotation(node: &ThreadSafeLayoutNode,
main_fragment: Fragment,
marker_fragment: Option<Fragment>,
flotation: Option<FloatKind>)
-> ListItemFlow {
let mut this = ListItemFlow {
block_flow: BlockFlow::from_node_and_fragment(node, main_fragment, flotation),
marker: marker_fragment,
};
if let Some(ref marker) = this.marker {
match marker.style().get_list().list_style_type {
list_style_type::T::disc |
list_style_type::T::none |
list_style_type::T::circle |
list_style_type::T::square |
list_style_type::T::disclosure_open |
list_style_type::T::disclosure_closed => {}
_ => this.block_flow.base.restyle_damage.insert(RESOLVE_GENERATED_CONTENT),
}
}
this
}
}
impl Flow for ListItemFlow {
fn class(&self) -> FlowClass {
FlowClass::ListItem
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
fn bubble_inline_sizes(&mut self) | fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
self.block_flow.assign_inline_sizes(layout_context);
if let Some(ref mut marker) = self.marker {
let containing_block_inline_size = self.block_flow.base.block_container_inline_size;
marker.assign_replaced_inline_size_if_necessary(containing_block_inline_size);
// Do this now. There's no need to do this in bubble-widths, since markers do not
// contribute to the inline size of this flow.
let intrinsic_inline_sizes = marker.compute_intrinsic_inline_sizes();
marker.border_box.size.inline =
intrinsic_inline_sizes.content_intrinsic_sizes.preferred_inline_size;
marker.border_box.start.i = self.block_flow.fragment.border_box.start.i -
marker.border_box.size.inline;
}
}
fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
self.block_flow.assign_block_size(layout_context);
if let Some(ref mut marker) = self.marker {
let containing_block_block_size =
self.block_flow.base.block_container_explicit_block_size.unwrap_or(Au(0));
marker.assign_replaced_block_size_if_necessary(containing_block_block_size);
let font_metrics =
text::font_metrics_for_style(layout_context.font_context(),
marker.style.get_font_arc());
let line_height = text::line_height_from_style(&*marker.style, &font_metrics);
let item_inline_metrics = InlineMetrics::from_font_metrics(&font_metrics, line_height);
let marker_inline_metrics = marker.inline_metrics(layout_context);
marker.border_box.start.b = item_inline_metrics.block_size_above_baseline -
marker_inline_metrics.block_size_above_baseline;
marker.border_box.size.block = marker_inline_metrics.block_size_above_baseline;
}
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn place_float_if_applicable<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
self.block_flow.place_float_if_applicable(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
self.build_display_list_for_list_item(box DisplayList::new(), layout_context);
if opts::get().validate_display_list_geometry {
self.block_flow.base.validate_display_list_geometry();
}
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position);
if let Some(ref marker) = self.marker {
if iterator.should_process(marker) {
iterator.process(
marker,
&marker.stacking_relative_border_box(&self.block_flow
.base
.stacking_relative_position,
&self.block_flow
.base
.absolute_position_info
.relative_containing_block_size,
self.block_flow
.base
.absolute_position_info
.relative_containing_block_mode,
CoordinateSystem::Own)
.translate(stacking_context_position));
}
}
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator);
if let Some(ref mut marker) = self.marker {
(*mutator)(marker)
}
}
}
/// The kind of content that `list-style-type` results in.
pub enum ListStyleTypeContent {
None,
StaticText(char),
GeneratedContent(Box<GeneratedContentInfo>),
}
impl ListStyleTypeContent {
/// Returns the content to be used for the given value of the `list-style-type` property.
pub fn from_list_style_type(list_style_type: list_style_type::T) -> ListStyleTypeContent {
// Just to keep things simple, use a nonbreaking space (Unicode 0xa0) to provide the marker
// separation.
match list_style_type {
list_style_type::T::none => ListStyleTypeContent::None,
list_style_type::T::disc | list_style_type::T::circle | list_style_type::T::square |
list_style_type::T::disclosure_open | list_style_type::T::disclosure_closed => {
let text = generated_content::static_representation(list_style_type);
ListStyleTypeContent::StaticText(text)
}
_ => ListStyleTypeContent::GeneratedContent(box GeneratedContentInfo::ListItem),
}
}
}
| {
// The marker contributes no intrinsic inline-size, so…
self.block_flow.bubble_inline_sizes()
}
| identifier_body |
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations and constants for 64-bits floats (`f64` type)
#![doc(primitive = "f64")]
// FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353
#![allow(overflowing_literals)]
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::*;
use intrinsics;
use mem;
use num::FpCategory as Fp;
use num::{Float, ParseFloatError};
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const RADIX: u32 = 2;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MANTISSA_DIGITS: u32 = 53;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const DIGITS: u32 = 15;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive, normalized f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_EXP: i32 = -1021;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_EXP: i32 = 1024;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_10_EXP: i32 = -307;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_10_EXP: i32 = 308;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NAN: f64 = 0.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const INFINITY: f64 = 1.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64;
/// Basic mathematial constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// pi * 2.0
#[unstable(feature = "float_consts",
reason = "unclear naming convention/usefulness")]
#[deprecated(since = "1.2.0", reason = "unclear on usefulness")]
pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64;
/// pi/2.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// pi/3.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// pi/4.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// pi/6.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// pi/8.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2.0/sqrt(pi)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1.0/sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log2(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log10(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
impl Float for f64 {
#[inline]
fn nan() -> f64 { NAN }
#[inline]
fn infinity() -> f64 { INFINITY }
#[inline]
fn neg_infinity() -> f64 { NEG_INFINITY }
#[inline]
fn zero() -> f64 { 0.0 }
#[inline]
fn neg_zero() -> f64 { -0.0 }
#[inline]
fn one() -> f64 { 1.0 }
from_str_radix_float_impl! { f64 }
/// Returns `true` if the number is NaN.
#[inline]
fn is_nan(self) -> bool { self!= self }
/// Returns `true` if the number is infinite.
#[inline]
fn is_infinite(self) -> bool {
self == Float::infinity() || self == Float::neg_infinity()
}
/// Returns `true` if the number is neither infinite or NaN.
#[inline]
fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite, subnormal or NaN.
#[inline]
fn is_normal(self) -> bool {
self.classify() == Fp::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
fn classify(self) -> Fp {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits: u64 = unsafe { mem::transmute(self) };
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => Fp::Zero,
(_, 0) => Fp::Subnormal,
(0, EXP_MASK) => Fp::Infinite,
(_, EXP_MASK) => Fp::Nan,
_ => Fp::Normal,
}
}
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits: u64 = unsafe { mem::transmute(self) };
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
// Exponent bias + mantissa shift
exponent -= 1023 + 52;
(mantissa, exponent, sign)
}
/// Rounds towards minus infinity.
#[inline]
fn floor(self) -> f64 {
unsafe { intrinsics::floorf64(self) }
}
/// Rounds towards plus infinity.
#[inline]
fn ceil(self) -> f64 {
unsafe { intrinsics::ceilf64(self) }
}
/// Rounds to nearest integer. Rounds half-way cases away from zero.
#[inline]
fn round(self) -> f64 {
unsafe { intrinsics::roundf64(self) }
}
/// Returns the integer part of the number (rounds towards zero).
#[inline]
fn trunc(self) -> f64 {
unsafe { intrinsics::truncf64(self) }
}
/// The fractional part of the number, satisfying:
///
/// ```
/// let x = 1.65f64;
/// assert!(x == x.trunc() + x.fract())
/// ```
#[inline]
fn fract(self) -> f64 { self - self.trunc() }
/// Computes the absolute value of `self`. Returns `Float::nan()` if the
/// number is `Float::nan()`.
#[inline]
fn abs(self) -> f64 {
unsafe { intrinsics::fabsf64(self) }
}
/// Returns a number that represents the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
/// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
/// - `Float::nan()` if the number is `Float::nan()`
#[inline]
fn signum(self) -> f64 {
if self.is_nan() {
Float::nan()
} else {
unsafe { intrinsics::copysignf64(1.0, self) }
}
}
/// Returns `true` if `self` is positive, including `+0.0` and
/// `Float::infinity()`.
#[inline]
fn is_positive(self) -> bool {
self > 0.0 || (1.0 / self) == Float::infinity()
}
/// Returns `true` if `self` is negative, including `-0.0` and
/// `Float::neg_infinity()`.
#[inline]
fn is_negative(self) -> bool {
self < 0.0 || (1.0 / self) == Float::neg_infinity()
}
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error. This produces a more accurate result with better performance than
/// a separate multiplication operation followed by an add.
#[inline]
fn mul_add(self, a: f64, b: f64) -> f64 {
unsafe { intrinsics::fmaf64(self, a, b) }
}
/// Returns the reciprocal (multiplicative inverse) of the number.
#[inline]
fn recip(self) -> f64 { 1.0 / self }
#[inline]
fn powf(self, n: f64) -> f64 {
unsafe { intrinsics::powf64(self, n) }
}
#[inline]
fn powi(self, n: i32) -> f64 {
unsafe { intrinsics::powif64(self, n) }
}
#[inline]
fn sqrt(self) -> f64 {
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf64(self) }
}
}
#[inline]
fn rsqrt(self) -> f64 { self.sqrt().recip() }
/// Returns the exponential of the number.
#[inline]
fn exp(self) -> f64 {
unsafe { intrinsics::expf64(self) }
}
/// Returns 2 raised to the power of the number.
#[inline]
fn exp2(self) -> f64 {
unsafe { intrinsics::exp2f64(self) }
}
/// Returns the natural logarithm of the number.
#[inline] | unsafe { intrinsics::logf64(self) }
}
/// Returns the logarithm of the number with respect to an arbitrary base.
#[inline]
fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
/// Returns the base 2 logarithm of the number.
#[inline]
fn log2(self) -> f64 {
unsafe { intrinsics::log2f64(self) }
}
/// Returns the base 10 logarithm of the number.
#[inline]
fn log10(self) -> f64 {
unsafe { intrinsics::log10f64(self) }
}
/// Converts to degrees, assuming the number is in radians.
#[inline]
fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) }
/// Converts to radians, assuming the number is in degrees.
#[inline]
fn to_radians(self) -> f64 {
let value: f64 = consts::PI;
self * (value / 180.0)
}
} | fn ln(self) -> f64 { | random_line_split |
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations and constants for 64-bits floats (`f64` type)
#![doc(primitive = "f64")]
// FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353
#![allow(overflowing_literals)]
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::*;
use intrinsics;
use mem;
use num::FpCategory as Fp;
use num::{Float, ParseFloatError};
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const RADIX: u32 = 2;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MANTISSA_DIGITS: u32 = 53;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const DIGITS: u32 = 15;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive, normalized f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_EXP: i32 = -1021;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_EXP: i32 = 1024;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_10_EXP: i32 = -307;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_10_EXP: i32 = 308;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NAN: f64 = 0.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const INFINITY: f64 = 1.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64;
/// Basic mathematial constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// pi * 2.0
#[unstable(feature = "float_consts",
reason = "unclear naming convention/usefulness")]
#[deprecated(since = "1.2.0", reason = "unclear on usefulness")]
pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64;
/// pi/2.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// pi/3.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// pi/4.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// pi/6.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// pi/8.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2.0/sqrt(pi)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1.0/sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log2(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log10(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
impl Float for f64 {
#[inline]
fn nan() -> f64 { NAN }
#[inline]
fn infinity() -> f64 { INFINITY }
#[inline]
fn neg_infinity() -> f64 { NEG_INFINITY }
#[inline]
fn zero() -> f64 { 0.0 }
#[inline]
fn neg_zero() -> f64 { -0.0 }
#[inline]
fn one() -> f64 { 1.0 }
from_str_radix_float_impl! { f64 }
/// Returns `true` if the number is NaN.
#[inline]
fn is_nan(self) -> bool { self!= self }
/// Returns `true` if the number is infinite.
#[inline]
fn is_infinite(self) -> bool {
self == Float::infinity() || self == Float::neg_infinity()
}
/// Returns `true` if the number is neither infinite or NaN.
#[inline]
fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite, subnormal or NaN.
#[inline]
fn is_normal(self) -> bool {
self.classify() == Fp::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
fn classify(self) -> Fp {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits: u64 = unsafe { mem::transmute(self) };
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => Fp::Zero,
(_, 0) => Fp::Subnormal,
(0, EXP_MASK) => Fp::Infinite,
(_, EXP_MASK) => Fp::Nan,
_ => Fp::Normal,
}
}
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits: u64 = unsafe { mem::transmute(self) };
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
// Exponent bias + mantissa shift
exponent -= 1023 + 52;
(mantissa, exponent, sign)
}
/// Rounds towards minus infinity.
#[inline]
fn floor(self) -> f64 {
unsafe { intrinsics::floorf64(self) }
}
/// Rounds towards plus infinity.
#[inline]
fn ceil(self) -> f64 {
unsafe { intrinsics::ceilf64(self) }
}
/// Rounds to nearest integer. Rounds half-way cases away from zero.
#[inline]
fn round(self) -> f64 {
unsafe { intrinsics::roundf64(self) }
}
/// Returns the integer part of the number (rounds towards zero).
#[inline]
fn trunc(self) -> f64 {
unsafe { intrinsics::truncf64(self) }
}
/// The fractional part of the number, satisfying:
///
/// ```
/// let x = 1.65f64;
/// assert!(x == x.trunc() + x.fract())
/// ```
#[inline]
fn fract(self) -> f64 { self - self.trunc() }
/// Computes the absolute value of `self`. Returns `Float::nan()` if the
/// number is `Float::nan()`.
#[inline]
fn abs(self) -> f64 {
unsafe { intrinsics::fabsf64(self) }
}
/// Returns a number that represents the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
/// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
/// - `Float::nan()` if the number is `Float::nan()`
#[inline]
fn signum(self) -> f64 {
if self.is_nan() {
Float::nan()
} else {
unsafe { intrinsics::copysignf64(1.0, self) }
}
}
/// Returns `true` if `self` is positive, including `+0.0` and
/// `Float::infinity()`.
#[inline]
fn is_positive(self) -> bool {
self > 0.0 || (1.0 / self) == Float::infinity()
}
/// Returns `true` if `self` is negative, including `-0.0` and
/// `Float::neg_infinity()`.
#[inline]
fn is_negative(self) -> bool {
self < 0.0 || (1.0 / self) == Float::neg_infinity()
}
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error. This produces a more accurate result with better performance than
/// a separate multiplication operation followed by an add.
#[inline]
fn mul_add(self, a: f64, b: f64) -> f64 {
unsafe { intrinsics::fmaf64(self, a, b) }
}
/// Returns the reciprocal (multiplicative inverse) of the number.
#[inline]
fn | (self) -> f64 { 1.0 / self }
#[inline]
fn powf(self, n: f64) -> f64 {
unsafe { intrinsics::powf64(self, n) }
}
#[inline]
fn powi(self, n: i32) -> f64 {
unsafe { intrinsics::powif64(self, n) }
}
#[inline]
fn sqrt(self) -> f64 {
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf64(self) }
}
}
#[inline]
fn rsqrt(self) -> f64 { self.sqrt().recip() }
/// Returns the exponential of the number.
#[inline]
fn exp(self) -> f64 {
unsafe { intrinsics::expf64(self) }
}
/// Returns 2 raised to the power of the number.
#[inline]
fn exp2(self) -> f64 {
unsafe { intrinsics::exp2f64(self) }
}
/// Returns the natural logarithm of the number.
#[inline]
fn ln(self) -> f64 {
unsafe { intrinsics::logf64(self) }
}
/// Returns the logarithm of the number with respect to an arbitrary base.
#[inline]
fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
/// Returns the base 2 logarithm of the number.
#[inline]
fn log2(self) -> f64 {
unsafe { intrinsics::log2f64(self) }
}
/// Returns the base 10 logarithm of the number.
#[inline]
fn log10(self) -> f64 {
unsafe { intrinsics::log10f64(self) }
}
/// Converts to degrees, assuming the number is in radians.
#[inline]
fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) }
/// Converts to radians, assuming the number is in degrees.
#[inline]
fn to_radians(self) -> f64 {
let value: f64 = consts::PI;
self * (value / 180.0)
}
}
| recip | identifier_name |
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations and constants for 64-bits floats (`f64` type)
#![doc(primitive = "f64")]
// FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353
#![allow(overflowing_literals)]
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::*;
use intrinsics;
use mem;
use num::FpCategory as Fp;
use num::{Float, ParseFloatError};
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const RADIX: u32 = 2;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MANTISSA_DIGITS: u32 = 53;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const DIGITS: u32 = 15;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive, normalized f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_EXP: i32 = -1021;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_EXP: i32 = 1024;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_10_EXP: i32 = -307;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_10_EXP: i32 = 308;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NAN: f64 = 0.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const INFINITY: f64 = 1.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64;
/// Basic mathematial constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// pi * 2.0
#[unstable(feature = "float_consts",
reason = "unclear naming convention/usefulness")]
#[deprecated(since = "1.2.0", reason = "unclear on usefulness")]
pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64;
/// pi/2.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// pi/3.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// pi/4.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// pi/6.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// pi/8.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2.0/sqrt(pi)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1.0/sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log2(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log10(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
impl Float for f64 {
#[inline]
fn nan() -> f64 { NAN }
#[inline]
fn infinity() -> f64 { INFINITY }
#[inline]
fn neg_infinity() -> f64 { NEG_INFINITY }
#[inline]
fn zero() -> f64 { 0.0 }
#[inline]
fn neg_zero() -> f64 { -0.0 }
#[inline]
fn one() -> f64 { 1.0 }
from_str_radix_float_impl! { f64 }
/// Returns `true` if the number is NaN.
#[inline]
fn is_nan(self) -> bool { self!= self }
/// Returns `true` if the number is infinite.
#[inline]
fn is_infinite(self) -> bool {
self == Float::infinity() || self == Float::neg_infinity()
}
/// Returns `true` if the number is neither infinite or NaN.
#[inline]
fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite, subnormal or NaN.
#[inline]
fn is_normal(self) -> bool {
self.classify() == Fp::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
fn classify(self) -> Fp {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits: u64 = unsafe { mem::transmute(self) };
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => Fp::Zero,
(_, 0) => Fp::Subnormal,
(0, EXP_MASK) => Fp::Infinite,
(_, EXP_MASK) => Fp::Nan,
_ => Fp::Normal,
}
}
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits: u64 = unsafe { mem::transmute(self) };
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
// Exponent bias + mantissa shift
exponent -= 1023 + 52;
(mantissa, exponent, sign)
}
/// Rounds towards minus infinity.
#[inline]
fn floor(self) -> f64 {
unsafe { intrinsics::floorf64(self) }
}
/// Rounds towards plus infinity.
#[inline]
fn ceil(self) -> f64 {
unsafe { intrinsics::ceilf64(self) }
}
/// Rounds to nearest integer. Rounds half-way cases away from zero.
#[inline]
fn round(self) -> f64 {
unsafe { intrinsics::roundf64(self) }
}
/// Returns the integer part of the number (rounds towards zero).
#[inline]
fn trunc(self) -> f64 {
unsafe { intrinsics::truncf64(self) }
}
/// The fractional part of the number, satisfying:
///
/// ```
/// let x = 1.65f64;
/// assert!(x == x.trunc() + x.fract())
/// ```
#[inline]
fn fract(self) -> f64 { self - self.trunc() }
/// Computes the absolute value of `self`. Returns `Float::nan()` if the
/// number is `Float::nan()`.
#[inline]
fn abs(self) -> f64 {
unsafe { intrinsics::fabsf64(self) }
}
/// Returns a number that represents the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
/// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
/// - `Float::nan()` if the number is `Float::nan()`
#[inline]
fn signum(self) -> f64 {
if self.is_nan() | else {
unsafe { intrinsics::copysignf64(1.0, self) }
}
}
/// Returns `true` if `self` is positive, including `+0.0` and
/// `Float::infinity()`.
#[inline]
fn is_positive(self) -> bool {
self > 0.0 || (1.0 / self) == Float::infinity()
}
/// Returns `true` if `self` is negative, including `-0.0` and
/// `Float::neg_infinity()`.
#[inline]
fn is_negative(self) -> bool {
self < 0.0 || (1.0 / self) == Float::neg_infinity()
}
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error. This produces a more accurate result with better performance than
/// a separate multiplication operation followed by an add.
#[inline]
fn mul_add(self, a: f64, b: f64) -> f64 {
unsafe { intrinsics::fmaf64(self, a, b) }
}
/// Returns the reciprocal (multiplicative inverse) of the number.
#[inline]
fn recip(self) -> f64 { 1.0 / self }
#[inline]
fn powf(self, n: f64) -> f64 {
unsafe { intrinsics::powf64(self, n) }
}
#[inline]
fn powi(self, n: i32) -> f64 {
unsafe { intrinsics::powif64(self, n) }
}
#[inline]
fn sqrt(self) -> f64 {
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf64(self) }
}
}
#[inline]
fn rsqrt(self) -> f64 { self.sqrt().recip() }
/// Returns the exponential of the number.
#[inline]
fn exp(self) -> f64 {
unsafe { intrinsics::expf64(self) }
}
/// Returns 2 raised to the power of the number.
#[inline]
fn exp2(self) -> f64 {
unsafe { intrinsics::exp2f64(self) }
}
/// Returns the natural logarithm of the number.
#[inline]
fn ln(self) -> f64 {
unsafe { intrinsics::logf64(self) }
}
/// Returns the logarithm of the number with respect to an arbitrary base.
#[inline]
fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
/// Returns the base 2 logarithm of the number.
#[inline]
fn log2(self) -> f64 {
unsafe { intrinsics::log2f64(self) }
}
/// Returns the base 10 logarithm of the number.
#[inline]
fn log10(self) -> f64 {
unsafe { intrinsics::log10f64(self) }
}
/// Converts to degrees, assuming the number is in radians.
#[inline]
fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) }
/// Converts to radians, assuming the number is in degrees.
#[inline]
fn to_radians(self) -> f64 {
let value: f64 = consts::PI;
self * (value / 180.0)
}
}
| {
Float::nan()
} | conditional_block |
f64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations and constants for 64-bits floats (`f64` type)
#![doc(primitive = "f64")]
// FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353
#![allow(overflowing_literals)]
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::*;
use intrinsics;
use mem;
use num::FpCategory as Fp;
use num::{Float, ParseFloatError};
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const RADIX: u32 = 2;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MANTISSA_DIGITS: u32 = 53;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const DIGITS: u32 = 15;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
/// Smallest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f64 = -1.7976931348623157e+308_f64;
/// Smallest positive, normalized f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
/// Largest finite f64 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_EXP: i32 = -1021;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_EXP: i32 = 1024;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MIN_10_EXP: i32 = -307;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const MAX_10_EXP: i32 = 308;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NAN: f64 = 0.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const INFINITY: f64 = 1.0_f64/0.0_f64;
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(missing_docs)]
pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64;
/// Basic mathematial constants.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod consts {
// FIXME: replace with mathematical constants from cmath.
/// Archimedes' constant
#[stable(feature = "rust1", since = "1.0.0")]
pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
/// pi * 2.0
#[unstable(feature = "float_consts",
reason = "unclear naming convention/usefulness")]
#[deprecated(since = "1.2.0", reason = "unclear on usefulness")]
pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64;
/// pi/2.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
/// pi/3.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
/// pi/4.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
/// pi/6.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
/// pi/8.0
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
/// 1.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
/// 2.0/pi
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
/// 2.0/sqrt(pi)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
/// sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
/// 1.0/sqrt(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
/// Euler's number
#[stable(feature = "rust1", since = "1.0.0")]
pub const E: f64 = 2.71828182845904523536028747135266250_f64;
/// log2(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
/// log10(e)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
/// ln(2.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
/// ln(10.0)
#[stable(feature = "rust1", since = "1.0.0")]
pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
impl Float for f64 {
#[inline]
fn nan() -> f64 { NAN }
#[inline]
fn infinity() -> f64 { INFINITY }
#[inline]
fn neg_infinity() -> f64 { NEG_INFINITY }
#[inline]
fn zero() -> f64 { 0.0 }
#[inline]
fn neg_zero() -> f64 { -0.0 }
#[inline]
fn one() -> f64 |
from_str_radix_float_impl! { f64 }
/// Returns `true` if the number is NaN.
#[inline]
fn is_nan(self) -> bool { self!= self }
/// Returns `true` if the number is infinite.
#[inline]
fn is_infinite(self) -> bool {
self == Float::infinity() || self == Float::neg_infinity()
}
/// Returns `true` if the number is neither infinite or NaN.
#[inline]
fn is_finite(self) -> bool {
!(self.is_nan() || self.is_infinite())
}
/// Returns `true` if the number is neither zero, infinite, subnormal or NaN.
#[inline]
fn is_normal(self) -> bool {
self.classify() == Fp::Normal
}
/// Returns the floating point category of the number. If only one property
/// is going to be tested, it is generally faster to use the specific
/// predicate instead.
fn classify(self) -> Fp {
const EXP_MASK: u64 = 0x7ff0000000000000;
const MAN_MASK: u64 = 0x000fffffffffffff;
let bits: u64 = unsafe { mem::transmute(self) };
match (bits & MAN_MASK, bits & EXP_MASK) {
(0, 0) => Fp::Zero,
(_, 0) => Fp::Subnormal,
(0, EXP_MASK) => Fp::Infinite,
(_, EXP_MASK) => Fp::Nan,
_ => Fp::Normal,
}
}
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits: u64 = unsafe { mem::transmute(self) };
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
// Exponent bias + mantissa shift
exponent -= 1023 + 52;
(mantissa, exponent, sign)
}
/// Rounds towards minus infinity.
#[inline]
fn floor(self) -> f64 {
unsafe { intrinsics::floorf64(self) }
}
/// Rounds towards plus infinity.
#[inline]
fn ceil(self) -> f64 {
unsafe { intrinsics::ceilf64(self) }
}
/// Rounds to nearest integer. Rounds half-way cases away from zero.
#[inline]
fn round(self) -> f64 {
unsafe { intrinsics::roundf64(self) }
}
/// Returns the integer part of the number (rounds towards zero).
#[inline]
fn trunc(self) -> f64 {
unsafe { intrinsics::truncf64(self) }
}
/// The fractional part of the number, satisfying:
///
/// ```
/// let x = 1.65f64;
/// assert!(x == x.trunc() + x.fract())
/// ```
#[inline]
fn fract(self) -> f64 { self - self.trunc() }
/// Computes the absolute value of `self`. Returns `Float::nan()` if the
/// number is `Float::nan()`.
#[inline]
fn abs(self) -> f64 {
unsafe { intrinsics::fabsf64(self) }
}
/// Returns a number that represents the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
/// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
/// - `Float::nan()` if the number is `Float::nan()`
#[inline]
fn signum(self) -> f64 {
if self.is_nan() {
Float::nan()
} else {
unsafe { intrinsics::copysignf64(1.0, self) }
}
}
/// Returns `true` if `self` is positive, including `+0.0` and
/// `Float::infinity()`.
#[inline]
fn is_positive(self) -> bool {
self > 0.0 || (1.0 / self) == Float::infinity()
}
/// Returns `true` if `self` is negative, including `-0.0` and
/// `Float::neg_infinity()`.
#[inline]
fn is_negative(self) -> bool {
self < 0.0 || (1.0 / self) == Float::neg_infinity()
}
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error. This produces a more accurate result with better performance than
/// a separate multiplication operation followed by an add.
#[inline]
fn mul_add(self, a: f64, b: f64) -> f64 {
unsafe { intrinsics::fmaf64(self, a, b) }
}
/// Returns the reciprocal (multiplicative inverse) of the number.
#[inline]
fn recip(self) -> f64 { 1.0 / self }
#[inline]
fn powf(self, n: f64) -> f64 {
unsafe { intrinsics::powf64(self, n) }
}
#[inline]
fn powi(self, n: i32) -> f64 {
unsafe { intrinsics::powif64(self, n) }
}
#[inline]
fn sqrt(self) -> f64 {
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf64(self) }
}
}
#[inline]
fn rsqrt(self) -> f64 { self.sqrt().recip() }
/// Returns the exponential of the number.
#[inline]
fn exp(self) -> f64 {
unsafe { intrinsics::expf64(self) }
}
/// Returns 2 raised to the power of the number.
#[inline]
fn exp2(self) -> f64 {
unsafe { intrinsics::exp2f64(self) }
}
/// Returns the natural logarithm of the number.
#[inline]
fn ln(self) -> f64 {
unsafe { intrinsics::logf64(self) }
}
/// Returns the logarithm of the number with respect to an arbitrary base.
#[inline]
fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
/// Returns the base 2 logarithm of the number.
#[inline]
fn log2(self) -> f64 {
unsafe { intrinsics::log2f64(self) }
}
/// Returns the base 10 logarithm of the number.
#[inline]
fn log10(self) -> f64 {
unsafe { intrinsics::log10f64(self) }
}
/// Converts to degrees, assuming the number is in radians.
#[inline]
fn to_degrees(self) -> f64 { self * (180.0f64 / consts::PI) }
/// Converts to radians, assuming the number is in degrees.
#[inline]
fn to_radians(self) -> f64 {
let value: f64 = consts::PI;
self * (value / 180.0)
}
}
| { 1.0 } | identifier_body |
method-self-arg-aux1.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.
// Test method calls with self as an argument (cross-crate)
#![allow(unknown_features)]
#![feature(box_syntax)]
// aux-build:method_self_arg1.rs
extern crate method_self_arg1;
use method_self_arg1::Foo;
fn main() | {
let x = Foo;
// Test external call.
Foo::bar(&x);
Foo::baz(x);
Foo::qux(box x);
x.foo(&x);
assert!(method_self_arg1::get_count() == 2u64*3*3*3*5*5*5*7*7*7);
} | identifier_body |
|
method-self-arg-aux1.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.
// Test method calls with self as an argument (cross-crate)
#![allow(unknown_features)]
#![feature(box_syntax)]
// aux-build:method_self_arg1.rs
extern crate method_self_arg1;
use method_self_arg1::Foo;
fn | () {
let x = Foo;
// Test external call.
Foo::bar(&x);
Foo::baz(x);
Foo::qux(box x);
x.foo(&x);
assert!(method_self_arg1::get_count() == 2u64*3*3*3*5*5*5*7*7*7);
}
| main | identifier_name |
method-self-arg-aux1.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.
// Test method calls with self as an argument (cross-crate)
#![allow(unknown_features)]
#![feature(box_syntax)]
| // aux-build:method_self_arg1.rs
extern crate method_self_arg1;
use method_self_arg1::Foo;
fn main() {
let x = Foo;
// Test external call.
Foo::bar(&x);
Foo::baz(x);
Foo::qux(box x);
x.foo(&x);
assert!(method_self_arg1::get_count() == 2u64*3*3*3*5*5*5*7*7*7);
} | random_line_split |
|
wiggle.rs | //! Dataflow node that generates/propagates/mutates a wiggle.
use util::{modulo_one, almost_eq, angle_almost_eq};
use network::{Network, NodeIndex, GenerationId, NodeId, OutputId, Inputs, Outputs};
use console_server::reactor::Messages;
use wiggles_value::{Data, Unipolar, Datatype};
use wiggles_value::knob::{Knobs, Response as KnobResponse};
use std::collections::HashMap;
use std::time::Duration;
use std::fmt;
use std::any::Any;
use serde::{Serialize, Serializer};
use serde::de::DeserializeOwned;
use serde_json::{Error as SerdeJsonError, self};
use super::serde::SerializableWiggle;
use clocks::clock::{ClockId, ClockProvider};
pub type KnobAddr = u32;
// We need to qualify the knob's address with the wiggle's address to go up into the network.
pub type WiggleKnobAddr = (WiggleId, KnobAddr);
pub trait WiggleProvider {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data;
}
pub trait Wiggle {
/// A string name for this kind of wiggle.
/// This string will be used during serialization and deserialization to uniquely identify
/// how to reconstruct this wiggle from a serialized form.
fn kind(&self) -> &'static str;
/// Return the name that has been assigned to this wiggle.
fn name(&self) -> &str;
/// Rename this wiggle.
fn set_name(&mut self, name: String);
/// Update the state of this wiggle using the provided update interval.
/// Return a message collection of some kind.
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<KnobAddr>>;
/// Render the state of this wiggle, providing its currently-assigned inputs as well as a
/// function that can be used to retrieve the current value of one of those inputs.
/// Specify which output port this wiggle should be rendered for.
/// Also provide access to the clock network if this node needs it.
fn render(
&self,
phase_offset: f64,
type_hint: Option<Datatype>,
inputs: &[Option<(WiggleId, OutputId)>],
output: OutputId,
network: &WiggleProvider,
clocks: &ClockProvider)
-> Data;
/// Return Ok if this wiggle uses a clock input, and return the current value of it.
/// If it doesn't use a clock, return Err.
fn clock_source(&self) -> Result<Option<ClockId>, ()>;
/// Set the clock source for this wiggle.
/// If this wiggle doesn't use a clock, return Err.
fn set_clock(&mut self, source: Option<ClockId>) -> Result<(), ()>;
/// Serialize yourself into JSON.
/// Every wiggle must implement this separately until an erased_serde solution is back in
/// action.
fn as_json(&self) -> Result<String, SerdeJsonError>;
fn serializable(&self) -> Result<SerializableWiggle, SerdeJsonError> {
Ok(SerializableWiggle {
kind: self.kind().to_string(),
serialized: self.as_json()?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct | (NodeIndex, GenerationId);
impl fmt::Display for WiggleId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "wiggle {}, generation {}", self.0, self.1)
}
}
impl NodeId for WiggleId {
fn new(idx: NodeIndex, gen_id: GenerationId) -> Self {
WiggleId(idx, gen_id)
}
fn index(&self) -> NodeIndex {
self.0
}
fn gen_id(&self) -> GenerationId {
self.1
}
}
/// Type alias for a network of wiggles.
pub type WiggleNetwork = Network<Box<CompleteWiggle>, WiggleId, KnobResponse<WiggleKnobAddr>>;
impl WiggleProvider for WiggleNetwork {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data
{
// if we don't have this node, return a default
match self.node(wiggle_id) {
Err(e) => {
error!("Error while trying to get wiggle from {}: {}.", wiggle_id, e);
Data::default_with_type_hint(type_hint)
}
Ok(node) => {
node.inner().render(phase_offset, type_hint, node.inputs(), output_id, self, clocks)
}
}
}
}
pub trait CompleteWiggle:
Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
{
fn eq(&self, other: &CompleteWiggle) -> bool;
fn as_any(&self) -> &Any;
}
impl<T> CompleteWiggle for T
where T:'static
+ Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
+ PartialEq
{
fn eq(&self, other: &CompleteWiggle) -> bool {
other.as_any().downcast_ref::<T>().map_or(false, |x| x == self)
}
fn as_any(&self) -> &Any {
self
}
}
impl<'a, 'b> PartialEq<CompleteWiggle+'b> for CompleteWiggle + 'a {
fn eq(&self, other: &(CompleteWiggle+'b)) -> bool {
CompleteWiggle::eq(self, other)
}
}
impl Outputs<KnobResponse<WiggleKnobAddr>, WiggleId> for Box<CompleteWiggle> {
fn default_output_count(&self) -> u32 {
(**self).default_output_count()
}
fn try_push_output(
&mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> {
(**self).try_push_output(node_id)
}
fn try_pop_output(
&mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> {
(**self).try_pop_output(node_id)
}
}
// TODO: consider generalizing Update and/or Render as traits.
/// Wrapper trait for a wiggle network.
pub trait WiggleCollection {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>>;
}
impl WiggleCollection for WiggleNetwork {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>> {
let mut update_messages = Messages::none();
{
let update = |node_id: WiggleId, wiggle: &mut Box<CompleteWiggle>| {
// lift the address of this message up into the network address space
let address_lifter = |knob_num| (node_id, knob_num);
let mut messages = wiggle.update(dt);
for message in messages.drain() {
let lifted_message = message.lift_address(&address_lifter);
(&mut update_messages).push(lifted_message);
}
};
self.map_inner(update);
}
update_messages
}
}
| WiggleId | identifier_name |
wiggle.rs | //! Dataflow node that generates/propagates/mutates a wiggle.
use util::{modulo_one, almost_eq, angle_almost_eq};
use network::{Network, NodeIndex, GenerationId, NodeId, OutputId, Inputs, Outputs};
use console_server::reactor::Messages;
use wiggles_value::{Data, Unipolar, Datatype};
use wiggles_value::knob::{Knobs, Response as KnobResponse};
use std::collections::HashMap;
use std::time::Duration;
use std::fmt;
use std::any::Any;
use serde::{Serialize, Serializer};
use serde::de::DeserializeOwned;
use serde_json::{Error as SerdeJsonError, self};
use super::serde::SerializableWiggle;
use clocks::clock::{ClockId, ClockProvider};
pub type KnobAddr = u32;
// We need to qualify the knob's address with the wiggle's address to go up into the network.
pub type WiggleKnobAddr = (WiggleId, KnobAddr);
pub trait WiggleProvider {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data;
}
pub trait Wiggle {
/// A string name for this kind of wiggle.
/// This string will be used during serialization and deserialization to uniquely identify
/// how to reconstruct this wiggle from a serialized form.
fn kind(&self) -> &'static str;
/// Return the name that has been assigned to this wiggle.
fn name(&self) -> &str;
/// Rename this wiggle.
fn set_name(&mut self, name: String);
/// Update the state of this wiggle using the provided update interval.
/// Return a message collection of some kind.
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<KnobAddr>>;
/// Render the state of this wiggle, providing its currently-assigned inputs as well as a
/// function that can be used to retrieve the current value of one of those inputs.
/// Specify which output port this wiggle should be rendered for.
/// Also provide access to the clock network if this node needs it.
fn render(
&self,
phase_offset: f64,
type_hint: Option<Datatype>,
inputs: &[Option<(WiggleId, OutputId)>],
output: OutputId,
network: &WiggleProvider,
clocks: &ClockProvider)
-> Data;
/// Return Ok if this wiggle uses a clock input, and return the current value of it.
/// If it doesn't use a clock, return Err.
fn clock_source(&self) -> Result<Option<ClockId>, ()>;
/// Set the clock source for this wiggle.
/// If this wiggle doesn't use a clock, return Err.
fn set_clock(&mut self, source: Option<ClockId>) -> Result<(), ()>;
/// Serialize yourself into JSON.
/// Every wiggle must implement this separately until an erased_serde solution is back in
/// action.
fn as_json(&self) -> Result<String, SerdeJsonError>;
fn serializable(&self) -> Result<SerializableWiggle, SerdeJsonError> {
Ok(SerializableWiggle {
kind: self.kind().to_string(),
serialized: self.as_json()?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WiggleId(NodeIndex, GenerationId);
impl fmt::Display for WiggleId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "wiggle {}, generation {}", self.0, self.1)
}
}
impl NodeId for WiggleId {
fn new(idx: NodeIndex, gen_id: GenerationId) -> Self {
WiggleId(idx, gen_id)
}
fn index(&self) -> NodeIndex {
self.0
}
fn gen_id(&self) -> GenerationId {
self.1
}
}
/// Type alias for a network of wiggles.
pub type WiggleNetwork = Network<Box<CompleteWiggle>, WiggleId, KnobResponse<WiggleKnobAddr>>;
impl WiggleProvider for WiggleNetwork {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data
{
// if we don't have this node, return a default
match self.node(wiggle_id) {
Err(e) => {
error!("Error while trying to get wiggle from {}: {}.", wiggle_id, e);
Data::default_with_type_hint(type_hint)
}
Ok(node) => {
node.inner().render(phase_offset, type_hint, node.inputs(), output_id, self, clocks)
}
}
}
}
pub trait CompleteWiggle:
Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
{
fn eq(&self, other: &CompleteWiggle) -> bool;
fn as_any(&self) -> &Any;
}
impl<T> CompleteWiggle for T
where T:'static
+ Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
+ PartialEq
{
fn eq(&self, other: &CompleteWiggle) -> bool {
other.as_any().downcast_ref::<T>().map_or(false, |x| x == self)
}
fn as_any(&self) -> &Any {
self
}
}
impl<'a, 'b> PartialEq<CompleteWiggle+'b> for CompleteWiggle + 'a {
fn eq(&self, other: &(CompleteWiggle+'b)) -> bool {
CompleteWiggle::eq(self, other)
}
}
impl Outputs<KnobResponse<WiggleKnobAddr>, WiggleId> for Box<CompleteWiggle> {
fn default_output_count(&self) -> u32 {
(**self).default_output_count()
}
fn try_push_output(
&mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> {
(**self).try_push_output(node_id)
}
fn try_pop_output( | (**self).try_pop_output(node_id)
}
}
// TODO: consider generalizing Update and/or Render as traits.
/// Wrapper trait for a wiggle network.
pub trait WiggleCollection {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>>;
}
impl WiggleCollection for WiggleNetwork {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>> {
let mut update_messages = Messages::none();
{
let update = |node_id: WiggleId, wiggle: &mut Box<CompleteWiggle>| {
// lift the address of this message up into the network address space
let address_lifter = |knob_num| (node_id, knob_num);
let mut messages = wiggle.update(dt);
for message in messages.drain() {
let lifted_message = message.lift_address(&address_lifter);
(&mut update_messages).push(lifted_message);
}
};
self.map_inner(update);
}
update_messages
}
} | &mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> { | random_line_split |
wiggle.rs | //! Dataflow node that generates/propagates/mutates a wiggle.
use util::{modulo_one, almost_eq, angle_almost_eq};
use network::{Network, NodeIndex, GenerationId, NodeId, OutputId, Inputs, Outputs};
use console_server::reactor::Messages;
use wiggles_value::{Data, Unipolar, Datatype};
use wiggles_value::knob::{Knobs, Response as KnobResponse};
use std::collections::HashMap;
use std::time::Duration;
use std::fmt;
use std::any::Any;
use serde::{Serialize, Serializer};
use serde::de::DeserializeOwned;
use serde_json::{Error as SerdeJsonError, self};
use super::serde::SerializableWiggle;
use clocks::clock::{ClockId, ClockProvider};
pub type KnobAddr = u32;
// We need to qualify the knob's address with the wiggle's address to go up into the network.
pub type WiggleKnobAddr = (WiggleId, KnobAddr);
pub trait WiggleProvider {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data;
}
pub trait Wiggle {
/// A string name for this kind of wiggle.
/// This string will be used during serialization and deserialization to uniquely identify
/// how to reconstruct this wiggle from a serialized form.
fn kind(&self) -> &'static str;
/// Return the name that has been assigned to this wiggle.
fn name(&self) -> &str;
/// Rename this wiggle.
fn set_name(&mut self, name: String);
/// Update the state of this wiggle using the provided update interval.
/// Return a message collection of some kind.
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<KnobAddr>>;
/// Render the state of this wiggle, providing its currently-assigned inputs as well as a
/// function that can be used to retrieve the current value of one of those inputs.
/// Specify which output port this wiggle should be rendered for.
/// Also provide access to the clock network if this node needs it.
fn render(
&self,
phase_offset: f64,
type_hint: Option<Datatype>,
inputs: &[Option<(WiggleId, OutputId)>],
output: OutputId,
network: &WiggleProvider,
clocks: &ClockProvider)
-> Data;
/// Return Ok if this wiggle uses a clock input, and return the current value of it.
/// If it doesn't use a clock, return Err.
fn clock_source(&self) -> Result<Option<ClockId>, ()>;
/// Set the clock source for this wiggle.
/// If this wiggle doesn't use a clock, return Err.
fn set_clock(&mut self, source: Option<ClockId>) -> Result<(), ()>;
/// Serialize yourself into JSON.
/// Every wiggle must implement this separately until an erased_serde solution is back in
/// action.
fn as_json(&self) -> Result<String, SerdeJsonError>;
fn serializable(&self) -> Result<SerializableWiggle, SerdeJsonError> {
Ok(SerializableWiggle {
kind: self.kind().to_string(),
serialized: self.as_json()?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WiggleId(NodeIndex, GenerationId);
impl fmt::Display for WiggleId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
impl NodeId for WiggleId {
fn new(idx: NodeIndex, gen_id: GenerationId) -> Self {
WiggleId(idx, gen_id)
}
fn index(&self) -> NodeIndex {
self.0
}
fn gen_id(&self) -> GenerationId {
self.1
}
}
/// Type alias for a network of wiggles.
pub type WiggleNetwork = Network<Box<CompleteWiggle>, WiggleId, KnobResponse<WiggleKnobAddr>>;
impl WiggleProvider for WiggleNetwork {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data
{
// if we don't have this node, return a default
match self.node(wiggle_id) {
Err(e) => {
error!("Error while trying to get wiggle from {}: {}.", wiggle_id, e);
Data::default_with_type_hint(type_hint)
}
Ok(node) => {
node.inner().render(phase_offset, type_hint, node.inputs(), output_id, self, clocks)
}
}
}
}
pub trait CompleteWiggle:
Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
{
fn eq(&self, other: &CompleteWiggle) -> bool;
fn as_any(&self) -> &Any;
}
impl<T> CompleteWiggle for T
where T:'static
+ Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
+ PartialEq
{
fn eq(&self, other: &CompleteWiggle) -> bool {
other.as_any().downcast_ref::<T>().map_or(false, |x| x == self)
}
fn as_any(&self) -> &Any {
self
}
}
impl<'a, 'b> PartialEq<CompleteWiggle+'b> for CompleteWiggle + 'a {
fn eq(&self, other: &(CompleteWiggle+'b)) -> bool {
CompleteWiggle::eq(self, other)
}
}
impl Outputs<KnobResponse<WiggleKnobAddr>, WiggleId> for Box<CompleteWiggle> {
fn default_output_count(&self) -> u32 {
(**self).default_output_count()
}
fn try_push_output(
&mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> {
(**self).try_push_output(node_id)
}
fn try_pop_output(
&mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> {
(**self).try_pop_output(node_id)
}
}
// TODO: consider generalizing Update and/or Render as traits.
/// Wrapper trait for a wiggle network.
pub trait WiggleCollection {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>>;
}
impl WiggleCollection for WiggleNetwork {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>> {
let mut update_messages = Messages::none();
{
let update = |node_id: WiggleId, wiggle: &mut Box<CompleteWiggle>| {
// lift the address of this message up into the network address space
let address_lifter = |knob_num| (node_id, knob_num);
let mut messages = wiggle.update(dt);
for message in messages.drain() {
let lifted_message = message.lift_address(&address_lifter);
(&mut update_messages).push(lifted_message);
}
};
self.map_inner(update);
}
update_messages
}
}
| {
write!(f, "wiggle {}, generation {}", self.0, self.1)
} | identifier_body |
wiggle.rs | //! Dataflow node that generates/propagates/mutates a wiggle.
use util::{modulo_one, almost_eq, angle_almost_eq};
use network::{Network, NodeIndex, GenerationId, NodeId, OutputId, Inputs, Outputs};
use console_server::reactor::Messages;
use wiggles_value::{Data, Unipolar, Datatype};
use wiggles_value::knob::{Knobs, Response as KnobResponse};
use std::collections::HashMap;
use std::time::Duration;
use std::fmt;
use std::any::Any;
use serde::{Serialize, Serializer};
use serde::de::DeserializeOwned;
use serde_json::{Error as SerdeJsonError, self};
use super::serde::SerializableWiggle;
use clocks::clock::{ClockId, ClockProvider};
pub type KnobAddr = u32;
// We need to qualify the knob's address with the wiggle's address to go up into the network.
pub type WiggleKnobAddr = (WiggleId, KnobAddr);
pub trait WiggleProvider {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data;
}
pub trait Wiggle {
/// A string name for this kind of wiggle.
/// This string will be used during serialization and deserialization to uniquely identify
/// how to reconstruct this wiggle from a serialized form.
fn kind(&self) -> &'static str;
/// Return the name that has been assigned to this wiggle.
fn name(&self) -> &str;
/// Rename this wiggle.
fn set_name(&mut self, name: String);
/// Update the state of this wiggle using the provided update interval.
/// Return a message collection of some kind.
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<KnobAddr>>;
/// Render the state of this wiggle, providing its currently-assigned inputs as well as a
/// function that can be used to retrieve the current value of one of those inputs.
/// Specify which output port this wiggle should be rendered for.
/// Also provide access to the clock network if this node needs it.
fn render(
&self,
phase_offset: f64,
type_hint: Option<Datatype>,
inputs: &[Option<(WiggleId, OutputId)>],
output: OutputId,
network: &WiggleProvider,
clocks: &ClockProvider)
-> Data;
/// Return Ok if this wiggle uses a clock input, and return the current value of it.
/// If it doesn't use a clock, return Err.
fn clock_source(&self) -> Result<Option<ClockId>, ()>;
/// Set the clock source for this wiggle.
/// If this wiggle doesn't use a clock, return Err.
fn set_clock(&mut self, source: Option<ClockId>) -> Result<(), ()>;
/// Serialize yourself into JSON.
/// Every wiggle must implement this separately until an erased_serde solution is back in
/// action.
fn as_json(&self) -> Result<String, SerdeJsonError>;
fn serializable(&self) -> Result<SerializableWiggle, SerdeJsonError> {
Ok(SerializableWiggle {
kind: self.kind().to_string(),
serialized: self.as_json()?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WiggleId(NodeIndex, GenerationId);
impl fmt::Display for WiggleId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "wiggle {}, generation {}", self.0, self.1)
}
}
impl NodeId for WiggleId {
fn new(idx: NodeIndex, gen_id: GenerationId) -> Self {
WiggleId(idx, gen_id)
}
fn index(&self) -> NodeIndex {
self.0
}
fn gen_id(&self) -> GenerationId {
self.1
}
}
/// Type alias for a network of wiggles.
pub type WiggleNetwork = Network<Box<CompleteWiggle>, WiggleId, KnobResponse<WiggleKnobAddr>>;
impl WiggleProvider for WiggleNetwork {
fn get_value(
&self,
wiggle_id: WiggleId,
output_id: OutputId,
phase_offset: f64,
type_hint: Option<Datatype>,
clocks: &ClockProvider)
-> Data
{
// if we don't have this node, return a default
match self.node(wiggle_id) {
Err(e) => {
error!("Error while trying to get wiggle from {}: {}.", wiggle_id, e);
Data::default_with_type_hint(type_hint)
}
Ok(node) => |
}
}
}
pub trait CompleteWiggle:
Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
{
fn eq(&self, other: &CompleteWiggle) -> bool;
fn as_any(&self) -> &Any;
}
impl<T> CompleteWiggle for T
where T:'static
+ Wiggle
+ Inputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Outputs<KnobResponse<WiggleKnobAddr>, WiggleId>
+ Knobs<KnobAddr>
+ fmt::Debug
+ PartialEq
{
fn eq(&self, other: &CompleteWiggle) -> bool {
other.as_any().downcast_ref::<T>().map_or(false, |x| x == self)
}
fn as_any(&self) -> &Any {
self
}
}
impl<'a, 'b> PartialEq<CompleteWiggle+'b> for CompleteWiggle + 'a {
fn eq(&self, other: &(CompleteWiggle+'b)) -> bool {
CompleteWiggle::eq(self, other)
}
}
impl Outputs<KnobResponse<WiggleKnobAddr>, WiggleId> for Box<CompleteWiggle> {
fn default_output_count(&self) -> u32 {
(**self).default_output_count()
}
fn try_push_output(
&mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> {
(**self).try_push_output(node_id)
}
fn try_pop_output(
&mut self, node_id: WiggleId) -> Result<Messages<KnobResponse<WiggleKnobAddr>>, ()> {
(**self).try_pop_output(node_id)
}
}
// TODO: consider generalizing Update and/or Render as traits.
/// Wrapper trait for a wiggle network.
pub trait WiggleCollection {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>>;
}
impl WiggleCollection for WiggleNetwork {
fn update(&mut self, dt: Duration) -> Messages<KnobResponse<WiggleKnobAddr>> {
let mut update_messages = Messages::none();
{
let update = |node_id: WiggleId, wiggle: &mut Box<CompleteWiggle>| {
// lift the address of this message up into the network address space
let address_lifter = |knob_num| (node_id, knob_num);
let mut messages = wiggle.update(dt);
for message in messages.drain() {
let lifted_message = message.lift_address(&address_lifter);
(&mut update_messages).push(lifted_message);
}
};
self.map_inner(update);
}
update_messages
}
}
| {
node.inner().render(phase_offset, type_hint, node.inputs(), output_id, self, clocks)
} | conditional_block |
create_mock.rs | use std::path::Path;
use clap::ArgMatches;
use itertools::Itertools;
use log::*;
use serde_json::Value;
use pact_models::pact::{Pact, ReadWritePact};
use pact_models::sync_pact::RequestResponsePact;
use crate::handle_error;
pub async fn create_mock_server(host: &str, port: u16, matches: &ArgMatches<'_>) -> Result<(), i32> {
let file = matches.value_of("file").unwrap();
log::info!("Creating mock server from file {}", file);
match RequestResponsePact::read_pact(Path::new(file)) { | }
if matches.is_present("tls") {
info!("Setting mock server to use TLS");
args.push("tls=true");
}
let url = if args.is_empty() {
format!("http://{}:{}/", host, port)
} else {
format!("http://{}:{}/?{}", host, port, args.iter().join("&"))
};
let client = reqwest::Client::new();
let json = match pact.to_json(pact.specification_version()) {
Ok(json) => json,
Err(err) => {
crate::display_error(format!("Failed to send pact as JSON '{}': {}", file, err), matches);
}
};
let resp = client.post(url.as_str())
.json(&json)
.send().await;
match resp {
Ok(response) => {
if response.status().is_success() {
match response.json::<Value>().await {
Ok(json) => {
debug!("Got response from master server: {:?}", json);
let mock_server = json.get("mockServer")
.ok_or_else(|| handle_error("Invalid JSON received from master server - no mockServer attribute"))?;
let id = mock_server.get("id")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no id attribute"))?
.as_str().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer id attribute is not a string"))?;
let port = mock_server.get("port")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no port attribute"))?
.as_u64().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer port attribute is not a number"))?;
println!("Mock server {} started on port {}", id, port);
Ok(())
},
Err(err) => {
error!("Failed to parse JSON: {}", err);
crate::display_error(format!("Failed to parse JSON: {}", err), matches);
}
}
} else {
crate::display_error(format!("Master mock server returned an error: {}\n{}",
response.status(), response.text().await.unwrap_or_default()), matches);
}
}
Err(err) => {
crate::display_error(format!("Failed to connect to the master mock server '{}': {}", url, err), matches);
}
}
},
Err(err) => {
crate::display_error(format!("Failed to load pact file '{}': {}", file, err), matches);
}
}
} | Ok(ref pact) => {
let mut args = vec![];
if matches.is_present("cors") {
info!("Setting mock server to handle CORS pre-flight requests");
args.push("cors=true"); | random_line_split |
create_mock.rs | use std::path::Path;
use clap::ArgMatches;
use itertools::Itertools;
use log::*;
use serde_json::Value;
use pact_models::pact::{Pact, ReadWritePact};
use pact_models::sync_pact::RequestResponsePact;
use crate::handle_error;
pub async fn create_mock_server(host: &str, port: u16, matches: &ArgMatches<'_>) -> Result<(), i32> | let client = reqwest::Client::new();
let json = match pact.to_json(pact.specification_version()) {
Ok(json) => json,
Err(err) => {
crate::display_error(format!("Failed to send pact as JSON '{}': {}", file, err), matches);
}
};
let resp = client.post(url.as_str())
.json(&json)
.send().await;
match resp {
Ok(response) => {
if response.status().is_success() {
match response.json::<Value>().await {
Ok(json) => {
debug!("Got response from master server: {:?}", json);
let mock_server = json.get("mockServer")
.ok_or_else(|| handle_error("Invalid JSON received from master server - no mockServer attribute"))?;
let id = mock_server.get("id")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no id attribute"))?
.as_str().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer id attribute is not a string"))?;
let port = mock_server.get("port")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no port attribute"))?
.as_u64().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer port attribute is not a number"))?;
println!("Mock server {} started on port {}", id, port);
Ok(())
},
Err(err) => {
error!("Failed to parse JSON: {}", err);
crate::display_error(format!("Failed to parse JSON: {}", err), matches);
}
}
} else {
crate::display_error(format!("Master mock server returned an error: {}\n{}",
response.status(), response.text().await.unwrap_or_default()), matches);
}
}
Err(err) => {
crate::display_error(format!("Failed to connect to the master mock server '{}': {}", url, err), matches);
}
}
},
Err(err) => {
crate::display_error(format!("Failed to load pact file '{}': {}", file, err), matches);
}
}
}
| {
let file = matches.value_of("file").unwrap();
log::info!("Creating mock server from file {}", file);
match RequestResponsePact::read_pact(Path::new(file)) {
Ok(ref pact) => {
let mut args = vec![];
if matches.is_present("cors") {
info!("Setting mock server to handle CORS pre-flight requests");
args.push("cors=true");
}
if matches.is_present("tls") {
info!("Setting mock server to use TLS");
args.push("tls=true");
}
let url = if args.is_empty() {
format!("http://{}:{}/", host, port)
} else {
format!("http://{}:{}/?{}", host, port, args.iter().join("&"))
}; | identifier_body |
create_mock.rs | use std::path::Path;
use clap::ArgMatches;
use itertools::Itertools;
use log::*;
use serde_json::Value;
use pact_models::pact::{Pact, ReadWritePact};
use pact_models::sync_pact::RequestResponsePact;
use crate::handle_error;
pub async fn create_mock_server(host: &str, port: u16, matches: &ArgMatches<'_>) -> Result<(), i32> {
let file = matches.value_of("file").unwrap();
log::info!("Creating mock server from file {}", file);
match RequestResponsePact::read_pact(Path::new(file)) {
Ok(ref pact) => {
let mut args = vec![];
if matches.is_present("cors") {
info!("Setting mock server to handle CORS pre-flight requests");
args.push("cors=true");
}
if matches.is_present("tls") {
info!("Setting mock server to use TLS");
args.push("tls=true");
}
let url = if args.is_empty() {
format!("http://{}:{}/", host, port)
} else {
format!("http://{}:{}/?{}", host, port, args.iter().join("&"))
};
let client = reqwest::Client::new();
let json = match pact.to_json(pact.specification_version()) {
Ok(json) => json,
Err(err) => {
crate::display_error(format!("Failed to send pact as JSON '{}': {}", file, err), matches);
}
};
let resp = client.post(url.as_str())
.json(&json)
.send().await;
match resp {
Ok(response) => {
if response.status().is_success() {
match response.json::<Value>().await {
Ok(json) => {
debug!("Got response from master server: {:?}", json);
let mock_server = json.get("mockServer")
.ok_or_else(|| handle_error("Invalid JSON received from master server - no mockServer attribute"))?;
let id = mock_server.get("id")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no id attribute"))?
.as_str().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer id attribute is not a string"))?;
let port = mock_server.get("port")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no port attribute"))?
.as_u64().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer port attribute is not a number"))?;
println!("Mock server {} started on port {}", id, port);
Ok(())
},
Err(err) => {
error!("Failed to parse JSON: {}", err);
crate::display_error(format!("Failed to parse JSON: {}", err), matches);
}
}
} else {
crate::display_error(format!("Master mock server returned an error: {}\n{}",
response.status(), response.text().await.unwrap_or_default()), matches);
}
}
Err(err) => {
crate::display_error(format!("Failed to connect to the master mock server '{}': {}", url, err), matches);
}
}
},
Err(err) => |
}
}
| {
crate::display_error(format!("Failed to load pact file '{}': {}", file, err), matches);
} | conditional_block |
create_mock.rs | use std::path::Path;
use clap::ArgMatches;
use itertools::Itertools;
use log::*;
use serde_json::Value;
use pact_models::pact::{Pact, ReadWritePact};
use pact_models::sync_pact::RequestResponsePact;
use crate::handle_error;
pub async fn | (host: &str, port: u16, matches: &ArgMatches<'_>) -> Result<(), i32> {
let file = matches.value_of("file").unwrap();
log::info!("Creating mock server from file {}", file);
match RequestResponsePact::read_pact(Path::new(file)) {
Ok(ref pact) => {
let mut args = vec![];
if matches.is_present("cors") {
info!("Setting mock server to handle CORS pre-flight requests");
args.push("cors=true");
}
if matches.is_present("tls") {
info!("Setting mock server to use TLS");
args.push("tls=true");
}
let url = if args.is_empty() {
format!("http://{}:{}/", host, port)
} else {
format!("http://{}:{}/?{}", host, port, args.iter().join("&"))
};
let client = reqwest::Client::new();
let json = match pact.to_json(pact.specification_version()) {
Ok(json) => json,
Err(err) => {
crate::display_error(format!("Failed to send pact as JSON '{}': {}", file, err), matches);
}
};
let resp = client.post(url.as_str())
.json(&json)
.send().await;
match resp {
Ok(response) => {
if response.status().is_success() {
match response.json::<Value>().await {
Ok(json) => {
debug!("Got response from master server: {:?}", json);
let mock_server = json.get("mockServer")
.ok_or_else(|| handle_error("Invalid JSON received from master server - no mockServer attribute"))?;
let id = mock_server.get("id")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no id attribute"))?
.as_str().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer id attribute is not a string"))?;
let port = mock_server.get("port")
.ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer has no port attribute"))?
.as_u64().ok_or_else(|| handle_error("Invalid JSON received from master server - mockServer port attribute is not a number"))?;
println!("Mock server {} started on port {}", id, port);
Ok(())
},
Err(err) => {
error!("Failed to parse JSON: {}", err);
crate::display_error(format!("Failed to parse JSON: {}", err), matches);
}
}
} else {
crate::display_error(format!("Master mock server returned an error: {}\n{}",
response.status(), response.text().await.unwrap_or_default()), matches);
}
}
Err(err) => {
crate::display_error(format!("Failed to connect to the master mock server '{}': {}", url, err), matches);
}
}
},
Err(err) => {
crate::display_error(format!("Failed to load pact file '{}': {}", file, err), matches);
}
}
}
| create_mock_server | identifier_name |
borrowck-vec-pattern-nesting.rs | fn a() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[~ref _a] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
_ => fail!("foo")
}
}
fn b() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._b] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
}
}
fn c() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a,.._b] => {
//~^ ERROR cannot move out
// Note: `_a` is *moved* here, but `b` is borrowing,
// hence illegal.
//
// See comment in middle/borrowck/gather_loans/mod.rs
// in the case covering these sorts of vectors. | _ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn d() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._a, _b] => {
//~^ ERROR cannot move out
}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn e() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a, _b, _c] => {}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn main() {} | } | random_line_split |
borrowck-vec-pattern-nesting.rs | fn a() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[~ref _a] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
_ => fail!("foo")
}
}
fn b() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._b] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
}
}
fn c() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a,.._b] => {
//~^ ERROR cannot move out
// Note: `_a` is *moved* here, but `b` is borrowing,
// hence illegal.
//
// See comment in middle/borrowck/gather_loans/mod.rs
// in the case covering these sorts of vectors.
}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn d() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._a, _b] => {
//~^ ERROR cannot move out
}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn e() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a, _b, _c] => {}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn main() | {} | identifier_body |
|
borrowck-vec-pattern-nesting.rs | fn a() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[~ref _a] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
_ => fail!("foo")
}
}
fn | () {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._b] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
}
}
fn c() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a,.._b] => {
//~^ ERROR cannot move out
// Note: `_a` is *moved* here, but `b` is borrowing,
// hence illegal.
//
// See comment in middle/borrowck/gather_loans/mod.rs
// in the case covering these sorts of vectors.
}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn d() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._a, _b] => {
//~^ ERROR cannot move out
}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn e() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a, _b, _c] => {}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn main() {}
| b | identifier_name |
borrowck-vec-pattern-nesting.rs | fn a() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[~ref _a] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
_ => fail!("foo")
}
}
fn b() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._b] => {
vec[0] = ~4; //~ ERROR cannot assign to `(*vec)[]` because it is borrowed
}
}
}
fn c() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a,.._b] => {
//~^ ERROR cannot move out
// Note: `_a` is *moved* here, but `b` is borrowing,
// hence illegal.
//
// See comment in middle/borrowck/gather_loans/mod.rs
// in the case covering these sorts of vectors.
}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn d() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[.._a, _b] => {
//~^ ERROR cannot move out
}
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn e() {
let mut vec = ~[~1, ~2, ~3];
match vec {
[_a, _b, _c] => |
_ => {}
}
let a = vec[0]; //~ ERROR use of partially moved value: `vec`
}
fn main() {}
| {} | conditional_block |
flate.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Some various other I/O types
// FIXME(#3660): should move to libextra
use prelude::*;
use super::*;
/// A Writer decorator that compresses using the 'deflate' scheme
pub struct DeflateWriter<W> {
inner_writer: W
}
impl<W: Writer> DeflateWriter<W> {
pub fn new(inner_writer: W) -> DeflateWriter<W> {
DeflateWriter {
inner_writer: inner_writer
}
}
}
impl<W: Writer> Writer for DeflateWriter<W> {
fn | (&mut self, _buf: &[u8]) { fail2!() }
fn flush(&mut self) { fail2!() }
}
impl<W: Writer> Decorator<W> for DeflateWriter<W> {
fn inner(self) -> W {
match self {
DeflateWriter { inner_writer: w } => w
}
}
fn inner_ref<'a>(&'a self) -> &'a W {
match *self {
DeflateWriter { inner_writer: ref w } => w
}
}
fn inner_mut_ref<'a>(&'a mut self) -> &'a mut W {
match *self {
DeflateWriter { inner_writer: ref mut w } => w
}
}
}
/// A Reader decorator that decompresses using the 'deflate' scheme
pub struct InflateReader<R> {
inner_reader: R
}
impl<R: Reader> InflateReader<R> {
pub fn new(inner_reader: R) -> InflateReader<R> {
InflateReader {
inner_reader: inner_reader
}
}
}
impl<R: Reader> Reader for InflateReader<R> {
fn read(&mut self, _buf: &mut [u8]) -> Option<uint> { fail2!() }
fn eof(&mut self) -> bool { fail2!() }
}
impl<R: Reader> Decorator<R> for InflateReader<R> {
fn inner(self) -> R {
match self {
InflateReader { inner_reader: r } => r
}
}
fn inner_ref<'a>(&'a self) -> &'a R {
match *self {
InflateReader { inner_reader: ref r } => r
}
}
fn inner_mut_ref<'a>(&'a mut self) -> &'a mut R {
match *self {
InflateReader { inner_reader: ref mut r } => r
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::*;
use super::super::mem::*;
use super::super::Decorator;
use str;
#[test]
#[ignore]
fn smoke_test() {
let mem_writer = MemWriter::new();
let mut deflate_writer = DeflateWriter::new(mem_writer);
let in_msg = "test";
let in_bytes = in_msg.as_bytes();
deflate_writer.write(in_bytes);
deflate_writer.flush();
let buf = deflate_writer.inner().inner();
let mem_reader = MemReader::new(buf);
let mut inflate_reader = InflateReader::new(mem_reader);
let mut out_bytes = [0,.. 100];
let bytes_read = inflate_reader.read(out_bytes).unwrap();
assert_eq!(bytes_read, in_bytes.len());
let out_msg = str::from_utf8(out_bytes);
assert!(in_msg == out_msg);
}
}
| write | identifier_name |
flate.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Some various other I/O types
// FIXME(#3660): should move to libextra
use prelude::*;
use super::*;
/// A Writer decorator that compresses using the 'deflate' scheme
pub struct DeflateWriter<W> {
inner_writer: W
}
impl<W: Writer> DeflateWriter<W> {
pub fn new(inner_writer: W) -> DeflateWriter<W> {
DeflateWriter {
inner_writer: inner_writer
}
}
}
impl<W: Writer> Writer for DeflateWriter<W> {
fn write(&mut self, _buf: &[u8]) { fail2!() }
fn flush(&mut self) { fail2!() }
}
impl<W: Writer> Decorator<W> for DeflateWriter<W> {
fn inner(self) -> W {
match self {
DeflateWriter { inner_writer: w } => w
}
}
fn inner_ref<'a>(&'a self) -> &'a W {
match *self {
DeflateWriter { inner_writer: ref w } => w
}
}
fn inner_mut_ref<'a>(&'a mut self) -> &'a mut W {
match *self {
DeflateWriter { inner_writer: ref mut w } => w
}
}
}
/// A Reader decorator that decompresses using the 'deflate' scheme
pub struct InflateReader<R> {
inner_reader: R
}
impl<R: Reader> InflateReader<R> {
pub fn new(inner_reader: R) -> InflateReader<R> {
InflateReader {
inner_reader: inner_reader
}
}
}
impl<R: Reader> Reader for InflateReader<R> {
fn read(&mut self, _buf: &mut [u8]) -> Option<uint> { fail2!() }
fn eof(&mut self) -> bool { fail2!() }
}
impl<R: Reader> Decorator<R> for InflateReader<R> {
fn inner(self) -> R {
match self {
InflateReader { inner_reader: r } => r
}
}
fn inner_ref<'a>(&'a self) -> &'a R {
match *self { | InflateReader { inner_reader: ref r } => r
}
}
fn inner_mut_ref<'a>(&'a mut self) -> &'a mut R {
match *self {
InflateReader { inner_reader: ref mut r } => r
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::*;
use super::super::mem::*;
use super::super::Decorator;
use str;
#[test]
#[ignore]
fn smoke_test() {
let mem_writer = MemWriter::new();
let mut deflate_writer = DeflateWriter::new(mem_writer);
let in_msg = "test";
let in_bytes = in_msg.as_bytes();
deflate_writer.write(in_bytes);
deflate_writer.flush();
let buf = deflate_writer.inner().inner();
let mem_reader = MemReader::new(buf);
let mut inflate_reader = InflateReader::new(mem_reader);
let mut out_bytes = [0,.. 100];
let bytes_read = inflate_reader.read(out_bytes).unwrap();
assert_eq!(bytes_read, in_bytes.len());
let out_msg = str::from_utf8(out_bytes);
assert!(in_msg == out_msg);
}
} | random_line_split |
|
flate.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Some various other I/O types
// FIXME(#3660): should move to libextra
use prelude::*;
use super::*;
/// A Writer decorator that compresses using the 'deflate' scheme
pub struct DeflateWriter<W> {
inner_writer: W
}
impl<W: Writer> DeflateWriter<W> {
pub fn new(inner_writer: W) -> DeflateWriter<W> {
DeflateWriter {
inner_writer: inner_writer
}
}
}
impl<W: Writer> Writer for DeflateWriter<W> {
fn write(&mut self, _buf: &[u8]) { fail2!() }
fn flush(&mut self) { fail2!() }
}
impl<W: Writer> Decorator<W> for DeflateWriter<W> {
fn inner(self) -> W {
match self {
DeflateWriter { inner_writer: w } => w
}
}
fn inner_ref<'a>(&'a self) -> &'a W {
match *self {
DeflateWriter { inner_writer: ref w } => w
}
}
fn inner_mut_ref<'a>(&'a mut self) -> &'a mut W {
match *self {
DeflateWriter { inner_writer: ref mut w } => w
}
}
}
/// A Reader decorator that decompresses using the 'deflate' scheme
pub struct InflateReader<R> {
inner_reader: R
}
impl<R: Reader> InflateReader<R> {
pub fn new(inner_reader: R) -> InflateReader<R> {
InflateReader {
inner_reader: inner_reader
}
}
}
impl<R: Reader> Reader for InflateReader<R> {
fn read(&mut self, _buf: &mut [u8]) -> Option<uint> { fail2!() }
fn eof(&mut self) -> bool { fail2!() }
}
impl<R: Reader> Decorator<R> for InflateReader<R> {
fn inner(self) -> R |
fn inner_ref<'a>(&'a self) -> &'a R {
match *self {
InflateReader { inner_reader: ref r } => r
}
}
fn inner_mut_ref<'a>(&'a mut self) -> &'a mut R {
match *self {
InflateReader { inner_reader: ref mut r } => r
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::*;
use super::super::mem::*;
use super::super::Decorator;
use str;
#[test]
#[ignore]
fn smoke_test() {
let mem_writer = MemWriter::new();
let mut deflate_writer = DeflateWriter::new(mem_writer);
let in_msg = "test";
let in_bytes = in_msg.as_bytes();
deflate_writer.write(in_bytes);
deflate_writer.flush();
let buf = deflate_writer.inner().inner();
let mem_reader = MemReader::new(buf);
let mut inflate_reader = InflateReader::new(mem_reader);
let mut out_bytes = [0,.. 100];
let bytes_read = inflate_reader.read(out_bytes).unwrap();
assert_eq!(bytes_read, in_bytes.len());
let out_msg = str::from_utf8(out_bytes);
assert!(in_msg == out_msg);
}
}
| {
match self {
InflateReader { inner_reader: r } => r
}
} | identifier_body |
work_mode.rs | use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, // generate widgets etc.
Sys, // generate -sys with FFI
Doc, // generate documentation file
DisplayNotBound, // Show not bound types
}
impl WorkMode {
pub fn is_normal(self) -> bool {
match self {
WorkMode::Normal => true,
_ => false,
}
}
pub fn is_generate_rust_files(self) -> bool {
match self {
WorkMode::Normal => true,
WorkMode::Sys => true,
_ => false,
}
}
}
impl Default for WorkMode {
fn default() -> WorkMode {
WorkMode::Normal
}
}
impl FromStr for WorkMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s { | "sys" => Ok(WorkMode::Sys),
"doc" => Ok(WorkMode::Doc),
"not_bound" => Ok(WorkMode::DisplayNotBound),
_ => Err(format!("Wrong work mode '{}'", s)),
}
}
} | "normal" => Ok(WorkMode::Normal), | random_line_split |
work_mode.rs | use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, // generate widgets etc.
Sys, // generate -sys with FFI
Doc, // generate documentation file
DisplayNotBound, // Show not bound types
}
impl WorkMode {
pub fn is_normal(self) -> bool {
match self {
WorkMode::Normal => true,
_ => false,
}
}
pub fn is_generate_rust_files(self) -> bool {
match self {
WorkMode::Normal => true,
WorkMode::Sys => true,
_ => false,
}
}
}
impl Default for WorkMode {
fn default() -> WorkMode {
WorkMode::Normal
}
}
impl FromStr for WorkMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> |
}
| {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
"doc" => Ok(WorkMode::Doc),
"not_bound" => Ok(WorkMode::DisplayNotBound),
_ => Err(format!("Wrong work mode '{}'", s)),
}
} | identifier_body |
work_mode.rs | use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, // generate widgets etc.
Sys, // generate -sys with FFI
Doc, // generate documentation file
DisplayNotBound, // Show not bound types
}
impl WorkMode {
pub fn is_normal(self) -> bool {
match self {
WorkMode::Normal => true,
_ => false,
}
}
pub fn is_generate_rust_files(self) -> bool {
match self {
WorkMode::Normal => true,
WorkMode::Sys => true,
_ => false,
}
}
}
impl Default for WorkMode {
fn default() -> WorkMode {
WorkMode::Normal
}
}
impl FromStr for WorkMode {
type Err = String;
fn | (s: &str) -> Result<Self, Self::Err> {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
"doc" => Ok(WorkMode::Doc),
"not_bound" => Ok(WorkMode::DisplayNotBound),
_ => Err(format!("Wrong work mode '{}'", s)),
}
}
}
| from_str | identifier_name |
stars.rs | use futures::prelude::*;
use hubcaps::{Credentials, Github};
use std::env;
use std::error::Error;
#[tokio::main]
async fn | () -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
let token = env::var("GITHUB_TOKEN")?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let stars = github.activity().stars();
let f = futures::future::try_join(
stars.star("softprops", "hubcaps"),
stars.is_starred("softprops", "hubcaps"),
);
match f.await {
Ok((_, starred)) => println!("starred? {:?}", starred),
Err(err) => println!("err {}", err),
}
stars
.iter("softprops")
.try_for_each(|s| async move {
println!("{:?}", s.html_url);
Ok(())
})
.await?;
Ok(())
}
| main | identifier_name |
stars.rs | use futures::prelude::*;
use hubcaps::{Credentials, Github};
use std::env;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> | println!("{:?}", s.html_url);
Ok(())
})
.await?;
Ok(())
}
| {
pretty_env_logger::init();
let token = env::var("GITHUB_TOKEN")?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let stars = github.activity().stars();
let f = futures::future::try_join(
stars.star("softprops", "hubcaps"),
stars.is_starred("softprops", "hubcaps"),
);
match f.await {
Ok((_, starred)) => println!("starred? {:?}", starred),
Err(err) => println!("err {}", err),
}
stars
.iter("softprops")
.try_for_each(|s| async move { | identifier_body |
stars.rs | use futures::prelude::*;
use hubcaps::{Credentials, Github};
use std::env;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
let token = env::var("GITHUB_TOKEN")?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let stars = github.activity().stars();
let f = futures::future::try_join(
stars.star("softprops", "hubcaps"),
stars.is_starred("softprops", "hubcaps"),
);
match f.await {
Ok((_, starred)) => println!("starred? {:?}", starred),
Err(err) => println!("err {}", err),
} | .try_for_each(|s| async move {
println!("{:?}", s.html_url);
Ok(())
})
.await?;
Ok(())
} |
stars
.iter("softprops") | random_line_split |
auto-encode.rs | // xfail-fast
// 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.
#[forbid(deprecated_pattern)];
extern mod std;
// These tests used to be separate files, but I wanted to refactor all
// the common code.
use EBReader = std::ebml::reader;
use EBWriter = std::ebml::writer;
use core::cmp::Eq;
use core::io::Writer;
use std::ebml;
use std::serialize::{Encodable, Decodable};
use std::time;
fn test_ebml<A:
Eq +
Encodable<EBWriter::Encoder> +
Decodable<EBReader::Decoder>
>(a1: &A) {
let bytes = do io::with_bytes_writer |wr| {
let ebml_w = &EBWriter::Encoder(wr);
a1.encode(ebml_w)
};
let d = EBReader::Doc(@bytes);
let a2: A = Decodable::decode(&EBReader::Decoder(d));
assert!(*a1 == a2);
}
#[auto_encode]
#[auto_decode]
enum Expr {
Val(uint),
Plus(@Expr, @Expr),
Minus(@Expr, @Expr)
}
impl cmp::Eq for Expr {
fn eq(&self, other: &Expr) -> bool {
match *self {
Val(e0a) => {
match *other {
Val(e0b) => e0a == e0b,
_ => false
}
}
Plus(e0a, e1a) => {
match *other {
Plus(e0b, e1b) => e0a == e0b && e1a == e1b,
_ => false
}
}
Minus(e0a, e1a) => {
match *other {
Minus(e0b, e1b) => e0a == e0b && e1a == e1b,
_ => false
}
}
}
}
fn ne(&self, other: &Expr) -> bool {!(*self).eq(other) }
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
self.x == other.x && self.y == other.y
}
fn ne(&self, other: &Point) -> bool {!(*self).eq(other) }
}
impl<T:cmp::Eq> cmp::Eq for Quark<T> {
fn eq(&self, other: &Quark<T>) -> bool {
match *self {
Top(ref q) => {
match *other {
Top(ref r) => q == r,
Bottom(_) => false
}
},
Bottom(ref q) => {
match *other {
Top(_) => false,
Bottom(ref r) => q == r
}
},
}
}
fn ne(&self, other: &Quark<T>) -> bool {!(*self).eq(other) }
}
impl cmp::Eq for CLike {
fn | (&self, other: &CLike) -> bool {
(*self) as int == *other as int
}
fn ne(&self, other: &CLike) -> bool {!self.eq(other) }
}
#[auto_encode]
#[auto_decode]
#[deriving(Eq)]
struct Spanned<T> {
lo: uint,
hi: uint,
node: T,
}
#[auto_encode]
#[auto_decode]
struct SomeStruct { v: ~[uint] }
#[auto_encode]
#[auto_decode]
struct Point {x: uint, y: uint}
#[auto_encode]
#[auto_decode]
enum Quark<T> {
Top(T),
Bottom(T)
}
#[auto_encode]
#[auto_decode]
enum CLike { A, B, C }
pub fn main() {
let a = &Plus(@Minus(@Val(3u), @Val(10u)), @Plus(@Val(22u), @Val(5u)));
test_ebml(a);
let a = &Spanned {lo: 0u, hi: 5u, node: 22u};
test_ebml(a);
let a = &Point {x: 3u, y: 5u};
test_ebml(a);
let a = &@[1u, 2u, 3u];
test_ebml(a);
let a = &Top(22u);
test_ebml(a);
let a = &Bottom(222u);
test_ebml(a);
let a = &A;
test_ebml(a);
let a = &B;
test_ebml(a);
let a = &time::now();
test_ebml(a);
}
| eq | identifier_name |
auto-encode.rs | // xfail-fast
// 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.
#[forbid(deprecated_pattern)];
extern mod std;
// These tests used to be separate files, but I wanted to refactor all
// the common code.
use EBReader = std::ebml::reader;
use EBWriter = std::ebml::writer;
use core::cmp::Eq;
use core::io::Writer;
use std::ebml;
use std::serialize::{Encodable, Decodable};
use std::time;
fn test_ebml<A:
Eq +
Encodable<EBWriter::Encoder> +
Decodable<EBReader::Decoder>
>(a1: &A) {
let bytes = do io::with_bytes_writer |wr| {
let ebml_w = &EBWriter::Encoder(wr);
a1.encode(ebml_w)
};
let d = EBReader::Doc(@bytes);
let a2: A = Decodable::decode(&EBReader::Decoder(d));
assert!(*a1 == a2);
}
#[auto_encode]
#[auto_decode]
enum Expr {
Val(uint),
Plus(@Expr, @Expr),
Minus(@Expr, @Expr)
}
impl cmp::Eq for Expr {
fn eq(&self, other: &Expr) -> bool {
match *self {
Val(e0a) => {
match *other {
Val(e0b) => e0a == e0b,
_ => false
}
}
Plus(e0a, e1a) => {
match *other {
Plus(e0b, e1b) => e0a == e0b && e1a == e1b,
_ => false
}
}
Minus(e0a, e1a) => {
match *other {
Minus(e0b, e1b) => e0a == e0b && e1a == e1b,
_ => false
}
}
}
}
fn ne(&self, other: &Expr) -> bool {!(*self).eq(other) }
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
self.x == other.x && self.y == other.y
}
fn ne(&self, other: &Point) -> bool {!(*self).eq(other) }
}
impl<T:cmp::Eq> cmp::Eq for Quark<T> {
fn eq(&self, other: &Quark<T>) -> bool {
match *self {
Top(ref q) => {
match *other {
Top(ref r) => q == r,
Bottom(_) => false
}
},
Bottom(ref q) => {
match *other {
Top(_) => false,
Bottom(ref r) => q == r
}
},
}
}
fn ne(&self, other: &Quark<T>) -> bool {!(*self).eq(other) }
}
impl cmp::Eq for CLike {
fn eq(&self, other: &CLike) -> bool {
(*self) as int == *other as int
}
fn ne(&self, other: &CLike) -> bool {!self.eq(other) }
}
#[auto_encode]
#[auto_decode]
#[deriving(Eq)] | lo: uint,
hi: uint,
node: T,
}
#[auto_encode]
#[auto_decode]
struct SomeStruct { v: ~[uint] }
#[auto_encode]
#[auto_decode]
struct Point {x: uint, y: uint}
#[auto_encode]
#[auto_decode]
enum Quark<T> {
Top(T),
Bottom(T)
}
#[auto_encode]
#[auto_decode]
enum CLike { A, B, C }
pub fn main() {
let a = &Plus(@Minus(@Val(3u), @Val(10u)), @Plus(@Val(22u), @Val(5u)));
test_ebml(a);
let a = &Spanned {lo: 0u, hi: 5u, node: 22u};
test_ebml(a);
let a = &Point {x: 3u, y: 5u};
test_ebml(a);
let a = &@[1u, 2u, 3u];
test_ebml(a);
let a = &Top(22u);
test_ebml(a);
let a = &Bottom(222u);
test_ebml(a);
let a = &A;
test_ebml(a);
let a = &B;
test_ebml(a);
let a = &time::now();
test_ebml(a);
} | struct Spanned<T> { | random_line_split |
serving.rs | // Copyright (c) 2016-2018 The http-serve developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::Entity;
use crate::etag;
use crate::range;
use bytes::Buf;
use futures_core::Stream;
use futures_util::stream::{self, StreamExt};
use http::header::{self, HeaderMap, HeaderValue};
use http::{self, Method, Request, Response, StatusCode};
use http_body::Body;
use httpdate::{fmt_http_date, parse_http_date};
use pin_project::pin_project;
use smallvec::SmallVec;
use std::future::Future;
use std::io::Write;
use std::ops::Range;
use std::pin::Pin;
use std::time::SystemTime;
const MAX_DECIMAL_U64_BYTES: usize = 20; // u64::max_value().to_string().len()
fn parse_modified_hdrs(
etag: &Option<HeaderValue>,
req_hdrs: &HeaderMap,
last_modified: Option<SystemTime>,
) -> Result<(bool, bool), &'static str> {
let precondition_failed = if!etag::any_match(etag, req_hdrs)? {
true
} else if let (Some(ref m), Some(ref since)) =
(last_modified, req_hdrs.get(header::IF_UNMODIFIED_SINCE))
{
const ERR: &str = "Unparseable If-Unmodified-Since";
*m > parse_http_date(since.to_str().map_err(|_| ERR)?).map_err(|_| ERR)?
} else {
false
};
let not_modified = if!etag::none_match(&etag, req_hdrs).unwrap_or(true) {
true
} else if let (Some(ref m), Some(ref since)) =
(last_modified, req_hdrs.get(header::IF_MODIFIED_SINCE))
{
const ERR: &str = "Unparseable If-Modified-Since";
*m <= parse_http_date(since.to_str().map_err(|_| ERR)?).map_err(|_| ERR)?
} else {
false
};
Ok((precondition_failed, not_modified))
}
fn static_body<D, E>(s: &'static str) -> Box<dyn Stream<Item = Result<D, E>> + Send>
where
D:'static + Send + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send,
{
Box::new(stream::once(futures_util::future::ok(s.as_bytes().into())))
}
fn empty_body<D, E>() -> Box<dyn Stream<Item = Result<D, E>> + Send>
where
D:'static + Send + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send,
{
Box::new(stream::empty())
}
/// Serves GET and HEAD requests for a given byte-ranged entity.
/// Handles conditional & subrange requests.
/// The caller is expected to have already determined the correct entity and appended
/// `Expires`, `Cache-Control`, and `Vary` headers if desired.
pub fn serve<
Ent: Entity,
B: Body + From<Box<dyn Stream<Item = Result<Ent::Data, Ent::Error>> + Send>>,
BI,
>(
entity: Ent,
req: &Request<BI>,
) -> Response<B> {
// serve takes entity itself for ownership, as needed for the multipart case. But to avoid
// monomorphization code bloat when there are many implementations of Entity<Data, Error>,
// delegate as much as possible to functions which take a reference to a trait object.
match serve_inner(&entity, req) {
ServeInner::Simple(res) => res,
ServeInner::Multipart {
res,
mut part_headers,
ranges,
} => {
let bodies = stream::unfold(0, move |state| {
next_multipart_body_chunk(state, &entity, &ranges[..], &mut part_headers[..])
});
let body = bodies.flatten();
let body: Box<dyn Stream<Item = Result<Ent::Data, Ent::Error>> + Send> = Box::new(body);
res.body(body.into()).unwrap()
}
}
}
/// An instruction from `serve_inner` to `serve` on how to respond.
enum ServeInner<B> {
Simple(Response<B>),
Multipart {
res: http::response::Builder,
part_headers: Vec<Vec<u8>>,
ranges: SmallVec<[Range<u64>; 1]>,
},
}
/// Runs trait object-based inner logic for `serve`.
fn serve_inner<
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
B: Body + From<Box<dyn Stream<Item = Result<D, E>> + Send>>,
BI,
>(
ent: &dyn Entity<Error = E, Data = D>,
req: &Request<BI>,
) -> ServeInner<B> {
if *req.method()!= Method::GET && *req.method()!= Method::HEAD {
return ServeInner::Simple(
Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED) | .header(header::ALLOW, HeaderValue::from_static("get, head"))
.body(static_body::<D, E>("This resource only supports GET and HEAD.").into())
.unwrap(),
);
}
let last_modified = ent.last_modified();
let etag = ent.etag();
let (precondition_failed, not_modified) =
match parse_modified_hdrs(&etag, req.headers(), last_modified) {
Err(s) => {
return ServeInner::Simple(
Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(static_body::<D, E>(s).into())
.unwrap(),
)
}
Ok(p) => p,
};
// See RFC 7233 section 4.1 <https://tools.ietf.org/html/rfc7233#section-4.1>: a Partial
// Content response should include other representation header fields (aka entity-headers in
// RFC 2616) iff the client didn't specify If-Range.
let mut range_hdr = req.headers().get(header::RANGE);
let include_entity_headers_on_range = match req.headers().get(header::IF_RANGE) {
Some(ref if_range) => {
let if_range = if_range.as_bytes();
if if_range.starts_with(b"W/\"") || if_range.starts_with(b"\"") {
// etag case.
if let Some(ref some_etag) = etag {
if etag::strong_eq(if_range, some_etag.as_bytes()) {
false
} else {
range_hdr = None;
true
}
} else {
range_hdr = None;
true
}
} else {
// Date case.
// Use the strong validation rules for an origin server:
// <https://tools.ietf.org/html/rfc7232#section-2.2.2>.
// The resource could have changed twice in the supplied second, so never match.
range_hdr = None;
true
}
}
None => true,
};
let mut res =
Response::builder().header(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
if let Some(m) = last_modified {
// See RFC 7232 section 2.2.1 <https://tools.ietf.org/html/rfc7232#section-2.2.1>: the
// Last-Modified must not exceed the Date. To guarantee this, set the Date now rather than
// let hyper set it.
let d = SystemTime::now();
res = res.header(header::DATE, fmt_http_date(d));
let clamped_m = std::cmp::min(m, d);
res = res.header(header::LAST_MODIFIED, fmt_http_date(clamped_m));
}
if let Some(e) = etag {
res = res.header(http::header::ETAG, e);
}
if precondition_failed {
res = res.status(StatusCode::PRECONDITION_FAILED);
return ServeInner::Simple(
res.body(static_body::<D, E>("Precondition failed").into())
.unwrap(),
);
}
if not_modified {
res = res.status(StatusCode::NOT_MODIFIED);
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
let len = ent.len();
let (range, include_entity_headers) = match range::parse(range_hdr, len) {
range::ResolvedRanges::None => (0..len, true),
range::ResolvedRanges::Satisfiable(ranges) => {
if ranges.len() == 1 {
res = res.header(
header::CONTENT_RANGE,
unsafe_fmt_ascii_val!(
MAX_DECIMAL_U64_BYTES * 3 + "bytes -/".len(),
"bytes {}-{}/{}",
ranges[0].start,
ranges[0].end - 1,
len
),
);
res = res.status(StatusCode::PARTIAL_CONTENT);
(ranges[0].clone(), include_entity_headers_on_range)
} else {
// Before serving multiple ranges via multipart/byteranges, estimate the total
// length. ("80" is the RFC's estimate of the size of each part's header.) If it's
// more than simply serving the whole entity, do that instead.
let est_len: u64 = ranges.iter().map(|r| 80 + r.end - r.start).sum();
if est_len < len {
let (res, part_headers) = prepare_multipart(
ent,
res,
&ranges[..],
len,
include_entity_headers_on_range,
);
if *req.method() == Method::HEAD {
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
return ServeInner::Multipart {
res,
part_headers,
ranges,
};
}
(0..len, true)
}
}
range::ResolvedRanges::NotSatisfiable => {
res = res.header(
http::header::CONTENT_RANGE,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES + "bytes */".len(), "bytes */{}", len),
);
res = res.status(StatusCode::RANGE_NOT_SATISFIABLE);
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
};
res = res.header(
header::CONTENT_LENGTH,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES, "{}", range.end - range.start),
);
let body = match *req.method() {
Method::HEAD => empty_body::<D, E>(),
_ => ent.get_range(range),
};
let mut res = res.body(body.into()).unwrap();
if include_entity_headers {
ent.add_headers(res.headers_mut());
}
ServeInner::Simple(res)
}
/// A body for use in the "stream of streams" (see `prepare_multipart` and its call site).
/// This avoids an extra allocation for the part headers and overall trailer.
#[pin_project(project=InnerBodyProj)]
enum InnerBody<D, E> {
Once(Option<D>),
// The box variant _holds_ a pin but isn't structurally pinned.
B(Pin<Box<dyn Stream<Item = Result<D, E>> + Sync + Send>>),
}
impl<D, E> Stream for InnerBody<D, E> {
type Item = Result<D, E>;
fn poll_next(
self: Pin<&mut Self>,
ctx: &mut std::task::Context,
) -> std::task::Poll<Option<Result<D, E>>> {
let mut this = self.project();
match this {
InnerBodyProj::Once(ref mut o) => std::task::Poll::Ready(o.take().map(Ok)),
InnerBodyProj::B(b) => b.as_mut().poll_next(ctx),
}
}
}
/// Prepares to send a `multipart/mixed` response.
/// Returns the response builder (with overall headers added) and each part's headers.
fn prepare_multipart<D, E>(
ent: &dyn Entity<Data = D, Error = E>,
mut res: http::response::Builder,
ranges: &[Range<u64>],
len: u64,
include_entity_headers: bool,
) -> (http::response::Builder, Vec<Vec<u8>>)
where
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
{
let mut each_part_headers = Vec::new();
if include_entity_headers {
let mut h = http::header::HeaderMap::new();
ent.add_headers(&mut h);
each_part_headers.reserve(
h.iter()
.map(|(k, v)| k.as_str().len() + v.as_bytes().len() + 4)
.sum::<usize>()
+ 2,
);
for (k, v) in &h {
each_part_headers.extend_from_slice(k.as_str().as_bytes());
each_part_headers.extend_from_slice(b": ");
each_part_headers.extend_from_slice(v.as_bytes());
each_part_headers.extend_from_slice(b"\r\n");
}
}
each_part_headers.extend_from_slice(b"\r\n");
let mut body_len = 0;
let mut part_headers: Vec<Vec<u8>> = Vec::with_capacity(2 * ranges.len() + 1);
for r in ranges {
let mut buf = Vec::with_capacity(64 + each_part_headers.len());
write!(
&mut buf,
"\r\n--B\r\nContent-Range: bytes {}-{}/{}\r\n",
r.start,
r.end - 1,
len
)
.unwrap();
buf.extend_from_slice(&each_part_headers);
body_len += buf.len() as u64 + r.end - r.start;
part_headers.push(buf);
}
body_len += PART_TRAILER.len() as u64;
res = res.header(
header::CONTENT_LENGTH,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES, "{}", body_len),
);
res = res.header(
header::CONTENT_TYPE,
HeaderValue::from_static("multipart/byteranges; boundary=B"),
);
res = res.status(StatusCode::PARTIAL_CONTENT);
(res, part_headers)
}
/// The trailer after all `multipart/byteranges` body parts.
const PART_TRAILER: &[u8] = b"\r\n--B--\r\n";
/// Produces a single chunk of the body and the following state, for use in an `unfold` call.
///
/// Alternates between portions of `part_headers` and their corresponding bodies, then the overall
/// trailer, then end the stream.
fn next_multipart_body_chunk<D, E>(
state: usize,
ent: &dyn Entity<Data = D, Error = E>,
ranges: &[Range<u64>],
part_headers: &mut [Vec<u8>],
) -> impl Future<Output = Option<(InnerBody<D, E>, usize)>>
where
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
{
let i = state >> 1;
let odd = (state & 1) == 1;
let body = if i == ranges.len() && odd {
return futures_util::future::ready(None);
} else if i == ranges.len() {
InnerBody::Once(Some(PART_TRAILER.into()))
} else if odd {
InnerBody::B(Pin::from(ent.get_range(ranges[i].clone())))
} else {
let v = std::mem::take(&mut part_headers[i]);
InnerBody::Once(Some(v.into()))
};
futures_util::future::ready(Some((body, state + 1)))
} | random_line_split |
|
serving.rs | // Copyright (c) 2016-2018 The http-serve developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::Entity;
use crate::etag;
use crate::range;
use bytes::Buf;
use futures_core::Stream;
use futures_util::stream::{self, StreamExt};
use http::header::{self, HeaderMap, HeaderValue};
use http::{self, Method, Request, Response, StatusCode};
use http_body::Body;
use httpdate::{fmt_http_date, parse_http_date};
use pin_project::pin_project;
use smallvec::SmallVec;
use std::future::Future;
use std::io::Write;
use std::ops::Range;
use std::pin::Pin;
use std::time::SystemTime;
const MAX_DECIMAL_U64_BYTES: usize = 20; // u64::max_value().to_string().len()
fn parse_modified_hdrs(
etag: &Option<HeaderValue>,
req_hdrs: &HeaderMap,
last_modified: Option<SystemTime>,
) -> Result<(bool, bool), &'static str> {
let precondition_failed = if!etag::any_match(etag, req_hdrs)? {
true
} else if let (Some(ref m), Some(ref since)) =
(last_modified, req_hdrs.get(header::IF_UNMODIFIED_SINCE))
{
const ERR: &str = "Unparseable If-Unmodified-Since";
*m > parse_http_date(since.to_str().map_err(|_| ERR)?).map_err(|_| ERR)?
} else {
false
};
let not_modified = if!etag::none_match(&etag, req_hdrs).unwrap_or(true) {
true
} else if let (Some(ref m), Some(ref since)) =
(last_modified, req_hdrs.get(header::IF_MODIFIED_SINCE))
{
const ERR: &str = "Unparseable If-Modified-Since";
*m <= parse_http_date(since.to_str().map_err(|_| ERR)?).map_err(|_| ERR)?
} else {
false
};
Ok((precondition_failed, not_modified))
}
fn static_body<D, E>(s: &'static str) -> Box<dyn Stream<Item = Result<D, E>> + Send>
where
D:'static + Send + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send,
{
Box::new(stream::once(futures_util::future::ok(s.as_bytes().into())))
}
fn empty_body<D, E>() -> Box<dyn Stream<Item = Result<D, E>> + Send>
where
D:'static + Send + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send,
{
Box::new(stream::empty())
}
/// Serves GET and HEAD requests for a given byte-ranged entity.
/// Handles conditional & subrange requests.
/// The caller is expected to have already determined the correct entity and appended
/// `Expires`, `Cache-Control`, and `Vary` headers if desired.
pub fn serve<
Ent: Entity,
B: Body + From<Box<dyn Stream<Item = Result<Ent::Data, Ent::Error>> + Send>>,
BI,
>(
entity: Ent,
req: &Request<BI>,
) -> Response<B> |
/// An instruction from `serve_inner` to `serve` on how to respond.
enum ServeInner<B> {
Simple(Response<B>),
Multipart {
res: http::response::Builder,
part_headers: Vec<Vec<u8>>,
ranges: SmallVec<[Range<u64>; 1]>,
},
}
/// Runs trait object-based inner logic for `serve`.
fn serve_inner<
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
B: Body + From<Box<dyn Stream<Item = Result<D, E>> + Send>>,
BI,
>(
ent: &dyn Entity<Error = E, Data = D>,
req: &Request<BI>,
) -> ServeInner<B> {
if *req.method()!= Method::GET && *req.method()!= Method::HEAD {
return ServeInner::Simple(
Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.header(header::ALLOW, HeaderValue::from_static("get, head"))
.body(static_body::<D, E>("This resource only supports GET and HEAD.").into())
.unwrap(),
);
}
let last_modified = ent.last_modified();
let etag = ent.etag();
let (precondition_failed, not_modified) =
match parse_modified_hdrs(&etag, req.headers(), last_modified) {
Err(s) => {
return ServeInner::Simple(
Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(static_body::<D, E>(s).into())
.unwrap(),
)
}
Ok(p) => p,
};
// See RFC 7233 section 4.1 <https://tools.ietf.org/html/rfc7233#section-4.1>: a Partial
// Content response should include other representation header fields (aka entity-headers in
// RFC 2616) iff the client didn't specify If-Range.
let mut range_hdr = req.headers().get(header::RANGE);
let include_entity_headers_on_range = match req.headers().get(header::IF_RANGE) {
Some(ref if_range) => {
let if_range = if_range.as_bytes();
if if_range.starts_with(b"W/\"") || if_range.starts_with(b"\"") {
// etag case.
if let Some(ref some_etag) = etag {
if etag::strong_eq(if_range, some_etag.as_bytes()) {
false
} else {
range_hdr = None;
true
}
} else {
range_hdr = None;
true
}
} else {
// Date case.
// Use the strong validation rules for an origin server:
// <https://tools.ietf.org/html/rfc7232#section-2.2.2>.
// The resource could have changed twice in the supplied second, so never match.
range_hdr = None;
true
}
}
None => true,
};
let mut res =
Response::builder().header(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
if let Some(m) = last_modified {
// See RFC 7232 section 2.2.1 <https://tools.ietf.org/html/rfc7232#section-2.2.1>: the
// Last-Modified must not exceed the Date. To guarantee this, set the Date now rather than
// let hyper set it.
let d = SystemTime::now();
res = res.header(header::DATE, fmt_http_date(d));
let clamped_m = std::cmp::min(m, d);
res = res.header(header::LAST_MODIFIED, fmt_http_date(clamped_m));
}
if let Some(e) = etag {
res = res.header(http::header::ETAG, e);
}
if precondition_failed {
res = res.status(StatusCode::PRECONDITION_FAILED);
return ServeInner::Simple(
res.body(static_body::<D, E>("Precondition failed").into())
.unwrap(),
);
}
if not_modified {
res = res.status(StatusCode::NOT_MODIFIED);
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
let len = ent.len();
let (range, include_entity_headers) = match range::parse(range_hdr, len) {
range::ResolvedRanges::None => (0..len, true),
range::ResolvedRanges::Satisfiable(ranges) => {
if ranges.len() == 1 {
res = res.header(
header::CONTENT_RANGE,
unsafe_fmt_ascii_val!(
MAX_DECIMAL_U64_BYTES * 3 + "bytes -/".len(),
"bytes {}-{}/{}",
ranges[0].start,
ranges[0].end - 1,
len
),
);
res = res.status(StatusCode::PARTIAL_CONTENT);
(ranges[0].clone(), include_entity_headers_on_range)
} else {
// Before serving multiple ranges via multipart/byteranges, estimate the total
// length. ("80" is the RFC's estimate of the size of each part's header.) If it's
// more than simply serving the whole entity, do that instead.
let est_len: u64 = ranges.iter().map(|r| 80 + r.end - r.start).sum();
if est_len < len {
let (res, part_headers) = prepare_multipart(
ent,
res,
&ranges[..],
len,
include_entity_headers_on_range,
);
if *req.method() == Method::HEAD {
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
return ServeInner::Multipart {
res,
part_headers,
ranges,
};
}
(0..len, true)
}
}
range::ResolvedRanges::NotSatisfiable => {
res = res.header(
http::header::CONTENT_RANGE,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES + "bytes */".len(), "bytes */{}", len),
);
res = res.status(StatusCode::RANGE_NOT_SATISFIABLE);
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
};
res = res.header(
header::CONTENT_LENGTH,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES, "{}", range.end - range.start),
);
let body = match *req.method() {
Method::HEAD => empty_body::<D, E>(),
_ => ent.get_range(range),
};
let mut res = res.body(body.into()).unwrap();
if include_entity_headers {
ent.add_headers(res.headers_mut());
}
ServeInner::Simple(res)
}
/// A body for use in the "stream of streams" (see `prepare_multipart` and its call site).
/// This avoids an extra allocation for the part headers and overall trailer.
#[pin_project(project=InnerBodyProj)]
enum InnerBody<D, E> {
Once(Option<D>),
// The box variant _holds_ a pin but isn't structurally pinned.
B(Pin<Box<dyn Stream<Item = Result<D, E>> + Sync + Send>>),
}
impl<D, E> Stream for InnerBody<D, E> {
type Item = Result<D, E>;
fn poll_next(
self: Pin<&mut Self>,
ctx: &mut std::task::Context,
) -> std::task::Poll<Option<Result<D, E>>> {
let mut this = self.project();
match this {
InnerBodyProj::Once(ref mut o) => std::task::Poll::Ready(o.take().map(Ok)),
InnerBodyProj::B(b) => b.as_mut().poll_next(ctx),
}
}
}
/// Prepares to send a `multipart/mixed` response.
/// Returns the response builder (with overall headers added) and each part's headers.
fn prepare_multipart<D, E>(
ent: &dyn Entity<Data = D, Error = E>,
mut res: http::response::Builder,
ranges: &[Range<u64>],
len: u64,
include_entity_headers: bool,
) -> (http::response::Builder, Vec<Vec<u8>>)
where
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
{
let mut each_part_headers = Vec::new();
if include_entity_headers {
let mut h = http::header::HeaderMap::new();
ent.add_headers(&mut h);
each_part_headers.reserve(
h.iter()
.map(|(k, v)| k.as_str().len() + v.as_bytes().len() + 4)
.sum::<usize>()
+ 2,
);
for (k, v) in &h {
each_part_headers.extend_from_slice(k.as_str().as_bytes());
each_part_headers.extend_from_slice(b": ");
each_part_headers.extend_from_slice(v.as_bytes());
each_part_headers.extend_from_slice(b"\r\n");
}
}
each_part_headers.extend_from_slice(b"\r\n");
let mut body_len = 0;
let mut part_headers: Vec<Vec<u8>> = Vec::with_capacity(2 * ranges.len() + 1);
for r in ranges {
let mut buf = Vec::with_capacity(64 + each_part_headers.len());
write!(
&mut buf,
"\r\n--B\r\nContent-Range: bytes {}-{}/{}\r\n",
r.start,
r.end - 1,
len
)
.unwrap();
buf.extend_from_slice(&each_part_headers);
body_len += buf.len() as u64 + r.end - r.start;
part_headers.push(buf);
}
body_len += PART_TRAILER.len() as u64;
res = res.header(
header::CONTENT_LENGTH,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES, "{}", body_len),
);
res = res.header(
header::CONTENT_TYPE,
HeaderValue::from_static("multipart/byteranges; boundary=B"),
);
res = res.status(StatusCode::PARTIAL_CONTENT);
(res, part_headers)
}
/// The trailer after all `multipart/byteranges` body parts.
const PART_TRAILER: &[u8] = b"\r\n--B--\r\n";
/// Produces a single chunk of the body and the following state, for use in an `unfold` call.
///
/// Alternates between portions of `part_headers` and their corresponding bodies, then the overall
/// trailer, then end the stream.
fn next_multipart_body_chunk<D, E>(
state: usize,
ent: &dyn Entity<Data = D, Error = E>,
ranges: &[Range<u64>],
part_headers: &mut [Vec<u8>],
) -> impl Future<Output = Option<(InnerBody<D, E>, usize)>>
where
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
{
let i = state >> 1;
let odd = (state & 1) == 1;
let body = if i == ranges.len() && odd {
return futures_util::future::ready(None);
} else if i == ranges.len() {
InnerBody::Once(Some(PART_TRAILER.into()))
} else if odd {
InnerBody::B(Pin::from(ent.get_range(ranges[i].clone())))
} else {
let v = std::mem::take(&mut part_headers[i]);
InnerBody::Once(Some(v.into()))
};
futures_util::future::ready(Some((body, state + 1)))
}
| {
// serve takes entity itself for ownership, as needed for the multipart case. But to avoid
// monomorphization code bloat when there are many implementations of Entity<Data, Error>,
// delegate as much as possible to functions which take a reference to a trait object.
match serve_inner(&entity, req) {
ServeInner::Simple(res) => res,
ServeInner::Multipart {
res,
mut part_headers,
ranges,
} => {
let bodies = stream::unfold(0, move |state| {
next_multipart_body_chunk(state, &entity, &ranges[..], &mut part_headers[..])
});
let body = bodies.flatten();
let body: Box<dyn Stream<Item = Result<Ent::Data, Ent::Error>> + Send> = Box::new(body);
res.body(body.into()).unwrap()
}
}
} | identifier_body |
serving.rs | // Copyright (c) 2016-2018 The http-serve developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::Entity;
use crate::etag;
use crate::range;
use bytes::Buf;
use futures_core::Stream;
use futures_util::stream::{self, StreamExt};
use http::header::{self, HeaderMap, HeaderValue};
use http::{self, Method, Request, Response, StatusCode};
use http_body::Body;
use httpdate::{fmt_http_date, parse_http_date};
use pin_project::pin_project;
use smallvec::SmallVec;
use std::future::Future;
use std::io::Write;
use std::ops::Range;
use std::pin::Pin;
use std::time::SystemTime;
const MAX_DECIMAL_U64_BYTES: usize = 20; // u64::max_value().to_string().len()
fn parse_modified_hdrs(
etag: &Option<HeaderValue>,
req_hdrs: &HeaderMap,
last_modified: Option<SystemTime>,
) -> Result<(bool, bool), &'static str> {
let precondition_failed = if!etag::any_match(etag, req_hdrs)? {
true
} else if let (Some(ref m), Some(ref since)) =
(last_modified, req_hdrs.get(header::IF_UNMODIFIED_SINCE))
{
const ERR: &str = "Unparseable If-Unmodified-Since";
*m > parse_http_date(since.to_str().map_err(|_| ERR)?).map_err(|_| ERR)?
} else {
false
};
let not_modified = if!etag::none_match(&etag, req_hdrs).unwrap_or(true) {
true
} else if let (Some(ref m), Some(ref since)) =
(last_modified, req_hdrs.get(header::IF_MODIFIED_SINCE))
{
const ERR: &str = "Unparseable If-Modified-Since";
*m <= parse_http_date(since.to_str().map_err(|_| ERR)?).map_err(|_| ERR)?
} else {
false
};
Ok((precondition_failed, not_modified))
}
fn static_body<D, E>(s: &'static str) -> Box<dyn Stream<Item = Result<D, E>> + Send>
where
D:'static + Send + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send,
{
Box::new(stream::once(futures_util::future::ok(s.as_bytes().into())))
}
fn empty_body<D, E>() -> Box<dyn Stream<Item = Result<D, E>> + Send>
where
D:'static + Send + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send,
{
Box::new(stream::empty())
}
/// Serves GET and HEAD requests for a given byte-ranged entity.
/// Handles conditional & subrange requests.
/// The caller is expected to have already determined the correct entity and appended
/// `Expires`, `Cache-Control`, and `Vary` headers if desired.
pub fn serve<
Ent: Entity,
B: Body + From<Box<dyn Stream<Item = Result<Ent::Data, Ent::Error>> + Send>>,
BI,
>(
entity: Ent,
req: &Request<BI>,
) -> Response<B> {
// serve takes entity itself for ownership, as needed for the multipart case. But to avoid
// monomorphization code bloat when there are many implementations of Entity<Data, Error>,
// delegate as much as possible to functions which take a reference to a trait object.
match serve_inner(&entity, req) {
ServeInner::Simple(res) => res,
ServeInner::Multipart {
res,
mut part_headers,
ranges,
} => {
let bodies = stream::unfold(0, move |state| {
next_multipart_body_chunk(state, &entity, &ranges[..], &mut part_headers[..])
});
let body = bodies.flatten();
let body: Box<dyn Stream<Item = Result<Ent::Data, Ent::Error>> + Send> = Box::new(body);
res.body(body.into()).unwrap()
}
}
}
/// An instruction from `serve_inner` to `serve` on how to respond.
enum ServeInner<B> {
Simple(Response<B>),
Multipart {
res: http::response::Builder,
part_headers: Vec<Vec<u8>>,
ranges: SmallVec<[Range<u64>; 1]>,
},
}
/// Runs trait object-based inner logic for `serve`.
fn serve_inner<
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
B: Body + From<Box<dyn Stream<Item = Result<D, E>> + Send>>,
BI,
>(
ent: &dyn Entity<Error = E, Data = D>,
req: &Request<BI>,
) -> ServeInner<B> {
if *req.method()!= Method::GET && *req.method()!= Method::HEAD {
return ServeInner::Simple(
Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.header(header::ALLOW, HeaderValue::from_static("get, head"))
.body(static_body::<D, E>("This resource only supports GET and HEAD.").into())
.unwrap(),
);
}
let last_modified = ent.last_modified();
let etag = ent.etag();
let (precondition_failed, not_modified) =
match parse_modified_hdrs(&etag, req.headers(), last_modified) {
Err(s) => {
return ServeInner::Simple(
Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(static_body::<D, E>(s).into())
.unwrap(),
)
}
Ok(p) => p,
};
// See RFC 7233 section 4.1 <https://tools.ietf.org/html/rfc7233#section-4.1>: a Partial
// Content response should include other representation header fields (aka entity-headers in
// RFC 2616) iff the client didn't specify If-Range.
let mut range_hdr = req.headers().get(header::RANGE);
let include_entity_headers_on_range = match req.headers().get(header::IF_RANGE) {
Some(ref if_range) => {
let if_range = if_range.as_bytes();
if if_range.starts_with(b"W/\"") || if_range.starts_with(b"\"") {
// etag case.
if let Some(ref some_etag) = etag {
if etag::strong_eq(if_range, some_etag.as_bytes()) {
false
} else {
range_hdr = None;
true
}
} else {
range_hdr = None;
true
}
} else {
// Date case.
// Use the strong validation rules for an origin server:
// <https://tools.ietf.org/html/rfc7232#section-2.2.2>.
// The resource could have changed twice in the supplied second, so never match.
range_hdr = None;
true
}
}
None => true,
};
let mut res =
Response::builder().header(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
if let Some(m) = last_modified {
// See RFC 7232 section 2.2.1 <https://tools.ietf.org/html/rfc7232#section-2.2.1>: the
// Last-Modified must not exceed the Date. To guarantee this, set the Date now rather than
// let hyper set it.
let d = SystemTime::now();
res = res.header(header::DATE, fmt_http_date(d));
let clamped_m = std::cmp::min(m, d);
res = res.header(header::LAST_MODIFIED, fmt_http_date(clamped_m));
}
if let Some(e) = etag {
res = res.header(http::header::ETAG, e);
}
if precondition_failed {
res = res.status(StatusCode::PRECONDITION_FAILED);
return ServeInner::Simple(
res.body(static_body::<D, E>("Precondition failed").into())
.unwrap(),
);
}
if not_modified {
res = res.status(StatusCode::NOT_MODIFIED);
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
let len = ent.len();
let (range, include_entity_headers) = match range::parse(range_hdr, len) {
range::ResolvedRanges::None => (0..len, true),
range::ResolvedRanges::Satisfiable(ranges) => {
if ranges.len() == 1 {
res = res.header(
header::CONTENT_RANGE,
unsafe_fmt_ascii_val!(
MAX_DECIMAL_U64_BYTES * 3 + "bytes -/".len(),
"bytes {}-{}/{}",
ranges[0].start,
ranges[0].end - 1,
len
),
);
res = res.status(StatusCode::PARTIAL_CONTENT);
(ranges[0].clone(), include_entity_headers_on_range)
} else {
// Before serving multiple ranges via multipart/byteranges, estimate the total
// length. ("80" is the RFC's estimate of the size of each part's header.) If it's
// more than simply serving the whole entity, do that instead.
let est_len: u64 = ranges.iter().map(|r| 80 + r.end - r.start).sum();
if est_len < len {
let (res, part_headers) = prepare_multipart(
ent,
res,
&ranges[..],
len,
include_entity_headers_on_range,
);
if *req.method() == Method::HEAD {
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
return ServeInner::Multipart {
res,
part_headers,
ranges,
};
}
(0..len, true)
}
}
range::ResolvedRanges::NotSatisfiable => {
res = res.header(
http::header::CONTENT_RANGE,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES + "bytes */".len(), "bytes */{}", len),
);
res = res.status(StatusCode::RANGE_NOT_SATISFIABLE);
return ServeInner::Simple(res.body(empty_body::<D, E>().into()).unwrap());
}
};
res = res.header(
header::CONTENT_LENGTH,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES, "{}", range.end - range.start),
);
let body = match *req.method() {
Method::HEAD => empty_body::<D, E>(),
_ => ent.get_range(range),
};
let mut res = res.body(body.into()).unwrap();
if include_entity_headers {
ent.add_headers(res.headers_mut());
}
ServeInner::Simple(res)
}
/// A body for use in the "stream of streams" (see `prepare_multipart` and its call site).
/// This avoids an extra allocation for the part headers and overall trailer.
#[pin_project(project=InnerBodyProj)]
enum InnerBody<D, E> {
Once(Option<D>),
// The box variant _holds_ a pin but isn't structurally pinned.
B(Pin<Box<dyn Stream<Item = Result<D, E>> + Sync + Send>>),
}
impl<D, E> Stream for InnerBody<D, E> {
type Item = Result<D, E>;
fn poll_next(
self: Pin<&mut Self>,
ctx: &mut std::task::Context,
) -> std::task::Poll<Option<Result<D, E>>> {
let mut this = self.project();
match this {
InnerBodyProj::Once(ref mut o) => std::task::Poll::Ready(o.take().map(Ok)),
InnerBodyProj::B(b) => b.as_mut().poll_next(ctx),
}
}
}
/// Prepares to send a `multipart/mixed` response.
/// Returns the response builder (with overall headers added) and each part's headers.
fn prepare_multipart<D, E>(
ent: &dyn Entity<Data = D, Error = E>,
mut res: http::response::Builder,
ranges: &[Range<u64>],
len: u64,
include_entity_headers: bool,
) -> (http::response::Builder, Vec<Vec<u8>>)
where
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
{
let mut each_part_headers = Vec::new();
if include_entity_headers {
let mut h = http::header::HeaderMap::new();
ent.add_headers(&mut h);
each_part_headers.reserve(
h.iter()
.map(|(k, v)| k.as_str().len() + v.as_bytes().len() + 4)
.sum::<usize>()
+ 2,
);
for (k, v) in &h {
each_part_headers.extend_from_slice(k.as_str().as_bytes());
each_part_headers.extend_from_slice(b": ");
each_part_headers.extend_from_slice(v.as_bytes());
each_part_headers.extend_from_slice(b"\r\n");
}
}
each_part_headers.extend_from_slice(b"\r\n");
let mut body_len = 0;
let mut part_headers: Vec<Vec<u8>> = Vec::with_capacity(2 * ranges.len() + 1);
for r in ranges {
let mut buf = Vec::with_capacity(64 + each_part_headers.len());
write!(
&mut buf,
"\r\n--B\r\nContent-Range: bytes {}-{}/{}\r\n",
r.start,
r.end - 1,
len
)
.unwrap();
buf.extend_from_slice(&each_part_headers);
body_len += buf.len() as u64 + r.end - r.start;
part_headers.push(buf);
}
body_len += PART_TRAILER.len() as u64;
res = res.header(
header::CONTENT_LENGTH,
unsafe_fmt_ascii_val!(MAX_DECIMAL_U64_BYTES, "{}", body_len),
);
res = res.header(
header::CONTENT_TYPE,
HeaderValue::from_static("multipart/byteranges; boundary=B"),
);
res = res.status(StatusCode::PARTIAL_CONTENT);
(res, part_headers)
}
/// The trailer after all `multipart/byteranges` body parts.
const PART_TRAILER: &[u8] = b"\r\n--B--\r\n";
/// Produces a single chunk of the body and the following state, for use in an `unfold` call.
///
/// Alternates between portions of `part_headers` and their corresponding bodies, then the overall
/// trailer, then end the stream.
fn | <D, E>(
state: usize,
ent: &dyn Entity<Data = D, Error = E>,
ranges: &[Range<u64>],
part_headers: &mut [Vec<u8>],
) -> impl Future<Output = Option<(InnerBody<D, E>, usize)>>
where
D:'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E:'static + Send + Sync,
{
let i = state >> 1;
let odd = (state & 1) == 1;
let body = if i == ranges.len() && odd {
return futures_util::future::ready(None);
} else if i == ranges.len() {
InnerBody::Once(Some(PART_TRAILER.into()))
} else if odd {
InnerBody::B(Pin::from(ent.get_range(ranges[i].clone())))
} else {
let v = std::mem::take(&mut part_headers[i]);
InnerBody::Once(Some(v.into()))
};
futures_util::future::ready(Some((body, state + 1)))
}
| next_multipart_body_chunk | identifier_name |
example.rs | use report::ExampleResult;
use header::ExampleHeader;
/// Test examples are the smallest unit of a testing framework, wrapping one or more assertions.
pub struct Example<T> {
pub(crate) header: ExampleHeader,
pub(crate) function: Box<Fn(&T) -> ExampleResult>,
}
impl<T> Example<T> {
pub(crate) fn new<F>(header: ExampleHeader, assertion: F) -> Self
where
F:'static + Fn(&T) -> ExampleResult,
{
Example {
header: header,
function: Box::new(assertion),
}
}
/// Used for testing purpose
#[cfg(test)]
pub fn fixture_success() -> Self {
Example::new(ExampleHeader::default(), |_| ExampleResult::Success)
}
/// Used for testing purpose
#[cfg(test)]
pub fn fixture_ignored() -> Self {
Example::new(ExampleHeader::default(), |_| ExampleResult::Ignored)
}
/// Used for testing purpose
#[cfg(test)]
pub fn | () -> Self {
Example::new(ExampleHeader::default(), |_| ExampleResult::Failure(None))
}
}
unsafe impl<T> Send for Example<T>
where
T: Send,
{
}
unsafe impl<T> Sync for Example<T>
where
T: Sync,
{
}
| fixture_failed | identifier_name |
example.rs | use report::ExampleResult;
use header::ExampleHeader;
/// Test examples are the smallest unit of a testing framework, wrapping one or more assertions.
pub struct Example<T> {
pub(crate) header: ExampleHeader,
pub(crate) function: Box<Fn(&T) -> ExampleResult>,
} | pub(crate) fn new<F>(header: ExampleHeader, assertion: F) -> Self
where
F:'static + Fn(&T) -> ExampleResult,
{
Example {
header: header,
function: Box::new(assertion),
}
}
/// Used for testing purpose
#[cfg(test)]
pub fn fixture_success() -> Self {
Example::new(ExampleHeader::default(), |_| ExampleResult::Success)
}
/// Used for testing purpose
#[cfg(test)]
pub fn fixture_ignored() -> Self {
Example::new(ExampleHeader::default(), |_| ExampleResult::Ignored)
}
/// Used for testing purpose
#[cfg(test)]
pub fn fixture_failed() -> Self {
Example::new(ExampleHeader::default(), |_| ExampleResult::Failure(None))
}
}
unsafe impl<T> Send for Example<T>
where
T: Send,
{
}
unsafe impl<T> Sync for Example<T>
where
T: Sync,
{
} |
impl<T> Example<T> { | random_line_split |
main.rs | //! Amethyst CLI binary crate.
//!
use std::process::exit;
use amethyst_cli as cli;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
fn | () {
eprintln!(
"WARNING! amethyst_tools has been deprecated and will stop working in future versions."
);
eprintln!("For more details please see https://community.amethyst.rs/t/end-of-life-for-amethyst-tools-the-cli/1656");
let matches = App::new("Amethyst CLI")
.author("Created by Amethyst developers")
.version(env!("CARGO_PKG_VERSION"))
.about("Allows managing Amethyst game projects")
.subcommand(
SubCommand::with_name("new")
.about("Creates a new Amethyst project")
.arg(
Arg::with_name("project_name")
.help("The directory name for the new project")
.required(true),
)
.arg(
Arg::with_name("amethyst_version")
.short("a")
.long("amethyst")
.value_name("AMETHYST_VERSION")
.takes_value(true)
.help("The requested version of Amethyst"),
)
.arg(
Arg::with_name("no_defaults")
.short("n")
.long("no-defaults")
.help("Do not autodetect graphics backend into Cargo.toml"),
),
)
.subcommand(
SubCommand::with_name("update")
.about("Checks if you can update Amethyst component")
.arg(
Arg::with_name("component_name")
.help("Name of component to try and update")
.value_name("COMPONENT_NAME")
.takes_value(true),
),
)
.setting(AppSettings::SubcommandRequiredElseHelp)
.get_matches();
match matches.subcommand() {
("new", Some(args)) => exec_new(args),
("update", Some(args)) => exec_update(args),
_ => eprintln!("WARNING: subcommand not tested. This is a bug."),
}
}
fn exec_new(args: &ArgMatches) {
let project_name = args
.value_of("project_name")
.expect("Bug: project_name is required");
let project_name = project_name.to_owned();
let version = args.value_of("amethyst_version").map(ToOwned::to_owned);
let no_defaults = args.is_present("no_defaults");
let n = cli::New {
project_name,
version,
no_defaults,
};
if let Err(e) = n.execute() {
handle_error(&e);
} else {
println!("Project ready!");
println!("Checking for updates...");
if let Err(e) = check_version() {
handle_error(&e);
}
}
}
fn exec_update(args: &ArgMatches) {
// We don't currently support checking anything other than the version of amethyst tools
let _component_name = args.value_of("component_name").map(ToOwned::to_owned);
if let Err(e) = check_version() {
handle_error(&e);
}
exit(0);
}
// Prints a warning/info message if this version of amethyst_cli is out of date
fn check_version() -> cli::error::Result<()> {
use ansi_term::Color;
use cli::get_latest_version;
let local_version = semver::Version::parse(env!("CARGO_PKG_VERSION"))?;
let remote_version_str = get_latest_version()?;
let remote_version = semver::Version::parse(&remote_version_str)?;
if local_version < remote_version {
eprintln!(
"{}: Local version of `amethyst_tools` ({}) is out of date. Latest version is {}",
Color::Yellow.paint("warning"),
env!("CARGO_PKG_VERSION"),
remote_version_str
);
} else {
println!("No new versions found.");
}
Ok(())
}
fn handle_error(e: &cli::error::Error) {
use ansi_term::Color;
eprintln!("{}: {}", Color::Red.paint("error"), e);
e.iter()
.skip(1)
.for_each(|e| eprintln!("{}: {}", Color::Red.paint("caused by"), e));
// Only shown if `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
eprintln!();
eprintln!("backtrace: {:?}", backtrace);
}
exit(1);
}
| main | identifier_name |
main.rs | //! Amethyst CLI binary crate.
//!
use std::process::exit;
use amethyst_cli as cli;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
fn main() {
eprintln!(
"WARNING! amethyst_tools has been deprecated and will stop working in future versions."
);
eprintln!("For more details please see https://community.amethyst.rs/t/end-of-life-for-amethyst-tools-the-cli/1656");
let matches = App::new("Amethyst CLI")
.author("Created by Amethyst developers")
.version(env!("CARGO_PKG_VERSION"))
.about("Allows managing Amethyst game projects")
.subcommand(
SubCommand::with_name("new")
.about("Creates a new Amethyst project")
.arg(
Arg::with_name("project_name")
.help("The directory name for the new project")
.required(true),
)
.arg( | .value_name("AMETHYST_VERSION")
.takes_value(true)
.help("The requested version of Amethyst"),
)
.arg(
Arg::with_name("no_defaults")
.short("n")
.long("no-defaults")
.help("Do not autodetect graphics backend into Cargo.toml"),
),
)
.subcommand(
SubCommand::with_name("update")
.about("Checks if you can update Amethyst component")
.arg(
Arg::with_name("component_name")
.help("Name of component to try and update")
.value_name("COMPONENT_NAME")
.takes_value(true),
),
)
.setting(AppSettings::SubcommandRequiredElseHelp)
.get_matches();
match matches.subcommand() {
("new", Some(args)) => exec_new(args),
("update", Some(args)) => exec_update(args),
_ => eprintln!("WARNING: subcommand not tested. This is a bug."),
}
}
fn exec_new(args: &ArgMatches) {
let project_name = args
.value_of("project_name")
.expect("Bug: project_name is required");
let project_name = project_name.to_owned();
let version = args.value_of("amethyst_version").map(ToOwned::to_owned);
let no_defaults = args.is_present("no_defaults");
let n = cli::New {
project_name,
version,
no_defaults,
};
if let Err(e) = n.execute() {
handle_error(&e);
} else {
println!("Project ready!");
println!("Checking for updates...");
if let Err(e) = check_version() {
handle_error(&e);
}
}
}
fn exec_update(args: &ArgMatches) {
// We don't currently support checking anything other than the version of amethyst tools
let _component_name = args.value_of("component_name").map(ToOwned::to_owned);
if let Err(e) = check_version() {
handle_error(&e);
}
exit(0);
}
// Prints a warning/info message if this version of amethyst_cli is out of date
fn check_version() -> cli::error::Result<()> {
use ansi_term::Color;
use cli::get_latest_version;
let local_version = semver::Version::parse(env!("CARGO_PKG_VERSION"))?;
let remote_version_str = get_latest_version()?;
let remote_version = semver::Version::parse(&remote_version_str)?;
if local_version < remote_version {
eprintln!(
"{}: Local version of `amethyst_tools` ({}) is out of date. Latest version is {}",
Color::Yellow.paint("warning"),
env!("CARGO_PKG_VERSION"),
remote_version_str
);
} else {
println!("No new versions found.");
}
Ok(())
}
fn handle_error(e: &cli::error::Error) {
use ansi_term::Color;
eprintln!("{}: {}", Color::Red.paint("error"), e);
e.iter()
.skip(1)
.for_each(|e| eprintln!("{}: {}", Color::Red.paint("caused by"), e));
// Only shown if `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
eprintln!();
eprintln!("backtrace: {:?}", backtrace);
}
exit(1);
} | Arg::with_name("amethyst_version")
.short("a")
.long("amethyst") | random_line_split |
main.rs | //! Amethyst CLI binary crate.
//!
use std::process::exit;
use amethyst_cli as cli;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
fn main() {
eprintln!(
"WARNING! amethyst_tools has been deprecated and will stop working in future versions."
);
eprintln!("For more details please see https://community.amethyst.rs/t/end-of-life-for-amethyst-tools-the-cli/1656");
let matches = App::new("Amethyst CLI")
.author("Created by Amethyst developers")
.version(env!("CARGO_PKG_VERSION"))
.about("Allows managing Amethyst game projects")
.subcommand(
SubCommand::with_name("new")
.about("Creates a new Amethyst project")
.arg(
Arg::with_name("project_name")
.help("The directory name for the new project")
.required(true),
)
.arg(
Arg::with_name("amethyst_version")
.short("a")
.long("amethyst")
.value_name("AMETHYST_VERSION")
.takes_value(true)
.help("The requested version of Amethyst"),
)
.arg(
Arg::with_name("no_defaults")
.short("n")
.long("no-defaults")
.help("Do not autodetect graphics backend into Cargo.toml"),
),
)
.subcommand(
SubCommand::with_name("update")
.about("Checks if you can update Amethyst component")
.arg(
Arg::with_name("component_name")
.help("Name of component to try and update")
.value_name("COMPONENT_NAME")
.takes_value(true),
),
)
.setting(AppSettings::SubcommandRequiredElseHelp)
.get_matches();
match matches.subcommand() {
("new", Some(args)) => exec_new(args),
("update", Some(args)) => exec_update(args),
_ => eprintln!("WARNING: subcommand not tested. This is a bug."),
}
}
fn exec_new(args: &ArgMatches) {
let project_name = args
.value_of("project_name")
.expect("Bug: project_name is required");
let project_name = project_name.to_owned();
let version = args.value_of("amethyst_version").map(ToOwned::to_owned);
let no_defaults = args.is_present("no_defaults");
let n = cli::New {
project_name,
version,
no_defaults,
};
if let Err(e) = n.execute() {
handle_error(&e);
} else {
println!("Project ready!");
println!("Checking for updates...");
if let Err(e) = check_version() {
handle_error(&e);
}
}
}
fn exec_update(args: &ArgMatches) {
// We don't currently support checking anything other than the version of amethyst tools
let _component_name = args.value_of("component_name").map(ToOwned::to_owned);
if let Err(e) = check_version() {
handle_error(&e);
}
exit(0);
}
// Prints a warning/info message if this version of amethyst_cli is out of date
fn check_version() -> cli::error::Result<()> |
fn handle_error(e: &cli::error::Error) {
use ansi_term::Color;
eprintln!("{}: {}", Color::Red.paint("error"), e);
e.iter()
.skip(1)
.for_each(|e| eprintln!("{}: {}", Color::Red.paint("caused by"), e));
// Only shown if `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
eprintln!();
eprintln!("backtrace: {:?}", backtrace);
}
exit(1);
}
| {
use ansi_term::Color;
use cli::get_latest_version;
let local_version = semver::Version::parse(env!("CARGO_PKG_VERSION"))?;
let remote_version_str = get_latest_version()?;
let remote_version = semver::Version::parse(&remote_version_str)?;
if local_version < remote_version {
eprintln!(
"{}: Local version of `amethyst_tools` ({}) is out of date. Latest version is {}",
Color::Yellow.paint("warning"),
env!("CARGO_PKG_VERSION"),
remote_version_str
);
} else {
println!("No new versions found.");
}
Ok(())
} | identifier_body |
feature-gate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that structural match is only permitted with a feature gate,
// and that if a feature gate is supplied, it permits the type to be
// used in a match.
// revisions: with_gate no_gate
// gate-test-structural_match
#![allow(unused)]
#![feature(rustc_attrs)]
#![cfg_attr(with_gate, feature(structural_match))]
#[structural_match] //[no_gate]~ ERROR semantics of constant patterns is not yet settled
struct Foo { |
#[rustc_error]
fn main() { //[with_gate]~ ERROR compilation successful
let y = Foo { x: 1 };
match y {
FOO => { }
_ => { }
}
} | x: u32
}
const FOO: Foo = Foo { x: 0 }; | random_line_split |
feature-gate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that structural match is only permitted with a feature gate,
// and that if a feature gate is supplied, it permits the type to be
// used in a match.
// revisions: with_gate no_gate
// gate-test-structural_match
#![allow(unused)]
#![feature(rustc_attrs)]
#![cfg_attr(with_gate, feature(structural_match))]
#[structural_match] //[no_gate]~ ERROR semantics of constant patterns is not yet settled
struct Foo {
x: u32
}
const FOO: Foo = Foo { x: 0 };
#[rustc_error]
fn | () { //[with_gate]~ ERROR compilation successful
let y = Foo { x: 1 };
match y {
FOO => { }
_ => { }
}
}
| main | identifier_name |
memory.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 https://mozilla.org/MPL/2.0/. */
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::StreamId;
use serde_json::{Map, Value};
use std::net::TcpStream;
#[derive(Serialize)]
pub struct TimelineMemoryReply {
jsObjectSize: u64,
jsStringSize: u64,
jsOtherSize: u64,
domSize: u64,
styleSize: u64,
otherSize: u64,
totalSize: u64,
jsMilliseconds: f64,
nonJSMilliseconds: f64,
}
pub struct MemoryActor {
pub name: String,
}
impl Actor for MemoryActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(
&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &Map<String, Value>,
_stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessageStatus::Ignored)
}
}
impl MemoryActor {
/// return name of actor
pub fn create(registry: &ActorRegistry) -> String {
let actor_name = registry.new_name("memory");
let actor = MemoryActor {
name: actor_name.clone(),
};
registry.register_later(Box::new(actor));
actor_name
}
pub fn measure(&self) -> TimelineMemoryReply |
}
| {
//TODO:
TimelineMemoryReply {
jsObjectSize: 1,
jsStringSize: 1,
jsOtherSize: 1,
domSize: 1,
styleSize: 1,
otherSize: 1,
totalSize: 1,
jsMilliseconds: 1.1,
nonJSMilliseconds: 1.1,
}
} | identifier_body |
memory.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 https://mozilla.org/MPL/2.0/. */
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::StreamId;
use serde_json::{Map, Value};
use std::net::TcpStream;
#[derive(Serialize)]
pub struct TimelineMemoryReply {
jsObjectSize: u64,
jsStringSize: u64,
jsOtherSize: u64,
domSize: u64,
styleSize: u64,
otherSize: u64,
totalSize: u64,
jsMilliseconds: f64,
nonJSMilliseconds: f64,
}
pub struct MemoryActor {
pub name: String,
}
impl Actor for MemoryActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(
&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &Map<String, Value>,
_stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessageStatus::Ignored)
}
}
impl MemoryActor {
/// return name of actor
pub fn create(registry: &ActorRegistry) -> String {
let actor_name = registry.new_name("memory");
let actor = MemoryActor {
name: actor_name.clone(),
}; | }
pub fn measure(&self) -> TimelineMemoryReply {
//TODO:
TimelineMemoryReply {
jsObjectSize: 1,
jsStringSize: 1,
jsOtherSize: 1,
domSize: 1,
styleSize: 1,
otherSize: 1,
totalSize: 1,
jsMilliseconds: 1.1,
nonJSMilliseconds: 1.1,
}
}
} |
registry.register_later(Box::new(actor));
actor_name | random_line_split |
memory.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 https://mozilla.org/MPL/2.0/. */
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::StreamId;
use serde_json::{Map, Value};
use std::net::TcpStream;
#[derive(Serialize)]
pub struct TimelineMemoryReply {
jsObjectSize: u64,
jsStringSize: u64,
jsOtherSize: u64,
domSize: u64,
styleSize: u64,
otherSize: u64,
totalSize: u64,
jsMilliseconds: f64,
nonJSMilliseconds: f64,
}
pub struct MemoryActor {
pub name: String,
}
impl Actor for MemoryActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(
&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &Map<String, Value>,
_stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessageStatus::Ignored)
}
}
impl MemoryActor {
/// return name of actor
pub fn | (registry: &ActorRegistry) -> String {
let actor_name = registry.new_name("memory");
let actor = MemoryActor {
name: actor_name.clone(),
};
registry.register_later(Box::new(actor));
actor_name
}
pub fn measure(&self) -> TimelineMemoryReply {
//TODO:
TimelineMemoryReply {
jsObjectSize: 1,
jsStringSize: 1,
jsOtherSize: 1,
domSize: 1,
styleSize: 1,
otherSize: 1,
totalSize: 1,
jsMilliseconds: 1.1,
nonJSMilliseconds: 1.1,
}
}
}
| create | identifier_name |
mod.rs | /* Copyright 2018 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use super::{
BinaryReader, BinaryReaderError, CustomSectionKind, ExternalKind, FuncType, GlobalType,
ImportSectionEntryType, LinkingType, MemoryType, NameType, Naming, Operator, Range, RelocType,
Result, SectionCode, TableType, Type,
};
use super::SectionHeader;
pub use self::code_section::CodeSectionReader;
pub use self::code_section::FunctionBody;
pub use self::code_section::LocalsReader;
use self::data_count_section::read_data_count_section_content;
pub use self::data_section::Data;
pub use self::data_section::DataKind;
pub use self::data_section::DataSectionReader;
pub use self::element_section::Element;
pub use self::element_section::ElementItems;
pub use self::element_section::ElementItemsReader;
pub use self::element_section::ElementKind;
pub use self::element_section::ElementSectionReader;
pub use self::export_section::Export;
pub use self::export_section::ExportSectionReader;
pub use self::function_section::FunctionSectionReader;
pub use self::global_section::Global;
pub use self::global_section::GlobalSectionReader;
pub use self::import_section::Import;
pub use self::import_section::ImportSectionReader;
pub use self::init_expr::InitExpr;
pub use self::memory_section::MemorySectionReader;
pub use self::module::CustomSectionContent;
pub use self::module::ModuleReader;
pub use self::module::Section;
pub use self::module::SectionContent;
use self::start_section::read_start_section_content;
pub use self::table_section::TableSectionReader;
pub use self::type_section::TypeSectionReader;
pub use self::section_reader::SectionIterator;
pub use self::section_reader::SectionIteratorLimited;
pub use self::section_reader::SectionReader;
pub use self::section_reader::SectionWithLimitedItems; |
pub use self::name_section::FunctionName;
pub use self::name_section::LocalName;
pub use self::name_section::ModuleName;
pub use self::name_section::Name;
pub use self::name_section::NameSectionReader;
pub use self::name_section::NamingReader;
pub use self::producers_section::ProducersField;
pub use self::producers_section::ProducersFieldValue;
pub use self::producers_section::ProducersSectionReader;
pub use self::linking_section::LinkingSectionReader;
pub use self::reloc_section::Reloc;
pub use self::reloc_section::RelocSectionReader;
use self::sourcemappingurl_section::read_sourcemappingurl_section_content;
pub use self::operators::OperatorsReader;
mod code_section;
mod data_count_section;
mod data_section;
mod element_section;
mod export_section;
mod function_section;
mod global_section;
mod import_section;
mod init_expr;
mod linking_section;
mod memory_section;
mod module;
mod name_section;
mod operators;
mod producers_section;
mod reloc_section;
mod section_reader;
mod sourcemappingurl_section;
mod start_section;
mod table_section;
mod type_section; | random_line_split |
|
from_raw_arc.rs | //! A "Manual Arc" which allows manually frobbing the reference count
//!
//! This module contains a copy of the `Arc` found in the standard library,
//! stripped down to the bare bones of what we actually need. The reason this is
//! done is for the ability to concretely know the memory layout of the `Inner`
//! structure of the arc pointer itself (e.g. `ArcInner` in the standard
//! library).
//!
//! We do some unsafe casting from `*mut OVERLAPPED` to a `FromRawArc<T>` to
//! ensure that data lives for the length of an I/O operation, but this means
//! that we have to know the layouts of the structures involved. This
//! representation primarily guarantees that the data, `T` is at the front of
//! the inner pointer always.
//!
//! Note that we're missing out on some various optimizations implemented in the
//! standard library:
//!
//! * The size of `FromRawArc` is actually two words because of the drop flag
//! * The compiler doesn't understand that the pointer in `FromRawArc` is never
//! null, so Option<FromRawArc<T>> is not a nullable pointer.
use std::mem;
use std::ops::Deref;
use std::sync::atomic::{self, AtomicUsize, Ordering};
pub struct FromRawArc<T> {
_inner: *mut Inner<T>,
}
unsafe impl<T: Sync + Send> Send for FromRawArc<T> {}
unsafe impl<T: Sync + Send> Sync for FromRawArc<T> {}
#[repr(C)]
struct | <T> {
data: T,
cnt: AtomicUsize,
}
impl<T> FromRawArc<T> {
pub fn new(data: T) -> FromRawArc<T> {
let x = Box::new(Inner {
data: data,
cnt: AtomicUsize::new(1),
});
FromRawArc {
_inner: unsafe { mem::transmute(x) },
}
}
pub unsafe fn from_raw(ptr: *mut T) -> FromRawArc<T> {
// Note that if we could use `mem::transmute` here to get a libstd Arc
// (guaranteed) then we could just use std::sync::Arc, but this is the
// crucial reason this currently exists.
FromRawArc {
_inner: ptr as *mut Inner<T>,
}
}
}
impl<T> Clone for FromRawArc<T> {
fn clone(&self) -> FromRawArc<T> {
// Atomic ordering of Relaxed lifted from libstd, but the general idea
// is that you need synchronization to communicate this increment to
// another thread, so this itself doesn't need to be synchronized.
unsafe {
(*self._inner).cnt.fetch_add(1, Ordering::Relaxed);
}
FromRawArc {
_inner: self._inner,
}
}
}
impl<T> Deref for FromRawArc<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &(*self._inner).data }
}
}
impl<T> Drop for FromRawArc<T> {
fn drop(&mut self) {
unsafe {
// Atomic orderings lifted from the standard library
if (*self._inner).cnt.fetch_sub(1, Ordering::Release)!= 1 {
return;
}
atomic::fence(Ordering::Acquire);
drop(mem::transmute::<_, Box<T>>(self._inner));
}
}
}
#[cfg(test)]
mod tests {
use super::FromRawArc;
#[test]
fn smoke() {
let a = FromRawArc::new(1);
assert_eq!(*a, 1);
assert_eq!(*a.clone(), 1);
}
#[test]
fn drops() {
struct A<'a>(&'a mut bool);
impl<'a> Drop for A<'a> {
fn drop(&mut self) {
*self.0 = true;
}
}
let mut a = false;
{
let a = FromRawArc::new(A(&mut a));
let _ = a.clone();
assert!(!*a.0);
}
assert!(a);
}
}
| Inner | identifier_name |
from_raw_arc.rs | //! A "Manual Arc" which allows manually frobbing the reference count
//!
//! This module contains a copy of the `Arc` found in the standard library,
//! stripped down to the bare bones of what we actually need. The reason this is
//! done is for the ability to concretely know the memory layout of the `Inner`
//! structure of the arc pointer itself (e.g. `ArcInner` in the standard
//! library).
//!
//! We do some unsafe casting from `*mut OVERLAPPED` to a `FromRawArc<T>` to
//! ensure that data lives for the length of an I/O operation, but this means
//! that we have to know the layouts of the structures involved. This
//! representation primarily guarantees that the data, `T` is at the front of
//! the inner pointer always.
//!
//! Note that we're missing out on some various optimizations implemented in the
//! standard library:
//!
//! * The size of `FromRawArc` is actually two words because of the drop flag
//! * The compiler doesn't understand that the pointer in `FromRawArc` is never
//! null, so Option<FromRawArc<T>> is not a nullable pointer.
use std::mem;
use std::ops::Deref;
use std::sync::atomic::{self, AtomicUsize, Ordering};
pub struct FromRawArc<T> {
_inner: *mut Inner<T>,
}
unsafe impl<T: Sync + Send> Send for FromRawArc<T> {}
unsafe impl<T: Sync + Send> Sync for FromRawArc<T> {}
#[repr(C)]
struct Inner<T> {
data: T,
cnt: AtomicUsize,
}
impl<T> FromRawArc<T> {
pub fn new(data: T) -> FromRawArc<T> { | FromRawArc {
_inner: unsafe { mem::transmute(x) },
}
}
pub unsafe fn from_raw(ptr: *mut T) -> FromRawArc<T> {
// Note that if we could use `mem::transmute` here to get a libstd Arc
// (guaranteed) then we could just use std::sync::Arc, but this is the
// crucial reason this currently exists.
FromRawArc {
_inner: ptr as *mut Inner<T>,
}
}
}
impl<T> Clone for FromRawArc<T> {
fn clone(&self) -> FromRawArc<T> {
// Atomic ordering of Relaxed lifted from libstd, but the general idea
// is that you need synchronization to communicate this increment to
// another thread, so this itself doesn't need to be synchronized.
unsafe {
(*self._inner).cnt.fetch_add(1, Ordering::Relaxed);
}
FromRawArc {
_inner: self._inner,
}
}
}
impl<T> Deref for FromRawArc<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &(*self._inner).data }
}
}
impl<T> Drop for FromRawArc<T> {
fn drop(&mut self) {
unsafe {
// Atomic orderings lifted from the standard library
if (*self._inner).cnt.fetch_sub(1, Ordering::Release)!= 1 {
return;
}
atomic::fence(Ordering::Acquire);
drop(mem::transmute::<_, Box<T>>(self._inner));
}
}
}
#[cfg(test)]
mod tests {
use super::FromRawArc;
#[test]
fn smoke() {
let a = FromRawArc::new(1);
assert_eq!(*a, 1);
assert_eq!(*a.clone(), 1);
}
#[test]
fn drops() {
struct A<'a>(&'a mut bool);
impl<'a> Drop for A<'a> {
fn drop(&mut self) {
*self.0 = true;
}
}
let mut a = false;
{
let a = FromRawArc::new(A(&mut a));
let _ = a.clone();
assert!(!*a.0);
}
assert!(a);
}
} | let x = Box::new(Inner {
data: data,
cnt: AtomicUsize::new(1),
}); | random_line_split |
from_raw_arc.rs | //! A "Manual Arc" which allows manually frobbing the reference count
//!
//! This module contains a copy of the `Arc` found in the standard library,
//! stripped down to the bare bones of what we actually need. The reason this is
//! done is for the ability to concretely know the memory layout of the `Inner`
//! structure of the arc pointer itself (e.g. `ArcInner` in the standard
//! library).
//!
//! We do some unsafe casting from `*mut OVERLAPPED` to a `FromRawArc<T>` to
//! ensure that data lives for the length of an I/O operation, but this means
//! that we have to know the layouts of the structures involved. This
//! representation primarily guarantees that the data, `T` is at the front of
//! the inner pointer always.
//!
//! Note that we're missing out on some various optimizations implemented in the
//! standard library:
//!
//! * The size of `FromRawArc` is actually two words because of the drop flag
//! * The compiler doesn't understand that the pointer in `FromRawArc` is never
//! null, so Option<FromRawArc<T>> is not a nullable pointer.
use std::mem;
use std::ops::Deref;
use std::sync::atomic::{self, AtomicUsize, Ordering};
pub struct FromRawArc<T> {
_inner: *mut Inner<T>,
}
unsafe impl<T: Sync + Send> Send for FromRawArc<T> {}
unsafe impl<T: Sync + Send> Sync for FromRawArc<T> {}
#[repr(C)]
struct Inner<T> {
data: T,
cnt: AtomicUsize,
}
impl<T> FromRawArc<T> {
pub fn new(data: T) -> FromRawArc<T> {
let x = Box::new(Inner {
data: data,
cnt: AtomicUsize::new(1),
});
FromRawArc {
_inner: unsafe { mem::transmute(x) },
}
}
pub unsafe fn from_raw(ptr: *mut T) -> FromRawArc<T> {
// Note that if we could use `mem::transmute` here to get a libstd Arc
// (guaranteed) then we could just use std::sync::Arc, but this is the
// crucial reason this currently exists.
FromRawArc {
_inner: ptr as *mut Inner<T>,
}
}
}
impl<T> Clone for FromRawArc<T> {
fn clone(&self) -> FromRawArc<T> {
// Atomic ordering of Relaxed lifted from libstd, but the general idea
// is that you need synchronization to communicate this increment to
// another thread, so this itself doesn't need to be synchronized.
unsafe {
(*self._inner).cnt.fetch_add(1, Ordering::Relaxed);
}
FromRawArc {
_inner: self._inner,
}
}
}
impl<T> Deref for FromRawArc<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &(*self._inner).data }
}
}
impl<T> Drop for FromRawArc<T> {
fn drop(&mut self) {
unsafe {
// Atomic orderings lifted from the standard library
if (*self._inner).cnt.fetch_sub(1, Ordering::Release)!= 1 |
atomic::fence(Ordering::Acquire);
drop(mem::transmute::<_, Box<T>>(self._inner));
}
}
}
#[cfg(test)]
mod tests {
use super::FromRawArc;
#[test]
fn smoke() {
let a = FromRawArc::new(1);
assert_eq!(*a, 1);
assert_eq!(*a.clone(), 1);
}
#[test]
fn drops() {
struct A<'a>(&'a mut bool);
impl<'a> Drop for A<'a> {
fn drop(&mut self) {
*self.0 = true;
}
}
let mut a = false;
{
let a = FromRawArc::new(A(&mut a));
let _ = a.clone();
assert!(!*a.0);
}
assert!(a);
}
}
| {
return;
} | conditional_block |
api_str.rs | // These tests don't really make sense with the bytes API, so we only test them
// on the Unicode API.
#[test]
fn empty_match_unicode_find_iter() {
// Tests that we still yield byte ranges at valid UTF-8 sequence boundaries
// even when we're susceptible to empty width matches.
let re = regex!(r".*?");
assert_eq!(
vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)],
findall!(re, "Ⅰ1Ⅱ2")
);
}
#[test]
fn empty_match_unicode_captures_iter() {
// Same as empty_match_unicode_find_iter, but tests capture iteration.
let re = regex!(r".*?");
let ms: Vec<_> = re
.captures_iter(text!("Ⅰ1Ⅱ2"))
.map(|c| c.get(0).unwrap())
.map(|m| (m.start(), m.end()))
.collect(); | let re = regex!(r"fo+");
let caps = re.captures("barfoobar").unwrap();
assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo"));
assert_eq!(caps.get(0).map(From::from), Some("foo"));
assert_eq!(caps.get(0).map(Into::into), Some("foo"));
} | assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], ms);
}
#[test]
fn match_as_str() { | random_line_split |
api_str.rs | // These tests don't really make sense with the bytes API, so we only test them
// on the Unicode API.
#[test]
fn empty_match_unicode_find_iter() {
// Tests that we still yield byte ranges at valid UTF-8 sequence boundaries
// even when we're susceptible to empty width matches.
let re = regex!(r".*?");
assert_eq!(
vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)],
findall!(re, "Ⅰ1Ⅱ2")
);
}
#[test]
fn empt |
// Same as empty_match_unicode_find_iter, but tests capture iteration.
let re = regex!(r".*?");
let ms: Vec<_> = re
.captures_iter(text!("Ⅰ1Ⅱ2"))
.map(|c| c.get(0).unwrap())
.map(|m| (m.start(), m.end()))
.collect();
assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], ms);
}
#[test]
fn match_as_str() {
let re = regex!(r"fo+");
let caps = re.captures("barfoobar").unwrap();
assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo"));
assert_eq!(caps.get(0).map(From::from), Some("foo"));
assert_eq!(caps.get(0).map(Into::into), Some("foo"));
}
| y_match_unicode_captures_iter() { | identifier_name |
api_str.rs | // These tests don't really make sense with the bytes API, so we only test them
// on the Unicode API.
#[test]
fn empty_match_unicode_find_iter() {
// Tests that we still yield byte ranges at valid UTF-8 sequence boundaries
// even when we're susceptible to empty width matches.
let re = regex!(r".*?");
assert_eq!(
vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)],
findall!(re, "Ⅰ1Ⅱ2")
);
}
#[test]
fn empty_match_unicode_captures_iter() {
// Same as empty_match_unicode_find_iter, but tests capture iteration.
let re = regex!(r".*?");
let ms: Vec<_> = re
.captures_iter(text!("Ⅰ1Ⅱ2"))
.map(|c| c.get(0).unwrap())
.map(|m| (m.start(), m.end()))
.collect();
assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], ms);
}
#[test]
fn match_as_str() {
le | t re = regex!(r"fo+");
let caps = re.captures("barfoobar").unwrap();
assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo"));
assert_eq!(caps.get(0).map(From::from), Some("foo"));
assert_eq!(caps.get(0).map(Into::into), Some("foo"));
}
| identifier_body |
|
font_template.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 font::FontHandleMethods;
use platform::font_context::FontContextHandle;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use string_cache::Atom;
use std::sync::{Arc, Weak};
use style::computed_values::{font_stretch, font_weight};
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Eq, Hash)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub stretch: font_stretch::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: font_weight::T, stretch: font_stretch::T, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight.is_bold() == other.weight.is_bold() &&
self.stretch == other.stretch &&
self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> FontTemplate {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(strong_ref.downgrade()),
None => None,
};
FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
}
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn get_if_matches(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> | let actual_desc = FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic());
let desc_match = actual_desc == *requested_desc;
self.descriptor = Some(actual_desc);
self.is_valid = true;
if desc_match {
Some(data)
} else {
None
}
}
Err(()) => {
self.is_valid = false;
debug!("Unable to create a font from template {}", self.identifier);
None
}
}
}
None => None,
}
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
Some(self.get_data())
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn get_data(&mut self) -> Arc<FontTemplateData> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return data
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None));
self.weak_ref = Some(template_data.downgrade());
template_data
}
}
| {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) => {
if *requested_desc == actual_desc {
Some(self.get_data())
} else {
None
}
},
None if self.is_valid => {
let data = self.get_data();
let handle: Result<FontHandle, ()> =
FontHandleMethods::new_from_template(fctx, data.clone(), None);
match handle {
Ok(handle) => { | identifier_body |
font_template.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 font::FontHandleMethods;
use platform::font_context::FontContextHandle;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use string_cache::Atom;
use std::sync::{Arc, Weak};
use style::computed_values::{font_stretch, font_weight};
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Eq, Hash)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub stretch: font_stretch::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: font_weight::T, stretch: font_stretch::T, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight.is_bold() == other.weight.is_bold() &&
self.stretch == other.stretch &&
self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> FontTemplate {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(strong_ref.downgrade()),
None => None,
};
FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
}
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn get_if_matches(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) => | ,
None if self.is_valid => {
let data = self.get_data();
let handle: Result<FontHandle, ()> =
FontHandleMethods::new_from_template(fctx, data.clone(), None);
match handle {
Ok(handle) => {
let actual_desc = FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic());
let desc_match = actual_desc == *requested_desc;
self.descriptor = Some(actual_desc);
self.is_valid = true;
if desc_match {
Some(data)
} else {
None
}
}
Err(()) => {
self.is_valid = false;
debug!("Unable to create a font from template {}", self.identifier);
None
}
}
}
None => None,
}
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
Some(self.get_data())
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn get_data(&mut self) -> Arc<FontTemplateData> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return data
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None));
self.weak_ref = Some(template_data.downgrade());
template_data
}
}
| {
if *requested_desc == actual_desc {
Some(self.get_data())
} else {
None
}
} | conditional_block |
font_template.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 font::FontHandleMethods;
use platform::font_context::FontContextHandle;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use string_cache::Atom;
use std::sync::{Arc, Weak};
use style::computed_values::{font_stretch, font_weight};
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Eq, Hash)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub stretch: font_stretch::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: font_weight::T, stretch: font_stretch::T, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight.is_bold() == other.weight.is_bold() &&
self.stretch == other.stretch &&
self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> FontTemplate {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(strong_ref.downgrade()),
None => None,
};
FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
}
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn | (&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) => {
if *requested_desc == actual_desc {
Some(self.get_data())
} else {
None
}
},
None if self.is_valid => {
let data = self.get_data();
let handle: Result<FontHandle, ()> =
FontHandleMethods::new_from_template(fctx, data.clone(), None);
match handle {
Ok(handle) => {
let actual_desc = FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic());
let desc_match = actual_desc == *requested_desc;
self.descriptor = Some(actual_desc);
self.is_valid = true;
if desc_match {
Some(data)
} else {
None
}
}
Err(()) => {
self.is_valid = false;
debug!("Unable to create a font from template {}", self.identifier);
None
}
}
}
None => None,
}
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
Some(self.get_data())
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn get_data(&mut self) -> Arc<FontTemplateData> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return data
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None));
self.weak_ref = Some(template_data.downgrade());
template_data
}
}
| get_if_matches | identifier_name |
font_template.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 font::FontHandleMethods;
use platform::font_context::FontContextHandle;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use string_cache::Atom;
use std::sync::{Arc, Weak};
use style::computed_values::{font_stretch, font_weight};
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Eq, Hash)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub stretch: font_stretch::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: font_weight::T, stretch: font_stretch::T, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight.is_bold() == other.weight.is_bold() &&
self.stretch == other.stretch &&
self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> FontTemplate {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(strong_ref.downgrade()),
None => None,
};
FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
}
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn get_if_matches(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) => {
if *requested_desc == actual_desc {
Some(self.get_data())
} else {
None
}
},
None if self.is_valid => {
let data = self.get_data();
let handle: Result<FontHandle, ()> =
FontHandleMethods::new_from_template(fctx, data.clone(), None);
match handle {
Ok(handle) => {
let actual_desc = FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic());
let desc_match = actual_desc == *requested_desc;
self.descriptor = Some(actual_desc);
self.is_valid = true;
if desc_match {
Some(data)
} else {
None
}
}
Err(()) => {
self.is_valid = false;
debug!("Unable to create a font from template {}", self.identifier);
None
}
}
}
None => None,
}
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
Some(self.get_data())
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn get_data(&mut self) -> Arc<FontTemplateData> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(), | return data
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None));
self.weak_ref = Some(template_data.downgrade());
template_data
}
} | None => None,
};
if let Some(data) = maybe_data { | random_line_split |
walker.rs | use std::cell::RefCell;
use std::io;
use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir, WalkDirIterator};
use pulldown_cmark::{Event, Parser, Tag};
use file_utils;
/// Wrapper of a list of Markdown files. With end goal to be able to convey the | /// hierarchy.
pub struct MarkdownFileList {
// Considering maintaining directory structure by Map<Vec<>>
files: Vec<MarkdownFile>,
}
impl MarkdownFileList {
pub fn new(files: Vec<MarkdownFile>) -> MarkdownFileList {
let mut sorted_files = files;
sorted_files.sort_by(|a, b| a.get_file_name().cmp(&b.get_file_name()));
MarkdownFileList {
files: sorted_files,
}
}
/// Get all Markdown files
pub fn get_files(&self) -> &Vec<MarkdownFile> {
&self.files
}
}
#[derive(Debug)]
pub struct MarkdownFile {
path: PathBuf,
heading: RefCell<String>,
}
impl MarkdownFile {
/// Creates a `MarkdownFile` from the provided path
pub fn from(path: &Path) -> MarkdownFile {
MarkdownFile {
path: path.to_path_buf(),
heading: RefCell::new(String::new()),
}
}
/// Return the path of the Markdown file
pub fn get_path(&self) -> &PathBuf {
&self.path
}
/// Return the name of the Markdown file
pub fn get_file_name(&self) -> String {
self.path
.as_path()
.file_stem()
.and_then(|x| x.to_str())
.expect("Unable to get Markdown filename")
.to_string()
}
/// Return the main heading of the Markdown file
pub fn get_heading(&self) -> String {
if self.heading.borrow().is_empty() {
let content = file_utils::read_from_file(&self.path)
.expect(&format!("Unable to read Markdown file: {:?}", self.path));
let parser = Parser::new(&content);
let mut iter = parser.into_iter();
let mut opt_header = None;
let mut in_header = false;
while let Some(event) = iter.next() {
// Look for a start event for a heading
if let Event::Start(tag) = event {
// Check the tag
if let Tag::Header(num) = tag {
if num == 1 {
in_header = true;
}
}
} else if let Event::Text(text) = event {
if in_header {
opt_header = Some(text.to_string());
break;
}
}
}
let result = opt_header.expect(&format!("No header 1 found for {:?}", self.path));
self.heading.borrow_mut().push_str(&result);
result
} else {
self.heading.borrow().clone()
}
}
}
/// Checks that the file extension matches the expected _md_.
fn is_accepted_markdown_file(path: &Path) -> bool {
const FILE_EXT: &str = "md";
if let Some(extension) = path.extension().and_then(|x| x.to_str()) {
if extension.to_lowercase().eq(FILE_EXT) {
return true;
}
}
false
}
/// Determines if the provided entry should be excluded from the files to check.
/// The check just determines if the file or directory begins with an
/// underscore.
fn is_excluded(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s.starts_with('_'))
.unwrap_or(false)
}
/// Walks the specified root directory to find all Markdown files and returns
/// the list of discovered files. A file is added if it has a file extension of
/// `*.md` or `*.MD`. Files will be ignored if they begin with an underscore,
/// this also includes any Markdown files beginning with an underscore.
pub fn find_markdown_files<P: AsRef<Path>>(root_dir: P) -> Result<Vec<MarkdownFile>, io::Error> {
let mut files = vec![];
let files_to_check = WalkDir::new(root_dir)
.into_iter()
.filter_entry(|file|!is_excluded(file));
for entry in files_to_check {
let entry = entry?;
let path = entry.path();
if is_accepted_markdown_file(path) {
debug!("Adding file {:?}", path);
files.push(MarkdownFile::from(path));
}
}
Ok(files)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::cell::RefCell;
#[test]
fn test_get_file_name() {
let file = super::MarkdownFile {
path: PathBuf::from("resources/tester.md"),
heading: RefCell::new(String::new()),
};
assert_eq!(file.get_file_name(), "tester");
}
#[test]
fn test_find_markdown_files() {
const ROOT_DIR: &str = "tests/resources/input/site";
let files = super::find_markdown_files(ROOT_DIR).unwrap();
const SKIPPED_TOP: &str = "_ignored_top.md";
const SKIPPED_NESTED: &str = "_ignored_nested.md";
let file_names: Vec<String> = files.iter().map(|x| x.get_file_name()).collect();
assert!(!file_names.contains(&SKIPPED_TOP.to_string()));
assert!(!file_names.contains(&SKIPPED_NESTED.to_string()));
}
} | random_line_split |
|
walker.rs | use std::cell::RefCell;
use std::io;
use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir, WalkDirIterator};
use pulldown_cmark::{Event, Parser, Tag};
use file_utils;
/// Wrapper of a list of Markdown files. With end goal to be able to convey the
/// hierarchy.
pub struct MarkdownFileList {
// Considering maintaining directory structure by Map<Vec<>>
files: Vec<MarkdownFile>,
}
impl MarkdownFileList {
pub fn new(files: Vec<MarkdownFile>) -> MarkdownFileList {
let mut sorted_files = files;
sorted_files.sort_by(|a, b| a.get_file_name().cmp(&b.get_file_name()));
MarkdownFileList {
files: sorted_files,
}
}
/// Get all Markdown files
pub fn get_files(&self) -> &Vec<MarkdownFile> {
&self.files
}
}
#[derive(Debug)]
pub struct MarkdownFile {
path: PathBuf,
heading: RefCell<String>,
}
impl MarkdownFile {
/// Creates a `MarkdownFile` from the provided path
pub fn from(path: &Path) -> MarkdownFile {
MarkdownFile {
path: path.to_path_buf(),
heading: RefCell::new(String::new()),
}
}
/// Return the path of the Markdown file
pub fn get_path(&self) -> &PathBuf {
&self.path
}
/// Return the name of the Markdown file
pub fn get_file_name(&self) -> String {
self.path
.as_path()
.file_stem()
.and_then(|x| x.to_str())
.expect("Unable to get Markdown filename")
.to_string()
}
/// Return the main heading of the Markdown file
pub fn get_heading(&self) -> String {
if self.heading.borrow().is_empty() {
let content = file_utils::read_from_file(&self.path)
.expect(&format!("Unable to read Markdown file: {:?}", self.path));
let parser = Parser::new(&content);
let mut iter = parser.into_iter();
let mut opt_header = None;
let mut in_header = false;
while let Some(event) = iter.next() {
// Look for a start event for a heading
if let Event::Start(tag) = event {
// Check the tag
if let Tag::Header(num) = tag {
if num == 1 {
in_header = true;
}
}
} else if let Event::Text(text) = event {
if in_header {
opt_header = Some(text.to_string());
break;
}
}
}
let result = opt_header.expect(&format!("No header 1 found for {:?}", self.path));
self.heading.borrow_mut().push_str(&result);
result
} else {
self.heading.borrow().clone()
}
}
}
/// Checks that the file extension matches the expected _md_.
fn is_accepted_markdown_file(path: &Path) -> bool {
const FILE_EXT: &str = "md";
if let Some(extension) = path.extension().and_then(|x| x.to_str()) {
if extension.to_lowercase().eq(FILE_EXT) {
return true;
}
}
false
}
/// Determines if the provided entry should be excluded from the files to check.
/// The check just determines if the file or directory begins with an
/// underscore.
fn is_excluded(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s.starts_with('_'))
.unwrap_or(false)
}
/// Walks the specified root directory to find all Markdown files and returns
/// the list of discovered files. A file is added if it has a file extension of
/// `*.md` or `*.MD`. Files will be ignored if they begin with an underscore,
/// this also includes any Markdown files beginning with an underscore.
pub fn find_markdown_files<P: AsRef<Path>>(root_dir: P) -> Result<Vec<MarkdownFile>, io::Error> {
let mut files = vec![];
let files_to_check = WalkDir::new(root_dir)
.into_iter()
.filter_entry(|file|!is_excluded(file));
for entry in files_to_check {
let entry = entry?;
let path = entry.path();
if is_accepted_markdown_file(path) |
}
Ok(files)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::cell::RefCell;
#[test]
fn test_get_file_name() {
let file = super::MarkdownFile {
path: PathBuf::from("resources/tester.md"),
heading: RefCell::new(String::new()),
};
assert_eq!(file.get_file_name(), "tester");
}
#[test]
fn test_find_markdown_files() {
const ROOT_DIR: &str = "tests/resources/input/site";
let files = super::find_markdown_files(ROOT_DIR).unwrap();
const SKIPPED_TOP: &str = "_ignored_top.md";
const SKIPPED_NESTED: &str = "_ignored_nested.md";
let file_names: Vec<String> = files.iter().map(|x| x.get_file_name()).collect();
assert!(!file_names.contains(&SKIPPED_TOP.to_string()));
assert!(!file_names.contains(&SKIPPED_NESTED.to_string()));
}
}
| {
debug!("Adding file {:?}", path);
files.push(MarkdownFile::from(path));
} | conditional_block |
walker.rs | use std::cell::RefCell;
use std::io;
use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir, WalkDirIterator};
use pulldown_cmark::{Event, Parser, Tag};
use file_utils;
/// Wrapper of a list of Markdown files. With end goal to be able to convey the
/// hierarchy.
pub struct MarkdownFileList {
// Considering maintaining directory structure by Map<Vec<>>
files: Vec<MarkdownFile>,
}
impl MarkdownFileList {
pub fn new(files: Vec<MarkdownFile>) -> MarkdownFileList {
let mut sorted_files = files;
sorted_files.sort_by(|a, b| a.get_file_name().cmp(&b.get_file_name()));
MarkdownFileList {
files: sorted_files,
}
}
/// Get all Markdown files
pub fn get_files(&self) -> &Vec<MarkdownFile> {
&self.files
}
}
#[derive(Debug)]
pub struct MarkdownFile {
path: PathBuf,
heading: RefCell<String>,
}
impl MarkdownFile {
/// Creates a `MarkdownFile` from the provided path
pub fn from(path: &Path) -> MarkdownFile {
MarkdownFile {
path: path.to_path_buf(),
heading: RefCell::new(String::new()),
}
}
/// Return the path of the Markdown file
pub fn get_path(&self) -> &PathBuf {
&self.path
}
/// Return the name of the Markdown file
pub fn get_file_name(&self) -> String {
self.path
.as_path()
.file_stem()
.and_then(|x| x.to_str())
.expect("Unable to get Markdown filename")
.to_string()
}
/// Return the main heading of the Markdown file
pub fn get_heading(&self) -> String {
if self.heading.borrow().is_empty() {
let content = file_utils::read_from_file(&self.path)
.expect(&format!("Unable to read Markdown file: {:?}", self.path));
let parser = Parser::new(&content);
let mut iter = parser.into_iter();
let mut opt_header = None;
let mut in_header = false;
while let Some(event) = iter.next() {
// Look for a start event for a heading
if let Event::Start(tag) = event {
// Check the tag
if let Tag::Header(num) = tag {
if num == 1 {
in_header = true;
}
}
} else if let Event::Text(text) = event {
if in_header {
opt_header = Some(text.to_string());
break;
}
}
}
let result = opt_header.expect(&format!("No header 1 found for {:?}", self.path));
self.heading.borrow_mut().push_str(&result);
result
} else {
self.heading.borrow().clone()
}
}
}
/// Checks that the file extension matches the expected _md_.
fn is_accepted_markdown_file(path: &Path) -> bool |
/// Determines if the provided entry should be excluded from the files to check.
/// The check just determines if the file or directory begins with an
/// underscore.
fn is_excluded(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s.starts_with('_'))
.unwrap_or(false)
}
/// Walks the specified root directory to find all Markdown files and returns
/// the list of discovered files. A file is added if it has a file extension of
/// `*.md` or `*.MD`. Files will be ignored if they begin with an underscore,
/// this also includes any Markdown files beginning with an underscore.
pub fn find_markdown_files<P: AsRef<Path>>(root_dir: P) -> Result<Vec<MarkdownFile>, io::Error> {
let mut files = vec![];
let files_to_check = WalkDir::new(root_dir)
.into_iter()
.filter_entry(|file|!is_excluded(file));
for entry in files_to_check {
let entry = entry?;
let path = entry.path();
if is_accepted_markdown_file(path) {
debug!("Adding file {:?}", path);
files.push(MarkdownFile::from(path));
}
}
Ok(files)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::cell::RefCell;
#[test]
fn test_get_file_name() {
let file = super::MarkdownFile {
path: PathBuf::from("resources/tester.md"),
heading: RefCell::new(String::new()),
};
assert_eq!(file.get_file_name(), "tester");
}
#[test]
fn test_find_markdown_files() {
const ROOT_DIR: &str = "tests/resources/input/site";
let files = super::find_markdown_files(ROOT_DIR).unwrap();
const SKIPPED_TOP: &str = "_ignored_top.md";
const SKIPPED_NESTED: &str = "_ignored_nested.md";
let file_names: Vec<String> = files.iter().map(|x| x.get_file_name()).collect();
assert!(!file_names.contains(&SKIPPED_TOP.to_string()));
assert!(!file_names.contains(&SKIPPED_NESTED.to_string()));
}
}
| {
const FILE_EXT: &str = "md";
if let Some(extension) = path.extension().and_then(|x| x.to_str()) {
if extension.to_lowercase().eq(FILE_EXT) {
return true;
}
}
false
} | identifier_body |
walker.rs | use std::cell::RefCell;
use std::io;
use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir, WalkDirIterator};
use pulldown_cmark::{Event, Parser, Tag};
use file_utils;
/// Wrapper of a list of Markdown files. With end goal to be able to convey the
/// hierarchy.
pub struct MarkdownFileList {
// Considering maintaining directory structure by Map<Vec<>>
files: Vec<MarkdownFile>,
}
impl MarkdownFileList {
pub fn new(files: Vec<MarkdownFile>) -> MarkdownFileList {
let mut sorted_files = files;
sorted_files.sort_by(|a, b| a.get_file_name().cmp(&b.get_file_name()));
MarkdownFileList {
files: sorted_files,
}
}
/// Get all Markdown files
pub fn get_files(&self) -> &Vec<MarkdownFile> {
&self.files
}
}
#[derive(Debug)]
pub struct MarkdownFile {
path: PathBuf,
heading: RefCell<String>,
}
impl MarkdownFile {
/// Creates a `MarkdownFile` from the provided path
pub fn | (path: &Path) -> MarkdownFile {
MarkdownFile {
path: path.to_path_buf(),
heading: RefCell::new(String::new()),
}
}
/// Return the path of the Markdown file
pub fn get_path(&self) -> &PathBuf {
&self.path
}
/// Return the name of the Markdown file
pub fn get_file_name(&self) -> String {
self.path
.as_path()
.file_stem()
.and_then(|x| x.to_str())
.expect("Unable to get Markdown filename")
.to_string()
}
/// Return the main heading of the Markdown file
pub fn get_heading(&self) -> String {
if self.heading.borrow().is_empty() {
let content = file_utils::read_from_file(&self.path)
.expect(&format!("Unable to read Markdown file: {:?}", self.path));
let parser = Parser::new(&content);
let mut iter = parser.into_iter();
let mut opt_header = None;
let mut in_header = false;
while let Some(event) = iter.next() {
// Look for a start event for a heading
if let Event::Start(tag) = event {
// Check the tag
if let Tag::Header(num) = tag {
if num == 1 {
in_header = true;
}
}
} else if let Event::Text(text) = event {
if in_header {
opt_header = Some(text.to_string());
break;
}
}
}
let result = opt_header.expect(&format!("No header 1 found for {:?}", self.path));
self.heading.borrow_mut().push_str(&result);
result
} else {
self.heading.borrow().clone()
}
}
}
/// Checks that the file extension matches the expected _md_.
fn is_accepted_markdown_file(path: &Path) -> bool {
const FILE_EXT: &str = "md";
if let Some(extension) = path.extension().and_then(|x| x.to_str()) {
if extension.to_lowercase().eq(FILE_EXT) {
return true;
}
}
false
}
/// Determines if the provided entry should be excluded from the files to check.
/// The check just determines if the file or directory begins with an
/// underscore.
fn is_excluded(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s.starts_with('_'))
.unwrap_or(false)
}
/// Walks the specified root directory to find all Markdown files and returns
/// the list of discovered files. A file is added if it has a file extension of
/// `*.md` or `*.MD`. Files will be ignored if they begin with an underscore,
/// this also includes any Markdown files beginning with an underscore.
pub fn find_markdown_files<P: AsRef<Path>>(root_dir: P) -> Result<Vec<MarkdownFile>, io::Error> {
let mut files = vec![];
let files_to_check = WalkDir::new(root_dir)
.into_iter()
.filter_entry(|file|!is_excluded(file));
for entry in files_to_check {
let entry = entry?;
let path = entry.path();
if is_accepted_markdown_file(path) {
debug!("Adding file {:?}", path);
files.push(MarkdownFile::from(path));
}
}
Ok(files)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::cell::RefCell;
#[test]
fn test_get_file_name() {
let file = super::MarkdownFile {
path: PathBuf::from("resources/tester.md"),
heading: RefCell::new(String::new()),
};
assert_eq!(file.get_file_name(), "tester");
}
#[test]
fn test_find_markdown_files() {
const ROOT_DIR: &str = "tests/resources/input/site";
let files = super::find_markdown_files(ROOT_DIR).unwrap();
const SKIPPED_TOP: &str = "_ignored_top.md";
const SKIPPED_NESTED: &str = "_ignored_nested.md";
let file_names: Vec<String> = files.iter().map(|x| x.get_file_name()).collect();
assert!(!file_names.contains(&SKIPPED_TOP.to_string()));
assert!(!file_names.contains(&SKIPPED_NESTED.to_string()));
}
}
| from | identifier_name |
transitionevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::TransitionEventBinding;
use dom::bindings::codegen::Bindings::TransitionEventBinding::{TransitionEventInit, TransitionEventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::num::Finite;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::globalscope::GlobalScope;
use dom::window::Window;
use servo_atoms::Atom;
#[dom_struct]
pub struct TransitionEvent {
event: Event,
property_name: Atom,
elapsed_time: Finite<f32>,
pseudo_element: DOMString,
}
impl TransitionEvent {
pub fn new_inherited(init: &TransitionEventInit) -> TransitionEvent {
TransitionEvent {
event: Event::new_inherited(),
property_name: Atom::from(init.propertyName.clone()),
elapsed_time: init.elapsedTime.clone(),
pseudo_element: init.pseudoElement.clone()
}
}
pub fn new(global: &GlobalScope,
type_: Atom,
init: &TransitionEventInit) -> Root<TransitionEvent> {
let ev = reflect_dom_object(box TransitionEvent::new_inherited(init),
global,
TransitionEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.init_event(type_, init.parent.bubbles, init.parent.cancelable);
}
ev
}
pub fn Constructor(window: &Window,
type_: DOMString,
init: &TransitionEventInit) -> Fallible<Root<TransitionEvent>> {
let global = window.upcast::<GlobalScope>();
Ok(TransitionEvent::new(global, Atom::from(type_), init))
}
}
impl TransitionEventMethods for TransitionEvent {
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-propertyName
fn PropertyName(&self) -> DOMString {
DOMString::from(&*self.property_name)
}
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-elapsedTime
fn ElapsedTime(&self) -> Finite<f32> {
self.elapsed_time.clone()
}
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-pseudoElement
fn PseudoElement(&self) -> DOMString |
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.upcast::<Event>().IsTrusted()
}
}
| {
self.pseudo_element.clone()
} | identifier_body |
transitionevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::TransitionEventBinding;
use dom::bindings::codegen::Bindings::TransitionEventBinding::{TransitionEventInit, TransitionEventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::num::Finite;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::globalscope::GlobalScope;
use dom::window::Window;
use servo_atoms::Atom;
#[dom_struct]
pub struct TransitionEvent {
event: Event,
property_name: Atom,
elapsed_time: Finite<f32>,
pseudo_element: DOMString,
}
impl TransitionEvent {
pub fn new_inherited(init: &TransitionEventInit) -> TransitionEvent {
TransitionEvent {
event: Event::new_inherited(),
property_name: Atom::from(init.propertyName.clone()),
elapsed_time: init.elapsedTime.clone(),
pseudo_element: init.pseudoElement.clone()
}
}
pub fn new(global: &GlobalScope,
type_: Atom,
init: &TransitionEventInit) -> Root<TransitionEvent> {
let ev = reflect_dom_object(box TransitionEvent::new_inherited(init),
global,
TransitionEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.init_event(type_, init.parent.bubbles, init.parent.cancelable);
}
ev
}
pub fn Constructor(window: &Window,
type_: DOMString,
init: &TransitionEventInit) -> Fallible<Root<TransitionEvent>> {
let global = window.upcast::<GlobalScope>();
Ok(TransitionEvent::new(global, Atom::from(type_), init))
}
}
impl TransitionEventMethods for TransitionEvent {
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-propertyName
fn | (&self) -> DOMString {
DOMString::from(&*self.property_name)
}
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-elapsedTime
fn ElapsedTime(&self) -> Finite<f32> {
self.elapsed_time.clone()
}
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-pseudoElement
fn PseudoElement(&self) -> DOMString {
self.pseudo_element.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.upcast::<Event>().IsTrusted()
}
}
| PropertyName | identifier_name |
transitionevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::TransitionEventBinding;
use dom::bindings::codegen::Bindings::TransitionEventBinding::{TransitionEventInit, TransitionEventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::num::Finite;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::globalscope::GlobalScope;
use dom::window::Window;
use servo_atoms::Atom;
#[dom_struct]
pub struct TransitionEvent {
event: Event,
property_name: Atom,
elapsed_time: Finite<f32>,
pseudo_element: DOMString,
}
impl TransitionEvent {
pub fn new_inherited(init: &TransitionEventInit) -> TransitionEvent {
TransitionEvent {
event: Event::new_inherited(),
property_name: Atom::from(init.propertyName.clone()),
elapsed_time: init.elapsedTime.clone(),
pseudo_element: init.pseudoElement.clone()
}
}
pub fn new(global: &GlobalScope,
type_: Atom,
init: &TransitionEventInit) -> Root<TransitionEvent> {
let ev = reflect_dom_object(box TransitionEvent::new_inherited(init),
global,
TransitionEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.init_event(type_, init.parent.bubbles, init.parent.cancelable); | }
ev
}
pub fn Constructor(window: &Window,
type_: DOMString,
init: &TransitionEventInit) -> Fallible<Root<TransitionEvent>> {
let global = window.upcast::<GlobalScope>();
Ok(TransitionEvent::new(global, Atom::from(type_), init))
}
}
impl TransitionEventMethods for TransitionEvent {
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-propertyName
fn PropertyName(&self) -> DOMString {
DOMString::from(&*self.property_name)
}
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-elapsedTime
fn ElapsedTime(&self) -> Finite<f32> {
self.elapsed_time.clone()
}
// https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-pseudoElement
fn PseudoElement(&self) -> DOMString {
self.pseudo_element.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.upcast::<Event>().IsTrusted()
}
} | random_line_split |
|
video.rs | use sdl2;
pub fn main() | sdl2::event::QuitEvent(_) => break'main,
sdl2::event::KeyDownEvent(_, _, key, _, _) => {
if key == sdl2::keycode::EscapeKey {
break'main
}
},
sdl2::event::NoEvent => break 'event,
_ => {}
}
}
}
sdl2::quit();
}
| {
sdl2::init(sdl2::InitVideo);
let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) {
Ok(window) => window,
Err(err) => fail!(format!("failed to create window: {}", err))
};
let renderer = match sdl2::render::Renderer::from_window(window, sdl2::render::DriverAuto, sdl2::render::Accelerated) {
Ok(renderer) => renderer,
Err(err) => fail!(format!("failed to create renderer: {}", err))
};
let _ = renderer.set_draw_color(sdl2::pixels::RGB(255, 0, 0));
let _ = renderer.clear();
renderer.present();
'main : loop {
'event : loop {
match sdl2::event::poll_event() { | identifier_body |
video.rs | use sdl2;
pub fn main() {
sdl2::init(sdl2::InitVideo);
let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) {
Ok(window) => window,
Err(err) => fail!(format!("failed to create window: {}", err))
};
let renderer = match sdl2::render::Renderer::from_window(window, sdl2::render::DriverAuto, sdl2::render::Accelerated) {
Ok(renderer) => renderer,
Err(err) => fail!(format!("failed to create renderer: {}", err))
};
let _ = renderer.set_draw_color(sdl2::pixels::RGB(255, 0, 0));
let _ = renderer.clear();
renderer.present();
'main : loop {
'event : loop {
match sdl2::event::poll_event() {
sdl2::event::QuitEvent(_) => break'main,
sdl2::event::KeyDownEvent(_, _, key, _, _) => {
if key == sdl2::keycode::EscapeKey |
},
sdl2::event::NoEvent => break 'event,
_ => {}
}
}
}
sdl2::quit();
}
| {
break 'main
} | conditional_block |
video.rs | use sdl2;
pub fn | () {
sdl2::init(sdl2::InitVideo);
let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) {
Ok(window) => window,
Err(err) => fail!(format!("failed to create window: {}", err))
};
let renderer = match sdl2::render::Renderer::from_window(window, sdl2::render::DriverAuto, sdl2::render::Accelerated) {
Ok(renderer) => renderer,
Err(err) => fail!(format!("failed to create renderer: {}", err))
};
let _ = renderer.set_draw_color(sdl2::pixels::RGB(255, 0, 0));
let _ = renderer.clear();
renderer.present();
'main : loop {
'event : loop {
match sdl2::event::poll_event() {
sdl2::event::QuitEvent(_) => break'main,
sdl2::event::KeyDownEvent(_, _, key, _, _) => {
if key == sdl2::keycode::EscapeKey {
break'main
}
},
sdl2::event::NoEvent => break 'event,
_ => {}
}
}
}
sdl2::quit();
}
| main | identifier_name |
video.rs | use sdl2;
pub fn main() {
sdl2::init(sdl2::InitVideo);
let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) {
Ok(window) => window,
Err(err) => fail!(format!("failed to create window: {}", err))
};
let renderer = match sdl2::render::Renderer::from_window(window, sdl2::render::DriverAuto, sdl2::render::Accelerated) { | Err(err) => fail!(format!("failed to create renderer: {}", err))
};
let _ = renderer.set_draw_color(sdl2::pixels::RGB(255, 0, 0));
let _ = renderer.clear();
renderer.present();
'main : loop {
'event : loop {
match sdl2::event::poll_event() {
sdl2::event::QuitEvent(_) => break'main,
sdl2::event::KeyDownEvent(_, _, key, _, _) => {
if key == sdl2::keycode::EscapeKey {
break'main
}
},
sdl2::event::NoEvent => break 'event,
_ => {}
}
}
}
sdl2::quit();
} | Ok(renderer) => renderer, | random_line_split |
simdty.rs | // Copyright 2016 chacha20-poly1305-aead Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.
#![allow(dead_code)]
#![allow(non_camel_case_types)]
use as_bytes::Safe;
#[cfg(feature = "simd")]
macro_rules! decl_simd {
($($decl:item)*) => {
$(
#[derive(Clone, Copy, Debug, Default)]
#[repr(simd)]
$decl
)*
}
}
#[cfg(not(feature = "simd"))]
macro_rules! decl_simd {
($($decl:item)*) => {
$(
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
$decl
)*
}
}
decl_simd! {
pub struct Simd4<T>(pub T, pub T, pub T, pub T);
pub struct Simd8<T>(pub T, pub T, pub T, pub T,
pub T, pub T, pub T, pub T);
pub struct Simd16<T>(pub T, pub T, pub T, pub T,
pub T, pub T, pub T, pub T,
pub T, pub T, pub T, pub T,
pub T, pub T, pub T, pub T);
}
pub type u32x4 = Simd4<u32>;
pub type u16x8 = Simd8<u16>;
pub type u8x16 = Simd16<u8>;
#[cfg_attr(feature = "clippy", allow(inline_always))]
impl<T> Simd4<T> {
#[inline(always)]
pub fn | (e0: T, e1: T, e2: T, e3: T) -> Simd4<T> {
Simd4(e0, e1, e2, e3)
}
}
unsafe impl<T: Safe> Safe for Simd4<T> {}
unsafe impl<T: Safe> Safe for Simd8<T> {}
unsafe impl<T: Safe> Safe for Simd16<T> {}
| new | identifier_name |
simdty.rs | // Copyright 2016 chacha20-poly1305-aead Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.
#![allow(dead_code)]
#![allow(non_camel_case_types)]
use as_bytes::Safe;
#[cfg(feature = "simd")]
macro_rules! decl_simd {
($($decl:item)*) => {
$(
#[derive(Clone, Copy, Debug, Default)]
#[repr(simd)]
$decl
)*
}
}
#[cfg(not(feature = "simd"))]
macro_rules! decl_simd {
($($decl:item)*) => {
$(
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
$decl
)*
}
}
decl_simd! {
pub struct Simd4<T>(pub T, pub T, pub T, pub T);
pub struct Simd8<T>(pub T, pub T, pub T, pub T, | pub T, pub T, pub T, pub T,
pub T, pub T, pub T, pub T,
pub T, pub T, pub T, pub T);
}
pub type u32x4 = Simd4<u32>;
pub type u16x8 = Simd8<u16>;
pub type u8x16 = Simd16<u8>;
#[cfg_attr(feature = "clippy", allow(inline_always))]
impl<T> Simd4<T> {
#[inline(always)]
pub fn new(e0: T, e1: T, e2: T, e3: T) -> Simd4<T> {
Simd4(e0, e1, e2, e3)
}
}
unsafe impl<T: Safe> Safe for Simd4<T> {}
unsafe impl<T: Safe> Safe for Simd8<T> {}
unsafe impl<T: Safe> Safe for Simd16<T> {} | pub T, pub T, pub T, pub T);
pub struct Simd16<T>(pub T, pub T, pub T, pub T, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.