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 |
---|---|---|---|---|
main.rs
|
// Works under Rust 1.14.0 :)
extern crate rand;
use std::io::prelude::*;
use std::io;
use rand::{thread_rng, Rng};
const MAX_ATTEMPTS:i16 = 5;
fn
|
(guess:u8, target:u8, remaining_guesses:i16) -> bool {
if guess == target {
// We won!
println!("Noice! You gone done did good, kid.");
return true;
} else {
if guess < target {
// Go lower
println!("Hmm too low, bro.");
} else if guess > target {
// Go higher
println!("Yo too high, guy.");
}
println!("You have {0} guesses left.
", remaining_guesses);
return false;
}
}
fn main() {
println!("
Yo! Welcome to Guess the Number with Rust!
Rust will, like, pick a number between 1 and 100 and, like, you've gotta guess it or whatever.
Oh. And you only get 5 guesses. Bonne chance!
");
let mut rng = thread_rng();
let _number = rng.gen_range::<u8>(1, 100);
let mut _attempt = 1;
// Our game loop
loop {
let position = MAX_ATTEMPTS - _attempt;
if position < 0 {
println!("Ouf. Sorry but you're all out of guesses. You lose =(");
println!("The number you were looking for is {}", _number);
break;
}
// Get input:
let mut input_text = String::new();
print!("Take a guess: ");
io::stdout().flush().ok(); //.expect("Could not flush stdout");
io::stdin().read_line(&mut input_text).unwrap();
match input_text.trim().parse::<u8>().ok() {
Some(i) => if play(i, _number, position) {
break;
} else {
_attempt += 1;
},
None => println!("Enter a number please...")
}
}
}
|
play
|
identifier_name
|
main.rs
|
// Works under Rust 1.14.0 :)
extern crate rand;
use std::io::prelude::*;
use std::io;
use rand::{thread_rng, Rng};
const MAX_ATTEMPTS:i16 = 5;
fn play(guess:u8, target:u8, remaining_guesses:i16) -> bool {
if guess == target {
// We won!
println!("Noice! You gone done did good, kid.");
return true;
} else {
if guess < target {
// Go lower
println!("Hmm too low, bro.");
} else if guess > target {
// Go higher
println!("Yo too high, guy.");
}
println!("You have {0} guesses left.
", remaining_guesses);
return false;
}
}
fn main() {
println!("
Yo! Welcome to Guess the Number with Rust!
Rust will, like, pick a number between 1 and 100 and, like, you've gotta guess it or whatever.
Oh. And you only get 5 guesses. Bonne chance!
");
let mut rng = thread_rng();
let _number = rng.gen_range::<u8>(1, 100);
let mut _attempt = 1;
// Our game loop
loop {
let position = MAX_ATTEMPTS - _attempt;
if position < 0
|
// Get input:
let mut input_text = String::new();
print!("Take a guess: ");
io::stdout().flush().ok(); //.expect("Could not flush stdout");
io::stdin().read_line(&mut input_text).unwrap();
match input_text.trim().parse::<u8>().ok() {
Some(i) => if play(i, _number, position) {
break;
} else {
_attempt += 1;
},
None => println!("Enter a number please...")
}
}
}
|
{
println!("Ouf. Sorry but you're all out of guesses. You lose =(");
println!("The number you were looking for is {}", _number);
break;
}
|
conditional_block
|
main.rs
|
// Works under Rust 1.14.0 :)
extern crate rand;
use std::io::prelude::*;
use std::io;
use rand::{thread_rng, Rng};
const MAX_ATTEMPTS:i16 = 5;
fn play(guess:u8, target:u8, remaining_guesses:i16) -> bool {
if guess == target {
// We won!
println!("Noice! You gone done did good, kid.");
return true;
} else {
if guess < target {
// Go lower
println!("Hmm too low, bro.");
} else if guess > target {
// Go higher
|
println!("Yo too high, guy.");
}
println!("You have {0} guesses left.
", remaining_guesses);
return false;
}
}
fn main() {
println!("
Yo! Welcome to Guess the Number with Rust!
Rust will, like, pick a number between 1 and 100 and, like, you've gotta guess it or whatever.
Oh. And you only get 5 guesses. Bonne chance!
");
let mut rng = thread_rng();
let _number = rng.gen_range::<u8>(1, 100);
let mut _attempt = 1;
// Our game loop
loop {
let position = MAX_ATTEMPTS - _attempt;
if position < 0 {
println!("Ouf. Sorry but you're all out of guesses. You lose =(");
println!("The number you were looking for is {}", _number);
break;
}
// Get input:
let mut input_text = String::new();
print!("Take a guess: ");
io::stdout().flush().ok(); //.expect("Could not flush stdout");
io::stdin().read_line(&mut input_text).unwrap();
match input_text.trim().parse::<u8>().ok() {
Some(i) => if play(i, _number, position) {
break;
} else {
_attempt += 1;
},
None => println!("Enter a number please...")
}
}
}
|
random_line_split
|
|
generic-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// Some versions of the non-rust-enabled LLDB print the wrong generic
// parameter type names in this test.
// rust-lldb
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print int_int
// gdbg-check:$1 = {key = 0, value = 1}
// gdbr-check:$1 = generic_struct::AGenericStruct<i32, i32> {key: 0, value: 1}
// gdb-command:print int_float
// gdbg-check:$2 = {key = 2, value = 3.5}
// gdbr-check:$2 = generic_struct::AGenericStruct<i32, f64> {key: 2, value: 3.5}
// gdb-command:print float_int
// gdbg-check:$3 = {key = 4.5, value = 5}
// gdbr-check:$3 = generic_struct::AGenericStruct<f64, i32> {key: 4.5, value: 5}
// gdb-command:print float_int_float
// gdbg-check:$4 = {key = 6.5, value = {key = 7, value = 8.5}}
// gdbr-check:$4 = generic_struct::AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>> {key: 6.5, value: generic_struct::AGenericStruct<i32, f64> {key: 7, value: 8.5}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print int_int
// lldbg-check:[...]$0 = AGenericStruct<i32, i32> { key: 0, value: 1 }
// lldbr-check:(generic_struct::AGenericStruct<i32, i32>) int_int = AGenericStruct<i32, i32> { key: 0, value: 1 }
// lldb-command:print int_float
// lldbg-check:[...]$1 = AGenericStruct<i32, f64> { key: 2, value: 3.5 }
// lldbr-check:(generic_struct::AGenericStruct<i32, f64>) int_float = AGenericStruct<i32, f64> { key: 2, value: 3.5 }
// lldb-command:print float_int
// lldbg-check:[...]$2 = AGenericStruct<f64, i32> { key: 4.5, value: 5 }
// lldbr-check:(generic_struct::AGenericStruct<f64, i32>) float_int = AGenericStruct<f64, i32> { key: 4.5, value: 5 }
// lldb-command:print float_int_float
// lldbg-check:[...]$3 = AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>> { key: 6.5, value: AGenericStruct<i32, f64> { key: 7, value: 8.5 } }
// lldbr-check:(generic_struct::AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>>) float_int_float = AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>> { key: 6.5, value: AGenericStruct<i32, f64> { key: 7, value: 8.5 } }
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
struct
|
<TKey, TValue> {
key: TKey,
value: TValue
}
fn main() {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5f64 };
let float_int = AGenericStruct { key: 4.5f64, value: 5 };
let float_int_float = AGenericStruct {
key: 6.5f64,
value: AGenericStruct { key: 7, value: 8.5f64 },
};
zzz(); // #break
}
fn zzz() { () }
|
AGenericStruct
|
identifier_name
|
generic-struct.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
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// Some versions of the non-rust-enabled LLDB print the wrong generic
// parameter type names in this test.
// rust-lldb
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print int_int
// gdbg-check:$1 = {key = 0, value = 1}
// gdbr-check:$1 = generic_struct::AGenericStruct<i32, i32> {key: 0, value: 1}
// gdb-command:print int_float
// gdbg-check:$2 = {key = 2, value = 3.5}
// gdbr-check:$2 = generic_struct::AGenericStruct<i32, f64> {key: 2, value: 3.5}
// gdb-command:print float_int
// gdbg-check:$3 = {key = 4.5, value = 5}
// gdbr-check:$3 = generic_struct::AGenericStruct<f64, i32> {key: 4.5, value: 5}
// gdb-command:print float_int_float
// gdbg-check:$4 = {key = 6.5, value = {key = 7, value = 8.5}}
// gdbr-check:$4 = generic_struct::AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>> {key: 6.5, value: generic_struct::AGenericStruct<i32, f64> {key: 7, value: 8.5}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print int_int
// lldbg-check:[...]$0 = AGenericStruct<i32, i32> { key: 0, value: 1 }
// lldbr-check:(generic_struct::AGenericStruct<i32, i32>) int_int = AGenericStruct<i32, i32> { key: 0, value: 1 }
// lldb-command:print int_float
// lldbg-check:[...]$1 = AGenericStruct<i32, f64> { key: 2, value: 3.5 }
// lldbr-check:(generic_struct::AGenericStruct<i32, f64>) int_float = AGenericStruct<i32, f64> { key: 2, value: 3.5 }
// lldb-command:print float_int
// lldbg-check:[...]$2 = AGenericStruct<f64, i32> { key: 4.5, value: 5 }
// lldbr-check:(generic_struct::AGenericStruct<f64, i32>) float_int = AGenericStruct<f64, i32> { key: 4.5, value: 5 }
// lldb-command:print float_int_float
// lldbg-check:[...]$3 = AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>> { key: 6.5, value: AGenericStruct<i32, f64> { key: 7, value: 8.5 } }
// lldbr-check:(generic_struct::AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>>) float_int_float = AGenericStruct<f64, generic_struct::AGenericStruct<i32, f64>> { key: 6.5, value: AGenericStruct<i32, f64> { key: 7, value: 8.5 } }
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
struct AGenericStruct<TKey, TValue> {
key: TKey,
value: TValue
}
fn main() {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5f64 };
let float_int = AGenericStruct { key: 4.5f64, value: 5 };
let float_int_float = AGenericStruct {
key: 6.5f64,
value: AGenericStruct { key: 7, value: 8.5f64 },
};
zzz(); // #break
}
fn zzz() { () }
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
random_line_split
|
protobuf-bin-gen-rust.rs
|
#![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOptions) {
let mut is = File::open(&Path::new(bin)).unwrap();
let fds = parse_from_reader::<FileDescriptorSet>(&mut is as &mut Reader).unwrap();
let file_names: Vec<String> = fds.get_file().iter()
.map(|f| f.get_name().to_string())
.collect();
let results = gen(fds.get_file(), file_names.as_slice(), gen_options);
for r in results.iter() {
let mut file_writer = File::create(&Path::new(r.name.as_slice())).unwrap();
file_writer.write(r.content.as_slice()).unwrap();
}
}
fn
|
() {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options = GenOptions {
dummy: false,
};
write_file(pb_bin.as_slice(), &gen_options);
}
|
main
|
identifier_name
|
protobuf-bin-gen-rust.rs
|
#![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOptions) {
let mut is = File::open(&Path::new(bin)).unwrap();
let fds = parse_from_reader::<FileDescriptorSet>(&mut is as &mut Reader).unwrap();
let file_names: Vec<String> = fds.get_file().iter()
.map(|f| f.get_name().to_string())
.collect();
let results = gen(fds.get_file(), file_names.as_slice(), gen_options);
|
}
}
fn main() {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options = GenOptions {
dummy: false,
};
write_file(pb_bin.as_slice(), &gen_options);
}
|
for r in results.iter() {
let mut file_writer = File::create(&Path::new(r.name.as_slice())).unwrap();
file_writer.write(r.content.as_slice()).unwrap();
|
random_line_split
|
protobuf-bin-gen-rust.rs
|
#![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOptions)
|
fn main() {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options = GenOptions {
dummy: false,
};
write_file(pb_bin.as_slice(), &gen_options);
}
|
{
let mut is = File::open(&Path::new(bin)).unwrap();
let fds = parse_from_reader::<FileDescriptorSet>(&mut is as &mut Reader).unwrap();
let file_names: Vec<String> = fds.get_file().iter()
.map(|f| f.get_name().to_string())
.collect();
let results = gen(fds.get_file(), file_names.as_slice(), gen_options);
for r in results.iter() {
let mut file_writer = File::create(&Path::new(r.name.as_slice())).unwrap();
file_writer.write(r.content.as_slice()).unwrap();
}
}
|
identifier_body
|
borrowck-let-suggestion-suffixes.rs
|
fn id<T>(x: T) -> T { x }
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
|
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live long enough
//~| NOTE borrowed value does not live long enough
} //~ NOTE `young[_]` dropped here while still borrowed
let mut v3 = Vec::new(); // statement 5
v3.push(&id('x')); // statement 6
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
{
let mut v4 = Vec::new(); // (sub) statement 0
v4.push(&id('y'));
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
v4.use_ref();
//~^ NOTE borrow later used here
} // (statement 7)
let mut v5 = Vec::new(); // statement 8
v5.push(&id('z'));
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
v1.push(&old[0]);
(v1, v2, v3, /* v4 is above. */ v5).use_ref();
//~^ NOTE borrow later used here
//~| NOTE borrow later used here
//~| NOTE borrow later used here
}
fn main() {
f();
}
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
|
let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3
|
random_line_split
|
borrowck-let-suggestion-suffixes.rs
|
fn id<T>(x: T) -> T { x }
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live long enough
//~| NOTE borrowed value does not live long enough
} //~ NOTE `young[_]` dropped here while still borrowed
let mut v3 = Vec::new(); // statement 5
v3.push(&id('x')); // statement 6
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
{
let mut v4 = Vec::new(); // (sub) statement 0
v4.push(&id('y'));
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
v4.use_ref();
//~^ NOTE borrow later used here
} // (statement 7)
let mut v5 = Vec::new(); // statement 8
v5.push(&id('z'));
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
v1.push(&old[0]);
(v1, v2, v3, /* v4 is above. */ v5).use_ref();
//~^ NOTE borrow later used here
//~| NOTE borrow later used here
//~| NOTE borrow later used here
}
fn main() {
f();
}
trait Fake { fn use_mut(&mut self) { } fn
|
(&self) { } }
impl<T> Fake for T { }
|
use_ref
|
identifier_name
|
borrowck-let-suggestion-suffixes.rs
|
fn id<T>(x: T) -> T
|
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live long enough
//~| NOTE borrowed value does not live long enough
} //~ NOTE `young[_]` dropped here while still borrowed
let mut v3 = Vec::new(); // statement 5
v3.push(&id('x')); // statement 6
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
{
let mut v4 = Vec::new(); // (sub) statement 0
v4.push(&id('y'));
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
v4.use_ref();
//~^ NOTE borrow later used here
} // (statement 7)
let mut v5 = Vec::new(); // statement 8
v5.push(&id('z'));
//~^ ERROR temporary value dropped while borrowed
//~| NOTE creates a temporary which is freed while still in use
//~| NOTE temporary value is freed at the end of this statement
//~| NOTE consider using a `let` binding to create a longer lived value
v1.push(&old[0]);
(v1, v2, v3, /* v4 is above. */ v5).use_ref();
//~^ NOTE borrow later used here
//~| NOTE borrow later used here
//~| NOTE borrow later used here
}
fn main() {
f();
}
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
|
{ x }
|
identifier_body
|
validations.rs
|
//! Operations related to UTF-8 validation.
use crate::mem;
use super::Utf8Error;
/// Returns the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
fn utf8_first_byte(byte: u8, width: u32) -> u32 {
(byte & (0x7F >> width)) as u32
}
/// Returns the value of `ch` updated with continuation byte `byte`.
#[inline]
fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 {
(ch << 6) | (byte & CONT_MASK) as u32
}
/// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
/// bits `10`).
#[inline]
pub(super) fn utf8_is_cont_byte(byte: u8) -> bool {
(byte &!CONT_MASK) == TAG_CONT_U8
}
#[inline]
fn unwrap_or_0(opt: Option<&u8>) -> u8 {
match opt {
Some(&byte) => byte,
None => 0,
}
}
/// Reads the next code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
return Some(x as u32);
}
// Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w]
// NOTE: Performance is sensitive to the exact formulation here
let init = utf8_first_byte(x, 2);
let y = unwrap_or_0(bytes.next());
let mut ch = utf8_acc_cont_byte(init, y);
if x >= 0xE0 {
// [[x y z] w] case
// 5th bit in 0xE0.. 0xEF is always clear, so `init` is still valid
let z = unwrap_or_0(bytes.next());
let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
ch = init << 12 | y_z;
if x >= 0xF0 {
// [x y z w] case
// use only the lower 3 bits of `init`
let w = unwrap_or_0(bytes.next());
ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
}
}
Some(ch)
}
/// Reads the last code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[inline]
pub(super) fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
where
I: DoubleEndedIterator<Item = &'a u8>,
{
// Decode UTF-8
let w = match *bytes.next_back()? {
next_byte if next_byte < 128 => return Some(next_byte as u32),
back_byte => back_byte,
};
// Multibyte case follows
// Decode from a byte combination out of: [x [y [z w]]]
let mut ch;
let z = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(z, 2);
if utf8_is_cont_byte(z) {
let y = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(y, 3);
if utf8_is_cont_byte(y) {
let x = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(x, 4);
ch = utf8_acc_cont_byte(ch, y);
}
ch = utf8_acc_cont_byte(ch, z);
}
ch = utf8_acc_cont_byte(ch, w);
Some(ch)
}
// use truncation to fit u64 into usize
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
/// Returns `true` if any byte in the word `x` is nonascii (>= 128).
#[inline]
fn contains_nonascii(x: usize) -> bool {
(x & NONASCII_MASK)!= 0
}
/// Walks through `v` checking that it's a valid UTF-8 sequence,
/// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
#[inline(always)]
pub(super) fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
let mut index = 0;
let len = v.len();
let usize_bytes = mem::size_of::<usize>();
let ascii_block_size = 2 * usize_bytes;
let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
let align = v.as_ptr().align_offset(usize_bytes);
while index < len {
let old_offset = index;
macro_rules! err {
($error_len: expr) => {
return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len })
};
}
macro_rules! next {
() => {{
index += 1;
// we needed data, but there was none: error!
if index >= len {
err!(None)
}
v[index]
}};
}
let first = v[index];
if first >= 128 {
let w = UTF8_CHAR_WIDTH[first as usize];
// 2-byte encoding is for codepoints \u{0080} to \u{07ff}
// first C2 80 last DF BF
// 3-byte encoding is for codepoints \u{0800} to \u{ffff}
// first E0 A0 80 last EF BF BF
// excluding surrogates codepoints \u{d800} to \u{dfff}
// ED A0 80 to ED BF BF
// 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
// first F0 90 80 80 last F4 8F BF BF
//
// Use the UTF-8 syntax from the RFC
//
// https://tools.ietf.org/html/rfc3629
// UTF8-1 = %x00-7F
// UTF8-2 = %xC2-DF UTF8-tail
// UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
// %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
// UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
// %xF4 %x80-8F 2( UTF8-tail )
match w {
2 => {
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(1))
}
}
3 => {
match (first, next!()) {
(0xE0, 0xA0..=0xBF)
| (0xE1..=0xEC, 0x80..=0xBF)
| (0xED, 0x80..=0x9F)
| (0xEE..=0xEF, 0x80..=0xBF) => {}
_ => err!(Some(1)),
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(2))
}
}
4 => {
match (first, next!()) {
(0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {}
_ => err!(Some(1)),
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(2))
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(3))
}
}
_ => err!(Some(1)),
}
index += 1;
} else {
// Ascii case, try to skip forward quickly.
// When the pointer is aligned, read 2 words of data per iteration
// until we find a word containing a non-ascii byte.
if align!= usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 {
let ptr = v.as_ptr();
while index < blocks_end {
// SAFETY: since `align - index` and `ascii_block_size` are
// multiples of `usize_bytes`, `block = ptr.add(index)` is
// always aligned with a `usize` so it's safe to dereference
// both `block` and `block.offset(1)`.
unsafe {
let block = ptr.add(index) as *const usize;
// break if there is a nonascii byte
let zu = contains_nonascii(*block);
let zv = contains_nonascii(*block.offset(1));
if zu | zv {
break;
}
}
index += ascii_block_size;
}
// step from the point where the wordwise loop stopped
while index < len && v[index] < 128 {
index += 1;
}
} else {
index += 1;
}
}
}
|
}
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x3F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x5F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x7F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0x9F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0xBF
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, // 0xDF
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF
];
/// Given a first byte, determines how many bytes are in this UTF-8 character.
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn utf8_char_width(b: u8) -> usize {
UTF8_CHAR_WIDTH[b as usize] as usize
}
/// Mask of the value bits of a continuation byte.
const CONT_MASK: u8 = 0b0011_1111;
/// Value of the tag bits (tag mask is!CONT_MASK) of a continuation byte.
const TAG_CONT_U8: u8 = 0b1000_0000;
// truncate `&str` to length at most equal to `max`
// return `true` if it were truncated, and the new str.
pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
if max >= s.len() {
(false, s)
} else {
while!s.is_char_boundary(max) {
max -= 1;
}
(true, &s[..max])
}
}
|
Ok(())
|
random_line_split
|
validations.rs
|
//! Operations related to UTF-8 validation.
use crate::mem;
use super::Utf8Error;
/// Returns the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
fn utf8_first_byte(byte: u8, width: u32) -> u32 {
(byte & (0x7F >> width)) as u32
}
/// Returns the value of `ch` updated with continuation byte `byte`.
#[inline]
fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 {
(ch << 6) | (byte & CONT_MASK) as u32
}
/// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
/// bits `10`).
#[inline]
pub(super) fn utf8_is_cont_byte(byte: u8) -> bool {
(byte &!CONT_MASK) == TAG_CONT_U8
}
#[inline]
fn unwrap_or_0(opt: Option<&u8>) -> u8 {
match opt {
Some(&byte) => byte,
None => 0,
}
}
/// Reads the next code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn
|
<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
return Some(x as u32);
}
// Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w]
// NOTE: Performance is sensitive to the exact formulation here
let init = utf8_first_byte(x, 2);
let y = unwrap_or_0(bytes.next());
let mut ch = utf8_acc_cont_byte(init, y);
if x >= 0xE0 {
// [[x y z] w] case
// 5th bit in 0xE0.. 0xEF is always clear, so `init` is still valid
let z = unwrap_or_0(bytes.next());
let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
ch = init << 12 | y_z;
if x >= 0xF0 {
// [x y z w] case
// use only the lower 3 bits of `init`
let w = unwrap_or_0(bytes.next());
ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
}
}
Some(ch)
}
/// Reads the last code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[inline]
pub(super) fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
where
I: DoubleEndedIterator<Item = &'a u8>,
{
// Decode UTF-8
let w = match *bytes.next_back()? {
next_byte if next_byte < 128 => return Some(next_byte as u32),
back_byte => back_byte,
};
// Multibyte case follows
// Decode from a byte combination out of: [x [y [z w]]]
let mut ch;
let z = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(z, 2);
if utf8_is_cont_byte(z) {
let y = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(y, 3);
if utf8_is_cont_byte(y) {
let x = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(x, 4);
ch = utf8_acc_cont_byte(ch, y);
}
ch = utf8_acc_cont_byte(ch, z);
}
ch = utf8_acc_cont_byte(ch, w);
Some(ch)
}
// use truncation to fit u64 into usize
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
/// Returns `true` if any byte in the word `x` is nonascii (>= 128).
#[inline]
fn contains_nonascii(x: usize) -> bool {
(x & NONASCII_MASK)!= 0
}
/// Walks through `v` checking that it's a valid UTF-8 sequence,
/// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
#[inline(always)]
pub(super) fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
let mut index = 0;
let len = v.len();
let usize_bytes = mem::size_of::<usize>();
let ascii_block_size = 2 * usize_bytes;
let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
let align = v.as_ptr().align_offset(usize_bytes);
while index < len {
let old_offset = index;
macro_rules! err {
($error_len: expr) => {
return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len })
};
}
macro_rules! next {
() => {{
index += 1;
// we needed data, but there was none: error!
if index >= len {
err!(None)
}
v[index]
}};
}
let first = v[index];
if first >= 128 {
let w = UTF8_CHAR_WIDTH[first as usize];
// 2-byte encoding is for codepoints \u{0080} to \u{07ff}
// first C2 80 last DF BF
// 3-byte encoding is for codepoints \u{0800} to \u{ffff}
// first E0 A0 80 last EF BF BF
// excluding surrogates codepoints \u{d800} to \u{dfff}
// ED A0 80 to ED BF BF
// 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
// first F0 90 80 80 last F4 8F BF BF
//
// Use the UTF-8 syntax from the RFC
//
// https://tools.ietf.org/html/rfc3629
// UTF8-1 = %x00-7F
// UTF8-2 = %xC2-DF UTF8-tail
// UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
// %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
// UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
// %xF4 %x80-8F 2( UTF8-tail )
match w {
2 => {
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(1))
}
}
3 => {
match (first, next!()) {
(0xE0, 0xA0..=0xBF)
| (0xE1..=0xEC, 0x80..=0xBF)
| (0xED, 0x80..=0x9F)
| (0xEE..=0xEF, 0x80..=0xBF) => {}
_ => err!(Some(1)),
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(2))
}
}
4 => {
match (first, next!()) {
(0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {}
_ => err!(Some(1)),
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(2))
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(3))
}
}
_ => err!(Some(1)),
}
index += 1;
} else {
// Ascii case, try to skip forward quickly.
// When the pointer is aligned, read 2 words of data per iteration
// until we find a word containing a non-ascii byte.
if align!= usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 {
let ptr = v.as_ptr();
while index < blocks_end {
// SAFETY: since `align - index` and `ascii_block_size` are
// multiples of `usize_bytes`, `block = ptr.add(index)` is
// always aligned with a `usize` so it's safe to dereference
// both `block` and `block.offset(1)`.
unsafe {
let block = ptr.add(index) as *const usize;
// break if there is a nonascii byte
let zu = contains_nonascii(*block);
let zv = contains_nonascii(*block.offset(1));
if zu | zv {
break;
}
}
index += ascii_block_size;
}
// step from the point where the wordwise loop stopped
while index < len && v[index] < 128 {
index += 1;
}
} else {
index += 1;
}
}
}
Ok(())
}
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x3F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x5F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x7F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0x9F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0xBF
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, // 0xDF
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF
];
/// Given a first byte, determines how many bytes are in this UTF-8 character.
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn utf8_char_width(b: u8) -> usize {
UTF8_CHAR_WIDTH[b as usize] as usize
}
/// Mask of the value bits of a continuation byte.
const CONT_MASK: u8 = 0b0011_1111;
/// Value of the tag bits (tag mask is!CONT_MASK) of a continuation byte.
const TAG_CONT_U8: u8 = 0b1000_0000;
// truncate `&str` to length at most equal to `max`
// return `true` if it were truncated, and the new str.
pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
if max >= s.len() {
(false, s)
} else {
while!s.is_char_boundary(max) {
max -= 1;
}
(true, &s[..max])
}
}
|
next_code_point
|
identifier_name
|
validations.rs
|
//! Operations related to UTF-8 validation.
use crate::mem;
use super::Utf8Error;
/// Returns the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
fn utf8_first_byte(byte: u8, width: u32) -> u32 {
(byte & (0x7F >> width)) as u32
}
/// Returns the value of `ch` updated with continuation byte `byte`.
#[inline]
fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 {
(ch << 6) | (byte & CONT_MASK) as u32
}
/// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
/// bits `10`).
#[inline]
pub(super) fn utf8_is_cont_byte(byte: u8) -> bool {
(byte &!CONT_MASK) == TAG_CONT_U8
}
#[inline]
fn unwrap_or_0(opt: Option<&u8>) -> u8
|
/// Reads the next code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
return Some(x as u32);
}
// Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w]
// NOTE: Performance is sensitive to the exact formulation here
let init = utf8_first_byte(x, 2);
let y = unwrap_or_0(bytes.next());
let mut ch = utf8_acc_cont_byte(init, y);
if x >= 0xE0 {
// [[x y z] w] case
// 5th bit in 0xE0.. 0xEF is always clear, so `init` is still valid
let z = unwrap_or_0(bytes.next());
let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
ch = init << 12 | y_z;
if x >= 0xF0 {
// [x y z w] case
// use only the lower 3 bits of `init`
let w = unwrap_or_0(bytes.next());
ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
}
}
Some(ch)
}
/// Reads the last code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[inline]
pub(super) fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
where
I: DoubleEndedIterator<Item = &'a u8>,
{
// Decode UTF-8
let w = match *bytes.next_back()? {
next_byte if next_byte < 128 => return Some(next_byte as u32),
back_byte => back_byte,
};
// Multibyte case follows
// Decode from a byte combination out of: [x [y [z w]]]
let mut ch;
let z = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(z, 2);
if utf8_is_cont_byte(z) {
let y = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(y, 3);
if utf8_is_cont_byte(y) {
let x = unwrap_or_0(bytes.next_back());
ch = utf8_first_byte(x, 4);
ch = utf8_acc_cont_byte(ch, y);
}
ch = utf8_acc_cont_byte(ch, z);
}
ch = utf8_acc_cont_byte(ch, w);
Some(ch)
}
// use truncation to fit u64 into usize
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
/// Returns `true` if any byte in the word `x` is nonascii (>= 128).
#[inline]
fn contains_nonascii(x: usize) -> bool {
(x & NONASCII_MASK)!= 0
}
/// Walks through `v` checking that it's a valid UTF-8 sequence,
/// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`.
#[inline(always)]
pub(super) fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
let mut index = 0;
let len = v.len();
let usize_bytes = mem::size_of::<usize>();
let ascii_block_size = 2 * usize_bytes;
let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 };
let align = v.as_ptr().align_offset(usize_bytes);
while index < len {
let old_offset = index;
macro_rules! err {
($error_len: expr) => {
return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len })
};
}
macro_rules! next {
() => {{
index += 1;
// we needed data, but there was none: error!
if index >= len {
err!(None)
}
v[index]
}};
}
let first = v[index];
if first >= 128 {
let w = UTF8_CHAR_WIDTH[first as usize];
// 2-byte encoding is for codepoints \u{0080} to \u{07ff}
// first C2 80 last DF BF
// 3-byte encoding is for codepoints \u{0800} to \u{ffff}
// first E0 A0 80 last EF BF BF
// excluding surrogates codepoints \u{d800} to \u{dfff}
// ED A0 80 to ED BF BF
// 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff
// first F0 90 80 80 last F4 8F BF BF
//
// Use the UTF-8 syntax from the RFC
//
// https://tools.ietf.org/html/rfc3629
// UTF8-1 = %x00-7F
// UTF8-2 = %xC2-DF UTF8-tail
// UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
// %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
// UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
// %xF4 %x80-8F 2( UTF8-tail )
match w {
2 => {
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(1))
}
}
3 => {
match (first, next!()) {
(0xE0, 0xA0..=0xBF)
| (0xE1..=0xEC, 0x80..=0xBF)
| (0xED, 0x80..=0x9F)
| (0xEE..=0xEF, 0x80..=0xBF) => {}
_ => err!(Some(1)),
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(2))
}
}
4 => {
match (first, next!()) {
(0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {}
_ => err!(Some(1)),
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(2))
}
if next!() &!CONT_MASK!= TAG_CONT_U8 {
err!(Some(3))
}
}
_ => err!(Some(1)),
}
index += 1;
} else {
// Ascii case, try to skip forward quickly.
// When the pointer is aligned, read 2 words of data per iteration
// until we find a word containing a non-ascii byte.
if align!= usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 {
let ptr = v.as_ptr();
while index < blocks_end {
// SAFETY: since `align - index` and `ascii_block_size` are
// multiples of `usize_bytes`, `block = ptr.add(index)` is
// always aligned with a `usize` so it's safe to dereference
// both `block` and `block.offset(1)`.
unsafe {
let block = ptr.add(index) as *const usize;
// break if there is a nonascii byte
let zu = contains_nonascii(*block);
let zv = contains_nonascii(*block.offset(1));
if zu | zv {
break;
}
}
index += ascii_block_size;
}
// step from the point where the wordwise loop stopped
while index < len && v[index] < 128 {
index += 1;
}
} else {
index += 1;
}
}
}
Ok(())
}
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x3F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x5F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x7F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0x9F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0xBF
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, // 0xDF
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF
];
/// Given a first byte, determines how many bytes are in this UTF-8 character.
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn utf8_char_width(b: u8) -> usize {
UTF8_CHAR_WIDTH[b as usize] as usize
}
/// Mask of the value bits of a continuation byte.
const CONT_MASK: u8 = 0b0011_1111;
/// Value of the tag bits (tag mask is!CONT_MASK) of a continuation byte.
const TAG_CONT_U8: u8 = 0b1000_0000;
// truncate `&str` to length at most equal to `max`
// return `true` if it were truncated, and the new str.
pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) {
if max >= s.len() {
(false, s)
} else {
while!s.is_char_boundary(max) {
max -= 1;
}
(true, &s[..max])
}
}
|
{
match opt {
Some(&byte) => byte,
None => 0,
}
}
|
identifier_body
|
expand.rs
|
use std::str;
use memchr::memchr;
use bytes::Captures;
pub fn expand(caps: &Captures, mut replacement: &[u8], dst: &mut Vec<u8>) {
while!replacement.is_empty() {
match memchr(b'$', replacement) {
None => break,
Some(i) => {
dst.extend(&replacement[..i]);
replacement = &replacement[i..];
}
}
if replacement.get(1).map_or(false, |&b| b == b'$') {
dst.push(b'$');
replacement = &replacement[2..];
continue;
}
debug_assert!(!replacement.is_empty());
let cap_ref = match find_cap_ref(replacement) {
Some(cap_ref) => cap_ref,
None => {
dst.push(b'$');
replacement = &replacement[1..];
continue;
}
};
replacement = cap_ref.rest;
match cap_ref.cap {
Ref::Number(i) => dst.extend(caps.at(i).unwrap_or(b"")),
Ref::Named(name) => dst.extend(caps.name(name).unwrap_or(b"")),
}
}
dst.extend(replacement);
}
struct CaptureRef<'a> {
rest: &'a [u8],
cap: Ref<'a>,
}
enum Ref<'a> {
Named(&'a str),
Number(usize),
}
fn find_cap_ref(mut replacement: &[u8]) -> Option<CaptureRef> {
if replacement.len() <= 1 || replacement[0]!= b'$' {
return None;
}
let mut brace = false;
replacement = &replacement[1..];
if replacement[0] == b'{' {
brace = true;
replacement = &replacement[1..];
}
let mut cap_end = 0;
while replacement.get(cap_end).map_or(false, is_valid_cap_letter) {
cap_end += 1;
}
if cap_end == 0 {
return None;
}
// We just verified that the range 0..cap_end is valid ASCII, so it must
// therefore be valid UTF-8. If we really cared, we could avoid this UTF-8
// check with either unsafe or by parsing the number straight from &[u8].
let cap = str::from_utf8(&replacement[..cap_end])
.ok().expect("valid UTF-8 capture name");
if brace {
if!replacement.get(cap_end).map_or(false, |&b| b == b'}') {
return None;
}
cap_end += 1;
}
Some(CaptureRef {
rest: &replacement[cap_end..],
cap: match cap.parse::<u32>() {
Ok(i) => Ref::Number(i as usize),
Err(_) => Ref::Named(cap),
},
})
}
fn
|
(b: &u8) -> bool {
match *b {
b'0'... b'9' | b'a'... b'z' | b'A'... b'Z' | b'_' => true,
_ => false,
}
}
|
is_valid_cap_letter
|
identifier_name
|
expand.rs
|
use std::str;
use memchr::memchr;
use bytes::Captures;
pub fn expand(caps: &Captures, mut replacement: &[u8], dst: &mut Vec<u8>) {
while!replacement.is_empty() {
match memchr(b'$', replacement) {
None => break,
Some(i) => {
dst.extend(&replacement[..i]);
replacement = &replacement[i..];
}
}
if replacement.get(1).map_or(false, |&b| b == b'$') {
dst.push(b'$');
replacement = &replacement[2..];
continue;
}
debug_assert!(!replacement.is_empty());
let cap_ref = match find_cap_ref(replacement) {
Some(cap_ref) => cap_ref,
None => {
dst.push(b'$');
replacement = &replacement[1..];
continue;
}
};
replacement = cap_ref.rest;
match cap_ref.cap {
Ref::Number(i) => dst.extend(caps.at(i).unwrap_or(b"")),
Ref::Named(name) => dst.extend(caps.name(name).unwrap_or(b"")),
}
}
dst.extend(replacement);
}
struct CaptureRef<'a> {
rest: &'a [u8],
cap: Ref<'a>,
}
enum Ref<'a> {
Named(&'a str),
Number(usize),
}
fn find_cap_ref(mut replacement: &[u8]) -> Option<CaptureRef> {
if replacement.len() <= 1 || replacement[0]!= b'$' {
return None;
}
let mut brace = false;
replacement = &replacement[1..];
if replacement[0] == b'{' {
brace = true;
replacement = &replacement[1..];
}
let mut cap_end = 0;
while replacement.get(cap_end).map_or(false, is_valid_cap_letter) {
cap_end += 1;
}
if cap_end == 0 {
return None;
}
// We just verified that the range 0..cap_end is valid ASCII, so it must
// therefore be valid UTF-8. If we really cared, we could avoid this UTF-8
// check with either unsafe or by parsing the number straight from &[u8].
let cap = str::from_utf8(&replacement[..cap_end])
.ok().expect("valid UTF-8 capture name");
if brace {
|
if!replacement.get(cap_end).map_or(false, |&b| b == b'}') {
return None;
}
cap_end += 1;
}
Some(CaptureRef {
rest: &replacement[cap_end..],
cap: match cap.parse::<u32>() {
Ok(i) => Ref::Number(i as usize),
Err(_) => Ref::Named(cap),
},
})
}
fn is_valid_cap_letter(b: &u8) -> bool {
match *b {
b'0'... b'9' | b'a'... b'z' | b'A'... b'Z' | b'_' => true,
_ => false,
}
}
|
random_line_split
|
|
borrowck-borrow-overloaded-deref-mut.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
fn deref_imm(x: Own<int>) {
let _i = &*x;
}
fn
|
(x: Own<int>) {
let _i = &mut *x; //~ ERROR cannot borrow
}
fn deref_mut2(mut x: Own<int>) {
let _i = &mut *x;
}
fn deref_extend<'a>(x: &'a Own<int>) -> &'a int {
&**x
}
fn deref_extend_mut1<'a>(x: &'a Own<int>) -> &'a mut int {
&mut **x //~ ERROR cannot borrow
}
fn deref_extend_mut2<'a>(x: &'a mut Own<int>) -> &'a mut int {
&mut **x
}
fn assign1<'a>(x: Own<int>) {
*x = 3; //~ ERROR cannot borrow
}
fn assign2<'a>(x: &'a Own<int>) {
**x = 3; //~ ERROR cannot borrow
}
fn assign3<'a>(x: &'a mut Own<int>) {
**x = 3;
}
pub fn main() {}
|
deref_mut1
|
identifier_name
|
borrowck-borrow-overloaded-deref-mut.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
|
value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
fn deref_imm(x: Own<int>) {
let _i = &*x;
}
fn deref_mut1(x: Own<int>) {
let _i = &mut *x; //~ ERROR cannot borrow
}
fn deref_mut2(mut x: Own<int>) {
let _i = &mut *x;
}
fn deref_extend<'a>(x: &'a Own<int>) -> &'a int {
&**x
}
fn deref_extend_mut1<'a>(x: &'a Own<int>) -> &'a mut int {
&mut **x //~ ERROR cannot borrow
}
fn deref_extend_mut2<'a>(x: &'a mut Own<int>) -> &'a mut int {
&mut **x
}
fn assign1<'a>(x: Own<int>) {
*x = 3; //~ ERROR cannot borrow
}
fn assign2<'a>(x: &'a Own<int>) {
**x = 3; //~ ERROR cannot borrow
}
fn assign3<'a>(x: &'a mut Own<int>) {
**x = 3;
}
pub fn main() {}
|
struct Own<T> {
|
random_line_split
|
borrowck-borrow-overloaded-deref-mut.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
fn deref_imm(x: Own<int>) {
let _i = &*x;
}
fn deref_mut1(x: Own<int>) {
let _i = &mut *x; //~ ERROR cannot borrow
}
fn deref_mut2(mut x: Own<int>) {
let _i = &mut *x;
}
fn deref_extend<'a>(x: &'a Own<int>) -> &'a int {
&**x
}
fn deref_extend_mut1<'a>(x: &'a Own<int>) -> &'a mut int {
&mut **x //~ ERROR cannot borrow
}
fn deref_extend_mut2<'a>(x: &'a mut Own<int>) -> &'a mut int
|
fn assign1<'a>(x: Own<int>) {
*x = 3; //~ ERROR cannot borrow
}
fn assign2<'a>(x: &'a Own<int>) {
**x = 3; //~ ERROR cannot borrow
}
fn assign3<'a>(x: &'a mut Own<int>) {
**x = 3;
}
pub fn main() {}
|
{
&mut **x
}
|
identifier_body
|
timer.rs
|
// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{
AsRawDescriptor, FakeClock, FromRawDescriptor, IntoRawDescriptor, RawDescriptor, Result,
};
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
use std::sync::Arc;
use std::time::Duration;
use sync::Mutex;
use sys_util::{FakeTimerFd, TimerFd};
/// See [TimerFd](sys_util::TimerFd) for struct- and method-level
/// documentation.
pub struct
|
(pub TimerFd);
impl Timer {
pub fn new() -> Result<Timer> {
TimerFd::new().map(Timer)
}
}
/// See [FakeTimerFd](sys_util::FakeTimerFd) for struct- and method-level
/// documentation.
pub struct FakeTimer(FakeTimerFd);
impl FakeTimer {
pub fn new(clock: Arc<Mutex<FakeClock>>) -> Self {
FakeTimer(FakeTimerFd::new(clock))
}
}
macro_rules! build_timer {
($timer:ident, $inner:ident) => {
impl $timer {
pub fn reset(&mut self, dur: Duration, interval: Option<Duration>) -> Result<()> {
self.0.reset(dur, interval)
}
pub fn wait(&mut self) -> Result<()> {
self.0.wait().map(|_| ())
}
pub fn is_armed(&self) -> Result<bool> {
self.0.is_armed()
}
pub fn clear(&mut self) -> Result<()> {
self.0.clear()
}
pub fn resolution() -> Result<Duration> {
$inner::resolution()
}
}
impl AsRawDescriptor for $timer {
fn as_raw_descriptor(&self) -> RawDescriptor {
self.0.as_raw_fd()
}
}
impl IntoRawDescriptor for $timer {
fn into_raw_descriptor(self) -> RawDescriptor {
self.0.into_raw_fd()
}
}
};
}
build_timer!(Timer, TimerFd);
build_timer!(FakeTimer, FakeTimerFd);
impl FromRawDescriptor for Timer {
unsafe fn from_raw_descriptor(descriptor: RawDescriptor) -> Self {
Timer(TimerFd::from_raw_fd(descriptor))
}
}
|
Timer
|
identifier_name
|
timer.rs
|
// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{
AsRawDescriptor, FakeClock, FromRawDescriptor, IntoRawDescriptor, RawDescriptor, Result,
};
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
use std::sync::Arc;
use std::time::Duration;
use sync::Mutex;
use sys_util::{FakeTimerFd, TimerFd};
/// See [TimerFd](sys_util::TimerFd) for struct- and method-level
/// documentation.
pub struct Timer(pub TimerFd);
impl Timer {
pub fn new() -> Result<Timer> {
TimerFd::new().map(Timer)
}
}
/// See [FakeTimerFd](sys_util::FakeTimerFd) for struct- and method-level
/// documentation.
pub struct FakeTimer(FakeTimerFd);
impl FakeTimer {
pub fn new(clock: Arc<Mutex<FakeClock>>) -> Self {
FakeTimer(FakeTimerFd::new(clock))
}
}
macro_rules! build_timer {
($timer:ident, $inner:ident) => {
impl $timer {
pub fn reset(&mut self, dur: Duration, interval: Option<Duration>) -> Result<()> {
|
pub fn wait(&mut self) -> Result<()> {
self.0.wait().map(|_| ())
}
pub fn is_armed(&self) -> Result<bool> {
self.0.is_armed()
}
pub fn clear(&mut self) -> Result<()> {
self.0.clear()
}
pub fn resolution() -> Result<Duration> {
$inner::resolution()
}
}
impl AsRawDescriptor for $timer {
fn as_raw_descriptor(&self) -> RawDescriptor {
self.0.as_raw_fd()
}
}
impl IntoRawDescriptor for $timer {
fn into_raw_descriptor(self) -> RawDescriptor {
self.0.into_raw_fd()
}
}
};
}
build_timer!(Timer, TimerFd);
build_timer!(FakeTimer, FakeTimerFd);
impl FromRawDescriptor for Timer {
unsafe fn from_raw_descriptor(descriptor: RawDescriptor) -> Self {
Timer(TimerFd::from_raw_fd(descriptor))
}
}
|
self.0.reset(dur, interval)
}
|
random_line_split
|
test_rotation.rs
|
extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match input.read(&mut buf) {
Ok(n) => n as isize,
Err(_) => -1,
}
}
#[test]
fn parse_rotation() {
let mut file = std::fs::File::open("tests/video_rotation_90.mp4").expect("Unknown file");
let io = Mp4parseIo {
read: Some(buf_read),
userdata: &mut file as *mut _ as *mut std::os::raw::c_void
};
unsafe {
let parser = mp4parse_new(&io);
let mut rv = mp4parse_read(parser);
|
let mut counts: u32 = 0;
rv = mp4parse_get_track_count(parser, &mut counts);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(counts, 1);
let mut video = Mp4parseTrackVideoInfo::default();
let rv = mp4parse_get_track_video_info(parser, 0, &mut video);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(video.rotation, 90);
mp4parse_free(parser);
}
}
|
assert_eq!(rv, Mp4parseStatus::Ok);
|
random_line_split
|
test_rotation.rs
|
extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize
|
#[test]
fn parse_rotation() {
let mut file = std::fs::File::open("tests/video_rotation_90.mp4").expect("Unknown file");
let io = Mp4parseIo {
read: Some(buf_read),
userdata: &mut file as *mut _ as *mut std::os::raw::c_void
};
unsafe {
let parser = mp4parse_new(&io);
let mut rv = mp4parse_read(parser);
assert_eq!(rv, Mp4parseStatus::Ok);
let mut counts: u32 = 0;
rv = mp4parse_get_track_count(parser, &mut counts);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(counts, 1);
let mut video = Mp4parseTrackVideoInfo::default();
let rv = mp4parse_get_track_video_info(parser, 0, &mut video);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(video.rotation, 90);
mp4parse_free(parser);
}
}
|
{
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match input.read(&mut buf) {
Ok(n) => n as isize,
Err(_) => -1,
}
}
|
identifier_body
|
test_rotation.rs
|
extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match input.read(&mut buf) {
Ok(n) => n as isize,
Err(_) => -1,
}
}
#[test]
fn
|
() {
let mut file = std::fs::File::open("tests/video_rotation_90.mp4").expect("Unknown file");
let io = Mp4parseIo {
read: Some(buf_read),
userdata: &mut file as *mut _ as *mut std::os::raw::c_void
};
unsafe {
let parser = mp4parse_new(&io);
let mut rv = mp4parse_read(parser);
assert_eq!(rv, Mp4parseStatus::Ok);
let mut counts: u32 = 0;
rv = mp4parse_get_track_count(parser, &mut counts);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(counts, 1);
let mut video = Mp4parseTrackVideoInfo::default();
let rv = mp4parse_get_track_video_info(parser, 0, &mut video);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(video.rotation, 90);
mp4parse_free(parser);
}
}
|
parse_rotation
|
identifier_name
|
typeid-intrinsic.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.
// aux-build:typeid-intrinsic.rs
// aux-build:typeid-intrinsic2.rs
extern crate "typeid-intrinsic" as other1;
extern crate "typeid-intrinsic2" as other2;
use std::hash::{self, SipHasher};
use std::any::TypeId;
struct A;
struct Test;
pub fn
|
() {
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(TypeId::of::<other1::E>(), other1::id_E());
assert_eq!(TypeId::of::<other1::F>(), other1::id_F());
assert_eq!(TypeId::of::<other1::G>(), other1::id_G());
assert_eq!(TypeId::of::<other1::H>(), other1::id_H());
assert_eq!(TypeId::of::<other2::A>(), other2::id_A());
assert_eq!(TypeId::of::<other2::B>(), other2::id_B());
assert_eq!(TypeId::of::<other2::C>(), other2::id_C());
assert_eq!(TypeId::of::<other2::D>(), other2::id_D());
assert_eq!(TypeId::of::<other2::E>(), other2::id_E());
assert_eq!(TypeId::of::<other2::F>(), other2::id_F());
assert_eq!(TypeId::of::<other2::G>(), other2::id_G());
assert_eq!(TypeId::of::<other2::H>(), other2::id_H());
assert_eq!(other1::id_F(), other2::id_F());
assert_eq!(other1::id_G(), other2::id_G());
assert_eq!(other1::id_H(), other2::id_H());
assert_eq!(TypeId::of::<int>(), other2::foo::<int>());
assert_eq!(TypeId::of::<int>(), other1::foo::<int>());
assert_eq!(other2::foo::<int>(), other1::foo::<int>());
assert_eq!(TypeId::of::<A>(), other2::foo::<A>());
assert_eq!(TypeId::of::<A>(), other1::foo::<A>());
assert_eq!(other2::foo::<A>(), other1::foo::<A>());
}
// sanity test of TypeId
let (a, b, c) = (TypeId::of::<uint>(), TypeId::of::<&'static str>(),
TypeId::of::<Test>());
let (d, e, f) = (TypeId::of::<uint>(), TypeId::of::<&'static str>(),
TypeId::of::<Test>());
assert!(a!= b);
assert!(a!= c);
assert!(b!= c);
assert_eq!(a, d);
assert_eq!(b, e);
assert_eq!(c, f);
// check it has a hash
let (a, b) = (TypeId::of::<uint>(), TypeId::of::<uint>());
assert_eq!(hash::hash::<TypeId, SipHasher>(&a),
hash::hash::<TypeId, SipHasher>(&b));
}
|
main
|
identifier_name
|
typeid-intrinsic.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.
// aux-build:typeid-intrinsic.rs
// aux-build:typeid-intrinsic2.rs
extern crate "typeid-intrinsic" as other1;
extern crate "typeid-intrinsic2" as other2;
use std::hash::{self, SipHasher};
use std::any::TypeId;
struct A;
struct Test;
pub fn main() {
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(TypeId::of::<other1::E>(), other1::id_E());
assert_eq!(TypeId::of::<other1::F>(), other1::id_F());
assert_eq!(TypeId::of::<other1::G>(), other1::id_G());
assert_eq!(TypeId::of::<other1::H>(), other1::id_H());
assert_eq!(TypeId::of::<other2::A>(), other2::id_A());
assert_eq!(TypeId::of::<other2::B>(), other2::id_B());
assert_eq!(TypeId::of::<other2::C>(), other2::id_C());
assert_eq!(TypeId::of::<other2::D>(), other2::id_D());
assert_eq!(TypeId::of::<other2::E>(), other2::id_E());
assert_eq!(TypeId::of::<other2::F>(), other2::id_F());
assert_eq!(TypeId::of::<other2::G>(), other2::id_G());
assert_eq!(TypeId::of::<other2::H>(), other2::id_H());
assert_eq!(other1::id_F(), other2::id_F());
assert_eq!(other1::id_G(), other2::id_G());
assert_eq!(other1::id_H(), other2::id_H());
assert_eq!(TypeId::of::<int>(), other2::foo::<int>());
assert_eq!(TypeId::of::<int>(), other1::foo::<int>());
assert_eq!(other2::foo::<int>(), other1::foo::<int>());
assert_eq!(TypeId::of::<A>(), other2::foo::<A>());
assert_eq!(TypeId::of::<A>(), other1::foo::<A>());
assert_eq!(other2::foo::<A>(), other1::foo::<A>());
}
// sanity test of TypeId
let (a, b, c) = (TypeId::of::<uint>(), TypeId::of::<&'static str>(),
TypeId::of::<Test>());
let (d, e, f) = (TypeId::of::<uint>(), TypeId::of::<&'static str>(),
TypeId::of::<Test>());
assert!(a!= b);
assert!(a!= c);
assert!(b!= c);
assert_eq!(a, d);
assert_eq!(b, e);
assert_eq!(c, f);
// check it has a hash
let (a, b) = (TypeId::of::<uint>(), TypeId::of::<uint>());
assert_eq!(hash::hash::<TypeId, SipHasher>(&a),
|
hash::hash::<TypeId, SipHasher>(&b));
}
|
random_line_split
|
|
typeid-intrinsic.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.
// aux-build:typeid-intrinsic.rs
// aux-build:typeid-intrinsic2.rs
extern crate "typeid-intrinsic" as other1;
extern crate "typeid-intrinsic2" as other2;
use std::hash::{self, SipHasher};
use std::any::TypeId;
struct A;
struct Test;
pub fn main()
|
assert_eq!(other1::id_F(), other2::id_F());
assert_eq!(other1::id_G(), other2::id_G());
assert_eq!(other1::id_H(), other2::id_H());
assert_eq!(TypeId::of::<int>(), other2::foo::<int>());
assert_eq!(TypeId::of::<int>(), other1::foo::<int>());
assert_eq!(other2::foo::<int>(), other1::foo::<int>());
assert_eq!(TypeId::of::<A>(), other2::foo::<A>());
assert_eq!(TypeId::of::<A>(), other1::foo::<A>());
assert_eq!(other2::foo::<A>(), other1::foo::<A>());
}
// sanity test of TypeId
let (a, b, c) = (TypeId::of::<uint>(), TypeId::of::<&'static str>(),
TypeId::of::<Test>());
let (d, e, f) = (TypeId::of::<uint>(), TypeId::of::<&'static str>(),
TypeId::of::<Test>());
assert!(a!= b);
assert!(a!= c);
assert!(b!= c);
assert_eq!(a, d);
assert_eq!(b, e);
assert_eq!(c, f);
// check it has a hash
let (a, b) = (TypeId::of::<uint>(), TypeId::of::<uint>());
assert_eq!(hash::hash::<TypeId, SipHasher>(&a),
hash::hash::<TypeId, SipHasher>(&b));
}
|
{
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(TypeId::of::<other1::E>(), other1::id_E());
assert_eq!(TypeId::of::<other1::F>(), other1::id_F());
assert_eq!(TypeId::of::<other1::G>(), other1::id_G());
assert_eq!(TypeId::of::<other1::H>(), other1::id_H());
assert_eq!(TypeId::of::<other2::A>(), other2::id_A());
assert_eq!(TypeId::of::<other2::B>(), other2::id_B());
assert_eq!(TypeId::of::<other2::C>(), other2::id_C());
assert_eq!(TypeId::of::<other2::D>(), other2::id_D());
assert_eq!(TypeId::of::<other2::E>(), other2::id_E());
assert_eq!(TypeId::of::<other2::F>(), other2::id_F());
assert_eq!(TypeId::of::<other2::G>(), other2::id_G());
assert_eq!(TypeId::of::<other2::H>(), other2::id_H());
|
identifier_body
|
abi.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.
pub static box_field_refcnt: uint = 0u;
pub static box_field_drop_glue: uint = 1u;
pub static box_field_body: uint = 4u;
pub static tydesc_field_visit_glue: uint = 3u;
// The two halves of a closure: code and environment.
pub static fn_field_code: uint = 0u;
pub static fn_field_box: uint = 1u;
// The two fields of a trait object/trait instance: vtable and box.
// The vtable contains the type descriptor as first element.
pub static trt_field_box: uint = 0u;
pub static trt_field_vtable: uint = 1u;
|
pub static slice_elt_base: uint = 0u;
pub static slice_elt_len: uint = 1u;
|
random_line_split
|
|
with_nom_result.rs
|
use m3u8_rs::Playlist;
use std::io::Read;
|
fn main() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playlist)) => playlist,
Result::Err(e) => panic!("Parsing error: \n{}", e),
};
match playlist {
Playlist::MasterPlaylist(pl) => println!("Master playlist:\n{:?}", pl),
Playlist::MediaPlaylist(pl) => println!("Media playlist:\n{:?}", pl),
}
}
#[allow(unused)]
fn main_alt() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
match parsed {
Result::Ok((_i, Playlist::MasterPlaylist(pl))) => println!("Master playlist:\n{:?}", pl),
Result::Ok((_i, Playlist::MediaPlaylist(pl))) => println!("Media playlist:\n{:?}", pl),
Result::Err(e) => panic!("Parsing error: \n{}", e),
}
}
|
random_line_split
|
|
with_nom_result.rs
|
use m3u8_rs::Playlist;
use std::io::Read;
fn
|
() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playlist)) => playlist,
Result::Err(e) => panic!("Parsing error: \n{}", e),
};
match playlist {
Playlist::MasterPlaylist(pl) => println!("Master playlist:\n{:?}", pl),
Playlist::MediaPlaylist(pl) => println!("Media playlist:\n{:?}", pl),
}
}
#[allow(unused)]
fn main_alt() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
match parsed {
Result::Ok((_i, Playlist::MasterPlaylist(pl))) => println!("Master playlist:\n{:?}", pl),
Result::Ok((_i, Playlist::MediaPlaylist(pl))) => println!("Media playlist:\n{:?}", pl),
Result::Err(e) => panic!("Parsing error: \n{}", e),
}
}
|
main
|
identifier_name
|
with_nom_result.rs
|
use m3u8_rs::Playlist;
use std::io::Read;
fn main() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playlist)) => playlist,
Result::Err(e) => panic!("Parsing error: \n{}", e),
};
match playlist {
Playlist::MasterPlaylist(pl) => println!("Master playlist:\n{:?}", pl),
Playlist::MediaPlaylist(pl) => println!("Media playlist:\n{:?}", pl),
}
}
#[allow(unused)]
fn main_alt()
|
{
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
match parsed {
Result::Ok((_i, Playlist::MasterPlaylist(pl))) => println!("Master playlist:\n{:?}", pl),
Result::Ok((_i, Playlist::MediaPlaylist(pl))) => println!("Media playlist:\n{:?}", pl),
Result::Err(e) => panic!("Parsing error: \n{}", e),
}
}
|
identifier_body
|
|
main.rs
|
extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status
{
let _ = res.serve(::http::status::Ok, "Wrong time, come back later.");
Continue
}
fn main()
{
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
|
else
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
}
|
{
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
}
|
conditional_block
|
main.rs
|
extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status
{
let _ = res.serve(::http::status::Ok, "Wrong time, come back later.");
Continue
}
fn main()
|
{
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
{
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
}
else
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
}
|
identifier_body
|
|
main.rs
|
extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn
|
(_req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status
{
let _ = res.serve(::http::status::Ok, "Wrong time, come back later.");
Continue
}
fn main()
{
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
{
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
}
else
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
}
|
come_again
|
identifier_name
|
main.rs
|
extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status
{
let _ = res.serve(::http::status::Ok, "Wrong time, come back later.");
Continue
}
fn main()
{
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
{
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
}
|
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
}
|
else
|
random_line_split
|
frame_reader.rs
|
//! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct FrameReader {
frames: Frames
}
impl FrameReader {
pub fn new(max_frame_size: u32) -> FrameReader {
FrameReader {
frames: Frames::new(max_frame_size)
}
}
pub fn read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
self.frames.read(reader)
}
pub fn iter_mut(&mut self) -> Iter {
Iter {
frames: &mut self.frames
}
}
}
pub struct Iter<'a> {
frames: &'a mut Frames
}
impl<'a> Iterator for Iter<'a> {
type Item = Vec<u8>;
fn next(&mut self) -> Option<Vec<u8>> {
self.frames.completed_frames.pop_front()
}
}
#[derive(Debug)]
struct Frames {
max_frame_size: u32,
bytes_read: usize,
header: [u8; 4],
reading_header: bool,
current: Vec<u8>,
completed_frames: VecDeque<Vec<u8>>
}
impl Frames {
pub fn new(max_frame_size: u32) -> Frames {
Frames {
max_frame_size: max_frame_size,
bytes_read: 0,
header: [0; 4],
reading_header: true,
current: Vec::with_capacity(0),
completed_frames: VecDeque::new()
}
}
/// Will read as much data as possible and build up frames to be retrieved from the iterator.
///
/// Will stop reading when 0 bytes are retrieved from the latest call to `do_read` or the error
/// kind is io::ErrorKind::WouldBlock.
///
/// Returns an error or the total amount of bytes read.
fn read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let mut total_bytes_read = 0;
loop {
match self.do_read(reader) {
Ok(0) => {
if total_bytes_read == 0 {
return Err(Error::new(ErrorKind::UnexpectedEof, "Read 0 bytes"));
}
return Ok(total_bytes_read);
},
Ok(bytes_read) => {
total_bytes_read += bytes_read;
},
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return Ok(total_bytes_read),
Err(e) => return Err(e)
}
}
}
fn do_read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
if self.reading_header {
self.read_header(reader)
} else {
self.read_value(reader)
}
}
// TODO: Return an error if size is greater than max_frame_size
fn read_header<T: Read>(&mut self, reader: &mut T) -> io::Result<usize>
|
fn read_value<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let bytes_read = try!(reader.read(&mut self.current[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == self.current.len() {
self.completed_frames.push_back(mem::replace(&mut self.current, Vec::new()));
self.bytes_read = 0;
self.reading_header = true;
}
Ok(bytes_read)
}
}
#[cfg(test)]
mod tests {
use std::{mem, thread};
use std::io::Cursor;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use super::FrameReader;
#[test]
fn partial_and_complete_reads() {
let buf1 = String::from("Hello World").into_bytes();
let buf2 = String::from("Hi.").into_bytes();
let header1: [u8; 4] = unsafe { mem::transmute((buf1.len() as u32).to_be()) };
let header2: [u8; 4] = unsafe { mem::transmute((buf2.len() as u32).to_be()) };
let mut reader = FrameReader::new(1024);
// Write a partial header
let mut header = Cursor::new(&header1[0..2]);
let bytes_read = reader.read(&mut header).unwrap();
assert_eq!(2, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing just the header
let mut header = Cursor::new(&header1[2..]);
let bytes_read = reader.read(&mut header).unwrap();
assert_eq!(2, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Write a partial value
let mut data = Cursor::new(&buf1[0..5]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(5, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing the first value
let mut data = Cursor::new(&buf1[5..]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(6, bytes_read);
let val = reader.iter_mut().next().unwrap();
assert_eq!(buf1, val);
// Write an entire header and value
let mut data = Cursor::new(Vec::with_capacity(7));
assert_eq!(4, data.write(&header2).unwrap());
assert_eq!(3, data.write(&buf2).unwrap());
data.set_position(0);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(7, bytes_read);
assert_eq!(buf2, reader.iter_mut().next().unwrap());
}
const IP: &'static str = "127.0.0.1:5003";
/// Test that we never get an io error, but instead get Ok(0) when the call to read would block
#[test]
fn would_block() {
let listener = TcpListener::bind(IP).unwrap();
let h = thread::spawn(move || {
for stream in listener.incoming() {
if let Ok(mut conn) = stream {
conn.set_nonblocking(true).unwrap();
let mut reader = FrameReader::new(1024);
let result = reader.read(&mut conn);
assert_matches!(result, Ok(0));
return;
}
}
});
// Assign to a variable so the sock isn't dropped early
// Name it with a preceding underscore so we don't get an unused variable warning
let _sock = TcpStream::connect(IP).unwrap();
h.join().unwrap();
}
}
|
{
let bytes_read = try!(reader.read(&mut self.header[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == 4 {
let len = unsafe { u32::from_be(mem::transmute(self.header)) };
self.bytes_read = 0;
self.reading_header = false;
self.current = Vec::with_capacity(len as usize);
unsafe { self.current.set_len(len as usize); }
}
Ok(bytes_read)
}
|
identifier_body
|
frame_reader.rs
|
//! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct FrameReader {
frames: Frames
}
impl FrameReader {
pub fn new(max_frame_size: u32) -> FrameReader {
FrameReader {
frames: Frames::new(max_frame_size)
}
}
pub fn read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
self.frames.read(reader)
}
pub fn iter_mut(&mut self) -> Iter {
Iter {
frames: &mut self.frames
}
}
}
pub struct Iter<'a> {
frames: &'a mut Frames
}
impl<'a> Iterator for Iter<'a> {
type Item = Vec<u8>;
fn next(&mut self) -> Option<Vec<u8>> {
self.frames.completed_frames.pop_front()
}
}
#[derive(Debug)]
struct Frames {
max_frame_size: u32,
bytes_read: usize,
header: [u8; 4],
reading_header: bool,
current: Vec<u8>,
completed_frames: VecDeque<Vec<u8>>
}
impl Frames {
pub fn new(max_frame_size: u32) -> Frames {
Frames {
max_frame_size: max_frame_size,
bytes_read: 0,
header: [0; 4],
reading_header: true,
current: Vec::with_capacity(0),
completed_frames: VecDeque::new()
}
}
/// Will read as much data as possible and build up frames to be retrieved from the iterator.
///
/// Will stop reading when 0 bytes are retrieved from the latest call to `do_read` or the error
/// kind is io::ErrorKind::WouldBlock.
///
/// Returns an error or the total amount of bytes read.
fn read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let mut total_bytes_read = 0;
loop {
match self.do_read(reader) {
Ok(0) => {
if total_bytes_read == 0 {
return Err(Error::new(ErrorKind::UnexpectedEof, "Read 0 bytes"));
}
return Ok(total_bytes_read);
},
Ok(bytes_read) => {
total_bytes_read += bytes_read;
},
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return Ok(total_bytes_read),
Err(e) => return Err(e)
}
}
}
fn do_read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
if self.reading_header {
self.read_header(reader)
} else {
self.read_value(reader)
}
}
// TODO: Return an error if size is greater than max_frame_size
fn read_header<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let bytes_read = try!(reader.read(&mut self.header[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == 4 {
let len = unsafe { u32::from_be(mem::transmute(self.header)) };
self.bytes_read = 0;
self.reading_header = false;
self.current = Vec::with_capacity(len as usize);
unsafe { self.current.set_len(len as usize); }
}
Ok(bytes_read)
}
fn read_value<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let bytes_read = try!(reader.read(&mut self.current[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == self.current.len() {
self.completed_frames.push_back(mem::replace(&mut self.current, Vec::new()));
self.bytes_read = 0;
self.reading_header = true;
}
Ok(bytes_read)
}
}
#[cfg(test)]
mod tests {
use std::{mem, thread};
use std::io::Cursor;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use super::FrameReader;
#[test]
fn partial_and_complete_reads() {
let buf1 = String::from("Hello World").into_bytes();
let buf2 = String::from("Hi.").into_bytes();
let header1: [u8; 4] = unsafe { mem::transmute((buf1.len() as u32).to_be()) };
let header2: [u8; 4] = unsafe { mem::transmute((buf2.len() as u32).to_be()) };
let mut reader = FrameReader::new(1024);
// Write a partial header
let mut header = Cursor::new(&header1[0..2]);
let bytes_read = reader.read(&mut header).unwrap();
assert_eq!(2, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing just the header
let mut header = Cursor::new(&header1[2..]);
let bytes_read = reader.read(&mut header).unwrap();
assert_eq!(2, bytes_read);
|
// Write a partial value
let mut data = Cursor::new(&buf1[0..5]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(5, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing the first value
let mut data = Cursor::new(&buf1[5..]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(6, bytes_read);
let val = reader.iter_mut().next().unwrap();
assert_eq!(buf1, val);
// Write an entire header and value
let mut data = Cursor::new(Vec::with_capacity(7));
assert_eq!(4, data.write(&header2).unwrap());
assert_eq!(3, data.write(&buf2).unwrap());
data.set_position(0);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(7, bytes_read);
assert_eq!(buf2, reader.iter_mut().next().unwrap());
}
const IP: &'static str = "127.0.0.1:5003";
/// Test that we never get an io error, but instead get Ok(0) when the call to read would block
#[test]
fn would_block() {
let listener = TcpListener::bind(IP).unwrap();
let h = thread::spawn(move || {
for stream in listener.incoming() {
if let Ok(mut conn) = stream {
conn.set_nonblocking(true).unwrap();
let mut reader = FrameReader::new(1024);
let result = reader.read(&mut conn);
assert_matches!(result, Ok(0));
return;
}
}
});
// Assign to a variable so the sock isn't dropped early
// Name it with a preceding underscore so we don't get an unused variable warning
let _sock = TcpStream::connect(IP).unwrap();
h.join().unwrap();
}
}
|
assert_eq!(None, reader.iter_mut().next());
|
random_line_split
|
frame_reader.rs
|
//! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct FrameReader {
frames: Frames
}
impl FrameReader {
pub fn new(max_frame_size: u32) -> FrameReader {
FrameReader {
frames: Frames::new(max_frame_size)
}
}
pub fn read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
self.frames.read(reader)
}
pub fn iter_mut(&mut self) -> Iter {
Iter {
frames: &mut self.frames
}
}
}
pub struct Iter<'a> {
frames: &'a mut Frames
}
impl<'a> Iterator for Iter<'a> {
type Item = Vec<u8>;
fn next(&mut self) -> Option<Vec<u8>> {
self.frames.completed_frames.pop_front()
}
}
#[derive(Debug)]
struct Frames {
max_frame_size: u32,
bytes_read: usize,
header: [u8; 4],
reading_header: bool,
current: Vec<u8>,
completed_frames: VecDeque<Vec<u8>>
}
impl Frames {
pub fn new(max_frame_size: u32) -> Frames {
Frames {
max_frame_size: max_frame_size,
bytes_read: 0,
header: [0; 4],
reading_header: true,
current: Vec::with_capacity(0),
completed_frames: VecDeque::new()
}
}
/// Will read as much data as possible and build up frames to be retrieved from the iterator.
///
/// Will stop reading when 0 bytes are retrieved from the latest call to `do_read` or the error
/// kind is io::ErrorKind::WouldBlock.
///
/// Returns an error or the total amount of bytes read.
fn read<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let mut total_bytes_read = 0;
loop {
match self.do_read(reader) {
Ok(0) => {
if total_bytes_read == 0 {
return Err(Error::new(ErrorKind::UnexpectedEof, "Read 0 bytes"));
}
return Ok(total_bytes_read);
},
Ok(bytes_read) => {
total_bytes_read += bytes_read;
},
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return Ok(total_bytes_read),
Err(e) => return Err(e)
}
}
}
fn
|
<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
if self.reading_header {
self.read_header(reader)
} else {
self.read_value(reader)
}
}
// TODO: Return an error if size is greater than max_frame_size
fn read_header<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let bytes_read = try!(reader.read(&mut self.header[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == 4 {
let len = unsafe { u32::from_be(mem::transmute(self.header)) };
self.bytes_read = 0;
self.reading_header = false;
self.current = Vec::with_capacity(len as usize);
unsafe { self.current.set_len(len as usize); }
}
Ok(bytes_read)
}
fn read_value<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let bytes_read = try!(reader.read(&mut self.current[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == self.current.len() {
self.completed_frames.push_back(mem::replace(&mut self.current, Vec::new()));
self.bytes_read = 0;
self.reading_header = true;
}
Ok(bytes_read)
}
}
#[cfg(test)]
mod tests {
use std::{mem, thread};
use std::io::Cursor;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use super::FrameReader;
#[test]
fn partial_and_complete_reads() {
let buf1 = String::from("Hello World").into_bytes();
let buf2 = String::from("Hi.").into_bytes();
let header1: [u8; 4] = unsafe { mem::transmute((buf1.len() as u32).to_be()) };
let header2: [u8; 4] = unsafe { mem::transmute((buf2.len() as u32).to_be()) };
let mut reader = FrameReader::new(1024);
// Write a partial header
let mut header = Cursor::new(&header1[0..2]);
let bytes_read = reader.read(&mut header).unwrap();
assert_eq!(2, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing just the header
let mut header = Cursor::new(&header1[2..]);
let bytes_read = reader.read(&mut header).unwrap();
assert_eq!(2, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Write a partial value
let mut data = Cursor::new(&buf1[0..5]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(5, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing the first value
let mut data = Cursor::new(&buf1[5..]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(6, bytes_read);
let val = reader.iter_mut().next().unwrap();
assert_eq!(buf1, val);
// Write an entire header and value
let mut data = Cursor::new(Vec::with_capacity(7));
assert_eq!(4, data.write(&header2).unwrap());
assert_eq!(3, data.write(&buf2).unwrap());
data.set_position(0);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(7, bytes_read);
assert_eq!(buf2, reader.iter_mut().next().unwrap());
}
const IP: &'static str = "127.0.0.1:5003";
/// Test that we never get an io error, but instead get Ok(0) when the call to read would block
#[test]
fn would_block() {
let listener = TcpListener::bind(IP).unwrap();
let h = thread::spawn(move || {
for stream in listener.incoming() {
if let Ok(mut conn) = stream {
conn.set_nonblocking(true).unwrap();
let mut reader = FrameReader::new(1024);
let result = reader.read(&mut conn);
assert_matches!(result, Ok(0));
return;
}
}
});
// Assign to a variable so the sock isn't dropped early
// Name it with a preceding underscore so we don't get an unused variable warning
let _sock = TcpStream::connect(IP).unwrap();
h.join().unwrap();
}
}
|
do_read
|
identifier_name
|
fullscreen.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn
|
() {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
let mut num = String::new();
io::stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID");
println!("Using {:?}", monitor.get_name());
monitor
};
let window = glutin::WindowBuilder::new()
.with_title("Hello world!".to_string())
.with_fullscreen(monitor)
.build()
.unwrap();
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
println!("{:?}", window.wait_events().next());
}
}
|
main
|
identifier_name
|
fullscreen.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main()
|
.with_title("Hello world!".to_string())
.with_fullscreen(monitor)
.build()
.unwrap();
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
println!("{:?}", window.wait_events().next());
}
}
|
{
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
let mut num = String::new();
io::stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID");
println!("Using {:?}", monitor.get_name());
monitor
};
let window = glutin::WindowBuilder::new()
|
identifier_body
|
fullscreen.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main() {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
let mut num = String::new();
io::stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID");
println!("Using {:?}", monitor.get_name());
monitor
};
let window = glutin::WindowBuilder::new()
.with_title("Hello world!".to_string())
|
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
println!("{:?}", window.wait_events().next());
}
}
|
.with_fullscreen(monitor)
.build()
.unwrap();
|
random_line_split
|
entry.rs
|
use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry, String> {
match fs::metadata(path) {
Ok(metadata) => Entry::from_metadata(path, &metadata),
Err(error) => Err(utils::describe_io_error(error))
}
}
pub fn from_metadata(path: &Path, metadata: &fs::Metadata) -> Result<Entry, String> {
let mut children = if metadata.is_dir()
|
else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in descending order
|a, b| b.size().cmp(&a.size())
);
Ok(Entry {
name: utils::short_name_from_path(path, metadata.is_dir()),
children: children,
self_size: metadata.len(),
is_file: metadata.is_file(),
})
}
fn in_directory(dir: &Path) -> Vec<Entry> {
match fs::read_dir(dir) {
Ok(read_dir) => {
read_dir.filter_map(|child| {
match child {
// TODO: Don't just ignore errors here; we should print them to STDERR and
// *then* ignore them.
Ok(child) => Entry::for_path(&child.path()).ok(),
Err(..) => None,
}
}).collect()
},
Err(..) => Vec::new()
}
}
fn descendent_size(&self) -> u64 {
self.children.iter().map(|child| child.size()).fold(0, |a, n| a + n)
}
}
impl DisplayableEntry for Entry {
type Child = Entry;
fn size(&self) -> u64 {
self.self_size + self.descendent_size()
}
fn name(&self) -> &String {
&self.name
}
fn children_iter(&self) -> Iter<Entry> {
self.children.iter()
}
fn is_file(&self) -> bool {
self.is_file
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.name(), self.size().as_size_display())
}
}
#[cfg(test)]
mod test {
use super::*;
use modes::DisplayableEntry;
use std::path::Path;
#[test]
fn it_can_be_constructed_with_a_path() {
let pwd = Entry::for_path(Path::new(".")).unwrap();
assert_eq!(pwd.name(), "./");
assert!(pwd.children_iter().count() > 0);
assert!(pwd.size() > 0);
}
#[test]
fn it_is_error_when_constructed_from_missing_path() {
let missing = Entry::for_path(Path::new("./does-not-exist"));
assert_eq!(missing.is_err(), true);
assert_eq!(missing.unwrap_err(), "File not found");
}
#[test]
fn it_is_hidden_when_filename_starts_with_a_dot() {
let hidden = Entry::for_path(Path::new("./.gitignore")).unwrap();
let normal = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(hidden.is_hidden(), true);
assert_eq!(normal.is_hidden(), false);
}
#[test]
fn file_entry_has_no_children() {
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(file.children_iter().count(), 0);
}
#[test]
fn it_can_be_displayed() {
use utils::SizeDisplay;
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(format!("{}", file), format!("LICENSE {}", file.size().as_size_display()));
}
#[test]
fn it_calculates_size_from_children() {
let entry = Entry::for_path(Path::new(".")).unwrap();
let children_size = entry
.children_iter()
.map(|child| child.size())
.fold(0, |sum, item| sum + item);
assert!(entry.size() >= children_size);
}
}
|
{
Entry::in_directory(path)
}
|
conditional_block
|
entry.rs
|
use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry, String> {
match fs::metadata(path) {
Ok(metadata) => Entry::from_metadata(path, &metadata),
Err(error) => Err(utils::describe_io_error(error))
}
}
pub fn from_metadata(path: &Path, metadata: &fs::Metadata) -> Result<Entry, String> {
let mut children = if metadata.is_dir() {
Entry::in_directory(path)
} else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in descending order
|a, b| b.size().cmp(&a.size())
);
Ok(Entry {
name: utils::short_name_from_path(path, metadata.is_dir()),
children: children,
self_size: metadata.len(),
is_file: metadata.is_file(),
})
}
fn in_directory(dir: &Path) -> Vec<Entry> {
match fs::read_dir(dir) {
Ok(read_dir) => {
read_dir.filter_map(|child| {
match child {
// TODO: Don't just ignore errors here; we should print them to STDERR and
// *then* ignore them.
Ok(child) => Entry::for_path(&child.path()).ok(),
Err(..) => None,
}
}).collect()
},
Err(..) => Vec::new()
}
}
fn descendent_size(&self) -> u64 {
self.children.iter().map(|child| child.size()).fold(0, |a, n| a + n)
}
}
impl DisplayableEntry for Entry {
type Child = Entry;
fn size(&self) -> u64 {
self.self_size + self.descendent_size()
}
fn name(&self) -> &String {
&self.name
}
fn children_iter(&self) -> Iter<Entry> {
self.children.iter()
}
fn
|
(&self) -> bool {
self.is_file
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.name(), self.size().as_size_display())
}
}
#[cfg(test)]
mod test {
use super::*;
use modes::DisplayableEntry;
use std::path::Path;
#[test]
fn it_can_be_constructed_with_a_path() {
let pwd = Entry::for_path(Path::new(".")).unwrap();
assert_eq!(pwd.name(), "./");
assert!(pwd.children_iter().count() > 0);
assert!(pwd.size() > 0);
}
#[test]
fn it_is_error_when_constructed_from_missing_path() {
let missing = Entry::for_path(Path::new("./does-not-exist"));
assert_eq!(missing.is_err(), true);
assert_eq!(missing.unwrap_err(), "File not found");
}
#[test]
fn it_is_hidden_when_filename_starts_with_a_dot() {
let hidden = Entry::for_path(Path::new("./.gitignore")).unwrap();
let normal = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(hidden.is_hidden(), true);
assert_eq!(normal.is_hidden(), false);
}
#[test]
fn file_entry_has_no_children() {
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(file.children_iter().count(), 0);
}
#[test]
fn it_can_be_displayed() {
use utils::SizeDisplay;
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(format!("{}", file), format!("LICENSE {}", file.size().as_size_display()));
}
#[test]
fn it_calculates_size_from_children() {
let entry = Entry::for_path(Path::new(".")).unwrap();
let children_size = entry
.children_iter()
.map(|child| child.size())
.fold(0, |sum, item| sum + item);
assert!(entry.size() >= children_size);
}
}
|
is_file
|
identifier_name
|
entry.rs
|
use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry, String> {
match fs::metadata(path) {
Ok(metadata) => Entry::from_metadata(path, &metadata),
Err(error) => Err(utils::describe_io_error(error))
}
}
pub fn from_metadata(path: &Path, metadata: &fs::Metadata) -> Result<Entry, String> {
let mut children = if metadata.is_dir() {
Entry::in_directory(path)
} else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in descending order
|a, b| b.size().cmp(&a.size())
);
Ok(Entry {
name: utils::short_name_from_path(path, metadata.is_dir()),
children: children,
self_size: metadata.len(),
is_file: metadata.is_file(),
})
}
fn in_directory(dir: &Path) -> Vec<Entry> {
match fs::read_dir(dir) {
Ok(read_dir) => {
read_dir.filter_map(|child| {
match child {
// TODO: Don't just ignore errors here; we should print them to STDERR and
// *then* ignore them.
Ok(child) => Entry::for_path(&child.path()).ok(),
Err(..) => None,
}
}).collect()
},
Err(..) => Vec::new()
}
}
fn descendent_size(&self) -> u64 {
self.children.iter().map(|child| child.size()).fold(0, |a, n| a + n)
}
}
impl DisplayableEntry for Entry {
type Child = Entry;
fn size(&self) -> u64 {
self.self_size + self.descendent_size()
}
fn name(&self) -> &String {
&self.name
}
fn children_iter(&self) -> Iter<Entry> {
self.children.iter()
}
fn is_file(&self) -> bool {
self.is_file
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.name(), self.size().as_size_display())
}
}
#[cfg(test)]
mod test {
use super::*;
use modes::DisplayableEntry;
use std::path::Path;
#[test]
fn it_can_be_constructed_with_a_path() {
let pwd = Entry::for_path(Path::new(".")).unwrap();
assert_eq!(pwd.name(), "./");
assert!(pwd.children_iter().count() > 0);
assert!(pwd.size() > 0);
}
#[test]
fn it_is_error_when_constructed_from_missing_path() {
let missing = Entry::for_path(Path::new("./does-not-exist"));
assert_eq!(missing.is_err(), true);
assert_eq!(missing.unwrap_err(), "File not found");
}
#[test]
fn it_is_hidden_when_filename_starts_with_a_dot() {
let hidden = Entry::for_path(Path::new("./.gitignore")).unwrap();
let normal = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(hidden.is_hidden(), true);
assert_eq!(normal.is_hidden(), false);
}
#[test]
fn file_entry_has_no_children()
|
#[test]
fn it_can_be_displayed() {
use utils::SizeDisplay;
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(format!("{}", file), format!("LICENSE {}", file.size().as_size_display()));
}
#[test]
fn it_calculates_size_from_children() {
let entry = Entry::for_path(Path::new(".")).unwrap();
let children_size = entry
.children_iter()
.map(|child| child.size())
.fold(0, |sum, item| sum + item);
assert!(entry.size() >= children_size);
}
}
|
{
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(file.children_iter().count(), 0);
}
|
identifier_body
|
entry.rs
|
use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry, String> {
match fs::metadata(path) {
Ok(metadata) => Entry::from_metadata(path, &metadata),
Err(error) => Err(utils::describe_io_error(error))
}
}
pub fn from_metadata(path: &Path, metadata: &fs::Metadata) -> Result<Entry, String> {
|
let mut children = if metadata.is_dir() {
Entry::in_directory(path)
} else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in descending order
|a, b| b.size().cmp(&a.size())
);
Ok(Entry {
name: utils::short_name_from_path(path, metadata.is_dir()),
children: children,
self_size: metadata.len(),
is_file: metadata.is_file(),
})
}
fn in_directory(dir: &Path) -> Vec<Entry> {
match fs::read_dir(dir) {
Ok(read_dir) => {
read_dir.filter_map(|child| {
match child {
// TODO: Don't just ignore errors here; we should print them to STDERR and
// *then* ignore them.
Ok(child) => Entry::for_path(&child.path()).ok(),
Err(..) => None,
}
}).collect()
},
Err(..) => Vec::new()
}
}
fn descendent_size(&self) -> u64 {
self.children.iter().map(|child| child.size()).fold(0, |a, n| a + n)
}
}
impl DisplayableEntry for Entry {
type Child = Entry;
fn size(&self) -> u64 {
self.self_size + self.descendent_size()
}
fn name(&self) -> &String {
&self.name
}
fn children_iter(&self) -> Iter<Entry> {
self.children.iter()
}
fn is_file(&self) -> bool {
self.is_file
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.name(), self.size().as_size_display())
}
}
#[cfg(test)]
mod test {
use super::*;
use modes::DisplayableEntry;
use std::path::Path;
#[test]
fn it_can_be_constructed_with_a_path() {
let pwd = Entry::for_path(Path::new(".")).unwrap();
assert_eq!(pwd.name(), "./");
assert!(pwd.children_iter().count() > 0);
assert!(pwd.size() > 0);
}
#[test]
fn it_is_error_when_constructed_from_missing_path() {
let missing = Entry::for_path(Path::new("./does-not-exist"));
assert_eq!(missing.is_err(), true);
assert_eq!(missing.unwrap_err(), "File not found");
}
#[test]
fn it_is_hidden_when_filename_starts_with_a_dot() {
let hidden = Entry::for_path(Path::new("./.gitignore")).unwrap();
let normal = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(hidden.is_hidden(), true);
assert_eq!(normal.is_hidden(), false);
}
#[test]
fn file_entry_has_no_children() {
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(file.children_iter().count(), 0);
}
#[test]
fn it_can_be_displayed() {
use utils::SizeDisplay;
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(format!("{}", file), format!("LICENSE {}", file.size().as_size_display()));
}
#[test]
fn it_calculates_size_from_children() {
let entry = Entry::for_path(Path::new(".")).unwrap();
let children_size = entry
.children_iter()
.map(|child| child.size())
.fold(0, |sum, item| sum + item);
assert!(entry.size() >= children_size);
}
}
|
random_line_split
|
|
toggle_button.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
use gtk::cast::GTK_TOGGLEBUTTON;
use gtk::{self, ffi};
use glib::{to_bool, to_gboolean};
pub trait ToggleButtonTrait: gtk::WidgetTrait + gtk::ContainerTrait + gtk::ButtonTrait {
fn set_mode(&mut self, draw_indicate: bool) {
unsafe { ffi::gtk_toggle_button_set_mode(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(draw_indicate)); }
}
fn get_mode(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_mode(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
fn toggled(&mut self) -> () {
unsafe {
ffi::gtk_toggle_button_toggled(GTK_TOGGLEBUTTON(self.unwrap_widget()))
}
}
fn set_active(&mut self, is_active: bool) {
unsafe { ffi::gtk_toggle_button_set_active(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(is_active)); }
}
fn get_active(&self) -> bool
|
fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_inconsistent(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
}
|
{
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
|
identifier_body
|
toggle_button.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
use gtk::cast::GTK_TOGGLEBUTTON;
use gtk::{self, ffi};
use glib::{to_bool, to_gboolean};
pub trait ToggleButtonTrait: gtk::WidgetTrait + gtk::ContainerTrait + gtk::ButtonTrait {
fn set_mode(&mut self, draw_indicate: bool) {
unsafe { ffi::gtk_toggle_button_set_mode(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(draw_indicate)); }
}
fn get_mode(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_mode(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
fn toggled(&mut self) -> () {
unsafe {
ffi::gtk_toggle_button_toggled(GTK_TOGGLEBUTTON(self.unwrap_widget()))
}
}
fn set_active(&mut self, is_active: bool) {
unsafe { ffi::gtk_toggle_button_set_active(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(is_active)); }
}
|
fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_inconsistent(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
}
|
fn get_active(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
|
random_line_split
|
toggle_button.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
use gtk::cast::GTK_TOGGLEBUTTON;
use gtk::{self, ffi};
use glib::{to_bool, to_gboolean};
pub trait ToggleButtonTrait: gtk::WidgetTrait + gtk::ContainerTrait + gtk::ButtonTrait {
fn set_mode(&mut self, draw_indicate: bool) {
unsafe { ffi::gtk_toggle_button_set_mode(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(draw_indicate)); }
}
fn get_mode(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_mode(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
fn toggled(&mut self) -> () {
unsafe {
ffi::gtk_toggle_button_toggled(GTK_TOGGLEBUTTON(self.unwrap_widget()))
}
}
fn set_active(&mut self, is_active: bool) {
unsafe { ffi::gtk_toggle_button_set_active(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(is_active)); }
}
fn
|
(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_inconsistent(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
}
|
get_active
|
identifier_name
|
parsed.rs
|
//! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------------------------------
/// A domain name parsed from a DNS message.
///
/// In an attempt to keep messages small, DNS uses a procedure called name
/// compression. It tries to minimize the space used for repeated domain names
/// by simply refering to the first occurence of the name. This works not only
/// for complete names but also for suffixes. In this case, the first unique
/// labels of the name are included and then a pointer is included for the
/// rest of the name.
///
/// A consequence of this is that when parsing a domain name, its labels can
/// be scattered all over the message and we would need to allocate some
/// space to re-assemble the original name. However, in many cases we don’t
/// need the complete message. Many operations can be completed by just
/// iterating over the labels which we can do in place.
///
/// This is what the `ParsedDName` type does: It takes a reference to a
/// message and an indicator where inside the message the name starts and
/// then walks over the message as necessity dictates. When created while
/// parsing a message, the parser quickly walks over the labels to make sure
/// that the name indeed is valid. While this takes up a bit of time, it
/// avoids late surprises and provides for a nicer interface with less
/// `Result`s.
///
/// Obviously, `ParsedDName` implements the [`DName`] trait and provides all
/// operations required by this trait. It also implements `PartialEq` and
/// `Eq`, as well as `PartialOrd` and `Ord` against all other domain name
/// types, plus `Hash` with the same as the other types.
///
/// [`DName`]: trait.DName.html
#[derive(Clone)]
pub struct ParsedDName<'a> {
message: &'a [u8],
start: usize
}
/// # Creation and Conversion
///
impl<'a> ParsedDName<'a> {
/// Creates a new parsed domain name.
///
/// This parses out the leading uncompressed labels from the parser and
/// then quickly jumps over any possible remaining compressing to check
/// that the name is valid.
pub fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
let res = ParsedDName{message: parser.bytes(), start: parser.pos()};
// Step 1: Walk over uncompressed labels to advance the parser.
let pos;
loop {
match try!(Self::parse_label(parser)) {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(x) => {
pos = x;
break
}
}
}
// Step 2: Walk over the rest to see if the name is valid.
let mut parser = parser.clone();
parser.remove_limit();
try!(parser.seek(pos));
loop {
let step = try!(Self::parse_label(&mut parser));
match step {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(pos) => try!(parser.seek(pos))
}
}
}
/// Unpacks the name.
///
/// This will return the cow’s borrowed variant for any parsed name that
/// isn’t in fact compressed. Otherwise it will assemble all the labels
/// into an owned domain name.
pub fn unpack(&self) -> Cow<'a, DNameSlice> {
match self.split_uncompressed() {
(Some(slice), None) => Cow::Borrowed(slice),
(None, Some(packed)) => packed.unpack(),
(None, None) => Cow::Borrowed(DNameSlice::empty()),
(Some(slice), Some(packed)) => {
let mut res = slice.to_owned();
for label in packed.labels() {
res.push(label).unwrap()
}
Cow::Owned(res)
}
}
}
/// Returns a slice if the name is uncompressed.
pub fn as_slice(&self) -> Option<&'a DNameSlice> {
if let (Some(slice), None) = self.split_uncompressed() {
Some(slice)
}
else {
None
}
}
}
/// # Working with Labels
///
impl<'a> ParsedDName<'a> {
/// Returns an iterator over the labels of the name.
pub fn labels(&self) -> NameLabels<'a> {
NameLabels::from_parsed(self.clone())
}
/// Returns an iterator over the labelettes of the name.
pub fn labelettes(&self) -> NameLabelettes<'a> {
NameLabelettes::new(self.labels())
}
/// Splits off the first label from the name.
///
/// For correctly encoded names, this function will always return
/// `Some(_)`. The first element will be the parsed out label. The
/// second element will be a parsed name of the remainder of the name
/// if the label wasn’t the root label or `None` otherwise.
pub fn split_first(&self) -> Option<(&'a Label, Option<Self>)> {
let mut name = self.clone();
loop {
let new_name = match name.split_label() {
Ok(x) => return Some(x),
Err(Some(x)) => x,
Err(None) => return None
};
name = new_name;
}
}
/// Splits a label or goes to where a pointer points.
///
/// Ok((label, tail)) -> a label and what is left.
/// Err(Some(tail)) -> re-positioned tail.
/// Err(None) -> broken
fn split_label(&self) -> Result<(&'a Label, Option<Self>), Option<Self>> {
if self.message[self.start] & 0xC0 == 0xC0 {
// Pointer label.
let start = ((self.message[self.start] & 0x3f) as usize) << 8
| match self.message.get(self.start + 1) {
Some(two) => *two as usize,
None => return Err(None)
};
if start >= self.message.len() {
Err(None)
}
else {
Err(Some(ParsedDName{message: self.message, start: start}))
}
}
else {
// "Real" label.
let (label, _) = match Label::split_from(
&self.message[self.start..]) {
Some(x) => x,
None => return Err(None)
};
let start = self.start + label.len();
if label.is_root() {
Ok((label, None))
}
else {
Ok((label, Some(ParsedDName{message: self.message,
start: start})))
}
}
}
/// Splits off the part that is uncompressed.
fn split_uncompressed(&self) -> (Option<&'a DNameSlice>, Option<Self>) {
let mut name = self.clone();
loop {
name = match name.split_label() {
Ok((_, Some(new_name))) => new_name,
Ok((label, None)) => {
let end = name.start + label.len();
let bytes = &self.message[self.start..end];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
None)
}
Err(Some(new_name)) => {
let bytes = &self.message[self.start..name.start];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
Some(new_name))
}
Err(None) => unreachable!()
};
}
}
/// Parses a label.
///
/// Returns `Ok(is_root)` if the label is a normal label. Returns
/// `Err(pos)` with the position of the next label.
fn parse_label(parser: &mut Parser<'a>)
-> ParseResult<Result<bool, usize>> {
let head = try!(parser.parse_u8());
match head {
0 => Ok(Ok(true)),
1... 0x3F => parser.skip(head as usize).map(|_| Ok(false)),
0x41 => {
let count = try!(parser.parse_u8());
let len = if count == 0 { 32 }
else { ((count - 1) / 8 + 1) as usize };
parser.skip(len).map(|_| Ok(false))
}
0xC0... 0xFF => {
Ok(Err(try!(parser.parse_u8()) as usize
+ (((head & 0x3F) as usize) << 8)))
}
_ => Err(ParseError::UnknownLabel)
}
}
}
//--- DName
impl<'a> DName for ParsedDName<'a> {
fn to_cow(&self) -> Cow<DNameSlice> {
self.unpack()
}
fn labels(&self) -> NameLabels {
NameLabels::from_parsed(self.clone())
}
}
//--- PartialEq and Eq
impl<'a, N: DName> PartialEq<N> for ParsedDName<'a> {
fn eq(&self
|
other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -> bool {
use std::str::FromStr;
let other = match DNameBuf::from_str(other) {
Ok(other) => other,
Err(_) => return false
};
self.eq(&other)
}
}
impl<'a> Eq for ParsedDName<'a> { }
//--- PartialOrd and Ord
impl<'a, N: DName> PartialOrd<N> for ParsedDName<'a> {
fn partial_cmp(&self, other: &N) -> Option<cmp::Ordering> {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.partial_cmp(other_iter)
}
}
impl<'a> Ord for ParsedDName<'a> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.cmp(other_iter)
}
}
//--- Hash
impl<'a> hash::Hash for ParsedDName<'a> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
for item in self.labelettes() {
item.hash(state)
}
}
}
//--- std::fmt traits
impl<'a> fmt::Display for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{}", label));
}
for label in labels {
try!(write!(f, ".{}", label))
}
Ok(())
}
}
impl<'a> fmt::Octal for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:o}", label));
}
for label in labels {
try!(write!(f, ".{:o}", label))
}
Ok(())
}
}
impl<'a> fmt::LowerHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:x}", label));
}
for label in labels {
try!(write!(f, ".{:x}", label))
}
Ok(())
}
}
impl<'a> fmt::UpperHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:X}", label));
}
for label in labels {
try!(write!(f, ".{:X}", label))
}
Ok(())
}
}
impl<'a> fmt::Binary for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:b}", label));
}
for label in labels {
try!(write!(f, ".{:b}", label))
}
Ok(())
}
}
impl<'a> fmt::Debug for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str("ParsedDName("));
try!(fmt::Display::fmt(self, f));
f.write_str(")")
}
}
|
,
|
identifier_name
|
parsed.rs
|
//! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------------------------------
/// A domain name parsed from a DNS message.
///
/// In an attempt to keep messages small, DNS uses a procedure called name
/// compression. It tries to minimize the space used for repeated domain names
/// by simply refering to the first occurence of the name. This works not only
/// for complete names but also for suffixes. In this case, the first unique
/// labels of the name are included and then a pointer is included for the
/// rest of the name.
///
/// A consequence of this is that when parsing a domain name, its labels can
/// be scattered all over the message and we would need to allocate some
/// space to re-assemble the original name. However, in many cases we don’t
/// need the complete message. Many operations can be completed by just
/// iterating over the labels which we can do in place.
///
/// This is what the `ParsedDName` type does: It takes a reference to a
/// message and an indicator where inside the message the name starts and
/// then walks over the message as necessity dictates. When created while
/// parsing a message, the parser quickly walks over the labels to make sure
/// that the name indeed is valid. While this takes up a bit of time, it
/// avoids late surprises and provides for a nicer interface with less
/// `Result`s.
///
/// Obviously, `ParsedDName` implements the [`DName`] trait and provides all
/// operations required by this trait. It also implements `PartialEq` and
/// `Eq`, as well as `PartialOrd` and `Ord` against all other domain name
/// types, plus `Hash` with the same as the other types.
///
/// [`DName`]: trait.DName.html
#[derive(Clone)]
pub struct ParsedDName<'a> {
message: &'a [u8],
start: usize
}
/// # Creation and Conversion
///
impl<'a> ParsedDName<'a> {
/// Creates a new parsed domain name.
///
/// This parses out the leading uncompressed labels from the parser and
/// then quickly jumps over any possible remaining compressing to check
/// that the name is valid.
pub fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
let res = ParsedDName{message: parser.bytes(), start: parser.pos()};
// Step 1: Walk over uncompressed labels to advance the parser.
let pos;
loop {
match try!(Self::parse_label(parser)) {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(x) => {
pos = x;
break
}
}
}
// Step 2: Walk over the rest to see if the name is valid.
let mut parser = parser.clone();
parser.remove_limit();
try!(parser.seek(pos));
loop {
let step = try!(Self::parse_label(&mut parser));
match step {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(pos) => try!(parser.seek(pos))
}
}
}
/// Unpacks the name.
///
/// This will return the cow’s borrowed variant for any parsed name that
/// isn’t in fact compressed. Otherwise it will assemble all the labels
/// into an owned domain name.
pub fn unpack(&self) -> Cow<'a, DNameSlice> {
match self.split_uncompressed() {
(Some(slice), None) => Cow::Borrowed(slice),
(None, Some(packed)) => packed.unpack(),
(None, None) => Cow::Borrowed(DNameSlice::empty()),
(Some(slice), Some(packed)) => {
let mut res = slice.to_owned();
for label in packed.labels() {
res.push(label).unwrap()
}
Cow::Owned(res)
}
}
}
/// Returns a slice if the name is uncompressed.
pub fn as_slice(&self) -> Option<&'a DNameSlice> {
if let (Some(slice), None) = self.split_uncompressed() {
Some(slice)
}
else {
None
}
}
}
/// # Working with Labels
///
impl<'a> ParsedDName<'a> {
/// Returns an iterator over the labels of the name.
pub fn labels(&self) -> NameLabels<'a> {
NameLabels::from_parsed(self.clone())
}
/// Returns an iterator over the labelettes of the name.
pub fn labelettes(&self) -> NameLabelettes<'a> {
NameLabelettes::new(self.labels())
}
/// Splits off the first label from the name.
///
/// For correctly encoded names, this function will always return
/// `Some(_)`. The first element will be the parsed out label. The
/// second element will be a parsed name of the remainder of the name
/// if the label wasn’t the root label or `None` otherwise.
pub fn split_first(&self) -> Option<(&'a Label, Option<Self>)> {
let mut name = self.clone();
loop {
let new_name = match name.split_label() {
Ok(x) => return Some(x),
Err(Some(x)) => x,
Err(None) => return None
};
name = new_name;
}
}
/// Splits a label or goes to where a pointer points.
///
/// Ok((label, tail)) -> a label and what is left.
/// Err(Some(tail)) -> re-positioned tail.
/// Err(None) -> broken
fn split_label(&self) -> Result<(&'a Label, Option<Self>), Option<Self>> {
if self.message[self.start] & 0xC0 == 0xC0 {
// Pointer label.
let start = ((self.message[self.start] & 0x3f) as usize) << 8
| match self.message.get(self.start + 1) {
Some(two) => *two as usize,
None => return Err(None)
};
if start >= self.message.len() {
Err(None)
}
else {
Err(Some(ParsedDName{message: self.message, start: start}))
}
}
else {
// "Real" label.
let (label, _) = match Label::split_from(
&self.message[self.start..]) {
Some(x) => x,
None => return Err(None)
};
let start = self.start + label.len();
if label.is_root() {
Ok((label, None))
}
else {
|
}
}
/// Splits off the part that is uncompressed.
fn split_uncompressed(&self) -> (Option<&'a DNameSlice>, Option<Self>) {
let mut name = self.clone();
loop {
name = match name.split_label() {
Ok((_, Some(new_name))) => new_name,
Ok((label, None)) => {
let end = name.start + label.len();
let bytes = &self.message[self.start..end];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
None)
}
Err(Some(new_name)) => {
let bytes = &self.message[self.start..name.start];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
Some(new_name))
}
Err(None) => unreachable!()
};
}
}
/// Parses a label.
///
/// Returns `Ok(is_root)` if the label is a normal label. Returns
/// `Err(pos)` with the position of the next label.
fn parse_label(parser: &mut Parser<'a>)
-> ParseResult<Result<bool, usize>> {
let head = try!(parser.parse_u8());
match head {
0 => Ok(Ok(true)),
1... 0x3F => parser.skip(head as usize).map(|_| Ok(false)),
0x41 => {
let count = try!(parser.parse_u8());
let len = if count == 0 { 32 }
else { ((count - 1) / 8 + 1) as usize };
parser.skip(len).map(|_| Ok(false))
}
0xC0... 0xFF => {
Ok(Err(try!(parser.parse_u8()) as usize
+ (((head & 0x3F) as usize) << 8)))
}
_ => Err(ParseError::UnknownLabel)
}
}
}
//--- DName
impl<'a> DName for ParsedDName<'a> {
fn to_cow(&self) -> Cow<DNameSlice> {
self.unpack()
}
fn labels(&self) -> NameLabels {
NameLabels::from_parsed(self.clone())
}
}
//--- PartialEq and Eq
impl<'a, N: DName> PartialEq<N> for ParsedDName<'a> {
fn eq(&self, other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -> bool {
use std::str::FromStr;
let other = match DNameBuf::from_str(other) {
Ok(other) => other,
Err(_) => return false
};
self.eq(&other)
}
}
impl<'a> Eq for ParsedDName<'a> { }
//--- PartialOrd and Ord
impl<'a, N: DName> PartialOrd<N> for ParsedDName<'a> {
fn partial_cmp(&self, other: &N) -> Option<cmp::Ordering> {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.partial_cmp(other_iter)
}
}
impl<'a> Ord for ParsedDName<'a> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.cmp(other_iter)
}
}
//--- Hash
impl<'a> hash::Hash for ParsedDName<'a> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
for item in self.labelettes() {
item.hash(state)
}
}
}
//--- std::fmt traits
impl<'a> fmt::Display for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{}", label));
}
for label in labels {
try!(write!(f, ".{}", label))
}
Ok(())
}
}
impl<'a> fmt::Octal for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:o}", label));
}
for label in labels {
try!(write!(f, ".{:o}", label))
}
Ok(())
}
}
impl<'a> fmt::LowerHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:x}", label));
}
for label in labels {
try!(write!(f, ".{:x}", label))
}
Ok(())
}
}
impl<'a> fmt::UpperHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:X}", label));
}
for label in labels {
try!(write!(f, ".{:X}", label))
}
Ok(())
}
}
impl<'a> fmt::Binary for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:b}", label));
}
for label in labels {
try!(write!(f, ".{:b}", label))
}
Ok(())
}
}
impl<'a> fmt::Debug for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str("ParsedDName("));
try!(fmt::Display::fmt(self, f));
f.write_str(")")
}
}
|
Ok((label, Some(ParsedDName{message: self.message,
start: start})))
}
|
conditional_block
|
parsed.rs
|
//! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------------------------------
/// A domain name parsed from a DNS message.
///
/// In an attempt to keep messages small, DNS uses a procedure called name
/// compression. It tries to minimize the space used for repeated domain names
/// by simply refering to the first occurence of the name. This works not only
/// for complete names but also for suffixes. In this case, the first unique
/// labels of the name are included and then a pointer is included for the
/// rest of the name.
///
/// A consequence of this is that when parsing a domain name, its labels can
/// be scattered all over the message and we would need to allocate some
/// space to re-assemble the original name. However, in many cases we don’t
/// need the complete message. Many operations can be completed by just
/// iterating over the labels which we can do in place.
///
/// This is what the `ParsedDName` type does: It takes a reference to a
/// message and an indicator where inside the message the name starts and
/// then walks over the message as necessity dictates. When created while
/// parsing a message, the parser quickly walks over the labels to make sure
/// that the name indeed is valid. While this takes up a bit of time, it
/// avoids late surprises and provides for a nicer interface with less
/// `Result`s.
///
/// Obviously, `ParsedDName` implements the [`DName`] trait and provides all
/// operations required by this trait. It also implements `PartialEq` and
/// `Eq`, as well as `PartialOrd` and `Ord` against all other domain name
/// types, plus `Hash` with the same as the other types.
///
/// [`DName`]: trait.DName.html
#[derive(Clone)]
pub struct ParsedDName<'a> {
message: &'a [u8],
start: usize
}
/// # Creation and Conversion
///
impl<'a> ParsedDName<'a> {
/// Creates a new parsed domain name.
///
/// This parses out the leading uncompressed labels from the parser and
/// then quickly jumps over any possible remaining compressing to check
/// that the name is valid.
pub fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
let res = ParsedDName{message: parser.bytes(), start: parser.pos()};
// Step 1: Walk over uncompressed labels to advance the parser.
let pos;
loop {
match try!(Self::parse_label(parser)) {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(x) => {
pos = x;
break
}
}
}
// Step 2: Walk over the rest to see if the name is valid.
let mut parser = parser.clone();
parser.remove_limit();
try!(parser.seek(pos));
loop {
let step = try!(Self::parse_label(&mut parser));
match step {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(pos) => try!(parser.seek(pos))
}
}
}
/// Unpacks the name.
///
/// This will return the cow’s borrowed variant for any parsed name that
/// isn’t in fact compressed. Otherwise it will assemble all the labels
/// into an owned domain name.
pub fn unpack(&self) -> Cow<'a, DNameSlice> {
match self.split_uncompressed() {
(Some(slice), None) => Cow::Borrowed(slice),
(None, Some(packed)) => packed.unpack(),
(None, None) => Cow::Borrowed(DNameSlice::empty()),
(Some(slice), Some(packed)) => {
let mut res = slice.to_owned();
for label in packed.labels() {
res.push(label).unwrap()
}
Cow::Owned(res)
}
}
}
/// Returns a slice if the name is uncompressed.
pub fn as_slice(&self) -> Option<&'a DNameSlice> {
if let (Some(slice), None) = self.split_uncompressed() {
Some(slice)
}
else {
None
}
}
}
/// # Working with Labels
///
impl<'a> ParsedDName<'a> {
/// Returns an iterator over the labels of the name.
pub fn labels(&self) -> NameLabels<'a> {
NameLabels::from_parsed(self.clone())
}
/// Returns an iterator over the labelettes of the name.
pub fn labelettes(&self) -> NameLabelettes<'a> {
NameLabelettes::new(self.labels())
}
/// Splits off the first label from the name.
///
/// For correctly encoded names, this function will always return
/// `Some(_)`. The first element will be the parsed out label. The
/// second element will be a parsed name of the remainder of the name
/// if the label wasn’t the root label or `None` otherwise.
pub fn split_first(&self) -> Option<(&'a Label, Option<Self>)> {
let mut name = self.clone();
loop {
let new_name = match name.split_label() {
Ok(x) => return Some(x),
Err(Some(x)) => x,
Err(None) => return None
};
name = new_name;
}
}
/// Splits a label or goes to where a pointer points.
///
/// Ok((label, tail)) -> a label and what is left.
/// Err(Some(tail)) -> re-positioned tail.
/// Err(None) -> broken
fn split_label(&self) -> Result<(&'a Label, Option<Self>), Option<Self>> {
if self.message[self.start] & 0xC0 == 0xC0 {
// Pointer label.
let start = ((self.message[self.start] & 0x3f) as usize) << 8
| match self.message.get(self.start + 1) {
Some(two) => *two as usize,
None => return Err(None)
};
if start >= self.message.len() {
Err(None)
}
else {
Err(Some(ParsedDName{message: self.message, start: start}))
}
}
else {
// "Real" label.
let (label, _) = match Label::split_from(
&self.message[self.start..]) {
Some(x) => x,
None => return Err(None)
};
let start = self.start + label.len();
if label.is_root() {
Ok((label, None))
}
else {
Ok((label, Some(ParsedDName{message: self.message,
start: start})))
}
}
}
/// Splits off the part that is uncompressed.
fn split_uncompressed(&self) -> (Option<&'a DNameSlice>, Option<Self>) {
let mut name = self.clone();
loop {
name = match name.split_label() {
Ok((_, Some(new_name))) => new_name,
Ok((label, None)) => {
let end = name.start + label.len();
let bytes = &self.message[self.start..end];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
None)
}
Err(Some(new_name)) => {
let bytes = &self.message[self.start..name.start];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
Some(new_name))
}
Err(None) => unreachable!()
};
}
}
/// Parses a label.
///
/// Returns `Ok(is_root)` if the label is a normal label. Returns
/// `Err(pos)` with the position of the next label.
fn parse_label(parser: &mut Parser<'a>)
-> ParseResult<Result<bool, usize>> {
let head = try!(parser.parse_u8());
match head {
0 => Ok(Ok(true)),
1... 0x3F => parser.skip(head as usize).map(|_| Ok(false)),
0x41 => {
let count = try!(parser.parse_u8());
let len = if count == 0 { 32 }
else { ((count - 1) / 8 + 1) as usize };
parser.skip(len).map(|_| Ok(false))
}
0xC0... 0xFF => {
Ok(Err(try!(parser.parse_u8()) as usize
+ (((head & 0x3F) as usize) << 8)))
}
_ => Err(ParseError::UnknownLabel)
}
}
}
//--- DName
impl<'a> DName for ParsedDName<'a> {
fn to_cow(&self) -> Cow<DNameSlice> {
self.unpack()
}
fn labels(&self) -> NameLabels {
NameLabels::from_parsed(self.clone())
}
}
//--- PartialEq and Eq
impl<'a, N: DName> PartialEq<N> for ParsedDName<'a> {
fn eq(&self, other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -> bool {
use std::str::FromStr;
let other = match DNameBuf::from_str(other) {
Ok(other) => other,
Err(_) => return false
};
self.eq(&other)
}
}
impl<'a> Eq for ParsedDName<'a> { }
//--- PartialOrd and Ord
impl<'a, N: DName> PartialOrd<N> for ParsedDName<'a> {
fn partial_cmp(&self, other: &N) -> Option<cmp::Ordering> {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.partial_cmp(other_iter)
}
}
impl<'a> Ord for ParsedDName<'a> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.cmp(other_iter)
}
}
//--- Hash
impl<'a> hash::Hash for ParsedDName<'a> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
for item in self.labelettes() {
item.hash(state)
}
}
}
//--- std::fmt traits
impl<'a> fmt::Display for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{}", label));
}
for label in labels {
try!(write!(f, ".{}", label))
}
Ok(())
}
}
impl<'a> fmt::Octal for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:o}", label));
}
for label in labels {
try!(write!(f, ".{:o}", label))
}
Ok(())
}
}
impl<'a> fmt::LowerHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:x}", label));
}
for label in labels {
try!(write!(f, ".{:x}", label))
|
impl<'a> fmt::UpperHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:X}", label));
}
for label in labels {
try!(write!(f, ".{:X}", label))
}
Ok(())
}
}
impl<'a> fmt::Binary for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:b}", label));
}
for label in labels {
try!(write!(f, ".{:b}", label))
}
Ok(())
}
}
impl<'a> fmt::Debug for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str("ParsedDName("));
try!(fmt::Display::fmt(self, f));
f.write_str(")")
}
}
|
}
Ok(())
}
}
|
random_line_split
|
parsed.rs
|
//! Parsed domain names.
use std::borrow::Cow;
use std::cmp;
use std::fmt;
use std::hash;
use super::super::{Parser, ParseError, ParseResult};
use super::{DName, DNameBuf, DNameSlice, Label, NameLabels, NameLabelettes};
use super::plain::slice_from_bytes_unsafe;
//------------ ParsedDName ---------------------------------------------------
/// A domain name parsed from a DNS message.
///
/// In an attempt to keep messages small, DNS uses a procedure called name
/// compression. It tries to minimize the space used for repeated domain names
/// by simply refering to the first occurence of the name. This works not only
/// for complete names but also for suffixes. In this case, the first unique
/// labels of the name are included and then a pointer is included for the
/// rest of the name.
///
/// A consequence of this is that when parsing a domain name, its labels can
/// be scattered all over the message and we would need to allocate some
/// space to re-assemble the original name. However, in many cases we don’t
/// need the complete message. Many operations can be completed by just
/// iterating over the labels which we can do in place.
///
/// This is what the `ParsedDName` type does: It takes a reference to a
/// message and an indicator where inside the message the name starts and
/// then walks over the message as necessity dictates. When created while
/// parsing a message, the parser quickly walks over the labels to make sure
/// that the name indeed is valid. While this takes up a bit of time, it
/// avoids late surprises and provides for a nicer interface with less
/// `Result`s.
///
/// Obviously, `ParsedDName` implements the [`DName`] trait and provides all
/// operations required by this trait. It also implements `PartialEq` and
/// `Eq`, as well as `PartialOrd` and `Ord` against all other domain name
/// types, plus `Hash` with the same as the other types.
///
/// [`DName`]: trait.DName.html
#[derive(Clone)]
pub struct ParsedDName<'a> {
message: &'a [u8],
start: usize
}
/// # Creation and Conversion
///
impl<'a> ParsedDName<'a> {
/// Creates a new parsed domain name.
///
/// This parses out the leading uncompressed labels from the parser and
/// then quickly jumps over any possible remaining compressing to check
/// that the name is valid.
pub fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
let res = ParsedDName{message: parser.bytes(), start: parser.pos()};
// Step 1: Walk over uncompressed labels to advance the parser.
let pos;
loop {
match try!(Self::parse_label(parser)) {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(x) => {
pos = x;
break
}
}
}
// Step 2: Walk over the rest to see if the name is valid.
let mut parser = parser.clone();
parser.remove_limit();
try!(parser.seek(pos));
loop {
let step = try!(Self::parse_label(&mut parser));
match step {
Ok(true) => return Ok(res),
Ok(false) => { }
Err(pos) => try!(parser.seek(pos))
}
}
}
/// Unpacks the name.
///
/// This will return the cow’s borrowed variant for any parsed name that
/// isn’t in fact compressed. Otherwise it will assemble all the labels
/// into an owned domain name.
pub fn unpack(&self) -> Cow<'a, DNameSlice> {
match self.split_uncompressed() {
(Some(slice), None) => Cow::Borrowed(slice),
(None, Some(packed)) => packed.unpack(),
(None, None) => Cow::Borrowed(DNameSlice::empty()),
(Some(slice), Some(packed)) => {
let mut res = slice.to_owned();
for label in packed.labels() {
res.push(label).unwrap()
}
Cow::Owned(res)
}
}
}
/// Returns a slice if the name is uncompressed.
pub fn as_slice(&self) -> Option<&'a DNameSlice> {
if let (Some(slice), None) = self.split_uncompressed() {
Some(slice)
}
else {
None
}
}
}
/// # Working with Labels
///
impl<'a> ParsedDName<'a> {
/// Returns an iterator over the labels of the name.
pub fn labels(&self) -> NameLabels<'a> {
NameLabels::from_parsed(self.clone())
}
/// Returns an iterator over the labelettes of the name.
pub fn labelettes(&self) -> NameLabelettes<'a> {
NameLabelettes::new(self.labels())
}
/// Splits off the first label from the name.
///
/// For correctly encoded names, this function will always return
/// `Some(_)`. The first element will be the parsed out label. The
/// second element will be a parsed name of the remainder of the name
/// if the label wasn’t the root label or `None` otherwise.
pub fn split_first(&self) -> Option<(&'a Label, Option<Self>)> {
let mut name = self.clone();
loop {
let new_name = match name.split_label() {
Ok(x) => return Some(x),
Err(Some(x)) => x,
Err(None) => return None
};
name = new_name;
}
}
/// Splits a label or goes to where a pointer points.
///
/// Ok((label, tail)) -> a label and what is left.
/// Err(Some(tail)) -> re-positioned tail.
/// Err(None) -> broken
fn split_label(&self) -> Result<(&'a Label, Option<Self>), Option<Self>> {
if self.message[self.start] & 0xC0 == 0xC0 {
// Pointer label.
let start = ((self.message[self.start] & 0x3f) as usize) << 8
| match self.message.get(self.start + 1) {
Some(two) => *two as usize,
None => return Err(None)
};
if start >= self.message.len() {
Err(None)
}
else {
Err(Some(ParsedDName{message: self.message, start: start}))
}
}
else {
// "Real" label.
let (label, _) = match Label::split_from(
&self.message[self.start..]) {
Some(x) => x,
None => return Err(None)
};
let start = self.start + label.len();
if label.is_root() {
Ok((label, None))
}
else {
Ok((label, Some(ParsedDName{message: self.message,
start: start})))
}
}
}
/// Splits off the part that is uncompressed.
fn split_uncompressed(&self) -> (Option<&'a DNameSlice>, Option<Self>) {
let mut name = self.clone();
loop {
name = match name.split_label() {
Ok((_, Some(new_name))) => new_name,
Ok((label, None)) => {
let end = name.start + label.len();
let bytes = &self.message[self.start..end];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
None)
}
Err(Some(new_name)) => {
let bytes = &self.message[self.start..name.start];
return (Some(unsafe { slice_from_bytes_unsafe(bytes) }),
Some(new_name))
}
Err(None) => unreachable!()
};
}
}
/// Parses a label.
///
/// Returns `Ok(is_root)` if the label is a normal label. Returns
/// `Err(pos)` with the position of the next label.
fn parse_label(parser: &mut Parser<'a>)
-> ParseResult<Result<bool, usize>> {
let head = try!(parser.parse_u8());
match head {
0 => Ok(Ok(true)),
1... 0x3F => parser.skip(head as usize).map(|_| Ok(false)),
0x41 => {
let count = try!(parser.parse_u8());
let len = if count == 0 { 32 }
else { ((count - 1) / 8 + 1) as usize };
parser.skip(len).map(|_| Ok(false))
}
0xC0... 0xFF => {
Ok(Err(try!(parser.parse_u8()) as usize
+ (((head & 0x3F) as usize) << 8)))
}
_ => Err(ParseError::UnknownLabel)
}
}
}
//--- DName
impl<'a> DName for ParsedDName<'a> {
fn to_cow(&self) -> Cow<DNameSlice> {
self.unpack()
}
fn labels(&self) -> NameLabels {
|
-- PartialEq and Eq
impl<'a, N: DName> PartialEq<N> for ParsedDName<'a> {
fn eq(&self, other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -> bool {
use std::str::FromStr;
let other = match DNameBuf::from_str(other) {
Ok(other) => other,
Err(_) => return false
};
self.eq(&other)
}
}
impl<'a> Eq for ParsedDName<'a> { }
//--- PartialOrd and Ord
impl<'a, N: DName> PartialOrd<N> for ParsedDName<'a> {
fn partial_cmp(&self, other: &N) -> Option<cmp::Ordering> {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.partial_cmp(other_iter)
}
}
impl<'a> Ord for ParsedDName<'a> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
let self_iter = self.labelettes().rev();
let other_iter = other.labelettes().rev();
self_iter.cmp(other_iter)
}
}
//--- Hash
impl<'a> hash::Hash for ParsedDName<'a> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
for item in self.labelettes() {
item.hash(state)
}
}
}
//--- std::fmt traits
impl<'a> fmt::Display for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{}", label));
}
for label in labels {
try!(write!(f, ".{}", label))
}
Ok(())
}
}
impl<'a> fmt::Octal for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:o}", label));
}
for label in labels {
try!(write!(f, ".{:o}", label))
}
Ok(())
}
}
impl<'a> fmt::LowerHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:x}", label));
}
for label in labels {
try!(write!(f, ".{:x}", label))
}
Ok(())
}
}
impl<'a> fmt::UpperHex for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:X}", label));
}
for label in labels {
try!(write!(f, ".{:X}", label))
}
Ok(())
}
}
impl<'a> fmt::Binary for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.labels();
if let Some(label) = labels.next() {
try!(write!(f, "{:b}", label));
}
for label in labels {
try!(write!(f, ".{:b}", label))
}
Ok(())
}
}
impl<'a> fmt::Debug for ParsedDName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str("ParsedDName("));
try!(fmt::Display::fmt(self, f));
f.write_str(")")
}
}
|
NameLabels::from_parsed(self.clone())
}
}
//-
|
identifier_body
|
misc.rs
|
//! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
|
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Adds a new temporary value of type `ty` storing the result of
/// evaluating `expr`.
///
/// N.B., **No cleanup is scheduled for this temporary.** You should
/// call `schedule_drop` once the temporary is initialized.
crate fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> {
// Mark this local as internal to avoid temporaries with types not present in the
// user's code resulting in ICEs from the generator transform.
let temp = self.local_decls.push(LocalDecl::new(ty, span).internal());
let place = Place::from(temp);
debug!("temp: created temp {:?} with type {:?}", place, self.local_decls[temp].ty);
place
}
/// Convenience function for creating a literal operand, one
/// without any user type annotation.
crate fn literal_operand(
&mut self,
span: Span,
literal: &'tcx ty::Const<'tcx>,
) -> Operand<'tcx> {
let literal = literal.into();
let constant = Box::new(Constant { span, user_ty: None, literal });
Operand::Constant(constant)
}
// Returns a zero literal operand for the appropriate type, works for
// bool, char and integers.
crate fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
let literal = ty::Const::from_bits(self.tcx, 0, ty::ParamEnv::empty().and(ty));
self.literal_operand(span, literal)
}
crate fn push_usize(
&mut self,
block: BasicBlock,
source_info: SourceInfo,
value: u64,
) -> Place<'tcx> {
let usize_ty = self.tcx.types.usize;
let temp = self.temp(usize_ty, source_info.span);
self.cfg.push_assign_constant(
block,
source_info,
temp,
Constant {
span: source_info.span,
user_ty: None,
literal: ty::Const::from_usize(self.tcx, value).into(),
},
);
temp
}
crate fn consume_by_copy_or_move(&self, place: Place<'tcx>) -> Operand<'tcx> {
let tcx = self.tcx;
let ty = place.ty(&self.local_decls, tcx).ty;
if!self.infcx.type_is_copy_modulo_regions(self.param_env, ty, DUMMY_SP) {
Operand::Move(place)
} else {
Operand::Copy(place)
}
}
}
|
random_line_split
|
|
misc.rs
|
//! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Adds a new temporary value of type `ty` storing the result of
/// evaluating `expr`.
///
/// N.B., **No cleanup is scheduled for this temporary.** You should
/// call `schedule_drop` once the temporary is initialized.
crate fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> {
// Mark this local as internal to avoid temporaries with types not present in the
// user's code resulting in ICEs from the generator transform.
let temp = self.local_decls.push(LocalDecl::new(ty, span).internal());
let place = Place::from(temp);
debug!("temp: created temp {:?} with type {:?}", place, self.local_decls[temp].ty);
place
}
/// Convenience function for creating a literal operand, one
/// without any user type annotation.
crate fn literal_operand(
&mut self,
span: Span,
literal: &'tcx ty::Const<'tcx>,
) -> Operand<'tcx> {
let literal = literal.into();
let constant = Box::new(Constant { span, user_ty: None, literal });
Operand::Constant(constant)
}
// Returns a zero literal operand for the appropriate type, works for
// bool, char and integers.
crate fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
let literal = ty::Const::from_bits(self.tcx, 0, ty::ParamEnv::empty().and(ty));
self.literal_operand(span, literal)
}
crate fn push_usize(
&mut self,
block: BasicBlock,
source_info: SourceInfo,
value: u64,
) -> Place<'tcx> {
let usize_ty = self.tcx.types.usize;
let temp = self.temp(usize_ty, source_info.span);
self.cfg.push_assign_constant(
block,
source_info,
temp,
Constant {
span: source_info.span,
user_ty: None,
literal: ty::Const::from_usize(self.tcx, value).into(),
},
);
temp
}
crate fn consume_by_copy_or_move(&self, place: Place<'tcx>) -> Operand<'tcx>
|
}
|
{
let tcx = self.tcx;
let ty = place.ty(&self.local_decls, tcx).ty;
if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, DUMMY_SP) {
Operand::Move(place)
} else {
Operand::Copy(place)
}
}
|
identifier_body
|
misc.rs
|
//! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Adds a new temporary value of type `ty` storing the result of
/// evaluating `expr`.
///
/// N.B., **No cleanup is scheduled for this temporary.** You should
/// call `schedule_drop` once the temporary is initialized.
crate fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> {
// Mark this local as internal to avoid temporaries with types not present in the
// user's code resulting in ICEs from the generator transform.
let temp = self.local_decls.push(LocalDecl::new(ty, span).internal());
let place = Place::from(temp);
debug!("temp: created temp {:?} with type {:?}", place, self.local_decls[temp].ty);
place
}
/// Convenience function for creating a literal operand, one
/// without any user type annotation.
crate fn literal_operand(
&mut self,
span: Span,
literal: &'tcx ty::Const<'tcx>,
) -> Operand<'tcx> {
let literal = literal.into();
let constant = Box::new(Constant { span, user_ty: None, literal });
Operand::Constant(constant)
}
// Returns a zero literal operand for the appropriate type, works for
// bool, char and integers.
crate fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
let literal = ty::Const::from_bits(self.tcx, 0, ty::ParamEnv::empty().and(ty));
self.literal_operand(span, literal)
}
crate fn push_usize(
&mut self,
block: BasicBlock,
source_info: SourceInfo,
value: u64,
) -> Place<'tcx> {
let usize_ty = self.tcx.types.usize;
let temp = self.temp(usize_ty, source_info.span);
self.cfg.push_assign_constant(
block,
source_info,
temp,
Constant {
span: source_info.span,
user_ty: None,
literal: ty::Const::from_usize(self.tcx, value).into(),
},
);
temp
}
crate fn consume_by_copy_or_move(&self, place: Place<'tcx>) -> Operand<'tcx> {
let tcx = self.tcx;
let ty = place.ty(&self.local_decls, tcx).ty;
if!self.infcx.type_is_copy_modulo_regions(self.param_env, ty, DUMMY_SP) {
Operand::Move(place)
} else
|
}
}
|
{
Operand::Copy(place)
}
|
conditional_block
|
misc.rs
|
//! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Adds a new temporary value of type `ty` storing the result of
/// evaluating `expr`.
///
/// N.B., **No cleanup is scheduled for this temporary.** You should
/// call `schedule_drop` once the temporary is initialized.
crate fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> {
// Mark this local as internal to avoid temporaries with types not present in the
// user's code resulting in ICEs from the generator transform.
let temp = self.local_decls.push(LocalDecl::new(ty, span).internal());
let place = Place::from(temp);
debug!("temp: created temp {:?} with type {:?}", place, self.local_decls[temp].ty);
place
}
/// Convenience function for creating a literal operand, one
/// without any user type annotation.
crate fn literal_operand(
&mut self,
span: Span,
literal: &'tcx ty::Const<'tcx>,
) -> Operand<'tcx> {
let literal = literal.into();
let constant = Box::new(Constant { span, user_ty: None, literal });
Operand::Constant(constant)
}
// Returns a zero literal operand for the appropriate type, works for
// bool, char and integers.
crate fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
let literal = ty::Const::from_bits(self.tcx, 0, ty::ParamEnv::empty().and(ty));
self.literal_operand(span, literal)
}
crate fn
|
(
&mut self,
block: BasicBlock,
source_info: SourceInfo,
value: u64,
) -> Place<'tcx> {
let usize_ty = self.tcx.types.usize;
let temp = self.temp(usize_ty, source_info.span);
self.cfg.push_assign_constant(
block,
source_info,
temp,
Constant {
span: source_info.span,
user_ty: None,
literal: ty::Const::from_usize(self.tcx, value).into(),
},
);
temp
}
crate fn consume_by_copy_or_move(&self, place: Place<'tcx>) -> Operand<'tcx> {
let tcx = self.tcx;
let ty = place.ty(&self.local_decls, tcx).ty;
if!self.infcx.type_is_copy_modulo_regions(self.param_env, ty, DUMMY_SP) {
Operand::Move(place)
} else {
Operand::Copy(place)
}
}
}
|
push_usize
|
identifier_name
|
build.rs
|
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source.
#![deny(
clippy::all,
clippy::default_trait_access,
clippy::expl_impl_clone_on_copy,
clippy::if_not_else,
clippy::needless_continue,
clippy::unseparated_literal_suffix,
clippy::used_underscore_binding
)]
// It is often more clear to show that nothing is being moved.
#![allow(clippy::match_ref_pats)]
// Subjective style.
#![allow(
clippy::len_without_is_empty,
clippy::redundant_field_names,
clippy::too_many_arguments
)]
// Default isn't as big a deal as people seem to think it is.
#![allow(clippy::new_without_default, clippy::new_ret_no_self)]
|
fn main() {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
}
|
// Arc<Mutex> can be more clear than needing to grok Orderings:
#![allow(clippy::mutex_atomic)]
|
random_line_split
|
build.rs
|
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source.
#![deny(
clippy::all,
clippy::default_trait_access,
clippy::expl_impl_clone_on_copy,
clippy::if_not_else,
clippy::needless_continue,
clippy::unseparated_literal_suffix,
clippy::used_underscore_binding
)]
// It is often more clear to show that nothing is being moved.
#![allow(clippy::match_ref_pats)]
// Subjective style.
#![allow(
clippy::len_without_is_empty,
clippy::redundant_field_names,
clippy::too_many_arguments
)]
// Default isn't as big a deal as people seem to think it is.
#![allow(clippy::new_without_default, clippy::new_ret_no_self)]
// Arc<Mutex> can be more clear than needing to grok Orderings:
#![allow(clippy::mutex_atomic)]
fn
|
() {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
}
|
main
|
identifier_name
|
build.rs
|
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source.
#![deny(
clippy::all,
clippy::default_trait_access,
clippy::expl_impl_clone_on_copy,
clippy::if_not_else,
clippy::needless_continue,
clippy::unseparated_literal_suffix,
clippy::used_underscore_binding
)]
// It is often more clear to show that nothing is being moved.
#![allow(clippy::match_ref_pats)]
// Subjective style.
#![allow(
clippy::len_without_is_empty,
clippy::redundant_field_names,
clippy::too_many_arguments
)]
// Default isn't as big a deal as people seem to think it is.
#![allow(clippy::new_without_default, clippy::new_ret_no_self)]
// Arc<Mutex> can be more clear than needing to grok Orderings:
#![allow(clippy::mutex_atomic)]
fn main()
|
{
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
}
|
identifier_body
|
|
db.rs
|
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State};
use std::ops::Deref;
type PgPool = Pool<ConnectionManager<PgConnection>>;
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let pool = request.guard::<State<PgPool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
}
}
}
impl Deref for DbConn {
type Target = PgConnection;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub fn init_pool() -> PgPool {
let manager = ConnectionManager::<PgConnection>::new(env!("DATABASE_URL"));
Pool::new(manager).expect("db pool")
}
|
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = ();
|
random_line_split
|
db.rs
|
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State};
use std::ops::Deref;
type PgPool = Pool<ConnectionManager<PgConnection>>;
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let pool = request.guard::<State<PgPool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
}
}
}
impl Deref for DbConn {
type Target = PgConnection;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub fn
|
() -> PgPool {
let manager = ConnectionManager::<PgConnection>::new(env!("DATABASE_URL"));
Pool::new(manager).expect("db pool")
}
|
init_pool
|
identifier_name
|
events.rs
|
/* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use crate::core::*;
use crate::smb::smb::*;
#[derive(AppLayerEvent)]
pub enum SMBEvent {
InternalError,
MalformedData,
RecordOverflow,
MalformedNtlmsspRequest,
MalformedNtlmsspResponse,
DuplicateNegotiate,
NegotiateMalformedDialects,
FileOverlap,
}
impl SMBTransaction {
/// Set event.
pub fn set_event(&mut self, e: SMBEvent) {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
/// Set events from vector of events.
pub fn set_events(&mut self, events: Vec<SMBEvent>) {
for e in events {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
}
}
impl SMBState {
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: SMBEvent) {
let len = self.transactions.len();
if len == 0
|
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
|
{
return;
}
|
conditional_block
|
events.rs
|
/* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use crate::core::*;
use crate::smb::smb::*;
#[derive(AppLayerEvent)]
pub enum SMBEvent {
InternalError,
MalformedData,
RecordOverflow,
MalformedNtlmsspRequest,
MalformedNtlmsspResponse,
DuplicateNegotiate,
NegotiateMalformedDialects,
FileOverlap,
}
impl SMBTransaction {
/// Set event.
pub fn set_event(&mut self, e: SMBEvent) {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
/// Set events from vector of events.
pub fn set_events(&mut self, events: Vec<SMBEvent>) {
for e in events {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
}
}
impl SMBState {
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: SMBEvent) {
let len = self.transactions.len();
if len == 0 {
return;
}
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
|
random_line_split
|
events.rs
|
/* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use crate::core::*;
use crate::smb::smb::*;
#[derive(AppLayerEvent)]
pub enum SMBEvent {
InternalError,
MalformedData,
RecordOverflow,
MalformedNtlmsspRequest,
MalformedNtlmsspResponse,
DuplicateNegotiate,
NegotiateMalformedDialects,
FileOverlap,
}
impl SMBTransaction {
/// Set event.
pub fn set_event(&mut self, e: SMBEvent)
|
/// Set events from vector of events.
pub fn set_events(&mut self, events: Vec<SMBEvent>) {
for e in events {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
}
}
impl SMBState {
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: SMBEvent) {
let len = self.transactions.len();
if len == 0 {
return;
}
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
|
{
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
|
identifier_body
|
events.rs
|
/* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use crate::core::*;
use crate::smb::smb::*;
#[derive(AppLayerEvent)]
pub enum SMBEvent {
InternalError,
MalformedData,
RecordOverflow,
MalformedNtlmsspRequest,
MalformedNtlmsspResponse,
DuplicateNegotiate,
NegotiateMalformedDialects,
FileOverlap,
}
impl SMBTransaction {
/// Set event.
pub fn set_event(&mut self, e: SMBEvent) {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
/// Set events from vector of events.
pub fn set_events(&mut self, events: Vec<SMBEvent>) {
for e in events {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
}
}
impl SMBState {
/// Set an event. The event is set on the most recent transaction.
pub fn
|
(&mut self, event: SMBEvent) {
let len = self.transactions.len();
if len == 0 {
return;
}
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
|
set_event
|
identifier_name
|
counters.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Counters", inherited=False, gecko_name="Content") %>
${helpers.predefined_type(
"content",
"Content",
"computed::Content::normal()",
initial_specified_value="specified::Content::normal()",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-content/#propdef-content",
servo_restyle_damage="rebuild_and_reflow",
)}
${helpers.predefined_type(
"counter-increment",
"CounterIncrement",
initial_value="Default::default()",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists/#propdef-counter-increment",
|
${helpers.predefined_type(
"counter-reset",
"CounterReset",
initial_value="Default::default()",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists-3/#propdef-counter-reset",
servo_restyle_damage="rebuild_and_reflow",
)}
|
servo_restyle_damage="rebuild_and_reflow",
)}
|
random_line_split
|
20.rs
|
/* Problem 20: Factorial digit sum
*
* n! means n × (n − 1) ×... × 3 × 2 × 1
*
* For example, 10! = 10 × 9 ×... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100! */
use num::bigint::{BigUint, ToBigUint};
use num::One;
fn main() {
let strnum = factorial(100).to_string();
let result = strnum.chars().fold(0, |digit, sum| digit + to_i(sum));
println!("{}", result);
}
fn factorial(n: u32) -> BigUint {
let mut result: BigUint = One::one();
let mut remaining: u32 = n;
while remaining > 0 {
result = result * remaining.to_biguint().unwrap();
remaining -= 1;
}
result
}
fn to_i(chr: ch
|
-> u32 {
chr.to_digit(10).unwrap()
}
|
ar)
|
identifier_name
|
20.rs
|
/* Problem 20: Factorial digit sum
*
* n! means n × (n − 1) ×... × 3 × 2 × 1
*
* For example, 10! = 10 × 9 ×... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100! */
use num::bigint::{BigUint, ToBigUint};
use num::One;
fn main() {
let strnum = factorial(100).to_string();
let result = strnum.chars().fold(0, |digit, sum| digit + to_i(sum));
println!("{}", result);
}
fn factorial(n: u32) -> BigUint {
|
remaining -= 1;
}
result
}
fn to_i(chr: char) -> u32 {
chr.to_digit(10).unwrap()
}
|
let mut result: BigUint = One::one();
let mut remaining: u32 = n;
while remaining > 0 {
result = result * remaining.to_biguint().unwrap();
|
random_line_split
|
20.rs
|
/* Problem 20: Factorial digit sum
*
* n! means n × (n − 1) ×... × 3 × 2 × 1
*
* For example, 10! = 10 × 9 ×... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100! */
use num::bigint::{BigUint, ToBigUint};
use num::One;
fn main() {
let st
|
al(n: u32) -> BigUint {
let mut result: BigUint = One::one();
let mut remaining: u32 = n;
while remaining > 0 {
result = result * remaining.to_biguint().unwrap();
remaining -= 1;
}
result
}
fn to_i(chr: char) -> u32 {
chr.to_digit(10).unwrap()
}
|
rnum = factorial(100).to_string();
let result = strnum.chars().fold(0, |digit, sum| digit + to_i(sum));
println!("{}", result);
}
fn factori
|
identifier_body
|
issue-32995.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.
#![allow(unused)]
fn main() {
let x: usize() = 1;
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let b: ::std::boxed()::Box<_> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::()::from_utf8(b"foo").unwrap();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::from_utf8::()(b"foo").unwrap();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let o : Box<::std::marker()::Send> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let o : Box<Send + ::std::marker()::Sync> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
|
fn foo<X:Default>() {
let d : X() = Default::default();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
}
|
}
|
random_line_split
|
issue-32995.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.
#![allow(unused)]
fn main()
|
let o : Box<Send + ::std::marker()::Sync> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
}
fn foo<X:Default>() {
let d : X() = Default::default();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
}
|
{
let x: usize() = 1;
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let b: ::std::boxed()::Box<_> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::()::from_utf8(b"foo").unwrap();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::from_utf8::()(b"foo").unwrap();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let o : Box<::std::marker()::Send> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
|
identifier_body
|
issue-32995.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.
#![allow(unused)]
fn
|
() {
let x: usize() = 1;
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let b: ::std::boxed()::Box<_> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::()::from_utf8(b"foo").unwrap();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let p = ::std::str::from_utf8::()(b"foo").unwrap();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let o : Box<::std::marker()::Send> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
let o : Box<Send + ::std::marker()::Sync> = Box::new(1);
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
}
fn foo<X:Default>() {
let d : X() = Default::default();
//~^ ERROR parenthesized parameters may only be used with a trait
//~| WARN previously accepted
}
|
main
|
identifier_name
|
lib.rs
|
//! Compile-time generated maps and sets.
//!
//! The `phf::Map` and `phf::Set` types have roughly comparable performance to
//! a standard hash table, but can be generated as compile-time static values.
//!
//! # Usage
//!
//! If the `macros` Cargo feature is enabled, the `phf_map`, `phf_set`,
//! `phf_ordered_map`, and `phf_ordered_set` macros can be used to construct
//! the PHF type. This method can be used with a stable compiler
//! (`rustc` version 1.30+)
//!
//! ```toml
//! [dependencies]
//! phf = { version = "0.7.24", features = ["macros"] }
//! ```
//!
//! ```
//! use phf::{phf_map, phf_set};
//!
//! static MY_MAP: phf::Map<&'static str, u32> = phf_map! {
//! "hello" => 1,
//! "world" => 2,
//! };
//!
//! static MY_SET: phf::Set<&'static str> = phf_set! {
//! "hello world",
//! "hola mundo",
//! };
//!
//! fn main() {
//! assert_eq!(MY_MAP["hello"], 1);
//! assert!(MY_SET.contains("hello world"));
//! }
//! ```
//!
//! (Alternatively, you can use the phf_codegen crate to generate PHF datatypes
//! in a build script)
#![doc(html_root_url="https://docs.rs/phf/0.7")]
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std as core;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`Map`].
///
/// Requires the `"macros"` feature.
///
/// # Example
///
/// ```rust,edition2018
/// use ::phf::{phf_map, Map};
///
/// static MY_MAP: Map<&'static str, u32> = phf_map! {
/// "hello" => 1,
/// "world" => 2,
/// };
///
/// fn main () {
/// assert_eq!(MY_MAP["hello"], 1);
/// }
/// ```
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros:: phf_map;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`OrderedMap`].
///
/// Requires the `"macros"` feature. Same usage as [`phf_map`]`!`.
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros::phf_ordered_map;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`Set`].
///
/// Requires the `"macros"` feature.
///
/// # Example
///
/// ```rust,edition2018
/// use ::phf::{phf_set, Set};
///
/// static MY_SET: Set<&'static str> = phf_set! {
/// "hello world",
/// "hola mundo",
/// };
///
/// fn main ()
/// {
/// assert!(MY_SET.contains("hello world"));
/// }
/// ```
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros::phf_set;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`OrderedSet`].
///
/// Requires the `"macros"` feature. Same usage as [`phf_set`]`!`.
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros::phf_ordered_set;
use core::ops::Deref;
|
#[doc(inline)]
pub use self::map::Map;
#[doc(inline)]
pub use self::set::Set;
#[doc(inline)]
pub use self::ordered_map::OrderedMap;
#[doc(inline)]
pub use self::ordered_set::OrderedSet;
pub mod map;
pub mod set;
pub mod ordered_map;
pub mod ordered_set;
// WARNING: this is not considered part of phf's public API and is subject to
// change at any time.
//
// Basically Cow, but with the Owned version conditionally compiled
#[doc(hidden)]
pub enum Slice<T:'static> {
Static(&'static [T]),
#[cfg(feature = "std")]
Dynamic(Vec<T>),
}
impl<T> Deref for Slice<T> {
type Target = [T];
fn deref(&self) -> &[T] {
match *self {
Slice::Static(t) => t,
#[cfg(feature = "std")]
Slice::Dynamic(ref t) => t,
}
}
}
|
pub use phf_shared::PhfHash;
|
random_line_split
|
lib.rs
|
//! Compile-time generated maps and sets.
//!
//! The `phf::Map` and `phf::Set` types have roughly comparable performance to
//! a standard hash table, but can be generated as compile-time static values.
//!
//! # Usage
//!
//! If the `macros` Cargo feature is enabled, the `phf_map`, `phf_set`,
//! `phf_ordered_map`, and `phf_ordered_set` macros can be used to construct
//! the PHF type. This method can be used with a stable compiler
//! (`rustc` version 1.30+)
//!
//! ```toml
//! [dependencies]
//! phf = { version = "0.7.24", features = ["macros"] }
//! ```
//!
//! ```
//! use phf::{phf_map, phf_set};
//!
//! static MY_MAP: phf::Map<&'static str, u32> = phf_map! {
//! "hello" => 1,
//! "world" => 2,
//! };
//!
//! static MY_SET: phf::Set<&'static str> = phf_set! {
//! "hello world",
//! "hola mundo",
//! };
//!
//! fn main() {
//! assert_eq!(MY_MAP["hello"], 1);
//! assert!(MY_SET.contains("hello world"));
//! }
//! ```
//!
//! (Alternatively, you can use the phf_codegen crate to generate PHF datatypes
//! in a build script)
#![doc(html_root_url="https://docs.rs/phf/0.7")]
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std as core;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`Map`].
///
/// Requires the `"macros"` feature.
///
/// # Example
///
/// ```rust,edition2018
/// use ::phf::{phf_map, Map};
///
/// static MY_MAP: Map<&'static str, u32> = phf_map! {
/// "hello" => 1,
/// "world" => 2,
/// };
///
/// fn main () {
/// assert_eq!(MY_MAP["hello"], 1);
/// }
/// ```
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros:: phf_map;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`OrderedMap`].
///
/// Requires the `"macros"` feature. Same usage as [`phf_map`]`!`.
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros::phf_ordered_map;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`Set`].
///
/// Requires the `"macros"` feature.
///
/// # Example
///
/// ```rust,edition2018
/// use ::phf::{phf_set, Set};
///
/// static MY_SET: Set<&'static str> = phf_set! {
/// "hello world",
/// "hola mundo",
/// };
///
/// fn main ()
/// {
/// assert!(MY_SET.contains("hello world"));
/// }
/// ```
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros::phf_set;
#[cfg(feature = "macros")]
/// Macro to create a `static` (compile-time) [`OrderedSet`].
///
/// Requires the `"macros"` feature. Same usage as [`phf_set`]`!`.
#[::proc_macro_hack::proc_macro_hack]
pub use phf_macros::phf_ordered_set;
use core::ops::Deref;
pub use phf_shared::PhfHash;
#[doc(inline)]
pub use self::map::Map;
#[doc(inline)]
pub use self::set::Set;
#[doc(inline)]
pub use self::ordered_map::OrderedMap;
#[doc(inline)]
pub use self::ordered_set::OrderedSet;
pub mod map;
pub mod set;
pub mod ordered_map;
pub mod ordered_set;
// WARNING: this is not considered part of phf's public API and is subject to
// change at any time.
//
// Basically Cow, but with the Owned version conditionally compiled
#[doc(hidden)]
pub enum Slice<T:'static> {
Static(&'static [T]),
#[cfg(feature = "std")]
Dynamic(Vec<T>),
}
impl<T> Deref for Slice<T> {
type Target = [T];
fn
|
(&self) -> &[T] {
match *self {
Slice::Static(t) => t,
#[cfg(feature = "std")]
Slice::Dynamic(ref t) => t,
}
}
}
|
deref
|
identifier_name
|
mod.rs
|
pub use self::{
bit_board::BitBoard,
board::Board,
player::{AiPlayer, PlayerKind},
};
mod bit_board;
mod board;
mod multi_direction;
mod player;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Point(pub u32, pub u32);
impl Point {
fn from_offset(off: u32, size: Size) -> Point {
Point(off % size.0, off / size.0)
}
fn offset(self, size: Size) -> u32 {
self.0 + size.0 * self.1
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Size(pub u32, pub u32);
pub const MIN_SIZE: u32 = 2;
pub const MAX_SIZE: u32 = 8;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Side {
Black,
White,
}
impl Side {
pub fn flip(self) -> Side {
match self {
Side::Black => Side::White,
|
Side::White => Side::Black,
}
}
}
|
random_line_split
|
|
mod.rs
|
pub use self::{
bit_board::BitBoard,
board::Board,
player::{AiPlayer, PlayerKind},
};
mod bit_board;
mod board;
mod multi_direction;
mod player;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Point(pub u32, pub u32);
impl Point {
fn from_offset(off: u32, size: Size) -> Point {
Point(off % size.0, off / size.0)
}
fn offset(self, size: Size) -> u32 {
self.0 + size.0 * self.1
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Size(pub u32, pub u32);
pub const MIN_SIZE: u32 = 2;
pub const MAX_SIZE: u32 = 8;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum
|
{
Black,
White,
}
impl Side {
pub fn flip(self) -> Side {
match self {
Side::Black => Side::White,
Side::White => Side::Black,
}
}
}
|
Side
|
identifier_name
|
types.rs
|
//! Holmes Language Types
//!
//! The types defined in this module are used to define the parts of the Holmes
//! language itself, and are used for writing rules, facts, etc.
use pg::dyn::{Type, Value};
/// A `Predicate` is a name combined with a list of typed slots, e.g.
///
/// ```c
/// foo(uint64, string)
/// ```
///
/// would be represented as
///
/// ```
/// use holmes::pg::dyn::types;
/// use holmes::engine::types::{Predicate, Field};
/// use std::sync::Arc;
/// Predicate {
/// name: "foo".to_string(),
/// description: None,
/// fields: vec![Field {
/// name: None,
/// description: None,
/// type_: Arc::new(types::UInt64)
/// }, Field {
/// name: None,
/// description: None,
/// type_: Arc::new(types::String)
/// }]
/// };
/// ```
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Predicate {
/// Predicate Name
pub name: String,
/// Description of what it means for this predicate to be true.
/// Purely documentation, not mechanical
pub description: Option<String>,
/// Predicate fields
pub fields: Vec<Field>,
}
/// Field for use in a predicate
/// The name is for use in selective matching or unordered definition,
/// and the description is to improve readability of code and comprehension of
/// results.
/// The `Type` is the only required component of a field, as it defines how to
/// actually interact with the field.
#[derive(Clone, Debug, Hash, Eq)]
pub struct Field {
/// Name of field, for use in matching and instantiating predicates
pub name: Option<String>,
/// Description of the field, purely documentation, not mechanical
pub description: Option<String>,
/// Type of the predicate, explaining how to store and retrieve
/// information from the `FactDB`
pub type_: Type,
}
// Manually implement PartialEq to work around rustc #[derive(PartialEq)] bug
// https://github.com/rust-lang/rust/issues/39128
impl PartialEq for Field {
fn eq(&self, other: &Self) -> bool {
(self.name == other.name) && (self.description == other.description) &&
(self.type_.eq(&other.type_))
}
}
/// A `Fact` is a particular filling of a `Predicate`'s slots such that it is
/// considered true.
///
/// Following the `Predicate` example,
///
/// ```c
/// foo(3, "argblarg")
/// ```
///
/// would be constructed as
///
/// ```
/// use holmes::pg::dyn::values::ToValue;
/// use holmes::engine::types::Fact;
/// Fact {
/// pred_name : "foo".to_string(),
/// args : vec![3.to_value(), "argblarg".to_value()]
/// };
/// ```
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Fact {
/// Predicate name
pub pred_name: String,
/// Slot values which make the predicate true
pub args: Vec<Value>,
}
/// `Var` is placeholder type for the representation of a variable in the
/// Holmes langauge. At the moment, it is just an index, and so is
/// transparently an integer, but this behavior should not be relied upon, as
/// it is likely that in the future it will carry other information (name,
/// type, etc.) for improved debugging.
pub type Var = usize;
/// A `MatchExpr` represents the possible things that could show up in a slot
/// in the body of a rule
#[derive(Clone, Debug, Hash, Eq)]
pub enum MatchExpr {
/// We do not care about the contents of the slot
Unbound,
/// Bind the contents of the slot to this variable if undefined, otherwise
/// only match if the definition matches the contents of the slot
Var(Var),
/// Only match if the contents of the slot match the provided value
Const(Value),
}
// This is a temporary impl. PartialEq should be derivable, but a compiler bug
// is preventing it from being derived
impl PartialEq for MatchExpr {
fn
|
(&self, other: &MatchExpr) -> bool {
use self::MatchExpr::*;
match (self, other) {
(&Unbound, &Unbound) => true,
(&Var(x), &Var(y)) => x == y,
(&Const(ref v), &Const(ref vv)) => v == vv,
_ => false,
}
}
}
/// A `BindExpr` is what appears on the left hand of the assignment in a
/// Holmes rule where clause.
/// It describes how to extend or limit the answer set based on the value
/// on the right side.
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub enum BindExpr {
/// Use the same filtering/binding rules as in a match expression
Normal(MatchExpr),
/// Treat the value as a tuple, and run each inner bind expression on the
/// corresponding tuple element
Destructure(Vec<BindExpr>),
/// Treat the value as a list, and extend the answer set with a new
/// possibility for each element in the list, binding to each list element
/// with the provided `BindExpr`
/// This is simlar the list monadic bind.
Iterate(Box<BindExpr>),
}
/// A `Clause` to be matched against, as you would see in the body of a datalog
/// rule.
///
/// Continuing with our running example,
///
/// ```c
/// foo(_, x)
/// ```
///
/// (match all `foo`s, bind the second slot to x) would be constructed as
///
/// ```
/// use holmes::engine::types::{Clause,MatchExpr};
/// Clause {
/// pred_name : "foo".to_string(),
/// args : vec![MatchExpr::Unbound, MatchExpr::Var(0)]
/// };
/// ```
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Clause {
/// Name of the predicate to match against
pub pred_name: String,
/// List of how to restrict or bind each slot
pub args: Vec<MatchExpr>,
}
/// `Expr` represents the right hand side of the where clause sublanguage of
/// Holmes.
#[derive(Clone, Debug, Hash, Eq)]
pub enum Expr {
/// Evaluates to whatever the inner variable is defined to.
Var(Var),
/// Evaluates to the value provided directly.
Val(Value),
/// Applies the function in the registry named the first argument to the
/// list of arguments provided as the second
App(String, Vec<Expr>),
}
// As per prvious, this is only needed due to a compiler bug. In the long
// run this impl should be derived
impl PartialEq for Expr {
fn eq(&self, other: &Expr) -> bool {
use self::Expr::*;
match (self, other) {
(&Var(ref x), &Var(ref y)) => x == y,
(&Val(ref x), &Val(ref y)) => x == y,
(&App(ref s0, ref ex0), &App(ref s1, ref ex1)) => (s0 == s1) && (ex0 == ex1),
_ => false,
}
}
}
/// A `Rule` represents a complete inference technique in the Holmes system
/// If the `body` clauses match, the `wheres` clauses are run on the answer
/// set, producing a new answer set, and the `head` clause is instantiated
/// at that answer set and inserted into the database.
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Rule {
/// Identifier for the rule
pub name: String,
/// Template for the facts this rule will output
pub head: Clause,
/// Datalog body to search the database with
pub body: Vec<Clause>,
/// Embedded language to call native functions on the results
pub wheres: Vec<WhereClause>,
}
/// A `WhereClause` is a single assignment in the Holmes sublanguage.
/// The right hand side is evaluated, and bound to the left hand side,
/// producing a new answer set.
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct WhereClause {
/// Instructions on how to assign the evaluated rhs
pub lhs: BindExpr,
/// The expression to evaluate
pub rhs: Expr,
}
/// A `Func` is the wrapper around dynamically typed functions which may be
/// registered with the engine to provide extralogical functionality.
pub struct Func {
/// The type of the `Value` the function expects to receive as input
pub input_type: Type,
/// The type of the `Value` the function will produce as output
pub output_type: Type,
/// The function itself
pub run: Box<Fn(Value) -> Value>,
}
|
eq
|
identifier_name
|
types.rs
|
//! Holmes Language Types
//!
//! The types defined in this module are used to define the parts of the Holmes
//! language itself, and are used for writing rules, facts, etc.
use pg::dyn::{Type, Value};
/// A `Predicate` is a name combined with a list of typed slots, e.g.
///
/// ```c
/// foo(uint64, string)
/// ```
///
/// would be represented as
///
|
/// use std::sync::Arc;
/// Predicate {
/// name: "foo".to_string(),
/// description: None,
/// fields: vec![Field {
/// name: None,
/// description: None,
/// type_: Arc::new(types::UInt64)
/// }, Field {
/// name: None,
/// description: None,
/// type_: Arc::new(types::String)
/// }]
/// };
/// ```
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Predicate {
/// Predicate Name
pub name: String,
/// Description of what it means for this predicate to be true.
/// Purely documentation, not mechanical
pub description: Option<String>,
/// Predicate fields
pub fields: Vec<Field>,
}
/// Field for use in a predicate
/// The name is for use in selective matching or unordered definition,
/// and the description is to improve readability of code and comprehension of
/// results.
/// The `Type` is the only required component of a field, as it defines how to
/// actually interact with the field.
#[derive(Clone, Debug, Hash, Eq)]
pub struct Field {
/// Name of field, for use in matching and instantiating predicates
pub name: Option<String>,
/// Description of the field, purely documentation, not mechanical
pub description: Option<String>,
/// Type of the predicate, explaining how to store and retrieve
/// information from the `FactDB`
pub type_: Type,
}
// Manually implement PartialEq to work around rustc #[derive(PartialEq)] bug
// https://github.com/rust-lang/rust/issues/39128
impl PartialEq for Field {
fn eq(&self, other: &Self) -> bool {
(self.name == other.name) && (self.description == other.description) &&
(self.type_.eq(&other.type_))
}
}
/// A `Fact` is a particular filling of a `Predicate`'s slots such that it is
/// considered true.
///
/// Following the `Predicate` example,
///
/// ```c
/// foo(3, "argblarg")
/// ```
///
/// would be constructed as
///
/// ```
/// use holmes::pg::dyn::values::ToValue;
/// use holmes::engine::types::Fact;
/// Fact {
/// pred_name : "foo".to_string(),
/// args : vec![3.to_value(), "argblarg".to_value()]
/// };
/// ```
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Fact {
/// Predicate name
pub pred_name: String,
/// Slot values which make the predicate true
pub args: Vec<Value>,
}
/// `Var` is placeholder type for the representation of a variable in the
/// Holmes langauge. At the moment, it is just an index, and so is
/// transparently an integer, but this behavior should not be relied upon, as
/// it is likely that in the future it will carry other information (name,
/// type, etc.) for improved debugging.
pub type Var = usize;
/// A `MatchExpr` represents the possible things that could show up in a slot
/// in the body of a rule
#[derive(Clone, Debug, Hash, Eq)]
pub enum MatchExpr {
/// We do not care about the contents of the slot
Unbound,
/// Bind the contents of the slot to this variable if undefined, otherwise
/// only match if the definition matches the contents of the slot
Var(Var),
/// Only match if the contents of the slot match the provided value
Const(Value),
}
// This is a temporary impl. PartialEq should be derivable, but a compiler bug
// is preventing it from being derived
impl PartialEq for MatchExpr {
fn eq(&self, other: &MatchExpr) -> bool {
use self::MatchExpr::*;
match (self, other) {
(&Unbound, &Unbound) => true,
(&Var(x), &Var(y)) => x == y,
(&Const(ref v), &Const(ref vv)) => v == vv,
_ => false,
}
}
}
/// A `BindExpr` is what appears on the left hand of the assignment in a
/// Holmes rule where clause.
/// It describes how to extend or limit the answer set based on the value
/// on the right side.
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub enum BindExpr {
/// Use the same filtering/binding rules as in a match expression
Normal(MatchExpr),
/// Treat the value as a tuple, and run each inner bind expression on the
/// corresponding tuple element
Destructure(Vec<BindExpr>),
/// Treat the value as a list, and extend the answer set with a new
/// possibility for each element in the list, binding to each list element
/// with the provided `BindExpr`
/// This is simlar the list monadic bind.
Iterate(Box<BindExpr>),
}
/// A `Clause` to be matched against, as you would see in the body of a datalog
/// rule.
///
/// Continuing with our running example,
///
/// ```c
/// foo(_, x)
/// ```
///
/// (match all `foo`s, bind the second slot to x) would be constructed as
///
/// ```
/// use holmes::engine::types::{Clause,MatchExpr};
/// Clause {
/// pred_name : "foo".to_string(),
/// args : vec![MatchExpr::Unbound, MatchExpr::Var(0)]
/// };
/// ```
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Clause {
/// Name of the predicate to match against
pub pred_name: String,
/// List of how to restrict or bind each slot
pub args: Vec<MatchExpr>,
}
/// `Expr` represents the right hand side of the where clause sublanguage of
/// Holmes.
#[derive(Clone, Debug, Hash, Eq)]
pub enum Expr {
/// Evaluates to whatever the inner variable is defined to.
Var(Var),
/// Evaluates to the value provided directly.
Val(Value),
/// Applies the function in the registry named the first argument to the
/// list of arguments provided as the second
App(String, Vec<Expr>),
}
// As per prvious, this is only needed due to a compiler bug. In the long
// run this impl should be derived
impl PartialEq for Expr {
fn eq(&self, other: &Expr) -> bool {
use self::Expr::*;
match (self, other) {
(&Var(ref x), &Var(ref y)) => x == y,
(&Val(ref x), &Val(ref y)) => x == y,
(&App(ref s0, ref ex0), &App(ref s1, ref ex1)) => (s0 == s1) && (ex0 == ex1),
_ => false,
}
}
}
/// A `Rule` represents a complete inference technique in the Holmes system
/// If the `body` clauses match, the `wheres` clauses are run on the answer
/// set, producing a new answer set, and the `head` clause is instantiated
/// at that answer set and inserted into the database.
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct Rule {
/// Identifier for the rule
pub name: String,
/// Template for the facts this rule will output
pub head: Clause,
/// Datalog body to search the database with
pub body: Vec<Clause>,
/// Embedded language to call native functions on the results
pub wheres: Vec<WhereClause>,
}
/// A `WhereClause` is a single assignment in the Holmes sublanguage.
/// The right hand side is evaluated, and bound to the left hand side,
/// producing a new answer set.
#[derive(PartialEq, Clone, Debug, Hash, Eq)]
pub struct WhereClause {
/// Instructions on how to assign the evaluated rhs
pub lhs: BindExpr,
/// The expression to evaluate
pub rhs: Expr,
}
/// A `Func` is the wrapper around dynamically typed functions which may be
/// registered with the engine to provide extralogical functionality.
pub struct Func {
/// The type of the `Value` the function expects to receive as input
pub input_type: Type,
/// The type of the `Value` the function will produce as output
pub output_type: Type,
/// The function itself
pub run: Box<Fn(Value) -> Value>,
}
|
/// ```
/// use holmes::pg::dyn::types;
/// use holmes::engine::types::{Predicate, Field};
|
random_line_split
|
lib.rs
|
#[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn new() -> PhiFailureDetector {
Self::default()
}
pub fn min_stddev(self, min_stddev: f64) -> PhiFailureDetector {
assert!(min_stddev > 0.0, "min_stddev must be > 0.0");
PhiFailureDetector { min_stddev,..self }
}
pub fn history_size(self, count: usize) -> PhiFailureDetector {
assert!(count > 0, "history_size must > 0");
PhiFailureDetector {
history_size: count,
..self
}
}
pub fn heartbeat(&mut self, t: u64) {
match &mut self.prev_heartbeat {
prev @ &mut None => {
*prev = Some(t);
}
&mut Some(ref mut prev) => {
if t < *prev {
return;
};
let delta = t - *prev;
self.buf.push_back(delta);
*prev = t;
if self.buf.len() > self.history_size {
let _ = self.buf.pop_front();
}
}
}
}
/// def ϕ(Tnow ) = − log10(Plater (Tnow − Tlast))
pub fn phi(&self, now: u64) -> f64 {
match &self.prev_heartbeat {
Some(prev_time) if now > *prev_time => {
trace!(
"now:{} - prev_heartbeat:{} = {:?}",
now,
prev_time,
now - prev_time
);
let p_later = self.p_later(now - prev_time);
-p_later.log10()
}
Some(prev_time) => {
trace!("now:{} <= prev_heartbeat:{}", now, prev_time);
0.0
}
|
/// Returns the time t (within epsilon) at which phi will be >= val.
pub fn next_crossing_at(&self, now: u64, threshold: f64) -> u64 {
let phappened = 1.0 - (10.0f64).powf(-threshold);
let x = phappened.norm_inv();
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let diff = x * stddev + mean;
let then = now + diff.ceil() as u64;
trace!(
"threshold:{}; phappened:{}; x:{}; mean:{}; stddev:{}; diff:{}; then:{}",
threshold,
phappened,
x,
mean,
stddev,
diff,
then
);
then
}
fn p_later(&self, diff: u64) -> f64 {
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let x = (diff as f64 - mean) / stddev;
// let cdf = 0.5*(1.0+ (x/(2.0f64).sqrt()).erf())
let p = 1.0 - x.norm();
trace!(
"diff:{:e}; mean:{:e}; stddev:{:e} x:{:e}; p_later:{:e}",
diff as f64,
mean,
stddev,
x,
p
);
// We want to avoid returning zero, as we want the logarithm of the probability.
// And the log of zero is meaningless.
if p < f64::MIN_POSITIVE {
f64::MIN_POSITIVE
} else {
p
}
}
}
impl Default for PhiFailureDetector {
fn default() -> Self {
PhiFailureDetector {
min_stddev: 1.0,
history_size: 10,
buf: VecDeque::new(),
prev_heartbeat: None,
}
}
}
#[cfg(test)]
mod tests {
use super::PhiFailureDetector;
use rand::thread_rng;
use rand_distr::Distribution;
use rand_distr::LogNormal;
#[test]
fn should_fail_when_no_heartbeats() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new();
for t in 0..100 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
for t in 100..110 {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for &t in &[110, 200, 300] {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
assert!(phi > 1.0, "t:{:?}; phi:{:?} > 1.0", t, phi);
}
}
#[test]
fn should_recover() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new().history_size(3);
for t in 0..10 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for t in 20..30 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
}
#[test]
fn should_estimate_threshold_times() {
env_logger::try_init().unwrap_or_default();
let epsilon = 2;
let mut detector = PhiFailureDetector::new().history_size(3);
let mut t = 0;
for n in 0u64..10 {
let dist = LogNormal::new(10.0, 100.0).expect("lognormal");
let diff = dist.sample(&mut thread_rng());
t = n * 1000;
trace!(
"at:{:?}, diff:{:e}; phi:{:?}; det: {:?}",
t,
diff,
detector.phi(t),
detector
);
detector.heartbeat(t);
}
// Estimate the point at which
let threshold = 1.0;
let est_1 = detector.next_crossing_at(t, threshold);
let pre = detector.phi(est_1 - epsilon);
let at = detector.phi(est_1);
assert!(
pre < threshold && at >= threshold,
"phi({}):{:?} < {:?} && phi({}):{:?} >= {:?}",
est_1 - epsilon,
pre,
threshold,
est_1,
at,
threshold
);
}
}
|
None => 0.0,
}
}
|
random_line_split
|
lib.rs
|
#[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn
|
() -> PhiFailureDetector {
Self::default()
}
pub fn min_stddev(self, min_stddev: f64) -> PhiFailureDetector {
assert!(min_stddev > 0.0, "min_stddev must be > 0.0");
PhiFailureDetector { min_stddev,..self }
}
pub fn history_size(self, count: usize) -> PhiFailureDetector {
assert!(count > 0, "history_size must > 0");
PhiFailureDetector {
history_size: count,
..self
}
}
pub fn heartbeat(&mut self, t: u64) {
match &mut self.prev_heartbeat {
prev @ &mut None => {
*prev = Some(t);
}
&mut Some(ref mut prev) => {
if t < *prev {
return;
};
let delta = t - *prev;
self.buf.push_back(delta);
*prev = t;
if self.buf.len() > self.history_size {
let _ = self.buf.pop_front();
}
}
}
}
/// def ϕ(Tnow ) = − log10(Plater (Tnow − Tlast))
pub fn phi(&self, now: u64) -> f64 {
match &self.prev_heartbeat {
Some(prev_time) if now > *prev_time => {
trace!(
"now:{} - prev_heartbeat:{} = {:?}",
now,
prev_time,
now - prev_time
);
let p_later = self.p_later(now - prev_time);
-p_later.log10()
}
Some(prev_time) => {
trace!("now:{} <= prev_heartbeat:{}", now, prev_time);
0.0
}
None => 0.0,
}
}
/// Returns the time t (within epsilon) at which phi will be >= val.
pub fn next_crossing_at(&self, now: u64, threshold: f64) -> u64 {
let phappened = 1.0 - (10.0f64).powf(-threshold);
let x = phappened.norm_inv();
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let diff = x * stddev + mean;
let then = now + diff.ceil() as u64;
trace!(
"threshold:{}; phappened:{}; x:{}; mean:{}; stddev:{}; diff:{}; then:{}",
threshold,
phappened,
x,
mean,
stddev,
diff,
then
);
then
}
fn p_later(&self, diff: u64) -> f64 {
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let x = (diff as f64 - mean) / stddev;
// let cdf = 0.5*(1.0+ (x/(2.0f64).sqrt()).erf())
let p = 1.0 - x.norm();
trace!(
"diff:{:e}; mean:{:e}; stddev:{:e} x:{:e}; p_later:{:e}",
diff as f64,
mean,
stddev,
x,
p
);
// We want to avoid returning zero, as we want the logarithm of the probability.
// And the log of zero is meaningless.
if p < f64::MIN_POSITIVE {
f64::MIN_POSITIVE
} else {
p
}
}
}
impl Default for PhiFailureDetector {
fn default() -> Self {
PhiFailureDetector {
min_stddev: 1.0,
history_size: 10,
buf: VecDeque::new(),
prev_heartbeat: None,
}
}
}
#[cfg(test)]
mod tests {
use super::PhiFailureDetector;
use rand::thread_rng;
use rand_distr::Distribution;
use rand_distr::LogNormal;
#[test]
fn should_fail_when_no_heartbeats() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new();
for t in 0..100 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
for t in 100..110 {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for &t in &[110, 200, 300] {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
assert!(phi > 1.0, "t:{:?}; phi:{:?} > 1.0", t, phi);
}
}
#[test]
fn should_recover() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new().history_size(3);
for t in 0..10 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for t in 20..30 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
}
#[test]
fn should_estimate_threshold_times() {
env_logger::try_init().unwrap_or_default();
let epsilon = 2;
let mut detector = PhiFailureDetector::new().history_size(3);
let mut t = 0;
for n in 0u64..10 {
let dist = LogNormal::new(10.0, 100.0).expect("lognormal");
let diff = dist.sample(&mut thread_rng());
t = n * 1000;
trace!(
"at:{:?}, diff:{:e}; phi:{:?}; det: {:?}",
t,
diff,
detector.phi(t),
detector
);
detector.heartbeat(t);
}
// Estimate the point at which
let threshold = 1.0;
let est_1 = detector.next_crossing_at(t, threshold);
let pre = detector.phi(est_1 - epsilon);
let at = detector.phi(est_1);
assert!(
pre < threshold && at >= threshold,
"phi({}):{:?} < {:?} && phi({}):{:?} >= {:?}",
est_1 - epsilon,
pre,
threshold,
est_1,
at,
threshold
);
}
}
|
new
|
identifier_name
|
lib.rs
|
#[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn new() -> PhiFailureDetector {
Self::default()
}
pub fn min_stddev(self, min_stddev: f64) -> PhiFailureDetector {
assert!(min_stddev > 0.0, "min_stddev must be > 0.0");
PhiFailureDetector { min_stddev,..self }
}
pub fn history_size(self, count: usize) -> PhiFailureDetector {
assert!(count > 0, "history_size must > 0");
PhiFailureDetector {
history_size: count,
..self
}
}
pub fn heartbeat(&mut self, t: u64) {
match &mut self.prev_heartbeat {
prev @ &mut None => {
*prev = Some(t);
}
&mut Some(ref mut prev) =>
|
}
}
/// def ϕ(Tnow ) = − log10(Plater (Tnow − Tlast))
pub fn phi(&self, now: u64) -> f64 {
match &self.prev_heartbeat {
Some(prev_time) if now > *prev_time => {
trace!(
"now:{} - prev_heartbeat:{} = {:?}",
now,
prev_time,
now - prev_time
);
let p_later = self.p_later(now - prev_time);
-p_later.log10()
}
Some(prev_time) => {
trace!("now:{} <= prev_heartbeat:{}", now, prev_time);
0.0
}
None => 0.0,
}
}
/// Returns the time t (within epsilon) at which phi will be >= val.
pub fn next_crossing_at(&self, now: u64, threshold: f64) -> u64 {
let phappened = 1.0 - (10.0f64).powf(-threshold);
let x = phappened.norm_inv();
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let diff = x * stddev + mean;
let then = now + diff.ceil() as u64;
trace!(
"threshold:{}; phappened:{}; x:{}; mean:{}; stddev:{}; diff:{}; then:{}",
threshold,
phappened,
x,
mean,
stddev,
diff,
then
);
then
}
fn p_later(&self, diff: u64) -> f64 {
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let x = (diff as f64 - mean) / stddev;
// let cdf = 0.5*(1.0+ (x/(2.0f64).sqrt()).erf())
let p = 1.0 - x.norm();
trace!(
"diff:{:e}; mean:{:e}; stddev:{:e} x:{:e}; p_later:{:e}",
diff as f64,
mean,
stddev,
x,
p
);
// We want to avoid returning zero, as we want the logarithm of the probability.
// And the log of zero is meaningless.
if p < f64::MIN_POSITIVE {
f64::MIN_POSITIVE
} else {
p
}
}
}
impl Default for PhiFailureDetector {
fn default() -> Self {
PhiFailureDetector {
min_stddev: 1.0,
history_size: 10,
buf: VecDeque::new(),
prev_heartbeat: None,
}
}
}
#[cfg(test)]
mod tests {
use super::PhiFailureDetector;
use rand::thread_rng;
use rand_distr::Distribution;
use rand_distr::LogNormal;
#[test]
fn should_fail_when_no_heartbeats() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new();
for t in 0..100 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
for t in 100..110 {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for &t in &[110, 200, 300] {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
assert!(phi > 1.0, "t:{:?}; phi:{:?} > 1.0", t, phi);
}
}
#[test]
fn should_recover() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new().history_size(3);
for t in 0..10 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for t in 20..30 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
}
#[test]
fn should_estimate_threshold_times() {
env_logger::try_init().unwrap_or_default();
let epsilon = 2;
let mut detector = PhiFailureDetector::new().history_size(3);
let mut t = 0;
for n in 0u64..10 {
let dist = LogNormal::new(10.0, 100.0).expect("lognormal");
let diff = dist.sample(&mut thread_rng());
t = n * 1000;
trace!(
"at:{:?}, diff:{:e}; phi:{:?}; det: {:?}",
t,
diff,
detector.phi(t),
detector
);
detector.heartbeat(t);
}
// Estimate the point at which
let threshold = 1.0;
let est_1 = detector.next_crossing_at(t, threshold);
let pre = detector.phi(est_1 - epsilon);
let at = detector.phi(est_1);
assert!(
pre < threshold && at >= threshold,
"phi({}):{:?} < {:?} && phi({}):{:?} >= {:?}",
est_1 - epsilon,
pre,
threshold,
est_1,
at,
threshold
);
}
}
|
{
if t < *prev {
return;
};
let delta = t - *prev;
self.buf.push_back(delta);
*prev = t;
if self.buf.len() > self.history_size {
let _ = self.buf.pop_front();
}
}
|
conditional_block
|
lib.rs
|
#[macro_use]
extern crate log;
use special_fun::FloatSpecial;
use std::collections::VecDeque;
use std::f64;
#[derive(Clone, Debug)]
pub struct PhiFailureDetector {
min_stddev: f64,
history_size: usize,
buf: VecDeque<u64>,
prev_heartbeat: Option<u64>,
}
impl PhiFailureDetector {
pub fn new() -> PhiFailureDetector {
Self::default()
}
pub fn min_stddev(self, min_stddev: f64) -> PhiFailureDetector {
assert!(min_stddev > 0.0, "min_stddev must be > 0.0");
PhiFailureDetector { min_stddev,..self }
}
pub fn history_size(self, count: usize) -> PhiFailureDetector {
assert!(count > 0, "history_size must > 0");
PhiFailureDetector {
history_size: count,
..self
}
}
pub fn heartbeat(&mut self, t: u64) {
match &mut self.prev_heartbeat {
prev @ &mut None => {
*prev = Some(t);
}
&mut Some(ref mut prev) => {
if t < *prev {
return;
};
let delta = t - *prev;
self.buf.push_back(delta);
*prev = t;
if self.buf.len() > self.history_size {
let _ = self.buf.pop_front();
}
}
}
}
/// def ϕ(Tnow ) = − log10(Plater (Tnow − Tlast))
pub fn phi(&self, now: u64) -> f64 {
match &self.prev_heartbeat {
Some(prev_time) if now > *prev_time => {
trace!(
"now:{} - prev_heartbeat:{} = {:?}",
now,
prev_time,
now - prev_time
);
let p_later = self.p_later(now - prev_time);
-p_later.log10()
}
Some(prev_time) => {
trace!("now:{} <= prev_heartbeat:{}", now, prev_time);
0.0
}
None => 0.0,
}
}
/// Returns the time t (within epsilon) at which phi will be >= val.
pub fn next_crossing_at(&self, now: u64, threshold: f64) -> u64 {
let phappened = 1.0 - (10.0f64).powf(-threshold);
let x = phappened.norm_inv();
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let diff = x * stddev + mean;
let then = now + diff.ceil() as u64;
trace!(
"threshold:{}; phappened:{}; x:{}; mean:{}; stddev:{}; diff:{}; then:{}",
threshold,
phappened,
x,
mean,
stddev,
diff,
then
);
then
}
fn p_later(&self, diff: u64) -> f64 {
let mean = stats::mean(self.buf.iter().cloned());
let stddev = stats::stddev(self.buf.iter().cloned()).max(self.min_stddev);
let x = (diff as f64 - mean) / stddev;
// let cdf = 0.5*(1.0+ (x/(2.0f64).sqrt()).erf())
let p = 1.0 - x.norm();
trace!(
"diff:{:e}; mean:{:e}; stddev:{:e} x:{:e}; p_later:{:e}",
diff as f64,
mean,
stddev,
x,
p
);
// We want to avoid returning zero, as we want the logarithm of the probability.
// And the log of zero is meaningless.
if p < f64::MIN_POSITIVE {
f64::MIN_POSITIVE
} else {
p
}
}
}
impl Default for PhiFailureDetector {
fn default() -> Self {
PhiFailureDetector {
min_stddev: 1.0,
history_size: 10,
buf: VecDeque::new(),
prev_heartbeat: None,
}
}
}
#[cfg(test)]
mod tests {
use super::PhiFailureDetector;
use rand::thread_rng;
use rand_distr::Distribution;
use rand_distr::LogNormal;
#[test]
fn should_fail_when_no_heartbeats() {
|
}
#[test]
fn should_recover() {
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new().history_size(3);
for t in 0..10 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for t in 20..30 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
}
#[test]
fn should_estimate_threshold_times() {
env_logger::try_init().unwrap_or_default();
let epsilon = 2;
let mut detector = PhiFailureDetector::new().history_size(3);
let mut t = 0;
for n in 0u64..10 {
let dist = LogNormal::new(10.0, 100.0).expect("lognormal");
let diff = dist.sample(&mut thread_rng());
t = n * 1000;
trace!(
"at:{:?}, diff:{:e}; phi:{:?}; det: {:?}",
t,
diff,
detector.phi(t),
detector
);
detector.heartbeat(t);
}
// Estimate the point at which
let threshold = 1.0;
let est_1 = detector.next_crossing_at(t, threshold);
let pre = detector.phi(est_1 - epsilon);
let at = detector.phi(est_1);
assert!(
pre < threshold && at >= threshold,
"phi({}):{:?} < {:?} && phi({}):{:?} >= {:?}",
est_1 - epsilon,
pre,
threshold,
est_1,
at,
threshold
);
}
}
|
env_logger::try_init().unwrap_or_default();
let mut detector = PhiFailureDetector::new();
for t in 0..100 {
detector.heartbeat(t);
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
if t > 10 {
assert!(phi < 1.0);
}
}
for t in 100..110 {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
}
for &t in &[110, 200, 300] {
let phi = detector.phi(t);
trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector);
assert!(phi > 1.0, "t:{:?}; phi:{:?} > 1.0", t, phi);
}
|
identifier_body
|
latex.rs
|
use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xcolor}
\\usepackage{fancyvrb}
\\newcommand{\\VerbBar}{|}
\\newcommand{\\VERB}{\\Verb[commandchars=\\\\\\{\\}]}
\\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\\\\{\\}}
% Add ',fontsize=\\small' for more characters per line
\\newenvironment{Shaded}{}{}
";
impl Backend for LatexBackend {
fn configure(&mut self, _vars: &HashMap<~str, ~str>) -> Result<(), ~str> {
Ok(())
}
fn header(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_str(HEADER));
for (ty, color) in colors::get_colors().iter() {
try!(writeln!(w, "\\\\definecolor\\{{}\\}\\{HTML\\}\\{{}\\}", ty, color));
}
Ok(())
}
fn code_start(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_line("\\begin{Shaded}"));
try!(w.write_line("\\begin{Highlighting}[]"));
Ok(())
}
fn code_end(&mut self, w: &mut Writer) -> IoResult<()>
|
fn start(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if colors::get_types().contains(&ty.to_owned()) {
try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty));
}
if ty == "attribute" {
try!(w.write_str("#"));
}
}
self.contexts.push(ty.to_owned());
Ok(())
}
fn end(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if ty == "attribute" {
try!(w.write_str("]"));
}
if colors::get_types().contains(&ty.to_owned()) {
try!(w.write_str("}"));
}
}
self.contexts.pop();
Ok(())
}
fn text(&mut self, w: &mut Writer, text: &str) -> IoResult<()> {
fn escape_latex(text: &str) -> ~str {
let mut result = StrBuf::new();
let mut escape = false;
for c in text.chars() {
if escape {
result.push_str("\\textbackslash{");
}
if c == '{' || c == '}' {
result.push_char('\\');
}
if c == '\\' {
escape = true;
} else {
result.push_char(c);
}
if escape && c!= '\\' {
result.push_char('}');
escape = false;
}
}
result.into_owned()
}
fn escape_comment(text: &str, has_color: bool) -> ~str {
let mut result = StrBuf::new();
let mut first = true;
for line in text.lines() {
if!first {
result.push_str("\n");
}
if line.len() > 0 && has_color {
result.push_str("\\textcolor{comment}{");
}
result.push_str(line);
if line.len() > 0 && has_color {
result.push_str("}");
}
first = false;
}
let old_len = text.len();
let text = text.trim_right_chars('\n').to_owned();
let new_len = text.len();
range(0, old_len - new_len).advance(|_| {
result.push_char('\n');
true
});
result.into_owned()
}
let context = self.contexts.last().unwrap();
let has_color = colors::get_types().contains(context);
let context = context.as_slice();
let text = if context == "comment" {
escape_comment(text, has_color)
} else {
escape_latex(text)
};
try!(w.write_str(text));
Ok(())
}
}
|
{
try!(w.write_line("\\end{Highlighting}"));
try!(w.write_line("\\end{Shaded}"));
Ok(())
}
|
identifier_body
|
latex.rs
|
use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xcolor}
\\usepackage{fancyvrb}
\\newcommand{\\VerbBar}{|}
\\newcommand{\\VERB}{\\Verb[commandchars=\\\\\\{\\}]}
\\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\\\\{\\}}
% Add ',fontsize=\\small' for more characters per line
\\newenvironment{Shaded}{}{}
";
impl Backend for LatexBackend {
fn configure(&mut self, _vars: &HashMap<~str, ~str>) -> Result<(), ~str> {
Ok(())
}
fn header(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_str(HEADER));
for (ty, color) in colors::get_colors().iter() {
try!(writeln!(w, "\\\\definecolor\\{{}\\}\\{HTML\\}\\{{}\\}", ty, color));
}
Ok(())
}
fn code_start(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_line("\\begin{Shaded}"));
try!(w.write_line("\\begin{Highlighting}[]"));
Ok(())
}
fn code_end(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_line("\\end{Highlighting}"));
try!(w.write_line("\\end{Shaded}"));
Ok(())
}
fn
|
(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if colors::get_types().contains(&ty.to_owned()) {
try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty));
}
if ty == "attribute" {
try!(w.write_str("#"));
}
}
self.contexts.push(ty.to_owned());
Ok(())
}
fn end(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if ty == "attribute" {
try!(w.write_str("]"));
}
if colors::get_types().contains(&ty.to_owned()) {
try!(w.write_str("}"));
}
}
self.contexts.pop();
Ok(())
}
fn text(&mut self, w: &mut Writer, text: &str) -> IoResult<()> {
fn escape_latex(text: &str) -> ~str {
let mut result = StrBuf::new();
let mut escape = false;
for c in text.chars() {
if escape {
result.push_str("\\textbackslash{");
}
if c == '{' || c == '}' {
result.push_char('\\');
}
if c == '\\' {
escape = true;
} else {
result.push_char(c);
}
if escape && c!= '\\' {
result.push_char('}');
escape = false;
}
}
result.into_owned()
}
fn escape_comment(text: &str, has_color: bool) -> ~str {
let mut result = StrBuf::new();
let mut first = true;
for line in text.lines() {
if!first {
result.push_str("\n");
}
if line.len() > 0 && has_color {
result.push_str("\\textcolor{comment}{");
}
result.push_str(line);
if line.len() > 0 && has_color {
result.push_str("}");
}
first = false;
}
let old_len = text.len();
let text = text.trim_right_chars('\n').to_owned();
let new_len = text.len();
range(0, old_len - new_len).advance(|_| {
result.push_char('\n');
true
});
result.into_owned()
}
let context = self.contexts.last().unwrap();
let has_color = colors::get_types().contains(context);
let context = context.as_slice();
let text = if context == "comment" {
escape_comment(text, has_color)
} else {
escape_latex(text)
};
try!(w.write_str(text));
Ok(())
}
}
|
start
|
identifier_name
|
latex.rs
|
use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xcolor}
\\usepackage{fancyvrb}
\\newcommand{\\VerbBar}{|}
\\newcommand{\\VERB}{\\Verb[commandchars=\\\\\\{\\}]}
\\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\\\\{\\}}
% Add ',fontsize=\\small' for more characters per line
\\newenvironment{Shaded}{}{}
";
impl Backend for LatexBackend {
fn configure(&mut self, _vars: &HashMap<~str, ~str>) -> Result<(), ~str> {
Ok(())
}
fn header(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_str(HEADER));
for (ty, color) in colors::get_colors().iter() {
try!(writeln!(w, "\\\\definecolor\\{{}\\}\\{HTML\\}\\{{}\\}", ty, color));
}
Ok(())
}
fn code_start(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_line("\\begin{Shaded}"));
try!(w.write_line("\\begin{Highlighting}[]"));
Ok(())
}
fn code_end(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_line("\\end{Highlighting}"));
try!(w.write_line("\\end{Shaded}"));
Ok(())
}
fn start(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if colors::get_types().contains(&ty.to_owned()) {
try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty));
}
if ty == "attribute" {
try!(w.write_str("#"));
}
}
self.contexts.push(ty.to_owned());
Ok(())
}
fn end(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if ty == "attribute" {
try!(w.write_str("]"));
}
if colors::get_types().contains(&ty.to_owned()) {
try!(w.write_str("}"));
}
}
self.contexts.pop();
Ok(())
}
fn text(&mut self, w: &mut Writer, text: &str) -> IoResult<()> {
fn escape_latex(text: &str) -> ~str {
let mut result = StrBuf::new();
let mut escape = false;
for c in text.chars() {
if escape {
result.push_str("\\textbackslash{");
}
if c == '{' || c == '}' {
result.push_char('\\');
}
if c == '\\' {
escape = true;
} else {
result.push_char(c);
}
if escape && c!= '\\' {
result.push_char('}');
escape = false;
}
}
result.into_owned()
}
fn escape_comment(text: &str, has_color: bool) -> ~str {
let mut result = StrBuf::new();
let mut first = true;
for line in text.lines() {
if!first {
result.push_str("\n");
}
if line.len() > 0 && has_color {
result.push_str("\\textcolor{comment}{");
}
result.push_str(line);
if line.len() > 0 && has_color {
|
}
first = false;
}
let old_len = text.len();
let text = text.trim_right_chars('\n').to_owned();
let new_len = text.len();
range(0, old_len - new_len).advance(|_| {
result.push_char('\n');
true
});
result.into_owned()
}
let context = self.contexts.last().unwrap();
let has_color = colors::get_types().contains(context);
let context = context.as_slice();
let text = if context == "comment" {
escape_comment(text, has_color)
} else {
escape_latex(text)
};
try!(w.write_str(text));
Ok(())
}
}
|
result.push_str("}");
|
random_line_split
|
latex.rs
|
use std::io::IoResult;
use collections::HashMap;
use backend::Backend;
use colors;
pub struct LatexBackend {
contexts: Vec<~str>,
}
impl LatexBackend {
pub fn new() -> LatexBackend {
LatexBackend {
contexts: Vec::new(),
}
}
}
static HEADER: &'static str = "\
\\usepackage{xcolor}
\\usepackage{fancyvrb}
\\newcommand{\\VerbBar}{|}
\\newcommand{\\VERB}{\\Verb[commandchars=\\\\\\{\\}]}
\\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\\\\{\\}}
% Add ',fontsize=\\small' for more characters per line
\\newenvironment{Shaded}{}{}
";
impl Backend for LatexBackend {
fn configure(&mut self, _vars: &HashMap<~str, ~str>) -> Result<(), ~str> {
Ok(())
}
fn header(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_str(HEADER));
for (ty, color) in colors::get_colors().iter() {
try!(writeln!(w, "\\\\definecolor\\{{}\\}\\{HTML\\}\\{{}\\}", ty, color));
}
Ok(())
}
fn code_start(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_line("\\begin{Shaded}"));
try!(w.write_line("\\begin{Highlighting}[]"));
Ok(())
}
fn code_end(&mut self, w: &mut Writer) -> IoResult<()> {
try!(w.write_line("\\end{Highlighting}"));
try!(w.write_line("\\end{Shaded}"));
Ok(())
}
fn start(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment" {
if colors::get_types().contains(&ty.to_owned()) {
try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty));
}
if ty == "attribute" {
try!(w.write_str("#"));
}
}
self.contexts.push(ty.to_owned());
Ok(())
}
fn end(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> {
if ty!= "comment"
|
self.contexts.pop();
Ok(())
}
fn text(&mut self, w: &mut Writer, text: &str) -> IoResult<()> {
fn escape_latex(text: &str) -> ~str {
let mut result = StrBuf::new();
let mut escape = false;
for c in text.chars() {
if escape {
result.push_str("\\textbackslash{");
}
if c == '{' || c == '}' {
result.push_char('\\');
}
if c == '\\' {
escape = true;
} else {
result.push_char(c);
}
if escape && c!= '\\' {
result.push_char('}');
escape = false;
}
}
result.into_owned()
}
fn escape_comment(text: &str, has_color: bool) -> ~str {
let mut result = StrBuf::new();
let mut first = true;
for line in text.lines() {
if!first {
result.push_str("\n");
}
if line.len() > 0 && has_color {
result.push_str("\\textcolor{comment}{");
}
result.push_str(line);
if line.len() > 0 && has_color {
result.push_str("}");
}
first = false;
}
let old_len = text.len();
let text = text.trim_right_chars('\n').to_owned();
let new_len = text.len();
range(0, old_len - new_len).advance(|_| {
result.push_char('\n');
true
});
result.into_owned()
}
let context = self.contexts.last().unwrap();
let has_color = colors::get_types().contains(context);
let context = context.as_slice();
let text = if context == "comment" {
escape_comment(text, has_color)
} else {
escape_latex(text)
};
try!(w.write_str(text));
Ok(())
}
}
|
{
if ty == "attribute" {
try!(w.write_str("]"));
}
if colors::get_types().contains(&ty.to_owned()) {
try!(w.write_str("}"));
}
}
|
conditional_block
|
raft_client.rs
|
BUF` is reserved for errors.
if self.size > 0
&& (self.size + msg_size + GRPC_SEND_MSG_BUF >= self.cfg.max_grpc_send_msg_len as usize
|| self.batch.get_msgs().len() >= RAFT_MSG_MAX_BATCH_SIZE)
{
self.overflowing = Some(msg);
return;
}
self.size += msg_size;
self.batch.mut_msgs().push(msg);
}
#[inline]
fn empty(&self) -> bool {
self.batch.get_msgs().is_empty()
}
#[inline]
fn flush(&mut self, sender: &mut ClientCStreamSender<BatchRaftMessage>) -> grpcio::Result<()> {
let batch = mem::take(&mut self.batch);
let res = Pin::new(sender).start_send((
batch,
WriteFlags::default().buffer_hint(self.overflowing.is_some()),
));
self.size = 0;
if let Some(more) = self.overflowing.take() {
self.push(more);
}
res
}
}
/// A buffer for non-batch RaftMessage.
struct MessageBuffer {
batch: VecDeque<RaftMessage>,
}
impl MessageBuffer {
fn new() -> MessageBuffer {
MessageBuffer {
batch: VecDeque::with_capacity(2),
}
}
}
impl Buffer for MessageBuffer {
type OutputMessage = RaftMessage;
#[inline]
fn full(&self) -> bool {
self.batch.len() >= 2
}
#[inline]
fn push(&mut self, msg: RaftMessage) {
self.batch.push_back(msg);
}
#[inline]
fn empty(&self) -> bool
|
#[inline]
fn flush(&mut self, sender: &mut ClientCStreamSender<RaftMessage>) -> grpcio::Result<()> {
if let Some(msg) = self.batch.pop_front() {
Pin::new(sender).start_send((
msg,
WriteFlags::default().buffer_hint(!self.batch.is_empty()),
))
} else {
Ok(())
}
}
}
/// Reporter reports whether a snapshot is sent successfully.
struct SnapshotReporter<T, E> {
raft_router: T,
engine: PhantomData<E>,
region_id: u64,
to_peer_id: u64,
to_store_id: u64,
}
impl<T, E> SnapshotReporter<T, E>
where
T: RaftStoreRouter<E> +'static,
E: KvEngine,
{
pub fn report(&self, status: SnapshotStatus) {
debug!(
"send snapshot";
"to_peer_id" => self.to_peer_id,
"region_id" => self.region_id,
"status" =>?status
);
if status == SnapshotStatus::Failure {
let store = self.to_store_id.to_string();
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&["snapshot", &*store])
.inc();
}
if let Err(e) =
self.raft_router
.report_snapshot_status(self.region_id, self.to_peer_id, status)
{
error!(?e;
"report snapshot to peer failes";
"to_peer_id" => self.to_peer_id,
"to_store_id" => self.to_store_id,
"region_id" => self.region_id,
);
}
}
}
fn report_unreachable<R, E>(router: &R, msg: &RaftMessage)
where
R: RaftStoreRouter<E>,
E: KvEngine,
{
let to_peer = msg.get_to_peer();
if msg.get_message().has_snapshot() {
let store = to_peer.store_id.to_string();
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&["snapshot", &*store])
.inc();
let res = router.report_snapshot_status(msg.region_id, to_peer.id, SnapshotStatus::Failure);
if let Err(e) = res {
error!(
?e;
"reporting snapshot to peer fails";
"to_peer_id" => to_peer.id,
"to_store_id" => to_peer.store_id,
"region_id" => msg.region_id,
);
}
}
let _ = router.report_unreachable(msg.region_id, to_peer.id);
}
fn grpc_error_is_unimplemented(e: &grpcio::Error) -> bool {
if let grpcio::Error::RpcFailure(RpcStatus { ref status,.. }) = e {
let x = *status == RpcStatusCode::UNIMPLEMENTED;
return x;
}
false
}
/// Struct tracks the lifetime of a `raft` or `batch_raft` RPC.
struct RaftCall<R, M, B, E> {
sender: ClientCStreamSender<M>,
receiver: ClientCStreamReceiver<Done>,
queue: Arc<Queue>,
buffer: B,
router: R,
snap_scheduler: Scheduler<SnapTask>,
lifetime: Option<oneshot::Sender<()>>,
store_id: u64,
addr: String,
engine: PhantomData<E>,
}
impl<R, M, B, E> RaftCall<R, M, B, E>
where
R: RaftStoreRouter<E> +'static,
B: Buffer<OutputMessage = M>,
E: KvEngine,
{
fn new_snapshot_reporter(&self, msg: &RaftMessage) -> SnapshotReporter<R, E> {
let region_id = msg.get_region_id();
let to_peer_id = msg.get_to_peer().get_id();
let to_store_id = msg.get_to_peer().get_store_id();
SnapshotReporter {
raft_router: self.router.clone(),
engine: PhantomData,
region_id,
to_peer_id,
to_store_id,
}
}
fn send_snapshot_sock(&self, msg: RaftMessage) {
let rep = self.new_snapshot_reporter(&msg);
let cb = Box::new(move |res: Result<_, _>| {
if res.is_err() {
rep.report(SnapshotStatus::Failure);
} else {
rep.report(SnapshotStatus::Finish);
}
});
if let Err(e) = self.snap_scheduler.schedule(SnapTask::Send {
addr: self.addr.clone(),
msg,
cb,
}) {
if let SnapTask::Send { cb,.. } = e.into_inner() {
error!(
"channel is unavailable, failed to schedule snapshot";
"to_addr" => &self.addr
);
cb(Err(box_err!("failed to schedule snapshot")));
}
}
}
fn fill_msg(&mut self, ctx: &Context) {
while!self.buffer.full() {
let msg = match self.queue.pop(ctx) {
Some(msg) => msg,
None => return,
};
if msg.get_message().has_snapshot() {
self.send_snapshot_sock(msg);
continue;
} else {
self.buffer.push(msg);
}
}
}
fn clean_up(&mut self, sink_err: &Option<grpcio::Error>, recv_err: &Option<grpcio::Error>) {
error!("connection aborted"; "store_id" => self.store_id, "sink_error" =>?sink_err, "receiver_err" =>?recv_err, "addr" => %self.addr);
if let Some(tx) = self.lifetime.take() {
let should_fallback = [sink_err, recv_err]
.iter()
.any(|e| e.as_ref().map_or(false, grpc_error_is_unimplemented));
if should_fallback {
// Asks backend to fallback.
let _ = tx.send(());
return;
}
}
let router = &self.router;
router.broadcast_unreachable(self.store_id);
}
}
impl<R, M, B, E> Future for RaftCall<R, M, B, E>
where
R: RaftStoreRouter<E> + Unpin +'static,
B: Buffer<OutputMessage = M> + Unpin,
E: KvEngine,
{
type Output = ();
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<()> {
let s = &mut *self;
loop {
s.fill_msg(ctx);
if!s.buffer.empty() {
let mut res = Pin::new(&mut s.sender).poll_ready(ctx);
if let Poll::Ready(Ok(())) = res {
res = Poll::Ready(s.buffer.flush(&mut s.sender));
}
match res {
Poll::Ready(Ok(())) => continue,
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(e)) => {
let re = match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Ready(Err(e)) => Some(e),
_ => None,
};
s.clean_up(&Some(e), &re);
return Poll::Ready(());
}
}
}
if let Poll::Ready(Err(e)) = Pin::new(&mut s.sender).poll_flush(ctx) {
let re = match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Ready(Err(e)) => Some(e),
_ => None,
};
s.clean_up(&Some(e), &re);
return Poll::Ready(());
}
match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(_)) => {
info!("connection close"; "store_id" => s.store_id, "addr" => %s.addr);
return Poll::Ready(());
}
Poll::Ready(Err(e)) => {
s.clean_up(&None, &Some(e));
return Poll::Ready(());
}
}
}
}
}
#[derive(Clone)]
pub struct ConnectionBuilder<S, R> {
env: Arc<Environment>,
cfg: Arc<Config>,
security_mgr: Arc<SecurityManager>,
resolver: S,
router: R,
snap_scheduler: Scheduler<SnapTask>,
}
impl<S, R> ConnectionBuilder<S, R> {
pub fn new(
env: Arc<Environment>,
cfg: Arc<Config>,
security_mgr: Arc<SecurityManager>,
resolver: S,
router: R,
snap_scheduler: Scheduler<SnapTask>,
) -> ConnectionBuilder<S, R> {
ConnectionBuilder {
env,
cfg,
security_mgr,
resolver,
router,
snap_scheduler,
}
}
}
/// StreamBackEnd watches lifetime of a connection and handles reconnecting,
/// spawn new RPC.
struct StreamBackEnd<S, R, E> {
store_id: u64,
queue: Arc<Queue>,
builder: ConnectionBuilder<S, R>,
engine: PhantomData<E>,
}
impl<S, R, E> StreamBackEnd<S, R, E>
where
S: StoreAddrResolver,
R: RaftStoreRouter<E> + Unpin +'static,
E: KvEngine,
{
fn resolve(&self) -> impl Future<Output = server::Result<String>> {
let (tx, rx) = oneshot::channel();
let store_id = self.store_id;
let res = self.builder.resolver.resolve(
store_id,
#[allow(unused_mut)]
Box::new(move |mut addr| {
{
// Wrapping the fail point in a closure, so we can modify
// local variables without return.
let mut transport_on_resolve_fp = || {
fail_point!(_ON_RESOLVE_FP, |sid| if let Some(sid) = sid {
use std::mem;
let sid: u64 = sid.parse().unwrap();
if sid == store_id {
mem::swap(&mut addr, &mut Err(box_err!("injected failure")));
}
})
};
transport_on_resolve_fp();
}
let _ = tx.send(addr);
}),
);
async move {
res?;
match rx.await {
Ok(a) => a,
Err(_) => Err(server::Error::Other(
"failed to receive resolve result".into(),
)),
}
}
}
fn clear_pending_message(&self, reason: &str) {
let len = self.queue.len();
for _ in 0..len {
let msg = self.queue.try_pop().unwrap();
report_unreachable(&self.builder.router, &msg)
}
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&[reason, &self.store_id.to_string()])
.inc_by(len as i64);
}
fn connect(&self, addr: &str) -> TikvClient {
info!("server: new connection with tikv endpoint"; "addr" => addr, "store_id" => self.store_id);
let cb = ChannelBuilder::new(self.builder.env.clone())
.stream_initial_window_size(self.builder.cfg.grpc_stream_initial_window_size.0 as i32)
.max_send_message_len(self.builder.cfg.max_grpc_send_msg_len)
.keepalive_time(self.builder.cfg.grpc_keepalive_time.0)
.keepalive_timeout(self.builder.cfg.grpc_keepalive_timeout.0)
.default_compression_algorithm(self.builder.cfg.grpc_compression_algorithm())
// hack: so it's different args, grpc will always create a new connection.
.raw_cfg_int(
CString::new("random id").unwrap(),
CONN_ID.fetch_add(1, Ordering::SeqCst),
);
let channel = self.builder.security_mgr.connect(cb, addr);
TikvClient::new(channel)
}
fn batch_call(&self, client: &TikvClient, addr: String) -> oneshot::Receiver<()> {
let (batch_sink, batch_stream) = client.batch_raft().unwrap();
let (tx, rx) = oneshot::channel();
let call = RaftCall {
sender: batch_sink,
receiver: batch_stream,
queue: self.queue.clone(),
buffer: BatchMessageBuffer::new(self.builder.cfg.clone()),
router: self.builder.router.clone(),
snap_scheduler: self.builder.snap_scheduler.clone(),
lifetime: Some(tx),
store_id: self.store_id,
addr,
engine: PhantomData::<E>,
};
// TODO: verify it will be notified if client is dropped while env still alive.
client.spawn(call);
rx
}
fn call(&self, client: &TikvClient, addr: String) -> oneshot::Receiver<()> {
let (sink, stream) = client.raft().unwrap();
let (tx, rx) = oneshot::channel();
let call = RaftCall {
sender: sink,
receiver: stream,
queue: self.queue.clone(),
buffer: MessageBuffer::new(),
router: self.builder.router.clone(),
snap_scheduler: self.builder.snap_scheduler.clone(),
lifetime: Some(tx),
store_id: self.store_id,
addr,
engine: PhantomData::<E>,
};
client.spawn(call);
rx
}
}
async fn maybe_backoff(cfg: &Config, last_wake_time: &mut Instant, retry_times: &mut u32) {
if *retry_times == 0 {
return;
}
let timeout = cfg.raft_client_backoff_step.0 * cmp::min(*retry_times, 5);
let now = Instant::now();
if *last_wake_time + timeout < now {
// We have spent long enough time in last retry, no need to backoff again.
*last_wake_time = now;
*retry_times = 0;
return;
}
if let Err(e) = GLOBAL_TIMER_HANDLE.delay(now + timeout).compat().await {
error_unknown!(?e; "failed to backoff");
}
*last_wake_time = Instant::now();
}
/// A future that drives the life cycle of a connection.
///
/// The general progress of connection is:
///
/// 1. resolve address
/// 2. connect
/// 3. make batch call
/// 4. fallback to legacy API if incompatible
///
/// Every failure during the process should trigger retry automatically.
async fn start<S, R, E>(
back_end: StreamBackEnd<S, R, E>,
conn_id: usize,
pool: Arc<Mutex<ConnectionPool>>,
) where
S: StoreAddrResolver + Send,
R: RaftStoreRouter<E> + Unpin + Send +'static,
E: KvEngine,
{
let mut last_wake_time = Instant::now();
let mut retry_times = 0;
loop {
maybe_backoff(&back_end.builder.cfg, &mut last_wake_time, &mut retry_times).await;
retry_times += 1;
let f = back_end.resolve();
let addr = match f.await {
Ok(addr) => {
RESOLVE_STORE_COUNTER.with_label_values(&["success"]).inc();
info!("resolve store address ok"; "store_id" => back_end.store_id, "addr" => %addr);
addr
}
Err(e) => {
RESOLVE_STORE_COUNTER.with_label_values(&["failed"]).inc();
back_end.clear_pending_message("resolve");
error_unknown!(?e; "resolve store address failed"; "store_id" => back_end.store_id,);
// TOMBSTONE
if format!("{}", e).contains("has been removed") {
let mut pool = pool.lock().unwrap();
if let Some(s) = pool.connections.remove(&(back_end.store_id, conn_id)) {
s.disconnect();
}
|
{
self.batch.is_empty()
}
|
identifier_body
|
raft_client.rs
|
(&self) {
self.connected.store(false, Ordering::SeqCst);
}
/// Wakes up consumer to retrive message.
fn notify(&self) {
if!self.buf.is_empty() {
let t = self.waker.lock().unwrap().take();
if let Some(t) = t {
t.wake();
}
}
}
/// Gets the buffer len.
#[inline]
fn len(&self) -> usize {
self.buf.len()
}
/// Gets message from the head of the queue.
fn try_pop(&self) -> Option<RaftMessage> {
self.buf.pop()
}
/// Same as `try_pop` but register interest on readiness when `None` is returned.
///
/// The method should be called in polling context. If the queue is empty,
/// it will register current polling task for notifications.
#[inline]
fn pop(&self, ctx: &Context) -> Option<RaftMessage> {
self.buf.pop().or_else(|| {
{
let mut waker = self.waker.lock().unwrap();
*waker = Some(ctx.waker().clone());
}
self.buf.pop()
})
}
}
trait Buffer {
type OutputMessage;
/// Tests if it is full.
///
/// A full buffer should be flushed successfully before calling `push`.
fn full(&self) -> bool;
/// Pushes the message into buffer.
fn push(&mut self, msg: RaftMessage);
/// Checks if the batch is empty.
fn empty(&self) -> bool;
/// Flushes the message to grpc.
///
/// `sender` should be able to accept messages.
fn flush(
&mut self,
sender: &mut ClientCStreamSender<Self::OutputMessage>,
) -> grpcio::Result<()>;
}
/// A buffer for BatchRaftMessage.
struct BatchMessageBuffer {
batch: BatchRaftMessage,
overflowing: Option<RaftMessage>,
size: usize,
cfg: Arc<Config>,
}
impl BatchMessageBuffer {
fn new(cfg: Arc<Config>) -> BatchMessageBuffer {
BatchMessageBuffer {
batch: BatchRaftMessage::default(),
overflowing: None,
size: 0,
cfg,
}
}
}
impl Buffer for BatchMessageBuffer {
type OutputMessage = BatchRaftMessage;
#[inline]
fn full(&self) -> bool {
self.overflowing.is_some()
}
#[inline]
fn push(&mut self, msg: RaftMessage) {
let mut msg_size = msg.start_key.len() + msg.end_key.len();
for entry in msg.get_message().get_entries() {
msg_size += entry.data.len();
}
// To avoid building too large batch, we limit each batch's size. Since `msg_size`
// is estimated, `GRPC_SEND_MSG_BUF` is reserved for errors.
if self.size > 0
&& (self.size + msg_size + GRPC_SEND_MSG_BUF >= self.cfg.max_grpc_send_msg_len as usize
|| self.batch.get_msgs().len() >= RAFT_MSG_MAX_BATCH_SIZE)
{
self.overflowing = Some(msg);
return;
}
self.size += msg_size;
self.batch.mut_msgs().push(msg);
}
#[inline]
fn empty(&self) -> bool {
self.batch.get_msgs().is_empty()
}
#[inline]
fn flush(&mut self, sender: &mut ClientCStreamSender<BatchRaftMessage>) -> grpcio::Result<()> {
let batch = mem::take(&mut self.batch);
let res = Pin::new(sender).start_send((
batch,
WriteFlags::default().buffer_hint(self.overflowing.is_some()),
));
self.size = 0;
if let Some(more) = self.overflowing.take() {
self.push(more);
}
res
}
}
/// A buffer for non-batch RaftMessage.
struct MessageBuffer {
batch: VecDeque<RaftMessage>,
}
impl MessageBuffer {
fn new() -> MessageBuffer {
MessageBuffer {
batch: VecDeque::with_capacity(2),
}
}
}
impl Buffer for MessageBuffer {
type OutputMessage = RaftMessage;
#[inline]
fn full(&self) -> bool {
self.batch.len() >= 2
}
#[inline]
fn push(&mut self, msg: RaftMessage) {
self.batch.push_back(msg);
}
#[inline]
fn empty(&self) -> bool {
self.batch.is_empty()
}
#[inline]
fn flush(&mut self, sender: &mut ClientCStreamSender<RaftMessage>) -> grpcio::Result<()> {
if let Some(msg) = self.batch.pop_front() {
Pin::new(sender).start_send((
msg,
WriteFlags::default().buffer_hint(!self.batch.is_empty()),
))
} else {
Ok(())
}
}
}
/// Reporter reports whether a snapshot is sent successfully.
struct SnapshotReporter<T, E> {
raft_router: T,
engine: PhantomData<E>,
region_id: u64,
to_peer_id: u64,
to_store_id: u64,
}
impl<T, E> SnapshotReporter<T, E>
where
T: RaftStoreRouter<E> +'static,
E: KvEngine,
{
pub fn report(&self, status: SnapshotStatus) {
debug!(
"send snapshot";
"to_peer_id" => self.to_peer_id,
"region_id" => self.region_id,
"status" =>?status
);
if status == SnapshotStatus::Failure {
let store = self.to_store_id.to_string();
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&["snapshot", &*store])
.inc();
}
if let Err(e) =
self.raft_router
.report_snapshot_status(self.region_id, self.to_peer_id, status)
{
error!(?e;
"report snapshot to peer failes";
"to_peer_id" => self.to_peer_id,
"to_store_id" => self.to_store_id,
"region_id" => self.region_id,
);
}
}
}
fn report_unreachable<R, E>(router: &R, msg: &RaftMessage)
where
R: RaftStoreRouter<E>,
E: KvEngine,
{
let to_peer = msg.get_to_peer();
if msg.get_message().has_snapshot() {
let store = to_peer.store_id.to_string();
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&["snapshot", &*store])
.inc();
let res = router.report_snapshot_status(msg.region_id, to_peer.id, SnapshotStatus::Failure);
if let Err(e) = res {
error!(
?e;
"reporting snapshot to peer fails";
"to_peer_id" => to_peer.id,
"to_store_id" => to_peer.store_id,
"region_id" => msg.region_id,
);
}
}
let _ = router.report_unreachable(msg.region_id, to_peer.id);
}
fn grpc_error_is_unimplemented(e: &grpcio::Error) -> bool {
if let grpcio::Error::RpcFailure(RpcStatus { ref status,.. }) = e {
let x = *status == RpcStatusCode::UNIMPLEMENTED;
return x;
}
false
}
/// Struct tracks the lifetime of a `raft` or `batch_raft` RPC.
struct RaftCall<R, M, B, E> {
sender: ClientCStreamSender<M>,
receiver: ClientCStreamReceiver<Done>,
queue: Arc<Queue>,
buffer: B,
router: R,
snap_scheduler: Scheduler<SnapTask>,
lifetime: Option<oneshot::Sender<()>>,
store_id: u64,
addr: String,
engine: PhantomData<E>,
}
impl<R, M, B, E> RaftCall<R, M, B, E>
where
R: RaftStoreRouter<E> +'static,
B: Buffer<OutputMessage = M>,
E: KvEngine,
{
fn new_snapshot_reporter(&self, msg: &RaftMessage) -> SnapshotReporter<R, E> {
let region_id = msg.get_region_id();
let to_peer_id = msg.get_to_peer().get_id();
let to_store_id = msg.get_to_peer().get_store_id();
SnapshotReporter {
raft_router: self.router.clone(),
engine: PhantomData,
region_id,
to_peer_id,
to_store_id,
}
}
fn send_snapshot_sock(&self, msg: RaftMessage) {
let rep = self.new_snapshot_reporter(&msg);
let cb = Box::new(move |res: Result<_, _>| {
if res.is_err() {
rep.report(SnapshotStatus::Failure);
} else {
rep.report(SnapshotStatus::Finish);
}
});
if let Err(e) = self.snap_scheduler.schedule(SnapTask::Send {
addr: self.addr.clone(),
msg,
cb,
}) {
if let SnapTask::Send { cb,.. } = e.into_inner() {
error!(
"channel is unavailable, failed to schedule snapshot";
"to_addr" => &self.addr
);
cb(Err(box_err!("failed to schedule snapshot")));
}
}
}
fn fill_msg(&mut self, ctx: &Context) {
while!self.buffer.full() {
let msg = match self.queue.pop(ctx) {
Some(msg) => msg,
None => return,
};
if msg.get_message().has_snapshot() {
self.send_snapshot_sock(msg);
continue;
} else {
self.buffer.push(msg);
}
}
}
fn clean_up(&mut self, sink_err: &Option<grpcio::Error>, recv_err: &Option<grpcio::Error>) {
error!("connection aborted"; "store_id" => self.store_id, "sink_error" =>?sink_err, "receiver_err" =>?recv_err, "addr" => %self.addr);
if let Some(tx) = self.lifetime.take() {
let should_fallback = [sink_err, recv_err]
.iter()
.any(|e| e.as_ref().map_or(false, grpc_error_is_unimplemented));
if should_fallback {
// Asks backend to fallback.
let _ = tx.send(());
return;
}
}
let router = &self.router;
router.broadcast_unreachable(self.store_id);
}
}
impl<R, M, B, E> Future for RaftCall<R, M, B, E>
where
R: RaftStoreRouter<E> + Unpin +'static,
B: Buffer<OutputMessage = M> + Unpin,
E: KvEngine,
{
type Output = ();
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<()> {
let s = &mut *self;
loop {
s.fill_msg(ctx);
if!s.buffer.empty() {
let mut res = Pin::new(&mut s.sender).poll_ready(ctx);
if let Poll::Ready(Ok(())) = res {
res = Poll::Ready(s.buffer.flush(&mut s.sender));
}
match res {
Poll::Ready(Ok(())) => continue,
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(e)) => {
let re = match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Ready(Err(e)) => Some(e),
_ => None,
};
s.clean_up(&Some(e), &re);
return Poll::Ready(());
}
}
}
if let Poll::Ready(Err(e)) = Pin::new(&mut s.sender).poll_flush(ctx) {
let re = match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Ready(Err(e)) => Some(e),
_ => None,
};
s.clean_up(&Some(e), &re);
return Poll::Ready(());
}
match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(_)) => {
info!("connection close"; "store_id" => s.store_id, "addr" => %s.addr);
return Poll::Ready(());
}
Poll::Ready(Err(e)) => {
s.clean_up(&None, &Some(e));
return Poll::Ready(());
}
}
}
}
}
#[derive(Clone)]
pub struct ConnectionBuilder<S, R> {
env: Arc<Environment>,
cfg: Arc<Config>,
security_mgr: Arc<SecurityManager>,
resolver: S,
router: R,
snap_scheduler: Scheduler<SnapTask>,
}
impl<S, R> ConnectionBuilder<S, R> {
pub fn new(
env: Arc<Environment>,
cfg: Arc<Config>,
security_mgr: Arc<SecurityManager>,
resolver: S,
router: R,
snap_scheduler: Scheduler<SnapTask>,
) -> ConnectionBuilder<S, R> {
ConnectionBuilder {
env,
cfg,
security_mgr,
resolver,
router,
snap_scheduler,
}
}
}
/// StreamBackEnd watches lifetime of a connection and handles reconnecting,
/// spawn new RPC.
struct StreamBackEnd<S, R, E> {
store_id: u64,
queue: Arc<Queue>,
builder: ConnectionBuilder<S, R>,
engine: PhantomData<E>,
}
impl<S, R, E> StreamBackEnd<S, R, E>
where
S: StoreAddrResolver,
R: RaftStoreRouter<E> + Unpin +'static,
E: KvEngine,
{
fn resolve(&self) -> impl Future<Output = server::Result<String>> {
let (tx, rx) = oneshot::channel();
let store_id = self.store_id;
let res = self.builder.resolver.resolve(
store_id,
#[allow(unused_mut)]
Box::new(move |mut addr| {
{
// Wrapping the fail point in a closure, so we can modify
// local variables without return.
let mut transport_on_resolve_fp = || {
fail_point!(_ON_RESOLVE_FP, |sid| if let Some(sid) = sid {
use std::mem;
let sid: u64 = sid.parse().unwrap();
if sid == store_id {
mem::swap(&mut addr, &mut Err(box_err!("injected failure")));
}
})
};
transport_on_resolve_fp();
}
let _ = tx.send(addr);
}),
);
async move {
res?;
match rx.await {
Ok(a) => a,
Err(_) => Err(server::Error::Other(
"failed to receive resolve result".into(),
)),
}
}
}
fn clear_pending_message(&self, reason: &str) {
let len = self.queue.len();
for _ in 0..len {
let msg = self.queue.try_pop().unwrap();
report_unreachable(&self.builder.router, &msg)
}
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&[reason, &self.store_id.to_string()])
.inc_by(len as i64);
}
fn connect(&self, addr: &str) -> TikvClient {
info!("server: new connection with tikv endpoint"; "addr" => addr, "store_id" => self.store_id);
let cb = ChannelBuilder::new(self.builder.env.clone())
.stream_initial_window_size(self.builder.cfg.grpc_stream_initial_window_size.0 as i32)
.max_send_message_len(self.builder.cfg.max_grpc_send_msg_len)
.keepalive_time(self.builder.cfg.grpc_keepalive_time.0)
.keepalive_timeout(self.builder.cfg.grpc_keepalive_timeout.0)
.default_compression_algorithm(self.builder.cfg.grpc_compression_algorithm())
// hack: so it's different args, grpc will always create a new connection.
.raw_cfg_int(
CString::new("random id").unwrap(),
CONN_ID.fetch_add(1, Ordering::SeqCst),
);
let channel = self.builder.security_mgr.connect(cb, addr);
TikvClient::new(channel)
}
fn batch_call(&self, client: &TikvClient, addr: String) -> oneshot::Receiver<()> {
let (batch_sink, batch_stream) = client.batch_raft().unwrap();
let (tx, rx) = oneshot::channel();
let call = RaftCall {
sender: batch_sink,
receiver: batch_stream,
queue: self.queue.clone(),
buffer: BatchMessageBuffer::new(self.builder.cfg.clone()),
router: self.builder.router.clone(),
snap_scheduler: self.builder.snap_scheduler.clone(),
lifetime: Some(tx),
store_id: self.store_id,
addr,
engine: PhantomData::<E>,
};
// TODO: verify it will be notified if client is dropped while env still alive.
client.spawn(call);
rx
}
fn call(&self, client: &TikvClient, addr: String) -> oneshot::Receiver<()> {
let (sink, stream) = client.raft().unwrap();
let (tx, rx) = oneshot::channel();
let call = RaftCall {
sender: sink,
receiver: stream,
queue: self.queue.clone(),
buffer: MessageBuffer::new(),
router: self.builder.router.clone(),
|
disconnect
|
identifier_name
|
|
raft_client.rs
|
_BUF` is reserved for errors.
if self.size > 0
&& (self.size + msg_size + GRPC_SEND_MSG_BUF >= self.cfg.max_grpc_send_msg_len as usize
|| self.batch.get_msgs().len() >= RAFT_MSG_MAX_BATCH_SIZE)
{
self.overflowing = Some(msg);
return;
}
self.size += msg_size;
self.batch.mut_msgs().push(msg);
}
#[inline]
fn empty(&self) -> bool {
self.batch.get_msgs().is_empty()
}
#[inline]
fn flush(&mut self, sender: &mut ClientCStreamSender<BatchRaftMessage>) -> grpcio::Result<()> {
let batch = mem::take(&mut self.batch);
let res = Pin::new(sender).start_send((
batch,
WriteFlags::default().buffer_hint(self.overflowing.is_some()),
));
self.size = 0;
if let Some(more) = self.overflowing.take() {
self.push(more);
}
res
}
}
/// A buffer for non-batch RaftMessage.
struct MessageBuffer {
batch: VecDeque<RaftMessage>,
}
impl MessageBuffer {
fn new() -> MessageBuffer {
MessageBuffer {
batch: VecDeque::with_capacity(2),
}
}
}
impl Buffer for MessageBuffer {
type OutputMessage = RaftMessage;
#[inline]
fn full(&self) -> bool {
self.batch.len() >= 2
}
#[inline]
fn push(&mut self, msg: RaftMessage) {
self.batch.push_back(msg);
}
#[inline]
fn empty(&self) -> bool {
self.batch.is_empty()
}
#[inline]
fn flush(&mut self, sender: &mut ClientCStreamSender<RaftMessage>) -> grpcio::Result<()> {
if let Some(msg) = self.batch.pop_front() {
Pin::new(sender).start_send((
msg,
WriteFlags::default().buffer_hint(!self.batch.is_empty()),
))
} else {
Ok(())
}
}
}
/// Reporter reports whether a snapshot is sent successfully.
struct SnapshotReporter<T, E> {
raft_router: T,
engine: PhantomData<E>,
region_id: u64,
to_peer_id: u64,
to_store_id: u64,
}
impl<T, E> SnapshotReporter<T, E>
where
T: RaftStoreRouter<E> +'static,
E: KvEngine,
{
pub fn report(&self, status: SnapshotStatus) {
debug!(
"send snapshot";
"to_peer_id" => self.to_peer_id,
"region_id" => self.region_id,
"status" =>?status
);
if status == SnapshotStatus::Failure {
let store = self.to_store_id.to_string();
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&["snapshot", &*store])
.inc();
}
if let Err(e) =
self.raft_router
.report_snapshot_status(self.region_id, self.to_peer_id, status)
{
error!(?e;
"report snapshot to peer failes";
"to_peer_id" => self.to_peer_id,
"to_store_id" => self.to_store_id,
"region_id" => self.region_id,
);
}
}
}
fn report_unreachable<R, E>(router: &R, msg: &RaftMessage)
where
R: RaftStoreRouter<E>,
E: KvEngine,
{
let to_peer = msg.get_to_peer();
if msg.get_message().has_snapshot() {
let store = to_peer.store_id.to_string();
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&["snapshot", &*store])
.inc();
let res = router.report_snapshot_status(msg.region_id, to_peer.id, SnapshotStatus::Failure);
if let Err(e) = res {
error!(
?e;
"reporting snapshot to peer fails";
"to_peer_id" => to_peer.id,
"to_store_id" => to_peer.store_id,
"region_id" => msg.region_id,
);
}
}
let _ = router.report_unreachable(msg.region_id, to_peer.id);
}
fn grpc_error_is_unimplemented(e: &grpcio::Error) -> bool {
if let grpcio::Error::RpcFailure(RpcStatus { ref status,.. }) = e {
let x = *status == RpcStatusCode::UNIMPLEMENTED;
return x;
}
false
}
/// Struct tracks the lifetime of a `raft` or `batch_raft` RPC.
struct RaftCall<R, M, B, E> {
sender: ClientCStreamSender<M>,
receiver: ClientCStreamReceiver<Done>,
queue: Arc<Queue>,
buffer: B,
router: R,
snap_scheduler: Scheduler<SnapTask>,
lifetime: Option<oneshot::Sender<()>>,
store_id: u64,
addr: String,
engine: PhantomData<E>,
}
impl<R, M, B, E> RaftCall<R, M, B, E>
where
R: RaftStoreRouter<E> +'static,
B: Buffer<OutputMessage = M>,
E: KvEngine,
{
fn new_snapshot_reporter(&self, msg: &RaftMessage) -> SnapshotReporter<R, E> {
let region_id = msg.get_region_id();
let to_peer_id = msg.get_to_peer().get_id();
let to_store_id = msg.get_to_peer().get_store_id();
SnapshotReporter {
raft_router: self.router.clone(),
engine: PhantomData,
region_id,
to_peer_id,
to_store_id,
}
}
fn send_snapshot_sock(&self, msg: RaftMessage) {
let rep = self.new_snapshot_reporter(&msg);
let cb = Box::new(move |res: Result<_, _>| {
if res.is_err() {
rep.report(SnapshotStatus::Failure);
} else {
rep.report(SnapshotStatus::Finish);
}
});
if let Err(e) = self.snap_scheduler.schedule(SnapTask::Send {
addr: self.addr.clone(),
msg,
cb,
}) {
if let SnapTask::Send { cb,.. } = e.into_inner() {
error!(
"channel is unavailable, failed to schedule snapshot";
"to_addr" => &self.addr
);
cb(Err(box_err!("failed to schedule snapshot")));
}
}
}
fn fill_msg(&mut self, ctx: &Context) {
while!self.buffer.full() {
let msg = match self.queue.pop(ctx) {
Some(msg) => msg,
None => return,
};
if msg.get_message().has_snapshot() {
self.send_snapshot_sock(msg);
continue;
} else {
self.buffer.push(msg);
}
}
}
fn clean_up(&mut self, sink_err: &Option<grpcio::Error>, recv_err: &Option<grpcio::Error>) {
error!("connection aborted"; "store_id" => self.store_id, "sink_error" =>?sink_err, "receiver_err" =>?recv_err, "addr" => %self.addr);
if let Some(tx) = self.lifetime.take() {
let should_fallback = [sink_err, recv_err]
.iter()
.any(|e| e.as_ref().map_or(false, grpc_error_is_unimplemented));
if should_fallback {
// Asks backend to fallback.
|
}
let router = &self.router;
router.broadcast_unreachable(self.store_id);
}
}
impl<R, M, B, E> Future for RaftCall<R, M, B, E>
where
R: RaftStoreRouter<E> + Unpin +'static,
B: Buffer<OutputMessage = M> + Unpin,
E: KvEngine,
{
type Output = ();
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<()> {
let s = &mut *self;
loop {
s.fill_msg(ctx);
if!s.buffer.empty() {
let mut res = Pin::new(&mut s.sender).poll_ready(ctx);
if let Poll::Ready(Ok(())) = res {
res = Poll::Ready(s.buffer.flush(&mut s.sender));
}
match res {
Poll::Ready(Ok(())) => continue,
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(e)) => {
let re = match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Ready(Err(e)) => Some(e),
_ => None,
};
s.clean_up(&Some(e), &re);
return Poll::Ready(());
}
}
}
if let Poll::Ready(Err(e)) = Pin::new(&mut s.sender).poll_flush(ctx) {
let re = match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Ready(Err(e)) => Some(e),
_ => None,
};
s.clean_up(&Some(e), &re);
return Poll::Ready(());
}
match Pin::new(&mut s.receiver).poll(ctx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(_)) => {
info!("connection close"; "store_id" => s.store_id, "addr" => %s.addr);
return Poll::Ready(());
}
Poll::Ready(Err(e)) => {
s.clean_up(&None, &Some(e));
return Poll::Ready(());
}
}
}
}
}
#[derive(Clone)]
pub struct ConnectionBuilder<S, R> {
env: Arc<Environment>,
cfg: Arc<Config>,
security_mgr: Arc<SecurityManager>,
resolver: S,
router: R,
snap_scheduler: Scheduler<SnapTask>,
}
impl<S, R> ConnectionBuilder<S, R> {
pub fn new(
env: Arc<Environment>,
cfg: Arc<Config>,
security_mgr: Arc<SecurityManager>,
resolver: S,
router: R,
snap_scheduler: Scheduler<SnapTask>,
) -> ConnectionBuilder<S, R> {
ConnectionBuilder {
env,
cfg,
security_mgr,
resolver,
router,
snap_scheduler,
}
}
}
/// StreamBackEnd watches lifetime of a connection and handles reconnecting,
/// spawn new RPC.
struct StreamBackEnd<S, R, E> {
store_id: u64,
queue: Arc<Queue>,
builder: ConnectionBuilder<S, R>,
engine: PhantomData<E>,
}
impl<S, R, E> StreamBackEnd<S, R, E>
where
S: StoreAddrResolver,
R: RaftStoreRouter<E> + Unpin +'static,
E: KvEngine,
{
fn resolve(&self) -> impl Future<Output = server::Result<String>> {
let (tx, rx) = oneshot::channel();
let store_id = self.store_id;
let res = self.builder.resolver.resolve(
store_id,
#[allow(unused_mut)]
Box::new(move |mut addr| {
{
// Wrapping the fail point in a closure, so we can modify
// local variables without return.
let mut transport_on_resolve_fp = || {
fail_point!(_ON_RESOLVE_FP, |sid| if let Some(sid) = sid {
use std::mem;
let sid: u64 = sid.parse().unwrap();
if sid == store_id {
mem::swap(&mut addr, &mut Err(box_err!("injected failure")));
}
})
};
transport_on_resolve_fp();
}
let _ = tx.send(addr);
}),
);
async move {
res?;
match rx.await {
Ok(a) => a,
Err(_) => Err(server::Error::Other(
"failed to receive resolve result".into(),
)),
}
}
}
fn clear_pending_message(&self, reason: &str) {
let len = self.queue.len();
for _ in 0..len {
let msg = self.queue.try_pop().unwrap();
report_unreachable(&self.builder.router, &msg)
}
REPORT_FAILURE_MSG_COUNTER
.with_label_values(&[reason, &self.store_id.to_string()])
.inc_by(len as i64);
}
fn connect(&self, addr: &str) -> TikvClient {
info!("server: new connection with tikv endpoint"; "addr" => addr, "store_id" => self.store_id);
let cb = ChannelBuilder::new(self.builder.env.clone())
.stream_initial_window_size(self.builder.cfg.grpc_stream_initial_window_size.0 as i32)
.max_send_message_len(self.builder.cfg.max_grpc_send_msg_len)
.keepalive_time(self.builder.cfg.grpc_keepalive_time.0)
.keepalive_timeout(self.builder.cfg.grpc_keepalive_timeout.0)
.default_compression_algorithm(self.builder.cfg.grpc_compression_algorithm())
// hack: so it's different args, grpc will always create a new connection.
.raw_cfg_int(
CString::new("random id").unwrap(),
CONN_ID.fetch_add(1, Ordering::SeqCst),
);
let channel = self.builder.security_mgr.connect(cb, addr);
TikvClient::new(channel)
}
fn batch_call(&self, client: &TikvClient, addr: String) -> oneshot::Receiver<()> {
let (batch_sink, batch_stream) = client.batch_raft().unwrap();
let (tx, rx) = oneshot::channel();
let call = RaftCall {
sender: batch_sink,
receiver: batch_stream,
queue: self.queue.clone(),
buffer: BatchMessageBuffer::new(self.builder.cfg.clone()),
router: self.builder.router.clone(),
snap_scheduler: self.builder.snap_scheduler.clone(),
lifetime: Some(tx),
store_id: self.store_id,
addr,
engine: PhantomData::<E>,
};
// TODO: verify it will be notified if client is dropped while env still alive.
client.spawn(call);
rx
}
fn call(&self, client: &TikvClient, addr: String) -> oneshot::Receiver<()> {
let (sink, stream) = client.raft().unwrap();
let (tx, rx) = oneshot::channel();
let call = RaftCall {
sender: sink,
receiver: stream,
queue: self.queue.clone(),
buffer: MessageBuffer::new(),
router: self.builder.router.clone(),
snap_scheduler: self.builder.snap_scheduler.clone(),
lifetime: Some(tx),
store_id: self.store_id,
addr,
engine: PhantomData::<E>,
};
client.spawn(call);
rx
}
}
async fn maybe_backoff(cfg: &Config, last_wake_time: &mut Instant, retry_times: &mut u32) {
if *retry_times == 0 {
return;
}
let timeout = cfg.raft_client_backoff_step.0 * cmp::min(*retry_times, 5);
let now = Instant::now();
if *last_wake_time + timeout < now {
// We have spent long enough time in last retry, no need to backoff again.
*last_wake_time = now;
*retry_times = 0;
return;
}
if let Err(e) = GLOBAL_TIMER_HANDLE.delay(now + timeout).compat().await {
error_unknown!(?e; "failed to backoff");
}
*last_wake_time = Instant::now();
}
/// A future that drives the life cycle of a connection.
///
/// The general progress of connection is:
///
/// 1. resolve address
/// 2. connect
/// 3. make batch call
/// 4. fallback to legacy API if incompatible
///
/// Every failure during the process should trigger retry automatically.
async fn start<S, R, E>(
back_end: StreamBackEnd<S, R, E>,
conn_id: usize,
pool: Arc<Mutex<ConnectionPool>>,
) where
S: StoreAddrResolver + Send,
R: RaftStoreRouter<E> + Unpin + Send +'static,
E: KvEngine,
{
let mut last_wake_time = Instant::now();
let mut retry_times = 0;
loop {
maybe_backoff(&back_end.builder.cfg, &mut last_wake_time, &mut retry_times).await;
retry_times += 1;
let f = back_end.resolve();
let addr = match f.await {
Ok(addr) => {
RESOLVE_STORE_COUNTER.with_label_values(&["success"]).inc();
info!("resolve store address ok"; "store_id" => back_end.store_id, "addr" => %addr);
addr
}
Err(e) => {
RESOLVE_STORE_COUNTER.with_label_values(&["failed"]).inc();
back_end.clear_pending_message("resolve");
error_unknown!(?e; "resolve store address failed"; "store_id" => back_end.store_id,);
// TOMBSTONE
if format!("{}", e).contains("has been removed") {
let mut pool = pool.lock().unwrap();
if let Some(s) = pool.connections.remove(&(back_end.store_id, conn_id)) {
s.disconnect();
}
|
let _ = tx.send(());
return;
}
|
random_line_split
|
into_stream.rs
|
use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream, TryStream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::unsafe_pinned;
/// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct IntoStream<St> {
stream: St,
}
impl<St> IntoStream<St> {
unsafe_pinned!(stream: St);
#[inline]
pub(super) fn new(stream: St) -> Self {
IntoStream { stream }
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
&self.stream
}
/// Acquires a mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_mut(&mut self) -> &mut St {
&mut self.stream
}
/// Acquires a pinned mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> {
self.stream()
}
/// Consumes this combinator, returning the underlying stream.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> St {
self.stream
}
}
impl<St: TryStream + FusedStream> FusedStream for IntoStream<St> {
fn is_terminated(&self) -> bool {
self.stream.is_terminated()
}
}
impl<St: TryStream> Stream for IntoStream<St> {
type Item = Result<St::Ok, St::Error>;
#[inline]
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>>
|
fn size_hint(&self) -> (usize, Option<usize>) {
self.stream.size_hint()
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Sink<Item>, Item> Sink<Item> for IntoStream<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
}
|
{
self.stream().try_poll_next(cx)
}
|
identifier_body
|
into_stream.rs
|
use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream, TryStream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::unsafe_pinned;
/// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct
|
<St> {
stream: St,
}
impl<St> IntoStream<St> {
unsafe_pinned!(stream: St);
#[inline]
pub(super) fn new(stream: St) -> Self {
IntoStream { stream }
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
&self.stream
}
/// Acquires a mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_mut(&mut self) -> &mut St {
&mut self.stream
}
/// Acquires a pinned mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> {
self.stream()
}
/// Consumes this combinator, returning the underlying stream.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> St {
self.stream
}
}
impl<St: TryStream + FusedStream> FusedStream for IntoStream<St> {
fn is_terminated(&self) -> bool {
self.stream.is_terminated()
}
}
impl<St: TryStream> Stream for IntoStream<St> {
type Item = Result<St::Ok, St::Error>;
#[inline]
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
self.stream().try_poll_next(cx)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.stream.size_hint()
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Sink<Item>, Item> Sink<Item> for IntoStream<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
}
|
IntoStream
|
identifier_name
|
into_stream.rs
|
use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream, TryStream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::unsafe_pinned;
/// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct IntoStream<St> {
stream: St,
}
impl<St> IntoStream<St> {
unsafe_pinned!(stream: St);
#[inline]
pub(super) fn new(stream: St) -> Self {
IntoStream { stream }
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
&self.stream
}
/// Acquires a mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_mut(&mut self) -> &mut St {
&mut self.stream
}
/// Acquires a pinned mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> {
self.stream()
}
/// Consumes this combinator, returning the underlying stream.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> St {
self.stream
}
}
impl<St: TryStream + FusedStream> FusedStream for IntoStream<St> {
fn is_terminated(&self) -> bool {
self.stream.is_terminated()
}
}
impl<St: TryStream> Stream for IntoStream<St> {
type Item = Result<St::Ok, St::Error>;
#[inline]
fn poll_next(
self: Pin<&mut Self>,
|
fn size_hint(&self) -> (usize, Option<usize>) {
self.stream.size_hint()
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Sink<Item>, Item> Sink<Item> for IntoStream<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
}
|
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
self.stream().try_poll_next(cx)
}
|
random_line_split
|
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
use values::computed::{Image, LengthOrPercentage};
use values::computed::url::ComputedUrl;
use values::generics::basic_shape as generic;
/// A computed clipping shape.
pub type ClippingShape = generic::ClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = generic::FloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
pub type BasicShape =
generic::BasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = generic::InsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = generic::Circle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = generic::Ellipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = generic::ShapeRadius<LengthOrPercentage>;
impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn
|
<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y)!= Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
|
to_css
|
identifier_name
|
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
use values::computed::{Image, LengthOrPercentage};
use values::computed::url::ComputedUrl;
use values::generics::basic_shape as generic;
/// A computed clipping shape.
pub type ClippingShape = generic::ClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = generic::FloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
pub type BasicShape =
generic::BasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = generic::InsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = generic::Circle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = generic::Ellipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = generic::ShapeRadius<LengthOrPercentage>;
|
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y)!= Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
|
impl ToCss for Circle {
|
random_line_split
|
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
use values::computed::{Image, LengthOrPercentage};
use values::computed::url::ComputedUrl;
use values::generics::basic_shape as generic;
/// A computed clipping shape.
pub type ClippingShape = generic::ClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = generic::FloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
pub type BasicShape =
generic::BasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = generic::InsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = generic::Circle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = generic::Ellipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = generic::ShapeRadius<LengthOrPercentage>;
impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y)!= Default::default()
|
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
|
{
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
|
conditional_block
|
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
use values::computed::{Image, LengthOrPercentage};
use values::computed::url::ComputedUrl;
use values::generics::basic_shape as generic;
/// A computed clipping shape.
pub type ClippingShape = generic::ClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = generic::FloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
pub type BasicShape =
generic::BasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = generic::InsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = generic::Circle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = generic::Ellipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = generic::ShapeRadius<LengthOrPercentage>;
impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
|
}
|
{
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y) != Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
|
identifier_body
|
lib.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/. */
#![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"]
#![feature(globs, macro_rules)]
#![deny(unused_imports)]
#![deny(unused_variables)]
#![feature(phase)]
#[phase(plugin, link)] extern crate log;
#[phase(plugin)] extern crate string_cache_macros;
extern crate collections;
extern crate geom;
extern crate serialize;
extern crate sync;
extern crate url;
extern crate cssparser;
extern crate encoding;
extern crate string_cache;
#[phase(plugin)]
|
extern crate string_cache_macros;
#[phase(plugin)]
extern crate lazy_static;
extern crate "util" as servo_util;
// Public API
pub use media_queries::{Device, Screen};
pub use stylesheets::{Stylesheet, iter_font_face_rules};
pub use selector_matching::{Stylist, StylesheetOrigin, UserAgentOrigin, AuthorOrigin, UserOrigin};
pub use selector_matching::{DeclarationBlock, CommonStyleAffectingAttributes};
pub use selector_matching::{CommonStyleAffectingAttributeInfo, CommonStyleAffectingAttributeMode};
pub use selector_matching::{AttrIsPresentMode, AttrIsEqualMode};
pub use selector_matching::{matches, matches_simple_selector, common_style_affecting_attributes};
pub use selector_matching::{RECOMMENDED_SELECTOR_BLOOM_FILTER_SIZE,SELECTOR_WHITESPACE};
pub use properties::{cascade, cascade_anonymous, computed};
pub use properties::{PropertyDeclaration, ComputedValues, computed_values, style_structs};
pub use properties::{PropertyDeclarationBlock, parse_style_attribute}; // Style attributes
pub use properties::{CSSFloat, DeclaredValue, PropertyDeclarationParseResult};
pub use properties::{Angle, AngleOrCorner, AngleAoc, CornerAoc};
pub use properties::{Left, Right, Bottom, Top};
pub use node::{TElement, TElementAttributes, TNode};
pub use selectors::{PseudoElement, Before, After, SelectorList, parse_selector_list_from_str};
pub use selectors::{AttrSelector, NamespaceConstraint, SpecificNamespace, AnyNamespace};
pub use selectors::{SimpleSelector,LocalNameSelector};
pub use cssparser::{Color, RGBA};
pub use legacy::{IntegerAttribute, LengthAttribute, SizeIntegerAttribute, WidthLengthAttribute};
pub use font_face::{Source, LocalSource, UrlSource_};
mod stylesheets;
mod errors;
mod selectors;
mod selector_matching;
mod properties;
mod namespaces;
mod node;
mod media_queries;
mod parsing_utils;
mod font_face;
mod legacy;
|
random_line_split
|
|
trace.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/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Garbage
//! Collector. A rooted DOM object implementing the interface `Foo` is traced
//! as follows:
//!
//! 1. The GC calls `_trace` defined in `FooBinding` during the marking
//! phase. (This happens through `JSClass.trace` for non-proxy bindings, and
//! through `ProxyTraps.trace` otherwise.)
//! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`).
//! This is typically derived via a `#[dom_struct]` (implies `#[jstraceable]`) annotation.
//! Non-JS-managed types have an empty inline `trace()` method,
//! achieved via `no_jsmanaged_fields!` or similar.
//! 3. For all fields, `Foo::trace()`
//! calls `trace()` on the field.
//! For example, for fields of type `JS<T>`, `JS<T>::trace()` calls
//! `trace_reflector()`.
//! 4. `trace_reflector()` calls `trace_object()` with the `JSObject` for the
//! reflector.
//! 5. `trace_object()` calls `JS_CallTracer()` to notify the GC, which will
//! add the object to the graph, and will trace that object as well.
//! 6. When the GC finishes tracing, it [`finalizes`](../index.html#destruction)
//! any reflectors that were not reachable.
//!
//! The `no_jsmanaged_fields!()` macro adds an empty implementation of `JSTraceable` to
//! a datatype.
use dom::bindings::js::JS;
use dom::bindings::refcounted::Trusted;
use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler};
use script_task::ScriptChan;
use cssparser::RGBA;
use encoding::types::EncodingRef;
use geom::matrix2d::Matrix2D;
use geom::rect::Rect;
use html5ever::tree_builder::QuirksMode;
use hyper::header::Headers;
use hyper::method::Method;
use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSGCTraceKind};
use js::jsval::JSVal;
use js::rust::{Cx, rt};
use layout_interface::{LayoutRPC, LayoutChan};
use libc;
use msg::constellation_msg::{PipelineId, SubpageId, WindowSizeData};
use net::image_cache_task::ImageCacheTask;
use net::storage_task::StorageType;
use script_traits::ScriptControlChan;
use script_traits::UntrustedNodeAddress;
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::ConstellationChan;
use util::smallvec::{SmallVec1, SmallVec};
use util::str::{LengthOrPercentageOrAuto};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::collections::hash_state::HashState;
use std::ffi::CString;
use std::hash::{Hash, Hasher};
use std::old_io::timer::Timer;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender};
use string_cache::{Atom, Namespace};
use style::properties::PropertyDeclarationBlock;
use url::Url;
/// A trait to allow tracing (only) DOM objects.
pub trait JSTraceable {
/// Trace `self`.
fn trace(&self, trc: *mut JSTracer);
}
impl<T: Reflectable> JSTraceable for JS<T> {
fn trace(&self, trc: *mut JSTracer) {
trace_reflector(trc, "", self.reflector());
}
}
no_jsmanaged_fields!(EncodingRef);
no_jsmanaged_fields!(Reflector);
/// Trace a `JSVal`.
pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
if!val.is_markable() {
return;
}
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing value {}", description);
JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind());
}
}
/// Trace the `JSObject` held by `reflector`.
#[allow(unrooted_must_root)]
pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
trace_object(tracer, description, reflector.get_jsobject())
}
/// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing {}", description);
JS_CallTracer(tracer, obj as *mut libc::c_void, JSGCTraceKind::JSTRACE_OBJECT);
}
}
impl<T: JSTraceable> JSTraceable for RefCell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.borrow().trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Rc<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Box<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable+Copy> JSTraceable for Cell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.get().trace(trc)
}
}
impl JSTraceable for *mut JSObject {
fn trace(&self, trc: *mut JSTracer) {
trace_object(trc, "object", *self);
}
}
impl JSTraceable for JSVal {
fn trace(&self, trc: *mut JSTracer) {
trace_jsval(trc, "val", *self);
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable> JSTraceable for Vec<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable +'static> JSTraceable for SmallVec1<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
impl<T: JSTraceable> JSTraceable for Option<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
self.as_ref().map(|e| e.trace(trc));
}
}
impl<K,V,S> JSTraceable for HashMap<K, V, S>
where K: Hash + Eq + JSTraceable,
V: JSTraceable,
S: HashState,
<S as HashState>::Hasher: Hasher,
{
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for (k, v) in self.iter() {
k.trace(trc);
v.trace(trc);
}
}
}
impl<A: JSTraceable, B: JSTraceable> JSTraceable for (A, B) {
#[inline]
fn trace(&self, trc: *mut JSTracer)
|
}
no_jsmanaged_fields!(bool, f32, f64, String, Url);
no_jsmanaged_fields!(usize, u8, u16, u32, u64);
no_jsmanaged_fields!(isize, i8, i16, i32, i64);
no_jsmanaged_fields!(Sender<T>);
no_jsmanaged_fields!(Receiver<T>);
no_jsmanaged_fields!(Rect<T>);
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan);
no_jsmanaged_fields!(Atom, Namespace, Timer);
no_jsmanaged_fields!(Trusted<T>);
no_jsmanaged_fields!(PropertyDeclarationBlock);
// These three are interdependent, if you plan to put jsmanaged data
// in one of these make sure it is propagated properly to containing structs
no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId);
no_jsmanaged_fields!(QuirksMode);
no_jsmanaged_fields!(Cx);
no_jsmanaged_fields!(rt);
no_jsmanaged_fields!(Headers, Method);
no_jsmanaged_fields!(ConstellationChan);
no_jsmanaged_fields!(LayoutChan);
no_jsmanaged_fields!(WindowProxyHandler);
no_jsmanaged_fields!(UntrustedNodeAddress);
no_jsmanaged_fields!(LengthOrPercentageOrAuto);
no_jsmanaged_fields!(RGBA);
no_jsmanaged_fields!(Matrix2D<T>);
no_jsmanaged_fields!(StorageType);
impl JSTraceable for Box<ScriptChan+Send> {
#[inline]
fn trace(&self, _trc: *mut JSTracer) {
// Do nothing
}
}
impl<'a> JSTraceable for &'a str {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl<A,B> JSTraceable for fn(A) -> B {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<ScriptListener+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<LayoutRPC+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
|
{
let (ref a, ref b) = *self;
a.trace(trc);
b.trace(trc);
}
|
identifier_body
|
trace.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/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Garbage
//! Collector. A rooted DOM object implementing the interface `Foo` is traced
//! as follows:
//!
//! 1. The GC calls `_trace` defined in `FooBinding` during the marking
//! phase. (This happens through `JSClass.trace` for non-proxy bindings, and
//! through `ProxyTraps.trace` otherwise.)
//! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`).
//! This is typically derived via a `#[dom_struct]` (implies `#[jstraceable]`) annotation.
//! Non-JS-managed types have an empty inline `trace()` method,
//! achieved via `no_jsmanaged_fields!` or similar.
//! 3. For all fields, `Foo::trace()`
//! calls `trace()` on the field.
//! For example, for fields of type `JS<T>`, `JS<T>::trace()` calls
//! `trace_reflector()`.
//! 4. `trace_reflector()` calls `trace_object()` with the `JSObject` for the
//! reflector.
//! 5. `trace_object()` calls `JS_CallTracer()` to notify the GC, which will
//! add the object to the graph, and will trace that object as well.
//! 6. When the GC finishes tracing, it [`finalizes`](../index.html#destruction)
//! any reflectors that were not reachable.
//!
//! The `no_jsmanaged_fields!()` macro adds an empty implementation of `JSTraceable` to
//! a datatype.
use dom::bindings::js::JS;
use dom::bindings::refcounted::Trusted;
use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler};
use script_task::ScriptChan;
use cssparser::RGBA;
use encoding::types::EncodingRef;
use geom::matrix2d::Matrix2D;
use geom::rect::Rect;
use html5ever::tree_builder::QuirksMode;
use hyper::header::Headers;
use hyper::method::Method;
use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSGCTraceKind};
use js::jsval::JSVal;
use js::rust::{Cx, rt};
use layout_interface::{LayoutRPC, LayoutChan};
use libc;
use msg::constellation_msg::{PipelineId, SubpageId, WindowSizeData};
use net::image_cache_task::ImageCacheTask;
use net::storage_task::StorageType;
use script_traits::ScriptControlChan;
use script_traits::UntrustedNodeAddress;
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::ConstellationChan;
use util::smallvec::{SmallVec1, SmallVec};
use util::str::{LengthOrPercentageOrAuto};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::collections::hash_state::HashState;
use std::ffi::CString;
use std::hash::{Hash, Hasher};
use std::old_io::timer::Timer;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender};
use string_cache::{Atom, Namespace};
use style::properties::PropertyDeclarationBlock;
use url::Url;
/// A trait to allow tracing (only) DOM objects.
pub trait JSTraceable {
/// Trace `self`.
fn trace(&self, trc: *mut JSTracer);
}
impl<T: Reflectable> JSTraceable for JS<T> {
fn trace(&self, trc: *mut JSTracer) {
trace_reflector(trc, "", self.reflector());
}
}
no_jsmanaged_fields!(EncodingRef);
no_jsmanaged_fields!(Reflector);
/// Trace a `JSVal`.
pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
if!val.is_markable()
|
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing value {}", description);
JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind());
}
}
/// Trace the `JSObject` held by `reflector`.
#[allow(unrooted_must_root)]
pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
trace_object(tracer, description, reflector.get_jsobject())
}
/// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing {}", description);
JS_CallTracer(tracer, obj as *mut libc::c_void, JSGCTraceKind::JSTRACE_OBJECT);
}
}
impl<T: JSTraceable> JSTraceable for RefCell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.borrow().trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Rc<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Box<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable+Copy> JSTraceable for Cell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.get().trace(trc)
}
}
impl JSTraceable for *mut JSObject {
fn trace(&self, trc: *mut JSTracer) {
trace_object(trc, "object", *self);
}
}
impl JSTraceable for JSVal {
fn trace(&self, trc: *mut JSTracer) {
trace_jsval(trc, "val", *self);
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable> JSTraceable for Vec<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable +'static> JSTraceable for SmallVec1<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
impl<T: JSTraceable> JSTraceable for Option<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
self.as_ref().map(|e| e.trace(trc));
}
}
impl<K,V,S> JSTraceable for HashMap<K, V, S>
where K: Hash + Eq + JSTraceable,
V: JSTraceable,
S: HashState,
<S as HashState>::Hasher: Hasher,
{
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for (k, v) in self.iter() {
k.trace(trc);
v.trace(trc);
}
}
}
impl<A: JSTraceable, B: JSTraceable> JSTraceable for (A, B) {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
let (ref a, ref b) = *self;
a.trace(trc);
b.trace(trc);
}
}
no_jsmanaged_fields!(bool, f32, f64, String, Url);
no_jsmanaged_fields!(usize, u8, u16, u32, u64);
no_jsmanaged_fields!(isize, i8, i16, i32, i64);
no_jsmanaged_fields!(Sender<T>);
no_jsmanaged_fields!(Receiver<T>);
no_jsmanaged_fields!(Rect<T>);
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan);
no_jsmanaged_fields!(Atom, Namespace, Timer);
no_jsmanaged_fields!(Trusted<T>);
no_jsmanaged_fields!(PropertyDeclarationBlock);
// These three are interdependent, if you plan to put jsmanaged data
// in one of these make sure it is propagated properly to containing structs
no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId);
no_jsmanaged_fields!(QuirksMode);
no_jsmanaged_fields!(Cx);
no_jsmanaged_fields!(rt);
no_jsmanaged_fields!(Headers, Method);
no_jsmanaged_fields!(ConstellationChan);
no_jsmanaged_fields!(LayoutChan);
no_jsmanaged_fields!(WindowProxyHandler);
no_jsmanaged_fields!(UntrustedNodeAddress);
no_jsmanaged_fields!(LengthOrPercentageOrAuto);
no_jsmanaged_fields!(RGBA);
no_jsmanaged_fields!(Matrix2D<T>);
no_jsmanaged_fields!(StorageType);
impl JSTraceable for Box<ScriptChan+Send> {
#[inline]
fn trace(&self, _trc: *mut JSTracer) {
// Do nothing
}
}
impl<'a> JSTraceable for &'a str {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl<A,B> JSTraceable for fn(A) -> B {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<ScriptListener+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<LayoutRPC+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
|
{
return;
}
|
conditional_block
|
trace.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/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Garbage
//! Collector. A rooted DOM object implementing the interface `Foo` is traced
//! as follows:
//!
//! 1. The GC calls `_trace` defined in `FooBinding` during the marking
//! phase. (This happens through `JSClass.trace` for non-proxy bindings, and
//! through `ProxyTraps.trace` otherwise.)
//! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`).
//! This is typically derived via a `#[dom_struct]` (implies `#[jstraceable]`) annotation.
//! Non-JS-managed types have an empty inline `trace()` method,
//! achieved via `no_jsmanaged_fields!` or similar.
//! 3. For all fields, `Foo::trace()`
//! calls `trace()` on the field.
//! For example, for fields of type `JS<T>`, `JS<T>::trace()` calls
//! `trace_reflector()`.
//! 4. `trace_reflector()` calls `trace_object()` with the `JSObject` for the
//! reflector.
//! 5. `trace_object()` calls `JS_CallTracer()` to notify the GC, which will
//! add the object to the graph, and will trace that object as well.
//! 6. When the GC finishes tracing, it [`finalizes`](../index.html#destruction)
//! any reflectors that were not reachable.
//!
//! The `no_jsmanaged_fields!()` macro adds an empty implementation of `JSTraceable` to
//! a datatype.
use dom::bindings::js::JS;
use dom::bindings::refcounted::Trusted;
use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler};
use script_task::ScriptChan;
use cssparser::RGBA;
use encoding::types::EncodingRef;
use geom::matrix2d::Matrix2D;
use geom::rect::Rect;
use html5ever::tree_builder::QuirksMode;
use hyper::header::Headers;
use hyper::method::Method;
use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSGCTraceKind};
use js::jsval::JSVal;
use js::rust::{Cx, rt};
use layout_interface::{LayoutRPC, LayoutChan};
use libc;
use msg::constellation_msg::{PipelineId, SubpageId, WindowSizeData};
use net::image_cache_task::ImageCacheTask;
use net::storage_task::StorageType;
use script_traits::ScriptControlChan;
use script_traits::UntrustedNodeAddress;
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::ConstellationChan;
use util::smallvec::{SmallVec1, SmallVec};
use util::str::{LengthOrPercentageOrAuto};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::collections::hash_state::HashState;
use std::ffi::CString;
use std::hash::{Hash, Hasher};
use std::old_io::timer::Timer;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender};
use string_cache::{Atom, Namespace};
use style::properties::PropertyDeclarationBlock;
use url::Url;
/// A trait to allow tracing (only) DOM objects.
pub trait JSTraceable {
/// Trace `self`.
fn trace(&self, trc: *mut JSTracer);
}
impl<T: Reflectable> JSTraceable for JS<T> {
fn trace(&self, trc: *mut JSTracer) {
trace_reflector(trc, "", self.reflector());
}
}
no_jsmanaged_fields!(EncodingRef);
no_jsmanaged_fields!(Reflector);
/// Trace a `JSVal`.
pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
if!val.is_markable() {
return;
}
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing value {}", description);
JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind());
}
}
/// Trace the `JSObject` held by `reflector`.
#[allow(unrooted_must_root)]
pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
trace_object(tracer, description, reflector.get_jsobject())
}
/// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing {}", description);
JS_CallTracer(tracer, obj as *mut libc::c_void, JSGCTraceKind::JSTRACE_OBJECT);
}
}
impl<T: JSTraceable> JSTraceable for RefCell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.borrow().trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Rc<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Box<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable+Copy> JSTraceable for Cell<T> {
fn
|
(&self, trc: *mut JSTracer) {
self.get().trace(trc)
}
}
impl JSTraceable for *mut JSObject {
fn trace(&self, trc: *mut JSTracer) {
trace_object(trc, "object", *self);
}
}
impl JSTraceable for JSVal {
fn trace(&self, trc: *mut JSTracer) {
trace_jsval(trc, "val", *self);
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable> JSTraceable for Vec<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable +'static> JSTraceable for SmallVec1<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
impl<T: JSTraceable> JSTraceable for Option<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
self.as_ref().map(|e| e.trace(trc));
}
}
impl<K,V,S> JSTraceable for HashMap<K, V, S>
where K: Hash + Eq + JSTraceable,
V: JSTraceable,
S: HashState,
<S as HashState>::Hasher: Hasher,
{
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for (k, v) in self.iter() {
k.trace(trc);
v.trace(trc);
}
}
}
impl<A: JSTraceable, B: JSTraceable> JSTraceable for (A, B) {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
let (ref a, ref b) = *self;
a.trace(trc);
b.trace(trc);
}
}
no_jsmanaged_fields!(bool, f32, f64, String, Url);
no_jsmanaged_fields!(usize, u8, u16, u32, u64);
no_jsmanaged_fields!(isize, i8, i16, i32, i64);
no_jsmanaged_fields!(Sender<T>);
no_jsmanaged_fields!(Receiver<T>);
no_jsmanaged_fields!(Rect<T>);
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan);
no_jsmanaged_fields!(Atom, Namespace, Timer);
no_jsmanaged_fields!(Trusted<T>);
no_jsmanaged_fields!(PropertyDeclarationBlock);
// These three are interdependent, if you plan to put jsmanaged data
// in one of these make sure it is propagated properly to containing structs
no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId);
no_jsmanaged_fields!(QuirksMode);
no_jsmanaged_fields!(Cx);
no_jsmanaged_fields!(rt);
no_jsmanaged_fields!(Headers, Method);
no_jsmanaged_fields!(ConstellationChan);
no_jsmanaged_fields!(LayoutChan);
no_jsmanaged_fields!(WindowProxyHandler);
no_jsmanaged_fields!(UntrustedNodeAddress);
no_jsmanaged_fields!(LengthOrPercentageOrAuto);
no_jsmanaged_fields!(RGBA);
no_jsmanaged_fields!(Matrix2D<T>);
no_jsmanaged_fields!(StorageType);
impl JSTraceable for Box<ScriptChan+Send> {
#[inline]
fn trace(&self, _trc: *mut JSTracer) {
// Do nothing
}
}
impl<'a> JSTraceable for &'a str {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl<A,B> JSTraceable for fn(A) -> B {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<ScriptListener+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<LayoutRPC+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
|
trace
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.