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 |
---|---|---|---|---|
default_ty_param_default_dependent_associated_type.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
#![feature(default_type_parameter_fallback)]
use std::marker::PhantomData;
trait Id {
type This;
}
impl<A> Id for A {
type This = A;
}
struct Foo<X: Default = usize, Y = <X as Id>::This> {
data: PhantomData<(X, Y)>
}
impl<X: Default, Y> Foo<X, Y> {
fn new() -> Foo<X, Y>
|
}
fn main() {
let foo = Foo::new();
}
|
{
Foo { data: PhantomData }
}
|
identifier_body
|
default_ty_param_default_dependent_associated_type.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
#![feature(default_type_parameter_fallback)]
use std::marker::PhantomData;
trait Id {
type This;
}
impl<A> Id for A {
type This = A;
}
struct Foo<X: Default = usize, Y = <X as Id>::This> {
data: PhantomData<(X, Y)>
}
impl<X: Default, Y> Foo<X, Y> {
fn
|
() -> Foo<X, Y> {
Foo { data: PhantomData }
}
}
fn main() {
let foo = Foo::new();
}
|
new
|
identifier_name
|
lib.rs
|
#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serializable types for the [Matrix Identity Service API][identity-api].
//! These types can be shared by client and identity service code.
//!
//! [identity-api]: https://spec.matrix.org/v1.2/identity-service-api/
#![warn(missing_docs)]
use std::fmt;
pub mod association;
pub mod authentication;
pub mod invitation;
pub mod keys;
pub mod lookup;
pub mod status;
pub mod tos;
// Wrapper around `Box<str>` that cannot be used in a meaningful way outside of
// this crate. Used for string enums because their `_Custom` variant can't be
// truly private (only `#[doc(hidden)]`).
#[doc(hidden)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct
|
(Box<str>);
impl fmt::Debug for PrivOwnedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
|
PrivOwnedStr
|
identifier_name
|
lib.rs
|
#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serializable types for the [Matrix Identity Service API][identity-api].
//! These types can be shared by client and identity service code.
//!
//! [identity-api]: https://spec.matrix.org/v1.2/identity-service-api/
|
pub mod association;
pub mod authentication;
pub mod invitation;
pub mod keys;
pub mod lookup;
pub mod status;
pub mod tos;
// Wrapper around `Box<str>` that cannot be used in a meaningful way outside of
// this crate. Used for string enums because their `_Custom` variant can't be
// truly private (only `#[doc(hidden)]`).
#[doc(hidden)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PrivOwnedStr(Box<str>);
impl fmt::Debug for PrivOwnedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
|
#![warn(missing_docs)]
use std::fmt;
|
random_line_split
|
lib.rs
|
#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serializable types for the [Matrix Identity Service API][identity-api].
//! These types can be shared by client and identity service code.
//!
//! [identity-api]: https://spec.matrix.org/v1.2/identity-service-api/
#![warn(missing_docs)]
use std::fmt;
pub mod association;
pub mod authentication;
pub mod invitation;
pub mod keys;
pub mod lookup;
pub mod status;
pub mod tos;
// Wrapper around `Box<str>` that cannot be used in a meaningful way outside of
// this crate. Used for string enums because their `_Custom` variant can't be
// truly private (only `#[doc(hidden)]`).
#[doc(hidden)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PrivOwnedStr(Box<str>);
impl fmt::Debug for PrivOwnedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
|
}
|
{
self.0.fmt(f)
}
|
identifier_body
|
main.rs
|
extern crate clap;
extern crate hex;
use clap::{App, Arg};
use self::hex::{FromHex, ToHex};
use std::collections::HashMap;
use std::io::{self, Read};
use std::f32;
use std::u8;
fn tally(vec: Vec<u8>) -> HashMap<u8, u8> {
let mut hashmap = HashMap::new();
for byte in vec {
let count = hashmap.entry(byte).or_insert(0);
*count += 1;
}
hashmap
}
fn normalize(hashmap: HashMap<u8, u8>) -> HashMap<u8, f32> {
let total = hashmap.iter().fold(0.0, |sum, (_, val)| sum + *val as f32);
hashmap.iter()
.map(|(&key, val)| (key, *val as f32 / total))
.collect()
}
fn
|
(vec: Vec<u8>) -> HashMap<u8, f32> {
let tallied = tally(vec);
normalize(tallied)
}
pub fn freqs_ascii() -> HashMap<u8, f32> {
[ (9, 0.000057)
, (23, 0.000000)
, (32, 0.171662)
, (33, 0.000072)
, (34, 0.002442)
, (35, 0.000179)
, (36, 0.000561)
, (37, 0.000160)
, (38, 0.000226)
, (39, 0.002447)
, (40, 0.002178)
, (41, 0.002233)
, (42, 0.000628)
, (43, 0.000215)
, (44, 0.007384)
, (45, 0.013734)
, (46, 0.015124)
, (47, 0.001549)
, (48, 0.005516)
, (49, 0.004594)
, (50, 0.003322)
, (51, 0.001847)
, (52, 0.001348)
, (53, 0.001663)
, (54, 0.001153)
, (55, 0.001030)
, (56, 0.001054)
, (57, 0.001024)
, (58, 0.004354)
, (59, 0.001214)
, (60, 0.001225)
, (61, 0.000227)
, (62, 0.001242)
, (63, 0.001474)
, (64, 0.000073)
, (65, 0.003132)
, (66, 0.002163)
, (67, 0.003906)
, (68, 0.003151)
, (69, 0.002673)
, (70, 0.001416)
, (71, 0.001876)
, (72, 0.002321)
, (73, 0.003211)
, (74, 0.001726)
, (75, 0.000687)
, (76, 0.001884)
, (77, 0.003529)
, (78, 0.002085)
, (79, 0.001842)
, (80, 0.002614)
, (81, 0.000316)
, (82, 0.002519)
, (83, 0.004003)
, (84, 0.003322)
, (85, 0.000814)
, (86, 0.000892)
, (87, 0.002527)
, (88, 0.000343)
, (89, 0.000304)
, (90, 0.000076)
, (91, 0.000086)
, (92, 0.000016)
, (93, 0.000088)
, (94, 0.000003)
, (95, 0.001159)
, (96, 0.000009)
, (97, 0.051880)
, (98, 0.010195)
, (99, 0.021129)
, (100, 0.025071)
, (101, 0.085771)
, (102, 0.013725)
, (103, 0.015597)
, (104, 0.027444)
, (105, 0.049019)
, (106, 0.000867)
, (107, 0.006753)
, (108, 0.031750)
, (109, 0.016437)
, (110, 0.049701)
, (111, 0.057701)
, (112, 0.015482)
, (113, 0.000747)
, (114, 0.042586)
, (115, 0.043686)
, (116, 0.063700)
, (117, 0.020999)
, (118, 0.008462)
, (119, 0.013034)
, (120, 0.001950)
, (121, 0.011330)
, (122, 0.000596)
, (123, 0.000026)
, (124, 0.000007)
, (125, 0.000026)
, (126, 0.000003)
, (131, 0.000000)
, (149, 0.006410)
, (183, 0.000010)
, (223, 0.000000)
, (226, 0.000000)
, (229, 0.000000)
, (230, 0.000000)
, (237, 0.000000)
].iter().cloned().collect()
}
fn mse(reference: HashMap<u8, f32>, target: HashMap<u8, f32>) -> f32 {
let mut result = HashMap::new();
for (key, val) in reference.iter() {
if target.contains_key(key) {
// (jtobin) branch is only entered if 'target' contains 'key'
let tval = target.get(key).unwrap();
let sqdiff = (tval - val).powf(2.0);
result.insert(key, sqdiff);
}
}
let size = result.len();
result.iter().fold(0.0, |sum, (_, val)| sum + val / size as f32)
}
fn score(string: &str) -> f32 {
let decoded = FromHex::from_hex(&string).unwrap();
let freq_dist = frequency_distribution(decoded);
mse(freqs_ascii(), freq_dist)
}
pub fn break_single_byte_xor(string: &str) -> (u8, String) {
let bytes: Vec<u8> = FromHex::from_hex(&string).unwrap();
let mut min = ("hi!".to_string(), 0, f32::INFINITY);
for ascii_char in 32..126 {
let mut other_bytes = bytes.clone();
for byte in other_bytes.iter_mut() {
*byte ^= ascii_char;
}
let decoded = String::from_utf8(other_bytes).unwrap();
let encoded = ToHex::to_hex(&decoded.clone());
let result = score(&encoded);
if result < min.2 { min = (decoded, ascii_char, result); }
}
(min.1, min.0)
}
fn main() {
let args = App::new("break_single_byte_xor")
.version("0.1.0")
.about("Break single-byte XOR")
.arg(Arg::with_name("return-byte")
.short("r")
.long("return-key")
.help("return encrypting byte"))
.get_matches();
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer)
.expect("single_byte_xor: bad input");
let return_byte = match args.occurrences_of("return-byte") {
0 => false,
_ => true,
};
let message = break_single_byte_xor(&buffer);
if return_byte {
println!("{} ({})", message.0 as char, message.0);
} else {
println!("{}", message.1);
}
}
|
frequency_distribution
|
identifier_name
|
main.rs
|
extern crate clap;
extern crate hex;
use clap::{App, Arg};
use self::hex::{FromHex, ToHex};
use std::collections::HashMap;
use std::io::{self, Read};
use std::f32;
use std::u8;
fn tally(vec: Vec<u8>) -> HashMap<u8, u8> {
let mut hashmap = HashMap::new();
for byte in vec {
let count = hashmap.entry(byte).or_insert(0);
*count += 1;
}
hashmap
}
fn normalize(hashmap: HashMap<u8, u8>) -> HashMap<u8, f32> {
let total = hashmap.iter().fold(0.0, |sum, (_, val)| sum + *val as f32);
hashmap.iter()
.map(|(&key, val)| (key, *val as f32 / total))
.collect()
}
fn frequency_distribution(vec: Vec<u8>) -> HashMap<u8, f32> {
let tallied = tally(vec);
normalize(tallied)
}
pub fn freqs_ascii() -> HashMap<u8, f32> {
[ (9, 0.000057)
, (23, 0.000000)
, (32, 0.171662)
, (33, 0.000072)
, (34, 0.002442)
, (35, 0.000179)
, (36, 0.000561)
, (37, 0.000160)
, (38, 0.000226)
, (39, 0.002447)
, (40, 0.002178)
, (41, 0.002233)
, (42, 0.000628)
, (43, 0.000215)
, (44, 0.007384)
, (45, 0.013734)
, (46, 0.015124)
, (47, 0.001549)
, (48, 0.005516)
, (49, 0.004594)
, (50, 0.003322)
, (51, 0.001847)
, (52, 0.001348)
, (53, 0.001663)
, (54, 0.001153)
, (55, 0.001030)
, (56, 0.001054)
, (57, 0.001024)
, (58, 0.004354)
, (59, 0.001214)
, (60, 0.001225)
, (61, 0.000227)
, (62, 0.001242)
, (63, 0.001474)
, (64, 0.000073)
, (65, 0.003132)
, (66, 0.002163)
, (67, 0.003906)
, (68, 0.003151)
, (69, 0.002673)
, (70, 0.001416)
, (71, 0.001876)
, (72, 0.002321)
, (73, 0.003211)
, (74, 0.001726)
, (75, 0.000687)
, (76, 0.001884)
, (77, 0.003529)
, (78, 0.002085)
, (79, 0.001842)
, (80, 0.002614)
, (81, 0.000316)
, (82, 0.002519)
, (83, 0.004003)
, (84, 0.003322)
, (85, 0.000814)
, (86, 0.000892)
, (87, 0.002527)
, (88, 0.000343)
, (89, 0.000304)
, (90, 0.000076)
, (91, 0.000086)
, (92, 0.000016)
, (93, 0.000088)
, (94, 0.000003)
, (95, 0.001159)
, (96, 0.000009)
, (97, 0.051880)
, (98, 0.010195)
, (99, 0.021129)
, (100, 0.025071)
, (101, 0.085771)
, (102, 0.013725)
, (103, 0.015597)
, (104, 0.027444)
, (105, 0.049019)
, (106, 0.000867)
, (107, 0.006753)
, (108, 0.031750)
, (109, 0.016437)
, (110, 0.049701)
, (111, 0.057701)
, (112, 0.015482)
, (113, 0.000747)
, (114, 0.042586)
, (115, 0.043686)
, (116, 0.063700)
, (117, 0.020999)
, (118, 0.008462)
, (119, 0.013034)
|
, (123, 0.000026)
, (124, 0.000007)
, (125, 0.000026)
, (126, 0.000003)
, (131, 0.000000)
, (149, 0.006410)
, (183, 0.000010)
, (223, 0.000000)
, (226, 0.000000)
, (229, 0.000000)
, (230, 0.000000)
, (237, 0.000000)
].iter().cloned().collect()
}
fn mse(reference: HashMap<u8, f32>, target: HashMap<u8, f32>) -> f32 {
let mut result = HashMap::new();
for (key, val) in reference.iter() {
if target.contains_key(key) {
// (jtobin) branch is only entered if 'target' contains 'key'
let tval = target.get(key).unwrap();
let sqdiff = (tval - val).powf(2.0);
result.insert(key, sqdiff);
}
}
let size = result.len();
result.iter().fold(0.0, |sum, (_, val)| sum + val / size as f32)
}
fn score(string: &str) -> f32 {
let decoded = FromHex::from_hex(&string).unwrap();
let freq_dist = frequency_distribution(decoded);
mse(freqs_ascii(), freq_dist)
}
pub fn break_single_byte_xor(string: &str) -> (u8, String) {
let bytes: Vec<u8> = FromHex::from_hex(&string).unwrap();
let mut min = ("hi!".to_string(), 0, f32::INFINITY);
for ascii_char in 32..126 {
let mut other_bytes = bytes.clone();
for byte in other_bytes.iter_mut() {
*byte ^= ascii_char;
}
let decoded = String::from_utf8(other_bytes).unwrap();
let encoded = ToHex::to_hex(&decoded.clone());
let result = score(&encoded);
if result < min.2 { min = (decoded, ascii_char, result); }
}
(min.1, min.0)
}
fn main() {
let args = App::new("break_single_byte_xor")
.version("0.1.0")
.about("Break single-byte XOR")
.arg(Arg::with_name("return-byte")
.short("r")
.long("return-key")
.help("return encrypting byte"))
.get_matches();
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer)
.expect("single_byte_xor: bad input");
let return_byte = match args.occurrences_of("return-byte") {
0 => false,
_ => true,
};
let message = break_single_byte_xor(&buffer);
if return_byte {
println!("{} ({})", message.0 as char, message.0);
} else {
println!("{}", message.1);
}
}
|
, (120, 0.001950)
, (121, 0.011330)
, (122, 0.000596)
|
random_line_split
|
main.rs
|
extern crate clap;
extern crate hex;
use clap::{App, Arg};
use self::hex::{FromHex, ToHex};
use std::collections::HashMap;
use std::io::{self, Read};
use std::f32;
use std::u8;
fn tally(vec: Vec<u8>) -> HashMap<u8, u8> {
let mut hashmap = HashMap::new();
for byte in vec {
let count = hashmap.entry(byte).or_insert(0);
*count += 1;
}
hashmap
}
fn normalize(hashmap: HashMap<u8, u8>) -> HashMap<u8, f32> {
let total = hashmap.iter().fold(0.0, |sum, (_, val)| sum + *val as f32);
hashmap.iter()
.map(|(&key, val)| (key, *val as f32 / total))
.collect()
}
fn frequency_distribution(vec: Vec<u8>) -> HashMap<u8, f32> {
let tallied = tally(vec);
normalize(tallied)
}
pub fn freqs_ascii() -> HashMap<u8, f32> {
[ (9, 0.000057)
, (23, 0.000000)
, (32, 0.171662)
, (33, 0.000072)
, (34, 0.002442)
, (35, 0.000179)
, (36, 0.000561)
, (37, 0.000160)
, (38, 0.000226)
, (39, 0.002447)
, (40, 0.002178)
, (41, 0.002233)
, (42, 0.000628)
, (43, 0.000215)
, (44, 0.007384)
, (45, 0.013734)
, (46, 0.015124)
, (47, 0.001549)
, (48, 0.005516)
, (49, 0.004594)
, (50, 0.003322)
, (51, 0.001847)
, (52, 0.001348)
, (53, 0.001663)
, (54, 0.001153)
, (55, 0.001030)
, (56, 0.001054)
, (57, 0.001024)
, (58, 0.004354)
, (59, 0.001214)
, (60, 0.001225)
, (61, 0.000227)
, (62, 0.001242)
, (63, 0.001474)
, (64, 0.000073)
, (65, 0.003132)
, (66, 0.002163)
, (67, 0.003906)
, (68, 0.003151)
, (69, 0.002673)
, (70, 0.001416)
, (71, 0.001876)
, (72, 0.002321)
, (73, 0.003211)
, (74, 0.001726)
, (75, 0.000687)
, (76, 0.001884)
, (77, 0.003529)
, (78, 0.002085)
, (79, 0.001842)
, (80, 0.002614)
, (81, 0.000316)
, (82, 0.002519)
, (83, 0.004003)
, (84, 0.003322)
, (85, 0.000814)
, (86, 0.000892)
, (87, 0.002527)
, (88, 0.000343)
, (89, 0.000304)
, (90, 0.000076)
, (91, 0.000086)
, (92, 0.000016)
, (93, 0.000088)
, (94, 0.000003)
, (95, 0.001159)
, (96, 0.000009)
, (97, 0.051880)
, (98, 0.010195)
, (99, 0.021129)
, (100, 0.025071)
, (101, 0.085771)
, (102, 0.013725)
, (103, 0.015597)
, (104, 0.027444)
, (105, 0.049019)
, (106, 0.000867)
, (107, 0.006753)
, (108, 0.031750)
, (109, 0.016437)
, (110, 0.049701)
, (111, 0.057701)
, (112, 0.015482)
, (113, 0.000747)
, (114, 0.042586)
, (115, 0.043686)
, (116, 0.063700)
, (117, 0.020999)
, (118, 0.008462)
, (119, 0.013034)
, (120, 0.001950)
, (121, 0.011330)
, (122, 0.000596)
, (123, 0.000026)
, (124, 0.000007)
, (125, 0.000026)
, (126, 0.000003)
, (131, 0.000000)
, (149, 0.006410)
, (183, 0.000010)
, (223, 0.000000)
, (226, 0.000000)
, (229, 0.000000)
, (230, 0.000000)
, (237, 0.000000)
].iter().cloned().collect()
}
fn mse(reference: HashMap<u8, f32>, target: HashMap<u8, f32>) -> f32
|
fn score(string: &str) -> f32 {
let decoded = FromHex::from_hex(&string).unwrap();
let freq_dist = frequency_distribution(decoded);
mse(freqs_ascii(), freq_dist)
}
pub fn break_single_byte_xor(string: &str) -> (u8, String) {
let bytes: Vec<u8> = FromHex::from_hex(&string).unwrap();
let mut min = ("hi!".to_string(), 0, f32::INFINITY);
for ascii_char in 32..126 {
let mut other_bytes = bytes.clone();
for byte in other_bytes.iter_mut() {
*byte ^= ascii_char;
}
let decoded = String::from_utf8(other_bytes).unwrap();
let encoded = ToHex::to_hex(&decoded.clone());
let result = score(&encoded);
if result < min.2 { min = (decoded, ascii_char, result); }
}
(min.1, min.0)
}
fn main() {
let args = App::new("break_single_byte_xor")
.version("0.1.0")
.about("Break single-byte XOR")
.arg(Arg::with_name("return-byte")
.short("r")
.long("return-key")
.help("return encrypting byte"))
.get_matches();
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer)
.expect("single_byte_xor: bad input");
let return_byte = match args.occurrences_of("return-byte") {
0 => false,
_ => true,
};
let message = break_single_byte_xor(&buffer);
if return_byte {
println!("{} ({})", message.0 as char, message.0);
} else {
println!("{}", message.1);
}
}
|
{
let mut result = HashMap::new();
for (key, val) in reference.iter() {
if target.contains_key(key) {
// (jtobin) branch is only entered if 'target' contains 'key'
let tval = target.get(key).unwrap();
let sqdiff = (tval - val).powf(2.0);
result.insert(key, sqdiff);
}
}
let size = result.len();
result.iter().fold(0.0, |sum, (_, val)| sum + val / size as f32)
}
|
identifier_body
|
main.rs
|
extern crate clap;
extern crate hex;
use clap::{App, Arg};
use self::hex::{FromHex, ToHex};
use std::collections::HashMap;
use std::io::{self, Read};
use std::f32;
use std::u8;
fn tally(vec: Vec<u8>) -> HashMap<u8, u8> {
let mut hashmap = HashMap::new();
for byte in vec {
let count = hashmap.entry(byte).or_insert(0);
*count += 1;
}
hashmap
}
fn normalize(hashmap: HashMap<u8, u8>) -> HashMap<u8, f32> {
let total = hashmap.iter().fold(0.0, |sum, (_, val)| sum + *val as f32);
hashmap.iter()
.map(|(&key, val)| (key, *val as f32 / total))
.collect()
}
fn frequency_distribution(vec: Vec<u8>) -> HashMap<u8, f32> {
let tallied = tally(vec);
normalize(tallied)
}
pub fn freqs_ascii() -> HashMap<u8, f32> {
[ (9, 0.000057)
, (23, 0.000000)
, (32, 0.171662)
, (33, 0.000072)
, (34, 0.002442)
, (35, 0.000179)
, (36, 0.000561)
, (37, 0.000160)
, (38, 0.000226)
, (39, 0.002447)
, (40, 0.002178)
, (41, 0.002233)
, (42, 0.000628)
, (43, 0.000215)
, (44, 0.007384)
, (45, 0.013734)
, (46, 0.015124)
, (47, 0.001549)
, (48, 0.005516)
, (49, 0.004594)
, (50, 0.003322)
, (51, 0.001847)
, (52, 0.001348)
, (53, 0.001663)
, (54, 0.001153)
, (55, 0.001030)
, (56, 0.001054)
, (57, 0.001024)
, (58, 0.004354)
, (59, 0.001214)
, (60, 0.001225)
, (61, 0.000227)
, (62, 0.001242)
, (63, 0.001474)
, (64, 0.000073)
, (65, 0.003132)
, (66, 0.002163)
, (67, 0.003906)
, (68, 0.003151)
, (69, 0.002673)
, (70, 0.001416)
, (71, 0.001876)
, (72, 0.002321)
, (73, 0.003211)
, (74, 0.001726)
, (75, 0.000687)
, (76, 0.001884)
, (77, 0.003529)
, (78, 0.002085)
, (79, 0.001842)
, (80, 0.002614)
, (81, 0.000316)
, (82, 0.002519)
, (83, 0.004003)
, (84, 0.003322)
, (85, 0.000814)
, (86, 0.000892)
, (87, 0.002527)
, (88, 0.000343)
, (89, 0.000304)
, (90, 0.000076)
, (91, 0.000086)
, (92, 0.000016)
, (93, 0.000088)
, (94, 0.000003)
, (95, 0.001159)
, (96, 0.000009)
, (97, 0.051880)
, (98, 0.010195)
, (99, 0.021129)
, (100, 0.025071)
, (101, 0.085771)
, (102, 0.013725)
, (103, 0.015597)
, (104, 0.027444)
, (105, 0.049019)
, (106, 0.000867)
, (107, 0.006753)
, (108, 0.031750)
, (109, 0.016437)
, (110, 0.049701)
, (111, 0.057701)
, (112, 0.015482)
, (113, 0.000747)
, (114, 0.042586)
, (115, 0.043686)
, (116, 0.063700)
, (117, 0.020999)
, (118, 0.008462)
, (119, 0.013034)
, (120, 0.001950)
, (121, 0.011330)
, (122, 0.000596)
, (123, 0.000026)
, (124, 0.000007)
, (125, 0.000026)
, (126, 0.000003)
, (131, 0.000000)
, (149, 0.006410)
, (183, 0.000010)
, (223, 0.000000)
, (226, 0.000000)
, (229, 0.000000)
, (230, 0.000000)
, (237, 0.000000)
].iter().cloned().collect()
}
fn mse(reference: HashMap<u8, f32>, target: HashMap<u8, f32>) -> f32 {
let mut result = HashMap::new();
for (key, val) in reference.iter() {
if target.contains_key(key) {
// (jtobin) branch is only entered if 'target' contains 'key'
let tval = target.get(key).unwrap();
let sqdiff = (tval - val).powf(2.0);
result.insert(key, sqdiff);
}
}
let size = result.len();
result.iter().fold(0.0, |sum, (_, val)| sum + val / size as f32)
}
fn score(string: &str) -> f32 {
let decoded = FromHex::from_hex(&string).unwrap();
let freq_dist = frequency_distribution(decoded);
mse(freqs_ascii(), freq_dist)
}
pub fn break_single_byte_xor(string: &str) -> (u8, String) {
let bytes: Vec<u8> = FromHex::from_hex(&string).unwrap();
let mut min = ("hi!".to_string(), 0, f32::INFINITY);
for ascii_char in 32..126 {
let mut other_bytes = bytes.clone();
for byte in other_bytes.iter_mut() {
*byte ^= ascii_char;
}
let decoded = String::from_utf8(other_bytes).unwrap();
let encoded = ToHex::to_hex(&decoded.clone());
let result = score(&encoded);
if result < min.2 { min = (decoded, ascii_char, result); }
}
(min.1, min.0)
}
fn main() {
let args = App::new("break_single_byte_xor")
.version("0.1.0")
.about("Break single-byte XOR")
.arg(Arg::with_name("return-byte")
.short("r")
.long("return-key")
.help("return encrypting byte"))
.get_matches();
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer)
.expect("single_byte_xor: bad input");
let return_byte = match args.occurrences_of("return-byte") {
0 => false,
_ => true,
};
let message = break_single_byte_xor(&buffer);
if return_byte {
println!("{} ({})", message.0 as char, message.0);
} else
|
}
|
{
println!("{}", message.1);
}
|
conditional_block
|
main.rs
|
pub mod cpu;
pub mod musashi;
mod ram;
#[macro_use]
extern crate lazy_static;
extern crate itertools;
use itertools::Itertools;
use std::io::Result;
use std::io::prelude::*;
use std::fs::File;
fn
|
() {
let mut cpu = cpu::Core::new_mem(0x40, &[0xc3, 0x00]);
cpu.ophandlers = cpu::ops::instruction_set();
cpu.dar[0] = 0x16;
cpu.dar[1] = 0x26;
cpu.execute1();
musashi::experimental_communication();
println!("Hello, CPU at {}", cpu.pc);
match write_state(&cpu) {
Ok(_) => return (),
Err(e) => panic!(e),
};
}
fn write_state(core: &cpu::Core) -> Result<()> {
let mut buffer = try!(File::create("cpustate.txt"));
let dxs = (0..8).map(|i| format!("D{}:{:08x}", i, core.dar[i])).join(" ");
let axs = (0..8).map(|i| format!("A{}:{:08x}", i, core.dar[i+8])).join(" ");
try!(writeln!(buffer, "PC:{:08x} SP:{:08x} SR:{:08x} FL:{} {} {}", core.pc, core.dar[15], core.status_register(), core.flags(), dxs, axs));
Ok(())
}
|
main
|
identifier_name
|
main.rs
|
pub mod cpu;
pub mod musashi;
mod ram;
#[macro_use]
extern crate lazy_static;
extern crate itertools;
use itertools::Itertools;
use std::io::Result;
use std::io::prelude::*;
use std::fs::File;
fn main()
|
fn write_state(core: &cpu::Core) -> Result<()> {
let mut buffer = try!(File::create("cpustate.txt"));
let dxs = (0..8).map(|i| format!("D{}:{:08x}", i, core.dar[i])).join(" ");
let axs = (0..8).map(|i| format!("A{}:{:08x}", i, core.dar[i+8])).join(" ");
try!(writeln!(buffer, "PC:{:08x} SP:{:08x} SR:{:08x} FL:{} {} {}", core.pc, core.dar[15], core.status_register(), core.flags(), dxs, axs));
Ok(())
}
|
{
let mut cpu = cpu::Core::new_mem(0x40, &[0xc3, 0x00]);
cpu.ophandlers = cpu::ops::instruction_set();
cpu.dar[0] = 0x16;
cpu.dar[1] = 0x26;
cpu.execute1();
musashi::experimental_communication();
println!("Hello, CPU at {}", cpu.pc);
match write_state(&cpu) {
Ok(_) => return (),
Err(e) => panic!(e),
};
}
|
identifier_body
|
main.rs
|
pub mod cpu;
pub mod musashi;
mod ram;
#[macro_use]
extern crate lazy_static;
extern crate itertools;
use itertools::Itertools;
|
use std::io::Result;
use std::io::prelude::*;
use std::fs::File;
fn main() {
let mut cpu = cpu::Core::new_mem(0x40, &[0xc3, 0x00]);
cpu.ophandlers = cpu::ops::instruction_set();
cpu.dar[0] = 0x16;
cpu.dar[1] = 0x26;
cpu.execute1();
musashi::experimental_communication();
println!("Hello, CPU at {}", cpu.pc);
match write_state(&cpu) {
Ok(_) => return (),
Err(e) => panic!(e),
};
}
fn write_state(core: &cpu::Core) -> Result<()> {
let mut buffer = try!(File::create("cpustate.txt"));
let dxs = (0..8).map(|i| format!("D{}:{:08x}", i, core.dar[i])).join(" ");
let axs = (0..8).map(|i| format!("A{}:{:08x}", i, core.dar[i+8])).join(" ");
try!(writeln!(buffer, "PC:{:08x} SP:{:08x} SR:{:08x} FL:{} {} {}", core.pc, core.dar[15], core.status_register(), core.flags(), dxs, axs));
Ok(())
}
|
random_line_split
|
|
errorevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::ErrorEventBinding;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::trace::JSTraceable;
use dom::event::{Event, EventBubbles, EventCancelable};
use js::jsapi::{RootedValue, HandleValue, JSContext};
use js::jsval::JSVal;
use std::cell::Cell;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct ErrorEvent {
event: Event,
message: DOMRefCell<DOMString>,
filename: DOMRefCell<DOMString>,
lineno: Cell<u32>,
colno: Cell<u32>,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
error: MutHeapJSVal,
}
impl ErrorEvent {
fn new_inherited() -> ErrorEvent {
ErrorEvent {
event: Event::new_inherited(),
message: DOMRefCell::new(DOMString::new()),
filename: DOMRefCell::new(DOMString::new()),
lineno: Cell::new(0),
colno: Cell::new(0),
error: MutHeapJSVal::new()
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<ErrorEvent> {
reflect_dom_object(box ErrorEvent::new_inherited(),
global,
ErrorEventBinding::Wrap)
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
message: DOMString,
filename: DOMString,
lineno: u32,
colno: u32,
error: HandleValue) -> Root<ErrorEvent> {
let ev = ErrorEvent::new_uninitialized(global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable);
*ev.message.borrow_mut() = message;
*ev.filename.borrow_mut() = filename;
ev.lineno.set(lineno);
ev.colno.set(colno);
}
ev.error.set(error.get());
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Root<ErrorEvent>>{
let msg = match init.message.as_ref() {
Some(message) => message.clone(),
None => DOMString::new(),
};
let file_name = match init.filename.as_ref() {
Some(filename) => filename.clone(),
None => DOMString::new(),
};
let line_num = init.lineno.unwrap_or(0);
let col_num = init.colno.unwrap_or(0);
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else
|
;
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
let error = RootedValue::new(global.get_cx(), init.error);
let event = ErrorEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
msg, file_name,
line_num, col_num,
error.handle());
Ok(event)
}
}
impl ErrorEventMethods for ErrorEvent {
// https://html.spec.whatwg.org/multipage/#dom-errorevent-lineno
fn Lineno(&self) -> u32 {
self.lineno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-colno
fn Colno(&self) -> u32 {
self.colno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-message
fn Message(&self) -> DOMString {
self.message.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-filename
fn Filename(&self) -> DOMString {
self.filename.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-error
fn Error(&self, _cx: *mut JSContext) -> JSVal {
self.error.get()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
{ EventBubbles::DoesNotBubble }
|
conditional_block
|
errorevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::ErrorEventBinding;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::trace::JSTraceable;
use dom::event::{Event, EventBubbles, EventCancelable};
use js::jsapi::{RootedValue, HandleValue, JSContext};
use js::jsval::JSVal;
use std::cell::Cell;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct ErrorEvent {
event: Event,
message: DOMRefCell<DOMString>,
filename: DOMRefCell<DOMString>,
lineno: Cell<u32>,
colno: Cell<u32>,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
error: MutHeapJSVal,
}
impl ErrorEvent {
fn new_inherited() -> ErrorEvent {
ErrorEvent {
event: Event::new_inherited(),
message: DOMRefCell::new(DOMString::new()),
filename: DOMRefCell::new(DOMString::new()),
lineno: Cell::new(0),
colno: Cell::new(0),
error: MutHeapJSVal::new()
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<ErrorEvent> {
reflect_dom_object(box ErrorEvent::new_inherited(),
global,
ErrorEventBinding::Wrap)
}
pub fn
|
(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
message: DOMString,
filename: DOMString,
lineno: u32,
colno: u32,
error: HandleValue) -> Root<ErrorEvent> {
let ev = ErrorEvent::new_uninitialized(global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable);
*ev.message.borrow_mut() = message;
*ev.filename.borrow_mut() = filename;
ev.lineno.set(lineno);
ev.colno.set(colno);
}
ev.error.set(error.get());
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Root<ErrorEvent>>{
let msg = match init.message.as_ref() {
Some(message) => message.clone(),
None => DOMString::new(),
};
let file_name = match init.filename.as_ref() {
Some(filename) => filename.clone(),
None => DOMString::new(),
};
let line_num = init.lineno.unwrap_or(0);
let col_num = init.colno.unwrap_or(0);
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
let error = RootedValue::new(global.get_cx(), init.error);
let event = ErrorEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
msg, file_name,
line_num, col_num,
error.handle());
Ok(event)
}
}
impl ErrorEventMethods for ErrorEvent {
// https://html.spec.whatwg.org/multipage/#dom-errorevent-lineno
fn Lineno(&self) -> u32 {
self.lineno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-colno
fn Colno(&self) -> u32 {
self.colno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-message
fn Message(&self) -> DOMString {
self.message.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-filename
fn Filename(&self) -> DOMString {
self.filename.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-error
fn Error(&self, _cx: *mut JSContext) -> JSVal {
self.error.get()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
new
|
identifier_name
|
errorevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::ErrorEventBinding;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::trace::JSTraceable;
use dom::event::{Event, EventBubbles, EventCancelable};
use js::jsapi::{RootedValue, HandleValue, JSContext};
use js::jsval::JSVal;
use std::cell::Cell;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct ErrorEvent {
event: Event,
message: DOMRefCell<DOMString>,
filename: DOMRefCell<DOMString>,
lineno: Cell<u32>,
colno: Cell<u32>,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
error: MutHeapJSVal,
}
impl ErrorEvent {
fn new_inherited() -> ErrorEvent {
ErrorEvent {
event: Event::new_inherited(),
message: DOMRefCell::new(DOMString::new()),
filename: DOMRefCell::new(DOMString::new()),
lineno: Cell::new(0),
colno: Cell::new(0),
error: MutHeapJSVal::new()
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<ErrorEvent> {
reflect_dom_object(box ErrorEvent::new_inherited(),
global,
ErrorEventBinding::Wrap)
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
message: DOMString,
filename: DOMString,
lineno: u32,
colno: u32,
error: HandleValue) -> Root<ErrorEvent> {
let ev = ErrorEvent::new_uninitialized(global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable);
*ev.message.borrow_mut() = message;
*ev.filename.borrow_mut() = filename;
ev.lineno.set(lineno);
ev.colno.set(colno);
}
ev.error.set(error.get());
ev
|
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Root<ErrorEvent>>{
let msg = match init.message.as_ref() {
Some(message) => message.clone(),
None => DOMString::new(),
};
let file_name = match init.filename.as_ref() {
Some(filename) => filename.clone(),
None => DOMString::new(),
};
let line_num = init.lineno.unwrap_or(0);
let col_num = init.colno.unwrap_or(0);
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
let error = RootedValue::new(global.get_cx(), init.error);
let event = ErrorEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
msg, file_name,
line_num, col_num,
error.handle());
Ok(event)
}
}
impl ErrorEventMethods for ErrorEvent {
// https://html.spec.whatwg.org/multipage/#dom-errorevent-lineno
fn Lineno(&self) -> u32 {
self.lineno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-colno
fn Colno(&self) -> u32 {
self.colno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-message
fn Message(&self) -> DOMString {
self.message.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-filename
fn Filename(&self) -> DOMString {
self.filename.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-error
fn Error(&self, _cx: *mut JSContext) -> JSVal {
self.error.get()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
}
|
random_line_split
|
errorevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::ErrorEventBinding;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::trace::JSTraceable;
use dom::event::{Event, EventBubbles, EventCancelable};
use js::jsapi::{RootedValue, HandleValue, JSContext};
use js::jsval::JSVal;
use std::cell::Cell;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct ErrorEvent {
event: Event,
message: DOMRefCell<DOMString>,
filename: DOMRefCell<DOMString>,
lineno: Cell<u32>,
colno: Cell<u32>,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
error: MutHeapJSVal,
}
impl ErrorEvent {
fn new_inherited() -> ErrorEvent {
ErrorEvent {
event: Event::new_inherited(),
message: DOMRefCell::new(DOMString::new()),
filename: DOMRefCell::new(DOMString::new()),
lineno: Cell::new(0),
colno: Cell::new(0),
error: MutHeapJSVal::new()
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<ErrorEvent> {
reflect_dom_object(box ErrorEvent::new_inherited(),
global,
ErrorEventBinding::Wrap)
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
message: DOMString,
filename: DOMString,
lineno: u32,
colno: u32,
error: HandleValue) -> Root<ErrorEvent> {
let ev = ErrorEvent::new_uninitialized(global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable);
*ev.message.borrow_mut() = message;
*ev.filename.borrow_mut() = filename;
ev.lineno.set(lineno);
ev.colno.set(colno);
}
ev.error.set(error.get());
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Root<ErrorEvent>>{
let msg = match init.message.as_ref() {
Some(message) => message.clone(),
None => DOMString::new(),
};
let file_name = match init.filename.as_ref() {
Some(filename) => filename.clone(),
None => DOMString::new(),
};
let line_num = init.lineno.unwrap_or(0);
let col_num = init.colno.unwrap_or(0);
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
let error = RootedValue::new(global.get_cx(), init.error);
let event = ErrorEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
msg, file_name,
line_num, col_num,
error.handle());
Ok(event)
}
}
impl ErrorEventMethods for ErrorEvent {
// https://html.spec.whatwg.org/multipage/#dom-errorevent-lineno
fn Lineno(&self) -> u32 {
self.lineno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-colno
fn Colno(&self) -> u32 {
self.colno.get()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-message
fn Message(&self) -> DOMString {
self.message.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-filename
fn Filename(&self) -> DOMString {
self.filename.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-errorevent-error
fn Error(&self, _cx: *mut JSContext) -> JSVal
|
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
{
self.error.get()
}
|
identifier_body
|
config.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use crate::prelude::*;
pub struct Config {
config: serde_yaml::Value,
args: Option<clap::ArgMatches<'static>>,
}
impl Config {
pub fn from_args(args: clap::ArgMatches<'static>, config_flag: Option<&str>) -> Result<Self> {
let mut config = serde_yaml::Value::Null;
if let Some(config_flag) = config_flag {
if let Some(filename) = args.value_of(config_flag) {
config = Self::load_file(filename)?;
}
}
Ok(Self {
config: config,
args: Some(args),
})
}
pub fn from_file(filename: &str) -> Result<Self> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(Self {
config: config,
args: None,
})
}
fn load_file(filename: &str) -> Result<serde_yaml::Value> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(config)
}
pub fn env_key(&self, key: &str) -> String
|
pub fn get_string(&self, key: &str) -> Result<Option<String>> {
let mut default: Option<String> = None;
// First check if an argument was explicitly provided.
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(Some(args.value_of(key).unwrap().into()));
}
// Save the default...
if args.is_present(key) {
default = Some(args.value_of(key).unwrap().into());
}
}
// Ok, no argument provided, check env.
if let Ok(val) = std::env::var(self.env_key(key)) {
return Ok(Some(val));
}
// No argument or environment variable, check the configuration file.
let config_value = match self.find_value(key) {
serde_yaml::Value::String(s) => Some(s.into()),
serde_yaml::Value::Number(n) => Some(n.to_string()),
_ => None,
};
if let Some(value) = config_value {
return Ok(Some(value));
}
// Is there a default value configured with clap?
return Ok(default);
}
pub fn get_strings(&self, key: &str) -> Result<Vec<String>> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
let val = args.values_of(key).unwrap().map(String::from).collect();
return Ok(val);
}
}
match self.find_value(key) {
serde_yaml::Value::Sequence(sequence) => {
let mut vals: Vec<String> = Vec::new();
for item in sequence {
if let Some(v) = item.as_str() {
vals.push(v.to_string());
}
}
return Ok(vals);
}
_ => Ok(Vec::new()),
}
}
pub fn get_u64(&self, key: &str) -> Result<Option<u64>> {
let mut default: Option<u64> = None;
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
if let Some(v) = args.value_of(key) {
let v = v.parse::<u64>()?;
return Ok(Some(v));
}
}
// Store the clap default value...
if let Some(v) = args.value_of(key) {
if let Ok(v) = v.parse::<u64>() {
default = Some(v);
}
}
}
match self.find_value(key) {
serde_yaml::Value::Number(n) => {
let v = n.as_u64().unwrap();
Ok(Some(v))
}
serde_yaml::Value::Null => {
// Return the clap default value.
Ok(default)
}
_ => {
bail!("value not convertable to string")
}
}
}
/// Get a value as a bool, returning false if the key does not exist.
pub fn get_bool(&self, key: &str) -> Result<bool> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(true);
}
}
// If no argument provided, check environment.
if let Ok(val) = std::env::var(self.env_key(key)) {
return match val.to_lowercase().as_ref() {
"true" | "yes" | "1" => Ok(true),
_ => Ok(false),
};
}
if let serde_yaml::Value::Bool(v) = self.find_value(key) {
return Ok(*v);
}
Ok(false)
}
fn find_value(&self, key: &str) -> &serde_yaml::Value {
let val = &self.config[key];
match val {
serde_yaml::Value::Null => {}
_ => return val,
}
let mut value = &self.config;
for part in key.split('.') {
value = &value[part];
}
return value;
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_config() {
let yaml = include_str!("test/server.yaml");
let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
let config = Config {
config: v,
args: None,
};
assert_eq!(
config
.get_string("database.elasticsearch.port")
.unwrap()
.unwrap(),
"9200"
);
assert_eq!(
config
.get_string("database.elasticsearch.url")
.unwrap()
.unwrap(),
"http://10.16.1.10:9200"
);
assert_eq!(config.get_bool("http.tls.enabled").unwrap(), true);
}
}
|
{
let xform = key.replace(".", "_").replace("-", "_");
format!("EVEBOX_{}", xform.to_uppercase())
}
|
identifier_body
|
config.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use crate::prelude::*;
pub struct Config {
config: serde_yaml::Value,
args: Option<clap::ArgMatches<'static>>,
}
impl Config {
pub fn from_args(args: clap::ArgMatches<'static>, config_flag: Option<&str>) -> Result<Self> {
let mut config = serde_yaml::Value::Null;
if let Some(config_flag) = config_flag {
if let Some(filename) = args.value_of(config_flag) {
config = Self::load_file(filename)?;
}
}
Ok(Self {
config: config,
args: Some(args),
})
}
pub fn from_file(filename: &str) -> Result<Self> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(Self {
config: config,
args: None,
})
}
fn load_file(filename: &str) -> Result<serde_yaml::Value> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(config)
}
pub fn env_key(&self, key: &str) -> String {
let xform = key.replace(".", "_").replace("-", "_");
format!("EVEBOX_{}", xform.to_uppercase())
}
pub fn get_string(&self, key: &str) -> Result<Option<String>> {
let mut default: Option<String> = None;
// First check if an argument was explicitly provided.
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(Some(args.value_of(key).unwrap().into()));
}
// Save the default...
if args.is_present(key) {
default = Some(args.value_of(key).unwrap().into());
}
}
// Ok, no argument provided, check env.
if let Ok(val) = std::env::var(self.env_key(key)) {
return Ok(Some(val));
}
// No argument or environment variable, check the configuration file.
let config_value = match self.find_value(key) {
serde_yaml::Value::String(s) => Some(s.into()),
serde_yaml::Value::Number(n) => Some(n.to_string()),
_ => None,
};
if let Some(value) = config_value {
return Ok(Some(value));
}
// Is there a default value configured with clap?
return Ok(default);
}
pub fn get_strings(&self, key: &str) -> Result<Vec<String>> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
let val = args.values_of(key).unwrap().map(String::from).collect();
return Ok(val);
}
}
match self.find_value(key) {
serde_yaml::Value::Sequence(sequence) => {
let mut vals: Vec<String> = Vec::new();
for item in sequence {
if let Some(v) = item.as_str() {
vals.push(v.to_string());
}
}
return Ok(vals);
}
_ => Ok(Vec::new()),
}
}
pub fn get_u64(&self, key: &str) -> Result<Option<u64>> {
let mut default: Option<u64> = None;
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
if let Some(v) = args.value_of(key) {
let v = v.parse::<u64>()?;
return Ok(Some(v));
}
}
// Store the clap default value...
if let Some(v) = args.value_of(key) {
if let Ok(v) = v.parse::<u64>() {
default = Some(v);
}
}
}
match self.find_value(key) {
serde_yaml::Value::Number(n) => {
let v = n.as_u64().unwrap();
Ok(Some(v))
}
serde_yaml::Value::Null => {
// Return the clap default value.
Ok(default)
}
_ => {
bail!("value not convertable to string")
}
}
}
/// Get a value as a bool, returning false if the key does not exist.
pub fn
|
(&self, key: &str) -> Result<bool> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(true);
}
}
// If no argument provided, check environment.
if let Ok(val) = std::env::var(self.env_key(key)) {
return match val.to_lowercase().as_ref() {
"true" | "yes" | "1" => Ok(true),
_ => Ok(false),
};
}
if let serde_yaml::Value::Bool(v) = self.find_value(key) {
return Ok(*v);
}
Ok(false)
}
fn find_value(&self, key: &str) -> &serde_yaml::Value {
let val = &self.config[key];
match val {
serde_yaml::Value::Null => {}
_ => return val,
}
let mut value = &self.config;
for part in key.split('.') {
value = &value[part];
}
return value;
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_config() {
let yaml = include_str!("test/server.yaml");
let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
let config = Config {
config: v,
args: None,
};
assert_eq!(
config
.get_string("database.elasticsearch.port")
.unwrap()
.unwrap(),
"9200"
);
assert_eq!(
config
.get_string("database.elasticsearch.url")
.unwrap()
.unwrap(),
"http://10.16.1.10:9200"
);
assert_eq!(config.get_bool("http.tls.enabled").unwrap(), true);
}
}
|
get_bool
|
identifier_name
|
config.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use crate::prelude::*;
pub struct Config {
config: serde_yaml::Value,
args: Option<clap::ArgMatches<'static>>,
}
impl Config {
pub fn from_args(args: clap::ArgMatches<'static>, config_flag: Option<&str>) -> Result<Self> {
let mut config = serde_yaml::Value::Null;
if let Some(config_flag) = config_flag {
if let Some(filename) = args.value_of(config_flag) {
config = Self::load_file(filename)?;
}
}
Ok(Self {
config: config,
args: Some(args),
})
}
pub fn from_file(filename: &str) -> Result<Self> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(Self {
config: config,
args: None,
})
}
fn load_file(filename: &str) -> Result<serde_yaml::Value> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(config)
}
pub fn env_key(&self, key: &str) -> String {
let xform = key.replace(".", "_").replace("-", "_");
format!("EVEBOX_{}", xform.to_uppercase())
}
pub fn get_string(&self, key: &str) -> Result<Option<String>> {
let mut default: Option<String> = None;
// First check if an argument was explicitly provided.
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(Some(args.value_of(key).unwrap().into()));
}
// Save the default...
if args.is_present(key) {
default = Some(args.value_of(key).unwrap().into());
}
}
// Ok, no argument provided, check env.
if let Ok(val) = std::env::var(self.env_key(key)) {
return Ok(Some(val));
}
// No argument or environment variable, check the configuration file.
let config_value = match self.find_value(key) {
serde_yaml::Value::String(s) => Some(s.into()),
serde_yaml::Value::Number(n) => Some(n.to_string()),
_ => None,
};
if let Some(value) = config_value {
return Ok(Some(value));
}
// Is there a default value configured with clap?
return Ok(default);
}
pub fn get_strings(&self, key: &str) -> Result<Vec<String>> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
let val = args.values_of(key).unwrap().map(String::from).collect();
return Ok(val);
}
}
match self.find_value(key) {
serde_yaml::Value::Sequence(sequence) => {
let mut vals: Vec<String> = Vec::new();
for item in sequence {
if let Some(v) = item.as_str() {
vals.push(v.to_string());
}
}
return Ok(vals);
}
_ => Ok(Vec::new()),
}
}
pub fn get_u64(&self, key: &str) -> Result<Option<u64>> {
let mut default: Option<u64> = None;
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
if let Some(v) = args.value_of(key) {
let v = v.parse::<u64>()?;
return Ok(Some(v));
}
}
// Store the clap default value...
if let Some(v) = args.value_of(key) {
if let Ok(v) = v.parse::<u64>() {
default = Some(v);
}
}
}
match self.find_value(key) {
serde_yaml::Value::Number(n) => {
let v = n.as_u64().unwrap();
Ok(Some(v))
}
serde_yaml::Value::Null => {
|
bail!("value not convertable to string")
}
}
}
/// Get a value as a bool, returning false if the key does not exist.
pub fn get_bool(&self, key: &str) -> Result<bool> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(true);
}
}
// If no argument provided, check environment.
if let Ok(val) = std::env::var(self.env_key(key)) {
return match val.to_lowercase().as_ref() {
"true" | "yes" | "1" => Ok(true),
_ => Ok(false),
};
}
if let serde_yaml::Value::Bool(v) = self.find_value(key) {
return Ok(*v);
}
Ok(false)
}
fn find_value(&self, key: &str) -> &serde_yaml::Value {
let val = &self.config[key];
match val {
serde_yaml::Value::Null => {}
_ => return val,
}
let mut value = &self.config;
for part in key.split('.') {
value = &value[part];
}
return value;
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_config() {
let yaml = include_str!("test/server.yaml");
let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
let config = Config {
config: v,
args: None,
};
assert_eq!(
config
.get_string("database.elasticsearch.port")
.unwrap()
.unwrap(),
"9200"
);
assert_eq!(
config
.get_string("database.elasticsearch.url")
.unwrap()
.unwrap(),
"http://10.16.1.10:9200"
);
assert_eq!(config.get_bool("http.tls.enabled").unwrap(), true);
}
}
|
// Return the clap default value.
Ok(default)
}
_ => {
|
random_line_split
|
config.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use crate::prelude::*;
pub struct Config {
config: serde_yaml::Value,
args: Option<clap::ArgMatches<'static>>,
}
impl Config {
pub fn from_args(args: clap::ArgMatches<'static>, config_flag: Option<&str>) -> Result<Self> {
let mut config = serde_yaml::Value::Null;
if let Some(config_flag) = config_flag {
if let Some(filename) = args.value_of(config_flag) {
config = Self::load_file(filename)?;
}
}
Ok(Self {
config: config,
args: Some(args),
})
}
pub fn from_file(filename: &str) -> Result<Self> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(Self {
config: config,
args: None,
})
}
fn load_file(filename: &str) -> Result<serde_yaml::Value> {
let file = std::fs::File::open(filename)?;
let config: serde_yaml::Value = serde_yaml::from_reader(file)?;
Ok(config)
}
pub fn env_key(&self, key: &str) -> String {
let xform = key.replace(".", "_").replace("-", "_");
format!("EVEBOX_{}", xform.to_uppercase())
}
pub fn get_string(&self, key: &str) -> Result<Option<String>> {
let mut default: Option<String> = None;
// First check if an argument was explicitly provided.
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(Some(args.value_of(key).unwrap().into()));
}
// Save the default...
if args.is_present(key) {
default = Some(args.value_of(key).unwrap().into());
}
}
// Ok, no argument provided, check env.
if let Ok(val) = std::env::var(self.env_key(key))
|
// No argument or environment variable, check the configuration file.
let config_value = match self.find_value(key) {
serde_yaml::Value::String(s) => Some(s.into()),
serde_yaml::Value::Number(n) => Some(n.to_string()),
_ => None,
};
if let Some(value) = config_value {
return Ok(Some(value));
}
// Is there a default value configured with clap?
return Ok(default);
}
pub fn get_strings(&self, key: &str) -> Result<Vec<String>> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
let val = args.values_of(key).unwrap().map(String::from).collect();
return Ok(val);
}
}
match self.find_value(key) {
serde_yaml::Value::Sequence(sequence) => {
let mut vals: Vec<String> = Vec::new();
for item in sequence {
if let Some(v) = item.as_str() {
vals.push(v.to_string());
}
}
return Ok(vals);
}
_ => Ok(Vec::new()),
}
}
pub fn get_u64(&self, key: &str) -> Result<Option<u64>> {
let mut default: Option<u64> = None;
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
if let Some(v) = args.value_of(key) {
let v = v.parse::<u64>()?;
return Ok(Some(v));
}
}
// Store the clap default value...
if let Some(v) = args.value_of(key) {
if let Ok(v) = v.parse::<u64>() {
default = Some(v);
}
}
}
match self.find_value(key) {
serde_yaml::Value::Number(n) => {
let v = n.as_u64().unwrap();
Ok(Some(v))
}
serde_yaml::Value::Null => {
// Return the clap default value.
Ok(default)
}
_ => {
bail!("value not convertable to string")
}
}
}
/// Get a value as a bool, returning false if the key does not exist.
pub fn get_bool(&self, key: &str) -> Result<bool> {
if let Some(args) = &self.args {
if args.occurrences_of(key) > 0 {
return Ok(true);
}
}
// If no argument provided, check environment.
if let Ok(val) = std::env::var(self.env_key(key)) {
return match val.to_lowercase().as_ref() {
"true" | "yes" | "1" => Ok(true),
_ => Ok(false),
};
}
if let serde_yaml::Value::Bool(v) = self.find_value(key) {
return Ok(*v);
}
Ok(false)
}
fn find_value(&self, key: &str) -> &serde_yaml::Value {
let val = &self.config[key];
match val {
serde_yaml::Value::Null => {}
_ => return val,
}
let mut value = &self.config;
for part in key.split('.') {
value = &value[part];
}
return value;
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_config() {
let yaml = include_str!("test/server.yaml");
let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
let config = Config {
config: v,
args: None,
};
assert_eq!(
config
.get_string("database.elasticsearch.port")
.unwrap()
.unwrap(),
"9200"
);
assert_eq!(
config
.get_string("database.elasticsearch.url")
.unwrap()
.unwrap(),
"http://10.16.1.10:9200"
);
assert_eq!(config.get_bool("http.tls.enabled").unwrap(), true);
}
}
|
{
return Ok(Some(val));
}
|
conditional_block
|
path.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Path utilities
use std::path::Path;
use std::path::PathBuf;
#[cfg(target_os = "macos")]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("Library");
home.push(name);
home
}
#[cfg(windows)]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("AppData");
home.push("Roaming");
home.push(name);
home
}
#[cfg(not(any(target_os = "macos", windows)))]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push(format!(".{}", name.to_lowercase()));
home
}
/// Get the specific folder inside a config path.
pub fn config_path_with(name: &str, then: &str) -> PathBuf {
let mut path = config_path(name);
path.push(then);
path
}
/// Default ethereum paths
pub mod ethereum {
use std::path::PathBuf;
/// Default path for ethereum installation on Mac Os
pub fn
|
() -> PathBuf { super::config_path("Ethereum") }
/// Default path for ethereum installation (testnet)
pub fn test() -> PathBuf {
let mut path = default();
path.push("testnet");
path
}
/// Get the specific folder inside default ethereum installation
pub fn with_default(s: &str) -> PathBuf {
let mut path = default();
path.push(s);
path
}
/// Get the specific folder inside default ethereum installation configured for testnet
pub fn with_testnet(s: &str) -> PathBuf {
let mut path = default();
path.push("testnet");
path.push(s);
path
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(unix)]
pub fn restrict_permissions_owner(file_path: &Path, write: bool, executable: bool) -> Result<(), String> {
let perms = ::std::os::unix::fs::PermissionsExt::from_mode(0o400 + write as u32 * 0o200 + executable as u32 * 0o100);
::std::fs::set_permissions(file_path, perms).map_err(|e| format!("{:?}", e))
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(unix))]
pub fn restrict_permissions_owner(_file_path: &Path, _write: bool, _executable: bool) -> Result<(), String> {
//TODO: implement me
Ok(())
}
|
default
|
identifier_name
|
path.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Path utilities
use std::path::Path;
use std::path::PathBuf;
#[cfg(target_os = "macos")]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("Library");
home.push(name);
home
}
#[cfg(windows)]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("AppData");
home.push("Roaming");
home.push(name);
home
}
#[cfg(not(any(target_os = "macos", windows)))]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push(format!(".{}", name.to_lowercase()));
home
}
/// Get the specific folder inside a config path.
pub fn config_path_with(name: &str, then: &str) -> PathBuf {
let mut path = config_path(name);
path.push(then);
path
}
/// Default ethereum paths
pub mod ethereum {
use std::path::PathBuf;
/// Default path for ethereum installation on Mac Os
pub fn default() -> PathBuf
|
/// Default path for ethereum installation (testnet)
pub fn test() -> PathBuf {
let mut path = default();
path.push("testnet");
path
}
/// Get the specific folder inside default ethereum installation
pub fn with_default(s: &str) -> PathBuf {
let mut path = default();
path.push(s);
path
}
/// Get the specific folder inside default ethereum installation configured for testnet
pub fn with_testnet(s: &str) -> PathBuf {
let mut path = default();
path.push("testnet");
path.push(s);
path
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(unix)]
pub fn restrict_permissions_owner(file_path: &Path, write: bool, executable: bool) -> Result<(), String> {
let perms = ::std::os::unix::fs::PermissionsExt::from_mode(0o400 + write as u32 * 0o200 + executable as u32 * 0o100);
::std::fs::set_permissions(file_path, perms).map_err(|e| format!("{:?}", e))
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(unix))]
pub fn restrict_permissions_owner(_file_path: &Path, _write: bool, _executable: bool) -> Result<(), String> {
//TODO: implement me
Ok(())
}
|
{ super::config_path("Ethereum") }
|
identifier_body
|
path.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Path utilities
use std::path::Path;
use std::path::PathBuf;
#[cfg(target_os = "macos")]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("Library");
home.push(name);
home
}
#[cfg(windows)]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("AppData");
home.push("Roaming");
home.push(name);
home
}
#[cfg(not(any(target_os = "macos", windows)))]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push(format!(".{}", name.to_lowercase()));
home
}
/// Get the specific folder inside a config path.
pub fn config_path_with(name: &str, then: &str) -> PathBuf {
let mut path = config_path(name);
path.push(then);
path
}
/// Default ethereum paths
pub mod ethereum {
use std::path::PathBuf;
/// Default path for ethereum installation on Mac Os
pub fn default() -> PathBuf { super::config_path("Ethereum") }
/// Default path for ethereum installation (testnet)
pub fn test() -> PathBuf {
let mut path = default();
path.push("testnet");
path
}
/// Get the specific folder inside default ethereum installation
pub fn with_default(s: &str) -> PathBuf {
let mut path = default();
path.push(s);
path
}
/// Get the specific folder inside default ethereum installation configured for testnet
pub fn with_testnet(s: &str) -> PathBuf {
let mut path = default();
path.push("testnet");
path.push(s);
path
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(unix)]
pub fn restrict_permissions_owner(file_path: &Path, write: bool, executable: bool) -> Result<(), String> {
let perms = ::std::os::unix::fs::PermissionsExt::from_mode(0o400 + write as u32 * 0o200 + executable as u32 * 0o100);
::std::fs::set_permissions(file_path, perms).map_err(|e| format!("{:?}", e))
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(unix))]
|
Ok(())
}
|
pub fn restrict_permissions_owner(_file_path: &Path, _write: bool, _executable: bool) -> Result<(), String> {
//TODO: implement me
|
random_line_split
|
float.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.
#![allow(missing_doc)]
use char;
use collections::Collection;
use fmt;
use iter::{Iterator, range, DoubleEndedIterator};
use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
use num::{Zero, One, cast};
use option::{None, Some};
use result::Ok;
use slice::{ImmutableVector, MutableVector};
use slice;
use str::StrSlice;
/// A flag that specifies whether to use exponential (scientific) notation.
pub enum ExponentFormat {
/// Do not use exponential notation.
ExpNone,
/// Use exponential notation with the exponent having a base of 10 and the
/// exponent sign being `e` or `E`. For example, 1000 would be printed
/// 1e3.
ExpDec,
/// Use exponential notation with the exponent having a base of 2 and the
/// exponent sign being `p` or `P`. For example, 8 would be printed 1p3.
ExpBin,
}
/// The number of digits used for emitting the fractional part of a number, if
/// any.
pub enum SignificantDigits {
/// All calculable digits will be printed.
///
/// Note that bignums or fractions may cause a surprisingly large number
/// of digits to be printed.
DigAll,
/// At most the given number of digits will be printed, truncating any
/// trailing zeroes.
DigMax(uint),
/// Precisely the given number of digits will be printed.
DigExact(uint)
}
/// How to emit the sign of a number.
pub enum SignFormat {
/// No sign will be printed. The exponent sign will also be emitted.
SignNone,
/// `-` will be printed for negative values, but no sign will be emitted
/// for positive numbers.
SignNeg,
/// `+` will be printed for positive values, and `-` will be printed for
/// negative values.
SignAll,
}
static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;
/**
* Converts a number to its string representation as a byte vector.
* This is meant to be a common base implementation for all numeric string
* conversion functions like `to_str()` or `to_str_radix()`.
*
* # Arguments
* - `num` - The number to convert. Accepts any number that
* implements the numeric traits.
* - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation
* is used, then this base is only used for the significand. The exponent
* itself always printed using a base of 10.
* - `negative_zero` - Whether to treat the special value `-0` as
* `-0` or as `+0`.
* - `sign` - How to emit the sign. See `SignFormat`.
* - `digits` - The amount of digits to use for emitting the fractional
* part, if any. See `SignificantDigits`.
* - `exp_format` - Whether or not to use the exponential (scientific) notation.
* See `ExponentFormat`.
* - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if
* exponential notation is desired.
* - `f` - A closure to invoke with the bytes representing the
* float.
*
* # Failure
* - Fails if `radix` < 2 or `radix` > 36.
* - Fails if `radix` > 14 and `exp_format` is `ExpDec` due to conflict
* between digit and exponent sign `'e'`.
* - Fails if `radix` > 25 and `exp_format` is `ExpBin` due to conflict
* between digit and exponent sign `'p'`.
*/
pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
num: T,
radix: uint,
negative_zero: bool,
sign: SignFormat,
digits: SignificantDigits,
exp_format: ExponentFormat,
exp_upper: bool,
f: |&[u8]| -> U
) -> U {
assert!(2 <= radix && radix <= 36);
match exp_format {
ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e'
=> fail!("float_to_str_bytes_common: radix {} incompatible with \
use of 'e' as decimal exponent", radix),
ExpBin if radix >= DIGIT_P_RADIX // binary exponent 'p'
=> fail!("float_to_str_bytes_common: radix {} incompatible with \
use of 'p' as binary exponent", radix),
_ => ()
}
let _0: T = Zero::zero();
let _1: T = One::one();
match num.classify() {
FPNaN => return f("NaN".as_bytes()),
FPInfinite if num > _0 => {
return match sign {
SignAll => return f("+inf".as_bytes()),
_ => return f("inf".as_bytes()),
};
}
FPInfinite if num < _0 => {
return match sign {
SignNone => return f("inf".as_bytes()),
_ => return f("-inf".as_bytes()),
};
}
_ => {}
}
let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
// For an f64 the exponent is in the range of [-1022, 1023] for base 2, so
// we may have up to that many digits. Give ourselves some extra wiggle room
// otherwise as well.
let mut buf = [0u8,..1536];
let mut end = 0;
let radix_gen: T = cast(radix as int).unwrap();
let (num, exp) = match exp_format {
ExpNone => (num, 0i32),
ExpDec | ExpBin if num == _0 => (num, 0i32),
ExpDec | ExpBin => {
let (exp, exp_base) = match exp_format {
ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()),
ExpBin => (num.abs().log2().floor(), cast::<f64, T>(2.0f64).unwrap()),
ExpNone => fail!("unreachable"),
};
(num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap())
}
};
// First emit the non-fractional part, looping at least once to make
// sure at least a `0` gets emitted.
let mut deccum = num.trunc();
loop {
// Calculate the absolute value of each digit instead of only
// doing it once for the whole number because a
// representable negative number doesn't necessary have an
// representable additive inverse of the same type
// (See twos complement). But we assume that for the
// numbers [-35.. 0] we always have [0.. 35].
let current_digit = (deccum % radix_gen).abs();
// Decrease the deccumulator one digit at a time
deccum = deccum / radix_gen;
deccum = deccum.trunc();
let c = char::from_digit(current_digit.to_int().unwrap() as uint, radix);
buf[end] = c.unwrap() as u8;
end += 1;
// No more digits to calculate for the non-fractional part -> break
if deccum == _0 { break; }
}
// If limited digits, calculate one digit more for rounding.
let (limit_digits, digit_count, exact) = match digits {
DigAll => (false, 0u, false),
DigMax(count) => (true, count+1, false),
DigExact(count) => (true, count+1, true)
};
// Decide what sign to put in front
match sign {
SignNeg | SignAll if neg => {
buf[end] = '-' as u8;
end += 1;
}
SignAll => {
buf[end] = '+' as u8;
end += 1;
}
_ => ()
}
buf.mut_slice_to(end).reverse();
// Remember start of the fractional digits.
// Points one beyond end of buf if none get generated,
// or at the '.' otherwise.
let start_fractional_digits = end;
// Now emit the fractional part, if any
deccum = num.fract();
if deccum!= _0 || (limit_digits && exact && digit_count > 0) {
buf[end] = '.' as u8;
end += 1;
let mut dig = 0u;
// calculate new digits while
// - there is no limit and there are digits left
// - or there is a limit, it's not reached yet and
// - it's exact
// - or it's a maximum, and there are still digits left
while (!limit_digits && deccum!= _0)
|| (limit_digits && dig < digit_count && (
exact
|| (!exact && deccum!= _0)
)
) {
// Shift first fractional digit into the integer part
deccum = deccum * radix_gen;
// Calculate the absolute value of each digit.
// See note in first loop.
let current_digit = deccum.trunc().abs();
let c = char::from_digit(current_digit.to_int().unwrap() as uint,
|
// Decrease the deccumulator one fractional digit at a time
deccum = deccum.fract();
dig += 1u;
}
// If digits are limited, and that limit has been reached,
// cut off the one extra digit, and depending on its value
// round the remaining ones.
if limit_digits && dig == digit_count {
let ascii2value = |chr: u8| {
char::to_digit(chr as char, radix).unwrap()
};
let value2ascii = |val: uint| {
char::from_digit(val, radix).unwrap() as u8
};
let extra_digit = ascii2value(buf[end - 1]);
end -= 1;
if extra_digit >= radix / 2 { // -> need to round
let mut i: int = end as int - 1;
loop {
// If reached left end of number, have to
// insert additional digit:
if i < 0
|| buf[i as uint] == '-' as u8
|| buf[i as uint] == '+' as u8 {
for j in range(i as uint + 1, end).rev() {
buf[j + 1] = buf[j];
}
buf[(i + 1) as uint] = value2ascii(1);
end += 1;
break;
}
// Skip the '.'
if buf[i as uint] == '.' as u8 { i -= 1; continue; }
// Either increment the digit,
// or set to 0 if max and carry the 1.
let current_digit = ascii2value(buf[i as uint]);
if current_digit < (radix - 1) {
buf[i as uint] = value2ascii(current_digit+1);
break;
} else {
buf[i as uint] = value2ascii(0);
i -= 1;
}
}
}
}
}
// if number of digits is not exact, remove all trailing '0's up to
// and including the '.'
if!exact {
let buf_max_i = end - 1;
// index to truncate from
let mut i = buf_max_i;
// discover trailing zeros of fractional part
while i > start_fractional_digits && buf[i] == '0' as u8 {
i -= 1;
}
// Only attempt to truncate digits if buf has fractional digits
if i >= start_fractional_digits {
// If buf ends with '.', cut that too.
if buf[i] == '.' as u8 { i -= 1 }
// only resize buf if we actually remove digits
if i < buf_max_i {
end = i + 1;
}
}
} // If exact and trailing '.', just cut that
else {
let max_i = end - 1;
if buf[max_i] == '.' as u8 {
end = max_i;
}
}
match exp_format {
ExpNone => {},
_ => {
buf[end] = match exp_format {
ExpDec if exp_upper => 'E',
ExpDec if!exp_upper => 'e',
ExpBin if exp_upper => 'P',
ExpBin if!exp_upper => 'p',
_ => fail!("unreachable"),
} as u8;
end += 1;
struct Filler<'a> {
buf: &'a mut [u8],
end: &'a mut uint,
}
impl<'a> fmt::FormatWriter for Filler<'a> {
fn write(&mut self, bytes: &[u8]) -> fmt::Result {
slice::bytes::copy_memory(self.buf.mut_slice_from(*self.end),
bytes);
*self.end += bytes.len();
Ok(())
}
}
let mut filler = Filler { buf: buf, end: &mut end };
match sign {
SignNeg => {
let _ = format_args!(|args| {
fmt::write(&mut filler, args)
}, "{:-}", exp);
}
SignNone | SignAll => {
let _ = format_args!(|args| {
fmt::write(&mut filler, args)
}, "{}", exp);
}
}
}
}
f(buf.slice_to(end))
}
|
radix);
buf[end] = c.unwrap() as u8;
end += 1;
|
random_line_split
|
float.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.
#![allow(missing_doc)]
use char;
use collections::Collection;
use fmt;
use iter::{Iterator, range, DoubleEndedIterator};
use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
use num::{Zero, One, cast};
use option::{None, Some};
use result::Ok;
use slice::{ImmutableVector, MutableVector};
use slice;
use str::StrSlice;
/// A flag that specifies whether to use exponential (scientific) notation.
pub enum ExponentFormat {
/// Do not use exponential notation.
ExpNone,
/// Use exponential notation with the exponent having a base of 10 and the
/// exponent sign being `e` or `E`. For example, 1000 would be printed
/// 1e3.
ExpDec,
/// Use exponential notation with the exponent having a base of 2 and the
/// exponent sign being `p` or `P`. For example, 8 would be printed 1p3.
ExpBin,
}
/// The number of digits used for emitting the fractional part of a number, if
/// any.
pub enum SignificantDigits {
/// All calculable digits will be printed.
///
/// Note that bignums or fractions may cause a surprisingly large number
/// of digits to be printed.
DigAll,
/// At most the given number of digits will be printed, truncating any
/// trailing zeroes.
DigMax(uint),
/// Precisely the given number of digits will be printed.
DigExact(uint)
}
/// How to emit the sign of a number.
pub enum SignFormat {
/// No sign will be printed. The exponent sign will also be emitted.
SignNone,
/// `-` will be printed for negative values, but no sign will be emitted
/// for positive numbers.
SignNeg,
/// `+` will be printed for positive values, and `-` will be printed for
/// negative values.
SignAll,
}
static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;
/**
* Converts a number to its string representation as a byte vector.
* This is meant to be a common base implementation for all numeric string
* conversion functions like `to_str()` or `to_str_radix()`.
*
* # Arguments
* - `num` - The number to convert. Accepts any number that
* implements the numeric traits.
* - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation
* is used, then this base is only used for the significand. The exponent
* itself always printed using a base of 10.
* - `negative_zero` - Whether to treat the special value `-0` as
* `-0` or as `+0`.
* - `sign` - How to emit the sign. See `SignFormat`.
* - `digits` - The amount of digits to use for emitting the fractional
* part, if any. See `SignificantDigits`.
* - `exp_format` - Whether or not to use the exponential (scientific) notation.
* See `ExponentFormat`.
* - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if
* exponential notation is desired.
* - `f` - A closure to invoke with the bytes representing the
* float.
*
* # Failure
* - Fails if `radix` < 2 or `radix` > 36.
* - Fails if `radix` > 14 and `exp_format` is `ExpDec` due to conflict
* between digit and exponent sign `'e'`.
* - Fails if `radix` > 25 and `exp_format` is `ExpBin` due to conflict
* between digit and exponent sign `'p'`.
*/
pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
num: T,
radix: uint,
negative_zero: bool,
sign: SignFormat,
digits: SignificantDigits,
exp_format: ExponentFormat,
exp_upper: bool,
f: |&[u8]| -> U
) -> U {
assert!(2 <= radix && radix <= 36);
match exp_format {
ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e'
=> fail!("float_to_str_bytes_common: radix {} incompatible with \
use of 'e' as decimal exponent", radix),
ExpBin if radix >= DIGIT_P_RADIX // binary exponent 'p'
=> fail!("float_to_str_bytes_common: radix {} incompatible with \
use of 'p' as binary exponent", radix),
_ => ()
}
let _0: T = Zero::zero();
let _1: T = One::one();
match num.classify() {
FPNaN => return f("NaN".as_bytes()),
FPInfinite if num > _0 => {
return match sign {
SignAll => return f("+inf".as_bytes()),
_ => return f("inf".as_bytes()),
};
}
FPInfinite if num < _0 => {
return match sign {
SignNone => return f("inf".as_bytes()),
_ => return f("-inf".as_bytes()),
};
}
_ => {}
}
let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
// For an f64 the exponent is in the range of [-1022, 1023] for base 2, so
// we may have up to that many digits. Give ourselves some extra wiggle room
// otherwise as well.
let mut buf = [0u8,..1536];
let mut end = 0;
let radix_gen: T = cast(radix as int).unwrap();
let (num, exp) = match exp_format {
ExpNone => (num, 0i32),
ExpDec | ExpBin if num == _0 => (num, 0i32),
ExpDec | ExpBin => {
let (exp, exp_base) = match exp_format {
ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()),
ExpBin => (num.abs().log2().floor(), cast::<f64, T>(2.0f64).unwrap()),
ExpNone => fail!("unreachable"),
};
(num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap())
}
};
// First emit the non-fractional part, looping at least once to make
// sure at least a `0` gets emitted.
let mut deccum = num.trunc();
loop {
// Calculate the absolute value of each digit instead of only
// doing it once for the whole number because a
// representable negative number doesn't necessary have an
// representable additive inverse of the same type
// (See twos complement). But we assume that for the
// numbers [-35.. 0] we always have [0.. 35].
let current_digit = (deccum % radix_gen).abs();
// Decrease the deccumulator one digit at a time
deccum = deccum / radix_gen;
deccum = deccum.trunc();
let c = char::from_digit(current_digit.to_int().unwrap() as uint, radix);
buf[end] = c.unwrap() as u8;
end += 1;
// No more digits to calculate for the non-fractional part -> break
if deccum == _0 { break; }
}
// If limited digits, calculate one digit more for rounding.
let (limit_digits, digit_count, exact) = match digits {
DigAll => (false, 0u, false),
DigMax(count) => (true, count+1, false),
DigExact(count) => (true, count+1, true)
};
// Decide what sign to put in front
match sign {
SignNeg | SignAll if neg => {
buf[end] = '-' as u8;
end += 1;
}
SignAll => {
buf[end] = '+' as u8;
end += 1;
}
_ => ()
}
buf.mut_slice_to(end).reverse();
// Remember start of the fractional digits.
// Points one beyond end of buf if none get generated,
// or at the '.' otherwise.
let start_fractional_digits = end;
// Now emit the fractional part, if any
deccum = num.fract();
if deccum!= _0 || (limit_digits && exact && digit_count > 0) {
buf[end] = '.' as u8;
end += 1;
let mut dig = 0u;
// calculate new digits while
// - there is no limit and there are digits left
// - or there is a limit, it's not reached yet and
// - it's exact
// - or it's a maximum, and there are still digits left
while (!limit_digits && deccum!= _0)
|| (limit_digits && dig < digit_count && (
exact
|| (!exact && deccum!= _0)
)
) {
// Shift first fractional digit into the integer part
deccum = deccum * radix_gen;
// Calculate the absolute value of each digit.
// See note in first loop.
let current_digit = deccum.trunc().abs();
let c = char::from_digit(current_digit.to_int().unwrap() as uint,
radix);
buf[end] = c.unwrap() as u8;
end += 1;
// Decrease the deccumulator one fractional digit at a time
deccum = deccum.fract();
dig += 1u;
}
// If digits are limited, and that limit has been reached,
// cut off the one extra digit, and depending on its value
// round the remaining ones.
if limit_digits && dig == digit_count {
let ascii2value = |chr: u8| {
char::to_digit(chr as char, radix).unwrap()
};
let value2ascii = |val: uint| {
char::from_digit(val, radix).unwrap() as u8
};
let extra_digit = ascii2value(buf[end - 1]);
end -= 1;
if extra_digit >= radix / 2 { // -> need to round
let mut i: int = end as int - 1;
loop {
// If reached left end of number, have to
// insert additional digit:
if i < 0
|| buf[i as uint] == '-' as u8
|| buf[i as uint] == '+' as u8 {
for j in range(i as uint + 1, end).rev() {
buf[j + 1] = buf[j];
}
buf[(i + 1) as uint] = value2ascii(1);
end += 1;
break;
}
// Skip the '.'
if buf[i as uint] == '.' as u8 { i -= 1; continue; }
// Either increment the digit,
// or set to 0 if max and carry the 1.
let current_digit = ascii2value(buf[i as uint]);
if current_digit < (radix - 1) {
buf[i as uint] = value2ascii(current_digit+1);
break;
} else {
buf[i as uint] = value2ascii(0);
i -= 1;
}
}
}
}
}
// if number of digits is not exact, remove all trailing '0's up to
// and including the '.'
if!exact {
let buf_max_i = end - 1;
// index to truncate from
let mut i = buf_max_i;
// discover trailing zeros of fractional part
while i > start_fractional_digits && buf[i] == '0' as u8 {
i -= 1;
}
// Only attempt to truncate digits if buf has fractional digits
if i >= start_fractional_digits {
// If buf ends with '.', cut that too.
if buf[i] == '.' as u8 { i -= 1 }
// only resize buf if we actually remove digits
if i < buf_max_i {
end = i + 1;
}
}
} // If exact and trailing '.', just cut that
else {
let max_i = end - 1;
if buf[max_i] == '.' as u8 {
end = max_i;
}
}
match exp_format {
ExpNone => {},
_ => {
buf[end] = match exp_format {
ExpDec if exp_upper => 'E',
ExpDec if!exp_upper => 'e',
ExpBin if exp_upper => 'P',
ExpBin if!exp_upper => 'p',
_ => fail!("unreachable"),
} as u8;
end += 1;
struct Filler<'a> {
buf: &'a mut [u8],
end: &'a mut uint,
}
impl<'a> fmt::FormatWriter for Filler<'a> {
fn
|
(&mut self, bytes: &[u8]) -> fmt::Result {
slice::bytes::copy_memory(self.buf.mut_slice_from(*self.end),
bytes);
*self.end += bytes.len();
Ok(())
}
}
let mut filler = Filler { buf: buf, end: &mut end };
match sign {
SignNeg => {
let _ = format_args!(|args| {
fmt::write(&mut filler, args)
}, "{:-}", exp);
}
SignNone | SignAll => {
let _ = format_args!(|args| {
fmt::write(&mut filler, args)
}, "{}", exp);
}
}
}
}
f(buf.slice_to(end))
}
|
write
|
identifier_name
|
float.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.
#![allow(missing_doc)]
use char;
use collections::Collection;
use fmt;
use iter::{Iterator, range, DoubleEndedIterator};
use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
use num::{Zero, One, cast};
use option::{None, Some};
use result::Ok;
use slice::{ImmutableVector, MutableVector};
use slice;
use str::StrSlice;
/// A flag that specifies whether to use exponential (scientific) notation.
pub enum ExponentFormat {
/// Do not use exponential notation.
ExpNone,
/// Use exponential notation with the exponent having a base of 10 and the
/// exponent sign being `e` or `E`. For example, 1000 would be printed
/// 1e3.
ExpDec,
/// Use exponential notation with the exponent having a base of 2 and the
/// exponent sign being `p` or `P`. For example, 8 would be printed 1p3.
ExpBin,
}
/// The number of digits used for emitting the fractional part of a number, if
/// any.
pub enum SignificantDigits {
/// All calculable digits will be printed.
///
/// Note that bignums or fractions may cause a surprisingly large number
/// of digits to be printed.
DigAll,
/// At most the given number of digits will be printed, truncating any
/// trailing zeroes.
DigMax(uint),
/// Precisely the given number of digits will be printed.
DigExact(uint)
}
/// How to emit the sign of a number.
pub enum SignFormat {
/// No sign will be printed. The exponent sign will also be emitted.
SignNone,
/// `-` will be printed for negative values, but no sign will be emitted
/// for positive numbers.
SignNeg,
/// `+` will be printed for positive values, and `-` will be printed for
/// negative values.
SignAll,
}
static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;
/**
* Converts a number to its string representation as a byte vector.
* This is meant to be a common base implementation for all numeric string
* conversion functions like `to_str()` or `to_str_radix()`.
*
* # Arguments
* - `num` - The number to convert. Accepts any number that
* implements the numeric traits.
* - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation
* is used, then this base is only used for the significand. The exponent
* itself always printed using a base of 10.
* - `negative_zero` - Whether to treat the special value `-0` as
* `-0` or as `+0`.
* - `sign` - How to emit the sign. See `SignFormat`.
* - `digits` - The amount of digits to use for emitting the fractional
* part, if any. See `SignificantDigits`.
* - `exp_format` - Whether or not to use the exponential (scientific) notation.
* See `ExponentFormat`.
* - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if
* exponential notation is desired.
* - `f` - A closure to invoke with the bytes representing the
* float.
*
* # Failure
* - Fails if `radix` < 2 or `radix` > 36.
* - Fails if `radix` > 14 and `exp_format` is `ExpDec` due to conflict
* between digit and exponent sign `'e'`.
* - Fails if `radix` > 25 and `exp_format` is `ExpBin` due to conflict
* between digit and exponent sign `'p'`.
*/
pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
num: T,
radix: uint,
negative_zero: bool,
sign: SignFormat,
digits: SignificantDigits,
exp_format: ExponentFormat,
exp_upper: bool,
f: |&[u8]| -> U
) -> U
|
_ => return f("inf".as_bytes()),
};
}
FPInfinite if num < _0 => {
return match sign {
SignNone => return f("inf".as_bytes()),
_ => return f("-inf".as_bytes()),
};
}
_ => {}
}
let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
// For an f64 the exponent is in the range of [-1022, 1023] for base 2, so
// we may have up to that many digits. Give ourselves some extra wiggle room
// otherwise as well.
let mut buf = [0u8,..1536];
let mut end = 0;
let radix_gen: T = cast(radix as int).unwrap();
let (num, exp) = match exp_format {
ExpNone => (num, 0i32),
ExpDec | ExpBin if num == _0 => (num, 0i32),
ExpDec | ExpBin => {
let (exp, exp_base) = match exp_format {
ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()),
ExpBin => (num.abs().log2().floor(), cast::<f64, T>(2.0f64).unwrap()),
ExpNone => fail!("unreachable"),
};
(num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap())
}
};
// First emit the non-fractional part, looping at least once to make
// sure at least a `0` gets emitted.
let mut deccum = num.trunc();
loop {
// Calculate the absolute value of each digit instead of only
// doing it once for the whole number because a
// representable negative number doesn't necessary have an
// representable additive inverse of the same type
// (See twos complement). But we assume that for the
// numbers [-35.. 0] we always have [0.. 35].
let current_digit = (deccum % radix_gen).abs();
// Decrease the deccumulator one digit at a time
deccum = deccum / radix_gen;
deccum = deccum.trunc();
let c = char::from_digit(current_digit.to_int().unwrap() as uint, radix);
buf[end] = c.unwrap() as u8;
end += 1;
// No more digits to calculate for the non-fractional part -> break
if deccum == _0 { break; }
}
// If limited digits, calculate one digit more for rounding.
let (limit_digits, digit_count, exact) = match digits {
DigAll => (false, 0u, false),
DigMax(count) => (true, count+1, false),
DigExact(count) => (true, count+1, true)
};
// Decide what sign to put in front
match sign {
SignNeg | SignAll if neg => {
buf[end] = '-' as u8;
end += 1;
}
SignAll => {
buf[end] = '+' as u8;
end += 1;
}
_ => ()
}
buf.mut_slice_to(end).reverse();
// Remember start of the fractional digits.
// Points one beyond end of buf if none get generated,
// or at the '.' otherwise.
let start_fractional_digits = end;
// Now emit the fractional part, if any
deccum = num.fract();
if deccum!= _0 || (limit_digits && exact && digit_count > 0) {
buf[end] = '.' as u8;
end += 1;
let mut dig = 0u;
// calculate new digits while
// - there is no limit and there are digits left
// - or there is a limit, it's not reached yet and
// - it's exact
// - or it's a maximum, and there are still digits left
while (!limit_digits && deccum!= _0)
|| (limit_digits && dig < digit_count && (
exact
|| (!exact && deccum!= _0)
)
) {
// Shift first fractional digit into the integer part
deccum = deccum * radix_gen;
// Calculate the absolute value of each digit.
// See note in first loop.
let current_digit = deccum.trunc().abs();
let c = char::from_digit(current_digit.to_int().unwrap() as uint,
radix);
buf[end] = c.unwrap() as u8;
end += 1;
// Decrease the deccumulator one fractional digit at a time
deccum = deccum.fract();
dig += 1u;
}
// If digits are limited, and that limit has been reached,
// cut off the one extra digit, and depending on its value
// round the remaining ones.
if limit_digits && dig == digit_count {
let ascii2value = |chr: u8| {
char::to_digit(chr as char, radix).unwrap()
};
let value2ascii = |val: uint| {
char::from_digit(val, radix).unwrap() as u8
};
let extra_digit = ascii2value(buf[end - 1]);
end -= 1;
if extra_digit >= radix / 2 { // -> need to round
let mut i: int = end as int - 1;
loop {
// If reached left end of number, have to
// insert additional digit:
if i < 0
|| buf[i as uint] == '-' as u8
|| buf[i as uint] == '+' as u8 {
for j in range(i as uint + 1, end).rev() {
buf[j + 1] = buf[j];
}
buf[(i + 1) as uint] = value2ascii(1);
end += 1;
break;
}
// Skip the '.'
if buf[i as uint] == '.' as u8 { i -= 1; continue; }
// Either increment the digit,
// or set to 0 if max and carry the 1.
let current_digit = ascii2value(buf[i as uint]);
if current_digit < (radix - 1) {
buf[i as uint] = value2ascii(current_digit+1);
break;
} else {
buf[i as uint] = value2ascii(0);
i -= 1;
}
}
}
}
}
// if number of digits is not exact, remove all trailing '0's up to
// and including the '.'
if!exact {
let buf_max_i = end - 1;
// index to truncate from
let mut i = buf_max_i;
// discover trailing zeros of fractional part
while i > start_fractional_digits && buf[i] == '0' as u8 {
i -= 1;
}
// Only attempt to truncate digits if buf has fractional digits
if i >= start_fractional_digits {
// If buf ends with '.', cut that too.
if buf[i] == '.' as u8 { i -= 1 }
// only resize buf if we actually remove digits
if i < buf_max_i {
end = i + 1;
}
}
} // If exact and trailing '.', just cut that
else {
let max_i = end - 1;
if buf[max_i] == '.' as u8 {
end = max_i;
}
}
match exp_format {
ExpNone => {},
_ => {
buf[end] = match exp_format {
ExpDec if exp_upper => 'E',
ExpDec if!exp_upper => 'e',
ExpBin if exp_upper => 'P',
ExpBin if!exp_upper => 'p',
_ => fail!("unreachable"),
} as u8;
end += 1;
struct Filler<'a> {
buf: &'a mut [u8],
end: &'a mut uint,
}
impl<'a> fmt::FormatWriter for Filler<'a> {
fn write(&mut self, bytes: &[u8]) -> fmt::Result {
slice::bytes::copy_memory(self.buf.mut_slice_from(*self.end),
bytes);
*self.end += bytes.len();
Ok(())
}
}
let mut filler = Filler { buf: buf, end: &mut end };
match sign {
SignNeg => {
let _ = format_args!(|args| {
fmt::write(&mut filler, args)
}, "{:-}", exp);
}
SignNone | SignAll => {
let _ = format_args!(|args| {
fmt::write(&mut filler, args)
}, "{}", exp);
}
}
}
}
f(buf.slice_to(end))
}
|
{
assert!(2 <= radix && radix <= 36);
match exp_format {
ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e'
=> fail!("float_to_str_bytes_common: radix {} incompatible with \
use of 'e' as decimal exponent", radix),
ExpBin if radix >= DIGIT_P_RADIX // binary exponent 'p'
=> fail!("float_to_str_bytes_common: radix {} incompatible with \
use of 'p' as binary exponent", radix),
_ => ()
}
let _0: T = Zero::zero();
let _1: T = One::one();
match num.classify() {
FPNaN => return f("NaN".as_bytes()),
FPInfinite if num > _0 => {
return match sign {
SignAll => return f("+inf".as_bytes()),
|
identifier_body
|
build_schema.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use crate::docblocks::extract_schema_from_docblock_sources;
use common::DiagnosticsResult;
use graphql_syntax::TypeSystemDefinition;
use schema::SDLSchema;
use std::sync::Arc;
pub fn
|
(
compiler_state: &CompilerState,
project_config: &ProjectConfig,
) -> DiagnosticsResult<Arc<SDLSchema>> {
let schema = compiler_state.schema_cache.get(&project_config.name);
match schema {
Some(schema) if!compiler_state.project_has_pending_schema_changes(project_config.name) => {
Ok(schema.clone())
}
_ => {
let mut extensions = vec![];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions.get_sources_with_location());
}
if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) =
compiler_state.extensions.get(&base_project_name)
{
extensions.extend(base_project_extensions.get_sources_with_location());
}
}
let mut schema_sources = Vec::new();
schema_sources.extend(
compiler_state.schemas[&project_config.name]
.get_sources()
.into_iter()
.map(String::as_str),
);
let mut schema =
relay_schema::build_schema_with_extensions(&schema_sources, &extensions)?;
if project_config.feature_flags.enable_relay_resolver_transform {
let mut projects = vec![project_config.name];
projects.extend(project_config.base);
let docblock_sources = projects
.iter()
.map(|name| compiler_state.docblocks.get(name))
.flatten();
for docblocks in docblock_sources {
for (file_path, docblock_sources) in &docblocks.get_all() {
for schema_document in extract_schema_from_docblock_sources(
file_path,
docblock_sources,
&schema,
)? {
for definition in schema_document.definitions {
match definition {
TypeSystemDefinition::ObjectTypeExtension(extension) => schema
.add_object_type_extension(
extension,
schema_document.location.source_location(),
true,
)?,
TypeSystemDefinition::InterfaceTypeExtension(extension) => {
schema.add_interface_type_extension(
extension,
schema_document.location.source_location(),
true,
)?
}
_ => panic!(
"Expected docblocks to only expose object and interface extensions"
),
}
}
}
}
}
}
Ok(Arc::new(schema))
}
}
}
|
build_schema
|
identifier_name
|
build_schema.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use crate::docblocks::extract_schema_from_docblock_sources;
use common::DiagnosticsResult;
use graphql_syntax::TypeSystemDefinition;
use schema::SDLSchema;
use std::sync::Arc;
pub fn build_schema(
compiler_state: &CompilerState,
project_config: &ProjectConfig,
) -> DiagnosticsResult<Arc<SDLSchema>> {
let schema = compiler_state.schema_cache.get(&project_config.name);
match schema {
Some(schema) if!compiler_state.project_has_pending_schema_changes(project_config.name) => {
Ok(schema.clone())
}
_ =>
|
relay_schema::build_schema_with_extensions(&schema_sources, &extensions)?;
if project_config.feature_flags.enable_relay_resolver_transform {
let mut projects = vec![project_config.name];
projects.extend(project_config.base);
let docblock_sources = projects
.iter()
.map(|name| compiler_state.docblocks.get(name))
.flatten();
for docblocks in docblock_sources {
for (file_path, docblock_sources) in &docblocks.get_all() {
for schema_document in extract_schema_from_docblock_sources(
file_path,
docblock_sources,
&schema,
)? {
for definition in schema_document.definitions {
match definition {
TypeSystemDefinition::ObjectTypeExtension(extension) => schema
.add_object_type_extension(
extension,
schema_document.location.source_location(),
true,
)?,
TypeSystemDefinition::InterfaceTypeExtension(extension) => {
schema.add_interface_type_extension(
extension,
schema_document.location.source_location(),
true,
)?
}
_ => panic!(
"Expected docblocks to only expose object and interface extensions"
),
}
}
}
}
}
}
Ok(Arc::new(schema))
}
}
}
|
{
let mut extensions = vec![];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions.get_sources_with_location());
}
if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) =
compiler_state.extensions.get(&base_project_name)
{
extensions.extend(base_project_extensions.get_sources_with_location());
}
}
let mut schema_sources = Vec::new();
schema_sources.extend(
compiler_state.schemas[&project_config.name]
.get_sources()
.into_iter()
.map(String::as_str),
);
let mut schema =
|
conditional_block
|
build_schema.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use crate::docblocks::extract_schema_from_docblock_sources;
use common::DiagnosticsResult;
use graphql_syntax::TypeSystemDefinition;
use schema::SDLSchema;
use std::sync::Arc;
pub fn build_schema(
compiler_state: &CompilerState,
project_config: &ProjectConfig,
) -> DiagnosticsResult<Arc<SDLSchema>>
|
compiler_state.schemas[&project_config.name]
.get_sources()
.into_iter()
.map(String::as_str),
);
let mut schema =
relay_schema::build_schema_with_extensions(&schema_sources, &extensions)?;
if project_config.feature_flags.enable_relay_resolver_transform {
let mut projects = vec![project_config.name];
projects.extend(project_config.base);
let docblock_sources = projects
.iter()
.map(|name| compiler_state.docblocks.get(name))
.flatten();
for docblocks in docblock_sources {
for (file_path, docblock_sources) in &docblocks.get_all() {
for schema_document in extract_schema_from_docblock_sources(
file_path,
docblock_sources,
&schema,
)? {
for definition in schema_document.definitions {
match definition {
TypeSystemDefinition::ObjectTypeExtension(extension) => schema
.add_object_type_extension(
extension,
schema_document.location.source_location(),
true,
)?,
TypeSystemDefinition::InterfaceTypeExtension(extension) => {
schema.add_interface_type_extension(
extension,
schema_document.location.source_location(),
true,
)?
}
_ => panic!(
"Expected docblocks to only expose object and interface extensions"
),
}
}
}
}
}
}
Ok(Arc::new(schema))
}
}
}
|
{
let schema = compiler_state.schema_cache.get(&project_config.name);
match schema {
Some(schema) if !compiler_state.project_has_pending_schema_changes(project_config.name) => {
Ok(schema.clone())
}
_ => {
let mut extensions = vec![];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions.get_sources_with_location());
}
if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) =
compiler_state.extensions.get(&base_project_name)
{
extensions.extend(base_project_extensions.get_sources_with_location());
}
}
let mut schema_sources = Vec::new();
schema_sources.extend(
|
identifier_body
|
build_schema.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use crate::docblocks::extract_schema_from_docblock_sources;
use common::DiagnosticsResult;
use graphql_syntax::TypeSystemDefinition;
use schema::SDLSchema;
use std::sync::Arc;
pub fn build_schema(
compiler_state: &CompilerState,
project_config: &ProjectConfig,
) -> DiagnosticsResult<Arc<SDLSchema>> {
let schema = compiler_state.schema_cache.get(&project_config.name);
match schema {
Some(schema) if!compiler_state.project_has_pending_schema_changes(project_config.name) => {
Ok(schema.clone())
}
_ => {
let mut extensions = vec![];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions.get_sources_with_location());
}
if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) =
compiler_state.extensions.get(&base_project_name)
{
extensions.extend(base_project_extensions.get_sources_with_location());
}
}
let mut schema_sources = Vec::new();
schema_sources.extend(
compiler_state.schemas[&project_config.name]
.get_sources()
.into_iter()
.map(String::as_str),
);
let mut schema =
relay_schema::build_schema_with_extensions(&schema_sources, &extensions)?;
if project_config.feature_flags.enable_relay_resolver_transform {
let mut projects = vec![project_config.name];
projects.extend(project_config.base);
let docblock_sources = projects
.iter()
.map(|name| compiler_state.docblocks.get(name))
.flatten();
for docblocks in docblock_sources {
for (file_path, docblock_sources) in &docblocks.get_all() {
for schema_document in extract_schema_from_docblock_sources(
file_path,
docblock_sources,
&schema,
)? {
for definition in schema_document.definitions {
match definition {
TypeSystemDefinition::ObjectTypeExtension(extension) => schema
.add_object_type_extension(
extension,
schema_document.location.source_location(),
true,
)?,
TypeSystemDefinition::InterfaceTypeExtension(extension) => {
schema.add_interface_type_extension(
extension,
schema_document.location.source_location(),
true,
)?
}
_ => panic!(
"Expected docblocks to only expose object and interface extensions"
),
}
}
|
}
}
}
}
Ok(Arc::new(schema))
}
}
}
|
random_line_split
|
|
foldable.rs
|
use lift::Foldable;
use std::hash::Hash;
use std::collections::linked_list::LinkedList;
use std::collections::vec_deque::VecDeque;
use std::collections::{BinaryHeap, BTreeSet, HashSet};
//Implementation of Foldable for Vec
foldable!(Vec);
//Implementation of Foldable for LinkedList
foldable!(LinkedList);
//Implementation of Foldable for VeqDeque
foldable!(VecDeque);
//Implemenatation of Foldable for BinaryHeap
impl<T: Ord> Foldable for BinaryHeap<T> {
type A = T;
fn
|
<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
//Implementation of Foldable for BTreeSet
impl<T: Ord> Foldable for BTreeSet<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
//Implementation of Foldable for HashSet
impl<T: Hash + Eq> Foldable for HashSet<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
|
foldr
|
identifier_name
|
foldable.rs
|
use lift::Foldable;
use std::hash::Hash;
use std::collections::linked_list::LinkedList;
use std::collections::vec_deque::VecDeque;
use std::collections::{BinaryHeap, BTreeSet, HashSet};
//Implementation of Foldable for Vec
foldable!(Vec);
//Implementation of Foldable for LinkedList
foldable!(LinkedList);
//Implementation of Foldable for VeqDeque
foldable!(VecDeque);
//Implemenatation of Foldable for BinaryHeap
impl<T: Ord> Foldable for BinaryHeap<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
//Implementation of Foldable for BTreeSet
impl<T: Ord> Foldable for BTreeSet<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
|
}
//Implementation of Foldable for HashSet
impl<T: Hash + Eq> Foldable for HashSet<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
|
{
self.iter().fold(accum, f)
}
|
identifier_body
|
foldable.rs
|
use std::collections::linked_list::LinkedList;
use std::collections::vec_deque::VecDeque;
use std::collections::{BinaryHeap, BTreeSet, HashSet};
//Implementation of Foldable for Vec
foldable!(Vec);
//Implementation of Foldable for LinkedList
foldable!(LinkedList);
//Implementation of Foldable for VeqDeque
foldable!(VecDeque);
//Implemenatation of Foldable for BinaryHeap
impl<T: Ord> Foldable for BinaryHeap<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
//Implementation of Foldable for BTreeSet
impl<T: Ord> Foldable for BTreeSet<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
//Implementation of Foldable for HashSet
impl<T: Hash + Eq> Foldable for HashSet<T> {
type A = T;
fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A
where F: FnMut(Self::A, &Self::A) -> Self::A
{
self.iter().fold(accum, f)
}
}
|
use lift::Foldable;
use std::hash::Hash;
|
random_line_split
|
|
assoc-const.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
trait Nat {
const VALUE: usize;
}
struct Zero;
struct Succ<N>(N);
impl Nat for Zero {
const VALUE: usize = 0;
}
impl<N: Nat> Nat for Succ<N> {
const VALUE: usize = N::VALUE + 1;
}
fn main() {
|
let x: [i32; <Succ<Succ<Succ<Succ<Zero>>>>>::VALUE] = [1, 2, 3, 4];
}
|
random_line_split
|
|
assoc-const.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
trait Nat {
const VALUE: usize;
}
struct Zero;
struct Succ<N>(N);
impl Nat for Zero {
const VALUE: usize = 0;
}
impl<N: Nat> Nat for Succ<N> {
const VALUE: usize = N::VALUE + 1;
}
fn
|
() {
let x: [i32; <Succ<Succ<Succ<Succ<Zero>>>>>::VALUE] = [1, 2, 3, 4];
}
|
main
|
identifier_name
|
assoc-const.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
trait Nat {
const VALUE: usize;
}
struct Zero;
struct Succ<N>(N);
impl Nat for Zero {
const VALUE: usize = 0;
}
impl<N: Nat> Nat for Succ<N> {
const VALUE: usize = N::VALUE + 1;
}
fn main()
|
{
let x: [i32; <Succ<Succ<Succ<Succ<Zero>>>>>::VALUE] = [1, 2, 3, 4];
}
|
identifier_body
|
|
response_file.rs
|
use std::io::Read;
use std::iter::Iterator;
use std::option::Option;
use std::collections::VecDeque;
use std::fs::File;
pub struct ParseResponseFiles<I>
where I: Iterator<Item = String>
{
iter: I,
response_file_stack: VecDeque<String>,
}
impl<I> ParseResponseFiles<I>
where I: Iterator<Item = String>
{
fn next_from_iter(&mut self) -> Option<I::Item>
|
fn next_from_stack(&mut self) -> Option<I::Item> {
self.response_file_stack.pop_front()
}
}
impl<I> Iterator for ParseResponseFiles<I>
where I: Iterator<Item = String>
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
if self.response_file_stack.is_empty() {
self.next_from_iter()
} else {
self.next_from_stack()
}
}
}
pub trait ExtendWithResponseFile: Iterator {
fn extend_with_response_file(self) -> ParseResponseFiles<Self>
where Self: Iterator<Item = String> + Sized
{
ParseResponseFiles {
iter: self,
response_file_stack: VecDeque::new(),
}
}
}
impl<I> ExtendWithResponseFile for I where I: Iterator {}
#[cfg(test)]
mod tests {
use tempdir::TempDir;
use std::io::{Result, Write};
use std::fs::File;
use super::ExtendWithResponseFile;
fn write_response_file(content: &String) -> Result<(String, TempDir)> {
let tmp_dir = try!(TempDir::new("cpp-codegen"));
let response_file_path = tmp_dir.path().join("interface.rsp");
let mut response_file = try!(File::create(&response_file_path));
try!(response_file.write(content.as_bytes()));
Ok((response_file_path.to_string_lossy().into_owned().to_string(), tmp_dir))
}
#[test]
fn should_leave_sequence_without_file_unaltered() {
let s = vec!["-DFOO", "-DBAR", "-WBAZ"];
assert_eq!(s.clone(),
s.into_iter().map(String::from).extend_with_response_file().collect::<Vec<_>>());
}
#[test]
fn should_read_single_file() {
let (path, _dir) = write_response_file(&"-x;c++;-std=c++14;-DFLAG".to_string()).unwrap();
let s = vec!["-x", "c++", "-std=c++14", "-DFLAG"];
let args = vec!["@".to_string() + &path];
assert_eq!(s.clone(),
args.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>());
}
#[test]
fn should_read_multiple_files_with_intermixed_args() {
let (path1, _dir1) = write_response_file(&"-x;c++".to_string()).unwrap();
let (path2, _dir2) = write_response_file(&"-DFOO;-DBAR".to_string()).unwrap();
let args = vec!["-DPRE".to_string(),
"@".to_string() + &path1,
"-DMID1".to_string(),
"-DMID2".to_string(),
"@".to_string() + &path2,
"-DPOST".to_string()];
let s = vec!["-DPRE".to_string(),
"-x".to_string(),
"c++".to_string(),
"-DMID1".to_string(),
"-DMID2".to_string(),
"-DFOO".to_string(),
"-DBAR".to_string(),
"-DPOST".to_string()];
assert_eq!(s.clone(), args.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>())
}
}
|
{
match self.iter.next() {
None => None,
Some(item) => {
if item.starts_with("@") {
let mut f = File::open(&item[1..]).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).unwrap();
self.response_file_stack = s.split(";").map(String::from).collect();
println!("read from response file: {:?}", self.response_file_stack);
self.response_file_stack.pop_front()
} else {
Some(item)
}
}
}
}
|
identifier_body
|
response_file.rs
|
use std::io::Read;
use std::iter::Iterator;
use std::option::Option;
use std::collections::VecDeque;
use std::fs::File;
pub struct ParseResponseFiles<I>
where I: Iterator<Item = String>
{
iter: I,
response_file_stack: VecDeque<String>,
}
impl<I> ParseResponseFiles<I>
where I: Iterator<Item = String>
{
fn next_from_iter(&mut self) -> Option<I::Item> {
match self.iter.next() {
None => None,
Some(item) => {
if item.starts_with("@") {
let mut f = File::open(&item[1..]).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).unwrap();
self.response_file_stack = s.split(";").map(String::from).collect();
println!("read from response file: {:?}", self.response_file_stack);
self.response_file_stack.pop_front()
} else {
Some(item)
}
}
}
}
fn next_from_stack(&mut self) -> Option<I::Item> {
self.response_file_stack.pop_front()
}
}
impl<I> Iterator for ParseResponseFiles<I>
where I: Iterator<Item = String>
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
if self.response_file_stack.is_empty() {
self.next_from_iter()
} else {
self.next_from_stack()
}
}
}
pub trait ExtendWithResponseFile: Iterator {
fn extend_with_response_file(self) -> ParseResponseFiles<Self>
where Self: Iterator<Item = String> + Sized
{
ParseResponseFiles {
iter: self,
response_file_stack: VecDeque::new(),
}
}
}
impl<I> ExtendWithResponseFile for I where I: Iterator {}
#[cfg(test)]
mod tests {
use tempdir::TempDir;
use std::io::{Result, Write};
use std::fs::File;
use super::ExtendWithResponseFile;
fn write_response_file(content: &String) -> Result<(String, TempDir)> {
let tmp_dir = try!(TempDir::new("cpp-codegen"));
let response_file_path = tmp_dir.path().join("interface.rsp");
let mut response_file = try!(File::create(&response_file_path));
try!(response_file.write(content.as_bytes()));
Ok((response_file_path.to_string_lossy().into_owned().to_string(), tmp_dir))
}
#[test]
fn should_leave_sequence_without_file_unaltered() {
let s = vec!["-DFOO", "-DBAR", "-WBAZ"];
assert_eq!(s.clone(),
s.into_iter().map(String::from).extend_with_response_file().collect::<Vec<_>>());
}
#[test]
fn should_read_single_file() {
let (path, _dir) = write_response_file(&"-x;c++;-std=c++14;-DFLAG".to_string()).unwrap();
let s = vec!["-x", "c++", "-std=c++14", "-DFLAG"];
let args = vec!["@".to_string() + &path];
assert_eq!(s.clone(),
args.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>());
}
#[test]
fn should_read_multiple_files_with_intermixed_args() {
let (path1, _dir1) = write_response_file(&"-x;c++".to_string()).unwrap();
let (path2, _dir2) = write_response_file(&"-DFOO;-DBAR".to_string()).unwrap();
let args = vec!["-DPRE".to_string(),
"@".to_string() + &path1,
"-DMID1".to_string(),
"-DMID2".to_string(),
"@".to_string() + &path2,
"-DPOST".to_string()];
let s = vec!["-DPRE".to_string(),
"-x".to_string(),
|
"-DBAR".to_string(),
"-DPOST".to_string()];
assert_eq!(s.clone(), args.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>())
}
}
|
"c++".to_string(),
"-DMID1".to_string(),
"-DMID2".to_string(),
"-DFOO".to_string(),
|
random_line_split
|
response_file.rs
|
use std::io::Read;
use std::iter::Iterator;
use std::option::Option;
use std::collections::VecDeque;
use std::fs::File;
pub struct ParseResponseFiles<I>
where I: Iterator<Item = String>
{
iter: I,
response_file_stack: VecDeque<String>,
}
impl<I> ParseResponseFiles<I>
where I: Iterator<Item = String>
{
fn next_from_iter(&mut self) -> Option<I::Item> {
match self.iter.next() {
None => None,
Some(item) => {
if item.starts_with("@") {
let mut f = File::open(&item[1..]).unwrap();
let mut s = String::new();
f.read_to_string(&mut s).unwrap();
self.response_file_stack = s.split(";").map(String::from).collect();
println!("read from response file: {:?}", self.response_file_stack);
self.response_file_stack.pop_front()
} else {
Some(item)
}
}
}
}
fn next_from_stack(&mut self) -> Option<I::Item> {
self.response_file_stack.pop_front()
}
}
impl<I> Iterator for ParseResponseFiles<I>
where I: Iterator<Item = String>
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
if self.response_file_stack.is_empty() {
self.next_from_iter()
} else {
self.next_from_stack()
}
}
}
pub trait ExtendWithResponseFile: Iterator {
fn extend_with_response_file(self) -> ParseResponseFiles<Self>
where Self: Iterator<Item = String> + Sized
{
ParseResponseFiles {
iter: self,
response_file_stack: VecDeque::new(),
}
}
}
impl<I> ExtendWithResponseFile for I where I: Iterator {}
#[cfg(test)]
mod tests {
use tempdir::TempDir;
use std::io::{Result, Write};
use std::fs::File;
use super::ExtendWithResponseFile;
fn
|
(content: &String) -> Result<(String, TempDir)> {
let tmp_dir = try!(TempDir::new("cpp-codegen"));
let response_file_path = tmp_dir.path().join("interface.rsp");
let mut response_file = try!(File::create(&response_file_path));
try!(response_file.write(content.as_bytes()));
Ok((response_file_path.to_string_lossy().into_owned().to_string(), tmp_dir))
}
#[test]
fn should_leave_sequence_without_file_unaltered() {
let s = vec!["-DFOO", "-DBAR", "-WBAZ"];
assert_eq!(s.clone(),
s.into_iter().map(String::from).extend_with_response_file().collect::<Vec<_>>());
}
#[test]
fn should_read_single_file() {
let (path, _dir) = write_response_file(&"-x;c++;-std=c++14;-DFLAG".to_string()).unwrap();
let s = vec!["-x", "c++", "-std=c++14", "-DFLAG"];
let args = vec!["@".to_string() + &path];
assert_eq!(s.clone(),
args.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>());
}
#[test]
fn should_read_multiple_files_with_intermixed_args() {
let (path1, _dir1) = write_response_file(&"-x;c++".to_string()).unwrap();
let (path2, _dir2) = write_response_file(&"-DFOO;-DBAR".to_string()).unwrap();
let args = vec!["-DPRE".to_string(),
"@".to_string() + &path1,
"-DMID1".to_string(),
"-DMID2".to_string(),
"@".to_string() + &path2,
"-DPOST".to_string()];
let s = vec!["-DPRE".to_string(),
"-x".to_string(),
"c++".to_string(),
"-DMID1".to_string(),
"-DMID2".to_string(),
"-DFOO".to_string(),
"-DBAR".to_string(),
"-DPOST".to_string()];
assert_eq!(s.clone(), args.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>())
}
}
|
write_response_file
|
identifier_name
|
main.rs
|
extern crate chan_signal;
#[macro_use]
extern crate clap;
extern crate daemonize;
extern crate env_logger;
extern crate fuse;
extern crate libc;
#[macro_use]
extern crate log;
extern crate syslog;
extern crate time;
use std::env;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::io;
use std::path::Path;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::thread;
use chan_signal::Signal;
use clap::{App, Arg};
use daemonize::{Daemonize};
use env_logger::LogBuilder;
use log::LogRecord;
use syslog::{Facility,Severity};
mod pcatfs;
mod catfs;
mod flags;
mod evicter;
use catfs::error;
use catfs::flags::{DiskSpace, FlagStorage};
use catfs::rlibc;
fn main()
|
static mut SYSLOG: bool = false;
static mut SYSLOGGER: Option<Box<syslog::Logger>> = None;
fn main_internal() -> error::Result<()> {
let format = |record: &LogRecord| {
let t = time::now();
let syslog: bool;
unsafe {
syslog = SYSLOG;
}
if!syslog {
format!(
"{} {:5} - {}",
time::strftime("%Y-%m-%d %H:%M:%S", &t).unwrap(),
record.level(),
record.args()
)
} else {
unsafe {
if let Some(ref logger) = SYSLOGGER {
let level = match record.level() {
log::LogLevel::Trace => Severity::LOG_DEBUG,
log::LogLevel::Debug => Severity::LOG_DEBUG,
log::LogLevel::Info => Severity::LOG_INFO,
log::LogLevel::Warn => Severity::LOG_WARNING,
log::LogLevel::Error => Severity::LOG_ERR,
};
let msg = format!("{}", record.args());
for line in msg.split('\n') {
// ignore error if we can't log, not much we can do anyway
let _ = logger.send_3164(level, line);
}
}
}
format!("\u{08}")
}
};
let mut builder = LogBuilder::new();
builder.format(format);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
} else {
// default to info
builder.parse("info");
}
builder.init().unwrap();
let mut flags: FlagStorage = Default::default();
let mut test = false;
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(OsString::from("atomic_o_trunc"));
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(
OsString::from("default_permissions"),
);
let app = App::new("catfs")
.about("Cache Anything FileSystem")
.version(crate_version!());
{
fn diskspace_validator(s: String) -> Result<(), String> {
DiskSpace::from_str(&s).map(|_| ()).map_err(
|e| e.to_str().to_owned(),
)
}
fn path_validator(s: String) -> Result<(), String> {
Path::new(&s)
.canonicalize()
.map_err(|e| e.to_string().to_owned())
.and_then(|p| if p.is_dir() {
Ok(())
} else {
Err("is not a directory".to_owned())
})
}
let mut args = [
flags::Flag {
arg: Arg::with_name("space")
.long("free")
.takes_value(true)
.help(
"Ensure filesystem has at least this much free space. (ex: 9.5%, 10G)",
)
.validator(diskspace_validator),
value: &mut flags.free_space,
},
flags::Flag {
arg: Arg::with_name("foreground").short("f").help(
"Run catfs in foreground.",
),
value: &mut flags.foreground,
},
flags::Flag{
arg: Arg::with_name("uid")
.long("uid")
.takes_value(true)
.help("Run as this uid"),
value: &mut flags.uid,
},
flags::Flag{
arg: Arg::with_name("gid")
.long("gid")
.takes_value(true)
.help("Run as this gid"),
value: &mut flags.gid,
},
flags::Flag {
arg: Arg::with_name("option")
.short("o")
.takes_value(true)
.multiple(true)
.help("Additional system-specific mount options. Be careful!"),
value: &mut flags.mount_options,
},
flags::Flag {
arg: Arg::with_name("test").long("test").help(
"Exit after parsing arguments",
),
value: &mut test,
},
flags::Flag {
arg: Arg::with_name("from")
.index(1)
.required(true)
.help("Cache files from this directory.")
.validator(path_validator),
value: &mut flags.cat_from,
},
flags::Flag {
arg: Arg::with_name("to")
.index(2)
.required(true)
.help("Cache files to this directory.")
.validator(path_validator),
value: &mut flags.cat_to,
},
flags::Flag {
arg: Arg::with_name("mountpoint")
.index(3)
.required(true)
.help("Expose the mount point at this directory.")
.validator(path_validator),
value: &mut flags.mount_point,
},
];
flags::parse_options(app, &mut args);
}
if test {
return Ok(());
}
if flags.gid!= 0 {
rlibc::setgid(flags.gid)?;
}
if flags.uid!= 0 {
rlibc::setuid(flags.uid)?;
}
if!flags.foreground {
let daemonize = Daemonize::new()
.working_directory(env::current_dir()?.as_path())
;
match daemonize.start() {
Ok(_) => {
if let Ok(mut logger) = syslog::unix(Facility::LOG_USER) {
unsafe {
logger.set_process_name("catfs".to_string());
logger.set_process_id(libc::getpid());
SYSLOGGER = Some(logger);
SYSLOG = true;
}
}
},
Err(e) => error!("unable to daemonize: {}", e),
}
}
let signal = chan_signal::notify(&[Signal::INT, Signal::TERM]);
let path_from = Path::new(&flags.cat_from).canonicalize()?;
let path_to = Path::new(&flags.cat_to).canonicalize()?;
let fs = catfs::CatFS::new(&path_from, &path_to)?;
let fs = pcatfs::PCatFS::new(fs);
let cache_dir = fs.get_cache_dir()?;
let mut options: Vec<&OsStr> = Vec::new();
for i in 0..flags.mount_options.len() {
options.push(&flags.mount_options[i]);
}
debug!("options are {:?}", flags.mount_options);
{
let mut session = fuse::Session::new(fs, Path::new(&flags.mount_point), &options)?;
let need_unmount = Arc::new(Mutex::new(true));
let need_unmount2 = need_unmount.clone();
thread::spawn(move || {
if let Err(e) = session.run() {
error!("session.run() = {}", e);
}
info!("{:?} unmounted", session.mountpoint());
let mut need_unmount = need_unmount2.lock().unwrap();
*need_unmount = false;
unsafe { libc::kill(libc::getpid(), libc::SIGTERM) };
});
let mut ev = evicter::Evicter::new(cache_dir, &flags.free_space);
ev.run();
// unmount after we get signaled becausep session will go out of scope
let s = signal.recv().unwrap();
info!(
"Received {:?}, attempting to unmount {:?}",
s,
flags.mount_point
);
let need_unmount = need_unmount.lock().unwrap();
if *need_unmount {
unmount(Path::new(&flags.mount_point))?;
}
}
rlibc::close(cache_dir)?;
return Ok(());
}
use libc::{c_char, c_int};
use std::ffi::{CString, CStr};
/// Unmount an arbitrary mount point
pub fn unmount(mountpoint: &Path) -> io::Result<()> {
// fuse_unmount_compat22 unfortunately doesn't return a status. Additionally,
// it attempts to call realpath, which in turn calls into the filesystem. So
// if the filesystem returns an error, the unmount does not take place, with
// no indication of the error available to the caller. So we call unmount
// directly, which is what osxfuse does anyway, since we already converted
// to the real path when we first mounted.
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd"))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
unsafe { libc::unmount(mnt.as_ptr(), 0) }
}
#[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd")))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
use std::io::ErrorKind::PermissionDenied;
let rc = unsafe { libc::umount(mnt.as_ptr()) };
if rc < 0 && io::Error::last_os_error().kind() == PermissionDenied {
// Linux always returns EPERM for non-root users. We have to let the
// library go through the setuid-root "fusermount -u" to unmount.
unsafe {
fuse_unmount_compat22(mnt.as_ptr());
}
0
} else {
rc
}
}
let mnt = CString::new(mountpoint.as_os_str().as_bytes())?;
let rc = libc_umount(&mnt);
if rc < 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
extern "system" {
pub fn fuse_unmount_compat22(mountpoint: *const c_char);
}
|
{
if let Err(e) = main_internal() {
error!("Cannot mount: {}", e);
std::process::exit(1);
}
}
|
identifier_body
|
main.rs
|
extern crate chan_signal;
#[macro_use]
extern crate clap;
extern crate daemonize;
extern crate env_logger;
extern crate fuse;
extern crate libc;
#[macro_use]
extern crate log;
extern crate syslog;
extern crate time;
use std::env;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::io;
use std::path::Path;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::thread;
use chan_signal::Signal;
use clap::{App, Arg};
use daemonize::{Daemonize};
use env_logger::LogBuilder;
use log::LogRecord;
use syslog::{Facility,Severity};
mod pcatfs;
mod catfs;
mod flags;
mod evicter;
use catfs::error;
use catfs::flags::{DiskSpace, FlagStorage};
use catfs::rlibc;
fn
|
() {
if let Err(e) = main_internal() {
error!("Cannot mount: {}", e);
std::process::exit(1);
}
}
static mut SYSLOG: bool = false;
static mut SYSLOGGER: Option<Box<syslog::Logger>> = None;
fn main_internal() -> error::Result<()> {
let format = |record: &LogRecord| {
let t = time::now();
let syslog: bool;
unsafe {
syslog = SYSLOG;
}
if!syslog {
format!(
"{} {:5} - {}",
time::strftime("%Y-%m-%d %H:%M:%S", &t).unwrap(),
record.level(),
record.args()
)
} else {
unsafe {
if let Some(ref logger) = SYSLOGGER {
let level = match record.level() {
log::LogLevel::Trace => Severity::LOG_DEBUG,
log::LogLevel::Debug => Severity::LOG_DEBUG,
log::LogLevel::Info => Severity::LOG_INFO,
log::LogLevel::Warn => Severity::LOG_WARNING,
log::LogLevel::Error => Severity::LOG_ERR,
};
let msg = format!("{}", record.args());
for line in msg.split('\n') {
// ignore error if we can't log, not much we can do anyway
let _ = logger.send_3164(level, line);
}
}
}
format!("\u{08}")
}
};
let mut builder = LogBuilder::new();
builder.format(format);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
} else {
// default to info
builder.parse("info");
}
builder.init().unwrap();
let mut flags: FlagStorage = Default::default();
let mut test = false;
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(OsString::from("atomic_o_trunc"));
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(
OsString::from("default_permissions"),
);
let app = App::new("catfs")
.about("Cache Anything FileSystem")
.version(crate_version!());
{
fn diskspace_validator(s: String) -> Result<(), String> {
DiskSpace::from_str(&s).map(|_| ()).map_err(
|e| e.to_str().to_owned(),
)
}
fn path_validator(s: String) -> Result<(), String> {
Path::new(&s)
.canonicalize()
.map_err(|e| e.to_string().to_owned())
.and_then(|p| if p.is_dir() {
Ok(())
} else {
Err("is not a directory".to_owned())
})
}
let mut args = [
flags::Flag {
arg: Arg::with_name("space")
.long("free")
.takes_value(true)
.help(
"Ensure filesystem has at least this much free space. (ex: 9.5%, 10G)",
)
.validator(diskspace_validator),
value: &mut flags.free_space,
},
flags::Flag {
arg: Arg::with_name("foreground").short("f").help(
"Run catfs in foreground.",
),
value: &mut flags.foreground,
},
flags::Flag{
arg: Arg::with_name("uid")
.long("uid")
.takes_value(true)
.help("Run as this uid"),
value: &mut flags.uid,
},
flags::Flag{
arg: Arg::with_name("gid")
.long("gid")
.takes_value(true)
.help("Run as this gid"),
value: &mut flags.gid,
},
flags::Flag {
arg: Arg::with_name("option")
.short("o")
.takes_value(true)
.multiple(true)
.help("Additional system-specific mount options. Be careful!"),
value: &mut flags.mount_options,
},
flags::Flag {
arg: Arg::with_name("test").long("test").help(
"Exit after parsing arguments",
),
value: &mut test,
},
flags::Flag {
arg: Arg::with_name("from")
.index(1)
.required(true)
.help("Cache files from this directory.")
.validator(path_validator),
value: &mut flags.cat_from,
},
flags::Flag {
arg: Arg::with_name("to")
.index(2)
.required(true)
.help("Cache files to this directory.")
.validator(path_validator),
value: &mut flags.cat_to,
},
flags::Flag {
arg: Arg::with_name("mountpoint")
.index(3)
.required(true)
.help("Expose the mount point at this directory.")
.validator(path_validator),
value: &mut flags.mount_point,
},
];
flags::parse_options(app, &mut args);
}
if test {
return Ok(());
}
if flags.gid!= 0 {
rlibc::setgid(flags.gid)?;
}
if flags.uid!= 0 {
rlibc::setuid(flags.uid)?;
}
if!flags.foreground {
let daemonize = Daemonize::new()
.working_directory(env::current_dir()?.as_path())
;
match daemonize.start() {
Ok(_) => {
if let Ok(mut logger) = syslog::unix(Facility::LOG_USER) {
unsafe {
logger.set_process_name("catfs".to_string());
logger.set_process_id(libc::getpid());
SYSLOGGER = Some(logger);
SYSLOG = true;
}
}
},
Err(e) => error!("unable to daemonize: {}", e),
}
}
let signal = chan_signal::notify(&[Signal::INT, Signal::TERM]);
let path_from = Path::new(&flags.cat_from).canonicalize()?;
let path_to = Path::new(&flags.cat_to).canonicalize()?;
let fs = catfs::CatFS::new(&path_from, &path_to)?;
let fs = pcatfs::PCatFS::new(fs);
let cache_dir = fs.get_cache_dir()?;
let mut options: Vec<&OsStr> = Vec::new();
for i in 0..flags.mount_options.len() {
options.push(&flags.mount_options[i]);
}
debug!("options are {:?}", flags.mount_options);
{
let mut session = fuse::Session::new(fs, Path::new(&flags.mount_point), &options)?;
let need_unmount = Arc::new(Mutex::new(true));
let need_unmount2 = need_unmount.clone();
thread::spawn(move || {
if let Err(e) = session.run() {
error!("session.run() = {}", e);
}
info!("{:?} unmounted", session.mountpoint());
let mut need_unmount = need_unmount2.lock().unwrap();
*need_unmount = false;
unsafe { libc::kill(libc::getpid(), libc::SIGTERM) };
});
let mut ev = evicter::Evicter::new(cache_dir, &flags.free_space);
ev.run();
// unmount after we get signaled becausep session will go out of scope
let s = signal.recv().unwrap();
info!(
"Received {:?}, attempting to unmount {:?}",
s,
flags.mount_point
);
let need_unmount = need_unmount.lock().unwrap();
if *need_unmount {
unmount(Path::new(&flags.mount_point))?;
}
}
rlibc::close(cache_dir)?;
return Ok(());
}
use libc::{c_char, c_int};
use std::ffi::{CString, CStr};
/// Unmount an arbitrary mount point
pub fn unmount(mountpoint: &Path) -> io::Result<()> {
// fuse_unmount_compat22 unfortunately doesn't return a status. Additionally,
// it attempts to call realpath, which in turn calls into the filesystem. So
// if the filesystem returns an error, the unmount does not take place, with
// no indication of the error available to the caller. So we call unmount
// directly, which is what osxfuse does anyway, since we already converted
// to the real path when we first mounted.
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd"))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
unsafe { libc::unmount(mnt.as_ptr(), 0) }
}
#[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd")))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
use std::io::ErrorKind::PermissionDenied;
let rc = unsafe { libc::umount(mnt.as_ptr()) };
if rc < 0 && io::Error::last_os_error().kind() == PermissionDenied {
// Linux always returns EPERM for non-root users. We have to let the
// library go through the setuid-root "fusermount -u" to unmount.
unsafe {
fuse_unmount_compat22(mnt.as_ptr());
}
0
} else {
rc
}
}
let mnt = CString::new(mountpoint.as_os_str().as_bytes())?;
let rc = libc_umount(&mnt);
if rc < 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
extern "system" {
pub fn fuse_unmount_compat22(mountpoint: *const c_char);
}
|
main
|
identifier_name
|
main.rs
|
extern crate chan_signal;
#[macro_use]
extern crate clap;
extern crate daemonize;
extern crate env_logger;
extern crate fuse;
extern crate libc;
#[macro_use]
extern crate log;
extern crate syslog;
extern crate time;
use std::env;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::io;
use std::path::Path;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::thread;
use chan_signal::Signal;
use clap::{App, Arg};
use daemonize::{Daemonize};
use env_logger::LogBuilder;
use log::LogRecord;
use syslog::{Facility,Severity};
mod pcatfs;
mod catfs;
mod flags;
mod evicter;
use catfs::error;
use catfs::flags::{DiskSpace, FlagStorage};
use catfs::rlibc;
fn main() {
if let Err(e) = main_internal() {
error!("Cannot mount: {}", e);
std::process::exit(1);
}
}
static mut SYSLOG: bool = false;
static mut SYSLOGGER: Option<Box<syslog::Logger>> = None;
fn main_internal() -> error::Result<()> {
let format = |record: &LogRecord| {
let t = time::now();
let syslog: bool;
unsafe {
syslog = SYSLOG;
}
if!syslog {
format!(
"{} {:5} - {}",
time::strftime("%Y-%m-%d %H:%M:%S", &t).unwrap(),
record.level(),
record.args()
)
} else {
unsafe {
if let Some(ref logger) = SYSLOGGER {
let level = match record.level() {
log::LogLevel::Trace => Severity::LOG_DEBUG,
log::LogLevel::Debug => Severity::LOG_DEBUG,
log::LogLevel::Info => Severity::LOG_INFO,
log::LogLevel::Warn => Severity::LOG_WARNING,
log::LogLevel::Error => Severity::LOG_ERR,
};
let msg = format!("{}", record.args());
for line in msg.split('\n') {
// ignore error if we can't log, not much we can do anyway
let _ = logger.send_3164(level, line);
}
}
}
format!("\u{08}")
}
};
let mut builder = LogBuilder::new();
builder.format(format);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
} else {
// default to info
builder.parse("info");
}
builder.init().unwrap();
let mut flags: FlagStorage = Default::default();
let mut test = false;
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(OsString::from("atomic_o_trunc"));
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(
OsString::from("default_permissions"),
);
let app = App::new("catfs")
.about("Cache Anything FileSystem")
.version(crate_version!());
{
fn diskspace_validator(s: String) -> Result<(), String> {
DiskSpace::from_str(&s).map(|_| ()).map_err(
|e| e.to_str().to_owned(),
)
}
fn path_validator(s: String) -> Result<(), String> {
Path::new(&s)
.canonicalize()
.map_err(|e| e.to_string().to_owned())
.and_then(|p| if p.is_dir() {
Ok(())
} else {
Err("is not a directory".to_owned())
})
}
let mut args = [
flags::Flag {
arg: Arg::with_name("space")
.long("free")
.takes_value(true)
.help(
"Ensure filesystem has at least this much free space. (ex: 9.5%, 10G)",
)
.validator(diskspace_validator),
value: &mut flags.free_space,
},
flags::Flag {
arg: Arg::with_name("foreground").short("f").help(
"Run catfs in foreground.",
),
value: &mut flags.foreground,
},
flags::Flag{
arg: Arg::with_name("uid")
.long("uid")
.takes_value(true)
.help("Run as this uid"),
value: &mut flags.uid,
},
flags::Flag{
|
.takes_value(true)
.help("Run as this gid"),
value: &mut flags.gid,
},
flags::Flag {
arg: Arg::with_name("option")
.short("o")
.takes_value(true)
.multiple(true)
.help("Additional system-specific mount options. Be careful!"),
value: &mut flags.mount_options,
},
flags::Flag {
arg: Arg::with_name("test").long("test").help(
"Exit after parsing arguments",
),
value: &mut test,
},
flags::Flag {
arg: Arg::with_name("from")
.index(1)
.required(true)
.help("Cache files from this directory.")
.validator(path_validator),
value: &mut flags.cat_from,
},
flags::Flag {
arg: Arg::with_name("to")
.index(2)
.required(true)
.help("Cache files to this directory.")
.validator(path_validator),
value: &mut flags.cat_to,
},
flags::Flag {
arg: Arg::with_name("mountpoint")
.index(3)
.required(true)
.help("Expose the mount point at this directory.")
.validator(path_validator),
value: &mut flags.mount_point,
},
];
flags::parse_options(app, &mut args);
}
if test {
return Ok(());
}
if flags.gid!= 0 {
rlibc::setgid(flags.gid)?;
}
if flags.uid!= 0 {
rlibc::setuid(flags.uid)?;
}
if!flags.foreground {
let daemonize = Daemonize::new()
.working_directory(env::current_dir()?.as_path())
;
match daemonize.start() {
Ok(_) => {
if let Ok(mut logger) = syslog::unix(Facility::LOG_USER) {
unsafe {
logger.set_process_name("catfs".to_string());
logger.set_process_id(libc::getpid());
SYSLOGGER = Some(logger);
SYSLOG = true;
}
}
},
Err(e) => error!("unable to daemonize: {}", e),
}
}
let signal = chan_signal::notify(&[Signal::INT, Signal::TERM]);
let path_from = Path::new(&flags.cat_from).canonicalize()?;
let path_to = Path::new(&flags.cat_to).canonicalize()?;
let fs = catfs::CatFS::new(&path_from, &path_to)?;
let fs = pcatfs::PCatFS::new(fs);
let cache_dir = fs.get_cache_dir()?;
let mut options: Vec<&OsStr> = Vec::new();
for i in 0..flags.mount_options.len() {
options.push(&flags.mount_options[i]);
}
debug!("options are {:?}", flags.mount_options);
{
let mut session = fuse::Session::new(fs, Path::new(&flags.mount_point), &options)?;
let need_unmount = Arc::new(Mutex::new(true));
let need_unmount2 = need_unmount.clone();
thread::spawn(move || {
if let Err(e) = session.run() {
error!("session.run() = {}", e);
}
info!("{:?} unmounted", session.mountpoint());
let mut need_unmount = need_unmount2.lock().unwrap();
*need_unmount = false;
unsafe { libc::kill(libc::getpid(), libc::SIGTERM) };
});
let mut ev = evicter::Evicter::new(cache_dir, &flags.free_space);
ev.run();
// unmount after we get signaled becausep session will go out of scope
let s = signal.recv().unwrap();
info!(
"Received {:?}, attempting to unmount {:?}",
s,
flags.mount_point
);
let need_unmount = need_unmount.lock().unwrap();
if *need_unmount {
unmount(Path::new(&flags.mount_point))?;
}
}
rlibc::close(cache_dir)?;
return Ok(());
}
use libc::{c_char, c_int};
use std::ffi::{CString, CStr};
/// Unmount an arbitrary mount point
pub fn unmount(mountpoint: &Path) -> io::Result<()> {
// fuse_unmount_compat22 unfortunately doesn't return a status. Additionally,
// it attempts to call realpath, which in turn calls into the filesystem. So
// if the filesystem returns an error, the unmount does not take place, with
// no indication of the error available to the caller. So we call unmount
// directly, which is what osxfuse does anyway, since we already converted
// to the real path when we first mounted.
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd"))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
unsafe { libc::unmount(mnt.as_ptr(), 0) }
}
#[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd")))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
use std::io::ErrorKind::PermissionDenied;
let rc = unsafe { libc::umount(mnt.as_ptr()) };
if rc < 0 && io::Error::last_os_error().kind() == PermissionDenied {
// Linux always returns EPERM for non-root users. We have to let the
// library go through the setuid-root "fusermount -u" to unmount.
unsafe {
fuse_unmount_compat22(mnt.as_ptr());
}
0
} else {
rc
}
}
let mnt = CString::new(mountpoint.as_os_str().as_bytes())?;
let rc = libc_umount(&mnt);
if rc < 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
extern "system" {
pub fn fuse_unmount_compat22(mountpoint: *const c_char);
}
|
arg: Arg::with_name("gid")
.long("gid")
|
random_line_split
|
main.rs
|
extern crate chan_signal;
#[macro_use]
extern crate clap;
extern crate daemonize;
extern crate env_logger;
extern crate fuse;
extern crate libc;
#[macro_use]
extern crate log;
extern crate syslog;
extern crate time;
use std::env;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::io;
use std::path::Path;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::thread;
use chan_signal::Signal;
use clap::{App, Arg};
use daemonize::{Daemonize};
use env_logger::LogBuilder;
use log::LogRecord;
use syslog::{Facility,Severity};
mod pcatfs;
mod catfs;
mod flags;
mod evicter;
use catfs::error;
use catfs::flags::{DiskSpace, FlagStorage};
use catfs::rlibc;
fn main() {
if let Err(e) = main_internal()
|
}
static mut SYSLOG: bool = false;
static mut SYSLOGGER: Option<Box<syslog::Logger>> = None;
fn main_internal() -> error::Result<()> {
let format = |record: &LogRecord| {
let t = time::now();
let syslog: bool;
unsafe {
syslog = SYSLOG;
}
if!syslog {
format!(
"{} {:5} - {}",
time::strftime("%Y-%m-%d %H:%M:%S", &t).unwrap(),
record.level(),
record.args()
)
} else {
unsafe {
if let Some(ref logger) = SYSLOGGER {
let level = match record.level() {
log::LogLevel::Trace => Severity::LOG_DEBUG,
log::LogLevel::Debug => Severity::LOG_DEBUG,
log::LogLevel::Info => Severity::LOG_INFO,
log::LogLevel::Warn => Severity::LOG_WARNING,
log::LogLevel::Error => Severity::LOG_ERR,
};
let msg = format!("{}", record.args());
for line in msg.split('\n') {
// ignore error if we can't log, not much we can do anyway
let _ = logger.send_3164(level, line);
}
}
}
format!("\u{08}")
}
};
let mut builder = LogBuilder::new();
builder.format(format);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
} else {
// default to info
builder.parse("info");
}
builder.init().unwrap();
let mut flags: FlagStorage = Default::default();
let mut test = false;
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(OsString::from("atomic_o_trunc"));
flags.mount_options.push(OsString::from("-o"));
flags.mount_options.push(
OsString::from("default_permissions"),
);
let app = App::new("catfs")
.about("Cache Anything FileSystem")
.version(crate_version!());
{
fn diskspace_validator(s: String) -> Result<(), String> {
DiskSpace::from_str(&s).map(|_| ()).map_err(
|e| e.to_str().to_owned(),
)
}
fn path_validator(s: String) -> Result<(), String> {
Path::new(&s)
.canonicalize()
.map_err(|e| e.to_string().to_owned())
.and_then(|p| if p.is_dir() {
Ok(())
} else {
Err("is not a directory".to_owned())
})
}
let mut args = [
flags::Flag {
arg: Arg::with_name("space")
.long("free")
.takes_value(true)
.help(
"Ensure filesystem has at least this much free space. (ex: 9.5%, 10G)",
)
.validator(diskspace_validator),
value: &mut flags.free_space,
},
flags::Flag {
arg: Arg::with_name("foreground").short("f").help(
"Run catfs in foreground.",
),
value: &mut flags.foreground,
},
flags::Flag{
arg: Arg::with_name("uid")
.long("uid")
.takes_value(true)
.help("Run as this uid"),
value: &mut flags.uid,
},
flags::Flag{
arg: Arg::with_name("gid")
.long("gid")
.takes_value(true)
.help("Run as this gid"),
value: &mut flags.gid,
},
flags::Flag {
arg: Arg::with_name("option")
.short("o")
.takes_value(true)
.multiple(true)
.help("Additional system-specific mount options. Be careful!"),
value: &mut flags.mount_options,
},
flags::Flag {
arg: Arg::with_name("test").long("test").help(
"Exit after parsing arguments",
),
value: &mut test,
},
flags::Flag {
arg: Arg::with_name("from")
.index(1)
.required(true)
.help("Cache files from this directory.")
.validator(path_validator),
value: &mut flags.cat_from,
},
flags::Flag {
arg: Arg::with_name("to")
.index(2)
.required(true)
.help("Cache files to this directory.")
.validator(path_validator),
value: &mut flags.cat_to,
},
flags::Flag {
arg: Arg::with_name("mountpoint")
.index(3)
.required(true)
.help("Expose the mount point at this directory.")
.validator(path_validator),
value: &mut flags.mount_point,
},
];
flags::parse_options(app, &mut args);
}
if test {
return Ok(());
}
if flags.gid!= 0 {
rlibc::setgid(flags.gid)?;
}
if flags.uid!= 0 {
rlibc::setuid(flags.uid)?;
}
if!flags.foreground {
let daemonize = Daemonize::new()
.working_directory(env::current_dir()?.as_path())
;
match daemonize.start() {
Ok(_) => {
if let Ok(mut logger) = syslog::unix(Facility::LOG_USER) {
unsafe {
logger.set_process_name("catfs".to_string());
logger.set_process_id(libc::getpid());
SYSLOGGER = Some(logger);
SYSLOG = true;
}
}
},
Err(e) => error!("unable to daemonize: {}", e),
}
}
let signal = chan_signal::notify(&[Signal::INT, Signal::TERM]);
let path_from = Path::new(&flags.cat_from).canonicalize()?;
let path_to = Path::new(&flags.cat_to).canonicalize()?;
let fs = catfs::CatFS::new(&path_from, &path_to)?;
let fs = pcatfs::PCatFS::new(fs);
let cache_dir = fs.get_cache_dir()?;
let mut options: Vec<&OsStr> = Vec::new();
for i in 0..flags.mount_options.len() {
options.push(&flags.mount_options[i]);
}
debug!("options are {:?}", flags.mount_options);
{
let mut session = fuse::Session::new(fs, Path::new(&flags.mount_point), &options)?;
let need_unmount = Arc::new(Mutex::new(true));
let need_unmount2 = need_unmount.clone();
thread::spawn(move || {
if let Err(e) = session.run() {
error!("session.run() = {}", e);
}
info!("{:?} unmounted", session.mountpoint());
let mut need_unmount = need_unmount2.lock().unwrap();
*need_unmount = false;
unsafe { libc::kill(libc::getpid(), libc::SIGTERM) };
});
let mut ev = evicter::Evicter::new(cache_dir, &flags.free_space);
ev.run();
// unmount after we get signaled becausep session will go out of scope
let s = signal.recv().unwrap();
info!(
"Received {:?}, attempting to unmount {:?}",
s,
flags.mount_point
);
let need_unmount = need_unmount.lock().unwrap();
if *need_unmount {
unmount(Path::new(&flags.mount_point))?;
}
}
rlibc::close(cache_dir)?;
return Ok(());
}
use libc::{c_char, c_int};
use std::ffi::{CString, CStr};
/// Unmount an arbitrary mount point
pub fn unmount(mountpoint: &Path) -> io::Result<()> {
// fuse_unmount_compat22 unfortunately doesn't return a status. Additionally,
// it attempts to call realpath, which in turn calls into the filesystem. So
// if the filesystem returns an error, the unmount does not take place, with
// no indication of the error available to the caller. So we call unmount
// directly, which is what osxfuse does anyway, since we already converted
// to the real path when we first mounted.
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd"))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
unsafe { libc::unmount(mnt.as_ptr(), 0) }
}
#[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly",
target_os = "openbsd", target_os = "bitrig", target_os = "netbsd")))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
use std::io::ErrorKind::PermissionDenied;
let rc = unsafe { libc::umount(mnt.as_ptr()) };
if rc < 0 && io::Error::last_os_error().kind() == PermissionDenied {
// Linux always returns EPERM for non-root users. We have to let the
// library go through the setuid-root "fusermount -u" to unmount.
unsafe {
fuse_unmount_compat22(mnt.as_ptr());
}
0
} else {
rc
}
}
let mnt = CString::new(mountpoint.as_os_str().as_bytes())?;
let rc = libc_umount(&mnt);
if rc < 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
extern "system" {
pub fn fuse_unmount_compat22(mountpoint: *const c_char);
}
|
{
error!("Cannot mount: {}", e);
std::process::exit(1);
}
|
conditional_block
|
normalization-debruijn-1.rs
|
// build-pass
// edition:2018
// Regression test to ensure we handle debruijn indices correctly in projection
// normalization under binders. Found in crater run for #85499
use std::future::Future;
use std::pin::Pin;
pub enum Outcome<S, E> {
Success((S, E)),
}
pub struct Request<'r> {
_marker: std::marker::PhantomData<&'r ()>,
}
pub trait FromRequest<'r>: Sized {
type Error;
fn from_request<'life0>(
request: &'r Request<'life0>,
) -> Pin<Box<dyn Future<Output = Outcome<Self, Self::Error>>>>;
}
impl<'r, T: FromRequest<'r>> FromRequest<'r> for Option<T> {
type Error = ();
fn from_request<'life0>(
request: &'r Request<'life0>,
) -> Pin<Box<dyn Future<Output = Outcome<Self, Self::Error>>>> {
Box::pin(async move {
let request = request;
match T::from_request(request).await {
_ => todo!(),
|
}
fn main() {}
|
}
});
todo!()
}
|
random_line_split
|
normalization-debruijn-1.rs
|
// build-pass
// edition:2018
// Regression test to ensure we handle debruijn indices correctly in projection
// normalization under binders. Found in crater run for #85499
use std::future::Future;
use std::pin::Pin;
pub enum Outcome<S, E> {
Success((S, E)),
}
pub struct Request<'r> {
_marker: std::marker::PhantomData<&'r ()>,
}
pub trait FromRequest<'r>: Sized {
type Error;
fn from_request<'life0>(
request: &'r Request<'life0>,
) -> Pin<Box<dyn Future<Output = Outcome<Self, Self::Error>>>>;
}
impl<'r, T: FromRequest<'r>> FromRequest<'r> for Option<T> {
type Error = ();
fn
|
<'life0>(
request: &'r Request<'life0>,
) -> Pin<Box<dyn Future<Output = Outcome<Self, Self::Error>>>> {
Box::pin(async move {
let request = request;
match T::from_request(request).await {
_ => todo!(),
}
});
todo!()
}
}
fn main() {}
|
from_request
|
identifier_name
|
normalization-debruijn-1.rs
|
// build-pass
// edition:2018
// Regression test to ensure we handle debruijn indices correctly in projection
// normalization under binders. Found in crater run for #85499
use std::future::Future;
use std::pin::Pin;
pub enum Outcome<S, E> {
Success((S, E)),
}
pub struct Request<'r> {
_marker: std::marker::PhantomData<&'r ()>,
}
pub trait FromRequest<'r>: Sized {
type Error;
fn from_request<'life0>(
request: &'r Request<'life0>,
) -> Pin<Box<dyn Future<Output = Outcome<Self, Self::Error>>>>;
}
impl<'r, T: FromRequest<'r>> FromRequest<'r> for Option<T> {
type Error = ();
fn from_request<'life0>(
request: &'r Request<'life0>,
) -> Pin<Box<dyn Future<Output = Outcome<Self, Self::Error>>>>
|
}
fn main() {}
|
{
Box::pin(async move {
let request = request;
match T::from_request(request).await {
_ => todo!(),
}
});
todo!()
}
|
identifier_body
|
websocket.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::InheritTypes::EventCast;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::error::Error::{InvalidAccess, Syntax};
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::USVString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::reflect_dom_object;
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use script_task::Runnable;
use script_task::ScriptMsg;
use std::cell::{Cell, RefCell};
use std::borrow::ToOwned;
use util::str::DOMString;
use websocket::Message;
use websocket::ws::sender::Sender as Sender_Object;
use websocket::client::sender::Sender;
use websocket::client::receiver::Receiver;
use websocket::stream::WebSocketStream;
use websocket::client::request::Url;
use websocket::Client;
use websocket::header::Origin;
#[derive(JSTraceable, PartialEq, Copy, Clone)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
no_jsmanaged_fields!(Sender<WebSocketStream>);
no_jsmanaged_fields!(Receiver<WebSocketStream>);
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
global: GlobalField,
ready_state: Cell<WebSocketRequestState>,
sender: RefCell<Option<Sender<WebSocketStream>>>,
receiver: RefCell<Option<Receiver<WebSocketStream>>>,
failed: Cell<bool>, //Flag to tell if websocket was closed due to failure
full: Cell<bool>, //Flag to tell if websocket queue is full
clean_close: Cell<bool>, //Flag to tell if the websocket closed cleanly (not due to full or fail)
code: Cell<u16>, //Closing code
reason: DOMRefCell<DOMString>, //Closing reason
data: DOMRefCell<DOMString>, //Data from send - TODO: Remove after buffer is added.
sendCloseFrame: Cell<bool>
}
fn parse_web_socket_url(url_str: &str) -> Fallible<(Url, String, u16, String, bool)> {
// https://html.spec.whatwg.org/multipage/#parse-a-websocket-url's-components
// Steps 1 and 2
let parsed_url = Url::parse(url_str);
let parsed_url = match parsed_url {
Ok(parsed_url) => parsed_url,
Err(_) => return Err(Error::Syntax),
};
// Step 4
if parsed_url.fragment!= None {
return Err(Error::Syntax);
}
// Steps 3 and 5
let secure = match parsed_url.scheme.as_ref() {
"ws" => false,
"wss" => true,
_ => return Err(Error::Syntax), // step 3
};
let host = parsed_url.host().unwrap().serialize(); // Step 6
let port = parsed_url.port_or_default().unwrap(); // Steps 7 and 8
let mut resource = parsed_url.path().unwrap().connect("/"); // Step 9
if resource.is_empty() {
resource = "/".to_owned(); // Step 10
}
// Step 11
if let Some(ref query) = parsed_url.query {
resource.push('?');
resource.push_str(query);
}
// Step 12
// FIXME remove parsed_url once it's no longer used in WebSocket::new
Ok((parsed_url, host, port, resource, secure))
}
impl WebSocket {
pub fn new_inherited(global: GlobalRef, url: Url) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::WebSocket),
url: url,
global: GlobalField::from_rooted(&global),
ready_state: Cell::new(WebSocketRequestState::Connecting),
failed: Cell::new(false),
sender: RefCell::new(None),
receiver: RefCell::new(None),
full: Cell::new(false),
clean_close: Cell::new(true),
code: Cell::new(0),
reason: DOMRefCell::new("".to_owned()),
data: DOMRefCell::new("".to_owned()),
sendCloseFrame: Cell::new(false)
}
}
pub fn new(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
// Step 1.
// FIXME extract the right variables once Client::connect
// implementation is fixed to follow the RFC 6455 properly.
let (url, _, _, _, _) = try!(parse_web_socket_url(&url));
/*TODO: This constructor is only a prototype, it does not accomplish the specs
defined here:
http://html.spec.whatwg.org
The remaining 8 items must be satisfied.
TODO: This constructor should be responsible for spawning a thread for the
receive loop after ws.r().Open() - See comment
*/
let ws = reflect_dom_object(box WebSocket::new_inherited(global, url.clone()),
global,
WebSocketBinding::Wrap);
// TODO Client::connect does not conform to RFC 6455
// see https://github.com/cyderize/rust-websocket/issues/38
let mut request = match Client::connect(url) {
Ok(request) => request,
Err(_) => {
let global_root = ws.r().global.root();
let address = Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let task = box WebSocketTaskHandler::new(address, WebSocketTask::Close);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(task)).unwrap();
return Ok(ws);
}
};
request.headers.set(Origin(global.get_url().serialize()));
let response = request.send().unwrap();
response.validate().unwrap();
let (temp_sender, temp_receiver) = response.begin().split();
*ws.r().sender.borrow_mut() = Some(temp_sender);
*ws.r().receiver.borrow_mut() = Some(temp_receiver);
//Create everything necessary for starting the open asynchronous task, then begin the task.
let global_root = ws.r().global.root();
let addr: Trusted<WebSocket> =
Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let open_task = box WebSocketTaskHandler::new(addr, WebSocketTask::ConnectionEstablished);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(open_task)).unwrap();
//TODO: Spawn thread here for receive loop
/*TODO: Add receive loop here and make new thread run this
Receive is an infinite loop "similiar" the one shown here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop however does need to follow the spec. These are outlined here
under "WebSocket message has been received" items 1-5:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop also needs to dispatch an asynchronous event as stated here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: When the receive loop receives a close message from the server,
it confirms the websocket is now closed. This requires the close event
to be fired (dispatch_close fires the close event - see implementation below)
*/
Ok(ws)
}
pub fn Constructor(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
WebSocket::new(global, url)
}
}
impl<'a> WebSocketMethods for &'a WebSocket {
event_handler!(open, GetOnopen, SetOnopen);
event_handler!(close, GetOnclose, SetOnclose);
event_handler!(error, GetOnerror, SetOnerror);
fn Url(self) -> DOMString {
self.url.serialize()
}
fn ReadyState(self) -> u16 {
self.ready_state.get() as u16
}
fn Send(self, data: Option<USVString>)-> Fallible<()>{
/*TODO: This is not up to spec see http://html.spec.whatwg.org/multipage/comms.html search for
"If argument is a string"
TODO: Need to buffer data
TODO: bufferedAmount attribute returns the size of the buffer in bytes -
this is a required attribute defined in the websocket.webidl file
TODO: The send function needs to flag when full by using the following
self.full.set(true). This needs to be done when the buffer is full
*/
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
if self.sendCloseFrame.get() { //TODO: Also check if the buffer is full
self.sendCloseFrame.set(false);
let _ = my_sender.send_message(Message::Close(None));
return Ok(());
}
let _ = my_sender.send_message(Message::Text(data.unwrap().0));
return Ok(())
}
fn Close(self, code: Option<u16>, reason: Option<USVString>) -> Fallible<()>{
if let Some(code) = code {
//Check code is NOT 1000 NOR in the range of 3000-4999 (inclusive)
if code!= 1000 && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
self.failed.set(true);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
//TODO: Sending here is just empty string, though no string is really needed. Another send, empty
// send, could be used.
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
WebSocketRequestState::Open => {
//Closing handshake not started - still in open
//Start the closing by setting the code and reason if they exist
if let Some(code) = code {
self.code.set(code);
}
if let Some(reason) = reason {
*self.reason.borrow_mut() = reason.0;
}
self.ready_state.set(WebSocketRequestState::Closing);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
}
Ok(()) //Return Ok
}
}
pub enum WebSocketTask {
/// Task queued when *the WebSocket connection is established*.
ConnectionEstablished,
Close,
}
pub struct WebSocketTaskHandler {
addr: Trusted<WebSocket>,
task: WebSocketTask,
}
impl WebSocketTaskHandler {
pub fn new(addr: Trusted<WebSocket>, task: WebSocketTask) -> WebSocketTaskHandler {
WebSocketTaskHandler {
addr: addr,
task: task,
}
}
fn connection_established(&self) {
/*TODO: Items 1, 3, 4, & 5 under "WebSocket connection is established" as specified here:
https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol
*/
let ws = self.addr.root();
// Step 1: Protocols.
// Step 2.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 3: Extensions.
// Step 4: Protocols.
// Step 5: Cookies.
// Step 6.
let global = ws.global.root();
let event = Event::new(global.r(), "open".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(EventTargetCast::from_ref(ws.r()));
}
fn dispatch_close(&self) {
let ws = self.addr.root();
let ws = ws.r();
let global = ws.global.root();
ws.ready_state.set(WebSocketRequestState::Closed);
//If failed or full, fire error event
if ws.failed.get() || ws.full.get() {
ws.failed.set(false);
ws.full.set(false);
//A Bad close
ws.clean_close.set(false);
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable);
let target = EventTargetCast::from_ref(ws);
event.r().fire(target);
}
let rsn = ws.reason.borrow();
let rsn_clone = rsn.clone();
/*In addition, we also have to fire a close even if error event fired
https://html.spec.whatwg.org/multipage/#closeWebSocket
*/
let close_event = CloseEvent::new(global.r(),
"close".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
ws.clean_close.get(),
ws.code.get(),
rsn_clone);
let target = EventTargetCast::from_ref(ws);
let event = EventCast::from_ref(close_event.r());
event.fire(target);
}
}
impl Runnable for WebSocketTaskHandler {
fn handler(self: Box<WebSocketTaskHandler>) {
match self.task {
WebSocketTask::ConnectionEstablished => {
self.connection_established();
}
WebSocketTask::Close =>
|
}
}
}
|
{
self.dispatch_close();
}
|
conditional_block
|
websocket.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::InheritTypes::EventCast;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::error::Error::{InvalidAccess, Syntax};
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::USVString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::reflect_dom_object;
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use script_task::Runnable;
use script_task::ScriptMsg;
use std::cell::{Cell, RefCell};
use std::borrow::ToOwned;
use util::str::DOMString;
use websocket::Message;
use websocket::ws::sender::Sender as Sender_Object;
use websocket::client::sender::Sender;
use websocket::client::receiver::Receiver;
use websocket::stream::WebSocketStream;
use websocket::client::request::Url;
use websocket::Client;
use websocket::header::Origin;
#[derive(JSTraceable, PartialEq, Copy, Clone)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
no_jsmanaged_fields!(Sender<WebSocketStream>);
no_jsmanaged_fields!(Receiver<WebSocketStream>);
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
global: GlobalField,
ready_state: Cell<WebSocketRequestState>,
sender: RefCell<Option<Sender<WebSocketStream>>>,
receiver: RefCell<Option<Receiver<WebSocketStream>>>,
failed: Cell<bool>, //Flag to tell if websocket was closed due to failure
full: Cell<bool>, //Flag to tell if websocket queue is full
clean_close: Cell<bool>, //Flag to tell if the websocket closed cleanly (not due to full or fail)
code: Cell<u16>, //Closing code
reason: DOMRefCell<DOMString>, //Closing reason
data: DOMRefCell<DOMString>, //Data from send - TODO: Remove after buffer is added.
sendCloseFrame: Cell<bool>
}
fn parse_web_socket_url(url_str: &str) -> Fallible<(Url, String, u16, String, bool)> {
// https://html.spec.whatwg.org/multipage/#parse-a-websocket-url's-components
// Steps 1 and 2
let parsed_url = Url::parse(url_str);
let parsed_url = match parsed_url {
Ok(parsed_url) => parsed_url,
Err(_) => return Err(Error::Syntax),
};
// Step 4
if parsed_url.fragment!= None {
return Err(Error::Syntax);
}
// Steps 3 and 5
let secure = match parsed_url.scheme.as_ref() {
"ws" => false,
"wss" => true,
_ => return Err(Error::Syntax), // step 3
};
let host = parsed_url.host().unwrap().serialize(); // Step 6
let port = parsed_url.port_or_default().unwrap(); // Steps 7 and 8
let mut resource = parsed_url.path().unwrap().connect("/"); // Step 9
if resource.is_empty() {
resource = "/".to_owned(); // Step 10
}
// Step 11
if let Some(ref query) = parsed_url.query {
resource.push('?');
resource.push_str(query);
}
// Step 12
// FIXME remove parsed_url once it's no longer used in WebSocket::new
Ok((parsed_url, host, port, resource, secure))
}
impl WebSocket {
pub fn new_inherited(global: GlobalRef, url: Url) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::WebSocket),
url: url,
global: GlobalField::from_rooted(&global),
ready_state: Cell::new(WebSocketRequestState::Connecting),
failed: Cell::new(false),
sender: RefCell::new(None),
receiver: RefCell::new(None),
full: Cell::new(false),
clean_close: Cell::new(true),
code: Cell::new(0),
reason: DOMRefCell::new("".to_owned()),
data: DOMRefCell::new("".to_owned()),
sendCloseFrame: Cell::new(false)
}
}
pub fn new(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
// Step 1.
// FIXME extract the right variables once Client::connect
// implementation is fixed to follow the RFC 6455 properly.
let (url, _, _, _, _) = try!(parse_web_socket_url(&url));
/*TODO: This constructor is only a prototype, it does not accomplish the specs
defined here:
http://html.spec.whatwg.org
The remaining 8 items must be satisfied.
TODO: This constructor should be responsible for spawning a thread for the
receive loop after ws.r().Open() - See comment
*/
let ws = reflect_dom_object(box WebSocket::new_inherited(global, url.clone()),
global,
WebSocketBinding::Wrap);
// TODO Client::connect does not conform to RFC 6455
// see https://github.com/cyderize/rust-websocket/issues/38
let mut request = match Client::connect(url) {
Ok(request) => request,
Err(_) => {
let global_root = ws.r().global.root();
let address = Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let task = box WebSocketTaskHandler::new(address, WebSocketTask::Close);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(task)).unwrap();
return Ok(ws);
}
};
request.headers.set(Origin(global.get_url().serialize()));
let response = request.send().unwrap();
response.validate().unwrap();
let (temp_sender, temp_receiver) = response.begin().split();
*ws.r().sender.borrow_mut() = Some(temp_sender);
*ws.r().receiver.borrow_mut() = Some(temp_receiver);
//Create everything necessary for starting the open asynchronous task, then begin the task.
let global_root = ws.r().global.root();
let addr: Trusted<WebSocket> =
Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let open_task = box WebSocketTaskHandler::new(addr, WebSocketTask::ConnectionEstablished);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(open_task)).unwrap();
//TODO: Spawn thread here for receive loop
/*TODO: Add receive loop here and make new thread run this
Receive is an infinite loop "similiar" the one shown here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop however does need to follow the spec. These are outlined here
under "WebSocket message has been received" items 1-5:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop also needs to dispatch an asynchronous event as stated here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: When the receive loop receives a close message from the server,
it confirms the websocket is now closed. This requires the close event
to be fired (dispatch_close fires the close event - see implementation below)
*/
Ok(ws)
}
pub fn Constructor(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
WebSocket::new(global, url)
}
}
impl<'a> WebSocketMethods for &'a WebSocket {
event_handler!(open, GetOnopen, SetOnopen);
event_handler!(close, GetOnclose, SetOnclose);
event_handler!(error, GetOnerror, SetOnerror);
fn Url(self) -> DOMString {
self.url.serialize()
}
fn ReadyState(self) -> u16 {
self.ready_state.get() as u16
}
fn Send(self, data: Option<USVString>)-> Fallible<()>{
/*TODO: This is not up to spec see http://html.spec.whatwg.org/multipage/comms.html search for
"If argument is a string"
TODO: Need to buffer data
TODO: bufferedAmount attribute returns the size of the buffer in bytes -
this is a required attribute defined in the websocket.webidl file
TODO: The send function needs to flag when full by using the following
self.full.set(true). This needs to be done when the buffer is full
*/
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
if self.sendCloseFrame.get() { //TODO: Also check if the buffer is full
self.sendCloseFrame.set(false);
let _ = my_sender.send_message(Message::Close(None));
return Ok(());
}
let _ = my_sender.send_message(Message::Text(data.unwrap().0));
return Ok(())
}
fn Close(self, code: Option<u16>, reason: Option<USVString>) -> Fallible<()>{
if let Some(code) = code {
//Check code is NOT 1000 NOR in the range of 3000-4999 (inclusive)
if code!= 1000 && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
self.failed.set(true);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
//TODO: Sending here is just empty string, though no string is really needed. Another send, empty
// send, could be used.
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
WebSocketRequestState::Open => {
//Closing handshake not started - still in open
//Start the closing by setting the code and reason if they exist
if let Some(code) = code {
self.code.set(code);
}
if let Some(reason) = reason {
*self.reason.borrow_mut() = reason.0;
}
self.ready_state.set(WebSocketRequestState::Closing);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
}
Ok(()) //Return Ok
}
}
pub enum WebSocketTask {
/// Task queued when *the WebSocket connection is established*.
ConnectionEstablished,
Close,
}
pub struct WebSocketTaskHandler {
addr: Trusted<WebSocket>,
task: WebSocketTask,
}
impl WebSocketTaskHandler {
pub fn new(addr: Trusted<WebSocket>, task: WebSocketTask) -> WebSocketTaskHandler {
WebSocketTaskHandler {
addr: addr,
task: task,
}
}
fn connection_established(&self) {
/*TODO: Items 1, 3, 4, & 5 under "WebSocket connection is established" as specified here:
https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol
*/
let ws = self.addr.root();
// Step 1: Protocols.
// Step 2.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 3: Extensions.
|
let event = Event::new(global.r(), "open".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(EventTargetCast::from_ref(ws.r()));
}
fn dispatch_close(&self) {
let ws = self.addr.root();
let ws = ws.r();
let global = ws.global.root();
ws.ready_state.set(WebSocketRequestState::Closed);
//If failed or full, fire error event
if ws.failed.get() || ws.full.get() {
ws.failed.set(false);
ws.full.set(false);
//A Bad close
ws.clean_close.set(false);
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable);
let target = EventTargetCast::from_ref(ws);
event.r().fire(target);
}
let rsn = ws.reason.borrow();
let rsn_clone = rsn.clone();
/*In addition, we also have to fire a close even if error event fired
https://html.spec.whatwg.org/multipage/#closeWebSocket
*/
let close_event = CloseEvent::new(global.r(),
"close".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
ws.clean_close.get(),
ws.code.get(),
rsn_clone);
let target = EventTargetCast::from_ref(ws);
let event = EventCast::from_ref(close_event.r());
event.fire(target);
}
}
impl Runnable for WebSocketTaskHandler {
fn handler(self: Box<WebSocketTaskHandler>) {
match self.task {
WebSocketTask::ConnectionEstablished => {
self.connection_established();
}
WebSocketTask::Close => {
self.dispatch_close();
}
}
}
}
|
// Step 4: Protocols.
// Step 5: Cookies.
// Step 6.
let global = ws.global.root();
|
random_line_split
|
websocket.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::InheritTypes::EventCast;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::error::Error::{InvalidAccess, Syntax};
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::USVString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::reflect_dom_object;
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use script_task::Runnable;
use script_task::ScriptMsg;
use std::cell::{Cell, RefCell};
use std::borrow::ToOwned;
use util::str::DOMString;
use websocket::Message;
use websocket::ws::sender::Sender as Sender_Object;
use websocket::client::sender::Sender;
use websocket::client::receiver::Receiver;
use websocket::stream::WebSocketStream;
use websocket::client::request::Url;
use websocket::Client;
use websocket::header::Origin;
#[derive(JSTraceable, PartialEq, Copy, Clone)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
no_jsmanaged_fields!(Sender<WebSocketStream>);
no_jsmanaged_fields!(Receiver<WebSocketStream>);
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
global: GlobalField,
ready_state: Cell<WebSocketRequestState>,
sender: RefCell<Option<Sender<WebSocketStream>>>,
receiver: RefCell<Option<Receiver<WebSocketStream>>>,
failed: Cell<bool>, //Flag to tell if websocket was closed due to failure
full: Cell<bool>, //Flag to tell if websocket queue is full
clean_close: Cell<bool>, //Flag to tell if the websocket closed cleanly (not due to full or fail)
code: Cell<u16>, //Closing code
reason: DOMRefCell<DOMString>, //Closing reason
data: DOMRefCell<DOMString>, //Data from send - TODO: Remove after buffer is added.
sendCloseFrame: Cell<bool>
}
fn parse_web_socket_url(url_str: &str) -> Fallible<(Url, String, u16, String, bool)> {
// https://html.spec.whatwg.org/multipage/#parse-a-websocket-url's-components
// Steps 1 and 2
let parsed_url = Url::parse(url_str);
let parsed_url = match parsed_url {
Ok(parsed_url) => parsed_url,
Err(_) => return Err(Error::Syntax),
};
// Step 4
if parsed_url.fragment!= None {
return Err(Error::Syntax);
}
// Steps 3 and 5
let secure = match parsed_url.scheme.as_ref() {
"ws" => false,
"wss" => true,
_ => return Err(Error::Syntax), // step 3
};
let host = parsed_url.host().unwrap().serialize(); // Step 6
let port = parsed_url.port_or_default().unwrap(); // Steps 7 and 8
let mut resource = parsed_url.path().unwrap().connect("/"); // Step 9
if resource.is_empty() {
resource = "/".to_owned(); // Step 10
}
// Step 11
if let Some(ref query) = parsed_url.query {
resource.push('?');
resource.push_str(query);
}
// Step 12
// FIXME remove parsed_url once it's no longer used in WebSocket::new
Ok((parsed_url, host, port, resource, secure))
}
impl WebSocket {
pub fn new_inherited(global: GlobalRef, url: Url) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::WebSocket),
url: url,
global: GlobalField::from_rooted(&global),
ready_state: Cell::new(WebSocketRequestState::Connecting),
failed: Cell::new(false),
sender: RefCell::new(None),
receiver: RefCell::new(None),
full: Cell::new(false),
clean_close: Cell::new(true),
code: Cell::new(0),
reason: DOMRefCell::new("".to_owned()),
data: DOMRefCell::new("".to_owned()),
sendCloseFrame: Cell::new(false)
}
}
pub fn new(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
// Step 1.
// FIXME extract the right variables once Client::connect
// implementation is fixed to follow the RFC 6455 properly.
let (url, _, _, _, _) = try!(parse_web_socket_url(&url));
/*TODO: This constructor is only a prototype, it does not accomplish the specs
defined here:
http://html.spec.whatwg.org
The remaining 8 items must be satisfied.
TODO: This constructor should be responsible for spawning a thread for the
receive loop after ws.r().Open() - See comment
*/
let ws = reflect_dom_object(box WebSocket::new_inherited(global, url.clone()),
global,
WebSocketBinding::Wrap);
// TODO Client::connect does not conform to RFC 6455
// see https://github.com/cyderize/rust-websocket/issues/38
let mut request = match Client::connect(url) {
Ok(request) => request,
Err(_) => {
let global_root = ws.r().global.root();
let address = Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let task = box WebSocketTaskHandler::new(address, WebSocketTask::Close);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(task)).unwrap();
return Ok(ws);
}
};
request.headers.set(Origin(global.get_url().serialize()));
let response = request.send().unwrap();
response.validate().unwrap();
let (temp_sender, temp_receiver) = response.begin().split();
*ws.r().sender.borrow_mut() = Some(temp_sender);
*ws.r().receiver.borrow_mut() = Some(temp_receiver);
//Create everything necessary for starting the open asynchronous task, then begin the task.
let global_root = ws.r().global.root();
let addr: Trusted<WebSocket> =
Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let open_task = box WebSocketTaskHandler::new(addr, WebSocketTask::ConnectionEstablished);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(open_task)).unwrap();
//TODO: Spawn thread here for receive loop
/*TODO: Add receive loop here and make new thread run this
Receive is an infinite loop "similiar" the one shown here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop however does need to follow the spec. These are outlined here
under "WebSocket message has been received" items 1-5:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop also needs to dispatch an asynchronous event as stated here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: When the receive loop receives a close message from the server,
it confirms the websocket is now closed. This requires the close event
to be fired (dispatch_close fires the close event - see implementation below)
*/
Ok(ws)
}
pub fn
|
(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
WebSocket::new(global, url)
}
}
impl<'a> WebSocketMethods for &'a WebSocket {
event_handler!(open, GetOnopen, SetOnopen);
event_handler!(close, GetOnclose, SetOnclose);
event_handler!(error, GetOnerror, SetOnerror);
fn Url(self) -> DOMString {
self.url.serialize()
}
fn ReadyState(self) -> u16 {
self.ready_state.get() as u16
}
fn Send(self, data: Option<USVString>)-> Fallible<()>{
/*TODO: This is not up to spec see http://html.spec.whatwg.org/multipage/comms.html search for
"If argument is a string"
TODO: Need to buffer data
TODO: bufferedAmount attribute returns the size of the buffer in bytes -
this is a required attribute defined in the websocket.webidl file
TODO: The send function needs to flag when full by using the following
self.full.set(true). This needs to be done when the buffer is full
*/
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
if self.sendCloseFrame.get() { //TODO: Also check if the buffer is full
self.sendCloseFrame.set(false);
let _ = my_sender.send_message(Message::Close(None));
return Ok(());
}
let _ = my_sender.send_message(Message::Text(data.unwrap().0));
return Ok(())
}
fn Close(self, code: Option<u16>, reason: Option<USVString>) -> Fallible<()>{
if let Some(code) = code {
//Check code is NOT 1000 NOR in the range of 3000-4999 (inclusive)
if code!= 1000 && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
self.failed.set(true);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
//TODO: Sending here is just empty string, though no string is really needed. Another send, empty
// send, could be used.
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
WebSocketRequestState::Open => {
//Closing handshake not started - still in open
//Start the closing by setting the code and reason if they exist
if let Some(code) = code {
self.code.set(code);
}
if let Some(reason) = reason {
*self.reason.borrow_mut() = reason.0;
}
self.ready_state.set(WebSocketRequestState::Closing);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
}
Ok(()) //Return Ok
}
}
pub enum WebSocketTask {
/// Task queued when *the WebSocket connection is established*.
ConnectionEstablished,
Close,
}
pub struct WebSocketTaskHandler {
addr: Trusted<WebSocket>,
task: WebSocketTask,
}
impl WebSocketTaskHandler {
pub fn new(addr: Trusted<WebSocket>, task: WebSocketTask) -> WebSocketTaskHandler {
WebSocketTaskHandler {
addr: addr,
task: task,
}
}
fn connection_established(&self) {
/*TODO: Items 1, 3, 4, & 5 under "WebSocket connection is established" as specified here:
https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol
*/
let ws = self.addr.root();
// Step 1: Protocols.
// Step 2.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 3: Extensions.
// Step 4: Protocols.
// Step 5: Cookies.
// Step 6.
let global = ws.global.root();
let event = Event::new(global.r(), "open".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(EventTargetCast::from_ref(ws.r()));
}
fn dispatch_close(&self) {
let ws = self.addr.root();
let ws = ws.r();
let global = ws.global.root();
ws.ready_state.set(WebSocketRequestState::Closed);
//If failed or full, fire error event
if ws.failed.get() || ws.full.get() {
ws.failed.set(false);
ws.full.set(false);
//A Bad close
ws.clean_close.set(false);
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable);
let target = EventTargetCast::from_ref(ws);
event.r().fire(target);
}
let rsn = ws.reason.borrow();
let rsn_clone = rsn.clone();
/*In addition, we also have to fire a close even if error event fired
https://html.spec.whatwg.org/multipage/#closeWebSocket
*/
let close_event = CloseEvent::new(global.r(),
"close".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
ws.clean_close.get(),
ws.code.get(),
rsn_clone);
let target = EventTargetCast::from_ref(ws);
let event = EventCast::from_ref(close_event.r());
event.fire(target);
}
}
impl Runnable for WebSocketTaskHandler {
fn handler(self: Box<WebSocketTaskHandler>) {
match self.task {
WebSocketTask::ConnectionEstablished => {
self.connection_established();
}
WebSocketTask::Close => {
self.dispatch_close();
}
}
}
}
|
Constructor
|
identifier_name
|
websocket.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::InheritTypes::EventCast;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::error::Error::{InvalidAccess, Syntax};
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::USVString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::reflect_dom_object;
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use script_task::Runnable;
use script_task::ScriptMsg;
use std::cell::{Cell, RefCell};
use std::borrow::ToOwned;
use util::str::DOMString;
use websocket::Message;
use websocket::ws::sender::Sender as Sender_Object;
use websocket::client::sender::Sender;
use websocket::client::receiver::Receiver;
use websocket::stream::WebSocketStream;
use websocket::client::request::Url;
use websocket::Client;
use websocket::header::Origin;
#[derive(JSTraceable, PartialEq, Copy, Clone)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
no_jsmanaged_fields!(Sender<WebSocketStream>);
no_jsmanaged_fields!(Receiver<WebSocketStream>);
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
global: GlobalField,
ready_state: Cell<WebSocketRequestState>,
sender: RefCell<Option<Sender<WebSocketStream>>>,
receiver: RefCell<Option<Receiver<WebSocketStream>>>,
failed: Cell<bool>, //Flag to tell if websocket was closed due to failure
full: Cell<bool>, //Flag to tell if websocket queue is full
clean_close: Cell<bool>, //Flag to tell if the websocket closed cleanly (not due to full or fail)
code: Cell<u16>, //Closing code
reason: DOMRefCell<DOMString>, //Closing reason
data: DOMRefCell<DOMString>, //Data from send - TODO: Remove after buffer is added.
sendCloseFrame: Cell<bool>
}
fn parse_web_socket_url(url_str: &str) -> Fallible<(Url, String, u16, String, bool)> {
// https://html.spec.whatwg.org/multipage/#parse-a-websocket-url's-components
// Steps 1 and 2
let parsed_url = Url::parse(url_str);
let parsed_url = match parsed_url {
Ok(parsed_url) => parsed_url,
Err(_) => return Err(Error::Syntax),
};
// Step 4
if parsed_url.fragment!= None {
return Err(Error::Syntax);
}
// Steps 3 and 5
let secure = match parsed_url.scheme.as_ref() {
"ws" => false,
"wss" => true,
_ => return Err(Error::Syntax), // step 3
};
let host = parsed_url.host().unwrap().serialize(); // Step 6
let port = parsed_url.port_or_default().unwrap(); // Steps 7 and 8
let mut resource = parsed_url.path().unwrap().connect("/"); // Step 9
if resource.is_empty() {
resource = "/".to_owned(); // Step 10
}
// Step 11
if let Some(ref query) = parsed_url.query {
resource.push('?');
resource.push_str(query);
}
// Step 12
// FIXME remove parsed_url once it's no longer used in WebSocket::new
Ok((parsed_url, host, port, resource, secure))
}
impl WebSocket {
pub fn new_inherited(global: GlobalRef, url: Url) -> WebSocket
|
pub fn new(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
// Step 1.
// FIXME extract the right variables once Client::connect
// implementation is fixed to follow the RFC 6455 properly.
let (url, _, _, _, _) = try!(parse_web_socket_url(&url));
/*TODO: This constructor is only a prototype, it does not accomplish the specs
defined here:
http://html.spec.whatwg.org
The remaining 8 items must be satisfied.
TODO: This constructor should be responsible for spawning a thread for the
receive loop after ws.r().Open() - See comment
*/
let ws = reflect_dom_object(box WebSocket::new_inherited(global, url.clone()),
global,
WebSocketBinding::Wrap);
// TODO Client::connect does not conform to RFC 6455
// see https://github.com/cyderize/rust-websocket/issues/38
let mut request = match Client::connect(url) {
Ok(request) => request,
Err(_) => {
let global_root = ws.r().global.root();
let address = Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let task = box WebSocketTaskHandler::new(address, WebSocketTask::Close);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(task)).unwrap();
return Ok(ws);
}
};
request.headers.set(Origin(global.get_url().serialize()));
let response = request.send().unwrap();
response.validate().unwrap();
let (temp_sender, temp_receiver) = response.begin().split();
*ws.r().sender.borrow_mut() = Some(temp_sender);
*ws.r().receiver.borrow_mut() = Some(temp_receiver);
//Create everything necessary for starting the open asynchronous task, then begin the task.
let global_root = ws.r().global.root();
let addr: Trusted<WebSocket> =
Trusted::new(global_root.r().get_cx(), ws.r(), global_root.r().script_chan().clone());
let open_task = box WebSocketTaskHandler::new(addr, WebSocketTask::ConnectionEstablished);
global_root.r().script_chan().send(ScriptMsg::RunnableMsg(open_task)).unwrap();
//TODO: Spawn thread here for receive loop
/*TODO: Add receive loop here and make new thread run this
Receive is an infinite loop "similiar" the one shown here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop however does need to follow the spec. These are outlined here
under "WebSocket message has been received" items 1-5:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: The receive loop also needs to dispatch an asynchronous event as stated here:
https://github.com/cyderize/rust-websocket/blob/master/examples/client.rs#L64
TODO: When the receive loop receives a close message from the server,
it confirms the websocket is now closed. This requires the close event
to be fired (dispatch_close fires the close event - see implementation below)
*/
Ok(ws)
}
pub fn Constructor(global: GlobalRef, url: DOMString) -> Fallible<Root<WebSocket>> {
WebSocket::new(global, url)
}
}
impl<'a> WebSocketMethods for &'a WebSocket {
event_handler!(open, GetOnopen, SetOnopen);
event_handler!(close, GetOnclose, SetOnclose);
event_handler!(error, GetOnerror, SetOnerror);
fn Url(self) -> DOMString {
self.url.serialize()
}
fn ReadyState(self) -> u16 {
self.ready_state.get() as u16
}
fn Send(self, data: Option<USVString>)-> Fallible<()>{
/*TODO: This is not up to spec see http://html.spec.whatwg.org/multipage/comms.html search for
"If argument is a string"
TODO: Need to buffer data
TODO: bufferedAmount attribute returns the size of the buffer in bytes -
this is a required attribute defined in the websocket.webidl file
TODO: The send function needs to flag when full by using the following
self.full.set(true). This needs to be done when the buffer is full
*/
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
if self.sendCloseFrame.get() { //TODO: Also check if the buffer is full
self.sendCloseFrame.set(false);
let _ = my_sender.send_message(Message::Close(None));
return Ok(());
}
let _ = my_sender.send_message(Message::Text(data.unwrap().0));
return Ok(())
}
fn Close(self, code: Option<u16>, reason: Option<USVString>) -> Fallible<()>{
if let Some(code) = code {
//Check code is NOT 1000 NOR in the range of 3000-4999 (inclusive)
if code!= 1000 && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
self.failed.set(true);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
//TODO: Sending here is just empty string, though no string is really needed. Another send, empty
// send, could be used.
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
WebSocketRequestState::Open => {
//Closing handshake not started - still in open
//Start the closing by setting the code and reason if they exist
if let Some(code) = code {
self.code.set(code);
}
if let Some(reason) = reason {
*self.reason.borrow_mut() = reason.0;
}
self.ready_state.set(WebSocketRequestState::Closing);
self.sendCloseFrame.set(true);
//Dispatch send task to send close frame
let _ = self.Send(None);
//Note: After sending the close message, the receive loop confirms a close message from the server and
// must fire a close event
}
}
Ok(()) //Return Ok
}
}
pub enum WebSocketTask {
/// Task queued when *the WebSocket connection is established*.
ConnectionEstablished,
Close,
}
pub struct WebSocketTaskHandler {
addr: Trusted<WebSocket>,
task: WebSocketTask,
}
impl WebSocketTaskHandler {
pub fn new(addr: Trusted<WebSocket>, task: WebSocketTask) -> WebSocketTaskHandler {
WebSocketTaskHandler {
addr: addr,
task: task,
}
}
fn connection_established(&self) {
/*TODO: Items 1, 3, 4, & 5 under "WebSocket connection is established" as specified here:
https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol
*/
let ws = self.addr.root();
// Step 1: Protocols.
// Step 2.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 3: Extensions.
// Step 4: Protocols.
// Step 5: Cookies.
// Step 6.
let global = ws.global.root();
let event = Event::new(global.r(), "open".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(EventTargetCast::from_ref(ws.r()));
}
fn dispatch_close(&self) {
let ws = self.addr.root();
let ws = ws.r();
let global = ws.global.root();
ws.ready_state.set(WebSocketRequestState::Closed);
//If failed or full, fire error event
if ws.failed.get() || ws.full.get() {
ws.failed.set(false);
ws.full.set(false);
//A Bad close
ws.clean_close.set(false);
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable);
let target = EventTargetCast::from_ref(ws);
event.r().fire(target);
}
let rsn = ws.reason.borrow();
let rsn_clone = rsn.clone();
/*In addition, we also have to fire a close even if error event fired
https://html.spec.whatwg.org/multipage/#closeWebSocket
*/
let close_event = CloseEvent::new(global.r(),
"close".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
ws.clean_close.get(),
ws.code.get(),
rsn_clone);
let target = EventTargetCast::from_ref(ws);
let event = EventCast::from_ref(close_event.r());
event.fire(target);
}
}
impl Runnable for WebSocketTaskHandler {
fn handler(self: Box<WebSocketTaskHandler>) {
match self.task {
WebSocketTask::ConnectionEstablished => {
self.connection_established();
}
WebSocketTask::Close => {
self.dispatch_close();
}
}
}
}
|
{
WebSocket {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::WebSocket),
url: url,
global: GlobalField::from_rooted(&global),
ready_state: Cell::new(WebSocketRequestState::Connecting),
failed: Cell::new(false),
sender: RefCell::new(None),
receiver: RefCell::new(None),
full: Cell::new(false),
clean_close: Cell::new(true),
code: Cell::new(0),
reason: DOMRefCell::new("".to_owned()),
data: DOMRefCell::new("".to_owned()),
sendCloseFrame: Cell::new(false)
}
}
|
identifier_body
|
parse_file.rs
|
#[macro_use]
extern crate difference;
use liquid::*;
use std::fs::File;
use std::io::Read;
fn compare_by_file(name: &str, globals: &Object) {
let input_file = format!("tests/fixtures/input/{}.txt", name);
let output_file = format!("tests/fixtures/output/{}.txt", name);
let template = ParserBuilder::with_stdlib()
.build()
.unwrap()
.parse_file(input_file)
.unwrap();
let output = template.render(globals).unwrap();
let mut comp = String::new();
File::open(output_file)
.unwrap()
.read_to_string(&mut comp)
.unwrap();
assert_diff!(&comp, &output, " ", 0);
}
#[test]
pub fn error_on_nonexistent_file() {
let template = ParserBuilder::with_stdlib()
.build()
.unwrap()
.parse_file("not-a-file.ext");
assert!(template.is_err());
}
#[test]
pub fn example_by_file()
|
{
let globals = object!({
"num": 5,
"numTwo": 6
});
compare_by_file("example", &globals);
}
|
identifier_body
|
|
parse_file.rs
|
#[macro_use]
extern crate difference;
use liquid::*;
use std::fs::File;
use std::io::Read;
fn compare_by_file(name: &str, globals: &Object) {
let input_file = format!("tests/fixtures/input/{}.txt", name);
let output_file = format!("tests/fixtures/output/{}.txt", name);
let template = ParserBuilder::with_stdlib()
.build()
.unwrap()
.parse_file(input_file)
.unwrap();
|
File::open(output_file)
.unwrap()
.read_to_string(&mut comp)
.unwrap();
assert_diff!(&comp, &output, " ", 0);
}
#[test]
pub fn error_on_nonexistent_file() {
let template = ParserBuilder::with_stdlib()
.build()
.unwrap()
.parse_file("not-a-file.ext");
assert!(template.is_err());
}
#[test]
pub fn example_by_file() {
let globals = object!({
"num": 5,
"numTwo": 6
});
compare_by_file("example", &globals);
}
|
let output = template.render(globals).unwrap();
let mut comp = String::new();
|
random_line_split
|
parse_file.rs
|
#[macro_use]
extern crate difference;
use liquid::*;
use std::fs::File;
use std::io::Read;
fn compare_by_file(name: &str, globals: &Object) {
let input_file = format!("tests/fixtures/input/{}.txt", name);
let output_file = format!("tests/fixtures/output/{}.txt", name);
let template = ParserBuilder::with_stdlib()
.build()
.unwrap()
.parse_file(input_file)
.unwrap();
let output = template.render(globals).unwrap();
let mut comp = String::new();
File::open(output_file)
.unwrap()
.read_to_string(&mut comp)
.unwrap();
assert_diff!(&comp, &output, " ", 0);
}
#[test]
pub fn
|
() {
let template = ParserBuilder::with_stdlib()
.build()
.unwrap()
.parse_file("not-a-file.ext");
assert!(template.is_err());
}
#[test]
pub fn example_by_file() {
let globals = object!({
"num": 5,
"numTwo": 6
});
compare_by_file("example", &globals);
}
|
error_on_nonexistent_file
|
identifier_name
|
tool_bar.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bool, to_gboolean};
use cast::{GTK_TOOLBAR, GTK_TOOLITEM};
use {IconSize, ReliefStyle, ToolbarStyle};
/// Toolbar — Create bars of buttons and other widgets
/*
* # Availables signals :
* * `focus-home-or-end` : Action
* * `orientation-changed` : Run First
* * `popup-context-menu` : Run Last
* * `style-changed` : Run First
*/
struct_Widget!(Toolbar);
impl Toolbar {
pub fn new() -> Option<Toolbar> {
let tmp_pointer = unsafe { ffi::gtk_toolbar_new() };
check_pointer!(tmp_pointer, Toolbar)
}
pub fn insert<T: ::ToolItemTrait>(&self,
item: &T,
pos: i32) -> () {
unsafe {
ffi::gtk_toolbar_insert(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), pos as c_int)
}
}
pub fn item_index<T: ::ToolItemTrait>(&self, item: &T) -> i32 {
unsafe {
ffi::gtk_toolbar_get_item_index(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget())) as i32
}
}
pub fn get_n_items(&self) -> i32 {
unsafe {
ffi::gtk_toolbar_get_n_items(GTK_TOOLBAR(self.pointer)) as i32
}
}
pub fn get_nth_item(&self, n: i32) -> Option<::ToolItem> {
unsafe {
let tmp_pointer = ffi::gtk_toolbar_get_nth_item(GTK_TOOLBAR(self.pointer), n as c_int) as *mut ffi::GtkWidget;
if tmp_pointer.is_null() {
|
lse {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
}
}
pub fn get_drop_index(&self, x: i32, y: i32) -> i32 {
unsafe {
ffi::gtk_toolbar_get_drop_index(GTK_TOOLBAR(self.pointer), x as c_int, y as c_int) as i32
}
}
pub fn set_drop_highlight_item<T: ::ToolItemTrait>(&self, item: &T, index: i32) -> () {
unsafe {
ffi::gtk_toolbar_set_drop_highlight_item(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), index as c_int);
}
}
pub fn set_show_arrow(&self, show_arrow: bool) -> () {
unsafe { ffi::gtk_toolbar_set_show_arrow(GTK_TOOLBAR(self.pointer), to_gboolean(show_arrow)); }
}
pub fn unset_icon_size(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_icon_size(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_show_arrow(&self) -> bool {
unsafe { to_bool(ffi::gtk_toolbar_get_show_arrow(GTK_TOOLBAR(self.pointer))) }
}
pub fn get_style(&self) -> ToolbarStyle {
unsafe {
ffi::gtk_toolbar_get_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_icon_size(&self) -> IconSize {
unsafe {
ffi::gtk_toolbar_get_icon_size(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_relief_style(&self) -> ReliefStyle {
unsafe {
ffi::gtk_toolbar_get_relief_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn set_style(&self, style: ToolbarStyle) -> () {
unsafe {
ffi::gtk_toolbar_set_style(GTK_TOOLBAR(self.pointer), style);
}
}
pub fn set_icon_size(&self, icon_size: IconSize) -> () {
unsafe {
ffi::gtk_toolbar_set_icon_size(GTK_TOOLBAR(self.pointer), icon_size);
}
}
pub fn unset_style(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_style(GTK_TOOLBAR(self.pointer));
}
}
}
impl_drop!(Toolbar);
impl_TraitWidget!(Toolbar);
impl ::ContainerTrait for Toolbar {}
impl ::ToolShellTrait for Toolbar {}
impl ::OrientableTrait for Toolbar {}
|
None
} e
|
conditional_block
|
tool_bar.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bool, to_gboolean};
use cast::{GTK_TOOLBAR, GTK_TOOLITEM};
use {IconSize, ReliefStyle, ToolbarStyle};
/// Toolbar — Create bars of buttons and other widgets
/*
* # Availables signals :
* * `focus-home-or-end` : Action
* * `orientation-changed` : Run First
* * `popup-context-menu` : Run Last
* * `style-changed` : Run First
*/
struct_Widget!(Toolbar);
impl Toolbar {
pub fn new() -> Option<Toolbar> {
let tmp_pointer = unsafe { ffi::gtk_toolbar_new() };
check_pointer!(tmp_pointer, Toolbar)
}
pub fn insert<T: ::ToolItemTrait>(&self,
item: &T,
pos: i32) -> () {
unsafe {
ffi::gtk_toolbar_insert(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), pos as c_int)
}
}
pub fn item_index<T: ::ToolItemTrait>(&self, item: &T) -> i32 {
unsafe {
ffi::gtk_toolbar_get_item_index(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget())) as i32
}
}
pub fn get_n_items(&self) -> i32 {
unsafe {
ffi::gtk_toolbar_get_n_items(GTK_TOOLBAR(self.pointer)) as i32
}
}
pub fn get_nth_item(&self, n: i32) -> Option<::ToolItem> {
|
pub fn get_drop_index(&self, x: i32, y: i32) -> i32 {
unsafe {
ffi::gtk_toolbar_get_drop_index(GTK_TOOLBAR(self.pointer), x as c_int, y as c_int) as i32
}
}
pub fn set_drop_highlight_item<T: ::ToolItemTrait>(&self, item: &T, index: i32) -> () {
unsafe {
ffi::gtk_toolbar_set_drop_highlight_item(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), index as c_int);
}
}
pub fn set_show_arrow(&self, show_arrow: bool) -> () {
unsafe { ffi::gtk_toolbar_set_show_arrow(GTK_TOOLBAR(self.pointer), to_gboolean(show_arrow)); }
}
pub fn unset_icon_size(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_icon_size(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_show_arrow(&self) -> bool {
unsafe { to_bool(ffi::gtk_toolbar_get_show_arrow(GTK_TOOLBAR(self.pointer))) }
}
pub fn get_style(&self) -> ToolbarStyle {
unsafe {
ffi::gtk_toolbar_get_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_icon_size(&self) -> IconSize {
unsafe {
ffi::gtk_toolbar_get_icon_size(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_relief_style(&self) -> ReliefStyle {
unsafe {
ffi::gtk_toolbar_get_relief_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn set_style(&self, style: ToolbarStyle) -> () {
unsafe {
ffi::gtk_toolbar_set_style(GTK_TOOLBAR(self.pointer), style);
}
}
pub fn set_icon_size(&self, icon_size: IconSize) -> () {
unsafe {
ffi::gtk_toolbar_set_icon_size(GTK_TOOLBAR(self.pointer), icon_size);
}
}
pub fn unset_style(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_style(GTK_TOOLBAR(self.pointer));
}
}
}
impl_drop!(Toolbar);
impl_TraitWidget!(Toolbar);
impl ::ContainerTrait for Toolbar {}
impl ::ToolShellTrait for Toolbar {}
impl ::OrientableTrait for Toolbar {}
|
unsafe {
let tmp_pointer = ffi::gtk_toolbar_get_nth_item(GTK_TOOLBAR(self.pointer), n as c_int) as *mut ffi::GtkWidget;
if tmp_pointer.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
}
}
|
identifier_body
|
tool_bar.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bool, to_gboolean};
use cast::{GTK_TOOLBAR, GTK_TOOLITEM};
use {IconSize, ReliefStyle, ToolbarStyle};
/// Toolbar — Create bars of buttons and other widgets
/*
* # Availables signals :
* * `focus-home-or-end` : Action
* * `orientation-changed` : Run First
* * `popup-context-menu` : Run Last
* * `style-changed` : Run First
*/
struct_Widget!(Toolbar);
impl Toolbar {
pub fn new() -> Option<Toolbar> {
let tmp_pointer = unsafe { ffi::gtk_toolbar_new() };
check_pointer!(tmp_pointer, Toolbar)
}
pub fn insert<T: ::ToolItemTrait>(&self,
item: &T,
pos: i32) -> () {
unsafe {
ffi::gtk_toolbar_insert(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), pos as c_int)
}
}
pub fn item_index<T: ::ToolItemTrait>(&self, item: &T) -> i32 {
unsafe {
ffi::gtk_toolbar_get_item_index(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget())) as i32
}
}
pub fn get_n_items(&self) -> i32 {
unsafe {
ffi::gtk_toolbar_get_n_items(GTK_TOOLBAR(self.pointer)) as i32
}
}
pub fn get_nth_item(&self, n: i32) -> Option<::ToolItem> {
unsafe {
let tmp_pointer = ffi::gtk_toolbar_get_nth_item(GTK_TOOLBAR(self.pointer), n as c_int) as *mut ffi::GtkWidget;
if tmp_pointer.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
}
}
pub fn get_drop_index(&self, x: i32, y: i32) -> i32 {
unsafe {
ffi::gtk_toolbar_get_drop_index(GTK_TOOLBAR(self.pointer), x as c_int, y as c_int) as i32
}
}
pub fn set_drop_highlight_item<T: ::ToolItemTrait>(&self, item: &T, index: i32) -> () {
unsafe {
ffi::gtk_toolbar_set_drop_highlight_item(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), index as c_int);
}
}
pub fn set_show_arrow(&self, show_arrow: bool) -> () {
unsafe { ffi::gtk_toolbar_set_show_arrow(GTK_TOOLBAR(self.pointer), to_gboolean(show_arrow)); }
}
pub fn un
|
self) -> () {
unsafe {
ffi::gtk_toolbar_unset_icon_size(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_show_arrow(&self) -> bool {
unsafe { to_bool(ffi::gtk_toolbar_get_show_arrow(GTK_TOOLBAR(self.pointer))) }
}
pub fn get_style(&self) -> ToolbarStyle {
unsafe {
ffi::gtk_toolbar_get_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_icon_size(&self) -> IconSize {
unsafe {
ffi::gtk_toolbar_get_icon_size(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_relief_style(&self) -> ReliefStyle {
unsafe {
ffi::gtk_toolbar_get_relief_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn set_style(&self, style: ToolbarStyle) -> () {
unsafe {
ffi::gtk_toolbar_set_style(GTK_TOOLBAR(self.pointer), style);
}
}
pub fn set_icon_size(&self, icon_size: IconSize) -> () {
unsafe {
ffi::gtk_toolbar_set_icon_size(GTK_TOOLBAR(self.pointer), icon_size);
}
}
pub fn unset_style(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_style(GTK_TOOLBAR(self.pointer));
}
}
}
impl_drop!(Toolbar);
impl_TraitWidget!(Toolbar);
impl ::ContainerTrait for Toolbar {}
impl ::ToolShellTrait for Toolbar {}
impl ::OrientableTrait for Toolbar {}
|
set_icon_size(&
|
identifier_name
|
tool_bar.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bool, to_gboolean};
use cast::{GTK_TOOLBAR, GTK_TOOLITEM};
use {IconSize, ReliefStyle, ToolbarStyle};
/// Toolbar — Create bars of buttons and other widgets
/*
* # Availables signals :
* * `focus-home-or-end` : Action
* * `orientation-changed` : Run First
* * `popup-context-menu` : Run Last
* * `style-changed` : Run First
*/
struct_Widget!(Toolbar);
impl Toolbar {
pub fn new() -> Option<Toolbar> {
let tmp_pointer = unsafe { ffi::gtk_toolbar_new() };
check_pointer!(tmp_pointer, Toolbar)
}
pub fn insert<T: ::ToolItemTrait>(&self,
item: &T,
pos: i32) -> () {
unsafe {
ffi::gtk_toolbar_insert(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), pos as c_int)
}
}
pub fn item_index<T: ::ToolItemTrait>(&self, item: &T) -> i32 {
unsafe {
ffi::gtk_toolbar_get_item_index(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget())) as i32
}
}
pub fn get_n_items(&self) -> i32 {
unsafe {
ffi::gtk_toolbar_get_n_items(GTK_TOOLBAR(self.pointer)) as i32
}
}
pub fn get_nth_item(&self, n: i32) -> Option<::ToolItem> {
unsafe {
let tmp_pointer = ffi::gtk_toolbar_get_nth_item(GTK_TOOLBAR(self.pointer), n as c_int) as *mut ffi::GtkWidget;
if tmp_pointer.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
}
}
pub fn get_drop_index(&self, x: i32, y: i32) -> i32 {
unsafe {
ffi::gtk_toolbar_get_drop_index(GTK_TOOLBAR(self.pointer), x as c_int, y as c_int) as i32
}
}
pub fn set_drop_highlight_item<T: ::ToolItemTrait>(&self, item: &T, index: i32) -> () {
unsafe {
ffi::gtk_toolbar_set_drop_highlight_item(GTK_TOOLBAR(self.pointer), GTK_TOOLITEM(item.unwrap_widget()), index as c_int);
}
}
pub fn set_show_arrow(&self, show_arrow: bool) -> () {
unsafe { ffi::gtk_toolbar_set_show_arrow(GTK_TOOLBAR(self.pointer), to_gboolean(show_arrow)); }
}
pub fn unset_icon_size(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_icon_size(GTK_TOOLBAR(self.pointer))
}
|
pub fn get_style(&self) -> ToolbarStyle {
unsafe {
ffi::gtk_toolbar_get_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_icon_size(&self) -> IconSize {
unsafe {
ffi::gtk_toolbar_get_icon_size(GTK_TOOLBAR(self.pointer))
}
}
pub fn get_relief_style(&self) -> ReliefStyle {
unsafe {
ffi::gtk_toolbar_get_relief_style(GTK_TOOLBAR(self.pointer))
}
}
pub fn set_style(&self, style: ToolbarStyle) -> () {
unsafe {
ffi::gtk_toolbar_set_style(GTK_TOOLBAR(self.pointer), style);
}
}
pub fn set_icon_size(&self, icon_size: IconSize) -> () {
unsafe {
ffi::gtk_toolbar_set_icon_size(GTK_TOOLBAR(self.pointer), icon_size);
}
}
pub fn unset_style(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_style(GTK_TOOLBAR(self.pointer));
}
}
}
impl_drop!(Toolbar);
impl_TraitWidget!(Toolbar);
impl ::ContainerTrait for Toolbar {}
impl ::ToolShellTrait for Toolbar {}
impl ::OrientableTrait for Toolbar {}
|
}
pub fn get_show_arrow(&self) -> bool {
unsafe { to_bool(ffi::gtk_toolbar_get_show_arrow(GTK_TOOLBAR(self.pointer))) }
}
|
random_line_split
|
nested_item.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.
// original problem
pub fn foo<T>() -> isize {
{
static foo: isize = 2;
foo
}
}
// issue 8134
struct Foo;
impl Foo {
|
static X: usize = 1;
}
}
// issue 8134
pub struct Parser<T>(T);
impl<T: std::iter::Iterator<Item=char>> Parser<T> {
fn in_doctype(&mut self) {
static DOCTYPEPattern: [char; 6] = ['O', 'C', 'T', 'Y', 'P', 'E'];
}
}
struct Bar;
impl Foo {
pub fn bar<T>(&self) {
static X: usize = 1;
}
}
|
pub fn foo<T>(&self) {
|
random_line_split
|
nested_item.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.
// original problem
pub fn foo<T>() -> isize {
{
static foo: isize = 2;
foo
}
}
// issue 8134
struct Foo;
impl Foo {
pub fn foo<T>(&self) {
static X: usize = 1;
}
}
// issue 8134
pub struct Parser<T>(T);
impl<T: std::iter::Iterator<Item=char>> Parser<T> {
fn in_doctype(&mut self)
|
}
struct Bar;
impl Foo {
pub fn bar<T>(&self) {
static X: usize = 1;
}
}
|
{
static DOCTYPEPattern: [char; 6] = ['O', 'C', 'T', 'Y', 'P', 'E'];
}
|
identifier_body
|
nested_item.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.
// original problem
pub fn foo<T>() -> isize {
{
static foo: isize = 2;
foo
}
}
// issue 8134
struct Foo;
impl Foo {
pub fn foo<T>(&self) {
static X: usize = 1;
}
}
// issue 8134
pub struct Parser<T>(T);
impl<T: std::iter::Iterator<Item=char>> Parser<T> {
fn in_doctype(&mut self) {
static DOCTYPEPattern: [char; 6] = ['O', 'C', 'T', 'Y', 'P', 'E'];
}
}
struct Bar;
impl Foo {
pub fn
|
<T>(&self) {
static X: usize = 1;
}
}
|
bar
|
identifier_name
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail() { let x = if false { fail2!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail()
|
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail2!() } else { 10 };
assert_eq!(x, 10);
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
{
let x = if true { 10 } else { fail2!() };
assert_eq!(x, 10);
}
|
identifier_body
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail() { let x = if false
|
else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail2!() };
assert_eq!(x, 10);
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail2!() } else { 10 };
assert_eq!(x, 10);
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
{ fail2!() }
|
conditional_block
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn
|
() { let x = if false { fail2!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail2!() };
assert_eq!(x, 10);
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail2!() } else { 10 };
assert_eq!(x, 10);
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
test_if_fail
|
identifier_name
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail() { let x = if false { fail2!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail2!() };
assert_eq!(x, 10);
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail2!() } else { 10 };
assert_eq!(x, 10);
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
random_line_split
|
|
main.rs
|
const n: usize = (16*1024);
struct foo {
chaMem: *mut [u32; n],
}
impl foo {
pub fn new() -> foo {
let mem: *mut [u32; n] = unsafe { ::std::mem::transmute(Box::new([1; n])) };
foo {chaMem: mem}
}
pub fn get_sig_ptr(&mut self, cha_signal: *mut *mut u32) {
unsafe {
*cha_signal = self.chaMem as *mut _;
}
}
pub fn get_sig_ptr2(&mut self) -> *mut u32 {
return self.chaMem as *mut _;
}
pub fn get_sig_ptr3(&mut self) -> *mut [u32; n]
|
pub fn get_sig_ptr4(&mut self) -> &mut [u32; n] {
unsafe {
return &mut *(self.chaMem);
}
}
}
// This code is editable and runnable!
fn main() {
let mut f = foo::new();
let mut cha_signal1: *mut u32 = ::std::ptr::null_mut();
f.get_sig_ptr(&mut cha_signal1);
for i in 1..n {
println!("{}", unsafe { *cha_signal1.offset(i as isize) }); // (*cha_signal)[i]
}
let mut cha_signal2: *mut u32 = f.get_sig_ptr2();
for i in 1..n {
println!("{}", unsafe { *cha_signal2.offset(i as isize) });
}
let mut cha_signal3: *mut [u32; n] = f.get_sig_ptr3();
for i in 1..n {
println!("{}", unsafe { (*cha_signal3)[i] });
}
// preferred version
let mut cha_signal4: &mut [u32; n] = f.get_sig_ptr4();
for i in 1..n {
println!("{}", cha_signal4[i]);
}
}
|
{
return self.chaMem;
}
|
identifier_body
|
main.rs
|
const n: usize = (16*1024);
struct foo {
chaMem: *mut [u32; n],
}
impl foo {
pub fn new() -> foo {
let mem: *mut [u32; n] = unsafe { ::std::mem::transmute(Box::new([1; n])) };
foo {chaMem: mem}
}
pub fn get_sig_ptr(&mut self, cha_signal: *mut *mut u32) {
unsafe {
*cha_signal = self.chaMem as *mut _;
}
}
pub fn get_sig_ptr2(&mut self) -> *mut u32 {
return self.chaMem as *mut _;
}
pub fn get_sig_ptr3(&mut self) -> *mut [u32; n] {
return self.chaMem;
}
pub fn get_sig_ptr4(&mut self) -> &mut [u32; n] {
unsafe {
return &mut *(self.chaMem);
}
}
}
|
let mut cha_signal1: *mut u32 = ::std::ptr::null_mut();
f.get_sig_ptr(&mut cha_signal1);
for i in 1..n {
println!("{}", unsafe { *cha_signal1.offset(i as isize) }); // (*cha_signal)[i]
}
let mut cha_signal2: *mut u32 = f.get_sig_ptr2();
for i in 1..n {
println!("{}", unsafe { *cha_signal2.offset(i as isize) });
}
let mut cha_signal3: *mut [u32; n] = f.get_sig_ptr3();
for i in 1..n {
println!("{}", unsafe { (*cha_signal3)[i] });
}
// preferred version
let mut cha_signal4: &mut [u32; n] = f.get_sig_ptr4();
for i in 1..n {
println!("{}", cha_signal4[i]);
}
}
|
// This code is editable and runnable!
fn main() {
let mut f = foo::new();
|
random_line_split
|
main.rs
|
const n: usize = (16*1024);
struct
|
{
chaMem: *mut [u32; n],
}
impl foo {
pub fn new() -> foo {
let mem: *mut [u32; n] = unsafe { ::std::mem::transmute(Box::new([1; n])) };
foo {chaMem: mem}
}
pub fn get_sig_ptr(&mut self, cha_signal: *mut *mut u32) {
unsafe {
*cha_signal = self.chaMem as *mut _;
}
}
pub fn get_sig_ptr2(&mut self) -> *mut u32 {
return self.chaMem as *mut _;
}
pub fn get_sig_ptr3(&mut self) -> *mut [u32; n] {
return self.chaMem;
}
pub fn get_sig_ptr4(&mut self) -> &mut [u32; n] {
unsafe {
return &mut *(self.chaMem);
}
}
}
// This code is editable and runnable!
fn main() {
let mut f = foo::new();
let mut cha_signal1: *mut u32 = ::std::ptr::null_mut();
f.get_sig_ptr(&mut cha_signal1);
for i in 1..n {
println!("{}", unsafe { *cha_signal1.offset(i as isize) }); // (*cha_signal)[i]
}
let mut cha_signal2: *mut u32 = f.get_sig_ptr2();
for i in 1..n {
println!("{}", unsafe { *cha_signal2.offset(i as isize) });
}
let mut cha_signal3: *mut [u32; n] = f.get_sig_ptr3();
for i in 1..n {
println!("{}", unsafe { (*cha_signal3)[i] });
}
// preferred version
let mut cha_signal4: &mut [u32; n] = f.get_sig_ptr4();
for i in 1..n {
println!("{}", cha_signal4[i]);
}
}
|
foo
|
identifier_name
|
grid_level.rs
|
use std::default::Default;
use tile::Tile;
use util::{Error, Grid};
use Vector;
#[derive(Clone)]
pub struct GridLevel<T> {
pub(crate) tiles: Grid<T>,
}
impl<T> GridLevel<T> {
pub fn get_width(&self) -> usize {
self.tiles.get_width()
}
pub fn get_height(&self) -> usize {
self.tiles.get_height()
}
pub fn get_tile(&self, x: usize, y: usize) -> Result<&T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_tile_with_vec(&self, pos: &Vector<usize>) -> Result<&T, Error> {
self.get_tile(pos.x, pos.y)
}
pub fn get_tile_with_tuple(&self, (x, y): (usize, usize)) -> Result<&T, Error> {
self.get_tile(x, y)
}
pub fn get_mut_tile(&mut self, x: usize, y: usize) -> Result<&mut T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&mut self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_mut_tile_with_vec(&mut self, pos: &Vector<usize>) -> Result<&mut T, Error> {
self.get_mut_tile(pos.x, pos.y)
}
pub fn get_mut_tile_with_tuple(&mut self, (x, y): (usize, usize)) -> Result<&mut T, Error> {
self.get_mut_tile(x, y)
}
pub fn apply<F>(&mut self, gen: F) -> &mut GridLevel<T>
where
F: FnOnce(&mut GridLevel<T>),
{
gen(self);
self
}
}
impl<T: Default + Clone> GridLevel<T> {
pub fn fill_with(&mut self, tile: T) {
let width = self.tiles.get_width();
let height = self.tiles.get_height();
for x in 0..width {
for y in 0..height {
self.tiles[(x, y)] = tile.clone();
}
}
}
pub fn new(width: usize, height: usize) -> GridLevel<T> {
GridLevel {
tiles: Grid::new(width, height),
}
}
pub fn new_filled_with(tile: T, width: usize, height: usize) -> GridLevel<T> {
GridLevel {
tiles: Grid::new_filled_with(tile, width, height),
}
}
}
pub fn fill_dead_end_tiles(level: &mut GridLevel<Tile>) -> bool {
let mut deadends = Vec::new();
for y in 0..level.get_height() {
for x in 0..level.get_width() {
if let Ok(n) = level.get_tile(x, y) {
if let &Tile::Floor(_) = n {
if is_deadend(level, x, y) {
deadends.push((x, y));
}
}
}
}
}
let mut filled_deadend = false;
for &(x, y) in &deadends {
if let Ok(tile) = level.get_mut_tile(x, y) {
*tile = Tile::Wall(0);
filled_deadend = true;
}
}
filled_deadend
}
pub fn
|
(level: &GridLevel<Tile>, x: usize, y: usize) -> bool {
use util::Direction;
let mut paths = 0;
for dir in Direction::get_orthogonal_dirs() {
let vector = dir.get_vec();
let coord = match (
add_isize_to_usize(vector.x, x),
add_isize_to_usize(vector.y, y),
) {
(Some(x), Some(y)) => (x, y),
_ => continue,
};
if let Ok(&Tile::Floor(_)) = level.get_tile_with_tuple(coord) {
paths += 1;
}
}
paths < 2
}
pub fn add_isize_to_usize(i: isize, mut u: usize) -> Option<usize> {
if i < 0 && u!= 0 {
u -= (-i) as usize;
} else if i >= 0 && u < usize::max_value() {
u += i as usize;
} else {
return None;
}
Some(u)
}
|
is_deadend
|
identifier_name
|
grid_level.rs
|
use std::default::Default;
use tile::Tile;
use util::{Error, Grid};
use Vector;
#[derive(Clone)]
pub struct GridLevel<T> {
pub(crate) tiles: Grid<T>,
}
impl<T> GridLevel<T> {
pub fn get_width(&self) -> usize {
self.tiles.get_width()
}
pub fn get_height(&self) -> usize {
self.tiles.get_height()
}
pub fn get_tile(&self, x: usize, y: usize) -> Result<&T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_tile_with_vec(&self, pos: &Vector<usize>) -> Result<&T, Error> {
self.get_tile(pos.x, pos.y)
}
pub fn get_tile_with_tuple(&self, (x, y): (usize, usize)) -> Result<&T, Error> {
self.get_tile(x, y)
}
pub fn get_mut_tile(&mut self, x: usize, y: usize) -> Result<&mut T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&mut self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_mut_tile_with_vec(&mut self, pos: &Vector<usize>) -> Result<&mut T, Error> {
self.get_mut_tile(pos.x, pos.y)
}
pub fn get_mut_tile_with_tuple(&mut self, (x, y): (usize, usize)) -> Result<&mut T, Error> {
self.get_mut_tile(x, y)
}
pub fn apply<F>(&mut self, gen: F) -> &mut GridLevel<T>
where
F: FnOnce(&mut GridLevel<T>),
{
gen(self);
self
}
}
impl<T: Default + Clone> GridLevel<T> {
pub fn fill_with(&mut self, tile: T) {
let width = self.tiles.get_width();
let height = self.tiles.get_height();
for x in 0..width {
for y in 0..height {
self.tiles[(x, y)] = tile.clone();
}
}
}
pub fn new(width: usize, height: usize) -> GridLevel<T> {
GridLevel {
tiles: Grid::new(width, height),
}
}
pub fn new_filled_with(tile: T, width: usize, height: usize) -> GridLevel<T> {
GridLevel {
tiles: Grid::new_filled_with(tile, width, height),
}
}
}
pub fn fill_dead_end_tiles(level: &mut GridLevel<Tile>) -> bool {
let mut deadends = Vec::new();
for y in 0..level.get_height() {
for x in 0..level.get_width() {
if let Ok(n) = level.get_tile(x, y) {
if let &Tile::Floor(_) = n {
if is_deadend(level, x, y) {
deadends.push((x, y));
}
}
}
}
}
let mut filled_deadend = false;
for &(x, y) in &deadends {
if let Ok(tile) = level.get_mut_tile(x, y) {
*tile = Tile::Wall(0);
filled_deadend = true;
}
}
filled_deadend
}
pub fn is_deadend(level: &GridLevel<Tile>, x: usize, y: usize) -> bool {
use util::Direction;
let mut paths = 0;
for dir in Direction::get_orthogonal_dirs() {
let vector = dir.get_vec();
let coord = match (
add_isize_to_usize(vector.x, x),
add_isize_to_usize(vector.y, y),
) {
(Some(x), Some(y)) => (x, y),
_ => continue,
};
if let Ok(&Tile::Floor(_)) = level.get_tile_with_tuple(coord) {
paths += 1;
}
}
paths < 2
}
pub fn add_isize_to_usize(i: isize, mut u: usize) -> Option<usize> {
if i < 0 && u!= 0 {
u -= (-i) as usize;
} else if i >= 0 && u < usize::max_value() {
u += i as usize;
} else
|
Some(u)
}
|
{
return None;
}
|
conditional_block
|
grid_level.rs
|
use std::default::Default;
use tile::Tile;
use util::{Error, Grid};
use Vector;
#[derive(Clone)]
pub struct GridLevel<T> {
pub(crate) tiles: Grid<T>,
}
impl<T> GridLevel<T> {
pub fn get_width(&self) -> usize {
self.tiles.get_width()
}
pub fn get_height(&self) -> usize {
self.tiles.get_height()
}
pub fn get_tile(&self, x: usize, y: usize) -> Result<&T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_tile_with_vec(&self, pos: &Vector<usize>) -> Result<&T, Error> {
self.get_tile(pos.x, pos.y)
}
pub fn get_tile_with_tuple(&self, (x, y): (usize, usize)) -> Result<&T, Error> {
self.get_tile(x, y)
}
pub fn get_mut_tile(&mut self, x: usize, y: usize) -> Result<&mut T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&mut self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_mut_tile_with_vec(&mut self, pos: &Vector<usize>) -> Result<&mut T, Error> {
self.get_mut_tile(pos.x, pos.y)
}
pub fn get_mut_tile_with_tuple(&mut self, (x, y): (usize, usize)) -> Result<&mut T, Error> {
self.get_mut_tile(x, y)
}
pub fn apply<F>(&mut self, gen: F) -> &mut GridLevel<T>
where
F: FnOnce(&mut GridLevel<T>),
{
gen(self);
self
}
}
impl<T: Default + Clone> GridLevel<T> {
pub fn fill_with(&mut self, tile: T) {
let width = self.tiles.get_width();
let height = self.tiles.get_height();
for x in 0..width {
for y in 0..height {
self.tiles[(x, y)] = tile.clone();
}
}
}
pub fn new(width: usize, height: usize) -> GridLevel<T>
|
pub fn new_filled_with(tile: T, width: usize, height: usize) -> GridLevel<T> {
GridLevel {
tiles: Grid::new_filled_with(tile, width, height),
}
}
}
pub fn fill_dead_end_tiles(level: &mut GridLevel<Tile>) -> bool {
let mut deadends = Vec::new();
for y in 0..level.get_height() {
for x in 0..level.get_width() {
if let Ok(n) = level.get_tile(x, y) {
if let &Tile::Floor(_) = n {
if is_deadend(level, x, y) {
deadends.push((x, y));
}
}
}
}
}
let mut filled_deadend = false;
for &(x, y) in &deadends {
if let Ok(tile) = level.get_mut_tile(x, y) {
*tile = Tile::Wall(0);
filled_deadend = true;
}
}
filled_deadend
}
pub fn is_deadend(level: &GridLevel<Tile>, x: usize, y: usize) -> bool {
use util::Direction;
let mut paths = 0;
for dir in Direction::get_orthogonal_dirs() {
let vector = dir.get_vec();
let coord = match (
add_isize_to_usize(vector.x, x),
add_isize_to_usize(vector.y, y),
) {
(Some(x), Some(y)) => (x, y),
_ => continue,
};
if let Ok(&Tile::Floor(_)) = level.get_tile_with_tuple(coord) {
paths += 1;
}
}
paths < 2
}
pub fn add_isize_to_usize(i: isize, mut u: usize) -> Option<usize> {
if i < 0 && u!= 0 {
u -= (-i) as usize;
} else if i >= 0 && u < usize::max_value() {
u += i as usize;
} else {
return None;
}
Some(u)
}
|
{
GridLevel {
tiles: Grid::new(width, height),
}
}
|
identifier_body
|
grid_level.rs
|
use std::default::Default;
use tile::Tile;
use util::{Error, Grid};
use Vector;
#[derive(Clone)]
pub struct GridLevel<T> {
pub(crate) tiles: Grid<T>,
}
impl<T> GridLevel<T> {
pub fn get_width(&self) -> usize {
self.tiles.get_width()
}
pub fn get_height(&self) -> usize {
self.tiles.get_height()
}
pub fn get_tile(&self, x: usize, y: usize) -> Result<&T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_tile_with_vec(&self, pos: &Vector<usize>) -> Result<&T, Error> {
self.get_tile(pos.x, pos.y)
}
pub fn get_tile_with_tuple(&self, (x, y): (usize, usize)) -> Result<&T, Error> {
self.get_tile(x, y)
}
pub fn get_mut_tile(&mut self, x: usize, y: usize) -> Result<&mut T, Error> {
if x < self.get_width() && y < self.get_height() {
Ok(&mut self.tiles[(x, y)])
} else {
Err(Error::IndexOutOfBounds)
}
}
pub fn get_mut_tile_with_vec(&mut self, pos: &Vector<usize>) -> Result<&mut T, Error> {
self.get_mut_tile(pos.x, pos.y)
}
pub fn get_mut_tile_with_tuple(&mut self, (x, y): (usize, usize)) -> Result<&mut T, Error> {
self.get_mut_tile(x, y)
}
pub fn apply<F>(&mut self, gen: F) -> &mut GridLevel<T>
where
F: FnOnce(&mut GridLevel<T>),
{
gen(self);
self
}
}
impl<T: Default + Clone> GridLevel<T> {
pub fn fill_with(&mut self, tile: T) {
let width = self.tiles.get_width();
let height = self.tiles.get_height();
for x in 0..width {
for y in 0..height {
self.tiles[(x, y)] = tile.clone();
}
}
}
pub fn new(width: usize, height: usize) -> GridLevel<T> {
GridLevel {
tiles: Grid::new(width, height),
}
}
pub fn new_filled_with(tile: T, width: usize, height: usize) -> GridLevel<T> {
GridLevel {
tiles: Grid::new_filled_with(tile, width, height),
}
}
}
pub fn fill_dead_end_tiles(level: &mut GridLevel<Tile>) -> bool {
let mut deadends = Vec::new();
for y in 0..level.get_height() {
for x in 0..level.get_width() {
if let Ok(n) = level.get_tile(x, y) {
if let &Tile::Floor(_) = n {
if is_deadend(level, x, y) {
deadends.push((x, y));
}
}
}
}
}
let mut filled_deadend = false;
for &(x, y) in &deadends {
if let Ok(tile) = level.get_mut_tile(x, y) {
*tile = Tile::Wall(0);
filled_deadend = true;
}
}
filled_deadend
}
pub fn is_deadend(level: &GridLevel<Tile>, x: usize, y: usize) -> bool {
use util::Direction;
let mut paths = 0;
for dir in Direction::get_orthogonal_dirs() {
let vector = dir.get_vec();
let coord = match (
add_isize_to_usize(vector.x, x),
add_isize_to_usize(vector.y, y),
) {
(Some(x), Some(y)) => (x, y),
_ => continue,
};
if let Ok(&Tile::Floor(_)) = level.get_tile_with_tuple(coord) {
paths += 1;
}
|
pub fn add_isize_to_usize(i: isize, mut u: usize) -> Option<usize> {
if i < 0 && u!= 0 {
u -= (-i) as usize;
} else if i >= 0 && u < usize::max_value() {
u += i as usize;
} else {
return None;
}
Some(u)
}
|
}
paths < 2
}
|
random_line_split
|
mod.rs
|
lazy_universe = Some(universe);
universe
});
let placeholder = ty::PlaceholderRegion { universe, name: br };
delegate.next_placeholder_region(placeholder)
} else {
delegate.next_existential_region_var()
}
}
};
value.skip_binder().visit_with(&mut ScopeInstantiator {
next_region: &mut next_region,
target_index: ty::INNERMOST,
bound_region_scope: &mut scope,
});
scope
}
/// When we encounter binders during the type traversal, we record
/// the value to substitute for each of the things contained in
/// that binder. (This will be either a universal placeholder or
/// an existential inference variable.) Given the debruijn index
/// `debruijn` (and name `br`) of some binder we have now
/// encountered, this routine finds the value that we instantiated
/// the region with; to do so, it indexes backwards into the list
/// of ambient scopes `scopes`.
fn lookup_bound_region(
debruijn: ty::DebruijnIndex,
br: &ty::BoundRegion,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
// The debruijn index is a "reverse index" into the
// scopes listing. So when we have INNERMOST (0), we
// want the *last* scope pushed, and so forth.
let debruijn_index = debruijn.index() - first_free_index.index();
let scope = &scopes[scopes.len() - debruijn_index - 1];
// Find this bound region in that scope to map to a
// particular region.
scope.map[br]
}
/// If `r` is a bound region, find the scope in which it is bound
/// (from `scopes`) and return the value that we instantiated it
/// with. Otherwise just return `r`.
fn replace_bound_region(
&self,
r: ty::Region<'tcx>,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
if let ty::ReLateBound(debruijn, br) = r {
Self::lookup_bound_region(*debruijn, br, first_free_index, scopes)
} else {
r
}
}
/// Push a new outlives requirement into our output set of
/// constraints.
fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>) {
debug!("push_outlives({:?}: {:?})", sup, sub);
self.delegate.push_outlives(sup, sub);
}
/// Relate a projection type and some value type lazily. This will always
/// succeed, but we push an additional `ProjectionEq` goal depending
/// on the value type:
/// - if the value type is any type `T` which is not a projection, we push
/// `ProjectionEq(projection = T)`.
/// - if the value type is another projection `other_projection`, we create
/// a new inference variable `?U` and push the two goals
/// `ProjectionEq(projection =?U)`, `ProjectionEq(other_projection =?U)`.
fn relate_projection_ty(
&mut self,
projection_ty: ty::ProjectionTy<'tcx>,
value_ty: ty::Ty<'tcx>
) -> Ty<'tcx> {
use crate::infer::type_variable::TypeVariableOrigin;
use crate::traits::WhereClause;
use syntax_pos::DUMMY_SP;
match value_ty.sty {
ty::Projection(other_projection_ty) => {
let var = self.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
self.relate_projection_ty(projection_ty, var);
self.relate_projection_ty(other_projection_ty, var);
var
}
_ => {
let projection = ty::ProjectionPredicate {
projection_ty,
ty: value_ty,
};
self.delegate.push_domain_goal(
DomainGoal::Holds(WhereClause::ProjectionEq(projection))
);
value_ty
}
}
}
/// Relate a type inference variable with a value type.
fn relate_ty_var(
&mut self,
vid: ty::TyVid,
value_ty: Ty<'tcx>
) -> RelateResult<'tcx, Ty<'tcx>> {
debug!("relate_ty_var(vid={:?}, value_ty={:?})", vid, value_ty);
match value_ty.sty {
ty::Infer(ty::TyVar(value_vid)) => {
// Two type variables: just equate them.
self.infcx.type_variables.borrow_mut().equate(vid, value_vid);
return Ok(value_ty);
}
ty::Projection(projection_ty)
if D::normalization() == NormalizationStrategy::Lazy =>
{
return Ok(self.relate_projection_ty(projection_ty, self.infcx.tcx.mk_var(vid)));
}
_ => (),
}
let generalized_ty = self.generalize_value(value_ty, vid)?;
debug!("relate_ty_var: generalized_ty = {:?}", generalized_ty);
if D::forbid_inference_vars() {
// In NLL, we don't have type inference variables
// floating around, so we can do this rather imprecise
// variant of the occurs-check.
assert!(!generalized_ty.has_infer_types());
}
self.infcx.type_variables.borrow_mut().instantiate(vid, generalized_ty);
// The generalized values we extract from `canonical_var_values` have
// been fully instantiated and hence the set of scopes we have
// doesn't matter -- just to be sure, put an empty vector
// in there.
let old_a_scopes = ::std::mem::replace(&mut self.a_scopes, vec![]);
// Relate the generalized kind to the original one.
let result = self.relate(&generalized_ty, &value_ty);
// Restore the old scopes now.
self.a_scopes = old_a_scopes;
debug!("relate_ty_var: complete, result = {:?}", result);
result
}
fn generalize_value<T: Relate<'tcx>>(
&mut self,
value: T,
for_vid: ty::TyVid
) -> RelateResult<'tcx, T> {
let universe = self.infcx.probe_ty_var(for_vid).unwrap_err();
let mut generalizer = TypeGeneralizer {
infcx: self.infcx,
delegate: &mut self.delegate,
first_free_index: ty::INNERMOST,
ambient_variance: self.ambient_variance,
for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
universe,
};
generalizer.relate(&value, &value)
}
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::subtype"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T> {
debug!(
"relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("relate_with_variance: r={:?}", r);
Ok(r)
}
fn tys(&mut self, a: Ty<'tcx>, mut b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
let a = self.infcx.shallow_resolve(a);
if!D::forbid_inference_vars() {
b = self.infcx.shallow_resolve(b);
}
match (&a.sty, &b.sty) {
(_, &ty::Infer(ty::TyVar(vid))) => {
if D::forbid_inference_vars() {
// Forbid inference variables in the RHS.
bug!("unexpected inference var {:?}", b)
} else {
self.relate_ty_var(vid, a)
}
}
(&ty::Infer(ty::TyVar(vid)), _) => self.relate_ty_var(vid, b),
(&ty::Projection(projection_ty), _)
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, b))
}
(_, &ty::Projection(projection_ty))
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, a))
}
_ => {
debug!(
"tys(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
// Will also handle unification of `IntVar` and `FloatVar`.
self.infcx.super_combine_tys(self, a, b)
}
}
}
fn regions(
&mut self,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Region<'tcx>> {
debug!(
"regions(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
let v_a = self.replace_bound_region(a, ty::INNERMOST, &self.a_scopes);
let v_b = self.replace_bound_region(b, ty::INNERMOST, &self.b_scopes);
debug!("regions: v_a = {:?}", v_a);
debug!("regions: v_b = {:?}", v_b);
if self.ambient_covariance() {
// Covariance: a <= b. Hence, `b: a`.
self.push_outlives(v_b, v_a);
}
if self.ambient_contravariance() {
// Contravariant: b <= a. Hence, `a: b`.
self.push_outlives(v_a, v_b);
}
Ok(a)
}
fn binders<T>(
&mut self,
a: &ty::Binder<T>,
b: &ty::Binder<T>,
) -> RelateResult<'tcx, ty::Binder<T>>
where
T: Relate<'tcx>,
{
// We want that
//
// ```
// for<'a> fn(&'a u32) -> &'a u32 <:
// fn(&'b u32) -> &'b u32
// ```
//
// but not
//
// ```
// fn(&'a u32) -> &'a u32 <:
// for<'b> fn(&'b u32) -> &'b u32
// ```
//
// We therefore proceed as follows:
//
// - Instantiate binders on `b` universally, yielding a universe U1.
// - Instantiate binders on `a` existentially in U1.
debug!(
"binders({:?}: {:?}, ambient_variance={:?})",
a, b, self.ambient_variance
);
if self.ambient_covariance() {
// Covariance, so we want `for<..> A <: for<..> B` --
// therefore we compare any instantiation of A (i.e., A
// instantiated with existentials) against every
// instantiation of B (i.e., B instantiated with
// universals).
let b_scope = self.create_scope(b, UniversallyQuantified(true));
let a_scope = self.create_scope(a, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (existential)", a_scope);
debug!("binders: b_scope = {:?} (universal)", b_scope);
self.b_scopes.push(b_scope);
self.a_scopes.push(a_scope);
// Reset the ambient variance to covariant. This is needed
// to correctly handle cases like
//
// for<'a> fn(&'a u32, &'a u3) == for<'b, 'c> fn(&'b u32, &'c u32)
//
// Somewhat surprisingly, these two types are actually
// **equal**, even though the one on the right looks more
// polymorphic. The reason is due to subtyping. To see it,
// consider that each function can call the other:
//
// - The left function can call the right with `'b` and
// `'c` both equal to `'a`
//
// - The right function can call the left with `'a` set to
// `{P}`, where P is the point in the CFG where the call
// itself occurs. Note that `'b` and `'c` must both
// include P. At the point, the call works because of
// subtyping (i.e., `&'b u32 <: &{P} u32`).
let variance = ::std::mem::replace(&mut self.ambient_variance, ty::Variance::Covariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
if self.ambient_contravariance() {
// Contravariance, so we want `for<..> A :> for<..> B`
// -- therefore we compare every instantiation of A (i.e.,
// A instantiated with universals) against any
// instantiation of B (i.e., B instantiated with
// existentials). Opposite of above.
let a_scope = self.create_scope(a, UniversallyQuantified(true));
let b_scope = self.create_scope(b, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (universal)", a_scope);
debug!("binders: b_scope = {:?} (existential)", b_scope);
self.a_scopes.push(a_scope);
self.b_scopes.push(b_scope);
// Reset ambient variance to contravariance. See the
// covariant case above for an explanation.
let variance =
::std::mem::replace(&mut self.ambient_variance, ty::Variance::Contravariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
Ok(a.clone())
}
}
/// When we encounter a binder like `for<..> fn(..)`, we actually have
/// to walk the `fn` value to find all the values bound by the `for`
/// (these are not explicitly present in the ty representation right
/// now). This visitor handles that: it descends the type, tracking
/// binder depth, and finds late-bound regions targeting the
/// `for<..`>. For each of those, it creates an entry in
/// `bound_region_scope`.
struct ScopeInstantiator<'me, 'tcx:'me> {
next_region: &'me mut dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
// The debruijn index of the scope we are instantiating.
target_index: ty::DebruijnIndex,
bound_region_scope: &'me mut BoundRegionScope<'tcx>,
}
impl<'me, 'tcx> TypeVisitor<'tcx> for ScopeInstantiator<'me, 'tcx> {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
self.target_index.shift_in(1);
t.super_visit_with(self);
self.target_index.shift_out(1);
false
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
let ScopeInstantiator {
bound_region_scope,
next_region,
..
} = self;
match r {
ty::ReLateBound(debruijn, br) if *debruijn == self.target_index => {
bound_region_scope
.map
.entry(*br)
.or_insert_with(|| next_region(*br));
}
_ => {}
}
false
}
}
/// The "type generalize" is used when handling inference variables.
///
/// The basic strategy for handling a constraint like `?A <: B` is to
/// apply a "generalization strategy" to the type `B` -- this replaces
/// all the lifetimes in the type `B` with fresh inference
/// variables. (You can read more about the strategy in this [blog
/// post].)
///
/// As an example, if we had `?A <: &'x u32`, we would generalize `&'x
/// u32` to `&'0 u32` where `'0` is a fresh variable. This becomes the
/// value of `A`. Finally, we relate `&'0 u32 <: &'x u32`, which
/// establishes `'0: 'x` as a constraint.
///
/// As a side-effect of this generalization procedure, we also replace
/// all the bound regions that we have traversed with concrete values,
/// so that the resulting generalized type is independent from the
/// scopes.
///
/// [blog post]: https://is.gd/0hKvIr
struct TypeGeneralizer<'me, 'gcx: 'tcx, 'tcx:'me, D>
where
D: TypeRelatingDelegate<'tcx> +'me,
{
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
delegate: &'me mut D,
/// After we generalize this type, we are going to relative it to
/// some other type. What will be the variance at this point?
ambient_variance: ty::Variance,
first_free_index: ty::DebruijnIndex,
/// The vid of the type variable that is in the process of being
/// instantiated. If we find this within the value we are folding,
/// that means we would have created a cyclic value.
for_vid_sub_root: ty::TyVid,
/// The universe of the type variable that is in the process of being
/// instantiated. If we find anything that this universe cannot name,
/// we reject the relation.
universe: ty::UniverseIndex,
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeGeneralizer<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::generalizer"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T>
|
{
debug!(
"TypeGeneralizer::relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"TypeGeneralizer::relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("TypeGeneralizer::relate_with_variance: r={:?}", r);
|
identifier_body
|
|
mod.rs
|
::Region<'tcx>;
/// Define the normalization strategy to use, eager or lazy.
fn normalization() -> NormalizationStrategy;
/// Enable some optimizations if we do not expect inference variables
/// in the RHS of the relation.
fn forbid_inference_vars() -> bool;
}
#[derive(Clone, Debug)]
struct ScopesAndKind<'tcx> {
scopes: Vec<BoundRegionScope<'tcx>>,
kind: Kind<'tcx>,
}
#[derive(Clone, Debug, Default)]
struct BoundRegionScope<'tcx> {
map: FxHashMap<ty::BoundRegion, ty::Region<'tcx>>,
}
#[derive(Copy, Clone)]
struct UniversallyQuantified(bool);
impl<'me, 'gcx, 'tcx, D> TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
pub fn new(
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
delegate: D,
ambient_variance: ty::Variance,
) -> Self {
Self {
infcx,
delegate,
ambient_variance,
a_scopes: vec![],
b_scopes: vec![],
}
}
fn ambient_covariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Covariant | ty::Variance::Invariant => true,
ty::Variance::Contravariant | ty::Variance::Bivariant => false,
}
}
fn ambient_contravariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Contravariant | ty::Variance::Invariant => true,
ty::Variance::Covariant | ty::Variance::Bivariant => false,
}
}
fn create_scope(
&mut self,
value: &ty::Binder<impl TypeFoldable<'tcx>>,
universally_quantified: UniversallyQuantified,
) -> BoundRegionScope<'tcx> {
let mut scope = BoundRegionScope::default();
// Create a callback that creates (via the delegate) either an
// existential or placeholder region as needed.
let mut next_region = {
let delegate = &mut self.delegate;
let mut lazy_universe = None;
move |br: ty::BoundRegion| {
if universally_quantified.0 {
// The first time this closure is called, create a
// new universe for the placeholders we will make
// from here out.
let universe = lazy_universe.unwrap_or_else(|| {
let universe = delegate.create_next_universe();
lazy_universe = Some(universe);
universe
});
let placeholder = ty::PlaceholderRegion { universe, name: br };
delegate.next_placeholder_region(placeholder)
} else {
delegate.next_existential_region_var()
}
}
};
value.skip_binder().visit_with(&mut ScopeInstantiator {
next_region: &mut next_region,
target_index: ty::INNERMOST,
bound_region_scope: &mut scope,
});
scope
}
/// When we encounter binders during the type traversal, we record
/// the value to substitute for each of the things contained in
/// that binder. (This will be either a universal placeholder or
/// an existential inference variable.) Given the debruijn index
/// `debruijn` (and name `br`) of some binder we have now
/// encountered, this routine finds the value that we instantiated
/// the region with; to do so, it indexes backwards into the list
/// of ambient scopes `scopes`.
fn lookup_bound_region(
debruijn: ty::DebruijnIndex,
br: &ty::BoundRegion,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
// The debruijn index is a "reverse index" into the
// scopes listing. So when we have INNERMOST (0), we
// want the *last* scope pushed, and so forth.
let debruijn_index = debruijn.index() - first_free_index.index();
let scope = &scopes[scopes.len() - debruijn_index - 1];
// Find this bound region in that scope to map to a
// particular region.
scope.map[br]
}
/// If `r` is a bound region, find the scope in which it is bound
/// (from `scopes`) and return the value that we instantiated it
/// with. Otherwise just return `r`.
fn replace_bound_region(
&self,
r: ty::Region<'tcx>,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
if let ty::ReLateBound(debruijn, br) = r {
Self::lookup_bound_region(*debruijn, br, first_free_index, scopes)
} else {
r
}
}
/// Push a new outlives requirement into our output set of
/// constraints.
fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>) {
debug!("push_outlives({:?}: {:?})", sup, sub);
self.delegate.push_outlives(sup, sub);
}
/// Relate a projection type and some value type lazily. This will always
/// succeed, but we push an additional `ProjectionEq` goal depending
/// on the value type:
/// - if the value type is any type `T` which is not a projection, we push
/// `ProjectionEq(projection = T)`.
/// - if the value type is another projection `other_projection`, we create
/// a new inference variable `?U` and push the two goals
/// `ProjectionEq(projection =?U)`, `ProjectionEq(other_projection =?U)`.
fn relate_projection_ty(
&mut self,
projection_ty: ty::ProjectionTy<'tcx>,
value_ty: ty::Ty<'tcx>
) -> Ty<'tcx> {
use crate::infer::type_variable::TypeVariableOrigin;
use crate::traits::WhereClause;
use syntax_pos::DUMMY_SP;
match value_ty.sty {
ty::Projection(other_projection_ty) => {
let var = self.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
self.relate_projection_ty(projection_ty, var);
self.relate_projection_ty(other_projection_ty, var);
var
}
_ => {
let projection = ty::ProjectionPredicate {
projection_ty,
ty: value_ty,
};
self.delegate.push_domain_goal(
DomainGoal::Holds(WhereClause::ProjectionEq(projection))
);
value_ty
}
}
}
/// Relate a type inference variable with a value type.
fn relate_ty_var(
&mut self,
vid: ty::TyVid,
value_ty: Ty<'tcx>
) -> RelateResult<'tcx, Ty<'tcx>> {
debug!("relate_ty_var(vid={:?}, value_ty={:?})", vid, value_ty);
match value_ty.sty {
ty::Infer(ty::TyVar(value_vid)) => {
// Two type variables: just equate them.
self.infcx.type_variables.borrow_mut().equate(vid, value_vid);
return Ok(value_ty);
}
ty::Projection(projection_ty)
if D::normalization() == NormalizationStrategy::Lazy =>
{
return Ok(self.relate_projection_ty(projection_ty, self.infcx.tcx.mk_var(vid)));
}
_ => (),
}
let generalized_ty = self.generalize_value(value_ty, vid)?;
debug!("relate_ty_var: generalized_ty = {:?}", generalized_ty);
if D::forbid_inference_vars() {
// In NLL, we don't have type inference variables
// floating around, so we can do this rather imprecise
// variant of the occurs-check.
assert!(!generalized_ty.has_infer_types());
}
self.infcx.type_variables.borrow_mut().instantiate(vid, generalized_ty);
// The generalized values we extract from `canonical_var_values` have
// been fully instantiated and hence the set of scopes we have
// doesn't matter -- just to be sure, put an empty vector
// in there.
let old_a_scopes = ::std::mem::replace(&mut self.a_scopes, vec![]);
// Relate the generalized kind to the original one.
let result = self.relate(&generalized_ty, &value_ty);
// Restore the old scopes now.
self.a_scopes = old_a_scopes;
debug!("relate_ty_var: complete, result = {:?}", result);
result
}
fn generalize_value<T: Relate<'tcx>>(
&mut self,
value: T,
for_vid: ty::TyVid
) -> RelateResult<'tcx, T> {
let universe = self.infcx.probe_ty_var(for_vid).unwrap_err();
let mut generalizer = TypeGeneralizer {
infcx: self.infcx,
delegate: &mut self.delegate,
first_free_index: ty::INNERMOST,
ambient_variance: self.ambient_variance,
for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
universe,
};
generalizer.relate(&value, &value)
}
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::subtype"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T> {
debug!(
"relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("relate_with_variance: r={:?}", r);
Ok(r)
}
fn tys(&mut self, a: Ty<'tcx>, mut b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
let a = self.infcx.shallow_resolve(a);
if!D::forbid_inference_vars() {
b = self.infcx.shallow_resolve(b);
}
match (&a.sty, &b.sty) {
(_, &ty::Infer(ty::TyVar(vid))) => {
if D::forbid_inference_vars() {
// Forbid inference variables in the RHS.
bug!("unexpected inference var {:?}", b)
} else {
self.relate_ty_var(vid, a)
}
}
(&ty::Infer(ty::TyVar(vid)), _) => self.relate_ty_var(vid, b),
(&ty::Projection(projection_ty), _)
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, b))
}
(_, &ty::Projection(projection_ty))
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, a))
}
_ => {
debug!(
"tys(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
// Will also handle unification of `IntVar` and `FloatVar`.
self.infcx.super_combine_tys(self, a, b)
}
}
}
fn regions(
&mut self,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Region<'tcx>> {
debug!(
"regions(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
let v_a = self.replace_bound_region(a, ty::INNERMOST, &self.a_scopes);
let v_b = self.replace_bound_region(b, ty::INNERMOST, &self.b_scopes);
debug!("regions: v_a = {:?}", v_a);
debug!("regions: v_b = {:?}", v_b);
if self.ambient_covariance() {
// Covariance: a <= b. Hence, `b: a`.
self.push_outlives(v_b, v_a);
}
if self.ambient_contravariance() {
// Contravariant: b <= a. Hence, `a: b`.
self.push_outlives(v_a, v_b);
}
Ok(a)
}
fn binders<T>(
&mut self,
a: &ty::Binder<T>,
b: &ty::Binder<T>,
) -> RelateResult<'tcx, ty::Binder<T>>
where
T: Relate<'tcx>,
{
// We want that
//
// ```
// for<'a> fn(&'a u32) -> &'a u32 <:
// fn(&'b u32) -> &'b u32
// ```
//
// but not
//
// ```
// fn(&'a u32) -> &'a u32 <:
// for<'b> fn(&'b u32) -> &'b u32
// ```
//
// We therefore proceed as follows:
//
// - Instantiate binders on `b` universally, yielding a universe U1.
// - Instantiate binders on `a` existentially in U1.
debug!(
"binders({:?}: {:?}, ambient_variance={:?})",
a, b, self.ambient_variance
);
if self.ambient_covariance() {
// Covariance, so we want `for<..> A <: for<..> B` --
// therefore we compare any instantiation of A (i.e., A
// instantiated with existentials) against every
// instantiation of B (i.e., B instantiated with
// universals).
let b_scope = self.create_scope(b, UniversallyQuantified(true));
let a_scope = self.create_scope(a, UniversallyQuantified(false));
|
debug!("binders: b_scope = {:?} (universal)", b_scope);
self.b_scopes.push(b_scope);
self.a_scopes.push(a_scope);
// Reset the ambient variance to covariant. This is needed
// to correctly handle cases like
//
// for<'a> fn(&'a u32, &'a u3) == for<'b, 'c> fn(&'b u32, &'c u32)
//
// Somewhat surprisingly, these two types are actually
// **equal**, even though the one on the right looks more
// polymorphic. The reason is due to subtyping. To see it,
// consider that each function can call the other:
//
// - The left function can call the right with `'b` and
// `'c` both equal to `'a`
//
// - The right function can call the left with `'a` set to
// `{P}`, where P is the point in the CFG where the call
// itself occurs. Note that `'b` and `'c` must both
// include P. At the point, the call works because of
// subtyping (i.e., `&'b u32 <: &{P} u32`).
let variance = ::std::mem::replace(&mut self.ambient_variance, ty::Variance::Covariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
if self.ambient_contravariance() {
// Contravariance, so we want `for<..> A :> for<..> B`
// -- therefore we compare every instantiation of A (i.e.,
// A instantiated with universals) against any
// instantiation of B (i.e., B instantiated with
// existentials). Opposite of above.
let a_scope = self.create_scope(a, UniversallyQuantified(true));
let b_scope = self.create_scope(b, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (universal)", a_scope);
debug!("binders: b_scope = {:?} (existential)", b_scope);
self.a_scopes.push(a_scope);
self.b_scopes.push(b_scope);
// Reset ambient variance to contravariance. See the
// covariant case above for an explanation.
let variance =
::std::mem::replace(&mut self.ambient_variance, ty::Variance::Contravariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
Ok(a.clone())
}
}
/// When we encounter a binder like `for<..> fn(..)`, we actually have
/// to walk the `fn` value to find all the values bound by the `for`
/// (these are not explicitly present in the ty representation right
/// now). This visitor handles that: it descends the type, tracking
/// binder depth, and finds late-bound regions targeting the
/// `for<..`>. For each of those, it creates an entry in
/// `bound_region_scope`.
struct ScopeInstantiator<'me, 'tcx:'me> {
next_region: &'me mut dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
// The debruijn index of the scope we are instantiating.
target_index: ty::DebruijnIndex,
bound_region_scope: &'me mut BoundRegionScope<'tcx>,
}
impl<'me, 'tcx> TypeVisitor<'tcx> for ScopeInstantiator<'me, 'tcx> {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
self.target_index.shift_in(1);
t.super_visit_with(self);
self.target_index.shift_out(1);
false
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
let ScopeInstantiator {
bound_region_scope,
next_region,
..
} = self;
match r {
ty::ReLateBound(debruijn, br) if *debruijn == self.target_index => {
bound_region_scope
.map
.entry(*br)
.or_insert_with(|| next_region(*br));
}
_ => {}
}
false
}
}
/// The "
|
debug!("binders: a_scope = {:?} (existential)", a_scope);
|
random_line_split
|
mod.rs
|
) -> RelateResult<'tcx, Ty<'tcx>> {
debug!("relate_ty_var(vid={:?}, value_ty={:?})", vid, value_ty);
match value_ty.sty {
ty::Infer(ty::TyVar(value_vid)) => {
// Two type variables: just equate them.
self.infcx.type_variables.borrow_mut().equate(vid, value_vid);
return Ok(value_ty);
}
ty::Projection(projection_ty)
if D::normalization() == NormalizationStrategy::Lazy =>
{
return Ok(self.relate_projection_ty(projection_ty, self.infcx.tcx.mk_var(vid)));
}
_ => (),
}
let generalized_ty = self.generalize_value(value_ty, vid)?;
debug!("relate_ty_var: generalized_ty = {:?}", generalized_ty);
if D::forbid_inference_vars() {
// In NLL, we don't have type inference variables
// floating around, so we can do this rather imprecise
// variant of the occurs-check.
assert!(!generalized_ty.has_infer_types());
}
self.infcx.type_variables.borrow_mut().instantiate(vid, generalized_ty);
// The generalized values we extract from `canonical_var_values` have
// been fully instantiated and hence the set of scopes we have
// doesn't matter -- just to be sure, put an empty vector
// in there.
let old_a_scopes = ::std::mem::replace(&mut self.a_scopes, vec![]);
// Relate the generalized kind to the original one.
let result = self.relate(&generalized_ty, &value_ty);
// Restore the old scopes now.
self.a_scopes = old_a_scopes;
debug!("relate_ty_var: complete, result = {:?}", result);
result
}
fn generalize_value<T: Relate<'tcx>>(
&mut self,
value: T,
for_vid: ty::TyVid
) -> RelateResult<'tcx, T> {
let universe = self.infcx.probe_ty_var(for_vid).unwrap_err();
let mut generalizer = TypeGeneralizer {
infcx: self.infcx,
delegate: &mut self.delegate,
first_free_index: ty::INNERMOST,
ambient_variance: self.ambient_variance,
for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
universe,
};
generalizer.relate(&value, &value)
}
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::subtype"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T> {
debug!(
"relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("relate_with_variance: r={:?}", r);
Ok(r)
}
fn tys(&mut self, a: Ty<'tcx>, mut b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
let a = self.infcx.shallow_resolve(a);
if!D::forbid_inference_vars() {
b = self.infcx.shallow_resolve(b);
}
match (&a.sty, &b.sty) {
(_, &ty::Infer(ty::TyVar(vid))) => {
if D::forbid_inference_vars() {
// Forbid inference variables in the RHS.
bug!("unexpected inference var {:?}", b)
} else {
self.relate_ty_var(vid, a)
}
}
(&ty::Infer(ty::TyVar(vid)), _) => self.relate_ty_var(vid, b),
(&ty::Projection(projection_ty), _)
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, b))
}
(_, &ty::Projection(projection_ty))
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, a))
}
_ => {
debug!(
"tys(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
// Will also handle unification of `IntVar` and `FloatVar`.
self.infcx.super_combine_tys(self, a, b)
}
}
}
fn regions(
&mut self,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Region<'tcx>> {
debug!(
"regions(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
let v_a = self.replace_bound_region(a, ty::INNERMOST, &self.a_scopes);
let v_b = self.replace_bound_region(b, ty::INNERMOST, &self.b_scopes);
debug!("regions: v_a = {:?}", v_a);
debug!("regions: v_b = {:?}", v_b);
if self.ambient_covariance() {
// Covariance: a <= b. Hence, `b: a`.
self.push_outlives(v_b, v_a);
}
if self.ambient_contravariance() {
// Contravariant: b <= a. Hence, `a: b`.
self.push_outlives(v_a, v_b);
}
Ok(a)
}
fn binders<T>(
&mut self,
a: &ty::Binder<T>,
b: &ty::Binder<T>,
) -> RelateResult<'tcx, ty::Binder<T>>
where
T: Relate<'tcx>,
{
// We want that
//
// ```
// for<'a> fn(&'a u32) -> &'a u32 <:
// fn(&'b u32) -> &'b u32
// ```
//
// but not
//
// ```
// fn(&'a u32) -> &'a u32 <:
// for<'b> fn(&'b u32) -> &'b u32
// ```
//
// We therefore proceed as follows:
//
// - Instantiate binders on `b` universally, yielding a universe U1.
// - Instantiate binders on `a` existentially in U1.
debug!(
"binders({:?}: {:?}, ambient_variance={:?})",
a, b, self.ambient_variance
);
if self.ambient_covariance() {
// Covariance, so we want `for<..> A <: for<..> B` --
// therefore we compare any instantiation of A (i.e., A
// instantiated with existentials) against every
// instantiation of B (i.e., B instantiated with
// universals).
let b_scope = self.create_scope(b, UniversallyQuantified(true));
let a_scope = self.create_scope(a, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (existential)", a_scope);
debug!("binders: b_scope = {:?} (universal)", b_scope);
self.b_scopes.push(b_scope);
self.a_scopes.push(a_scope);
// Reset the ambient variance to covariant. This is needed
// to correctly handle cases like
//
// for<'a> fn(&'a u32, &'a u3) == for<'b, 'c> fn(&'b u32, &'c u32)
//
// Somewhat surprisingly, these two types are actually
// **equal**, even though the one on the right looks more
// polymorphic. The reason is due to subtyping. To see it,
// consider that each function can call the other:
//
// - The left function can call the right with `'b` and
// `'c` both equal to `'a`
//
// - The right function can call the left with `'a` set to
// `{P}`, where P is the point in the CFG where the call
// itself occurs. Note that `'b` and `'c` must both
// include P. At the point, the call works because of
// subtyping (i.e., `&'b u32 <: &{P} u32`).
let variance = ::std::mem::replace(&mut self.ambient_variance, ty::Variance::Covariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
if self.ambient_contravariance() {
// Contravariance, so we want `for<..> A :> for<..> B`
// -- therefore we compare every instantiation of A (i.e.,
// A instantiated with universals) against any
// instantiation of B (i.e., B instantiated with
// existentials). Opposite of above.
let a_scope = self.create_scope(a, UniversallyQuantified(true));
let b_scope = self.create_scope(b, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (universal)", a_scope);
debug!("binders: b_scope = {:?} (existential)", b_scope);
self.a_scopes.push(a_scope);
self.b_scopes.push(b_scope);
// Reset ambient variance to contravariance. See the
// covariant case above for an explanation.
let variance =
::std::mem::replace(&mut self.ambient_variance, ty::Variance::Contravariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
Ok(a.clone())
}
}
/// When we encounter a binder like `for<..> fn(..)`, we actually have
/// to walk the `fn` value to find all the values bound by the `for`
/// (these are not explicitly present in the ty representation right
/// now). This visitor handles that: it descends the type, tracking
/// binder depth, and finds late-bound regions targeting the
/// `for<..`>. For each of those, it creates an entry in
/// `bound_region_scope`.
struct ScopeInstantiator<'me, 'tcx:'me> {
next_region: &'me mut dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
// The debruijn index of the scope we are instantiating.
target_index: ty::DebruijnIndex,
bound_region_scope: &'me mut BoundRegionScope<'tcx>,
}
impl<'me, 'tcx> TypeVisitor<'tcx> for ScopeInstantiator<'me, 'tcx> {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
self.target_index.shift_in(1);
t.super_visit_with(self);
self.target_index.shift_out(1);
false
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
let ScopeInstantiator {
bound_region_scope,
next_region,
..
} = self;
match r {
ty::ReLateBound(debruijn, br) if *debruijn == self.target_index => {
bound_region_scope
.map
.entry(*br)
.or_insert_with(|| next_region(*br));
}
_ => {}
}
false
}
}
/// The "type generalize" is used when handling inference variables.
///
/// The basic strategy for handling a constraint like `?A <: B` is to
/// apply a "generalization strategy" to the type `B` -- this replaces
/// all the lifetimes in the type `B` with fresh inference
/// variables. (You can read more about the strategy in this [blog
/// post].)
///
/// As an example, if we had `?A <: &'x u32`, we would generalize `&'x
/// u32` to `&'0 u32` where `'0` is a fresh variable. This becomes the
/// value of `A`. Finally, we relate `&'0 u32 <: &'x u32`, which
/// establishes `'0: 'x` as a constraint.
///
/// As a side-effect of this generalization procedure, we also replace
/// all the bound regions that we have traversed with concrete values,
/// so that the resulting generalized type is independent from the
/// scopes.
///
/// [blog post]: https://is.gd/0hKvIr
struct TypeGeneralizer<'me, 'gcx: 'tcx, 'tcx:'me, D>
where
D: TypeRelatingDelegate<'tcx> +'me,
{
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
delegate: &'me mut D,
/// After we generalize this type, we are going to relative it to
/// some other type. What will be the variance at this point?
ambient_variance: ty::Variance,
first_free_index: ty::DebruijnIndex,
/// The vid of the type variable that is in the process of being
/// instantiated. If we find this within the value we are folding,
/// that means we would have created a cyclic value.
for_vid_sub_root: ty::TyVid,
/// The universe of the type variable that is in the process of being
/// instantiated. If we find anything that this universe cannot name,
/// we reject the relation.
universe: ty::UniverseIndex,
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeGeneralizer<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::generalizer"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T> {
debug!(
"TypeGeneralizer::relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"TypeGeneralizer::relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("TypeGeneralizer::relate_with_variance: r={:?}", r);
Ok(r)
}
fn tys(&mut self, a: Ty<'tcx>, _: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
use crate::infer::type_variable::TypeVariableValue;
debug!("TypeGeneralizer::tys(a={:?})", a,);
match a.sty {
ty::Infer(ty::TyVar(_)) | ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_))
if D::forbid_inference_vars() =>
{
bug!(
"unexpected inference variable encountered in NLL generalization: {:?}",
a
);
}
ty::Infer(ty::TyVar(vid)) => {
let mut variables = self.infcx.type_variables.borrow_mut();
let vid = variables.root_var(vid);
let sub_vid = variables.sub_root_var(vid);
if sub_vid == self.for_vid_sub_root {
// If sub-roots are equal, then `for_vid` and
// `vid` are related via subtyping.
debug!("TypeGeneralizer::tys: occurs check failed");
return Err(TypeError::Mismatch);
} else {
match variables.probe(vid) {
TypeVariableValue::Known { value: u } => {
drop(variables);
self.relate(&u, &u)
}
TypeVariableValue::Unknown { universe: _universe } => {
if self.ambient_variance == ty::Bivariant {
// FIXME: we may need a WF predicate (related to #54105).
}
let origin = *variables.var_origin(vid);
// Replacing with a new variable in the universe `self.universe`,
// it will be unified later with the original type variable in
// the universe `_universe`.
let new_var_id = variables.new_var(self.universe, false, origin);
let u = self.tcx().mk_var(new_var_id);
debug!(
"generalize: replacing original vid={:?} with new={:?}",
vid,
u
);
return Ok(u);
}
}
}
}
ty::Infer(ty::IntVar(_)) |
ty::Infer(ty::FloatVar(_)) => {
// No matter what mode we are in,
// integer/floating-point types must be equal to be
// relatable.
Ok(a)
}
ty::Placeholder(placeholder) => {
if self.universe.cannot_name(placeholder.universe)
|
{
debug!(
"TypeGeneralizer::tys: root universe {:?} cannot name\
placeholder in universe {:?}",
self.universe,
placeholder.universe
);
Err(TypeError::Mismatch)
}
|
conditional_block
|
|
mod.rs
|
{
Lazy,
Eager,
}
pub struct TypeRelating<'me, 'gcx: 'tcx, 'tcx:'me, D>
where
D: TypeRelatingDelegate<'tcx>,
{
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
/// Callback to use when we deduce an outlives relationship
delegate: D,
/// How are we relating `a` and `b`?
///
/// - covariant means `a <: b`
/// - contravariant means `b <: a`
/// - invariant means `a == b
/// - bivariant means that it doesn't matter
ambient_variance: ty::Variance,
/// When we pass through a set of binders (e.g., when looking into
/// a `fn` type), we push a new bound region scope onto here. This
/// will contain the instantiated region for each region in those
/// binders. When we then encounter a `ReLateBound(d, br)`, we can
/// use the debruijn index `d` to find the right scope, and then
/// bound region name `br` to find the specific instantiation from
/// within that scope. See `replace_bound_region`.
///
/// This field stores the instantiations for late-bound regions in
/// the `a` type.
a_scopes: Vec<BoundRegionScope<'tcx>>,
/// Same as `a_scopes`, but for the `b` type.
b_scopes: Vec<BoundRegionScope<'tcx>>,
}
pub trait TypeRelatingDelegate<'tcx> {
/// Push a constraint `sup: sub` -- this constraint must be
/// satisfied for the two types to be related. `sub` and `sup` may
/// be regions from the type or new variables created through the
/// delegate.
fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>);
/// Push a domain goal that will need to be proved for the two types to
/// be related. Used for lazy normalization.
fn push_domain_goal(&mut self, domain_goal: DomainGoal<'tcx>);
/// Creates a new universe index. Used when instantiating placeholders.
fn create_next_universe(&mut self) -> ty::UniverseIndex;
/// Creates a new region variable representing a higher-ranked
/// region that is instantiated existentially. This creates an
/// inference variable, typically.
///
/// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
/// we will invoke this method to instantiate `'a` with an
/// inference variable (though `'b` would be instantiated first,
/// as a placeholder).
fn next_existential_region_var(&mut self) -> ty::Region<'tcx>;
/// Creates a new region variable representing a
/// higher-ranked region that is instantiated universally.
/// This creates a new region placeholder, typically.
///
/// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
/// we will invoke this method to instantiate `'b` with a
/// placeholder region.
fn next_placeholder_region(&mut self, placeholder: ty::PlaceholderRegion) -> ty::Region<'tcx>;
/// Creates a new existential region in the given universe. This
/// is used when handling subtyping and type variables -- if we
/// have that `?X <: Foo<'a>`, for example, we would instantiate
/// `?X` with a type like `Foo<'?0>` where `'?0` is a fresh
/// existential variable created by this function. We would then
/// relate `Foo<'?0>` with `Foo<'a>` (and probably add an outlives
/// relation stating that `'?0: 'a`).
fn generalize_existential(&mut self, universe: ty::UniverseIndex) -> ty::Region<'tcx>;
/// Define the normalization strategy to use, eager or lazy.
fn normalization() -> NormalizationStrategy;
/// Enable some optimizations if we do not expect inference variables
/// in the RHS of the relation.
fn forbid_inference_vars() -> bool;
}
#[derive(Clone, Debug)]
struct ScopesAndKind<'tcx> {
scopes: Vec<BoundRegionScope<'tcx>>,
kind: Kind<'tcx>,
}
#[derive(Clone, Debug, Default)]
struct BoundRegionScope<'tcx> {
map: FxHashMap<ty::BoundRegion, ty::Region<'tcx>>,
}
#[derive(Copy, Clone)]
struct UniversallyQuantified(bool);
impl<'me, 'gcx, 'tcx, D> TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
pub fn new(
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
delegate: D,
ambient_variance: ty::Variance,
) -> Self {
Self {
infcx,
delegate,
ambient_variance,
a_scopes: vec![],
b_scopes: vec![],
}
}
fn ambient_covariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Covariant | ty::Variance::Invariant => true,
ty::Variance::Contravariant | ty::Variance::Bivariant => false,
}
}
fn ambient_contravariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Contravariant | ty::Variance::Invariant => true,
ty::Variance::Covariant | ty::Variance::Bivariant => false,
}
}
fn create_scope(
&mut self,
value: &ty::Binder<impl TypeFoldable<'tcx>>,
universally_quantified: UniversallyQuantified,
) -> BoundRegionScope<'tcx> {
let mut scope = BoundRegionScope::default();
// Create a callback that creates (via the delegate) either an
// existential or placeholder region as needed.
let mut next_region = {
let delegate = &mut self.delegate;
let mut lazy_universe = None;
move |br: ty::BoundRegion| {
if universally_quantified.0 {
// The first time this closure is called, create a
// new universe for the placeholders we will make
// from here out.
let universe = lazy_universe.unwrap_or_else(|| {
let universe = delegate.create_next_universe();
lazy_universe = Some(universe);
universe
});
let placeholder = ty::PlaceholderRegion { universe, name: br };
delegate.next_placeholder_region(placeholder)
} else {
delegate.next_existential_region_var()
}
}
};
value.skip_binder().visit_with(&mut ScopeInstantiator {
next_region: &mut next_region,
target_index: ty::INNERMOST,
bound_region_scope: &mut scope,
});
scope
}
/// When we encounter binders during the type traversal, we record
/// the value to substitute for each of the things contained in
/// that binder. (This will be either a universal placeholder or
/// an existential inference variable.) Given the debruijn index
/// `debruijn` (and name `br`) of some binder we have now
/// encountered, this routine finds the value that we instantiated
/// the region with; to do so, it indexes backwards into the list
/// of ambient scopes `scopes`.
fn lookup_bound_region(
debruijn: ty::DebruijnIndex,
br: &ty::BoundRegion,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
// The debruijn index is a "reverse index" into the
// scopes listing. So when we have INNERMOST (0), we
// want the *last* scope pushed, and so forth.
let debruijn_index = debruijn.index() - first_free_index.index();
let scope = &scopes[scopes.len() - debruijn_index - 1];
// Find this bound region in that scope to map to a
// particular region.
scope.map[br]
}
/// If `r` is a bound region, find the scope in which it is bound
/// (from `scopes`) and return the value that we instantiated it
/// with. Otherwise just return `r`.
fn replace_bound_region(
&self,
r: ty::Region<'tcx>,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
if let ty::ReLateBound(debruijn, br) = r {
Self::lookup_bound_region(*debruijn, br, first_free_index, scopes)
} else {
r
}
}
/// Push a new outlives requirement into our output set of
/// constraints.
fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>) {
debug!("push_outlives({:?}: {:?})", sup, sub);
self.delegate.push_outlives(sup, sub);
}
/// Relate a projection type and some value type lazily. This will always
/// succeed, but we push an additional `ProjectionEq` goal depending
/// on the value type:
/// - if the value type is any type `T` which is not a projection, we push
/// `ProjectionEq(projection = T)`.
/// - if the value type is another projection `other_projection`, we create
/// a new inference variable `?U` and push the two goals
/// `ProjectionEq(projection =?U)`, `ProjectionEq(other_projection =?U)`.
fn relate_projection_ty(
&mut self,
projection_ty: ty::ProjectionTy<'tcx>,
value_ty: ty::Ty<'tcx>
) -> Ty<'tcx> {
use crate::infer::type_variable::TypeVariableOrigin;
use crate::traits::WhereClause;
use syntax_pos::DUMMY_SP;
match value_ty.sty {
ty::Projection(other_projection_ty) => {
let var = self.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
self.relate_projection_ty(projection_ty, var);
self.relate_projection_ty(other_projection_ty, var);
var
}
_ => {
let projection = ty::ProjectionPredicate {
projection_ty,
ty: value_ty,
};
self.delegate.push_domain_goal(
DomainGoal::Holds(WhereClause::ProjectionEq(projection))
);
value_ty
}
}
}
/// Relate a type inference variable with a value type.
fn relate_ty_var(
&mut self,
vid: ty::TyVid,
value_ty: Ty<'tcx>
) -> RelateResult<'tcx, Ty<'tcx>> {
debug!("relate_ty_var(vid={:?}, value_ty={:?})", vid, value_ty);
match value_ty.sty {
ty::Infer(ty::TyVar(value_vid)) => {
// Two type variables: just equate them.
self.infcx.type_variables.borrow_mut().equate(vid, value_vid);
return Ok(value_ty);
}
ty::Projection(projection_ty)
if D::normalization() == NormalizationStrategy::Lazy =>
{
return Ok(self.relate_projection_ty(projection_ty, self.infcx.tcx.mk_var(vid)));
}
_ => (),
}
let generalized_ty = self.generalize_value(value_ty, vid)?;
debug!("relate_ty_var: generalized_ty = {:?}", generalized_ty);
if D::forbid_inference_vars() {
// In NLL, we don't have type inference variables
// floating around, so we can do this rather imprecise
// variant of the occurs-check.
assert!(!generalized_ty.has_infer_types());
}
self.infcx.type_variables.borrow_mut().instantiate(vid, generalized_ty);
// The generalized values we extract from `canonical_var_values` have
// been fully instantiated and hence the set of scopes we have
// doesn't matter -- just to be sure, put an empty vector
// in there.
let old_a_scopes = ::std::mem::replace(&mut self.a_scopes, vec![]);
// Relate the generalized kind to the original one.
let result = self.relate(&generalized_ty, &value_ty);
// Restore the old scopes now.
self.a_scopes = old_a_scopes;
debug!("relate_ty_var: complete, result = {:?}", result);
result
}
fn generalize_value<T: Relate<'tcx>>(
&mut self,
value: T,
for_vid: ty::TyVid
) -> RelateResult<'tcx, T> {
let universe = self.infcx.probe_ty_var(for_vid).unwrap_err();
let mut generalizer = TypeGeneralizer {
infcx: self.infcx,
delegate: &mut self.delegate,
first_free_index: ty::INNERMOST,
ambient_variance: self.ambient_variance,
for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
universe,
};
generalizer.relate(&value, &value)
}
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::subtype"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T> {
debug!(
"relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("relate_with_variance: r={:?}", r);
Ok(r)
}
fn tys(&mut self, a: Ty<'tcx>, mut b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
let a = self.infcx.shallow_resolve(a);
if!D::forbid_inference_vars() {
b = self.infcx.shallow_resolve(b);
}
match (&a.sty, &b.sty) {
(_, &ty::Infer(ty::TyVar(vid))) => {
if D::forbid_inference_vars() {
// Forbid inference variables in the RHS.
bug!("unexpected inference var {:?}", b)
} else {
self.relate_ty_var(vid, a)
}
}
(&ty::Infer(ty::TyVar(vid)), _) => self.relate_ty_var(vid, b),
(&ty::Projection(projection_ty), _)
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, b))
}
(_, &ty::Projection(projection_ty))
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, a))
}
_ => {
debug!(
"tys(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
// Will also handle unification of `IntVar` and `FloatVar`.
self.infcx.super_combine_tys(self, a, b)
}
}
}
fn regions(
&mut self,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Region<'tcx>> {
debug!(
"regions(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
let v_a = self.replace_bound_region(a, ty::INNERMOST, &self.a_scopes);
let v_b = self.replace_bound_region(b, ty::INNERMOST, &self.b_scopes);
debug!("regions: v_a = {:?}", v_a);
debug!("regions: v_b = {:?}", v_b);
if self.ambient_covariance() {
// Covariance: a <= b. Hence, `b: a`.
self.push_outlives(v_b, v_a);
}
if self.ambient_contravariance() {
// Contravariant: b <= a. Hence, `a: b`.
self.push_outlives(v_a, v_b);
}
Ok(a)
}
fn binders<T>(
&mut self,
a: &ty::Binder<T>,
b: &ty::Binder<T>,
) -> RelateResult<'tcx, ty::Binder<T>>
where
T: Relate<'tcx>,
{
// We want that
//
// ```
// for<'a> fn(&'a u32) -> &'a u32 <:
// fn(&'b u32) -> &'b u32
// ```
//
// but not
//
// ```
// fn(&'a u32) -> &'a u32 <:
// for<'b> fn(&'b u32) -> &'b u32
// ```
//
// We therefore proceed as follows:
//
// - Instantiate binders on `b` universally, yielding a universe U1.
// - Instantiate binders on `a` existentially in U1.
debug!(
"binders({:?}: {:?}, ambient_variance={:?})",
a, b, self.ambient_variance
);
if self.ambient_covariance() {
// Covariance, so we want `for<..> A <: for<..> B` --
// therefore we compare any instantiation of A (i.e., A
// instantiated with existentials) against every
// instantiation of B (i.e., B instantiated with
// universals).
let b_scope = self.create_scope(b, UniversallyQuantified(true));
let a_scope = self.create_scope(a, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (existential)", a_scope);
debug!("binders: b_scope = {:?} (universal)", b_scope);
self.b_scopes.push(b_scope);
self.a_scopes.push(a_scope);
// Reset the ambient variance to covariant. This is needed
// to correctly handle cases like
//
// for<'a> fn(&'a u32, &'a u3) == for<'b, 'c> fn(&'b u32, &'c u32)
//
// Somewhat surprisingly, these two types are actually
// **equal**, even though the one on the right looks more
// polymorphic. The reason is due to subtyping. To see it,
// consider that each function can call the other:
//
// - The left function can call the right with `'b` and
// `'c` both equal to `'a`
//
// - The right function can call the left with `'a` set to
// `{P}`, where P is the point in the CFG where the call
// itself occurs. Note that `'b` and `'c` must both
// include P. At the point, the call works because of
// subtyping (i.e., `&'b u32 <: &{P} u32`).
let variance = ::std::mem::replace(&mut self.ambient_variance, ty::Variance::Covariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
if self.ambient_contravariance() {
// Contravariance, so we want `for<..> A :> for<..> B`
// -- therefore we compare every instantiation of A (i.e.,
// A instantiated with universals) against any
// instantiation of B (i.e., B instantiated with
|
NormalizationStrategy
|
identifier_name
|
|
net.rs
|
//! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, TypeId};
use std::fmt;
use std::io::{self, ErrorKind, Read, Write};
use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener, Shutdown};
use std::mem;
#[cfg(feature = "openssl")]
pub use self::openssl::Openssl;
use typeable::Typeable;
use traitobject;
/// The write-status indicating headers have not been written.
pub enum Fresh {}
/// The write-status indicating headers have been written.
pub enum Streaming {}
/// An abstraction to listen for connections on a certain port.
pub trait NetworkListener: Clone {
/// The stream produced for each connection.
type Stream: NetworkStream + Send + Clone;
/// Listens on a socket.
//fn listen<To: ToSocketAddrs>(&mut self, addr: To) -> io::Result<Self::Acceptor>;
/// Returns an iterator of streams.
fn accept(&mut self) -> ::Result<Self::Stream>;
/// Get the address this Listener ended up listening on.
fn local_addr(&mut self) -> io::Result<SocketAddr>;
/// Closes the Acceptor, so no more incoming connections will be handled.
// fn close(&mut self) -> io::Result<()>;
/// Returns an iterator over incoming connections.
fn incoming(&mut self) -> NetworkConnections<Self> {
NetworkConnections(self)
}
}
/// An iterator wrapper over a NetworkAcceptor.
pub struct NetworkConnections<'a, N: NetworkListener + 'a>(&'a mut N);
impl<'a, N: NetworkListener + 'a> Iterator for NetworkConnections<'a, N> {
type Item = ::Result<N::Stream>;
fn next(&mut self) -> Option<::Result<N::Stream>> {
Some(self.0.accept())
}
}
/// An abstraction over streams that a Server can utilize.
pub trait NetworkStream: Read + Write + Any + Send + Typeable {
/// Get the remote address of the underlying connection.
fn peer_addr(&mut self) -> io::Result<SocketAddr>;
/// This will be called when Stream should no longer be kept alive.
#[inline]
fn close(&mut self, _how: Shutdown) -> io::Result<()> {
Ok(())
}
}
/// A connector creates a NetworkStream.
pub trait NetworkConnector {
/// Type of Stream to create
type Stream: Into<Box<NetworkStream + Send>>;
/// Connect to a remote address.
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream>;
}
impl<T: NetworkStream + Send> From<T> for Box<NetworkStream + Send> {
fn from(s: T) -> Box<NetworkStream + Send> {
Box::new(s)
}
}
impl fmt::Debug for Box<NetworkStream + Send> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad("Box<NetworkStream>")
}
}
impl NetworkStream + Send {
unsafe fn downcast_ref_unchecked<T:'static>(&self) -> &T {
mem::transmute(traitobject::data(self))
}
unsafe fn downcast_mut_unchecked<T:'static>(&mut self) -> &mut T {
mem::transmute(traitobject::data_mut(self))
}
unsafe fn downcast_unchecked<T:'static>(self: Box<NetworkStream + Send>) -> Box<T> {
let raw: *mut NetworkStream = mem::transmute(self);
mem::transmute(traitobject::data_mut(raw))
}
}
impl NetworkStream + Send {
/// Is the underlying type in this trait object a T?
#[inline]
pub fn is<T: Any>(&self) -> bool {
(*self).get_type() == TypeId::of::<T>()
}
/// If the underlying type is T, get a reference to the contained data.
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
Some(unsafe { self.downcast_ref_unchecked() })
} else {
None
}
}
/// If the underlying type is T, get a mutable reference to the contained
/// data.
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
Some(unsafe { self.downcast_mut_unchecked() })
} else {
None
}
}
/// If the underlying type is T, extract it.
#[inline]
pub fn downcast<T: Any>(self: Box<NetworkStream + Send>)
-> Result<Box<T>, Box<NetworkStream + Send>> {
if self.is::<T>() {
Ok(unsafe { self.downcast_unchecked() })
} else {
Err(self)
}
}
}
/// A `NetworkListener` for `HttpStream`s.
pub struct HttpListener(TcpListener);
impl Clone for HttpListener {
#[inline]
fn clone(&self) -> HttpListener {
HttpListener(self.0.try_clone().unwrap())
}
}
impl HttpListener {
/// Start listening to an address over HTTP.
pub fn new<To: ToSocketAddrs>(addr: To) -> ::Result<HttpListener> {
Ok(HttpListener(try!(TcpListener::bind(addr))))
}
}
impl NetworkListener for HttpListener {
type Stream = HttpStream;
#[inline]
fn accept(&mut self) -> ::Result<HttpStream> {
Ok(HttpStream(try!(self.0.accept()).0))
}
#[inline]
fn local_addr(&mut self) -> io::Result<SocketAddr> {
self.0.local_addr()
}
}
/// A wrapper around a TcpStream.
pub struct HttpStream(pub TcpStream);
impl Clone for HttpStream {
#[inline]
fn clone(&self) -> HttpStream {
HttpStream(self.0.try_clone().unwrap())
}
}
impl fmt::Debug for HttpStream {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("HttpStream(_)")
}
}
impl Read for HttpStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl Write for HttpStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.0.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
#[cfg(windows)]
impl ::std::os::windows::io::AsRawSocket for HttpStream {
fn as_raw_socket(&self) -> ::std::os::windows::io::RawSocket {
self.0.as_raw_socket()
}
}
#[cfg(unix)]
impl ::std::os::unix::io::AsRawFd for HttpStream {
fn as_raw_fd(&self) -> i32 {
self.0.as_raw_fd()
}
}
impl NetworkStream for HttpStream {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
self.0.peer_addr()
}
#[inline]
fn close(&mut self, how: Shutdown) -> io::Result<()> {
match self.0.shutdown(how) {
Ok(_) => Ok(()),
// see https://github.com/hyperium/hyper/issues/508
Err(ref e) if e.kind() == ErrorKind::NotConnected => Ok(()),
err => err
}
}
}
/// A connector that will produce HttpStreams.
#[derive(Debug, Clone, Default)]
pub struct HttpConnector;
impl NetworkConnector for HttpConnector {
type Stream = HttpStream;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
let addr = &(host, port);
Ok(try!(match scheme {
"http" => {
debug!("http scheme");
Ok(HttpStream(try!(TcpStream::connect(addr))))
},
_ => {
Err(io::Error::new(io::ErrorKind::InvalidInput,
"Invalid scheme for Http"))
}
}))
}
}
/// An abstraction to allow any SSL implementation to be used with HttpsStreams.
pub trait Ssl {
/// The protected stream.
type Stream: NetworkStream + Send + Clone;
/// Wrap a client stream with SSL.
fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>;
/// Wrap a server stream with SSL.
fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream>;
}
/// A stream over the HTTP protocol, possibly protected by SSL.
#[derive(Debug, Clone)]
pub enum HttpsStream<S: NetworkStream> {
/// A plain text stream.
Http(HttpStream),
/// A stream protected by SSL.
Https(S)
}
impl<S: NetworkStream> Read for HttpsStream<S> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.read(buf),
HttpsStream::Https(ref mut s) => s.read(buf)
}
}
}
impl<S: NetworkStream> Write for HttpsStream<S> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.write(msg),
HttpsStream::Https(ref mut s) => s.write(msg)
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match *self {
HttpsStream::Http(ref mut s) => s.flush(),
HttpsStream::Https(ref mut s) => s.flush()
}
}
}
impl<S: NetworkStream> NetworkStream for HttpsStream<S> {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
match *self {
HttpsStream::Http(ref mut s) => s.peer_addr(),
HttpsStream::Https(ref mut s) => s.peer_addr()
}
}
#[inline]
fn close(&mut self, how: Shutdown) -> io::Result<()> {
match *self {
HttpsStream::Http(ref mut s) => s.close(how),
HttpsStream::Https(ref mut s) => s.close(how)
}
}
}
/// A Http Listener over SSL.
#[derive(Clone)]
pub struct HttpsListener<S: Ssl> {
listener: HttpListener,
ssl: S,
}
impl<S: Ssl> HttpsListener<S> {
/// Start listening to an address over HTTPS.
pub fn new<To: ToSocketAddrs>(addr: To, ssl: S) -> ::Result<HttpsListener<S>> {
HttpListener::new(addr).map(|l| HttpsListener {
listener: l,
ssl: ssl
})
}
}
impl<S: Ssl + Clone> NetworkListener for HttpsListener<S> {
type Stream = S::Stream;
#[inline]
fn accept(&mut self) -> ::Result<S::Stream> {
self.listener.accept().and_then(|s| self.ssl.wrap_server(s))
}
#[inline]
fn local_addr(&mut self) -> io::Result<SocketAddr> {
self.listener.local_addr()
}
}
/// A connector that can protect HTTP streams using SSL.
#[derive(Debug, Default)]
pub struct
|
<S: Ssl> {
ssl: S
}
impl<S: Ssl> HttpsConnector<S> {
/// Create a new connector using the provided SSL implementation.
pub fn new(s: S) -> HttpsConnector<S> {
HttpsConnector { ssl: s }
}
}
impl<S: Ssl> NetworkConnector for HttpsConnector<S> {
type Stream = HttpsStream<S::Stream>;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> {
let addr = &(host, port);
if scheme == "https" {
debug!("https scheme");
let stream = HttpStream(try!(TcpStream::connect(addr)));
self.ssl.wrap_client(stream, host).map(HttpsStream::Https)
} else {
HttpConnector.connect(host, port, scheme).map(HttpsStream::Http)
}
}
}
#[cfg(not(feature = "openssl"))]
#[doc(hidden)]
pub type DefaultConnector = HttpConnector;
#[cfg(feature = "openssl")]
#[doc(hidden)]
pub type DefaultConnector = HttpsConnector<self::openssl::Openssl>;
#[cfg(feature = "openssl")]
mod openssl {
use std::io;
use std::net::{SocketAddr, Shutdown};
use std::path::Path;
use std::sync::Arc;
use openssl::ssl::{Ssl, SslContext, SslStream, SslMethod, SSL_VERIFY_NONE};
use openssl::ssl::error::StreamError as SslIoError;
use openssl::ssl::error::SslError;
use openssl::x509::X509FileType;
use super::{NetworkStream, HttpStream};
/// An implementation of `Ssl` for OpenSSL.
///
/// # Example
///
/// ```no_run
/// use hyper::Server;
/// use hyper::net::Openssl;
///
/// let ssl = Openssl::with_cert_and_key("/home/foo/cert", "/home/foo/key").unwrap();
/// Server::https("0.0.0.0:443", ssl).unwrap();
/// ```
///
/// For complete control, create a `SslContext` with the options you desire
/// and then create `Openssl { context: ctx }
#[derive(Debug, Clone)]
pub struct Openssl {
/// The `SslContext` from openssl crate.
pub context: Arc<SslContext>
}
impl Default for Openssl {
fn default() -> Openssl {
Openssl {
context: Arc::new(SslContext::new(SslMethod::Sslv23).unwrap_or_else(|e| {
// if we cannot create a SslContext, that's because of a
// serious problem. just crash.
panic!("{}", e)
}))
}
}
}
impl Openssl {
/// Ease creating an `Openssl` with a certificate and key.
pub fn with_cert_and_key<C, K>(cert: C, key: K) -> Result<Openssl, SslError>
where C: AsRef<Path>, K: AsRef<Path> {
let mut ctx = try!(SslContext::new(SslMethod::Sslv23));
try!(ctx.set_cipher_list("DEFAULT"));
try!(ctx.set_certificate_file(cert.as_ref(), X509FileType::PEM));
try!(ctx.set_private_key_file(key.as_ref(), X509FileType::PEM));
ctx.set_verify(SSL_VERIFY_NONE, None);
Ok(Openssl { context: Arc::new(ctx) })
}
}
impl super::Ssl for Openssl {
type Stream = SslStream<HttpStream>;
fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> {
let ssl = try!(Ssl::new(&self.context));
try!(ssl.set_hostname(host));
SslStream::connect(ssl, stream).map_err(From::from)
}
fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> {
match SslStream::accept(&*self.context, stream) {
Ok(ssl_stream) => Ok(ssl_stream),
Err(SslIoError(e)) => {
Err(io::Error::new(io::ErrorKind::ConnectionAborted, e).into())
},
Err(e) => Err(e.into())
}
}
}
impl<S: NetworkStream> NetworkStream for SslStream<S> {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
self.get_mut().peer_addr()
}
fn close(&mut self, how: Shutdown) -> io::Result<()> {
self.get_mut().close(how)
}
}
}
#[cfg(test)]
mod tests {
use mock::MockStream;
use super::{NetworkStream};
#[test]
fn test_downcast_box_stream() {
// FIXME: Use Type ascription
let stream: Box<NetworkStream + Send> = Box::new(MockStream::new());
let mock = stream.downcast::<MockStream>().ok().unwrap();
assert_eq!(mock, Box::new(MockStream::new()));
}
#[test]
fn test_downcast_unchecked_box_stream() {
// FIXME: Use Type ascription
let stream: Box<NetworkStream + Send> = Box::new(MockStream::new());
let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
assert_eq!(mock, Box::new(MockStream::new()));
}
}
|
HttpsConnector
|
identifier_name
|
net.rs
|
//! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, TypeId};
use std::fmt;
use std::io::{self, ErrorKind, Read, Write};
use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener, Shutdown};
use std::mem;
#[cfg(feature = "openssl")]
pub use self::openssl::Openssl;
use typeable::Typeable;
use traitobject;
/// The write-status indicating headers have not been written.
pub enum Fresh {}
/// The write-status indicating headers have been written.
pub enum Streaming {}
/// An abstraction to listen for connections on a certain port.
pub trait NetworkListener: Clone {
/// The stream produced for each connection.
type Stream: NetworkStream + Send + Clone;
/// Listens on a socket.
//fn listen<To: ToSocketAddrs>(&mut self, addr: To) -> io::Result<Self::Acceptor>;
/// Returns an iterator of streams.
fn accept(&mut self) -> ::Result<Self::Stream>;
/// Get the address this Listener ended up listening on.
fn local_addr(&mut self) -> io::Result<SocketAddr>;
/// Closes the Acceptor, so no more incoming connections will be handled.
// fn close(&mut self) -> io::Result<()>;
/// Returns an iterator over incoming connections.
fn incoming(&mut self) -> NetworkConnections<Self> {
NetworkConnections(self)
}
}
/// An iterator wrapper over a NetworkAcceptor.
pub struct NetworkConnections<'a, N: NetworkListener + 'a>(&'a mut N);
impl<'a, N: NetworkListener + 'a> Iterator for NetworkConnections<'a, N> {
type Item = ::Result<N::Stream>;
fn next(&mut self) -> Option<::Result<N::Stream>> {
Some(self.0.accept())
}
}
/// An abstraction over streams that a Server can utilize.
pub trait NetworkStream: Read + Write + Any + Send + Typeable {
/// Get the remote address of the underlying connection.
fn peer_addr(&mut self) -> io::Result<SocketAddr>;
/// This will be called when Stream should no longer be kept alive.
#[inline]
fn close(&mut self, _how: Shutdown) -> io::Result<()> {
Ok(())
}
}
/// A connector creates a NetworkStream.
pub trait NetworkConnector {
/// Type of Stream to create
type Stream: Into<Box<NetworkStream + Send>>;
/// Connect to a remote address.
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream>;
}
impl<T: NetworkStream + Send> From<T> for Box<NetworkStream + Send> {
fn from(s: T) -> Box<NetworkStream + Send> {
Box::new(s)
}
}
impl fmt::Debug for Box<NetworkStream + Send> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad("Box<NetworkStream>")
}
}
impl NetworkStream + Send {
unsafe fn downcast_ref_unchecked<T:'static>(&self) -> &T {
mem::transmute(traitobject::data(self))
}
unsafe fn downcast_mut_unchecked<T:'static>(&mut self) -> &mut T {
mem::transmute(traitobject::data_mut(self))
}
unsafe fn downcast_unchecked<T:'static>(self: Box<NetworkStream + Send>) -> Box<T> {
let raw: *mut NetworkStream = mem::transmute(self);
mem::transmute(traitobject::data_mut(raw))
}
}
impl NetworkStream + Send {
/// Is the underlying type in this trait object a T?
#[inline]
pub fn is<T: Any>(&self) -> bool {
(*self).get_type() == TypeId::of::<T>()
}
/// If the underlying type is T, get a reference to the contained data.
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
Some(unsafe { self.downcast_ref_unchecked() })
} else {
None
}
}
/// If the underlying type is T, get a mutable reference to the contained
/// data.
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
Some(unsafe { self.downcast_mut_unchecked() })
} else {
None
}
}
/// If the underlying type is T, extract it.
#[inline]
pub fn downcast<T: Any>(self: Box<NetworkStream + Send>)
-> Result<Box<T>, Box<NetworkStream + Send>> {
if self.is::<T>() {
Ok(unsafe { self.downcast_unchecked() })
} else {
Err(self)
}
}
}
/// A `NetworkListener` for `HttpStream`s.
pub struct HttpListener(TcpListener);
impl Clone for HttpListener {
#[inline]
fn clone(&self) -> HttpListener {
HttpListener(self.0.try_clone().unwrap())
}
}
impl HttpListener {
/// Start listening to an address over HTTP.
pub fn new<To: ToSocketAddrs>(addr: To) -> ::Result<HttpListener> {
Ok(HttpListener(try!(TcpListener::bind(addr))))
}
}
impl NetworkListener for HttpListener {
type Stream = HttpStream;
#[inline]
fn accept(&mut self) -> ::Result<HttpStream> {
Ok(HttpStream(try!(self.0.accept()).0))
}
#[inline]
fn local_addr(&mut self) -> io::Result<SocketAddr> {
self.0.local_addr()
}
}
/// A wrapper around a TcpStream.
pub struct HttpStream(pub TcpStream);
impl Clone for HttpStream {
#[inline]
fn clone(&self) -> HttpStream {
HttpStream(self.0.try_clone().unwrap())
}
}
impl fmt::Debug for HttpStream {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("HttpStream(_)")
}
}
impl Read for HttpStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl Write for HttpStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.0.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
#[cfg(windows)]
impl ::std::os::windows::io::AsRawSocket for HttpStream {
fn as_raw_socket(&self) -> ::std::os::windows::io::RawSocket {
self.0.as_raw_socket()
}
}
#[cfg(unix)]
impl ::std::os::unix::io::AsRawFd for HttpStream {
fn as_raw_fd(&self) -> i32 {
self.0.as_raw_fd()
}
}
impl NetworkStream for HttpStream {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
self.0.peer_addr()
}
#[inline]
fn close(&mut self, how: Shutdown) -> io::Result<()> {
match self.0.shutdown(how) {
Ok(_) => Ok(()),
// see https://github.com/hyperium/hyper/issues/508
Err(ref e) if e.kind() == ErrorKind::NotConnected => Ok(()),
err => err
}
}
}
/// A connector that will produce HttpStreams.
#[derive(Debug, Clone, Default)]
pub struct HttpConnector;
impl NetworkConnector for HttpConnector {
type Stream = HttpStream;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
let addr = &(host, port);
Ok(try!(match scheme {
"http" => {
debug!("http scheme");
Ok(HttpStream(try!(TcpStream::connect(addr))))
},
_ => {
Err(io::Error::new(io::ErrorKind::InvalidInput,
"Invalid scheme for Http"))
}
}))
}
}
/// An abstraction to allow any SSL implementation to be used with HttpsStreams.
pub trait Ssl {
/// The protected stream.
type Stream: NetworkStream + Send + Clone;
/// Wrap a client stream with SSL.
fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>;
/// Wrap a server stream with SSL.
fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream>;
}
/// A stream over the HTTP protocol, possibly protected by SSL.
#[derive(Debug, Clone)]
pub enum HttpsStream<S: NetworkStream> {
/// A plain text stream.
Http(HttpStream),
/// A stream protected by SSL.
Https(S)
}
impl<S: NetworkStream> Read for HttpsStream<S> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.read(buf),
HttpsStream::Https(ref mut s) => s.read(buf)
}
}
}
impl<S: NetworkStream> Write for HttpsStream<S> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.write(msg),
HttpsStream::Https(ref mut s) => s.write(msg)
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match *self {
HttpsStream::Http(ref mut s) => s.flush(),
HttpsStream::Https(ref mut s) => s.flush()
}
}
}
impl<S: NetworkStream> NetworkStream for HttpsStream<S> {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
match *self {
HttpsStream::Http(ref mut s) => s.peer_addr(),
HttpsStream::Https(ref mut s) => s.peer_addr()
}
}
#[inline]
fn close(&mut self, how: Shutdown) -> io::Result<()> {
match *self {
HttpsStream::Http(ref mut s) => s.close(how),
HttpsStream::Https(ref mut s) => s.close(how)
}
}
}
/// A Http Listener over SSL.
#[derive(Clone)]
pub struct HttpsListener<S: Ssl> {
listener: HttpListener,
ssl: S,
}
impl<S: Ssl> HttpsListener<S> {
/// Start listening to an address over HTTPS.
pub fn new<To: ToSocketAddrs>(addr: To, ssl: S) -> ::Result<HttpsListener<S>> {
HttpListener::new(addr).map(|l| HttpsListener {
listener: l,
ssl: ssl
})
}
}
impl<S: Ssl + Clone> NetworkListener for HttpsListener<S> {
type Stream = S::Stream;
#[inline]
fn accept(&mut self) -> ::Result<S::Stream> {
self.listener.accept().and_then(|s| self.ssl.wrap_server(s))
}
#[inline]
fn local_addr(&mut self) -> io::Result<SocketAddr> {
self.listener.local_addr()
}
}
/// A connector that can protect HTTP streams using SSL.
#[derive(Debug, Default)]
pub struct HttpsConnector<S: Ssl> {
ssl: S
}
impl<S: Ssl> HttpsConnector<S> {
/// Create a new connector using the provided SSL implementation.
pub fn new(s: S) -> HttpsConnector<S> {
HttpsConnector { ssl: s }
}
}
impl<S: Ssl> NetworkConnector for HttpsConnector<S> {
type Stream = HttpsStream<S::Stream>;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> {
let addr = &(host, port);
if scheme == "https" {
debug!("https scheme");
let stream = HttpStream(try!(TcpStream::connect(addr)));
self.ssl.wrap_client(stream, host).map(HttpsStream::Https)
} else {
HttpConnector.connect(host, port, scheme).map(HttpsStream::Http)
}
}
}
#[cfg(not(feature = "openssl"))]
#[doc(hidden)]
pub type DefaultConnector = HttpConnector;
#[cfg(feature = "openssl")]
#[doc(hidden)]
pub type DefaultConnector = HttpsConnector<self::openssl::Openssl>;
#[cfg(feature = "openssl")]
mod openssl {
use std::io;
use std::net::{SocketAddr, Shutdown};
use std::path::Path;
use std::sync::Arc;
use openssl::ssl::{Ssl, SslContext, SslStream, SslMethod, SSL_VERIFY_NONE};
use openssl::ssl::error::StreamError as SslIoError;
use openssl::ssl::error::SslError;
use openssl::x509::X509FileType;
use super::{NetworkStream, HttpStream};
/// An implementation of `Ssl` for OpenSSL.
///
/// # Example
///
/// ```no_run
/// use hyper::Server;
/// use hyper::net::Openssl;
///
/// let ssl = Openssl::with_cert_and_key("/home/foo/cert", "/home/foo/key").unwrap();
/// Server::https("0.0.0.0:443", ssl).unwrap();
/// ```
///
/// For complete control, create a `SslContext` with the options you desire
/// and then create `Openssl { context: ctx }
#[derive(Debug, Clone)]
pub struct Openssl {
/// The `SslContext` from openssl crate.
pub context: Arc<SslContext>
}
impl Default for Openssl {
fn default() -> Openssl {
Openssl {
context: Arc::new(SslContext::new(SslMethod::Sslv23).unwrap_or_else(|e| {
// if we cannot create a SslContext, that's because of a
// serious problem. just crash.
panic!("{}", e)
}))
}
}
}
impl Openssl {
/// Ease creating an `Openssl` with a certificate and key.
pub fn with_cert_and_key<C, K>(cert: C, key: K) -> Result<Openssl, SslError>
where C: AsRef<Path>, K: AsRef<Path> {
let mut ctx = try!(SslContext::new(SslMethod::Sslv23));
try!(ctx.set_cipher_list("DEFAULT"));
try!(ctx.set_certificate_file(cert.as_ref(), X509FileType::PEM));
try!(ctx.set_private_key_file(key.as_ref(), X509FileType::PEM));
ctx.set_verify(SSL_VERIFY_NONE, None);
Ok(Openssl { context: Arc::new(ctx) })
}
}
impl super::Ssl for Openssl {
type Stream = SslStream<HttpStream>;
fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> {
let ssl = try!(Ssl::new(&self.context));
try!(ssl.set_hostname(host));
SslStream::connect(ssl, stream).map_err(From::from)
}
fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> {
match SslStream::accept(&*self.context, stream) {
Ok(ssl_stream) => Ok(ssl_stream),
Err(SslIoError(e)) => {
Err(io::Error::new(io::ErrorKind::ConnectionAborted, e).into())
},
Err(e) => Err(e.into())
}
}
}
impl<S: NetworkStream> NetworkStream for SslStream<S> {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr>
|
fn close(&mut self, how: Shutdown) -> io::Result<()> {
self.get_mut().close(how)
}
}
}
#[cfg(test)]
mod tests {
use mock::MockStream;
use super::{NetworkStream};
#[test]
fn test_downcast_box_stream() {
// FIXME: Use Type ascription
let stream: Box<NetworkStream + Send> = Box::new(MockStream::new());
let mock = stream.downcast::<MockStream>().ok().unwrap();
assert_eq!(mock, Box::new(MockStream::new()));
}
#[test]
fn test_downcast_unchecked_box_stream() {
// FIXME: Use Type ascription
let stream: Box<NetworkStream + Send> = Box::new(MockStream::new());
let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
assert_eq!(mock, Box::new(MockStream::new()));
}
}
|
{
self.get_mut().peer_addr()
}
|
identifier_body
|
net.rs
|
//! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, TypeId};
use std::fmt;
use std::io::{self, ErrorKind, Read, Write};
use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener, Shutdown};
use std::mem;
#[cfg(feature = "openssl")]
pub use self::openssl::Openssl;
use typeable::Typeable;
use traitobject;
/// The write-status indicating headers have not been written.
pub enum Fresh {}
/// The write-status indicating headers have been written.
pub enum Streaming {}
/// An abstraction to listen for connections on a certain port.
pub trait NetworkListener: Clone {
/// The stream produced for each connection.
type Stream: NetworkStream + Send + Clone;
/// Listens on a socket.
//fn listen<To: ToSocketAddrs>(&mut self, addr: To) -> io::Result<Self::Acceptor>;
/// Returns an iterator of streams.
fn accept(&mut self) -> ::Result<Self::Stream>;
/// Get the address this Listener ended up listening on.
fn local_addr(&mut self) -> io::Result<SocketAddr>;
/// Closes the Acceptor, so no more incoming connections will be handled.
// fn close(&mut self) -> io::Result<()>;
/// Returns an iterator over incoming connections.
fn incoming(&mut self) -> NetworkConnections<Self> {
NetworkConnections(self)
}
}
/// An iterator wrapper over a NetworkAcceptor.
pub struct NetworkConnections<'a, N: NetworkListener + 'a>(&'a mut N);
impl<'a, N: NetworkListener + 'a> Iterator for NetworkConnections<'a, N> {
type Item = ::Result<N::Stream>;
fn next(&mut self) -> Option<::Result<N::Stream>> {
Some(self.0.accept())
}
}
/// An abstraction over streams that a Server can utilize.
pub trait NetworkStream: Read + Write + Any + Send + Typeable {
/// Get the remote address of the underlying connection.
fn peer_addr(&mut self) -> io::Result<SocketAddr>;
/// This will be called when Stream should no longer be kept alive.
#[inline]
fn close(&mut self, _how: Shutdown) -> io::Result<()> {
Ok(())
}
}
/// A connector creates a NetworkStream.
pub trait NetworkConnector {
/// Type of Stream to create
type Stream: Into<Box<NetworkStream + Send>>;
/// Connect to a remote address.
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream>;
}
impl<T: NetworkStream + Send> From<T> for Box<NetworkStream + Send> {
fn from(s: T) -> Box<NetworkStream + Send> {
Box::new(s)
}
}
impl fmt::Debug for Box<NetworkStream + Send> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad("Box<NetworkStream>")
}
}
impl NetworkStream + Send {
unsafe fn downcast_ref_unchecked<T:'static>(&self) -> &T {
mem::transmute(traitobject::data(self))
}
unsafe fn downcast_mut_unchecked<T:'static>(&mut self) -> &mut T {
mem::transmute(traitobject::data_mut(self))
}
unsafe fn downcast_unchecked<T:'static>(self: Box<NetworkStream + Send>) -> Box<T> {
let raw: *mut NetworkStream = mem::transmute(self);
mem::transmute(traitobject::data_mut(raw))
}
}
impl NetworkStream + Send {
/// Is the underlying type in this trait object a T?
#[inline]
pub fn is<T: Any>(&self) -> bool {
(*self).get_type() == TypeId::of::<T>()
}
/// If the underlying type is T, get a reference to the contained data.
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
Some(unsafe { self.downcast_ref_unchecked() })
} else {
None
}
}
/// If the underlying type is T, get a mutable reference to the contained
/// data.
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
Some(unsafe { self.downcast_mut_unchecked() })
} else {
None
}
}
/// If the underlying type is T, extract it.
#[inline]
pub fn downcast<T: Any>(self: Box<NetworkStream + Send>)
-> Result<Box<T>, Box<NetworkStream + Send>> {
if self.is::<T>() {
Ok(unsafe { self.downcast_unchecked() })
} else {
Err(self)
}
}
}
/// A `NetworkListener` for `HttpStream`s.
pub struct HttpListener(TcpListener);
impl Clone for HttpListener {
#[inline]
fn clone(&self) -> HttpListener {
HttpListener(self.0.try_clone().unwrap())
}
}
impl HttpListener {
/// Start listening to an address over HTTP.
pub fn new<To: ToSocketAddrs>(addr: To) -> ::Result<HttpListener> {
Ok(HttpListener(try!(TcpListener::bind(addr))))
}
}
impl NetworkListener for HttpListener {
type Stream = HttpStream;
#[inline]
fn accept(&mut self) -> ::Result<HttpStream> {
Ok(HttpStream(try!(self.0.accept()).0))
}
#[inline]
fn local_addr(&mut self) -> io::Result<SocketAddr> {
self.0.local_addr()
}
}
/// A wrapper around a TcpStream.
pub struct HttpStream(pub TcpStream);
impl Clone for HttpStream {
#[inline]
fn clone(&self) -> HttpStream {
HttpStream(self.0.try_clone().unwrap())
}
}
impl fmt::Debug for HttpStream {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("HttpStream(_)")
}
}
impl Read for HttpStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl Write for HttpStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.0.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
#[cfg(windows)]
impl ::std::os::windows::io::AsRawSocket for HttpStream {
fn as_raw_socket(&self) -> ::std::os::windows::io::RawSocket {
self.0.as_raw_socket()
}
}
#[cfg(unix)]
impl ::std::os::unix::io::AsRawFd for HttpStream {
fn as_raw_fd(&self) -> i32 {
self.0.as_raw_fd()
}
}
impl NetworkStream for HttpStream {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
self.0.peer_addr()
}
#[inline]
fn close(&mut self, how: Shutdown) -> io::Result<()> {
match self.0.shutdown(how) {
Ok(_) => Ok(()),
// see https://github.com/hyperium/hyper/issues/508
Err(ref e) if e.kind() == ErrorKind::NotConnected => Ok(()),
err => err
}
}
}
/// A connector that will produce HttpStreams.
#[derive(Debug, Clone, Default)]
pub struct HttpConnector;
impl NetworkConnector for HttpConnector {
|
Ok(try!(match scheme {
"http" => {
debug!("http scheme");
Ok(HttpStream(try!(TcpStream::connect(addr))))
},
_ => {
Err(io::Error::new(io::ErrorKind::InvalidInput,
"Invalid scheme for Http"))
}
}))
}
}
/// An abstraction to allow any SSL implementation to be used with HttpsStreams.
pub trait Ssl {
/// The protected stream.
type Stream: NetworkStream + Send + Clone;
/// Wrap a client stream with SSL.
fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>;
/// Wrap a server stream with SSL.
fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream>;
}
/// A stream over the HTTP protocol, possibly protected by SSL.
#[derive(Debug, Clone)]
pub enum HttpsStream<S: NetworkStream> {
/// A plain text stream.
Http(HttpStream),
/// A stream protected by SSL.
Https(S)
}
impl<S: NetworkStream> Read for HttpsStream<S> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.read(buf),
HttpsStream::Https(ref mut s) => s.read(buf)
}
}
}
impl<S: NetworkStream> Write for HttpsStream<S> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.write(msg),
HttpsStream::Https(ref mut s) => s.write(msg)
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match *self {
HttpsStream::Http(ref mut s) => s.flush(),
HttpsStream::Https(ref mut s) => s.flush()
}
}
}
impl<S: NetworkStream> NetworkStream for HttpsStream<S> {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
match *self {
HttpsStream::Http(ref mut s) => s.peer_addr(),
HttpsStream::Https(ref mut s) => s.peer_addr()
}
}
#[inline]
fn close(&mut self, how: Shutdown) -> io::Result<()> {
match *self {
HttpsStream::Http(ref mut s) => s.close(how),
HttpsStream::Https(ref mut s) => s.close(how)
}
}
}
/// A Http Listener over SSL.
#[derive(Clone)]
pub struct HttpsListener<S: Ssl> {
listener: HttpListener,
ssl: S,
}
impl<S: Ssl> HttpsListener<S> {
/// Start listening to an address over HTTPS.
pub fn new<To: ToSocketAddrs>(addr: To, ssl: S) -> ::Result<HttpsListener<S>> {
HttpListener::new(addr).map(|l| HttpsListener {
listener: l,
ssl: ssl
})
}
}
impl<S: Ssl + Clone> NetworkListener for HttpsListener<S> {
type Stream = S::Stream;
#[inline]
fn accept(&mut self) -> ::Result<S::Stream> {
self.listener.accept().and_then(|s| self.ssl.wrap_server(s))
}
#[inline]
fn local_addr(&mut self) -> io::Result<SocketAddr> {
self.listener.local_addr()
}
}
/// A connector that can protect HTTP streams using SSL.
#[derive(Debug, Default)]
pub struct HttpsConnector<S: Ssl> {
ssl: S
}
impl<S: Ssl> HttpsConnector<S> {
/// Create a new connector using the provided SSL implementation.
pub fn new(s: S) -> HttpsConnector<S> {
HttpsConnector { ssl: s }
}
}
impl<S: Ssl> NetworkConnector for HttpsConnector<S> {
type Stream = HttpsStream<S::Stream>;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> {
let addr = &(host, port);
if scheme == "https" {
debug!("https scheme");
let stream = HttpStream(try!(TcpStream::connect(addr)));
self.ssl.wrap_client(stream, host).map(HttpsStream::Https)
} else {
HttpConnector.connect(host, port, scheme).map(HttpsStream::Http)
}
}
}
#[cfg(not(feature = "openssl"))]
#[doc(hidden)]
pub type DefaultConnector = HttpConnector;
#[cfg(feature = "openssl")]
#[doc(hidden)]
pub type DefaultConnector = HttpsConnector<self::openssl::Openssl>;
#[cfg(feature = "openssl")]
mod openssl {
use std::io;
use std::net::{SocketAddr, Shutdown};
use std::path::Path;
use std::sync::Arc;
use openssl::ssl::{Ssl, SslContext, SslStream, SslMethod, SSL_VERIFY_NONE};
use openssl::ssl::error::StreamError as SslIoError;
use openssl::ssl::error::SslError;
use openssl::x509::X509FileType;
use super::{NetworkStream, HttpStream};
/// An implementation of `Ssl` for OpenSSL.
///
/// # Example
///
/// ```no_run
/// use hyper::Server;
/// use hyper::net::Openssl;
///
/// let ssl = Openssl::with_cert_and_key("/home/foo/cert", "/home/foo/key").unwrap();
/// Server::https("0.0.0.0:443", ssl).unwrap();
/// ```
///
/// For complete control, create a `SslContext` with the options you desire
/// and then create `Openssl { context: ctx }
#[derive(Debug, Clone)]
pub struct Openssl {
/// The `SslContext` from openssl crate.
pub context: Arc<SslContext>
}
impl Default for Openssl {
fn default() -> Openssl {
Openssl {
context: Arc::new(SslContext::new(SslMethod::Sslv23).unwrap_or_else(|e| {
// if we cannot create a SslContext, that's because of a
// serious problem. just crash.
panic!("{}", e)
}))
}
}
}
impl Openssl {
/// Ease creating an `Openssl` with a certificate and key.
pub fn with_cert_and_key<C, K>(cert: C, key: K) -> Result<Openssl, SslError>
where C: AsRef<Path>, K: AsRef<Path> {
let mut ctx = try!(SslContext::new(SslMethod::Sslv23));
try!(ctx.set_cipher_list("DEFAULT"));
try!(ctx.set_certificate_file(cert.as_ref(), X509FileType::PEM));
try!(ctx.set_private_key_file(key.as_ref(), X509FileType::PEM));
ctx.set_verify(SSL_VERIFY_NONE, None);
Ok(Openssl { context: Arc::new(ctx) })
}
}
impl super::Ssl for Openssl {
type Stream = SslStream<HttpStream>;
fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> {
let ssl = try!(Ssl::new(&self.context));
try!(ssl.set_hostname(host));
SslStream::connect(ssl, stream).map_err(From::from)
}
fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> {
match SslStream::accept(&*self.context, stream) {
Ok(ssl_stream) => Ok(ssl_stream),
Err(SslIoError(e)) => {
Err(io::Error::new(io::ErrorKind::ConnectionAborted, e).into())
},
Err(e) => Err(e.into())
}
}
}
impl<S: NetworkStream> NetworkStream for SslStream<S> {
#[inline]
fn peer_addr(&mut self) -> io::Result<SocketAddr> {
self.get_mut().peer_addr()
}
fn close(&mut self, how: Shutdown) -> io::Result<()> {
self.get_mut().close(how)
}
}
}
#[cfg(test)]
mod tests {
use mock::MockStream;
use super::{NetworkStream};
#[test]
fn test_downcast_box_stream() {
// FIXME: Use Type ascription
let stream: Box<NetworkStream + Send> = Box::new(MockStream::new());
let mock = stream.downcast::<MockStream>().ok().unwrap();
assert_eq!(mock, Box::new(MockStream::new()));
}
#[test]
fn test_downcast_unchecked_box_stream() {
// FIXME: Use Type ascription
let stream: Box<NetworkStream + Send> = Box::new(MockStream::new());
let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
assert_eq!(mock, Box::new(MockStream::new()));
}
}
|
type Stream = HttpStream;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
let addr = &(host, port);
|
random_line_split
|
lib.rs
|
use std::collections::VecDeque;
use std::io::{Cursor, Read, Write};
#[macro_use]
extern crate strider;
use strider::SliceRing;
use strider::SliceRingImpl;
macro_rules! test_string_windowing {
($new:expr) => {{
const WINDOW_SIZE: usize = 8;
const STEP_SIZE: usize = 2;
let mut input = Cursor::new("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
let mut output = Cursor::new(Vec::<u8>::new());
let mut ring = $new;
let mut input_buffer: &mut [u8] = &mut [0; 4];
let mut window_buffer: &mut [u8] = &mut [0; WINDOW_SIZE];
loop {
let input_count = input.read(input_buffer).unwrap();
if input_count == 0 { break; }
ring.push_many_back(&input_buffer[..input_count]);
// read as long as enough samples are present (remain) in ring
while WINDOW_SIZE <= ring.len() {
ring.read_many_front(window_buffer);
output.write(window_buffer).unwrap();
// step
ring.drop_many_front(STEP_SIZE);
}
}
let actual = String::from_utf8(output.into_inner()).unwrap();
let mut expected = String::new();
expected.push_str("ABCDEFGH");
expected.push_str("CDEFGHIJ");
expected.push_str("EFGHIJKL");
expected.push_str("GHIJKLMN");
expected.push_str("IJKLMNOP");
expected.push_str("KLMNOPQR");
expected.push_str("MNOPQRST");
expected.push_str("OPQRSTUV");
expected.push_str("QRSTUVWX");
expected.push_str("STUVWXYZ");
assert_eq!(actual, expected);
}}
}
#[test]
fn
|
() {
test_string_windowing!(VecDeque::<u8>::new());
}
#[test]
fn test_string_windowing_optimized() {
test_string_windowing!(SliceRingImpl::<u8>::new());
}
#[test]
fn test_slice_ring_deque() {
test_slice_ring!(VecDeque::<i32>::new());
}
#[test]
fn test_slice_ring_optimized() {
test_slice_ring!(SliceRingImpl::<i32>::new());
}
|
test_test_string_windowing_deque
|
identifier_name
|
lib.rs
|
use std::collections::VecDeque;
use std::io::{Cursor, Read, Write};
#[macro_use]
extern crate strider;
use strider::SliceRing;
use strider::SliceRingImpl;
macro_rules! test_string_windowing {
($new:expr) => {{
const WINDOW_SIZE: usize = 8;
const STEP_SIZE: usize = 2;
let mut input = Cursor::new("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
let mut output = Cursor::new(Vec::<u8>::new());
let mut ring = $new;
let mut input_buffer: &mut [u8] = &mut [0; 4];
let mut window_buffer: &mut [u8] = &mut [0; WINDOW_SIZE];
loop {
let input_count = input.read(input_buffer).unwrap();
if input_count == 0 { break; }
ring.push_many_back(&input_buffer[..input_count]);
// read as long as enough samples are present (remain) in ring
while WINDOW_SIZE <= ring.len() {
ring.read_many_front(window_buffer);
output.write(window_buffer).unwrap();
// step
ring.drop_many_front(STEP_SIZE);
}
}
let actual = String::from_utf8(output.into_inner()).unwrap();
let mut expected = String::new();
expected.push_str("ABCDEFGH");
expected.push_str("CDEFGHIJ");
expected.push_str("EFGHIJKL");
expected.push_str("GHIJKLMN");
expected.push_str("IJKLMNOP");
expected.push_str("KLMNOPQR");
expected.push_str("MNOPQRST");
expected.push_str("OPQRSTUV");
expected.push_str("QRSTUVWX");
expected.push_str("STUVWXYZ");
assert_eq!(actual, expected);
}}
}
#[test]
fn test_test_string_windowing_deque() {
test_string_windowing!(VecDeque::<u8>::new());
}
#[test]
fn test_string_windowing_optimized()
|
#[test]
fn test_slice_ring_deque() {
test_slice_ring!(VecDeque::<i32>::new());
}
#[test]
fn test_slice_ring_optimized() {
test_slice_ring!(SliceRingImpl::<i32>::new());
}
|
{
test_string_windowing!(SliceRingImpl::<u8>::new());
}
|
identifier_body
|
lib.rs
|
use std::collections::VecDeque;
use std::io::{Cursor, Read, Write};
#[macro_use]
extern crate strider;
use strider::SliceRing;
use strider::SliceRingImpl;
macro_rules! test_string_windowing {
($new:expr) => {{
const WINDOW_SIZE: usize = 8;
const STEP_SIZE: usize = 2;
let mut input = Cursor::new("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
let mut output = Cursor::new(Vec::<u8>::new());
let mut ring = $new;
let mut input_buffer: &mut [u8] = &mut [0; 4];
let mut window_buffer: &mut [u8] = &mut [0; WINDOW_SIZE];
loop {
let input_count = input.read(input_buffer).unwrap();
if input_count == 0 { break; }
ring.push_many_back(&input_buffer[..input_count]);
// read as long as enough samples are present (remain) in ring
while WINDOW_SIZE <= ring.len() {
ring.read_many_front(window_buffer);
output.write(window_buffer).unwrap();
// step
ring.drop_many_front(STEP_SIZE);
}
}
let actual = String::from_utf8(output.into_inner()).unwrap();
let mut expected = String::new();
expected.push_str("ABCDEFGH");
expected.push_str("CDEFGHIJ");
expected.push_str("EFGHIJKL");
expected.push_str("GHIJKLMN");
expected.push_str("IJKLMNOP");
expected.push_str("KLMNOPQR");
expected.push_str("MNOPQRST");
expected.push_str("OPQRSTUV");
expected.push_str("QRSTUVWX");
expected.push_str("STUVWXYZ");
assert_eq!(actual, expected);
}}
}
#[test]
fn test_test_string_windowing_deque() {
test_string_windowing!(VecDeque::<u8>::new());
}
#[test]
fn test_string_windowing_optimized() {
test_string_windowing!(SliceRingImpl::<u8>::new());
|
#[test]
fn test_slice_ring_deque() {
test_slice_ring!(VecDeque::<i32>::new());
}
#[test]
fn test_slice_ring_optimized() {
test_slice_ring!(SliceRingImpl::<i32>::new());
}
|
}
|
random_line_split
|
parse.rs
|
use std::str;
/// A fragment of json.
#[derive(Debug)]
pub enum JsonFragment<'a> {
Literal(String),
Repl(&'a str)
}
/// Parse and sanitise the complete sequence as a literal.
pub fn parse_literal(remainder: &[u8], json: &mut String) {
let _ = literal(remainder, json, false);
}
/// Parse and sanitise the complete sequence as literals and replacements.
pub fn parse_fragments<'a>(remainder: &'a [u8], fragments: &mut Vec<JsonFragment<'a>>) {
// Parse a literal
let mut l = String::new();
let remainder = literal(remainder, &mut l, true);
if l.len() > 0 {
fragments.push(JsonFragment::Literal(l));
}
// Parse a repl
let (remainder, r) = repl(remainder);
if r.len() > 0 {
fragments.push(JsonFragment::Repl(r));
}
// If there's anything left, run again
if remainder.len() > 0 {
parse_fragments(remainder, fragments);
}
}
// Parse a replacement ident.
fn repl(remainder: &[u8]) -> (&[u8], &str) {
if remainder.len() == 0 {
return (&[], "");
}
take_while(&remainder, (), |_, c| {
((), is_ident(c as char))
})
}
// Parse a literal and maybe break on a replacement token.
fn literal<'a>(remainder: &'a [u8], sanitised: &mut String, break_on_repl: bool) -> &'a [u8] {
if remainder.len() == 0 {
return &[];
}
let current = remainder[0];
match current {
//Key
b'"'|b'\'' => {
enum StringState {
Unescaped,
Escaped
}
let (rest, key) = take_while(&remainder[1..], StringState::Unescaped,
|s, c| {
match (s, c) {
//Escape char
(StringState::Unescaped, b'\\') => {
(StringState::Escaped, true)
},
//Ignore char after escape
(StringState::Escaped, _) => {
(StringState::Unescaped, true)
},
//Unescaped quote
(StringState::Unescaped, c) if c == current => {
(StringState::Unescaped, false)
},
//Anything else
_ => {
(StringState::Unescaped, true)
}
}
}
);
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
literal(&rest[1..], sanitised, break_on_repl)
},
//Start of item
b'{'|b'['|b':' => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
},
//Trim whitespace
b' '|b'\r'|b'\n'|b'\t' => {
literal(&remainder[1..], sanitised, break_on_repl)
},
//Unquoted key
b if (b as char).is_alphabetic() => {
let (rest, key) = take_while(remainder, (), |_, c| {
((), is_ident(c as char))
});
//Check if the string is a special value; true, false or null
//For special values, push them as straight unquoted values. Otherwise, quote them
match key {
"true"|"false"|"null" =>
sanitised.push_str(key),
_ => {
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
}
}
literal(rest, sanitised, break_on_repl)
},
//Number
b if (b as char).is_numeric() => {
let (rest, key) = take_while(remainder, (), |_, c| {
((), {
(c as char).is_numeric() ||
c == b'.' ||
c == b'+' ||
c == b'-' ||
c == b'e' ||
c == b'E'
})
});
sanitised.push_str(key);
literal(rest, sanitised, break_on_repl)
},
//Replacement
b'$' if break_on_repl => {
//Strip trailing whitespace
let remainder = shift_while(&remainder[1..], |c| c == b' ');
remainder
},
//Other chars
_ => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
}
}
}
#[inline]
fn is_ident(c: char) -> bool {
c.is_alphabetic() || c == '_'
}
fn shift_while<F>(i: &[u8], f: F) -> &[u8]
where F: Fn(u8) -> bool
{
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
&i[ctr..]
}
fn
|
<F, S>(i: &[u8], mut s: S, f: F) -> (&[u8], &str)
where F: Fn(S, u8) -> (S, bool)
{
let mut ctr = 0;
for c in i {
let (new_state, more) = f(s, *c);
if more {
s = new_state;
ctr += 1;
}
else {
break;
}
}
(&i[ctr..], unsafe { str::from_utf8_unchecked(&i[..ctr]) })
}
|
take_while
|
identifier_name
|
parse.rs
|
use std::str;
/// A fragment of json.
#[derive(Debug)]
pub enum JsonFragment<'a> {
Literal(String),
Repl(&'a str)
}
/// Parse and sanitise the complete sequence as a literal.
pub fn parse_literal(remainder: &[u8], json: &mut String) {
let _ = literal(remainder, json, false);
}
/// Parse and sanitise the complete sequence as literals and replacements.
pub fn parse_fragments<'a>(remainder: &'a [u8], fragments: &mut Vec<JsonFragment<'a>>) {
// Parse a literal
let mut l = String::new();
let remainder = literal(remainder, &mut l, true);
if l.len() > 0 {
fragments.push(JsonFragment::Literal(l));
}
// Parse a repl
let (remainder, r) = repl(remainder);
if r.len() > 0 {
fragments.push(JsonFragment::Repl(r));
}
// If there's anything left, run again
if remainder.len() > 0 {
parse_fragments(remainder, fragments);
}
}
// Parse a replacement ident.
fn repl(remainder: &[u8]) -> (&[u8], &str) {
if remainder.len() == 0 {
return (&[], "");
}
take_while(&remainder, (), |_, c| {
((), is_ident(c as char))
})
}
// Parse a literal and maybe break on a replacement token.
fn literal<'a>(remainder: &'a [u8], sanitised: &mut String, break_on_repl: bool) -> &'a [u8] {
if remainder.len() == 0 {
return &[];
}
let current = remainder[0];
match current {
//Key
b'"'|b'\'' => {
enum StringState {
Unescaped,
Escaped
}
let (rest, key) = take_while(&remainder[1..], StringState::Unescaped,
|s, c| {
match (s, c) {
//Escape char
(StringState::Unescaped, b'\\') => {
(StringState::Escaped, true)
},
//Ignore char after escape
(StringState::Escaped, _) => {
(StringState::Unescaped, true)
},
//Unescaped quote
(StringState::Unescaped, c) if c == current => {
(StringState::Unescaped, false)
},
//Anything else
_ => {
(StringState::Unescaped, true)
}
}
}
);
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
literal(&rest[1..], sanitised, break_on_repl)
},
//Start of item
b'{'|b'['|b':' => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
},
//Trim whitespace
b' '|b'\r'|b'\n'|b'\t' => {
literal(&remainder[1..], sanitised, break_on_repl)
},
//Unquoted key
b if (b as char).is_alphabetic() => {
|
((), is_ident(c as char))
});
//Check if the string is a special value; true, false or null
//For special values, push them as straight unquoted values. Otherwise, quote them
match key {
"true"|"false"|"null" =>
sanitised.push_str(key),
_ => {
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
}
}
literal(rest, sanitised, break_on_repl)
},
//Number
b if (b as char).is_numeric() => {
let (rest, key) = take_while(remainder, (), |_, c| {
((), {
(c as char).is_numeric() ||
c == b'.' ||
c == b'+' ||
c == b'-' ||
c == b'e' ||
c == b'E'
})
});
sanitised.push_str(key);
literal(rest, sanitised, break_on_repl)
},
//Replacement
b'$' if break_on_repl => {
//Strip trailing whitespace
let remainder = shift_while(&remainder[1..], |c| c == b' ');
remainder
},
//Other chars
_ => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
}
}
}
#[inline]
fn is_ident(c: char) -> bool {
c.is_alphabetic() || c == '_'
}
fn shift_while<F>(i: &[u8], f: F) -> &[u8]
where F: Fn(u8) -> bool
{
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
&i[ctr..]
}
fn take_while<F, S>(i: &[u8], mut s: S, f: F) -> (&[u8], &str)
where F: Fn(S, u8) -> (S, bool)
{
let mut ctr = 0;
for c in i {
let (new_state, more) = f(s, *c);
if more {
s = new_state;
ctr += 1;
}
else {
break;
}
}
(&i[ctr..], unsafe { str::from_utf8_unchecked(&i[..ctr]) })
}
|
let (rest, key) = take_while(remainder, (), |_, c| {
|
random_line_split
|
parse.rs
|
use std::str;
/// A fragment of json.
#[derive(Debug)]
pub enum JsonFragment<'a> {
Literal(String),
Repl(&'a str)
}
/// Parse and sanitise the complete sequence as a literal.
pub fn parse_literal(remainder: &[u8], json: &mut String) {
let _ = literal(remainder, json, false);
}
/// Parse and sanitise the complete sequence as literals and replacements.
pub fn parse_fragments<'a>(remainder: &'a [u8], fragments: &mut Vec<JsonFragment<'a>>) {
// Parse a literal
let mut l = String::new();
let remainder = literal(remainder, &mut l, true);
if l.len() > 0 {
fragments.push(JsonFragment::Literal(l));
}
// Parse a repl
let (remainder, r) = repl(remainder);
if r.len() > 0 {
fragments.push(JsonFragment::Repl(r));
}
// If there's anything left, run again
if remainder.len() > 0 {
parse_fragments(remainder, fragments);
}
}
// Parse a replacement ident.
fn repl(remainder: &[u8]) -> (&[u8], &str) {
if remainder.len() == 0 {
return (&[], "");
}
take_while(&remainder, (), |_, c| {
((), is_ident(c as char))
})
}
// Parse a literal and maybe break on a replacement token.
fn literal<'a>(remainder: &'a [u8], sanitised: &mut String, break_on_repl: bool) -> &'a [u8] {
if remainder.len() == 0 {
return &[];
}
let current = remainder[0];
match current {
//Key
b'"'|b'\'' => {
enum StringState {
Unescaped,
Escaped
}
let (rest, key) = take_while(&remainder[1..], StringState::Unescaped,
|s, c| {
match (s, c) {
//Escape char
(StringState::Unescaped, b'\\') => {
(StringState::Escaped, true)
},
//Ignore char after escape
(StringState::Escaped, _) => {
(StringState::Unescaped, true)
},
//Unescaped quote
(StringState::Unescaped, c) if c == current => {
(StringState::Unescaped, false)
},
//Anything else
_ => {
(StringState::Unescaped, true)
}
}
}
);
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
literal(&rest[1..], sanitised, break_on_repl)
},
//Start of item
b'{'|b'['|b':' => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
},
//Trim whitespace
b' '|b'\r'|b'\n'|b'\t' => {
literal(&remainder[1..], sanitised, break_on_repl)
},
//Unquoted key
b if (b as char).is_alphabetic() => {
let (rest, key) = take_while(remainder, (), |_, c| {
((), is_ident(c as char))
});
//Check if the string is a special value; true, false or null
//For special values, push them as straight unquoted values. Otherwise, quote them
match key {
"true"|"false"|"null" =>
sanitised.push_str(key),
_ => {
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
}
}
literal(rest, sanitised, break_on_repl)
},
//Number
b if (b as char).is_numeric() => {
let (rest, key) = take_while(remainder, (), |_, c| {
((), {
(c as char).is_numeric() ||
c == b'.' ||
c == b'+' ||
c == b'-' ||
c == b'e' ||
c == b'E'
})
});
sanitised.push_str(key);
literal(rest, sanitised, break_on_repl)
},
//Replacement
b'$' if break_on_repl => {
//Strip trailing whitespace
let remainder = shift_while(&remainder[1..], |c| c == b' ');
remainder
},
//Other chars
_ => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
}
}
}
#[inline]
fn is_ident(c: char) -> bool
|
fn shift_while<F>(i: &[u8], f: F) -> &[u8]
where F: Fn(u8) -> bool
{
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
&i[ctr..]
}
fn take_while<F, S>(i: &[u8], mut s: S, f: F) -> (&[u8], &str)
where F: Fn(S, u8) -> (S, bool)
{
let mut ctr = 0;
for c in i {
let (new_state, more) = f(s, *c);
if more {
s = new_state;
ctr += 1;
}
else {
break;
}
}
(&i[ctr..], unsafe { str::from_utf8_unchecked(&i[..ctr]) })
}
|
{
c.is_alphabetic() || c == '_'
}
|
identifier_body
|
parse.rs
|
use std::str;
/// A fragment of json.
#[derive(Debug)]
pub enum JsonFragment<'a> {
Literal(String),
Repl(&'a str)
}
/// Parse and sanitise the complete sequence as a literal.
pub fn parse_literal(remainder: &[u8], json: &mut String) {
let _ = literal(remainder, json, false);
}
/// Parse and sanitise the complete sequence as literals and replacements.
pub fn parse_fragments<'a>(remainder: &'a [u8], fragments: &mut Vec<JsonFragment<'a>>) {
// Parse a literal
let mut l = String::new();
let remainder = literal(remainder, &mut l, true);
if l.len() > 0 {
fragments.push(JsonFragment::Literal(l));
}
// Parse a repl
let (remainder, r) = repl(remainder);
if r.len() > 0
|
// If there's anything left, run again
if remainder.len() > 0 {
parse_fragments(remainder, fragments);
}
}
// Parse a replacement ident.
fn repl(remainder: &[u8]) -> (&[u8], &str) {
if remainder.len() == 0 {
return (&[], "");
}
take_while(&remainder, (), |_, c| {
((), is_ident(c as char))
})
}
// Parse a literal and maybe break on a replacement token.
fn literal<'a>(remainder: &'a [u8], sanitised: &mut String, break_on_repl: bool) -> &'a [u8] {
if remainder.len() == 0 {
return &[];
}
let current = remainder[0];
match current {
//Key
b'"'|b'\'' => {
enum StringState {
Unescaped,
Escaped
}
let (rest, key) = take_while(&remainder[1..], StringState::Unescaped,
|s, c| {
match (s, c) {
//Escape char
(StringState::Unescaped, b'\\') => {
(StringState::Escaped, true)
},
//Ignore char after escape
(StringState::Escaped, _) => {
(StringState::Unescaped, true)
},
//Unescaped quote
(StringState::Unescaped, c) if c == current => {
(StringState::Unescaped, false)
},
//Anything else
_ => {
(StringState::Unescaped, true)
}
}
}
);
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
literal(&rest[1..], sanitised, break_on_repl)
},
//Start of item
b'{'|b'['|b':' => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
},
//Trim whitespace
b' '|b'\r'|b'\n'|b'\t' => {
literal(&remainder[1..], sanitised, break_on_repl)
},
//Unquoted key
b if (b as char).is_alphabetic() => {
let (rest, key) = take_while(remainder, (), |_, c| {
((), is_ident(c as char))
});
//Check if the string is a special value; true, false or null
//For special values, push them as straight unquoted values. Otherwise, quote them
match key {
"true"|"false"|"null" =>
sanitised.push_str(key),
_ => {
sanitised.push('"');
sanitised.push_str(key);
sanitised.push('"');
}
}
literal(rest, sanitised, break_on_repl)
},
//Number
b if (b as char).is_numeric() => {
let (rest, key) = take_while(remainder, (), |_, c| {
((), {
(c as char).is_numeric() ||
c == b'.' ||
c == b'+' ||
c == b'-' ||
c == b'e' ||
c == b'E'
})
});
sanitised.push_str(key);
literal(rest, sanitised, break_on_repl)
},
//Replacement
b'$' if break_on_repl => {
//Strip trailing whitespace
let remainder = shift_while(&remainder[1..], |c| c == b' ');
remainder
},
//Other chars
_ => {
sanitised.push(current as char);
literal(&remainder[1..], sanitised, break_on_repl)
}
}
}
#[inline]
fn is_ident(c: char) -> bool {
c.is_alphabetic() || c == '_'
}
fn shift_while<F>(i: &[u8], f: F) -> &[u8]
where F: Fn(u8) -> bool
{
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
&i[ctr..]
}
fn take_while<F, S>(i: &[u8], mut s: S, f: F) -> (&[u8], &str)
where F: Fn(S, u8) -> (S, bool)
{
let mut ctr = 0;
for c in i {
let (new_state, more) = f(s, *c);
if more {
s = new_state;
ctr += 1;
}
else {
break;
}
}
(&i[ctr..], unsafe { str::from_utf8_unchecked(&i[..ctr]) })
}
|
{
fragments.push(JsonFragment::Repl(r));
}
|
conditional_block
|
for_each_concurrent.rs
|
use crate::stream::{FuturesUnordered, StreamExt};
use core::fmt;
use core::pin::Pin;
use core::num::NonZeroUsize;
use futures_core::future::{FusedFuture, Future};
use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Future for the [`for_each_concurrent`](super::StreamExt::for_each_concurrent)
/// method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct
|
<St, Fut, F> {
stream: Option<St>,
f: F,
futures: FuturesUnordered<Fut>,
limit: Option<NonZeroUsize>,
}
impl<St, Fut, F> Unpin for ForEachConcurrent<St, Fut, F>
where St: Unpin,
Fut: Unpin,
{}
impl<St, Fut, F> fmt::Debug for ForEachConcurrent<St, Fut, F>
where
St: fmt::Debug,
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ForEachConcurrent")
.field("stream", &self.stream)
.field("futures", &self.futures)
.field("limit", &self.limit)
.finish()
}
}
impl<St, Fut, F> ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
unsafe_pinned!(stream: Option<St>);
unsafe_unpinned!(f: F);
unsafe_unpinned!(futures: FuturesUnordered<Fut>);
unsafe_unpinned!(limit: Option<NonZeroUsize>);
pub(super) fn new(stream: St, limit: Option<usize>, f: F) -> ForEachConcurrent<St, Fut, F> {
ForEachConcurrent {
stream: Some(stream),
// Note: `limit` = 0 gets ignored.
limit: limit.and_then(NonZeroUsize::new),
f,
futures: FuturesUnordered::new(),
}
}
}
impl<St, Fut, F> FusedFuture for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
fn is_terminated(&self) -> bool {
self.stream.is_none() && self.futures.is_empty()
}
}
impl<St, Fut, F> Future for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
loop {
let mut made_progress_this_iter = false;
// Try and pull an item from the stream
let current_len = self.futures.len();
// Check if we've already created a number of futures greater than `limit`
if self.limit.map(|limit| limit.get() > current_len).unwrap_or(true) {
let mut stream_completed = false;
let elem = if let Some(stream) = self.as_mut().stream().as_pin_mut() {
match stream.poll_next(cx) {
Poll::Ready(Some(elem)) => {
made_progress_this_iter = true;
Some(elem)
},
Poll::Ready(None) => {
stream_completed = true;
None
}
Poll::Pending => None,
}
} else {
None
};
if stream_completed {
self.as_mut().stream().set(None);
}
if let Some(elem) = elem {
let next_future = (self.as_mut().f())(elem);
self.as_mut().futures().push(next_future);
}
}
match self.as_mut().futures().poll_next_unpin(cx) {
Poll::Ready(Some(())) => made_progress_this_iter = true,
Poll::Ready(None) => {
if self.stream.is_none() {
return Poll::Ready(())
}
},
Poll::Pending => {}
}
if!made_progress_this_iter {
return Poll::Pending;
}
}
}
}
|
ForEachConcurrent
|
identifier_name
|
for_each_concurrent.rs
|
use crate::stream::{FuturesUnordered, StreamExt};
use core::fmt;
use core::pin::Pin;
use core::num::NonZeroUsize;
use futures_core::future::{FusedFuture, Future};
use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Future for the [`for_each_concurrent`](super::StreamExt::for_each_concurrent)
/// method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ForEachConcurrent<St, Fut, F> {
stream: Option<St>,
f: F,
futures: FuturesUnordered<Fut>,
limit: Option<NonZeroUsize>,
}
impl<St, Fut, F> Unpin for ForEachConcurrent<St, Fut, F>
where St: Unpin,
Fut: Unpin,
{}
impl<St, Fut, F> fmt::Debug for ForEachConcurrent<St, Fut, F>
where
St: fmt::Debug,
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ForEachConcurrent")
.field("stream", &self.stream)
.field("futures", &self.futures)
.field("limit", &self.limit)
.finish()
}
}
impl<St, Fut, F> ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
unsafe_pinned!(stream: Option<St>);
unsafe_unpinned!(f: F);
unsafe_unpinned!(futures: FuturesUnordered<Fut>);
unsafe_unpinned!(limit: Option<NonZeroUsize>);
pub(super) fn new(stream: St, limit: Option<usize>, f: F) -> ForEachConcurrent<St, Fut, F> {
ForEachConcurrent {
stream: Some(stream),
// Note: `limit` = 0 gets ignored.
limit: limit.and_then(NonZeroUsize::new),
f,
futures: FuturesUnordered::new(),
}
}
}
impl<St, Fut, F> FusedFuture for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
fn is_terminated(&self) -> bool {
self.stream.is_none() && self.futures.is_empty()
}
}
impl<St, Fut, F> Future for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
loop {
let mut made_progress_this_iter = false;
// Try and pull an item from the stream
let current_len = self.futures.len();
// Check if we've already created a number of futures greater than `limit`
if self.limit.map(|limit| limit.get() > current_len).unwrap_or(true) {
let mut stream_completed = false;
let elem = if let Some(stream) = self.as_mut().stream().as_pin_mut()
|
else {
None
};
if stream_completed {
self.as_mut().stream().set(None);
}
if let Some(elem) = elem {
let next_future = (self.as_mut().f())(elem);
self.as_mut().futures().push(next_future);
}
}
match self.as_mut().futures().poll_next_unpin(cx) {
Poll::Ready(Some(())) => made_progress_this_iter = true,
Poll::Ready(None) => {
if self.stream.is_none() {
return Poll::Ready(())
}
},
Poll::Pending => {}
}
if!made_progress_this_iter {
return Poll::Pending;
}
}
}
}
|
{
match stream.poll_next(cx) {
Poll::Ready(Some(elem)) => {
made_progress_this_iter = true;
Some(elem)
},
Poll::Ready(None) => {
stream_completed = true;
None
}
Poll::Pending => None,
}
}
|
conditional_block
|
for_each_concurrent.rs
|
use crate::stream::{FuturesUnordered, StreamExt};
use core::fmt;
use core::pin::Pin;
use core::num::NonZeroUsize;
use futures_core::future::{FusedFuture, Future};
use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Future for the [`for_each_concurrent`](super::StreamExt::for_each_concurrent)
/// method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ForEachConcurrent<St, Fut, F> {
stream: Option<St>,
f: F,
futures: FuturesUnordered<Fut>,
limit: Option<NonZeroUsize>,
}
impl<St, Fut, F> Unpin for ForEachConcurrent<St, Fut, F>
where St: Unpin,
Fut: Unpin,
{}
impl<St, Fut, F> fmt::Debug for ForEachConcurrent<St, Fut, F>
where
St: fmt::Debug,
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ForEachConcurrent")
.field("stream", &self.stream)
.field("futures", &self.futures)
.field("limit", &self.limit)
.finish()
}
}
impl<St, Fut, F> ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
|
Fut: Future<Output = ()>,
{
unsafe_pinned!(stream: Option<St>);
unsafe_unpinned!(f: F);
unsafe_unpinned!(futures: FuturesUnordered<Fut>);
unsafe_unpinned!(limit: Option<NonZeroUsize>);
pub(super) fn new(stream: St, limit: Option<usize>, f: F) -> ForEachConcurrent<St, Fut, F> {
ForEachConcurrent {
stream: Some(stream),
// Note: `limit` = 0 gets ignored.
limit: limit.and_then(NonZeroUsize::new),
f,
futures: FuturesUnordered::new(),
}
}
}
impl<St, Fut, F> FusedFuture for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
fn is_terminated(&self) -> bool {
self.stream.is_none() && self.futures.is_empty()
}
}
impl<St, Fut, F> Future for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
loop {
let mut made_progress_this_iter = false;
// Try and pull an item from the stream
let current_len = self.futures.len();
// Check if we've already created a number of futures greater than `limit`
if self.limit.map(|limit| limit.get() > current_len).unwrap_or(true) {
let mut stream_completed = false;
let elem = if let Some(stream) = self.as_mut().stream().as_pin_mut() {
match stream.poll_next(cx) {
Poll::Ready(Some(elem)) => {
made_progress_this_iter = true;
Some(elem)
},
Poll::Ready(None) => {
stream_completed = true;
None
}
Poll::Pending => None,
}
} else {
None
};
if stream_completed {
self.as_mut().stream().set(None);
}
if let Some(elem) = elem {
let next_future = (self.as_mut().f())(elem);
self.as_mut().futures().push(next_future);
}
}
match self.as_mut().futures().poll_next_unpin(cx) {
Poll::Ready(Some(())) => made_progress_this_iter = true,
Poll::Ready(None) => {
if self.stream.is_none() {
return Poll::Ready(())
}
},
Poll::Pending => {}
}
if!made_progress_this_iter {
return Poll::Pending;
}
}
}
}
|
random_line_split
|
|
for_each_concurrent.rs
|
use crate::stream::{FuturesUnordered, StreamExt};
use core::fmt;
use core::pin::Pin;
use core::num::NonZeroUsize;
use futures_core::future::{FusedFuture, Future};
use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Future for the [`for_each_concurrent`](super::StreamExt::for_each_concurrent)
/// method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ForEachConcurrent<St, Fut, F> {
stream: Option<St>,
f: F,
futures: FuturesUnordered<Fut>,
limit: Option<NonZeroUsize>,
}
impl<St, Fut, F> Unpin for ForEachConcurrent<St, Fut, F>
where St: Unpin,
Fut: Unpin,
{}
impl<St, Fut, F> fmt::Debug for ForEachConcurrent<St, Fut, F>
where
St: fmt::Debug,
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ForEachConcurrent")
.field("stream", &self.stream)
.field("futures", &self.futures)
.field("limit", &self.limit)
.finish()
}
}
impl<St, Fut, F> ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
unsafe_pinned!(stream: Option<St>);
unsafe_unpinned!(f: F);
unsafe_unpinned!(futures: FuturesUnordered<Fut>);
unsafe_unpinned!(limit: Option<NonZeroUsize>);
pub(super) fn new(stream: St, limit: Option<usize>, f: F) -> ForEachConcurrent<St, Fut, F>
|
}
impl<St, Fut, F> FusedFuture for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
fn is_terminated(&self) -> bool {
self.stream.is_none() && self.futures.is_empty()
}
}
impl<St, Fut, F> Future for ForEachConcurrent<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
loop {
let mut made_progress_this_iter = false;
// Try and pull an item from the stream
let current_len = self.futures.len();
// Check if we've already created a number of futures greater than `limit`
if self.limit.map(|limit| limit.get() > current_len).unwrap_or(true) {
let mut stream_completed = false;
let elem = if let Some(stream) = self.as_mut().stream().as_pin_mut() {
match stream.poll_next(cx) {
Poll::Ready(Some(elem)) => {
made_progress_this_iter = true;
Some(elem)
},
Poll::Ready(None) => {
stream_completed = true;
None
}
Poll::Pending => None,
}
} else {
None
};
if stream_completed {
self.as_mut().stream().set(None);
}
if let Some(elem) = elem {
let next_future = (self.as_mut().f())(elem);
self.as_mut().futures().push(next_future);
}
}
match self.as_mut().futures().poll_next_unpin(cx) {
Poll::Ready(Some(())) => made_progress_this_iter = true,
Poll::Ready(None) => {
if self.stream.is_none() {
return Poll::Ready(())
}
},
Poll::Pending => {}
}
if!made_progress_this_iter {
return Poll::Pending;
}
}
}
}
|
{
ForEachConcurrent {
stream: Some(stream),
// Note: `limit` = 0 gets ignored.
limit: limit.and_then(NonZeroUsize::new),
f,
futures: FuturesUnordered::new(),
}
}
|
identifier_body
|
enum_set.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A structure for holding a set of enum variants.
//!
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.
use core::prelude::*;
use core::marker;
use core::fmt;
use core::iter::{FromIterator};
use core::ops::{Sub, BitOr, BitAnd, BitXor};
// FIXME(contentions): implement union family of methods? (general design may be wrong here)
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A specialized set implementation to use enum types.
///
/// It is a logic error for an item to be modified in such a way that the transformation of the
/// item to or from a `usize`, as determined by the `CLike` trait, changes while the item is in the
/// set. This is normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe
/// code.
pub struct EnumSet<E> {
// We must maintain the invariant that no bits are set
// for which no variant exists
bits: usize,
marker: marker::PhantomData<E>,
}
impl<E> Copy for EnumSet<E> {}
impl<E> Clone for EnumSet<E> {
fn clone(&self) -> EnumSet<E> { *self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<E:CLike + fmt::Debug> fmt::Debug for EnumSet<E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "{{"));
let mut first = true;
for e in self {
if!first {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{:?}", e));
first = false;
}
write!(fmt, "}}")
}
}
/// An interface for casting C-like enum to usize and back.
/// A typically implementation is as below.
///
/// ```{rust,ignore}
/// #[repr(usize)]
/// enum Foo {
/// A, B, C
/// }
///
/// impl CLike for Foo {
/// fn to_usize(&self) -> usize {
/// *self as usize
/// }
///
/// fn from_usize(v: usize) -> Foo {
/// unsafe { mem::transmute(v) }
/// }
/// }
/// ```
pub trait CLike {
/// Converts a C-like enum to a `usize`.
fn to_usize(&self) -> usize;
/// Converts a `usize` to a C-like enum.
fn from_usize(usize) -> Self;
}
fn bit<E:CLike>(e: &E) -> usize {
use core::usize;
let value = e.to_usize();
assert!(value < usize::BITS,
"EnumSet only supports up to {} variants.", usize::BITS - 1);
1 << value
}
impl<E:CLike> EnumSet<E> {
/// Returns an empty `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn new() -> EnumSet<E> {
EnumSet {bits: 0, marker: marker::PhantomData}
}
/// Returns the number of elements in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn len(&self) -> usize {
self.bits.count_ones() as usize
}
/// Returns true if the `EnumSet` is empty.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_empty(&self) -> bool {
self.bits == 0
}
pub fn clear(&mut self) {
self.bits = 0;
}
/// Returns `false` if the `EnumSet` contains any enum of the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_disjoint(&self, other: &EnumSet<E>) -> bool {
(self.bits & other.bits) == 0
}
/// Returns `true` if a given `EnumSet` is included in this `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_superset(&self, other: &EnumSet<E>) -> bool {
(self.bits & other.bits) == other.bits
}
/// Returns `true` if this `EnumSet` is included in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_subset(&self, other: &EnumSet<E>) -> bool {
other.is_superset(self)
}
/// Returns the union of both `EnumSets`.
pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits,
marker: marker::PhantomData}
}
/// Returns the intersection of both `EnumSets`.
pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits,
marker: marker::PhantomData}
}
/// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn insert(&mut self, e: E) -> bool {
let result =!self.contains(&e);
self.bits |= bit(&e);
result
}
/// Removes an enum from the EnumSet
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn remove(&mut self, e: &E) -> bool {
let result = self.contains(e);
self.bits &=!bit(e);
result
}
/// Returns `true` if an `EnumSet` contains a given enum.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn contains(&self, e: &E) -> bool {
(self.bits & bit(e))!= 0
}
/// Returns an iterator over an `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn iter(&self) -> Iter<E> {
Iter::new(self.bits)
}
}
impl<E:CLike> Sub for EnumSet<E> {
type Output = EnumSet<E>;
fn sub(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits &!e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitOr for EnumSet<E> {
type Output = EnumSet<E>;
fn bitor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitAnd for EnumSet<E> {
type Output = EnumSet<E>;
fn bitand(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitXor for EnumSet<E> {
type Output = EnumSet<E>;
fn bitxor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits ^ e.bits, marker: marker::PhantomData}
}
}
/// An iterator over an EnumSet
pub struct Iter<E> {
index: usize,
bits: usize,
marker: marker::PhantomData<E>,
}
// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<E> Clone for Iter<E> {
fn clone(&self) -> Iter<E> {
Iter {
index: self.index,
bits: self.bits,
marker: marker::PhantomData,
}
}
}
|
impl<E:CLike> Iterator for Iter<E> {
type Item = E;
fn next(&mut self) -> Option<E> {
if self.bits == 0 {
return None;
}
while (self.bits & 1) == 0 {
self.index += 1;
self.bits >>= 1;
}
let elem = CLike::from_usize(self.index);
self.index += 1;
self.bits >>= 1;
Some(elem)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = self.bits.count_ones() as usize;
(exact, Some(exact))
}
}
impl<E:CLike> FromIterator<E> for EnumSet<E> {
fn from_iter<I: IntoIterator<Item=E>>(iter: I) -> EnumSet<E> {
let mut ret = EnumSet::new();
ret.extend(iter);
ret
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike {
type Item = E;
type IntoIter = Iter<E>;
fn into_iter(self) -> Iter<E> {
self.iter()
}
}
impl<E:CLike> Extend<E> for EnumSet<E> {
fn extend<I: IntoIterator<Item=E>>(&mut self, iter: I) {
for element in iter {
self.insert(element);
}
}
}
|
impl<E:CLike> Iter<E> {
fn new(bits: usize) -> Iter<E> {
Iter { index: 0, bits: bits, marker: marker::PhantomData }
}
}
|
random_line_split
|
enum_set.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A structure for holding a set of enum variants.
//!
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.
use core::prelude::*;
use core::marker;
use core::fmt;
use core::iter::{FromIterator};
use core::ops::{Sub, BitOr, BitAnd, BitXor};
// FIXME(contentions): implement union family of methods? (general design may be wrong here)
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A specialized set implementation to use enum types.
///
/// It is a logic error for an item to be modified in such a way that the transformation of the
/// item to or from a `usize`, as determined by the `CLike` trait, changes while the item is in the
/// set. This is normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe
/// code.
pub struct EnumSet<E> {
// We must maintain the invariant that no bits are set
// for which no variant exists
bits: usize,
marker: marker::PhantomData<E>,
}
impl<E> Copy for EnumSet<E> {}
impl<E> Clone for EnumSet<E> {
fn clone(&self) -> EnumSet<E> { *self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<E:CLike + fmt::Debug> fmt::Debug for EnumSet<E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "{{"));
let mut first = true;
for e in self {
if!first {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{:?}", e));
first = false;
}
write!(fmt, "}}")
}
}
/// An interface for casting C-like enum to usize and back.
/// A typically implementation is as below.
///
/// ```{rust,ignore}
/// #[repr(usize)]
/// enum Foo {
/// A, B, C
/// }
///
/// impl CLike for Foo {
/// fn to_usize(&self) -> usize {
/// *self as usize
/// }
///
/// fn from_usize(v: usize) -> Foo {
/// unsafe { mem::transmute(v) }
/// }
/// }
/// ```
pub trait CLike {
/// Converts a C-like enum to a `usize`.
fn to_usize(&self) -> usize;
/// Converts a `usize` to a C-like enum.
fn from_usize(usize) -> Self;
}
fn bit<E:CLike>(e: &E) -> usize {
use core::usize;
let value = e.to_usize();
assert!(value < usize::BITS,
"EnumSet only supports up to {} variants.", usize::BITS - 1);
1 << value
}
impl<E:CLike> EnumSet<E> {
/// Returns an empty `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn new() -> EnumSet<E> {
EnumSet {bits: 0, marker: marker::PhantomData}
}
/// Returns the number of elements in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn len(&self) -> usize {
self.bits.count_ones() as usize
}
/// Returns true if the `EnumSet` is empty.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_empty(&self) -> bool {
self.bits == 0
}
pub fn clear(&mut self) {
self.bits = 0;
}
/// Returns `false` if the `EnumSet` contains any enum of the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_disjoint(&self, other: &EnumSet<E>) -> bool {
(self.bits & other.bits) == 0
}
/// Returns `true` if a given `EnumSet` is included in this `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_superset(&self, other: &EnumSet<E>) -> bool {
(self.bits & other.bits) == other.bits
}
/// Returns `true` if this `EnumSet` is included in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_subset(&self, other: &EnumSet<E>) -> bool {
other.is_superset(self)
}
/// Returns the union of both `EnumSets`.
pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits,
marker: marker::PhantomData}
}
/// Returns the intersection of both `EnumSets`.
pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits,
marker: marker::PhantomData}
}
/// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn insert(&mut self, e: E) -> bool {
let result =!self.contains(&e);
self.bits |= bit(&e);
result
}
/// Removes an enum from the EnumSet
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn remove(&mut self, e: &E) -> bool {
let result = self.contains(e);
self.bits &=!bit(e);
result
}
/// Returns `true` if an `EnumSet` contains a given enum.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn contains(&self, e: &E) -> bool {
(self.bits & bit(e))!= 0
}
/// Returns an iterator over an `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn iter(&self) -> Iter<E> {
Iter::new(self.bits)
}
}
impl<E:CLike> Sub for EnumSet<E> {
type Output = EnumSet<E>;
fn sub(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits &!e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitOr for EnumSet<E> {
type Output = EnumSet<E>;
fn bitor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitAnd for EnumSet<E> {
type Output = EnumSet<E>;
fn bitand(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitXor for EnumSet<E> {
type Output = EnumSet<E>;
fn bitxor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits ^ e.bits, marker: marker::PhantomData}
}
}
/// An iterator over an EnumSet
pub struct Iter<E> {
index: usize,
bits: usize,
marker: marker::PhantomData<E>,
}
// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<E> Clone for Iter<E> {
fn clone(&self) -> Iter<E> {
Iter {
index: self.index,
bits: self.bits,
marker: marker::PhantomData,
}
}
}
impl<E:CLike> Iter<E> {
fn new(bits: usize) -> Iter<E> {
Iter { index: 0, bits: bits, marker: marker::PhantomData }
}
}
impl<E:CLike> Iterator for Iter<E> {
type Item = E;
fn next(&mut self) -> Option<E> {
if self.bits == 0 {
return None;
}
while (self.bits & 1) == 0 {
self.index += 1;
self.bits >>= 1;
}
let elem = CLike::from_usize(self.index);
self.index += 1;
self.bits >>= 1;
Some(elem)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = self.bits.count_ones() as usize;
(exact, Some(exact))
}
}
impl<E:CLike> FromIterator<E> for EnumSet<E> {
fn from_iter<I: IntoIterator<Item=E>>(iter: I) -> EnumSet<E> {
let mut ret = EnumSet::new();
ret.extend(iter);
ret
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike {
type Item = E;
type IntoIter = Iter<E>;
fn into_iter(self) -> Iter<E> {
self.iter()
}
}
impl<E:CLike> Extend<E> for EnumSet<E> {
fn
|
<I: IntoIterator<Item=E>>(&mut self, iter: I) {
for element in iter {
self.insert(element);
}
}
}
|
extend
|
identifier_name
|
enum_set.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A structure for holding a set of enum variants.
//!
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.
use core::prelude::*;
use core::marker;
use core::fmt;
use core::iter::{FromIterator};
use core::ops::{Sub, BitOr, BitAnd, BitXor};
// FIXME(contentions): implement union family of methods? (general design may be wrong here)
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A specialized set implementation to use enum types.
///
/// It is a logic error for an item to be modified in such a way that the transformation of the
/// item to or from a `usize`, as determined by the `CLike` trait, changes while the item is in the
/// set. This is normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe
/// code.
pub struct EnumSet<E> {
// We must maintain the invariant that no bits are set
// for which no variant exists
bits: usize,
marker: marker::PhantomData<E>,
}
impl<E> Copy for EnumSet<E> {}
impl<E> Clone for EnumSet<E> {
fn clone(&self) -> EnumSet<E> { *self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<E:CLike + fmt::Debug> fmt::Debug for EnumSet<E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "{{"));
let mut first = true;
for e in self {
if!first
|
try!(write!(fmt, "{:?}", e));
first = false;
}
write!(fmt, "}}")
}
}
/// An interface for casting C-like enum to usize and back.
/// A typically implementation is as below.
///
/// ```{rust,ignore}
/// #[repr(usize)]
/// enum Foo {
/// A, B, C
/// }
///
/// impl CLike for Foo {
/// fn to_usize(&self) -> usize {
/// *self as usize
/// }
///
/// fn from_usize(v: usize) -> Foo {
/// unsafe { mem::transmute(v) }
/// }
/// }
/// ```
pub trait CLike {
/// Converts a C-like enum to a `usize`.
fn to_usize(&self) -> usize;
/// Converts a `usize` to a C-like enum.
fn from_usize(usize) -> Self;
}
fn bit<E:CLike>(e: &E) -> usize {
use core::usize;
let value = e.to_usize();
assert!(value < usize::BITS,
"EnumSet only supports up to {} variants.", usize::BITS - 1);
1 << value
}
impl<E:CLike> EnumSet<E> {
/// Returns an empty `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn new() -> EnumSet<E> {
EnumSet {bits: 0, marker: marker::PhantomData}
}
/// Returns the number of elements in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn len(&self) -> usize {
self.bits.count_ones() as usize
}
/// Returns true if the `EnumSet` is empty.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_empty(&self) -> bool {
self.bits == 0
}
pub fn clear(&mut self) {
self.bits = 0;
}
/// Returns `false` if the `EnumSet` contains any enum of the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_disjoint(&self, other: &EnumSet<E>) -> bool {
(self.bits & other.bits) == 0
}
/// Returns `true` if a given `EnumSet` is included in this `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_superset(&self, other: &EnumSet<E>) -> bool {
(self.bits & other.bits) == other.bits
}
/// Returns `true` if this `EnumSet` is included in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_subset(&self, other: &EnumSet<E>) -> bool {
other.is_superset(self)
}
/// Returns the union of both `EnumSets`.
pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits,
marker: marker::PhantomData}
}
/// Returns the intersection of both `EnumSets`.
pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits,
marker: marker::PhantomData}
}
/// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn insert(&mut self, e: E) -> bool {
let result =!self.contains(&e);
self.bits |= bit(&e);
result
}
/// Removes an enum from the EnumSet
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn remove(&mut self, e: &E) -> bool {
let result = self.contains(e);
self.bits &=!bit(e);
result
}
/// Returns `true` if an `EnumSet` contains a given enum.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn contains(&self, e: &E) -> bool {
(self.bits & bit(e))!= 0
}
/// Returns an iterator over an `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn iter(&self) -> Iter<E> {
Iter::new(self.bits)
}
}
impl<E:CLike> Sub for EnumSet<E> {
type Output = EnumSet<E>;
fn sub(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits &!e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitOr for EnumSet<E> {
type Output = EnumSet<E>;
fn bitor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitAnd for EnumSet<E> {
type Output = EnumSet<E>;
fn bitand(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitXor for EnumSet<E> {
type Output = EnumSet<E>;
fn bitxor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits ^ e.bits, marker: marker::PhantomData}
}
}
/// An iterator over an EnumSet
pub struct Iter<E> {
index: usize,
bits: usize,
marker: marker::PhantomData<E>,
}
// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<E> Clone for Iter<E> {
fn clone(&self) -> Iter<E> {
Iter {
index: self.index,
bits: self.bits,
marker: marker::PhantomData,
}
}
}
impl<E:CLike> Iter<E> {
fn new(bits: usize) -> Iter<E> {
Iter { index: 0, bits: bits, marker: marker::PhantomData }
}
}
impl<E:CLike> Iterator for Iter<E> {
type Item = E;
fn next(&mut self) -> Option<E> {
if self.bits == 0 {
return None;
}
while (self.bits & 1) == 0 {
self.index += 1;
self.bits >>= 1;
}
let elem = CLike::from_usize(self.index);
self.index += 1;
self.bits >>= 1;
Some(elem)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = self.bits.count_ones() as usize;
(exact, Some(exact))
}
}
impl<E:CLike> FromIterator<E> for EnumSet<E> {
fn from_iter<I: IntoIterator<Item=E>>(iter: I) -> EnumSet<E> {
let mut ret = EnumSet::new();
ret.extend(iter);
ret
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike {
type Item = E;
type IntoIter = Iter<E>;
fn into_iter(self) -> Iter<E> {
self.iter()
}
}
impl<E:CLike> Extend<E> for EnumSet<E> {
fn extend<I: IntoIterator<Item=E>>(&mut self, iter: I) {
for element in iter {
self.insert(element);
}
}
}
|
{
try!(write!(fmt, ", "));
}
|
conditional_block
|
enum_set.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A structure for holding a set of enum variants.
//!
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.
use core::prelude::*;
use core::marker;
use core::fmt;
use core::iter::{FromIterator};
use core::ops::{Sub, BitOr, BitAnd, BitXor};
// FIXME(contentions): implement union family of methods? (general design may be wrong here)
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A specialized set implementation to use enum types.
///
/// It is a logic error for an item to be modified in such a way that the transformation of the
/// item to or from a `usize`, as determined by the `CLike` trait, changes while the item is in the
/// set. This is normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe
/// code.
pub struct EnumSet<E> {
// We must maintain the invariant that no bits are set
// for which no variant exists
bits: usize,
marker: marker::PhantomData<E>,
}
impl<E> Copy for EnumSet<E> {}
impl<E> Clone for EnumSet<E> {
fn clone(&self) -> EnumSet<E> { *self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<E:CLike + fmt::Debug> fmt::Debug for EnumSet<E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "{{"));
let mut first = true;
for e in self {
if!first {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{:?}", e));
first = false;
}
write!(fmt, "}}")
}
}
/// An interface for casting C-like enum to usize and back.
/// A typically implementation is as below.
///
/// ```{rust,ignore}
/// #[repr(usize)]
/// enum Foo {
/// A, B, C
/// }
///
/// impl CLike for Foo {
/// fn to_usize(&self) -> usize {
/// *self as usize
/// }
///
/// fn from_usize(v: usize) -> Foo {
/// unsafe { mem::transmute(v) }
/// }
/// }
/// ```
pub trait CLike {
/// Converts a C-like enum to a `usize`.
fn to_usize(&self) -> usize;
/// Converts a `usize` to a C-like enum.
fn from_usize(usize) -> Self;
}
fn bit<E:CLike>(e: &E) -> usize {
use core::usize;
let value = e.to_usize();
assert!(value < usize::BITS,
"EnumSet only supports up to {} variants.", usize::BITS - 1);
1 << value
}
impl<E:CLike> EnumSet<E> {
/// Returns an empty `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn new() -> EnumSet<E> {
EnumSet {bits: 0, marker: marker::PhantomData}
}
/// Returns the number of elements in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn len(&self) -> usize {
self.bits.count_ones() as usize
}
/// Returns true if the `EnumSet` is empty.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_empty(&self) -> bool {
self.bits == 0
}
pub fn clear(&mut self) {
self.bits = 0;
}
/// Returns `false` if the `EnumSet` contains any enum of the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_disjoint(&self, other: &EnumSet<E>) -> bool {
(self.bits & other.bits) == 0
}
/// Returns `true` if a given `EnumSet` is included in this `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_superset(&self, other: &EnumSet<E>) -> bool
|
/// Returns `true` if this `EnumSet` is included in the given `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn is_subset(&self, other: &EnumSet<E>) -> bool {
other.is_superset(self)
}
/// Returns the union of both `EnumSets`.
pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits,
marker: marker::PhantomData}
}
/// Returns the intersection of both `EnumSets`.
pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits,
marker: marker::PhantomData}
}
/// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn insert(&mut self, e: E) -> bool {
let result =!self.contains(&e);
self.bits |= bit(&e);
result
}
/// Removes an enum from the EnumSet
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn remove(&mut self, e: &E) -> bool {
let result = self.contains(e);
self.bits &=!bit(e);
result
}
/// Returns `true` if an `EnumSet` contains a given enum.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn contains(&self, e: &E) -> bool {
(self.bits & bit(e))!= 0
}
/// Returns an iterator over an `EnumSet`.
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn iter(&self) -> Iter<E> {
Iter::new(self.bits)
}
}
impl<E:CLike> Sub for EnumSet<E> {
type Output = EnumSet<E>;
fn sub(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits &!e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitOr for EnumSet<E> {
type Output = EnumSet<E>;
fn bitor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitAnd for EnumSet<E> {
type Output = EnumSet<E>;
fn bitand(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits, marker: marker::PhantomData}
}
}
impl<E:CLike> BitXor for EnumSet<E> {
type Output = EnumSet<E>;
fn bitxor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits ^ e.bits, marker: marker::PhantomData}
}
}
/// An iterator over an EnumSet
pub struct Iter<E> {
index: usize,
bits: usize,
marker: marker::PhantomData<E>,
}
// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<E> Clone for Iter<E> {
fn clone(&self) -> Iter<E> {
Iter {
index: self.index,
bits: self.bits,
marker: marker::PhantomData,
}
}
}
impl<E:CLike> Iter<E> {
fn new(bits: usize) -> Iter<E> {
Iter { index: 0, bits: bits, marker: marker::PhantomData }
}
}
impl<E:CLike> Iterator for Iter<E> {
type Item = E;
fn next(&mut self) -> Option<E> {
if self.bits == 0 {
return None;
}
while (self.bits & 1) == 0 {
self.index += 1;
self.bits >>= 1;
}
let elem = CLike::from_usize(self.index);
self.index += 1;
self.bits >>= 1;
Some(elem)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = self.bits.count_ones() as usize;
(exact, Some(exact))
}
}
impl<E:CLike> FromIterator<E> for EnumSet<E> {
fn from_iter<I: IntoIterator<Item=E>>(iter: I) -> EnumSet<E> {
let mut ret = EnumSet::new();
ret.extend(iter);
ret
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike {
type Item = E;
type IntoIter = Iter<E>;
fn into_iter(self) -> Iter<E> {
self.iter()
}
}
impl<E:CLike> Extend<E> for EnumSet<E> {
fn extend<I: IntoIterator<Item=E>>(&mut self, iter: I) {
for element in iter {
self.insert(element);
}
}
}
|
{
(self.bits & other.bits) == other.bits
}
|
identifier_body
|
main.rs
|
extern crate chrono;
extern crate clap;
extern crate openssl;
extern crate helperlib;
use chrono::Utc;
use clap::{Arg, App};
use openssl::x509::X509;
fn
|
() {
let args = App::new("X.509 Parse")
.about("Experiment in parsing X.509 certificates")
.arg(Arg::with_name("InputFile")
.long("file")
.short("f")
.takes_value(true)
.required(true))
.get_matches();
let input_file_path = args.value_of("InputFile").unwrap();
let cert_bytes = helperlib::get_cert_bytes(input_file_path).unwrap();
let cert = X509::from_pem(&cert_bytes).unwrap();
println!("------------COMMON NAMES------------");
let cert_common_names = helperlib::get_subject_name(&cert);
for cn in cert_common_names {
match cn {
Ok(cn) => println!("{:?}", cn),
Err(err) => println!("{:?}", err)
}
}
println!("------------SUBJECT ALT NAMES------------");
let cert_subject_alt_names = helperlib::get_subject_alt_names(&cert);
match cert_subject_alt_names {
None => println!("{:?}", "No SANs listed in certificate".to_string()),
Some(sans) => {
for san in sans {
println!("{:?}", san)
}
}
}
println!("------------Validity Dates------------");
let validity_dates = helperlib::get_validity_dates(&cert);
println!("Not before: {}", validity_dates.0);
println!("Not after: {}", validity_dates.1);
let not_before = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.0);
match not_before {
Err(e) => println!("Error parsing not_before date: {}", e),
Ok(not_before) => println!("Not before: {:?}", not_before)
}
let not_after = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.1);
match not_after {
Err(e) => println!("Error parsing not_after date: {}", e),
Ok(not_after) => println!("Not after: {:?}", not_after)
}
if let Ok(not_before) = not_before {
if let Ok(not_after) = not_after {
let now = Utc::now();
if not_before <= now && now <= not_after {
println!("Certificate is between validity dates");
} else if now < not_before {
println!("Certificate not yet valid");
} else {
println!("Certificate expired");
}
}
}
}
|
main
|
identifier_name
|
main.rs
|
extern crate chrono;
extern crate clap;
extern crate openssl;
extern crate helperlib;
use chrono::Utc;
use clap::{Arg, App};
use openssl::x509::X509;
fn main()
|
}
}
println!("------------SUBJECT ALT NAMES------------");
let cert_subject_alt_names = helperlib::get_subject_alt_names(&cert);
match cert_subject_alt_names {
None => println!("{:?}", "No SANs listed in certificate".to_string()),
Some(sans) => {
for san in sans {
println!("{:?}", san)
}
}
}
println!("------------Validity Dates------------");
let validity_dates = helperlib::get_validity_dates(&cert);
println!("Not before: {}", validity_dates.0);
println!("Not after: {}", validity_dates.1);
let not_before = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.0);
match not_before {
Err(e) => println!("Error parsing not_before date: {}", e),
Ok(not_before) => println!("Not before: {:?}", not_before)
}
let not_after = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.1);
match not_after {
Err(e) => println!("Error parsing not_after date: {}", e),
Ok(not_after) => println!("Not after: {:?}", not_after)
}
if let Ok(not_before) = not_before {
if let Ok(not_after) = not_after {
let now = Utc::now();
if not_before <= now && now <= not_after {
println!("Certificate is between validity dates");
} else if now < not_before {
println!("Certificate not yet valid");
} else {
println!("Certificate expired");
}
}
}
}
|
{
let args = App::new("X.509 Parse")
.about("Experiment in parsing X.509 certificates")
.arg(Arg::with_name("InputFile")
.long("file")
.short("f")
.takes_value(true)
.required(true))
.get_matches();
let input_file_path = args.value_of("InputFile").unwrap();
let cert_bytes = helperlib::get_cert_bytes(input_file_path).unwrap();
let cert = X509::from_pem(&cert_bytes).unwrap();
println!("------------COMMON NAMES------------");
let cert_common_names = helperlib::get_subject_name(&cert);
for cn in cert_common_names {
match cn {
Ok(cn) => println!("{:?}", cn),
Err(err) => println!("{:?}", err)
|
identifier_body
|
main.rs
|
extern crate chrono;
extern crate clap;
extern crate openssl;
extern crate helperlib;
use chrono::Utc;
use clap::{Arg, App};
use openssl::x509::X509;
fn main() {
let args = App::new("X.509 Parse")
.about("Experiment in parsing X.509 certificates")
.arg(Arg::with_name("InputFile")
.long("file")
.short("f")
.takes_value(true)
.required(true))
.get_matches();
let input_file_path = args.value_of("InputFile").unwrap();
let cert_bytes = helperlib::get_cert_bytes(input_file_path).unwrap();
let cert = X509::from_pem(&cert_bytes).unwrap();
println!("------------COMMON NAMES------------");
let cert_common_names = helperlib::get_subject_name(&cert);
for cn in cert_common_names {
match cn {
Ok(cn) => println!("{:?}", cn),
Err(err) => println!("{:?}", err)
}
}
println!("------------SUBJECT ALT NAMES------------");
let cert_subject_alt_names = helperlib::get_subject_alt_names(&cert);
match cert_subject_alt_names {
None => println!("{:?}", "No SANs listed in certificate".to_string()),
Some(sans) => {
for san in sans {
println!("{:?}", san)
}
}
}
println!("------------Validity Dates------------");
let validity_dates = helperlib::get_validity_dates(&cert);
println!("Not before: {}", validity_dates.0);
println!("Not after: {}", validity_dates.1);
let not_before = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.0);
match not_before {
Err(e) => println!("Error parsing not_before date: {}", e),
Ok(not_before) => println!("Not before: {:?}", not_before)
}
let not_after = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.1);
match not_after {
Err(e) => println!("Error parsing not_after date: {}", e),
Ok(not_after) => println!("Not after: {:?}", not_after)
}
if let Ok(not_before) = not_before {
if let Ok(not_after) = not_after
|
}
}
|
{
let now = Utc::now();
if not_before <= now && now <= not_after {
println!("Certificate is between validity dates");
} else if now < not_before {
println!("Certificate not yet valid");
} else {
println!("Certificate expired");
}
}
|
conditional_block
|
main.rs
|
extern crate chrono;
extern crate clap;
extern crate openssl;
extern crate helperlib;
use chrono::Utc;
use clap::{Arg, App};
use openssl::x509::X509;
|
fn main() {
let args = App::new("X.509 Parse")
.about("Experiment in parsing X.509 certificates")
.arg(Arg::with_name("InputFile")
.long("file")
.short("f")
.takes_value(true)
.required(true))
.get_matches();
let input_file_path = args.value_of("InputFile").unwrap();
let cert_bytes = helperlib::get_cert_bytes(input_file_path).unwrap();
let cert = X509::from_pem(&cert_bytes).unwrap();
println!("------------COMMON NAMES------------");
let cert_common_names = helperlib::get_subject_name(&cert);
for cn in cert_common_names {
match cn {
Ok(cn) => println!("{:?}", cn),
Err(err) => println!("{:?}", err)
}
}
println!("------------SUBJECT ALT NAMES------------");
let cert_subject_alt_names = helperlib::get_subject_alt_names(&cert);
match cert_subject_alt_names {
None => println!("{:?}", "No SANs listed in certificate".to_string()),
Some(sans) => {
for san in sans {
println!("{:?}", san)
}
}
}
println!("------------Validity Dates------------");
let validity_dates = helperlib::get_validity_dates(&cert);
println!("Not before: {}", validity_dates.0);
println!("Not after: {}", validity_dates.1);
let not_before = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.0);
match not_before {
Err(e) => println!("Error parsing not_before date: {}", e),
Ok(not_before) => println!("Not before: {:?}", not_before)
}
let not_after = helperlib::convert_Asn1TimeRef_to_DateTimeUTC(validity_dates.1);
match not_after {
Err(e) => println!("Error parsing not_after date: {}", e),
Ok(not_after) => println!("Not after: {:?}", not_after)
}
if let Ok(not_before) = not_before {
if let Ok(not_after) = not_after {
let now = Utc::now();
if not_before <= now && now <= not_after {
println!("Certificate is between validity dates");
} else if now < not_before {
println!("Certificate not yet valid");
} else {
println!("Certificate expired");
}
}
}
}
|
random_line_split
|
|
world.rs
|
use rand::Rng;
use crate::{
geometry::Size,
models::{Bullet, Enemy, Particle, Player, Powerup, Star},
};
const MAX_STARS: usize = 100;
|
pub bullets: Vec<Bullet>,
pub enemies: Vec<Enemy>,
pub stars: Vec<Star>,
pub size: Size,
}
impl World {
/// Returns a new world of the given size
pub fn new<R: Rng>(rng: &mut R, size: Size) -> World {
World {
player: Player::random(rng, size),
particles: Vec::with_capacity(1000),
powerups: vec![],
bullets: vec![],
enemies: vec![],
stars: (0..MAX_STARS).map(|_| Star::new(size, rng)).collect(),
size: size,
}
}
}
|
/// A model that contains the other models and renders them
pub struct World {
pub player: Player,
pub particles: Vec<Particle>,
pub powerups: Vec<Powerup>,
|
random_line_split
|
world.rs
|
use rand::Rng;
use crate::{
geometry::Size,
models::{Bullet, Enemy, Particle, Player, Powerup, Star},
};
const MAX_STARS: usize = 100;
/// A model that contains the other models and renders them
pub struct World {
pub player: Player,
pub particles: Vec<Particle>,
pub powerups: Vec<Powerup>,
pub bullets: Vec<Bullet>,
pub enemies: Vec<Enemy>,
pub stars: Vec<Star>,
pub size: Size,
}
impl World {
/// Returns a new world of the given size
pub fn new<R: Rng>(rng: &mut R, size: Size) -> World
|
}
|
{
World {
player: Player::random(rng, size),
particles: Vec::with_capacity(1000),
powerups: vec![],
bullets: vec![],
enemies: vec![],
stars: (0..MAX_STARS).map(|_| Star::new(size, rng)).collect(),
size: size,
}
}
|
identifier_body
|
world.rs
|
use rand::Rng;
use crate::{
geometry::Size,
models::{Bullet, Enemy, Particle, Player, Powerup, Star},
};
const MAX_STARS: usize = 100;
/// A model that contains the other models and renders them
pub struct
|
{
pub player: Player,
pub particles: Vec<Particle>,
pub powerups: Vec<Powerup>,
pub bullets: Vec<Bullet>,
pub enemies: Vec<Enemy>,
pub stars: Vec<Star>,
pub size: Size,
}
impl World {
/// Returns a new world of the given size
pub fn new<R: Rng>(rng: &mut R, size: Size) -> World {
World {
player: Player::random(rng, size),
particles: Vec::with_capacity(1000),
powerups: vec![],
bullets: vec![],
enemies: vec![],
stars: (0..MAX_STARS).map(|_| Star::new(size, rng)).collect(),
size: size,
}
}
}
|
World
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.