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 |
---|---|---|---|---|
last-use-in-block.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.
// Issue #1818
fn lp<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {
while false {
let r = f(s);
return (r);
} | }
fn apply<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {
fn g<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {f(s)}
g(s, |v| { let r = f(v); r })
}
pub fn main() {} | panic!(); | random_line_split |
last-use-in-block.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.
// Issue #1818
fn lp<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {
while false {
let r = f(s);
return (r);
}
panic!();
}
fn apply<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T |
pub fn main() {}
| {
fn g<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {f(s)}
g(s, |v| { let r = f(v); r })
} | identifier_body |
layout.rs | use super::{FractionalHex,Hex};
use std::f32::consts::PI;
pub struct Orientation {
f: Vec<f32>,
b: Vec<f32>,
start_angle: f32
}
impl Orientation {
pub fn new(f: Vec<f32>,b: Vec<f32>,start_angle: f32) -> Orientation {
Orientation {
f: f,
b: b,
start_angle: start_angle
}
}
pub fn pointy() -> Orientation {
Orientation::new(
vec![(3.0 as f32).sqrt(), (3.0 as f32).sqrt() / 2.0, 0.0, 3.0 / 2.0],
vec![(3.0 as f32).sqrt() / 3.0, -1.0 / 3.0, 0.0, 2.0 / 3.0],
0.5
) | Orientation::new(vec![3.0 / 2.0, 0.0, (3.0 as f32).sqrt() / 2.0, (3.0 as f32).sqrt()],
vec![2.0 / 3.0, 0.0, -1.0 / 3.0, (3.0 as f32).sqrt() / 3.0],
0.0)
}
}
pub struct Point {
pub x: f32,
pub y: f32
}
impl Point {
pub fn new(x: f32,y: f32) -> Point {
Point {
x: x,
y: y
}
}
}
pub struct Layout {
orientation: Orientation,
size: Point,
origin: Point
}
impl Layout {
pub fn new(orientation: Orientation,size: Point,origin: Point) -> Layout {
Layout {
orientation: orientation,
size: size,
origin: origin
}
}
pub fn hex_to_pixel(&self,h: Hex) -> Point {
let orient = &self.orientation;
let x = (orient.f[0] * h.x as f32 + orient.f[1] * h.y as f32 ) * &self.size.x;
let y = (orient.f[2] * h.x as f32 + orient.f[3] * h.y as f32 ) * &self.size.y;
Point::new(x + &self.origin.x,y + &self.origin.y)
}
pub fn screen_to_hex(&self,p: Point) -> FractionalHex {
let orient = &self.orientation;
let pt = Point::new((p.x - &self.origin.x) / &self.size.x,(p.y - &self.size.y));
let x: f32 = orient.b[0] * pt.x as f32 + orient.b[1] * pt.y as f32 ;
let y: f32 = orient.b[2] * pt.x as f32 + orient.b[2] * pt.y as f32 ;
FractionalHex::new(x,y,-x - y)
}
pub fn hex_corner_offset(&self,corner: i32) -> Point{
let angle = 2.0 * PI * (&self.orientation.start_angle + corner as f32) / 6.0;
Point::new(&self.size.x * angle.cos(), &self.size.y * angle.sin())
}
pub fn polygon_corners(&self,h: Hex) -> Vec<Point> {
let mut corners: Vec<Point> = Vec::new();
let center = &self.hex_to_pixel(h);
for i in 1..6 {
let offset = &self.hex_corner_offset(i);
corners.push(Point::new(center.x + offset.x,center.y + offset.y))
}
corners
}
} | }
pub fn flat() -> Orientation { | random_line_split |
layout.rs | use super::{FractionalHex,Hex};
use std::f32::consts::PI;
pub struct Orientation {
f: Vec<f32>,
b: Vec<f32>,
start_angle: f32
}
impl Orientation {
pub fn | (f: Vec<f32>,b: Vec<f32>,start_angle: f32) -> Orientation {
Orientation {
f: f,
b: b,
start_angle: start_angle
}
}
pub fn pointy() -> Orientation {
Orientation::new(
vec![(3.0 as f32).sqrt(), (3.0 as f32).sqrt() / 2.0, 0.0, 3.0 / 2.0],
vec![(3.0 as f32).sqrt() / 3.0, -1.0 / 3.0, 0.0, 2.0 / 3.0],
0.5
)
}
pub fn flat() -> Orientation {
Orientation::new(vec![3.0 / 2.0, 0.0, (3.0 as f32).sqrt() / 2.0, (3.0 as f32).sqrt()],
vec![2.0 / 3.0, 0.0, -1.0 / 3.0, (3.0 as f32).sqrt() / 3.0],
0.0)
}
}
pub struct Point {
pub x: f32,
pub y: f32
}
impl Point {
pub fn new(x: f32,y: f32) -> Point {
Point {
x: x,
y: y
}
}
}
pub struct Layout {
orientation: Orientation,
size: Point,
origin: Point
}
impl Layout {
pub fn new(orientation: Orientation,size: Point,origin: Point) -> Layout {
Layout {
orientation: orientation,
size: size,
origin: origin
}
}
pub fn hex_to_pixel(&self,h: Hex) -> Point {
let orient = &self.orientation;
let x = (orient.f[0] * h.x as f32 + orient.f[1] * h.y as f32 ) * &self.size.x;
let y = (orient.f[2] * h.x as f32 + orient.f[3] * h.y as f32 ) * &self.size.y;
Point::new(x + &self.origin.x,y + &self.origin.y)
}
pub fn screen_to_hex(&self,p: Point) -> FractionalHex {
let orient = &self.orientation;
let pt = Point::new((p.x - &self.origin.x) / &self.size.x,(p.y - &self.size.y));
let x: f32 = orient.b[0] * pt.x as f32 + orient.b[1] * pt.y as f32 ;
let y: f32 = orient.b[2] * pt.x as f32 + orient.b[2] * pt.y as f32 ;
FractionalHex::new(x,y,-x - y)
}
pub fn hex_corner_offset(&self,corner: i32) -> Point{
let angle = 2.0 * PI * (&self.orientation.start_angle + corner as f32) / 6.0;
Point::new(&self.size.x * angle.cos(), &self.size.y * angle.sin())
}
pub fn polygon_corners(&self,h: Hex) -> Vec<Point> {
let mut corners: Vec<Point> = Vec::new();
let center = &self.hex_to_pixel(h);
for i in 1..6 {
let offset = &self.hex_corner_offset(i);
corners.push(Point::new(center.x + offset.x,center.y + offset.y))
}
corners
}
}
| new | identifier_name |
maildir.rs | use std::time::Duration;
use crossbeam_channel::Sender;
use maildir::Maildir as ExtMaildir;
use serde_derive::Deserialize;
use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::de::deserialize_duration;
use crate::errors::*;
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::{I3BarWidget, State};
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MailType {
New,
Cur,
All,
}
impl MailType {
fn count_mail(&self, maildir: &ExtMaildir) -> usize {
match self {
MailType::New => maildir.count_new(),
MailType::Cur => maildir.count_cur(),
MailType::All => maildir.count_new() + maildir.count_cur(),
}
}
}
pub struct Maildir {
id: usize,
text: TextWidget,
update_interval: Duration,
inboxes: Vec<String>,
threshold_warning: usize,
threshold_critical: usize,
display_type: MailType,
}
//TODO add `format`
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct MaildirConfig {
/// Update interval in seconds
#[serde(deserialize_with = "deserialize_duration")]
pub interval: Duration,
pub inboxes: Vec<String>,
pub threshold_warning: usize,
pub threshold_critical: usize,
pub display_type: MailType,
// DEPRECATED
pub icon: bool,
}
impl Default for MaildirConfig {
fn default() -> Self {
Self {
interval: Duration::from_secs(5),
inboxes: Vec::new(),
threshold_warning: 1,
threshold_critical: 10,
display_type: MailType::New,
icon: true,
}
}
}
impl ConfigBlock for Maildir {
type Config = MaildirConfig;
fn new(
id: usize,
block_config: Self::Config,
shared_config: SharedConfig,
_tx_update_request: Sender<Task>,
) -> Result<Self> {
let widget = TextWidget::new(id, 0, shared_config).with_text("");
Ok(Maildir {
id,
update_interval: block_config.interval,
text: if block_config.icon {
widget.with_icon("mail")?
} else {
widget
},
inboxes: block_config.inboxes,
threshold_warning: block_config.threshold_warning,
threshold_critical: block_config.threshold_critical,
display_type: block_config.display_type,
})
}
}
impl Block for Maildir {
fn update(&mut self) -> Result<Option<Update>> {
let mut newmails = 0;
for inbox in &self.inboxes {
let isl: &str = &inbox[..];
let maildir = ExtMaildir::from(isl);
newmails += self.display_type.count_mail(&maildir)
}
let mut state = State::Idle;
if newmails >= self.threshold_critical {
state = State::Critical;
} else if newmails >= self.threshold_warning {
state = State::Warning;
}
self.text.set_state(state);
self.text.set_text(format!("{}", newmails));
Ok(Some(self.update_interval.into()))
}
fn view(&self) -> Vec<&dyn I3BarWidget> {
vec![&self.text]
}
fn id(&self) -> usize |
}
| {
self.id
} | identifier_body |
maildir.rs | use std::time::Duration;
use crossbeam_channel::Sender;
use maildir::Maildir as ExtMaildir;
use serde_derive::Deserialize;
use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::de::deserialize_duration;
use crate::errors::*;
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::{I3BarWidget, State};
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MailType {
New,
Cur,
All,
}
impl MailType {
fn count_mail(&self, maildir: &ExtMaildir) -> usize {
match self {
MailType::New => maildir.count_new(),
MailType::Cur => maildir.count_cur(),
MailType::All => maildir.count_new() + maildir.count_cur(),
}
}
}
pub struct Maildir {
id: usize,
text: TextWidget,
update_interval: Duration,
inboxes: Vec<String>,
threshold_warning: usize,
threshold_critical: usize,
display_type: MailType,
}
//TODO add `format`
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct MaildirConfig {
/// Update interval in seconds
#[serde(deserialize_with = "deserialize_duration")]
pub interval: Duration,
pub inboxes: Vec<String>,
pub threshold_warning: usize,
pub threshold_critical: usize,
pub display_type: MailType,
// DEPRECATED
pub icon: bool,
}
impl Default for MaildirConfig {
fn default() -> Self {
Self {
interval: Duration::from_secs(5),
inboxes: Vec::new(),
threshold_warning: 1,
threshold_critical: 10,
display_type: MailType::New,
icon: true,
}
}
}
impl ConfigBlock for Maildir {
type Config = MaildirConfig;
fn new(
id: usize,
block_config: Self::Config,
shared_config: SharedConfig,
_tx_update_request: Sender<Task>,
) -> Result<Self> {
let widget = TextWidget::new(id, 0, shared_config).with_text("");
Ok(Maildir {
id,
update_interval: block_config.interval,
text: if block_config.icon {
widget.with_icon("mail")?
} else {
widget
},
inboxes: block_config.inboxes,
threshold_warning: block_config.threshold_warning,
threshold_critical: block_config.threshold_critical,
display_type: block_config.display_type,
})
}
}
impl Block for Maildir {
fn update(&mut self) -> Result<Option<Update>> {
let mut newmails = 0;
for inbox in &self.inboxes {
let isl: &str = &inbox[..];
let maildir = ExtMaildir::from(isl);
newmails += self.display_type.count_mail(&maildir)
}
let mut state = State::Idle;
if newmails >= self.threshold_critical {
state = State::Critical;
} else if newmails >= self.threshold_warning {
state = State::Warning;
}
self.text.set_state(state);
self.text.set_text(format!("{}", newmails));
Ok(Some(self.update_interval.into()))
}
fn | (&self) -> Vec<&dyn I3BarWidget> {
vec![&self.text]
}
fn id(&self) -> usize {
self.id
}
}
| view | identifier_name |
maildir.rs | use std::time::Duration;
use crossbeam_channel::Sender;
use maildir::Maildir as ExtMaildir;
use serde_derive::Deserialize;
use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::de::deserialize_duration;
use crate::errors::*;
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::{I3BarWidget, State};
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MailType {
New,
Cur,
All,
}
impl MailType {
fn count_mail(&self, maildir: &ExtMaildir) -> usize {
match self {
MailType::New => maildir.count_new(),
MailType::Cur => maildir.count_cur(),
MailType::All => maildir.count_new() + maildir.count_cur(),
}
}
}
pub struct Maildir {
id: usize,
text: TextWidget,
update_interval: Duration,
inboxes: Vec<String>,
threshold_warning: usize, | display_type: MailType,
}
//TODO add `format`
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct MaildirConfig {
/// Update interval in seconds
#[serde(deserialize_with = "deserialize_duration")]
pub interval: Duration,
pub inboxes: Vec<String>,
pub threshold_warning: usize,
pub threshold_critical: usize,
pub display_type: MailType,
// DEPRECATED
pub icon: bool,
}
impl Default for MaildirConfig {
fn default() -> Self {
Self {
interval: Duration::from_secs(5),
inboxes: Vec::new(),
threshold_warning: 1,
threshold_critical: 10,
display_type: MailType::New,
icon: true,
}
}
}
impl ConfigBlock for Maildir {
type Config = MaildirConfig;
fn new(
id: usize,
block_config: Self::Config,
shared_config: SharedConfig,
_tx_update_request: Sender<Task>,
) -> Result<Self> {
let widget = TextWidget::new(id, 0, shared_config).with_text("");
Ok(Maildir {
id,
update_interval: block_config.interval,
text: if block_config.icon {
widget.with_icon("mail")?
} else {
widget
},
inboxes: block_config.inboxes,
threshold_warning: block_config.threshold_warning,
threshold_critical: block_config.threshold_critical,
display_type: block_config.display_type,
})
}
}
impl Block for Maildir {
fn update(&mut self) -> Result<Option<Update>> {
let mut newmails = 0;
for inbox in &self.inboxes {
let isl: &str = &inbox[..];
let maildir = ExtMaildir::from(isl);
newmails += self.display_type.count_mail(&maildir)
}
let mut state = State::Idle;
if newmails >= self.threshold_critical {
state = State::Critical;
} else if newmails >= self.threshold_warning {
state = State::Warning;
}
self.text.set_state(state);
self.text.set_text(format!("{}", newmails));
Ok(Some(self.update_interval.into()))
}
fn view(&self) -> Vec<&dyn I3BarWidget> {
vec![&self.text]
}
fn id(&self) -> usize {
self.id
}
} | threshold_critical: usize, | random_line_split |
maildir.rs | use std::time::Duration;
use crossbeam_channel::Sender;
use maildir::Maildir as ExtMaildir;
use serde_derive::Deserialize;
use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::de::deserialize_duration;
use crate::errors::*;
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::{I3BarWidget, State};
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MailType {
New,
Cur,
All,
}
impl MailType {
fn count_mail(&self, maildir: &ExtMaildir) -> usize {
match self {
MailType::New => maildir.count_new(),
MailType::Cur => maildir.count_cur(),
MailType::All => maildir.count_new() + maildir.count_cur(),
}
}
}
pub struct Maildir {
id: usize,
text: TextWidget,
update_interval: Duration,
inboxes: Vec<String>,
threshold_warning: usize,
threshold_critical: usize,
display_type: MailType,
}
//TODO add `format`
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct MaildirConfig {
/// Update interval in seconds
#[serde(deserialize_with = "deserialize_duration")]
pub interval: Duration,
pub inboxes: Vec<String>,
pub threshold_warning: usize,
pub threshold_critical: usize,
pub display_type: MailType,
// DEPRECATED
pub icon: bool,
}
impl Default for MaildirConfig {
fn default() -> Self {
Self {
interval: Duration::from_secs(5),
inboxes: Vec::new(),
threshold_warning: 1,
threshold_critical: 10,
display_type: MailType::New,
icon: true,
}
}
}
impl ConfigBlock for Maildir {
type Config = MaildirConfig;
fn new(
id: usize,
block_config: Self::Config,
shared_config: SharedConfig,
_tx_update_request: Sender<Task>,
) -> Result<Self> {
let widget = TextWidget::new(id, 0, shared_config).with_text("");
Ok(Maildir {
id,
update_interval: block_config.interval,
text: if block_config.icon {
widget.with_icon("mail")?
} else | ,
inboxes: block_config.inboxes,
threshold_warning: block_config.threshold_warning,
threshold_critical: block_config.threshold_critical,
display_type: block_config.display_type,
})
}
}
impl Block for Maildir {
fn update(&mut self) -> Result<Option<Update>> {
let mut newmails = 0;
for inbox in &self.inboxes {
let isl: &str = &inbox[..];
let maildir = ExtMaildir::from(isl);
newmails += self.display_type.count_mail(&maildir)
}
let mut state = State::Idle;
if newmails >= self.threshold_critical {
state = State::Critical;
} else if newmails >= self.threshold_warning {
state = State::Warning;
}
self.text.set_state(state);
self.text.set_text(format!("{}", newmails));
Ok(Some(self.update_interval.into()))
}
fn view(&self) -> Vec<&dyn I3BarWidget> {
vec![&self.text]
}
fn id(&self) -> usize {
self.id
}
}
| {
widget
} | conditional_block |
main.rs | #![feature(bool_to_option)]
use std::path::Path;
use log::*;
use simplelog::*;
use std::time::{Instant};
use clap::{Arg, App};
mod checkloc;
use checkloc::checkloc;
mod average;
use average::average_all_images;
#[macro_use] extern crate lalrpop_util;
fn | () {
CombinedLogger::init(
vec![
TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed),
]
).unwrap();
let mut app = App::new("krtools")
.version("1.0")
.author("Pedro M. <[email protected]>")
.about("Does things the KR way")
.subcommand(App::new("average").arg(Arg::new("image_directory").required(true)))
.subcommand(App::new("checkloc").arg(Arg::new("pdx_directory").required(true)))
.subcommand(App::new("styletransfer").arg(Arg::new("style_file").required(true)).arg(Arg::new("apply_file").required(true)));
let matches = app.to_owned().get_matches();
let start = Instant::now();
match matches.subcommand() {
Some(("average", args)) => {
args.value_of("image_directory").and_then(|e| {
let path = Path::new(e);
average_all_images(path);
Some(e)
});
}
Some(("checkloc", args)) => {
args.value_of("pdx_directory").and_then(|e| {
let path = Path::new(e);
checkloc(path);
Some(e)
});
}
_ => {
error!(target: "kr_style_transfer", "Unknown or unimplemented subcommand");
app.print_long_help();
}
}
info!(target: "kr_style_transfer", "Finished in {:?} seconds", start.elapsed().as_secs());
}
| main | identifier_name |
main.rs | #![feature(bool_to_option)]
use std::path::Path;
use log::*;
use simplelog::*;
use std::time::{Instant};
use clap::{Arg, App};
mod checkloc;
use checkloc::checkloc;
mod average;
use average::average_all_images;
#[macro_use] extern crate lalrpop_util;
fn main() {
CombinedLogger::init(
vec![
TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed),
]
).unwrap();
let mut app = App::new("krtools")
.version("1.0")
.author("Pedro M. <[email protected]>")
.about("Does things the KR way")
.subcommand(App::new("average").arg(Arg::new("image_directory").required(true)))
.subcommand(App::new("checkloc").arg(Arg::new("pdx_directory").required(true)))
.subcommand(App::new("styletransfer").arg(Arg::new("style_file").required(true)).arg(Arg::new("apply_file").required(true)));
let matches = app.to_owned().get_matches();
let start = Instant::now();
match matches.subcommand() {
Some(("average", args)) => {
args.value_of("image_directory").and_then(|e| {
let path = Path::new(e);
average_all_images(path);
Some(e)
});
}
Some(("checkloc", args)) => {
args.value_of("pdx_directory").and_then(|e| {
let path = Path::new(e);
checkloc(path);
Some(e)
});
}
_ => |
}
info!(target: "kr_style_transfer", "Finished in {:?} seconds", start.elapsed().as_secs());
}
| {
error!(target: "kr_style_transfer", "Unknown or unimplemented subcommand");
app.print_long_help();
} | conditional_block |
main.rs | #![feature(bool_to_option)]
use std::path::Path;
use log::*;
use simplelog::*;
use std::time::{Instant};
use clap::{Arg, App};
mod checkloc;
use checkloc::checkloc;
mod average;
use average::average_all_images;
#[macro_use] extern crate lalrpop_util;
fn main() | let path = Path::new(e);
average_all_images(path);
Some(e)
});
}
Some(("checkloc", args)) => {
args.value_of("pdx_directory").and_then(|e| {
let path = Path::new(e);
checkloc(path);
Some(e)
});
}
_ => {
error!(target: "kr_style_transfer", "Unknown or unimplemented subcommand");
app.print_long_help();
}
}
info!(target: "kr_style_transfer", "Finished in {:?} seconds", start.elapsed().as_secs());
}
| {
CombinedLogger::init(
vec![
TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed),
]
).unwrap();
let mut app = App::new("krtools")
.version("1.0")
.author("Pedro M. <[email protected]>")
.about("Does things the KR way")
.subcommand(App::new("average").arg(Arg::new("image_directory").required(true)))
.subcommand(App::new("checkloc").arg(Arg::new("pdx_directory").required(true)))
.subcommand(App::new("styletransfer").arg(Arg::new("style_file").required(true)).arg(Arg::new("apply_file").required(true)));
let matches = app.to_owned().get_matches();
let start = Instant::now();
match matches.subcommand() {
Some(("average", args)) => {
args.value_of("image_directory").and_then(|e| { | identifier_body |
main.rs | #![feature(bool_to_option)]
use std::path::Path;
use log::*;
use simplelog::*;
use std::time::{Instant};
use clap::{Arg, App};
mod checkloc;
use checkloc::checkloc;
mod average;
use average::average_all_images;
#[macro_use] extern crate lalrpop_util;
fn main() {
CombinedLogger::init(
vec![
TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed),
]
).unwrap();
let mut app = App::new("krtools")
.version("1.0")
.author("Pedro M. <[email protected]>")
.about("Does things the KR way")
.subcommand(App::new("average").arg(Arg::new("image_directory").required(true)))
.subcommand(App::new("checkloc").arg(Arg::new("pdx_directory").required(true)))
.subcommand(App::new("styletransfer").arg(Arg::new("style_file").required(true)).arg(Arg::new("apply_file").required(true)));
let matches = app.to_owned().get_matches();
let start = Instant::now();
match matches.subcommand() {
Some(("average", args)) => {
args.value_of("image_directory").and_then(|e| {
let path = Path::new(e);
average_all_images(path);
Some(e)
});
}
Some(("checkloc", args)) => {
args.value_of("pdx_directory").and_then(|e| {
let path = Path::new(e);
checkloc(path);
Some(e)
});
} | }
info!(target: "kr_style_transfer", "Finished in {:?} seconds", start.elapsed().as_secs());
} | _ => {
error!(target: "kr_style_transfer", "Unknown or unimplemented subcommand");
app.print_long_help();
} | random_line_split |
diagnostic.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.
use codemap::{Pos, Span};
use codemap;
use std::io;
use std::local_data;
use extra::term;
pub trait Emitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub trait handler {
fn fatal(@mut self, msg: &str) ->!;
fn err(@mut self, msg: &str);
fn bump_err_count(@mut self);
fn err_count(@mut self) -> uint;
fn has_errors(@mut self) -> bool;
fn abort_if_errors(@mut self);
fn warn(@mut self, msg: &str);
fn note(@mut self, msg: &str);
// used to indicate a bug in the compiler:
fn bug(@mut self, msg: &str) ->!;
fn unimpl(@mut self, msg: &str) ->!;
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>, |
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub trait span_handler {
fn span_fatal(@mut self, sp: Span, msg: &str) ->!;
fn span_err(@mut self, sp: Span, msg: &str);
fn span_warn(@mut self, sp: Span, msg: &str);
fn span_note(@mut self, sp: Span, msg: &str);
fn span_bug(@mut self, sp: Span, msg: &str) ->!;
fn span_unimpl(@mut self, sp: Span, msg: &str) ->!;
fn handler(@mut self) -> @mut handler;
}
struct HandlerT {
err_count: uint,
emit: @Emitter,
}
struct CodemapT {
handler: @mut handler,
cm: @codemap::CodeMap,
}
impl span_handler for CodemapT {
fn span_fatal(@mut self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((self.cm, sp)), msg, fatal);
fail!();
}
fn span_err(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, error);
self.handler.bump_err_count();
}
fn span_warn(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, warning);
}
fn span_note(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, note);
}
fn span_bug(@mut self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
fn span_unimpl(@mut self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
fn handler(@mut self) -> @mut handler {
self.handler
}
}
impl handler for HandlerT {
fn fatal(@mut self, msg: &str) ->! {
self.emit.emit(None, msg, fatal);
fail!();
}
fn err(@mut self, msg: &str) {
self.emit.emit(None, msg, error);
self.bump_err_count();
}
fn bump_err_count(@mut self) {
self.err_count += 1u;
}
fn err_count(@mut self) -> uint {
self.err_count
}
fn has_errors(@mut self) -> bool {
self.err_count > 0u
}
fn abort_if_errors(@mut self) {
let s;
match self.err_count {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = fmt!("aborting due to %u previous errors",
self.err_count);
}
}
self.fatal(s);
}
fn warn(@mut self, msg: &str) {
self.emit.emit(None, msg, warning);
}
fn note(@mut self, msg: &str) {
self.emit.emit(None, msg, note);
}
fn bug(@mut self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
fn unimpl(@mut self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
fmt!("internal compiler error: %s", msg)
}
pub fn mk_span_handler(handler: @mut handler, cm: @codemap::CodeMap)
-> @mut span_handler {
@mut CodemapT {
handler: handler,
cm: cm,
} as @mut span_handler
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @mut handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@mut HandlerT {
err_count: 0,
emit: emit,
} as @mut handler
}
#[deriving(Eq)]
pub enum level {
fatal,
error,
warning,
note,
}
fn diagnosticstr(lvl: level) -> ~str {
match lvl {
fatal => ~"error",
error => ~"error",
warning => ~"warning",
note => ~"note"
}
}
fn diagnosticcolor(lvl: level) -> term::color::Color {
match lvl {
fatal => term::color::BRIGHT_RED,
error => term::color::BRIGHT_RED,
warning => term::color::BRIGHT_YELLOW,
note => term::color::BRIGHT_GREEN
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: @Option<term::Terminal>)
let stderr = io::stderr();
if stderr.get_type() == io::Screen {
let t = match local_data::get(tls_terminal, |v| v.map_move(|k| *k)) {
None => {
let t = term::Terminal::new(stderr);
let tls = @match t {
Ok(t) => Some(t),
Err(_) => None
};
local_data::set(tls_terminal, tls);
&*tls
}
Some(tls) => &*tls
};
match t {
&Some(ref term) => {
term.attr(color);
stderr.write_str(msg);
term.reset();
},
_ => stderr.write_str(msg)
}
} else {
stderr.write_str(msg);
}
}
fn print_diagnostic(topic: &str, lvl: level, msg: &str) {
let stderr = io::stderr();
if!topic.is_empty() {
stderr.write_str(fmt!("%s ", topic));
}
print_maybe_styled(fmt!("%s: ", diagnosticstr(lvl)),
term::attr::ForegroundColor(diagnosticcolor(lvl)));
print_maybe_styled(fmt!("%s\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: @codemap::CodeMap,
sp: Span,
lvl: level,
lines: @codemap::FileLines) {
let fm = lines.file;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = /* FIXME (#2543) */ lines.lines.clone();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines).to_owned();
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
io::stderr().write_str(fmt!("%s:%u ", fm.name, *line + 1u));
let s = fm.get_line(*line as int) + "\n";
io::stderr().write_str(s);
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = fmt!("%s:%u ", fm.name, last_line + 1u);
let mut indent = s.len();
let mut out = ~"";
while indent > 0u {
out.push_char(' ');
indent -= 1u;
}
out.push_str("...\n");
io::stderr().write_str(out);
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
do skip.times() {
s.push_char(' ');
}
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
io::stderr().write_str(s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
do num_squigglies.times() {
s.push_char('~')
}
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(diagnosticcolor(lvl)));
}
}
fn print_macro_backtrace(cm: @codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.map_default(~"", |span| cm.span_to_str(*span));
print_diagnostic(ss, note,
fmt!("in expansion of %s!", ei.callee.name));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(diag: @mut span_handler,
opt: Option<T>,
msg: &fn() -> ~str) -> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
} | msg: &str,
lvl: level);
} | random_line_split |
diagnostic.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.
use codemap::{Pos, Span};
use codemap;
use std::io;
use std::local_data;
use extra::term;
pub trait Emitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub trait handler {
fn fatal(@mut self, msg: &str) ->!;
fn err(@mut self, msg: &str);
fn bump_err_count(@mut self);
fn err_count(@mut self) -> uint;
fn has_errors(@mut self) -> bool;
fn abort_if_errors(@mut self);
fn warn(@mut self, msg: &str);
fn note(@mut self, msg: &str);
// used to indicate a bug in the compiler:
fn bug(@mut self, msg: &str) ->!;
fn unimpl(@mut self, msg: &str) ->!;
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub trait span_handler {
fn span_fatal(@mut self, sp: Span, msg: &str) ->!;
fn span_err(@mut self, sp: Span, msg: &str);
fn span_warn(@mut self, sp: Span, msg: &str);
fn span_note(@mut self, sp: Span, msg: &str);
fn span_bug(@mut self, sp: Span, msg: &str) ->!;
fn span_unimpl(@mut self, sp: Span, msg: &str) ->!;
fn handler(@mut self) -> @mut handler;
}
struct HandlerT {
err_count: uint,
emit: @Emitter,
}
struct CodemapT {
handler: @mut handler,
cm: @codemap::CodeMap,
}
impl span_handler for CodemapT {
fn span_fatal(@mut self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((self.cm, sp)), msg, fatal);
fail!();
}
fn span_err(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, error);
self.handler.bump_err_count();
}
fn span_warn(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, warning);
}
fn span_note(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, note);
}
fn span_bug(@mut self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
fn span_unimpl(@mut self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
fn handler(@mut self) -> @mut handler {
self.handler
}
}
impl handler for HandlerT {
fn fatal(@mut self, msg: &str) ->! {
self.emit.emit(None, msg, fatal);
fail!();
}
fn err(@mut self, msg: &str) {
self.emit.emit(None, msg, error);
self.bump_err_count();
}
fn bump_err_count(@mut self) {
self.err_count += 1u;
}
fn err_count(@mut self) -> uint {
self.err_count
}
fn has_errors(@mut self) -> bool {
self.err_count > 0u
}
fn abort_if_errors(@mut self) {
let s;
match self.err_count {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = fmt!("aborting due to %u previous errors",
self.err_count);
}
}
self.fatal(s);
}
fn warn(@mut self, msg: &str) {
self.emit.emit(None, msg, warning);
}
fn | (@mut self, msg: &str) {
self.emit.emit(None, msg, note);
}
fn bug(@mut self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
fn unimpl(@mut self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
fmt!("internal compiler error: %s", msg)
}
pub fn mk_span_handler(handler: @mut handler, cm: @codemap::CodeMap)
-> @mut span_handler {
@mut CodemapT {
handler: handler,
cm: cm,
} as @mut span_handler
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @mut handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@mut HandlerT {
err_count: 0,
emit: emit,
} as @mut handler
}
#[deriving(Eq)]
pub enum level {
fatal,
error,
warning,
note,
}
fn diagnosticstr(lvl: level) -> ~str {
match lvl {
fatal => ~"error",
error => ~"error",
warning => ~"warning",
note => ~"note"
}
}
fn diagnosticcolor(lvl: level) -> term::color::Color {
match lvl {
fatal => term::color::BRIGHT_RED,
error => term::color::BRIGHT_RED,
warning => term::color::BRIGHT_YELLOW,
note => term::color::BRIGHT_GREEN
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: @Option<term::Terminal>)
let stderr = io::stderr();
if stderr.get_type() == io::Screen {
let t = match local_data::get(tls_terminal, |v| v.map_move(|k| *k)) {
None => {
let t = term::Terminal::new(stderr);
let tls = @match t {
Ok(t) => Some(t),
Err(_) => None
};
local_data::set(tls_terminal, tls);
&*tls
}
Some(tls) => &*tls
};
match t {
&Some(ref term) => {
term.attr(color);
stderr.write_str(msg);
term.reset();
},
_ => stderr.write_str(msg)
}
} else {
stderr.write_str(msg);
}
}
fn print_diagnostic(topic: &str, lvl: level, msg: &str) {
let stderr = io::stderr();
if!topic.is_empty() {
stderr.write_str(fmt!("%s ", topic));
}
print_maybe_styled(fmt!("%s: ", diagnosticstr(lvl)),
term::attr::ForegroundColor(diagnosticcolor(lvl)));
print_maybe_styled(fmt!("%s\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: @codemap::CodeMap,
sp: Span,
lvl: level,
lines: @codemap::FileLines) {
let fm = lines.file;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = /* FIXME (#2543) */ lines.lines.clone();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines).to_owned();
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
io::stderr().write_str(fmt!("%s:%u ", fm.name, *line + 1u));
let s = fm.get_line(*line as int) + "\n";
io::stderr().write_str(s);
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = fmt!("%s:%u ", fm.name, last_line + 1u);
let mut indent = s.len();
let mut out = ~"";
while indent > 0u {
out.push_char(' ');
indent -= 1u;
}
out.push_str("...\n");
io::stderr().write_str(out);
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
do skip.times() {
s.push_char(' ');
}
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
io::stderr().write_str(s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
do num_squigglies.times() {
s.push_char('~')
}
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(diagnosticcolor(lvl)));
}
}
fn print_macro_backtrace(cm: @codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.map_default(~"", |span| cm.span_to_str(*span));
print_diagnostic(ss, note,
fmt!("in expansion of %s!", ei.callee.name));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(diag: @mut span_handler,
opt: Option<T>,
msg: &fn() -> ~str) -> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
}
| note | identifier_name |
diagnostic.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.
use codemap::{Pos, Span};
use codemap;
use std::io;
use std::local_data;
use extra::term;
pub trait Emitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub trait handler {
fn fatal(@mut self, msg: &str) ->!;
fn err(@mut self, msg: &str);
fn bump_err_count(@mut self);
fn err_count(@mut self) -> uint;
fn has_errors(@mut self) -> bool;
fn abort_if_errors(@mut self);
fn warn(@mut self, msg: &str);
fn note(@mut self, msg: &str);
// used to indicate a bug in the compiler:
fn bug(@mut self, msg: &str) ->!;
fn unimpl(@mut self, msg: &str) ->!;
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub trait span_handler {
fn span_fatal(@mut self, sp: Span, msg: &str) ->!;
fn span_err(@mut self, sp: Span, msg: &str);
fn span_warn(@mut self, sp: Span, msg: &str);
fn span_note(@mut self, sp: Span, msg: &str);
fn span_bug(@mut self, sp: Span, msg: &str) ->!;
fn span_unimpl(@mut self, sp: Span, msg: &str) ->!;
fn handler(@mut self) -> @mut handler;
}
struct HandlerT {
err_count: uint,
emit: @Emitter,
}
struct CodemapT {
handler: @mut handler,
cm: @codemap::CodeMap,
}
impl span_handler for CodemapT {
fn span_fatal(@mut self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((self.cm, sp)), msg, fatal);
fail!();
}
fn span_err(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, error);
self.handler.bump_err_count();
}
fn span_warn(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, warning);
}
fn span_note(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, note);
}
fn span_bug(@mut self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
fn span_unimpl(@mut self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
fn handler(@mut self) -> @mut handler {
self.handler
}
}
impl handler for HandlerT {
fn fatal(@mut self, msg: &str) ->! {
self.emit.emit(None, msg, fatal);
fail!();
}
fn err(@mut self, msg: &str) {
self.emit.emit(None, msg, error);
self.bump_err_count();
}
fn bump_err_count(@mut self) {
self.err_count += 1u;
}
fn err_count(@mut self) -> uint {
self.err_count
}
fn has_errors(@mut self) -> bool {
self.err_count > 0u
}
fn abort_if_errors(@mut self) {
let s;
match self.err_count {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = fmt!("aborting due to %u previous errors",
self.err_count);
}
}
self.fatal(s);
}
fn warn(@mut self, msg: &str) {
self.emit.emit(None, msg, warning);
}
fn note(@mut self, msg: &str) {
self.emit.emit(None, msg, note);
}
fn bug(@mut self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
fn unimpl(@mut self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
fmt!("internal compiler error: %s", msg)
}
pub fn mk_span_handler(handler: @mut handler, cm: @codemap::CodeMap)
-> @mut span_handler {
@mut CodemapT {
handler: handler,
cm: cm,
} as @mut span_handler
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @mut handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@mut HandlerT {
err_count: 0,
emit: emit,
} as @mut handler
}
#[deriving(Eq)]
pub enum level {
fatal,
error,
warning,
note,
}
fn diagnosticstr(lvl: level) -> ~str {
match lvl {
fatal => ~"error",
error => ~"error",
warning => ~"warning",
note => ~"note"
}
}
fn diagnosticcolor(lvl: level) -> term::color::Color {
match lvl {
fatal => term::color::BRIGHT_RED,
error => term::color::BRIGHT_RED,
warning => term::color::BRIGHT_YELLOW,
note => term::color::BRIGHT_GREEN
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) | &Some(ref term) => {
term.attr(color);
stderr.write_str(msg);
term.reset();
},
_ => stderr.write_str(msg)
}
} else {
stderr.write_str(msg);
}
}
fn print_diagnostic(topic: &str, lvl: level, msg: &str) {
let stderr = io::stderr();
if!topic.is_empty() {
stderr.write_str(fmt!("%s ", topic));
}
print_maybe_styled(fmt!("%s: ", diagnosticstr(lvl)),
term::attr::ForegroundColor(diagnosticcolor(lvl)));
print_maybe_styled(fmt!("%s\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: @codemap::CodeMap,
sp: Span,
lvl: level,
lines: @codemap::FileLines) {
let fm = lines.file;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = /* FIXME (#2543) */ lines.lines.clone();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines).to_owned();
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
io::stderr().write_str(fmt!("%s:%u ", fm.name, *line + 1u));
let s = fm.get_line(*line as int) + "\n";
io::stderr().write_str(s);
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = fmt!("%s:%u ", fm.name, last_line + 1u);
let mut indent = s.len();
let mut out = ~"";
while indent > 0u {
out.push_char(' ');
indent -= 1u;
}
out.push_str("...\n");
io::stderr().write_str(out);
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
do skip.times() {
s.push_char(' ');
}
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
io::stderr().write_str(s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
do num_squigglies.times() {
s.push_char('~')
}
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(diagnosticcolor(lvl)));
}
}
fn print_macro_backtrace(cm: @codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.map_default(~"", |span| cm.span_to_str(*span));
print_diagnostic(ss, note,
fmt!("in expansion of %s!", ei.callee.name));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(diag: @mut span_handler,
opt: Option<T>,
msg: &fn() -> ~str) -> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
}
| {
local_data_key!(tls_terminal: @Option<term::Terminal>)
let stderr = io::stderr();
if stderr.get_type() == io::Screen {
let t = match local_data::get(tls_terminal, |v| v.map_move(|k| *k)) {
None => {
let t = term::Terminal::new(stderr);
let tls = @match t {
Ok(t) => Some(t),
Err(_) => None
};
local_data::set(tls_terminal, tls);
&*tls
}
Some(tls) => &*tls
};
match t { | identifier_body |
borrowck-borrow-of-mut-base-ptr-safe.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that freezing an `&mut` pointer while referent is
// frozen is legal.
//
// Example from src/librustc_borrowck/borrowck/README.md
// pretty-expanded FIXME #23616
fn foo<'a>(mut t0: &'a mut isize,
mut t1: &'a mut isize) {
let p: &isize = &*t0; // Freezes `*t0`
let mut t2 = &t0;
let q: &isize = &**t2; // Freezes `*t0`, but that's ok...
let r: &isize = &*t0; //...after all, could do same thing directly.
}
pub fn | () {
}
| main | identifier_name |
borrowck-borrow-of-mut-base-ptr-safe.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that freezing an `&mut` pointer while referent is
// frozen is legal.
//
// Example from src/librustc_borrowck/borrowck/README.md | // pretty-expanded FIXME #23616
fn foo<'a>(mut t0: &'a mut isize,
mut t1: &'a mut isize) {
let p: &isize = &*t0; // Freezes `*t0`
let mut t2 = &t0;
let q: &isize = &**t2; // Freezes `*t0`, but that's ok...
let r: &isize = &*t0; //...after all, could do same thing directly.
}
pub fn main() {
} | random_line_split |
|
borrowck-borrow-of-mut-base-ptr-safe.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that freezing an `&mut` pointer while referent is
// frozen is legal.
//
// Example from src/librustc_borrowck/borrowck/README.md
// pretty-expanded FIXME #23616
fn foo<'a>(mut t0: &'a mut isize,
mut t1: &'a mut isize) {
let p: &isize = &*t0; // Freezes `*t0`
let mut t2 = &t0;
let q: &isize = &**t2; // Freezes `*t0`, but that's ok...
let r: &isize = &*t0; //...after all, could do same thing directly.
}
pub fn main() | {
} | identifier_body |
|
content_length.rs | use std::fmt;
use header::{Header, Raw, parsing};
/// `Content-Length` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)
///
/// When a message does not have a `Transfer-Encoding` header field, a
/// Content-Length header field can provide the anticipated size, as a
/// decimal number of octets, for a potential payload body. For messages
/// that do include a payload body, the Content-Length field-value
/// provides the framing information necessary for determining where the
/// body (and message) ends. For messages that do not include a payload
/// body, the Content-Length indicates the size of the selected
/// representation.
///
/// # ABNF
/// ```plain
/// Content-Length = 1*DIGIT
/// ```
///
/// # Example values
/// * `3495`
///
/// # Example | /// headers.set(ContentLength(1024u64));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContentLength(pub u64);
//static NAME: &'static str = "Content-Length";
impl Header for ContentLength {
#[inline]
fn header_name() -> &'static str {
static NAME: &'static str = "Content-Length";
NAME
}
fn parse_header(raw: &Raw) -> ::Result<ContentLength> {
// If multiple Content-Length headers were sent, everything can still
// be alright if they all contain the same value, and all parse
// correctly. If not, then it's an error.
raw.iter()
.map(parsing::from_raw_str)
.fold(None, |prev, x| {
match (prev, x) {
(None, x) => Some(x),
(e @ Some(Err(_)), _ ) => e,
(Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
_ => Some(Err(::Error::Header)),
}
})
.unwrap_or(Err(::Error::Header))
.map(ContentLength)
}
#[inline]
fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
f.fmt_line(self)
}
}
impl fmt::Display for ContentLength {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
__hyper__deref!(ContentLength => u64);
__hyper__tm!(ContentLength, tests {
// Testcase from RFC
test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
test_header!(test_invalid, vec![b"34v95"], None);
// Can't use the test_header macro because "5, 5" gets cleaned to "5".
#[test]
fn test_duplicates() {
let parsed = HeaderField::parse_header(&vec![b"5".to_vec(),
b"5".to_vec()].into()).unwrap();
assert_eq!(parsed, HeaderField(5));
assert_eq!(format!("{}", parsed), "5");
}
test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
});
bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] }); | /// ```
/// use hyper::header::{Headers, ContentLength};
///
/// let mut headers = Headers::new(); | random_line_split |
content_length.rs | use std::fmt;
use header::{Header, Raw, parsing};
/// `Content-Length` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)
///
/// When a message does not have a `Transfer-Encoding` header field, a
/// Content-Length header field can provide the anticipated size, as a
/// decimal number of octets, for a potential payload body. For messages
/// that do include a payload body, the Content-Length field-value
/// provides the framing information necessary for determining where the
/// body (and message) ends. For messages that do not include a payload
/// body, the Content-Length indicates the size of the selected
/// representation.
///
/// # ABNF
/// ```plain
/// Content-Length = 1*DIGIT
/// ```
///
/// # Example values
/// * `3495`
///
/// # Example
/// ```
/// use hyper::header::{Headers, ContentLength};
///
/// let mut headers = Headers::new();
/// headers.set(ContentLength(1024u64));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContentLength(pub u64);
//static NAME: &'static str = "Content-Length";
impl Header for ContentLength {
#[inline]
fn header_name() -> &'static str |
fn parse_header(raw: &Raw) -> ::Result<ContentLength> {
// If multiple Content-Length headers were sent, everything can still
// be alright if they all contain the same value, and all parse
// correctly. If not, then it's an error.
raw.iter()
.map(parsing::from_raw_str)
.fold(None, |prev, x| {
match (prev, x) {
(None, x) => Some(x),
(e @ Some(Err(_)), _ ) => e,
(Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
_ => Some(Err(::Error::Header)),
}
})
.unwrap_or(Err(::Error::Header))
.map(ContentLength)
}
#[inline]
fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
f.fmt_line(self)
}
}
impl fmt::Display for ContentLength {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
__hyper__deref!(ContentLength => u64);
__hyper__tm!(ContentLength, tests {
// Testcase from RFC
test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
test_header!(test_invalid, vec![b"34v95"], None);
// Can't use the test_header macro because "5, 5" gets cleaned to "5".
#[test]
fn test_duplicates() {
let parsed = HeaderField::parse_header(&vec![b"5".to_vec(),
b"5".to_vec()].into()).unwrap();
assert_eq!(parsed, HeaderField(5));
assert_eq!(format!("{}", parsed), "5");
}
test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
});
bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] });
| {
static NAME: &'static str = "Content-Length";
NAME
} | identifier_body |
content_length.rs | use std::fmt;
use header::{Header, Raw, parsing};
/// `Content-Length` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)
///
/// When a message does not have a `Transfer-Encoding` header field, a
/// Content-Length header field can provide the anticipated size, as a
/// decimal number of octets, for a potential payload body. For messages
/// that do include a payload body, the Content-Length field-value
/// provides the framing information necessary for determining where the
/// body (and message) ends. For messages that do not include a payload
/// body, the Content-Length indicates the size of the selected
/// representation.
///
/// # ABNF
/// ```plain
/// Content-Length = 1*DIGIT
/// ```
///
/// # Example values
/// * `3495`
///
/// # Example
/// ```
/// use hyper::header::{Headers, ContentLength};
///
/// let mut headers = Headers::new();
/// headers.set(ContentLength(1024u64));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContentLength(pub u64);
//static NAME: &'static str = "Content-Length";
impl Header for ContentLength {
#[inline]
fn header_name() -> &'static str {
static NAME: &'static str = "Content-Length";
NAME
}
fn parse_header(raw: &Raw) -> ::Result<ContentLength> {
// If multiple Content-Length headers were sent, everything can still
// be alright if they all contain the same value, and all parse
// correctly. If not, then it's an error.
raw.iter()
.map(parsing::from_raw_str)
.fold(None, |prev, x| {
match (prev, x) {
(None, x) => Some(x),
(e @ Some(Err(_)), _ ) => e,
(Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
_ => Some(Err(::Error::Header)),
}
})
.unwrap_or(Err(::Error::Header))
.map(ContentLength)
}
#[inline]
fn | (&self, f: &mut ::header::Formatter) -> fmt::Result {
f.fmt_line(self)
}
}
impl fmt::Display for ContentLength {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
__hyper__deref!(ContentLength => u64);
__hyper__tm!(ContentLength, tests {
// Testcase from RFC
test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
test_header!(test_invalid, vec![b"34v95"], None);
// Can't use the test_header macro because "5, 5" gets cleaned to "5".
#[test]
fn test_duplicates() {
let parsed = HeaderField::parse_header(&vec![b"5".to_vec(),
b"5".to_vec()].into()).unwrap();
assert_eq!(parsed, HeaderField(5));
assert_eq!(format!("{}", parsed), "5");
}
test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
});
bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] });
| fmt_header | identifier_name |
server_decoration.rs | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display;
pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create,
wlr_server_decoration_manager_destroy, wlr_server_decoration_manager_set_default_mode
};
#[derive(Debug)]
/// Coordinates whether the server should create
/// server-side window decorations.
pub struct Manager {
manager: *mut wlr_server_decoration_manager
}
impl Manager {
pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
let manager_raw = wlr_server_decoration_manager_create(display as *mut wl_display);
if!manager_raw.is_null() | else {
None
}
}
/// Given a mode, set the server decoration mode
pub fn set_default_mode(&mut self, mode: Mode) {
wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode);
unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
}
}
impl Drop for Manager {
fn drop(&mut self) {
unsafe { wlr_server_decoration_manager_destroy(self.manager) }
}
}
| {
Some(Manager { manager: manager_raw })
} | conditional_block |
server_decoration.rs | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display;
pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create,
wlr_server_decoration_manager_destroy, wlr_server_decoration_manager_set_default_mode
};
#[derive(Debug)]
/// Coordinates whether the server should create
/// server-side window decorations.
pub struct Manager {
manager: *mut wlr_server_decoration_manager
}
impl Manager {
pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
let manager_raw = wlr_server_decoration_manager_create(display as *mut wl_display);
if!manager_raw.is_null() {
Some(Manager { manager: manager_raw })
} else {
None
}
}
/// Given a mode, set the server decoration mode
pub fn set_default_mode(&mut self, mode: Mode) |
}
impl Drop for Manager {
fn drop(&mut self) {
unsafe { wlr_server_decoration_manager_destroy(self.manager) }
}
}
| {
wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode);
unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
} | identifier_body |
server_decoration.rs | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display;
pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create,
wlr_server_decoration_manager_destroy, wlr_server_decoration_manager_set_default_mode
};
#[derive(Debug)]
/// Coordinates whether the server should create
/// server-side window decorations.
pub struct Manager {
manager: *mut wlr_server_decoration_manager
}
impl Manager {
pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
let manager_raw = wlr_server_decoration_manager_create(display as *mut wl_display);
if!manager_raw.is_null() {
Some(Manager { manager: manager_raw })
} else {
None
}
}
/// Given a mode, set the server decoration mode
pub fn | (&mut self, mode: Mode) {
wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode);
unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
}
}
impl Drop for Manager {
fn drop(&mut self) {
unsafe { wlr_server_decoration_manager_destroy(self.manager) }
}
}
| set_default_mode | identifier_name |
server_decoration.rs | pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create,
wlr_server_decoration_manager_destroy, wlr_server_decoration_manager_set_default_mode
};
#[derive(Debug)]
/// Coordinates whether the server should create
/// server-side window decorations.
pub struct Manager {
manager: *mut wlr_server_decoration_manager
}
impl Manager {
pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
let manager_raw = wlr_server_decoration_manager_create(display as *mut wl_display);
if!manager_raw.is_null() {
Some(Manager { manager: manager_raw })
} else {
None
}
}
/// Given a mode, set the server decoration mode
pub fn set_default_mode(&mut self, mode: Mode) {
wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode);
unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
}
}
impl Drop for Manager {
fn drop(&mut self) {
unsafe { wlr_server_decoration_manager_destroy(self.manager) }
}
} | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display; | random_line_split |
|
pointing.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("Pointing", inherited=True, gecko_name="UserInterface") %>
<%helpers:longhand name="cursor">
pub use self::computed_value::T as SpecifiedValue;
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub mod computed_value { | use style_traits::cursor::Cursor;
#[derive(Clone, PartialEq, Eq, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum T {
AutoCursor,
SpecifiedCursor(Cursor),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::AutoCursor => dest.write_str("auto"),
T::SpecifiedCursor(c) => c.to_css(dest),
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::AutoCursor
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use std::ascii::AsciiExt;
use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident());
if ident.eq_ignore_ascii_case("auto") {
Ok(SpecifiedValue::AutoCursor)
} else {
Cursor::from_css_keyword(&ident)
.map(SpecifiedValue::SpecifiedCursor)
}
}
</%helpers:longhand>
// NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact)
// is nonstandard, slated for CSS4-UI.
// TODO(pcwalton): SVG-only values.
${helpers.single_keyword("pointer-events", "auto none")}
${helpers.single_keyword("-moz-user-input", "none enabled disabled", products="gecko",
gecko_ffi_name="mUserInput", gecko_constant_prefix="NS_STYLE_USER_INPUT")}
${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko",
gecko_ffi_name="mUserModify", gecko_constant_prefix="NS_STYLE_USER_MODIFY")}
${helpers.single_keyword("-moz-user-focus",
"ignore normal select-after select-before select-menu select-same select-all none",
products="gecko",
gecko_ffi_name="mUserFocus",
gecko_constant_prefix="NS_STYLE_USER_FOCUS")} | use cssparser::ToCss;
use std::fmt; | random_line_split |
pointing.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("Pointing", inherited=True, gecko_name="UserInterface") %>
<%helpers:longhand name="cursor">
pub use self::computed_value::T as SpecifiedValue;
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub mod computed_value {
use cssparser::ToCss;
use std::fmt;
use style_traits::cursor::Cursor;
#[derive(Clone, PartialEq, Eq, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum T {
AutoCursor,
SpecifiedCursor(Cursor),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::AutoCursor => dest.write_str("auto"),
T::SpecifiedCursor(c) => c.to_css(dest),
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::AutoCursor
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> |
</%helpers:longhand>
// NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact)
// is nonstandard, slated for CSS4-UI.
// TODO(pcwalton): SVG-only values.
${helpers.single_keyword("pointer-events", "auto none")}
${helpers.single_keyword("-moz-user-input", "none enabled disabled", products="gecko",
gecko_ffi_name="mUserInput", gecko_constant_prefix="NS_STYLE_USER_INPUT")}
${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko",
gecko_ffi_name="mUserModify", gecko_constant_prefix="NS_STYLE_USER_MODIFY")}
${helpers.single_keyword("-moz-user-focus",
"ignore normal select-after select-before select-menu select-same select-all none",
products="gecko",
gecko_ffi_name="mUserFocus",
gecko_constant_prefix="NS_STYLE_USER_FOCUS")}
| {
use std::ascii::AsciiExt;
use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident());
if ident.eq_ignore_ascii_case("auto") {
Ok(SpecifiedValue::AutoCursor)
} else {
Cursor::from_css_keyword(&ident)
.map(SpecifiedValue::SpecifiedCursor)
}
} | identifier_body |
pointing.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("Pointing", inherited=True, gecko_name="UserInterface") %>
<%helpers:longhand name="cursor">
pub use self::computed_value::T as SpecifiedValue;
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub mod computed_value {
use cssparser::ToCss;
use std::fmt;
use style_traits::cursor::Cursor;
#[derive(Clone, PartialEq, Eq, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum T {
AutoCursor,
SpecifiedCursor(Cursor),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::AutoCursor => dest.write_str("auto"),
T::SpecifiedCursor(c) => c.to_css(dest),
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::AutoCursor
}
pub fn | (_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use std::ascii::AsciiExt;
use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident());
if ident.eq_ignore_ascii_case("auto") {
Ok(SpecifiedValue::AutoCursor)
} else {
Cursor::from_css_keyword(&ident)
.map(SpecifiedValue::SpecifiedCursor)
}
}
</%helpers:longhand>
// NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact)
// is nonstandard, slated for CSS4-UI.
// TODO(pcwalton): SVG-only values.
${helpers.single_keyword("pointer-events", "auto none")}
${helpers.single_keyword("-moz-user-input", "none enabled disabled", products="gecko",
gecko_ffi_name="mUserInput", gecko_constant_prefix="NS_STYLE_USER_INPUT")}
${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko",
gecko_ffi_name="mUserModify", gecko_constant_prefix="NS_STYLE_USER_MODIFY")}
${helpers.single_keyword("-moz-user-focus",
"ignore normal select-after select-before select-menu select-same select-all none",
products="gecko",
gecko_ffi_name="mUserFocus",
gecko_constant_prefix="NS_STYLE_USER_FOCUS")}
| parse | identifier_name |
pointing.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("Pointing", inherited=True, gecko_name="UserInterface") %>
<%helpers:longhand name="cursor">
pub use self::computed_value::T as SpecifiedValue;
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub mod computed_value {
use cssparser::ToCss;
use std::fmt;
use style_traits::cursor::Cursor;
#[derive(Clone, PartialEq, Eq, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum T {
AutoCursor,
SpecifiedCursor(Cursor),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::AutoCursor => dest.write_str("auto"),
T::SpecifiedCursor(c) => c.to_css(dest),
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::AutoCursor
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use std::ascii::AsciiExt;
use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident());
if ident.eq_ignore_ascii_case("auto") | else {
Cursor::from_css_keyword(&ident)
.map(SpecifiedValue::SpecifiedCursor)
}
}
</%helpers:longhand>
// NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact)
// is nonstandard, slated for CSS4-UI.
// TODO(pcwalton): SVG-only values.
${helpers.single_keyword("pointer-events", "auto none")}
${helpers.single_keyword("-moz-user-input", "none enabled disabled", products="gecko",
gecko_ffi_name="mUserInput", gecko_constant_prefix="NS_STYLE_USER_INPUT")}
${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko",
gecko_ffi_name="mUserModify", gecko_constant_prefix="NS_STYLE_USER_MODIFY")}
${helpers.single_keyword("-moz-user-focus",
"ignore normal select-after select-before select-menu select-same select-all none",
products="gecko",
gecko_ffi_name="mUserFocus",
gecko_constant_prefix="NS_STYLE_USER_FOCUS")}
| {
Ok(SpecifiedValue::AutoCursor)
} | conditional_block |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate app_units;
extern crate gfx;
extern crate servo_arc;
extern crate servo_atoms;
extern crate style;
extern crate webrender_api;
use app_units::Au;
use gfx::font::{fallback_font_families, FontDescriptor, FontFamilyDescriptor, FontFamilyName, FontSearchScope};
use gfx::font_cache_thread::{FontTemplates, FontTemplateInfo};
use gfx::font_context::{FontContext, FontContextHandle, FontSource};
use gfx::font_template::FontTemplateDescriptor;
use servo_arc::Arc;
use servo_atoms::Atom;
use std::cell::Cell;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use std::rc::Rc;
use style::properties::longhands::font_variant_caps::computed_value::T as FontVariantCaps;
use style::properties::style_structs::Font as FontStyleStruct;
use style::values::computed::font::{FamilyName, FamilyNameSyntax, FontFamily, FontFamilyList, FontSize};
use style::values::computed::font::{FontStretch, FontWeight, SingleFontFamily};
use style::values::generics::font::FontStyle;
struct TestFontSource {
handle: FontContextHandle,
families: HashMap<String, FontTemplates>,
find_font_count: Rc<Cell<isize>>,
}
impl TestFontSource {
fn new() -> TestFontSource {
let mut csstest_ascii = FontTemplates::new();
Self::add_face(&mut csstest_ascii, "csstest-ascii", None);
let mut csstest_basic = FontTemplates::new();
Self::add_face(&mut csstest_basic, "csstest-basic-regular", None);
let mut fallback = FontTemplates::new();
Self::add_face(&mut fallback, "csstest-basic-regular", Some("fallback"));
let mut families = HashMap::new();
families.insert("CSSTest ASCII".to_owned(), csstest_ascii);
families.insert("CSSTest Basic".to_owned(), csstest_basic);
families.insert(fallback_font_families(None)[0].to_owned(), fallback);
TestFontSource {
handle: FontContextHandle::new(),
families,
find_font_count: Rc::new(Cell::new(0)),
}
}
fn add_face(family: &mut FontTemplates, name: &str, identifier: Option<&str>) {
let mut path: PathBuf = [env!("CARGO_MANIFEST_DIR"), "tests", "support", "CSSTest"]
.iter()
.collect();
path.push(format!("{}.ttf", name));
let file = File::open(path).unwrap();
let identifier = Atom::from(identifier.unwrap_or(name));
family.add_template(identifier, Some(file.bytes().map(|b| b.unwrap()).collect()))
}
}
impl FontSource for TestFontSource {
fn get_font_instance(
&mut self,
_key: webrender_api::FontKey,
_size: Au,
) -> webrender_api::FontInstanceKey {
webrender_api::FontInstanceKey(webrender_api::IdNamespace(0), 0)
}
fn font_template(
&mut self,
template_descriptor: FontTemplateDescriptor,
family_descriptor: FontFamilyDescriptor,
) -> Option<FontTemplateInfo> {
let handle = &self.handle;
self.find_font_count.set(self.find_font_count.get() + 1);
self.families
.get_mut(family_descriptor.name())
.and_then(|family| family.find_font_for_style(&template_descriptor, handle))
.map(|template| FontTemplateInfo {
font_template: template,
font_key: webrender_api::FontKey(webrender_api::IdNamespace(0), 0),
})
}
}
fn style() -> FontStyleStruct {
let mut style = FontStyleStruct {
font_family: FontFamily::serif(),
font_style: FontStyle::Normal,
font_variant_caps: FontVariantCaps::Normal,
font_weight: FontWeight::normal(),
font_size: FontSize::medium(),
font_stretch: FontStretch::hundred(),
hash: 0,
};
style.compute_font_hash();
style
}
fn font_family(names: Vec<&str>) -> FontFamily {
let names: Vec<SingleFontFamily> = names
.into_iter()
.map(|name| {
SingleFontFamily::FamilyName(FamilyName {
name: Atom::from(name),
syntax: FamilyNameSyntax::Quoted,
})
}).collect();
FontFamily(FontFamilyList::new(names.into_boxed_slice()))
}
#[test]
fn test_font_group_is_cached_by_style() {
let source = TestFontSource::new();
let mut context = FontContext::new(source);
let style1 = style();
let mut style2 = style();
style2.set_font_style(FontStyle::Italic);
assert_eq!(
context.font_group(Arc::new(style1.clone())).as_ptr(),
context.font_group(Arc::new(style1.clone())).as_ptr(),
"the same font group should be returned for two styles with the same hash"
);
assert_ne!(
context.font_group(Arc::new(style1.clone())).as_ptr(),
context.font_group(Arc::new(style2.clone())).as_ptr(), | #[test]
fn test_font_group_find_by_codepoint() {
let source = TestFontSource::new();
let count = source.find_font_count.clone();
let mut context = FontContext::new(source);
let mut style = style();
style.set_font_family(font_family(vec!["CSSTest ASCII", "CSSTest Basic"]));
let group = context.font_group(Arc::new(style));
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'a')
.unwrap();
assert_eq!(&*font.borrow().identifier(), "csstest-ascii");
assert_eq!(
count.get(),
1,
"only the first font in the list should have been loaded"
);
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'a')
.unwrap();
assert_eq!(&*font.borrow().identifier(), "csstest-ascii");
assert_eq!(
count.get(),
1,
"we shouldn't load the same font a second time"
);
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'á')
.unwrap();
assert_eq!(&*font.borrow().identifier(), "csstest-basic-regular");
assert_eq!(count.get(), 2, "both fonts should now have been loaded");
}
#[test]
fn test_font_fallback() {
let source = TestFontSource::new();
let mut context = FontContext::new(source);
let mut style = style();
style.set_font_family(font_family(vec!["CSSTest ASCII"]));
let group = context.font_group(Arc::new(style));
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'a')
.unwrap();
assert_eq!(
&*font.borrow().identifier(),
"csstest-ascii",
"a family in the group should be used if there is a matching glyph"
);
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'á')
.unwrap();
assert_eq!(
&*font.borrow().identifier(),
"fallback",
"a fallback font should be used if there is no matching glyph in the group"
);
}
#[test]
fn test_font_template_is_cached() {
let source = TestFontSource::new();
let count = source.find_font_count.clone();
let mut context = FontContext::new(source);
let mut font_descriptor = FontDescriptor {
template_descriptor: FontTemplateDescriptor {
weight: FontWeight::normal(),
stretch: FontStretch::hundred(),
style: FontStyle::Normal,
},
variant: FontVariantCaps::Normal,
pt_size: Au(10),
};
let family_descriptor =
FontFamilyDescriptor::new(FontFamilyName::from("CSSTest Basic"), FontSearchScope::Any);
let font1 = context.font(&font_descriptor, &family_descriptor).unwrap();
font_descriptor.pt_size = Au(20);
let font2 = context.font(&font_descriptor, &family_descriptor).unwrap();
assert_ne!(
font1.borrow().actual_pt_size,
font2.borrow().actual_pt_size,
"the same font should not have been returned"
);
assert_eq!(
count.get(),
1,
"we should only have fetched the template data from the cache thread once"
);
} | "different font groups should be returned for two styles with different hashes"
)
}
| random_line_split |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate app_units;
extern crate gfx;
extern crate servo_arc;
extern crate servo_atoms;
extern crate style;
extern crate webrender_api;
use app_units::Au;
use gfx::font::{fallback_font_families, FontDescriptor, FontFamilyDescriptor, FontFamilyName, FontSearchScope};
use gfx::font_cache_thread::{FontTemplates, FontTemplateInfo};
use gfx::font_context::{FontContext, FontContextHandle, FontSource};
use gfx::font_template::FontTemplateDescriptor;
use servo_arc::Arc;
use servo_atoms::Atom;
use std::cell::Cell;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use std::rc::Rc;
use style::properties::longhands::font_variant_caps::computed_value::T as FontVariantCaps;
use style::properties::style_structs::Font as FontStyleStruct;
use style::values::computed::font::{FamilyName, FamilyNameSyntax, FontFamily, FontFamilyList, FontSize};
use style::values::computed::font::{FontStretch, FontWeight, SingleFontFamily};
use style::values::generics::font::FontStyle;
struct TestFontSource {
handle: FontContextHandle,
families: HashMap<String, FontTemplates>,
find_font_count: Rc<Cell<isize>>,
}
impl TestFontSource {
fn new() -> TestFontSource {
let mut csstest_ascii = FontTemplates::new();
Self::add_face(&mut csstest_ascii, "csstest-ascii", None);
let mut csstest_basic = FontTemplates::new();
Self::add_face(&mut csstest_basic, "csstest-basic-regular", None);
let mut fallback = FontTemplates::new();
Self::add_face(&mut fallback, "csstest-basic-regular", Some("fallback"));
let mut families = HashMap::new();
families.insert("CSSTest ASCII".to_owned(), csstest_ascii);
families.insert("CSSTest Basic".to_owned(), csstest_basic);
families.insert(fallback_font_families(None)[0].to_owned(), fallback);
TestFontSource {
handle: FontContextHandle::new(),
families,
find_font_count: Rc::new(Cell::new(0)),
}
}
fn add_face(family: &mut FontTemplates, name: &str, identifier: Option<&str>) {
let mut path: PathBuf = [env!("CARGO_MANIFEST_DIR"), "tests", "support", "CSSTest"]
.iter()
.collect();
path.push(format!("{}.ttf", name));
let file = File::open(path).unwrap();
let identifier = Atom::from(identifier.unwrap_or(name));
family.add_template(identifier, Some(file.bytes().map(|b| b.unwrap()).collect()))
}
}
impl FontSource for TestFontSource {
fn get_font_instance(
&mut self,
_key: webrender_api::FontKey,
_size: Au,
) -> webrender_api::FontInstanceKey {
webrender_api::FontInstanceKey(webrender_api::IdNamespace(0), 0)
}
fn font_template(
&mut self,
template_descriptor: FontTemplateDescriptor,
family_descriptor: FontFamilyDescriptor,
) -> Option<FontTemplateInfo> {
let handle = &self.handle;
self.find_font_count.set(self.find_font_count.get() + 1);
self.families
.get_mut(family_descriptor.name())
.and_then(|family| family.find_font_for_style(&template_descriptor, handle))
.map(|template| FontTemplateInfo {
font_template: template,
font_key: webrender_api::FontKey(webrender_api::IdNamespace(0), 0),
})
}
}
fn style() -> FontStyleStruct {
let mut style = FontStyleStruct {
font_family: FontFamily::serif(),
font_style: FontStyle::Normal,
font_variant_caps: FontVariantCaps::Normal,
font_weight: FontWeight::normal(),
font_size: FontSize::medium(),
font_stretch: FontStretch::hundred(),
hash: 0,
};
style.compute_font_hash();
style
}
fn font_family(names: Vec<&str>) -> FontFamily {
let names: Vec<SingleFontFamily> = names
.into_iter()
.map(|name| {
SingleFontFamily::FamilyName(FamilyName {
name: Atom::from(name),
syntax: FamilyNameSyntax::Quoted,
})
}).collect();
FontFamily(FontFamilyList::new(names.into_boxed_slice()))
}
#[test]
fn test_font_group_is_cached_by_style() {
let source = TestFontSource::new();
let mut context = FontContext::new(source);
let style1 = style();
let mut style2 = style();
style2.set_font_style(FontStyle::Italic);
assert_eq!(
context.font_group(Arc::new(style1.clone())).as_ptr(),
context.font_group(Arc::new(style1.clone())).as_ptr(),
"the same font group should be returned for two styles with the same hash"
);
assert_ne!(
context.font_group(Arc::new(style1.clone())).as_ptr(),
context.font_group(Arc::new(style2.clone())).as_ptr(),
"different font groups should be returned for two styles with different hashes"
)
}
#[test]
fn test_font_group_find_by_codepoint() {
let source = TestFontSource::new();
let count = source.find_font_count.clone();
let mut context = FontContext::new(source);
let mut style = style();
style.set_font_family(font_family(vec!["CSSTest ASCII", "CSSTest Basic"]));
let group = context.font_group(Arc::new(style));
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'a')
.unwrap();
assert_eq!(&*font.borrow().identifier(), "csstest-ascii");
assert_eq!(
count.get(),
1,
"only the first font in the list should have been loaded"
);
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'a')
.unwrap();
assert_eq!(&*font.borrow().identifier(), "csstest-ascii");
assert_eq!(
count.get(),
1,
"we shouldn't load the same font a second time"
);
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'á')
.unwrap();
assert_eq!(&*font.borrow().identifier(), "csstest-basic-regular");
assert_eq!(count.get(), 2, "both fonts should now have been loaded");
}
#[test]
fn t | ) {
let source = TestFontSource::new();
let mut context = FontContext::new(source);
let mut style = style();
style.set_font_family(font_family(vec!["CSSTest ASCII"]));
let group = context.font_group(Arc::new(style));
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'a')
.unwrap();
assert_eq!(
&*font.borrow().identifier(),
"csstest-ascii",
"a family in the group should be used if there is a matching glyph"
);
let font = group
.borrow_mut()
.find_by_codepoint(&mut context, 'á')
.unwrap();
assert_eq!(
&*font.borrow().identifier(),
"fallback",
"a fallback font should be used if there is no matching glyph in the group"
);
}
#[test]
fn test_font_template_is_cached() {
let source = TestFontSource::new();
let count = source.find_font_count.clone();
let mut context = FontContext::new(source);
let mut font_descriptor = FontDescriptor {
template_descriptor: FontTemplateDescriptor {
weight: FontWeight::normal(),
stretch: FontStretch::hundred(),
style: FontStyle::Normal,
},
variant: FontVariantCaps::Normal,
pt_size: Au(10),
};
let family_descriptor =
FontFamilyDescriptor::new(FontFamilyName::from("CSSTest Basic"), FontSearchScope::Any);
let font1 = context.font(&font_descriptor, &family_descriptor).unwrap();
font_descriptor.pt_size = Au(20);
let font2 = context.font(&font_descriptor, &family_descriptor).unwrap();
assert_ne!(
font1.borrow().actual_pt_size,
font2.borrow().actual_pt_size,
"the same font should not have been returned"
);
assert_eq!(
count.get(),
1,
"we should only have fetched the template data from the cache thread once"
);
}
| est_font_fallback( | identifier_name |
framebuffer_info.rs | //! Handles the framebuffer information tag.
use super::get_tag;
#[cfg(target_arch = "x86_64")]
use arch::vga_buffer;
use memory::{Address, VirtualAddress};
/// Represents the framebuffer information tag.
#[repr(C)]
pub struct FramebufferInfo {
// type = 8
tag_type: u32,
size: u32,
pub framebuffer_addr: u64,
framebuffer_pitch: u32,
pub framebuffer_width: u32,
pub framebuffer_height: u32,
framebuffer_bpp: u8,
framebuffer_type: u8,
reserved: u8,
color_info: u32 // This is just a placeholder, this depends on the framebuffer_type.
}
/// Returns the VGA buffer information requested.
#[cfg(target_arch = "x86_64")]
pub fn | () -> vga_buffer::Info {
let framebuffer_tag = get_tag(8);
match framebuffer_tag {
Some(framebuffer_tag_address) => {
let framebuffer_tag = unsafe { &*(framebuffer_tag_address as *const FramebufferInfo) };
vga_buffer::Info {
height: framebuffer_tag.framebuffer_height as usize,
width: framebuffer_tag.framebuffer_width as usize,
address: VirtualAddress::from_usize(to_virtual!(framebuffer_tag.framebuffer_addr))
}
},
None => vga_buffer::Info {
height: 25,
width: 80,
address: VirtualAddress::from_usize(to_virtual!(0xb8000))
}
}
}
| get_vga_info | identifier_name |
framebuffer_info.rs | //! Handles the framebuffer information tag.
use super::get_tag;
#[cfg(target_arch = "x86_64")]
use arch::vga_buffer;
use memory::{Address, VirtualAddress};
/// Represents the framebuffer information tag.
#[repr(C)]
pub struct FramebufferInfo {
// type = 8
tag_type: u32,
size: u32,
pub framebuffer_addr: u64,
framebuffer_pitch: u32,
pub framebuffer_width: u32,
pub framebuffer_height: u32,
framebuffer_bpp: u8,
framebuffer_type: u8,
reserved: u8,
color_info: u32 // This is just a placeholder, this depends on the framebuffer_type.
}
/// Returns the VGA buffer information requested.
#[cfg(target_arch = "x86_64")]
pub fn get_vga_info() -> vga_buffer::Info {
let framebuffer_tag = get_tag(8);
match framebuffer_tag {
Some(framebuffer_tag_address) => {
let framebuffer_tag = unsafe { &*(framebuffer_tag_address as *const FramebufferInfo) }; | vga_buffer::Info {
height: framebuffer_tag.framebuffer_height as usize,
width: framebuffer_tag.framebuffer_width as usize,
address: VirtualAddress::from_usize(to_virtual!(framebuffer_tag.framebuffer_addr))
}
},
None => vga_buffer::Info {
height: 25,
width: 80,
address: VirtualAddress::from_usize(to_virtual!(0xb8000))
}
}
} | random_line_split |
|
object-lifetime-default-ambiguous.rs | // Test that if a struct declares multiple region bounds for a given
// type parameter, an explicit lifetime bound is required on object
// lifetimes within.
#![allow(dead_code)]
trait Test {
fn foo(&self) { }
}
struct Ref0<T:?Sized> {
r: *mut T
}
struct Ref1<'a,T:'a+?Sized> {
r: &'a T
}
struct Ref2<'a,'b:'a,T:'a+'b+?Sized> {
r: &'a &'b T
}
fn a<'a,'b>(t: Ref2<'a,'b, dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
}
fn b(t: Ref2<dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
} | }
fn d(t: Ref2<Ref1<dyn Test>>) {
// In this case, the lifetime parameter from the Ref1 overrides.
}
fn e(t: Ref2<Ref0<dyn Test>>) {
// In this case, Ref2 is ambiguous, but Ref0 overrides with'static.
}
fn f(t: &Ref2<dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
}
fn main() {
} |
fn c(t: Ref2<&dyn Test>) {
// In this case, the &'a overrides. | random_line_split |
object-lifetime-default-ambiguous.rs | // Test that if a struct declares multiple region bounds for a given
// type parameter, an explicit lifetime bound is required on object
// lifetimes within.
#![allow(dead_code)]
trait Test {
fn foo(&self) { }
}
struct Ref0<T:?Sized> {
r: *mut T
}
struct Ref1<'a,T:'a+?Sized> {
r: &'a T
}
struct Ref2<'a,'b:'a,T:'a+'b+?Sized> {
r: &'a &'b T
}
fn | <'a,'b>(t: Ref2<'a,'b, dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
}
fn b(t: Ref2<dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
}
fn c(t: Ref2<&dyn Test>) {
// In this case, the &'a overrides.
}
fn d(t: Ref2<Ref1<dyn Test>>) {
// In this case, the lifetime parameter from the Ref1 overrides.
}
fn e(t: Ref2<Ref0<dyn Test>>) {
// In this case, Ref2 is ambiguous, but Ref0 overrides with'static.
}
fn f(t: &Ref2<dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
}
fn main() {
}
| a | identifier_name |
object-lifetime-default-ambiguous.rs | // Test that if a struct declares multiple region bounds for a given
// type parameter, an explicit lifetime bound is required on object
// lifetimes within.
#![allow(dead_code)]
trait Test {
fn foo(&self) { }
}
struct Ref0<T:?Sized> {
r: *mut T
}
struct Ref1<'a,T:'a+?Sized> {
r: &'a T
}
struct Ref2<'a,'b:'a,T:'a+'b+?Sized> {
r: &'a &'b T
}
fn a<'a,'b>(t: Ref2<'a,'b, dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
}
fn b(t: Ref2<dyn Test>) {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
}
fn c(t: Ref2<&dyn Test>) {
// In this case, the &'a overrides.
}
fn d(t: Ref2<Ref1<dyn Test>>) {
// In this case, the lifetime parameter from the Ref1 overrides.
}
fn e(t: Ref2<Ref0<dyn Test>>) {
// In this case, Ref2 is ambiguous, but Ref0 overrides with'static.
}
fn f(t: &Ref2<dyn Test>) |
fn main() {
}
| {
//~^ ERROR lifetime bound for this object type cannot be deduced from context
} | identifier_body |
attr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::parser::SelectorImpl;
use cssparser::ToCss;
use std::fmt;
#[derive(Clone, Eq, PartialEq, ToShmem)]
#[shmem(no_bounds)]
pub struct AttrSelectorWithOptionalNamespace<Impl: SelectorImpl> {
#[shmem(field_bound)]
pub namespace: Option<NamespaceConstraint<(Impl::NamespacePrefix, Impl::NamespaceUrl)>>,
#[shmem(field_bound)]
pub local_name: Impl::LocalName,
pub local_name_lower: Impl::LocalName,
#[shmem(field_bound)]
pub operation: ParsedAttrSelectorOperation<Impl::AttrValue>,
pub never_matches: bool,
}
impl<Impl: SelectorImpl> AttrSelectorWithOptionalNamespace<Impl> {
pub fn namespace(&self) -> Option<NamespaceConstraint<&Impl::NamespaceUrl>> {
self.namespace.as_ref().map(|ns| match ns {
NamespaceConstraint::Any => NamespaceConstraint::Any,
NamespaceConstraint::Specific((_, ref url)) => NamespaceConstraint::Specific(url),
})
}
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum | <NamespaceUrl> {
Any,
/// Empty string for no namespace
Specific(NamespaceUrl),
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum ParsedAttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: ParsedCaseSensitivity,
expected_value: AttrValue,
},
}
#[derive(Clone, Eq, PartialEq)]
pub enum AttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: CaseSensitivity,
expected_value: AttrValue,
},
}
impl<AttrValue> AttrSelectorOperation<AttrValue> {
pub fn eval_str(&self, element_attr_value: &str) -> bool
where
AttrValue: AsRef<str>,
{
match *self {
AttrSelectorOperation::Exists => true,
AttrSelectorOperation::WithValue {
operator,
case_sensitivity,
ref expected_value,
} => operator.eval_str(
element_attr_value,
expected_value.as_ref(),
case_sensitivity,
),
}
}
}
#[derive(Clone, Copy, Eq, PartialEq, ToShmem)]
pub enum AttrSelectorOperator {
Equal,
Includes,
DashMatch,
Prefix,
Substring,
Suffix,
}
impl ToCss for AttrSelectorOperator {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
// https://drafts.csswg.org/cssom/#serializing-selectors
// See "attribute selector".
dest.write_str(match *self {
AttrSelectorOperator::Equal => "=",
AttrSelectorOperator::Includes => "~=",
AttrSelectorOperator::DashMatch => "|=",
AttrSelectorOperator::Prefix => "^=",
AttrSelectorOperator::Substring => "*=",
AttrSelectorOperator::Suffix => "$=",
})
}
}
impl AttrSelectorOperator {
pub fn eval_str(
self,
element_attr_value: &str,
attr_selector_value: &str,
case_sensitivity: CaseSensitivity,
) -> bool {
let e = element_attr_value.as_bytes();
let s = attr_selector_value.as_bytes();
let case = case_sensitivity;
match self {
AttrSelectorOperator::Equal => case.eq(e, s),
AttrSelectorOperator::Prefix => e.len() >= s.len() && case.eq(&e[..s.len()], s),
AttrSelectorOperator::Suffix => {
e.len() >= s.len() && case.eq(&e[(e.len() - s.len())..], s)
},
AttrSelectorOperator::Substring => {
case.contains(element_attr_value, attr_selector_value)
},
AttrSelectorOperator::Includes => element_attr_value
.split(SELECTOR_WHITESPACE)
.any(|part| case.eq(part.as_bytes(), s)),
AttrSelectorOperator::DashMatch => {
case.eq(e, s) || (e.get(s.len()) == Some(&b'-') && case.eq(&e[..s.len()], s))
},
}
}
}
/// The definition of whitespace per CSS Selectors Level 3 § 4.
pub static SELECTOR_WHITESPACE: &'static [char] = &[' ', '\t', '\n', '\r', '\x0C'];
#[derive(Clone, Copy, Debug, Eq, PartialEq, ToShmem)]
pub enum ParsedCaseSensitivity {
//'s' was specified.
ExplicitCaseSensitive,
// 'i' was specified.
AsciiCaseInsensitive,
// No flags were specified and HTML says this is a case-sensitive attribute.
CaseSensitive,
// No flags were specified and HTML says this is a case-insensitive attribute.
AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument,
}
impl ParsedCaseSensitivity {
pub fn to_unconditional(self, is_html_element_in_html_document: bool) -> CaseSensitivity {
match self {
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument
if is_html_element_in_html_document =>
{
CaseSensitivity::AsciiCaseInsensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {
CaseSensitivity::CaseSensitive
},
ParsedCaseSensitivity::CaseSensitive | ParsedCaseSensitivity::ExplicitCaseSensitive => {
CaseSensitivity::CaseSensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitive => CaseSensitivity::AsciiCaseInsensitive,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CaseSensitivity {
CaseSensitive,
AsciiCaseInsensitive,
}
impl CaseSensitivity {
pub fn eq(self, a: &[u8], b: &[u8]) -> bool {
match self {
CaseSensitivity::CaseSensitive => a == b,
CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
pub fn contains(self, haystack: &str, needle: &str) -> bool {
match self {
CaseSensitivity::CaseSensitive => haystack.contains(needle),
CaseSensitivity::AsciiCaseInsensitive => {
if let Some((&n_first_byte, n_rest)) = needle.as_bytes().split_first() {
haystack.bytes().enumerate().any(|(i, byte)| {
if!byte.eq_ignore_ascii_case(&n_first_byte) {
return false;
}
let after_this_byte = &haystack.as_bytes()[i + 1..];
match after_this_byte.get(..n_rest.len()) {
None => false,
Some(haystack_slice) => haystack_slice.eq_ignore_ascii_case(n_rest),
}
})
} else {
// any_str.contains("") == true,
// though these cases should be handled with *NeverMatches and never go here.
true
}
},
}
}
}
| NamespaceConstraint | identifier_name |
attr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::parser::SelectorImpl;
use cssparser::ToCss;
use std::fmt;
#[derive(Clone, Eq, PartialEq, ToShmem)]
#[shmem(no_bounds)]
pub struct AttrSelectorWithOptionalNamespace<Impl: SelectorImpl> {
#[shmem(field_bound)]
pub namespace: Option<NamespaceConstraint<(Impl::NamespacePrefix, Impl::NamespaceUrl)>>,
#[shmem(field_bound)]
pub local_name: Impl::LocalName,
pub local_name_lower: Impl::LocalName,
#[shmem(field_bound)]
pub operation: ParsedAttrSelectorOperation<Impl::AttrValue>,
pub never_matches: bool,
}
impl<Impl: SelectorImpl> AttrSelectorWithOptionalNamespace<Impl> {
pub fn namespace(&self) -> Option<NamespaceConstraint<&Impl::NamespaceUrl>> {
self.namespace.as_ref().map(|ns| match ns {
NamespaceConstraint::Any => NamespaceConstraint::Any,
NamespaceConstraint::Specific((_, ref url)) => NamespaceConstraint::Specific(url),
})
}
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum NamespaceConstraint<NamespaceUrl> {
Any,
/// Empty string for no namespace
Specific(NamespaceUrl),
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum ParsedAttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: ParsedCaseSensitivity,
expected_value: AttrValue,
},
}
#[derive(Clone, Eq, PartialEq)]
pub enum AttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: CaseSensitivity,
expected_value: AttrValue,
},
}
impl<AttrValue> AttrSelectorOperation<AttrValue> {
pub fn eval_str(&self, element_attr_value: &str) -> bool
where
AttrValue: AsRef<str>,
{
match *self {
AttrSelectorOperation::Exists => true,
AttrSelectorOperation::WithValue {
operator,
case_sensitivity,
ref expected_value,
} => operator.eval_str(
element_attr_value,
expected_value.as_ref(),
case_sensitivity,
),
}
}
}
| #[derive(Clone, Copy, Eq, PartialEq, ToShmem)]
pub enum AttrSelectorOperator {
Equal,
Includes,
DashMatch,
Prefix,
Substring,
Suffix,
}
impl ToCss for AttrSelectorOperator {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
// https://drafts.csswg.org/cssom/#serializing-selectors
// See "attribute selector".
dest.write_str(match *self {
AttrSelectorOperator::Equal => "=",
AttrSelectorOperator::Includes => "~=",
AttrSelectorOperator::DashMatch => "|=",
AttrSelectorOperator::Prefix => "^=",
AttrSelectorOperator::Substring => "*=",
AttrSelectorOperator::Suffix => "$=",
})
}
}
impl AttrSelectorOperator {
pub fn eval_str(
self,
element_attr_value: &str,
attr_selector_value: &str,
case_sensitivity: CaseSensitivity,
) -> bool {
let e = element_attr_value.as_bytes();
let s = attr_selector_value.as_bytes();
let case = case_sensitivity;
match self {
AttrSelectorOperator::Equal => case.eq(e, s),
AttrSelectorOperator::Prefix => e.len() >= s.len() && case.eq(&e[..s.len()], s),
AttrSelectorOperator::Suffix => {
e.len() >= s.len() && case.eq(&e[(e.len() - s.len())..], s)
},
AttrSelectorOperator::Substring => {
case.contains(element_attr_value, attr_selector_value)
},
AttrSelectorOperator::Includes => element_attr_value
.split(SELECTOR_WHITESPACE)
.any(|part| case.eq(part.as_bytes(), s)),
AttrSelectorOperator::DashMatch => {
case.eq(e, s) || (e.get(s.len()) == Some(&b'-') && case.eq(&e[..s.len()], s))
},
}
}
}
/// The definition of whitespace per CSS Selectors Level 3 § 4.
pub static SELECTOR_WHITESPACE: &'static [char] = &[' ', '\t', '\n', '\r', '\x0C'];
#[derive(Clone, Copy, Debug, Eq, PartialEq, ToShmem)]
pub enum ParsedCaseSensitivity {
//'s' was specified.
ExplicitCaseSensitive,
// 'i' was specified.
AsciiCaseInsensitive,
// No flags were specified and HTML says this is a case-sensitive attribute.
CaseSensitive,
// No flags were specified and HTML says this is a case-insensitive attribute.
AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument,
}
impl ParsedCaseSensitivity {
pub fn to_unconditional(self, is_html_element_in_html_document: bool) -> CaseSensitivity {
match self {
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument
if is_html_element_in_html_document =>
{
CaseSensitivity::AsciiCaseInsensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {
CaseSensitivity::CaseSensitive
},
ParsedCaseSensitivity::CaseSensitive | ParsedCaseSensitivity::ExplicitCaseSensitive => {
CaseSensitivity::CaseSensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitive => CaseSensitivity::AsciiCaseInsensitive,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CaseSensitivity {
CaseSensitive,
AsciiCaseInsensitive,
}
impl CaseSensitivity {
pub fn eq(self, a: &[u8], b: &[u8]) -> bool {
match self {
CaseSensitivity::CaseSensitive => a == b,
CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
pub fn contains(self, haystack: &str, needle: &str) -> bool {
match self {
CaseSensitivity::CaseSensitive => haystack.contains(needle),
CaseSensitivity::AsciiCaseInsensitive => {
if let Some((&n_first_byte, n_rest)) = needle.as_bytes().split_first() {
haystack.bytes().enumerate().any(|(i, byte)| {
if!byte.eq_ignore_ascii_case(&n_first_byte) {
return false;
}
let after_this_byte = &haystack.as_bytes()[i + 1..];
match after_this_byte.get(..n_rest.len()) {
None => false,
Some(haystack_slice) => haystack_slice.eq_ignore_ascii_case(n_rest),
}
})
} else {
// any_str.contains("") == true,
// though these cases should be handled with *NeverMatches and never go here.
true
}
},
}
}
} | random_line_split |
|
attr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::parser::SelectorImpl;
use cssparser::ToCss;
use std::fmt;
#[derive(Clone, Eq, PartialEq, ToShmem)]
#[shmem(no_bounds)]
pub struct AttrSelectorWithOptionalNamespace<Impl: SelectorImpl> {
#[shmem(field_bound)]
pub namespace: Option<NamespaceConstraint<(Impl::NamespacePrefix, Impl::NamespaceUrl)>>,
#[shmem(field_bound)]
pub local_name: Impl::LocalName,
pub local_name_lower: Impl::LocalName,
#[shmem(field_bound)]
pub operation: ParsedAttrSelectorOperation<Impl::AttrValue>,
pub never_matches: bool,
}
impl<Impl: SelectorImpl> AttrSelectorWithOptionalNamespace<Impl> {
pub fn namespace(&self) -> Option<NamespaceConstraint<&Impl::NamespaceUrl>> {
self.namespace.as_ref().map(|ns| match ns {
NamespaceConstraint::Any => NamespaceConstraint::Any,
NamespaceConstraint::Specific((_, ref url)) => NamespaceConstraint::Specific(url),
})
}
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum NamespaceConstraint<NamespaceUrl> {
Any,
/// Empty string for no namespace
Specific(NamespaceUrl),
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum ParsedAttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: ParsedCaseSensitivity,
expected_value: AttrValue,
},
}
#[derive(Clone, Eq, PartialEq)]
pub enum AttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: CaseSensitivity,
expected_value: AttrValue,
},
}
impl<AttrValue> AttrSelectorOperation<AttrValue> {
pub fn eval_str(&self, element_attr_value: &str) -> bool
where
AttrValue: AsRef<str>,
{
match *self {
AttrSelectorOperation::Exists => true,
AttrSelectorOperation::WithValue {
operator,
case_sensitivity,
ref expected_value,
} => operator.eval_str(
element_attr_value,
expected_value.as_ref(),
case_sensitivity,
),
}
}
}
#[derive(Clone, Copy, Eq, PartialEq, ToShmem)]
pub enum AttrSelectorOperator {
Equal,
Includes,
DashMatch,
Prefix,
Substring,
Suffix,
}
impl ToCss for AttrSelectorOperator {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
// https://drafts.csswg.org/cssom/#serializing-selectors
// See "attribute selector".
dest.write_str(match *self {
AttrSelectorOperator::Equal => "=",
AttrSelectorOperator::Includes => "~=",
AttrSelectorOperator::DashMatch => "|=",
AttrSelectorOperator::Prefix => "^=",
AttrSelectorOperator::Substring => "*=",
AttrSelectorOperator::Suffix => "$=",
})
}
}
impl AttrSelectorOperator {
pub fn eval_str(
self,
element_attr_value: &str,
attr_selector_value: &str,
case_sensitivity: CaseSensitivity,
) -> bool {
let e = element_attr_value.as_bytes();
let s = attr_selector_value.as_bytes();
let case = case_sensitivity;
match self {
AttrSelectorOperator::Equal => case.eq(e, s),
AttrSelectorOperator::Prefix => e.len() >= s.len() && case.eq(&e[..s.len()], s),
AttrSelectorOperator::Suffix => {
e.len() >= s.len() && case.eq(&e[(e.len() - s.len())..], s)
},
AttrSelectorOperator::Substring => {
case.contains(element_attr_value, attr_selector_value)
},
AttrSelectorOperator::Includes => element_attr_value
.split(SELECTOR_WHITESPACE)
.any(|part| case.eq(part.as_bytes(), s)),
AttrSelectorOperator::DashMatch => {
case.eq(e, s) || (e.get(s.len()) == Some(&b'-') && case.eq(&e[..s.len()], s))
},
}
}
}
/// The definition of whitespace per CSS Selectors Level 3 § 4.
pub static SELECTOR_WHITESPACE: &'static [char] = &[' ', '\t', '\n', '\r', '\x0C'];
#[derive(Clone, Copy, Debug, Eq, PartialEq, ToShmem)]
pub enum ParsedCaseSensitivity {
//'s' was specified.
ExplicitCaseSensitive,
// 'i' was specified.
AsciiCaseInsensitive,
// No flags were specified and HTML says this is a case-sensitive attribute.
CaseSensitive,
// No flags were specified and HTML says this is a case-insensitive attribute.
AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument,
}
impl ParsedCaseSensitivity {
pub fn to_unconditional(self, is_html_element_in_html_document: bool) -> CaseSensitivity {
match self {
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument
if is_html_element_in_html_document =>
{
CaseSensitivity::AsciiCaseInsensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => { |
ParsedCaseSensitivity::CaseSensitive | ParsedCaseSensitivity::ExplicitCaseSensitive => {
CaseSensitivity::CaseSensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitive => CaseSensitivity::AsciiCaseInsensitive,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CaseSensitivity {
CaseSensitive,
AsciiCaseInsensitive,
}
impl CaseSensitivity {
pub fn eq(self, a: &[u8], b: &[u8]) -> bool {
match self {
CaseSensitivity::CaseSensitive => a == b,
CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
pub fn contains(self, haystack: &str, needle: &str) -> bool {
match self {
CaseSensitivity::CaseSensitive => haystack.contains(needle),
CaseSensitivity::AsciiCaseInsensitive => {
if let Some((&n_first_byte, n_rest)) = needle.as_bytes().split_first() {
haystack.bytes().enumerate().any(|(i, byte)| {
if!byte.eq_ignore_ascii_case(&n_first_byte) {
return false;
}
let after_this_byte = &haystack.as_bytes()[i + 1..];
match after_this_byte.get(..n_rest.len()) {
None => false,
Some(haystack_slice) => haystack_slice.eq_ignore_ascii_case(n_rest),
}
})
} else {
// any_str.contains("") == true,
// though these cases should be handled with *NeverMatches and never go here.
true
}
},
}
}
}
|
CaseSensitivity::CaseSensitive
}, | conditional_block |
attr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::parser::SelectorImpl;
use cssparser::ToCss;
use std::fmt;
#[derive(Clone, Eq, PartialEq, ToShmem)]
#[shmem(no_bounds)]
pub struct AttrSelectorWithOptionalNamespace<Impl: SelectorImpl> {
#[shmem(field_bound)]
pub namespace: Option<NamespaceConstraint<(Impl::NamespacePrefix, Impl::NamespaceUrl)>>,
#[shmem(field_bound)]
pub local_name: Impl::LocalName,
pub local_name_lower: Impl::LocalName,
#[shmem(field_bound)]
pub operation: ParsedAttrSelectorOperation<Impl::AttrValue>,
pub never_matches: bool,
}
impl<Impl: SelectorImpl> AttrSelectorWithOptionalNamespace<Impl> {
pub fn namespace(&self) -> Option<NamespaceConstraint<&Impl::NamespaceUrl>> {
self.namespace.as_ref().map(|ns| match ns {
NamespaceConstraint::Any => NamespaceConstraint::Any,
NamespaceConstraint::Specific((_, ref url)) => NamespaceConstraint::Specific(url),
})
}
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum NamespaceConstraint<NamespaceUrl> {
Any,
/// Empty string for no namespace
Specific(NamespaceUrl),
}
#[derive(Clone, Eq, PartialEq, ToShmem)]
pub enum ParsedAttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: ParsedCaseSensitivity,
expected_value: AttrValue,
},
}
#[derive(Clone, Eq, PartialEq)]
pub enum AttrSelectorOperation<AttrValue> {
Exists,
WithValue {
operator: AttrSelectorOperator,
case_sensitivity: CaseSensitivity,
expected_value: AttrValue,
},
}
impl<AttrValue> AttrSelectorOperation<AttrValue> {
pub fn eval_str(&self, element_attr_value: &str) -> bool
where
AttrValue: AsRef<str>,
{
match *self {
AttrSelectorOperation::Exists => true,
AttrSelectorOperation::WithValue {
operator,
case_sensitivity,
ref expected_value,
} => operator.eval_str(
element_attr_value,
expected_value.as_ref(),
case_sensitivity,
),
}
}
}
#[derive(Clone, Copy, Eq, PartialEq, ToShmem)]
pub enum AttrSelectorOperator {
Equal,
Includes,
DashMatch,
Prefix,
Substring,
Suffix,
}
impl ToCss for AttrSelectorOperator {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
// https://drafts.csswg.org/cssom/#serializing-selectors
// See "attribute selector".
dest.write_str(match *self {
AttrSelectorOperator::Equal => "=",
AttrSelectorOperator::Includes => "~=",
AttrSelectorOperator::DashMatch => "|=",
AttrSelectorOperator::Prefix => "^=",
AttrSelectorOperator::Substring => "*=",
AttrSelectorOperator::Suffix => "$=",
})
}
}
impl AttrSelectorOperator {
pub fn eval_str(
self,
element_attr_value: &str,
attr_selector_value: &str,
case_sensitivity: CaseSensitivity,
) -> bool {
let e = element_attr_value.as_bytes();
let s = attr_selector_value.as_bytes();
let case = case_sensitivity;
match self {
AttrSelectorOperator::Equal => case.eq(e, s),
AttrSelectorOperator::Prefix => e.len() >= s.len() && case.eq(&e[..s.len()], s),
AttrSelectorOperator::Suffix => {
e.len() >= s.len() && case.eq(&e[(e.len() - s.len())..], s)
},
AttrSelectorOperator::Substring => {
case.contains(element_attr_value, attr_selector_value)
},
AttrSelectorOperator::Includes => element_attr_value
.split(SELECTOR_WHITESPACE)
.any(|part| case.eq(part.as_bytes(), s)),
AttrSelectorOperator::DashMatch => {
case.eq(e, s) || (e.get(s.len()) == Some(&b'-') && case.eq(&e[..s.len()], s))
},
}
}
}
/// The definition of whitespace per CSS Selectors Level 3 § 4.
pub static SELECTOR_WHITESPACE: &'static [char] = &[' ', '\t', '\n', '\r', '\x0C'];
#[derive(Clone, Copy, Debug, Eq, PartialEq, ToShmem)]
pub enum ParsedCaseSensitivity {
//'s' was specified.
ExplicitCaseSensitive,
// 'i' was specified.
AsciiCaseInsensitive,
// No flags were specified and HTML says this is a case-sensitive attribute.
CaseSensitive,
// No flags were specified and HTML says this is a case-insensitive attribute.
AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument,
}
impl ParsedCaseSensitivity {
pub fn to_unconditional(self, is_html_element_in_html_document: bool) -> CaseSensitivity {
match self {
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument
if is_html_element_in_html_document =>
{
CaseSensitivity::AsciiCaseInsensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {
CaseSensitivity::CaseSensitive
},
ParsedCaseSensitivity::CaseSensitive | ParsedCaseSensitivity::ExplicitCaseSensitive => {
CaseSensitivity::CaseSensitive
},
ParsedCaseSensitivity::AsciiCaseInsensitive => CaseSensitivity::AsciiCaseInsensitive,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CaseSensitivity {
CaseSensitive,
AsciiCaseInsensitive,
}
impl CaseSensitivity {
pub fn eq(self, a: &[u8], b: &[u8]) -> bool { |
pub fn contains(self, haystack: &str, needle: &str) -> bool {
match self {
CaseSensitivity::CaseSensitive => haystack.contains(needle),
CaseSensitivity::AsciiCaseInsensitive => {
if let Some((&n_first_byte, n_rest)) = needle.as_bytes().split_first() {
haystack.bytes().enumerate().any(|(i, byte)| {
if!byte.eq_ignore_ascii_case(&n_first_byte) {
return false;
}
let after_this_byte = &haystack.as_bytes()[i + 1..];
match after_this_byte.get(..n_rest.len()) {
None => false,
Some(haystack_slice) => haystack_slice.eq_ignore_ascii_case(n_rest),
}
})
} else {
// any_str.contains("") == true,
// though these cases should be handled with *NeverMatches and never go here.
true
}
},
}
}
}
|
match self {
CaseSensitivity::CaseSensitive => a == b,
CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
| identifier_body |
lib.rs | // Copyright 2013-2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
#![allow(deprecated)]
#![cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
#![cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))]
extern crate gdk_pixbuf;
extern crate gdk_sys;
extern crate gio;
extern crate gio_sys;
extern crate glib_sys;
#[macro_use]
extern crate glib;
extern crate cairo;
extern crate cairo_sys;
extern crate gobject_sys;
extern crate libc;
extern crate pango;
#[macro_use]
extern crate bitflags;
#[macro_use]
mod rt;
#[macro_use]
mod event;
#[cfg_attr(feature = "cargo-clippy", allow(type_complexity))]
#[cfg_attr(feature = "cargo-clippy", allow(unreadable_literal))]
mod auto;
pub mod prelude;
pub use self::auto::functions::*;
pub use auto::*;
mod atom;
mod cairo_interaction;
mod change_data;
mod device;
mod device_manager;
mod drag_context;
mod event_button;
mod event_configure;
mod event_crossing;
mod event_dnd;
mod event_expose;
mod event_focus;
mod event_grab_broken;
mod event_key;
mod event_motion;
mod event_owner_change;
#[cfg(any(feature = "v3_22", feature = "dox"))]
mod event_pad_axis;
#[cfg(any(feature = "v3_22", feature = "dox"))]
mod event_pad_button;
#[cfg(any(feature = "v3_22", feature = "dox"))]
mod event_pad_group_mode;
mod event_property;
mod event_proximity;
mod event_scroll;
mod event_selection;
mod event_setting;
mod event_touch;
#[cfg(any(feature = "v3_18", feature = "dox"))]
mod event_touchpad_pinch;
#[cfg(any(feature = "v3_18", feature = "dox"))]
mod event_touchpad_swipe;
mod event_visibility;
mod event_window_state;
mod frame_clock;
mod frame_timings;
mod functions;
mod geometry;
mod keymap;
mod keymap_key;
pub mod keys;
mod rectangle; | mod time_coord;
mod visual;
mod window;
pub use gdk_sys::GdkColor as Color;
pub use self::rt::{init, set_initialized};
pub use atom::Atom;
pub use atom::NONE as ATOM_NONE;
pub use atom::SELECTION_CLIPBOARD;
pub use atom::SELECTION_PRIMARY;
pub use atom::SELECTION_SECONDARY;
pub use atom::SELECTION_TYPE_ATOM;
pub use atom::SELECTION_TYPE_BITMAP;
pub use atom::SELECTION_TYPE_COLORMAP;
pub use atom::SELECTION_TYPE_DRAWABLE;
pub use atom::SELECTION_TYPE_INTEGER;
pub use atom::SELECTION_TYPE_PIXMAP;
pub use atom::SELECTION_TYPE_STRING;
pub use atom::SELECTION_TYPE_WINDOW;
pub use atom::TARGET_BITMAP;
pub use atom::TARGET_COLORMAP;
pub use atom::TARGET_DRAWABLE;
pub use atom::TARGET_PIXMAP;
pub use atom::TARGET_STRING;
pub use change_data::ChangeData;
pub use event::Event;
pub use event_button::EventButton;
pub use event_configure::EventConfigure;
pub use event_crossing::EventCrossing;
pub use event_dnd::EventDND;
pub use event_expose::EventExpose;
pub use event_focus::EventFocus;
pub use event_grab_broken::EventGrabBroken;
pub use event_key::EventKey;
pub use event_motion::EventMotion;
pub use event_owner_change::EventOwnerChange;
#[cfg(any(feature = "v3_22", feature = "dox"))]
pub use event_pad_axis::EventPadAxis;
#[cfg(any(feature = "v3_22", feature = "dox"))]
pub use event_pad_button::EventPadButton;
#[cfg(any(feature = "v3_22", feature = "dox"))]
pub use event_pad_group_mode::EventPadGroupMode;
pub use event_property::EventProperty;
pub use event_proximity::EventProximity;
pub use event_scroll::EventScroll;
pub use event_selection::EventSelection;
pub use event_setting::EventSetting;
pub use event_touch::EventTouch;
#[cfg(any(feature = "v3_18", feature = "dox"))]
pub use event_touchpad_pinch::EventTouchpadPinch;
#[cfg(any(feature = "v3_18", feature = "dox"))]
pub use event_touchpad_swipe::EventTouchpadSwipe;
pub use event_visibility::EventVisibility;
pub use event_window_state::EventWindowState;
pub use functions::*;
pub use geometry::Geometry;
pub use keymap_key::KeymapKey;
pub use rectangle::Rectangle;
pub use rgba::{RgbaParseError, RGBA};
pub use time_coord::TimeCoord;
pub use window::WindowAttr;
#[allow(non_camel_case_types)]
pub type key = i32;
/// The primary button. This is typically the left mouse button, or the right button in a left-handed setup.
pub const BUTTON_PRIMARY: u32 = gdk_sys::GDK_BUTTON_PRIMARY as u32;
/// The middle button.
pub const BUTTON_MIDDLE: u32 = gdk_sys::GDK_BUTTON_MIDDLE as u32;
/// The secondary button. This is typically the right mouse button, or the left button in a left-handed setup.
pub const BUTTON_SECONDARY: u32 = gdk_sys::GDK_BUTTON_SECONDARY as u32;
// Used as the return value for stopping the propagation of an event handler.
pub const EVENT_STOP: u32 = gdk_sys::GDK_EVENT_STOP as u32;
// Used as the return value for continuing the propagation of an event handler.
pub const EVENT_PROPAGATE: u32 = gdk_sys::GDK_EVENT_PROPAGATE as u32; | mod rgba;
mod screen; | random_line_split |
macros.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
macro_rules! mint_vec {
($name:ident [ $($field:ident),* ] = $std_name:ident) => {
#[cfg(feature = "mint")]
impl<T, U> From<mint::$std_name<T>> for $name<T, U> {
fn from(v: mint::$std_name<T>) -> Self {
$name {
$( $field: v.$field, )*
_unit: PhantomData,
}
}
} | mint::$std_name {
$( $field: self.$field, )*
}
}
}
}
} | #[cfg(feature = "mint")]
impl<T, U> Into<mint::$std_name<T>> for $name<T, U> {
fn into(self) -> mint::$std_name<T> { | random_line_split |
i2c_ds3231.rs | // i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231
// RTC using I2C.
use std::error::Error;
use std::thread;
use std::time::Duration;
use rppal::i2c::I2c;
// DS3231 I2C default slave address.
const ADDR_DS3231: u16 = 0x68;
| const REG_SECONDS: usize = 0x00;
const REG_MINUTES: usize = 0x01;
const REG_HOURS: usize = 0x02;
// Helper functions to encode and decode binary-coded decimal (BCD) values.
fn bcd2dec(bcd: u8) -> u8 {
(((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F)
}
fn dec2bcd(dec: u8) -> u8 {
((dec / 10) << 4) | (dec % 10)
}
fn main() -> Result<(), Box<dyn Error>> {
let mut i2c = I2c::new()?;
// Set the I2C slave address to the device we're communicating with.
i2c.set_slave_address(ADDR_DS3231)?;
// Set the time to 11:59:50 AM. Start at register address 0x00 (Seconds) and
// write 3 bytes, overwriting the Seconds, Minutes and Hours registers.
// Setting bit 6 of the Hours register indicates we're using a 12-hour
// format. Leaving bit 5 unset indicates AM.
i2c.block_write(
REG_SECONDS as u8,
&[dec2bcd(50), dec2bcd(59), dec2bcd(11) | (1 << 6)],
)?;
let mut reg = [0u8; 3];
loop {
// Start at register address 0x00 (Seconds) and read the values of the
// next 3 registers (Seconds, Minutes, Hours) into the reg variable.
i2c.block_read(REG_SECONDS as u8, &mut reg)?;
// Display the retrieved time in the appropriate format based on bit 6 of
// the Hours register.
if reg[REG_HOURS] & (1 << 6) > 0 {
// 12-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2} {}",
bcd2dec(reg[REG_HOURS] & 0x1F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS]),
if reg[REG_HOURS] & (1 << 5) > 0 {
"PM"
} else {
"AM"
}
);
} else {
// 24-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2}",
bcd2dec(reg[REG_HOURS] & 0x3F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS])
);
}
thread::sleep(Duration::from_secs(1));
}
} | // DS3231 register addresses. | random_line_split |
i2c_ds3231.rs | // i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231
// RTC using I2C.
use std::error::Error;
use std::thread;
use std::time::Duration;
use rppal::i2c::I2c;
// DS3231 I2C default slave address.
const ADDR_DS3231: u16 = 0x68;
// DS3231 register addresses.
const REG_SECONDS: usize = 0x00;
const REG_MINUTES: usize = 0x01;
const REG_HOURS: usize = 0x02;
// Helper functions to encode and decode binary-coded decimal (BCD) values.
fn bcd2dec(bcd: u8) -> u8 |
fn dec2bcd(dec: u8) -> u8 {
((dec / 10) << 4) | (dec % 10)
}
fn main() -> Result<(), Box<dyn Error>> {
let mut i2c = I2c::new()?;
// Set the I2C slave address to the device we're communicating with.
i2c.set_slave_address(ADDR_DS3231)?;
// Set the time to 11:59:50 AM. Start at register address 0x00 (Seconds) and
// write 3 bytes, overwriting the Seconds, Minutes and Hours registers.
// Setting bit 6 of the Hours register indicates we're using a 12-hour
// format. Leaving bit 5 unset indicates AM.
i2c.block_write(
REG_SECONDS as u8,
&[dec2bcd(50), dec2bcd(59), dec2bcd(11) | (1 << 6)],
)?;
let mut reg = [0u8; 3];
loop {
// Start at register address 0x00 (Seconds) and read the values of the
// next 3 registers (Seconds, Minutes, Hours) into the reg variable.
i2c.block_read(REG_SECONDS as u8, &mut reg)?;
// Display the retrieved time in the appropriate format based on bit 6 of
// the Hours register.
if reg[REG_HOURS] & (1 << 6) > 0 {
// 12-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2} {}",
bcd2dec(reg[REG_HOURS] & 0x1F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS]),
if reg[REG_HOURS] & (1 << 5) > 0 {
"PM"
} else {
"AM"
}
);
} else {
// 24-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2}",
bcd2dec(reg[REG_HOURS] & 0x3F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS])
);
}
thread::sleep(Duration::from_secs(1));
}
}
| {
(((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F)
} | identifier_body |
i2c_ds3231.rs | // i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231
// RTC using I2C.
use std::error::Error;
use std::thread;
use std::time::Duration;
use rppal::i2c::I2c;
// DS3231 I2C default slave address.
const ADDR_DS3231: u16 = 0x68;
// DS3231 register addresses.
const REG_SECONDS: usize = 0x00;
const REG_MINUTES: usize = 0x01;
const REG_HOURS: usize = 0x02;
// Helper functions to encode and decode binary-coded decimal (BCD) values.
fn | (bcd: u8) -> u8 {
(((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F)
}
fn dec2bcd(dec: u8) -> u8 {
((dec / 10) << 4) | (dec % 10)
}
fn main() -> Result<(), Box<dyn Error>> {
let mut i2c = I2c::new()?;
// Set the I2C slave address to the device we're communicating with.
i2c.set_slave_address(ADDR_DS3231)?;
// Set the time to 11:59:50 AM. Start at register address 0x00 (Seconds) and
// write 3 bytes, overwriting the Seconds, Minutes and Hours registers.
// Setting bit 6 of the Hours register indicates we're using a 12-hour
// format. Leaving bit 5 unset indicates AM.
i2c.block_write(
REG_SECONDS as u8,
&[dec2bcd(50), dec2bcd(59), dec2bcd(11) | (1 << 6)],
)?;
let mut reg = [0u8; 3];
loop {
// Start at register address 0x00 (Seconds) and read the values of the
// next 3 registers (Seconds, Minutes, Hours) into the reg variable.
i2c.block_read(REG_SECONDS as u8, &mut reg)?;
// Display the retrieved time in the appropriate format based on bit 6 of
// the Hours register.
if reg[REG_HOURS] & (1 << 6) > 0 {
// 12-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2} {}",
bcd2dec(reg[REG_HOURS] & 0x1F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS]),
if reg[REG_HOURS] & (1 << 5) > 0 {
"PM"
} else {
"AM"
}
);
} else {
// 24-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2}",
bcd2dec(reg[REG_HOURS] & 0x3F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS])
);
}
thread::sleep(Duration::from_secs(1));
}
}
| bcd2dec | identifier_name |
i2c_ds3231.rs | // i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231
// RTC using I2C.
use std::error::Error;
use std::thread;
use std::time::Duration;
use rppal::i2c::I2c;
// DS3231 I2C default slave address.
const ADDR_DS3231: u16 = 0x68;
// DS3231 register addresses.
const REG_SECONDS: usize = 0x00;
const REG_MINUTES: usize = 0x01;
const REG_HOURS: usize = 0x02;
// Helper functions to encode and decode binary-coded decimal (BCD) values.
fn bcd2dec(bcd: u8) -> u8 {
(((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F)
}
fn dec2bcd(dec: u8) -> u8 {
((dec / 10) << 4) | (dec % 10)
}
fn main() -> Result<(), Box<dyn Error>> {
let mut i2c = I2c::new()?;
// Set the I2C slave address to the device we're communicating with.
i2c.set_slave_address(ADDR_DS3231)?;
// Set the time to 11:59:50 AM. Start at register address 0x00 (Seconds) and
// write 3 bytes, overwriting the Seconds, Minutes and Hours registers.
// Setting bit 6 of the Hours register indicates we're using a 12-hour
// format. Leaving bit 5 unset indicates AM.
i2c.block_write(
REG_SECONDS as u8,
&[dec2bcd(50), dec2bcd(59), dec2bcd(11) | (1 << 6)],
)?;
let mut reg = [0u8; 3];
loop {
// Start at register address 0x00 (Seconds) and read the values of the
// next 3 registers (Seconds, Minutes, Hours) into the reg variable.
i2c.block_read(REG_SECONDS as u8, &mut reg)?;
// Display the retrieved time in the appropriate format based on bit 6 of
// the Hours register.
if reg[REG_HOURS] & (1 << 6) > 0 | else {
// 24-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2}",
bcd2dec(reg[REG_HOURS] & 0x3F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS])
);
}
thread::sleep(Duration::from_secs(1));
}
}
| {
// 12-hour format.
println!(
"{:0>2}:{:0>2}:{:0>2} {}",
bcd2dec(reg[REG_HOURS] & 0x1F),
bcd2dec(reg[REG_MINUTES]),
bcd2dec(reg[REG_SECONDS]),
if reg[REG_HOURS] & (1 << 5) > 0 {
"PM"
} else {
"AM"
}
);
} | conditional_block |
dfs.rs | //! `PathExplorer` that works by exploring the CFG in Depth First Order.
use std::collections::VecDeque;
use libsmt::theories::core;
use explorer::explorer::PathExplorer;
use engine::rune::RuneControl;
use context::context::{Context, Evaluate, RegisterRead};
use context::rune_ctx::RuneContext;
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(dead_code)]
enum BranchType {
True,
False, | }
#[derive(Clone, Debug)]
struct SavedState<C: Context> {
pub ctx: C,
pub branch: BranchType,
}
impl<C: Context> SavedState<C> {
fn new(ctx: C, b: BranchType) -> SavedState<C> {
SavedState {
ctx: ctx,
branch: b,
}
}
}
/// An explorer that traverses the program states in a depth first order.
pub struct DFSExplorer<Ctx: Context> {
/// Depth First Queue
queue: VecDeque<SavedState<Ctx>>,
}
// TODO: [X] Add constraints for T/F branch
// [ ] Check if the paths are feasible before enqueue
impl PathExplorer for DFSExplorer<RuneContext> {
type C = RuneControl;
type Ctx = RuneContext;
fn new() -> DFSExplorer<RuneContext> {
DFSExplorer { queue: VecDeque::new() }
}
// TODO: Terminate the current execution path if the depth is greater than a
// preset threshold.
fn next(&mut self, _: &mut Self::Ctx) -> RuneControl {
RuneControl::Continue
}
// When rune finishes its execution, pop another unexplored path for it to
// explore.
fn next_job(&mut self, ctx: &mut Self::Ctx) -> Option<RuneControl> {
if let Some(ref state) = self.queue.pop_back() {
*ctx = state.ctx.clone();
Some(match state.branch {
BranchType::True => RuneControl::ExploreTrue,
BranchType::False => RuneControl::ExploreFalse,
})
} else {
None
}
}
fn register_branch(&mut self,
ctx: &mut Self::Ctx,
condition: <Self::Ctx as RegisterRead>::VarRef)
-> RuneControl {
// When a new branch is encountered, push the false branch into the queue and
// explore the
// true branch. Note that this choice is arbitrary and we could have as well
// chosen the
// other part without changing the nature of this explorer.
let mut false_ctx = ctx.clone();
{
let zero = ctx.define_const(0, 1);
false_ctx.eval(core::OpCodes::Cmp, &[condition, zero]);
}
self.queue.push_back(SavedState::new(false_ctx, BranchType::False));
{
let one = ctx.define_const(1, 1);
ctx.eval(core::OpCodes::Cmp, &[condition, one]);
}
RuneControl::ExploreTrue
}
} | random_line_split |
|
dfs.rs | //! `PathExplorer` that works by exploring the CFG in Depth First Order.
use std::collections::VecDeque;
use libsmt::theories::core;
use explorer::explorer::PathExplorer;
use engine::rune::RuneControl;
use context::context::{Context, Evaluate, RegisterRead};
use context::rune_ctx::RuneContext;
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(dead_code)]
enum BranchType {
True,
False,
}
#[derive(Clone, Debug)]
struct SavedState<C: Context> {
pub ctx: C,
pub branch: BranchType,
}
impl<C: Context> SavedState<C> {
fn new(ctx: C, b: BranchType) -> SavedState<C> {
SavedState {
ctx: ctx,
branch: b,
}
}
}
/// An explorer that traverses the program states in a depth first order.
pub struct DFSExplorer<Ctx: Context> {
/// Depth First Queue
queue: VecDeque<SavedState<Ctx>>,
}
// TODO: [X] Add constraints for T/F branch
// [ ] Check if the paths are feasible before enqueue
impl PathExplorer for DFSExplorer<RuneContext> {
type C = RuneControl;
type Ctx = RuneContext;
fn new() -> DFSExplorer<RuneContext> {
DFSExplorer { queue: VecDeque::new() }
}
// TODO: Terminate the current execution path if the depth is greater than a
// preset threshold.
fn next(&mut self, _: &mut Self::Ctx) -> RuneControl {
RuneControl::Continue
}
// When rune finishes its execution, pop another unexplored path for it to
// explore.
fn next_job(&mut self, ctx: &mut Self::Ctx) -> Option<RuneControl> {
if let Some(ref state) = self.queue.pop_back() | else {
None
}
}
fn register_branch(&mut self,
ctx: &mut Self::Ctx,
condition: <Self::Ctx as RegisterRead>::VarRef)
-> RuneControl {
// When a new branch is encountered, push the false branch into the queue and
// explore the
// true branch. Note that this choice is arbitrary and we could have as well
// chosen the
// other part without changing the nature of this explorer.
let mut false_ctx = ctx.clone();
{
let zero = ctx.define_const(0, 1);
false_ctx.eval(core::OpCodes::Cmp, &[condition, zero]);
}
self.queue.push_back(SavedState::new(false_ctx, BranchType::False));
{
let one = ctx.define_const(1, 1);
ctx.eval(core::OpCodes::Cmp, &[condition, one]);
}
RuneControl::ExploreTrue
}
}
| {
*ctx = state.ctx.clone();
Some(match state.branch {
BranchType::True => RuneControl::ExploreTrue,
BranchType::False => RuneControl::ExploreFalse,
})
} | conditional_block |
dfs.rs | //! `PathExplorer` that works by exploring the CFG in Depth First Order.
use std::collections::VecDeque;
use libsmt::theories::core;
use explorer::explorer::PathExplorer;
use engine::rune::RuneControl;
use context::context::{Context, Evaluate, RegisterRead};
use context::rune_ctx::RuneContext;
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(dead_code)]
enum | {
True,
False,
}
#[derive(Clone, Debug)]
struct SavedState<C: Context> {
pub ctx: C,
pub branch: BranchType,
}
impl<C: Context> SavedState<C> {
fn new(ctx: C, b: BranchType) -> SavedState<C> {
SavedState {
ctx: ctx,
branch: b,
}
}
}
/// An explorer that traverses the program states in a depth first order.
pub struct DFSExplorer<Ctx: Context> {
/// Depth First Queue
queue: VecDeque<SavedState<Ctx>>,
}
// TODO: [X] Add constraints for T/F branch
// [ ] Check if the paths are feasible before enqueue
impl PathExplorer for DFSExplorer<RuneContext> {
type C = RuneControl;
type Ctx = RuneContext;
fn new() -> DFSExplorer<RuneContext> {
DFSExplorer { queue: VecDeque::new() }
}
// TODO: Terminate the current execution path if the depth is greater than a
// preset threshold.
fn next(&mut self, _: &mut Self::Ctx) -> RuneControl {
RuneControl::Continue
}
// When rune finishes its execution, pop another unexplored path for it to
// explore.
fn next_job(&mut self, ctx: &mut Self::Ctx) -> Option<RuneControl> {
if let Some(ref state) = self.queue.pop_back() {
*ctx = state.ctx.clone();
Some(match state.branch {
BranchType::True => RuneControl::ExploreTrue,
BranchType::False => RuneControl::ExploreFalse,
})
} else {
None
}
}
fn register_branch(&mut self,
ctx: &mut Self::Ctx,
condition: <Self::Ctx as RegisterRead>::VarRef)
-> RuneControl {
// When a new branch is encountered, push the false branch into the queue and
// explore the
// true branch. Note that this choice is arbitrary and we could have as well
// chosen the
// other part without changing the nature of this explorer.
let mut false_ctx = ctx.clone();
{
let zero = ctx.define_const(0, 1);
false_ctx.eval(core::OpCodes::Cmp, &[condition, zero]);
}
self.queue.push_back(SavedState::new(false_ctx, BranchType::False));
{
let one = ctx.define_const(1, 1);
ctx.eval(core::OpCodes::Cmp, &[condition, one]);
}
RuneControl::ExploreTrue
}
}
| BranchType | identifier_name |
dfs.rs | //! `PathExplorer` that works by exploring the CFG in Depth First Order.
use std::collections::VecDeque;
use libsmt::theories::core;
use explorer::explorer::PathExplorer;
use engine::rune::RuneControl;
use context::context::{Context, Evaluate, RegisterRead};
use context::rune_ctx::RuneContext;
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(dead_code)]
enum BranchType {
True,
False,
}
#[derive(Clone, Debug)]
struct SavedState<C: Context> {
pub ctx: C,
pub branch: BranchType,
}
impl<C: Context> SavedState<C> {
fn new(ctx: C, b: BranchType) -> SavedState<C> {
SavedState {
ctx: ctx,
branch: b,
}
}
}
/// An explorer that traverses the program states in a depth first order.
pub struct DFSExplorer<Ctx: Context> {
/// Depth First Queue
queue: VecDeque<SavedState<Ctx>>,
}
// TODO: [X] Add constraints for T/F branch
// [ ] Check if the paths are feasible before enqueue
impl PathExplorer for DFSExplorer<RuneContext> {
type C = RuneControl;
type Ctx = RuneContext;
fn new() -> DFSExplorer<RuneContext> {
DFSExplorer { queue: VecDeque::new() }
}
// TODO: Terminate the current execution path if the depth is greater than a
// preset threshold.
fn next(&mut self, _: &mut Self::Ctx) -> RuneControl {
RuneControl::Continue
}
// When rune finishes its execution, pop another unexplored path for it to
// explore.
fn next_job(&mut self, ctx: &mut Self::Ctx) -> Option<RuneControl> |
fn register_branch(&mut self,
ctx: &mut Self::Ctx,
condition: <Self::Ctx as RegisterRead>::VarRef)
-> RuneControl {
// When a new branch is encountered, push the false branch into the queue and
// explore the
// true branch. Note that this choice is arbitrary and we could have as well
// chosen the
// other part without changing the nature of this explorer.
let mut false_ctx = ctx.clone();
{
let zero = ctx.define_const(0, 1);
false_ctx.eval(core::OpCodes::Cmp, &[condition, zero]);
}
self.queue.push_back(SavedState::new(false_ctx, BranchType::False));
{
let one = ctx.define_const(1, 1);
ctx.eval(core::OpCodes::Cmp, &[condition, one]);
}
RuneControl::ExploreTrue
}
}
| {
if let Some(ref state) = self.queue.pop_back() {
*ctx = state.ctx.clone();
Some(match state.branch {
BranchType::True => RuneControl::ExploreTrue,
BranchType::False => RuneControl::ExploreFalse,
})
} else {
None
}
} | identifier_body |
chacha.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.
//! The ChaCha random number generator.
use core::prelude::*;
use {Rng, SeedableRng, Rand};
const KEY_WORDS : uint = 8; // 8 words for the 256-bit key
const STATE_WORDS : uint = 16;
const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing
/// A random number generator that uses the ChaCha20 algorithm [1].
///
/// The ChaCha algorithm is widely accepted as suitable for
/// cryptographic purposes, but this implementation has not been
/// verified as such. Prefer a generator like `OsRng` that defers to
/// the operating system for cases that need high security.
///
/// [1]: D. J. Bernstein, [*ChaCha, a variant of
/// Salsa20*](http://cr.yp.to/chacha.html)
pub struct ChaChaRng {
buffer: [u32,..STATE_WORDS], // Internal buffer of output
state: [u32,..STATE_WORDS], // Initial state
index: uint, // Index into state
}
static EMPTY: ChaChaRng = ChaChaRng {
buffer: [0,..STATE_WORDS],
state: [0,..STATE_WORDS],
index: STATE_WORDS
};
macro_rules! quarter_round{
($a: expr, $b: expr, $c: expr, $d: expr) => {{
$a += $b; $d ^= $a; $d = $d.rotate_left(16);
$c += $d; $b ^= $c; $b = $b.rotate_left(12);
$a += $b; $d ^= $a; $d = $d.rotate_left( 8);
$c += $d; $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round{
($x: expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
#[inline]
fn core(output: &mut [u32,..STATE_WORDS], input: &[u32,..STATE_WORDS]) {
*output = *input;
for _ in range(0, CHACHA_ROUNDS / 2) {
double_round!(output);
}
for i in range(0, STATE_WORDS) {
output[i] += input[i];
}
}
impl ChaChaRng {
/// Create an ChaCha random number generator using the default
/// fixed key of 8 zero words.
pub fn new_unseeded() -> ChaChaRng {
let mut rng = EMPTY;
rng.init(&[0,..KEY_WORDS]);
rng
}
/// Sets the internal 128-bit ChaCha counter to
/// a user-provided value. This permits jumping
/// arbitrarily ahead (or backwards) in the pseudorandom stream.
///
/// Since the nonce words are used to extend the counter to 128 bits,
/// users wishing to obtain the conventional ChaCha pseudorandom stream
/// associated with a particular nonce can call this function with
/// arguments `0, desired_nonce`.
pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) {
self.state[12] = (counter_low >> 0) as u32;
self.state[13] = (counter_low >> 32) as u32;
self.state[14] = (counter_high >> 0) as u32;
self.state[15] = (counter_high >> 32) as u32;
self.index = STATE_WORDS; // force recomputation
}
/// Initializes `self.state` with the appropriate key and constants
///
/// We deviate slightly from the ChaCha specification regarding
/// the nonce, which is used to extend the counter to 128 bits.
/// This is provably as strong as the original cipher, though,
/// since any distinguishing attack on our variant also works
/// against ChaCha with a chosen-nonce. See the XSalsa20 [1]
/// security proof for a more involved example of this.
///
/// The modified word layout is:
/// ```notrust
/// constant constant constant constant
/// key key key key
/// key key key key
/// counter counter counter counter
/// ```
/// [1]: Daniel J. Bernstein. [*Extending the Salsa20
/// nonce.*](http://cr.yp.to/papers.html#xsalsa)
fn init(&mut self, key: &[u32,..KEY_WORDS]) {
self.state[0] = 0x61707865;
self.state[1] = 0x3320646E;
self.state[2] = 0x79622D32;
self.state[3] = 0x6B206574;
for i in range(0, KEY_WORDS) {
self.state[4+i] = key[i];
}
self.state[12] = 0;
self.state[13] = 0;
self.state[14] = 0;
self.state[15] = 0;
self.index = STATE_WORDS;
}
/// Refill the internal output buffer (`self.buffer`)
fn update(&mut self) {
core(&mut self.buffer, &self.state);
self.index = 0;
// update 128-bit counter
self.state[12] += 1;
if self.state[12]!= 0 { return };
self.state[13] += 1;
if self.state[13]!= 0 { return };
self.state[14] += 1;
if self.state[14]!= 0 { return };
self.state[15] += 1;
}
}
impl Rng for ChaChaRng {
#[inline]
fn next_u32(&mut self) -> u32 |
}
impl<'a> SeedableRng<&'a [u32]> for ChaChaRng {
fn reseed(&mut self, seed: &'a [u32]) {
// reset state
self.init(&[0u32,..KEY_WORDS]);
// set key inplace
let key = self.state.slice_mut(4, 4+KEY_WORDS);
for (k, s) in key.iter_mut().zip(seed.iter()) {
*k = *s;
}
}
/// Create a ChaCha generator from a seed,
/// obtained from a variable-length u32 array.
/// Only up to 8 words are used; if less than 8
/// words are used, the remaining are set to zero.
fn from_seed(seed: &'a [u32]) -> ChaChaRng {
let mut rng = EMPTY;
rng.reseed(seed);
rng
}
}
impl Rand for ChaChaRng {
fn rand<R: Rng>(other: &mut R) -> ChaChaRng {
let mut key : [u32,..KEY_WORDS] = [0,..KEY_WORDS];
for word in key.iter_mut() {
*word = other.gen();
}
SeedableRng::from_seed(key.as_slice())
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use core::iter::order;
use {Rng, SeedableRng};
use super::ChaChaRng;
#[test]
fn test_rng_rand_seeded() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut ra: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let mut rb: ChaChaRng = SeedableRng::from_seed(s.as_slice());
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_seeded() {
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let mut rb: ChaChaRng = SeedableRng::from_seed(seed);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut r: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed(s.as_slice());
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
#[test]
fn test_rng_true_values() {
// Test vectors 1 and 2 from
// http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
let seed : &[_] = &[0u32,..8];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653,
0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b,
0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8,
0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2));
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73,
0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32,
0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874,
0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b));
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
// Store the 17*i-th 32-bit word,
// i.e., the i-th word of the i-th 16-word block
let mut v : Vec<u32> = Vec::new();
for _ in range(0u, 16) {
v.push(ra.next_u32());
for _ in range(0u, 16) {
ra.next_u32();
}
}
assert_eq!(v,
vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036,
0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384,
0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530,
0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4));
}
}
| {
if self.index == STATE_WORDS {
self.update();
}
let value = self.buffer[self.index % STATE_WORDS];
self.index += 1;
value
} | identifier_body |
chacha.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.
//! The ChaCha random number generator.
use core::prelude::*;
use {Rng, SeedableRng, Rand};
const KEY_WORDS : uint = 8; // 8 words for the 256-bit key
const STATE_WORDS : uint = 16;
const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing
/// A random number generator that uses the ChaCha20 algorithm [1].
///
/// The ChaCha algorithm is widely accepted as suitable for
/// cryptographic purposes, but this implementation has not been
/// verified as such. Prefer a generator like `OsRng` that defers to
/// the operating system for cases that need high security.
///
/// [1]: D. J. Bernstein, [*ChaCha, a variant of
/// Salsa20*](http://cr.yp.to/chacha.html)
pub struct ChaChaRng {
buffer: [u32,..STATE_WORDS], // Internal buffer of output
state: [u32,..STATE_WORDS], // Initial state
index: uint, // Index into state
}
static EMPTY: ChaChaRng = ChaChaRng {
buffer: [0,..STATE_WORDS],
state: [0,..STATE_WORDS],
index: STATE_WORDS
};
macro_rules! quarter_round{
($a: expr, $b: expr, $c: expr, $d: expr) => {{
$a += $b; $d ^= $a; $d = $d.rotate_left(16);
$c += $d; $b ^= $c; $b = $b.rotate_left(12);
$a += $b; $d ^= $a; $d = $d.rotate_left( 8);
$c += $d; $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round{
($x: expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
#[inline]
fn core(output: &mut [u32,..STATE_WORDS], input: &[u32,..STATE_WORDS]) {
*output = *input;
for _ in range(0, CHACHA_ROUNDS / 2) {
double_round!(output);
}
for i in range(0, STATE_WORDS) {
output[i] += input[i];
}
}
impl ChaChaRng {
/// Create an ChaCha random number generator using the default
/// fixed key of 8 zero words.
pub fn new_unseeded() -> ChaChaRng {
let mut rng = EMPTY;
rng.init(&[0,..KEY_WORDS]);
rng
}
/// Sets the internal 128-bit ChaCha counter to
/// a user-provided value. This permits jumping
/// arbitrarily ahead (or backwards) in the pseudorandom stream.
///
/// Since the nonce words are used to extend the counter to 128 bits,
/// users wishing to obtain the conventional ChaCha pseudorandom stream
/// associated with a particular nonce can call this function with
/// arguments `0, desired_nonce`.
pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) {
self.state[12] = (counter_low >> 0) as u32;
self.state[13] = (counter_low >> 32) as u32;
self.state[14] = (counter_high >> 0) as u32;
self.state[15] = (counter_high >> 32) as u32;
self.index = STATE_WORDS; // force recomputation
}
/// Initializes `self.state` with the appropriate key and constants
///
/// We deviate slightly from the ChaCha specification regarding
/// the nonce, which is used to extend the counter to 128 bits.
/// This is provably as strong as the original cipher, though,
/// since any distinguishing attack on our variant also works
/// against ChaCha with a chosen-nonce. See the XSalsa20 [1]
/// security proof for a more involved example of this.
///
/// The modified word layout is:
/// ```notrust
/// constant constant constant constant
/// key key key key
/// key key key key
/// counter counter counter counter
/// ```
/// [1]: Daniel J. Bernstein. [*Extending the Salsa20
/// nonce.*](http://cr.yp.to/papers.html#xsalsa)
fn init(&mut self, key: &[u32,..KEY_WORDS]) {
self.state[0] = 0x61707865;
self.state[1] = 0x3320646E;
self.state[2] = 0x79622D32;
self.state[3] = 0x6B206574;
for i in range(0, KEY_WORDS) {
self.state[4+i] = key[i];
}
self.state[12] = 0;
self.state[13] = 0;
self.state[14] = 0;
self.state[15] = 0;
self.index = STATE_WORDS;
}
/// Refill the internal output buffer (`self.buffer`)
fn update(&mut self) {
core(&mut self.buffer, &self.state);
self.index = 0;
// update 128-bit counter
self.state[12] += 1;
if self.state[12]!= 0 { return };
self.state[13] += 1;
if self.state[13]!= 0 { return };
self.state[14] += 1;
if self.state[14]!= 0 { return };
self.state[15] += 1;
}
}
impl Rng for ChaChaRng {
#[inline]
fn next_u32(&mut self) -> u32 {
if self.index == STATE_WORDS {
self.update();
}
let value = self.buffer[self.index % STATE_WORDS];
self.index += 1;
value
}
}
impl<'a> SeedableRng<&'a [u32]> for ChaChaRng {
fn reseed(&mut self, seed: &'a [u32]) {
// reset state
self.init(&[0u32,..KEY_WORDS]);
// set key inplace
let key = self.state.slice_mut(4, 4+KEY_WORDS);
for (k, s) in key.iter_mut().zip(seed.iter()) {
*k = *s;
}
}
/// Create a ChaCha generator from a seed,
/// obtained from a variable-length u32 array.
/// Only up to 8 words are used; if less than 8
/// words are used, the remaining are set to zero.
fn from_seed(seed: &'a [u32]) -> ChaChaRng {
let mut rng = EMPTY;
rng.reseed(seed);
rng
}
}
impl Rand for ChaChaRng {
fn rand<R: Rng>(other: &mut R) -> ChaChaRng {
let mut key : [u32,..KEY_WORDS] = [0,..KEY_WORDS];
for word in key.iter_mut() {
*word = other.gen();
}
SeedableRng::from_seed(key.as_slice())
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use core::iter::order;
use {Rng, SeedableRng};
use super::ChaChaRng;
#[test]
fn test_rng_rand_seeded() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut ra: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let mut rb: ChaChaRng = SeedableRng::from_seed(s.as_slice());
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_seeded() {
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let mut rb: ChaChaRng = SeedableRng::from_seed(seed);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut r: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed(s.as_slice());
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
#[test]
fn | () {
// Test vectors 1 and 2 from
// http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
let seed : &[_] = &[0u32,..8];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653,
0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b,
0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8,
0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2));
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73,
0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32,
0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874,
0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b));
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
// Store the 17*i-th 32-bit word,
// i.e., the i-th word of the i-th 16-word block
let mut v : Vec<u32> = Vec::new();
for _ in range(0u, 16) {
v.push(ra.next_u32());
for _ in range(0u, 16) {
ra.next_u32();
}
}
assert_eq!(v,
vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036,
0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384,
0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530,
0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4));
}
}
| test_rng_true_values | identifier_name |
chacha.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.
//! The ChaCha random number generator.
use core::prelude::*;
use {Rng, SeedableRng, Rand};
const KEY_WORDS : uint = 8; // 8 words for the 256-bit key
const STATE_WORDS : uint = 16;
const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing
/// A random number generator that uses the ChaCha20 algorithm [1].
///
/// The ChaCha algorithm is widely accepted as suitable for
/// cryptographic purposes, but this implementation has not been
/// verified as such. Prefer a generator like `OsRng` that defers to
/// the operating system for cases that need high security.
///
/// [1]: D. J. Bernstein, [*ChaCha, a variant of
/// Salsa20*](http://cr.yp.to/chacha.html)
pub struct ChaChaRng {
buffer: [u32,..STATE_WORDS], // Internal buffer of output
state: [u32,..STATE_WORDS], // Initial state
index: uint, // Index into state
}
static EMPTY: ChaChaRng = ChaChaRng {
buffer: [0,..STATE_WORDS],
state: [0,..STATE_WORDS],
index: STATE_WORDS
};
macro_rules! quarter_round{
($a: expr, $b: expr, $c: expr, $d: expr) => {{
$a += $b; $d ^= $a; $d = $d.rotate_left(16);
$c += $d; $b ^= $c; $b = $b.rotate_left(12);
$a += $b; $d ^= $a; $d = $d.rotate_left( 8);
$c += $d; $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round{
($x: expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
#[inline]
fn core(output: &mut [u32,..STATE_WORDS], input: &[u32,..STATE_WORDS]) {
*output = *input;
for _ in range(0, CHACHA_ROUNDS / 2) {
double_round!(output);
}
for i in range(0, STATE_WORDS) {
output[i] += input[i];
}
}
impl ChaChaRng {
/// Create an ChaCha random number generator using the default
/// fixed key of 8 zero words.
pub fn new_unseeded() -> ChaChaRng {
let mut rng = EMPTY;
rng.init(&[0,..KEY_WORDS]);
rng
}
/// Sets the internal 128-bit ChaCha counter to
/// a user-provided value. This permits jumping
/// arbitrarily ahead (or backwards) in the pseudorandom stream.
///
/// Since the nonce words are used to extend the counter to 128 bits,
/// users wishing to obtain the conventional ChaCha pseudorandom stream
/// associated with a particular nonce can call this function with
/// arguments `0, desired_nonce`.
pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) {
self.state[12] = (counter_low >> 0) as u32;
self.state[13] = (counter_low >> 32) as u32;
self.state[14] = (counter_high >> 0) as u32;
self.state[15] = (counter_high >> 32) as u32;
self.index = STATE_WORDS; // force recomputation
}
/// Initializes `self.state` with the appropriate key and constants
///
/// We deviate slightly from the ChaCha specification regarding
/// the nonce, which is used to extend the counter to 128 bits.
/// This is provably as strong as the original cipher, though,
/// since any distinguishing attack on our variant also works
/// against ChaCha with a chosen-nonce. See the XSalsa20 [1]
/// security proof for a more involved example of this.
///
/// The modified word layout is:
/// ```notrust
/// constant constant constant constant
/// key key key key
/// key key key key
/// counter counter counter counter
/// ```
/// [1]: Daniel J. Bernstein. [*Extending the Salsa20
/// nonce.*](http://cr.yp.to/papers.html#xsalsa)
fn init(&mut self, key: &[u32,..KEY_WORDS]) {
self.state[0] = 0x61707865;
self.state[1] = 0x3320646E;
self.state[2] = 0x79622D32;
self.state[3] = 0x6B206574;
for i in range(0, KEY_WORDS) {
self.state[4+i] = key[i];
}
self.state[12] = 0;
self.state[13] = 0;
self.state[14] = 0;
self.state[15] = 0;
self.index = STATE_WORDS;
}
/// Refill the internal output buffer (`self.buffer`)
fn update(&mut self) {
core(&mut self.buffer, &self.state);
self.index = 0;
// update 128-bit counter
self.state[12] += 1;
if self.state[12]!= 0 { return };
self.state[13] += 1;
if self.state[13]!= 0 { return };
self.state[14] += 1;
if self.state[14]!= 0 { return };
self.state[15] += 1;
}
}
impl Rng for ChaChaRng {
#[inline]
fn next_u32(&mut self) -> u32 {
if self.index == STATE_WORDS |
let value = self.buffer[self.index % STATE_WORDS];
self.index += 1;
value
}
}
impl<'a> SeedableRng<&'a [u32]> for ChaChaRng {
fn reseed(&mut self, seed: &'a [u32]) {
// reset state
self.init(&[0u32,..KEY_WORDS]);
// set key inplace
let key = self.state.slice_mut(4, 4+KEY_WORDS);
for (k, s) in key.iter_mut().zip(seed.iter()) {
*k = *s;
}
}
/// Create a ChaCha generator from a seed,
/// obtained from a variable-length u32 array.
/// Only up to 8 words are used; if less than 8
/// words are used, the remaining are set to zero.
fn from_seed(seed: &'a [u32]) -> ChaChaRng {
let mut rng = EMPTY;
rng.reseed(seed);
rng
}
}
impl Rand for ChaChaRng {
fn rand<R: Rng>(other: &mut R) -> ChaChaRng {
let mut key : [u32,..KEY_WORDS] = [0,..KEY_WORDS];
for word in key.iter_mut() {
*word = other.gen();
}
SeedableRng::from_seed(key.as_slice())
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use core::iter::order;
use {Rng, SeedableRng};
use super::ChaChaRng;
#[test]
fn test_rng_rand_seeded() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut ra: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let mut rb: ChaChaRng = SeedableRng::from_seed(s.as_slice());
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_seeded() {
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let mut rb: ChaChaRng = SeedableRng::from_seed(seed);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut r: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed(s.as_slice());
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
#[test]
fn test_rng_true_values() {
// Test vectors 1 and 2 from
// http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
let seed : &[_] = &[0u32,..8];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653,
0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b,
0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8,
0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2));
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73,
0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32,
0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874,
0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b));
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
// Store the 17*i-th 32-bit word,
// i.e., the i-th word of the i-th 16-word block
let mut v : Vec<u32> = Vec::new();
for _ in range(0u, 16) {
v.push(ra.next_u32());
for _ in range(0u, 16) {
ra.next_u32();
}
}
assert_eq!(v,
vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036,
0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384,
0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530,
0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4));
}
}
| {
self.update();
} | conditional_block |
chacha.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.
//! The ChaCha random number generator.
use core::prelude::*;
use {Rng, SeedableRng, Rand};
const KEY_WORDS : uint = 8; // 8 words for the 256-bit key
const STATE_WORDS : uint = 16; | ///
/// The ChaCha algorithm is widely accepted as suitable for
/// cryptographic purposes, but this implementation has not been
/// verified as such. Prefer a generator like `OsRng` that defers to
/// the operating system for cases that need high security.
///
/// [1]: D. J. Bernstein, [*ChaCha, a variant of
/// Salsa20*](http://cr.yp.to/chacha.html)
pub struct ChaChaRng {
buffer: [u32,..STATE_WORDS], // Internal buffer of output
state: [u32,..STATE_WORDS], // Initial state
index: uint, // Index into state
}
static EMPTY: ChaChaRng = ChaChaRng {
buffer: [0,..STATE_WORDS],
state: [0,..STATE_WORDS],
index: STATE_WORDS
};
macro_rules! quarter_round{
($a: expr, $b: expr, $c: expr, $d: expr) => {{
$a += $b; $d ^= $a; $d = $d.rotate_left(16);
$c += $d; $b ^= $c; $b = $b.rotate_left(12);
$a += $b; $d ^= $a; $d = $d.rotate_left( 8);
$c += $d; $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round{
($x: expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
#[inline]
fn core(output: &mut [u32,..STATE_WORDS], input: &[u32,..STATE_WORDS]) {
*output = *input;
for _ in range(0, CHACHA_ROUNDS / 2) {
double_round!(output);
}
for i in range(0, STATE_WORDS) {
output[i] += input[i];
}
}
impl ChaChaRng {
/// Create an ChaCha random number generator using the default
/// fixed key of 8 zero words.
pub fn new_unseeded() -> ChaChaRng {
let mut rng = EMPTY;
rng.init(&[0,..KEY_WORDS]);
rng
}
/// Sets the internal 128-bit ChaCha counter to
/// a user-provided value. This permits jumping
/// arbitrarily ahead (or backwards) in the pseudorandom stream.
///
/// Since the nonce words are used to extend the counter to 128 bits,
/// users wishing to obtain the conventional ChaCha pseudorandom stream
/// associated with a particular nonce can call this function with
/// arguments `0, desired_nonce`.
pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) {
self.state[12] = (counter_low >> 0) as u32;
self.state[13] = (counter_low >> 32) as u32;
self.state[14] = (counter_high >> 0) as u32;
self.state[15] = (counter_high >> 32) as u32;
self.index = STATE_WORDS; // force recomputation
}
/// Initializes `self.state` with the appropriate key and constants
///
/// We deviate slightly from the ChaCha specification regarding
/// the nonce, which is used to extend the counter to 128 bits.
/// This is provably as strong as the original cipher, though,
/// since any distinguishing attack on our variant also works
/// against ChaCha with a chosen-nonce. See the XSalsa20 [1]
/// security proof for a more involved example of this.
///
/// The modified word layout is:
/// ```notrust
/// constant constant constant constant
/// key key key key
/// key key key key
/// counter counter counter counter
/// ```
/// [1]: Daniel J. Bernstein. [*Extending the Salsa20
/// nonce.*](http://cr.yp.to/papers.html#xsalsa)
fn init(&mut self, key: &[u32,..KEY_WORDS]) {
self.state[0] = 0x61707865;
self.state[1] = 0x3320646E;
self.state[2] = 0x79622D32;
self.state[3] = 0x6B206574;
for i in range(0, KEY_WORDS) {
self.state[4+i] = key[i];
}
self.state[12] = 0;
self.state[13] = 0;
self.state[14] = 0;
self.state[15] = 0;
self.index = STATE_WORDS;
}
/// Refill the internal output buffer (`self.buffer`)
fn update(&mut self) {
core(&mut self.buffer, &self.state);
self.index = 0;
// update 128-bit counter
self.state[12] += 1;
if self.state[12]!= 0 { return };
self.state[13] += 1;
if self.state[13]!= 0 { return };
self.state[14] += 1;
if self.state[14]!= 0 { return };
self.state[15] += 1;
}
}
impl Rng for ChaChaRng {
#[inline]
fn next_u32(&mut self) -> u32 {
if self.index == STATE_WORDS {
self.update();
}
let value = self.buffer[self.index % STATE_WORDS];
self.index += 1;
value
}
}
impl<'a> SeedableRng<&'a [u32]> for ChaChaRng {
fn reseed(&mut self, seed: &'a [u32]) {
// reset state
self.init(&[0u32,..KEY_WORDS]);
// set key inplace
let key = self.state.slice_mut(4, 4+KEY_WORDS);
for (k, s) in key.iter_mut().zip(seed.iter()) {
*k = *s;
}
}
/// Create a ChaCha generator from a seed,
/// obtained from a variable-length u32 array.
/// Only up to 8 words are used; if less than 8
/// words are used, the remaining are set to zero.
fn from_seed(seed: &'a [u32]) -> ChaChaRng {
let mut rng = EMPTY;
rng.reseed(seed);
rng
}
}
impl Rand for ChaChaRng {
fn rand<R: Rng>(other: &mut R) -> ChaChaRng {
let mut key : [u32,..KEY_WORDS] = [0,..KEY_WORDS];
for word in key.iter_mut() {
*word = other.gen();
}
SeedableRng::from_seed(key.as_slice())
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use core::iter::order;
use {Rng, SeedableRng};
use super::ChaChaRng;
#[test]
fn test_rng_rand_seeded() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut ra: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let mut rb: ChaChaRng = SeedableRng::from_seed(s.as_slice());
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_seeded() {
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let mut rb: ChaChaRng = SeedableRng::from_seed(seed);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
let mut r: ChaChaRng = SeedableRng::from_seed(s.as_slice());
let string1: String = r.gen_ascii_chars().take(100).collect();
r.reseed(s.as_slice());
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
}
#[test]
fn test_rng_true_values() {
// Test vectors 1 and 2 from
// http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
let seed : &[_] = &[0u32,..8];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653,
0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b,
0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8,
0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2));
let v = Vec::from_fn(16, |_| ra.next_u32());
assert_eq!(v,
vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73,
0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32,
0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874,
0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b));
let seed : &[_] = &[0,1,2,3,4,5,6,7];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
// Store the 17*i-th 32-bit word,
// i.e., the i-th word of the i-th 16-word block
let mut v : Vec<u32> = Vec::new();
for _ in range(0u, 16) {
v.push(ra.next_u32());
for _ in range(0u, 16) {
ra.next_u32();
}
}
assert_eq!(v,
vec!(0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036,
0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384,
0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530,
0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4));
}
} | const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing
/// A random number generator that uses the ChaCha20 algorithm [1]. | random_line_split |
audio.rs | use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use ringbuf::{Producer, RingBuffer};
pub struct AudioPlayer {
buffer_producer: Producer<f32>,
output_stream: cpal::Stream,
}
impl AudioPlayer {
pub fn new(sample_rate: u32) -> Self {
let host = cpal::default_host();
let output_device = host
.default_output_device()
.expect("failed to get default output audio device");
let config = cpal::StreamConfig {
channels: 2,
sample_rate: cpal::SampleRate(sample_rate),
buffer_size: cpal::BufferSize::Default,
};
// Limiting the number of samples in the buffer is better to minimize
// audio delay in emulation, this is because emulation speed
// does not 100% match audio playing speed (44100Hz).
// The buffer holds only audio for 1/4 second, which is good enough for delays,
// It can be reduced more, but it might cause noise(?) for slower machines
// or if any CPU intensive process started while the emulator is running
let buffer = RingBuffer::new(sample_rate as usize / 2);
let (buffer_producer, mut buffer_consumer) = buffer.split();
let output_data_fn = move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
for sample in data {
// /5.5 to reduce the volume of the sample
*sample = buffer_consumer.pop().unwrap_or(0.) / 5.5;
}
};
let output_stream = output_device
.build_output_stream(&config, output_data_fn, Self::err_fn)
.expect("failed to build an output audio stream");
Self {
buffer_producer,
output_stream,
}
}
pub fn | (&self) {
self.output_stream.play().unwrap();
}
/// Pause the player
/// > not used for now, but maybe later
#[allow(dead_code)]
pub fn pause(&self) {
self.output_stream.pause().unwrap();
}
pub fn queue(&mut self, data: &[f32]) {
self.buffer_producer.push_slice(data);
}
}
impl AudioPlayer {
fn err_fn(err: cpal::StreamError) {
eprintln!("an error occurred on audio stream: {}", err);
}
}
| play | identifier_name |
audio.rs | use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use ringbuf::{Producer, RingBuffer};
pub struct AudioPlayer {
buffer_producer: Producer<f32>,
output_stream: cpal::Stream,
}
impl AudioPlayer {
pub fn new(sample_rate: u32) -> Self {
let host = cpal::default_host();
let output_device = host | .expect("failed to get default output audio device");
let config = cpal::StreamConfig {
channels: 2,
sample_rate: cpal::SampleRate(sample_rate),
buffer_size: cpal::BufferSize::Default,
};
// Limiting the number of samples in the buffer is better to minimize
// audio delay in emulation, this is because emulation speed
// does not 100% match audio playing speed (44100Hz).
// The buffer holds only audio for 1/4 second, which is good enough for delays,
// It can be reduced more, but it might cause noise(?) for slower machines
// or if any CPU intensive process started while the emulator is running
let buffer = RingBuffer::new(sample_rate as usize / 2);
let (buffer_producer, mut buffer_consumer) = buffer.split();
let output_data_fn = move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
for sample in data {
// /5.5 to reduce the volume of the sample
*sample = buffer_consumer.pop().unwrap_or(0.) / 5.5;
}
};
let output_stream = output_device
.build_output_stream(&config, output_data_fn, Self::err_fn)
.expect("failed to build an output audio stream");
Self {
buffer_producer,
output_stream,
}
}
pub fn play(&self) {
self.output_stream.play().unwrap();
}
/// Pause the player
/// > not used for now, but maybe later
#[allow(dead_code)]
pub fn pause(&self) {
self.output_stream.pause().unwrap();
}
pub fn queue(&mut self, data: &[f32]) {
self.buffer_producer.push_slice(data);
}
}
impl AudioPlayer {
fn err_fn(err: cpal::StreamError) {
eprintln!("an error occurred on audio stream: {}", err);
}
} | .default_output_device() | random_line_split |
snippet.rs | // # Snippet example
//
// This example shows how to return a representative snippet of
// your hit result.
// Snippet are an extracted of a target document, and returned in HTML format.
// The keyword searched by the user are highlighted with a `<b>` tag.
// ---
// Importing tantivy...
use tantivy::collector::TopDocs;
use tantivy::query::QueryParser;
use tantivy::schema::*;
use tantivy::{doc, Index, Snippet, SnippetGenerator};
use tempfile::TempDir;
fn main() -> tantivy::Result<()> | bank and runs deep and green. The water is warm too, for it has slipped twinkling \
over the yellow sands in the sunlight before reaching the narrow pool. On one \
side of the river the golden foothill slopes curve up to the strong and rocky \
Gabilan Mountains, but on the valley side the water is lined with trees—willows \
fresh and green with every spring, carrying in their lower leaf junctures the \
debris of the winter’s flooding; and sycamores with mottled, white, recumbent \
limbs and branches that arch over the pool"
))?;
//...
index_writer.commit()?;
let reader = index.reader()?;
let searcher = reader.searcher();
let query_parser = QueryParser::for_index(&index, vec![title, body]);
let query = query_parser.parse_query("sycamore spring")?;
let top_docs = searcher.search(&query, &TopDocs::with_limit(10))?;
let snippet_generator = SnippetGenerator::create(&searcher, &*query, body)?;
for (score, doc_address) in top_docs {
let doc = searcher.doc(doc_address)?;
let snippet = snippet_generator.snippet_from_doc(&doc);
println!("Document score {}:", score);
println!("title: {}", doc.get_first(title).unwrap().text().unwrap());
println!("snippet: {}", snippet.to_html());
println!("custom highlighting: {}", highlight(snippet));
}
Ok(())
}
fn
highlight(snippet: Snippet) -> String {
let mut result = String::new();
let mut start_from = 0;
for fragment_range in snippet.highlighted() {
result.push_str(&snippet.fragment()[start_from..fragment_range.start]);
result.push_str(" --> ");
result.push_str(&snippet.fragment()[fragment_range.clone()]);
result.push_str(" <-- ");
start_from = fragment_range.end;
}
result.push_str(&snippet.fragment()[start_from..]);
result
}
| {
// Let's create a temporary directory for the
// sake of this example
let index_path = TempDir::new()?;
// # Defining the schema
let mut schema_builder = Schema::builder();
let title = schema_builder.add_text_field("title", TEXT | STORED);
let body = schema_builder.add_text_field("body", TEXT | STORED);
let schema = schema_builder.build();
// # Indexing documents
let index = Index::create_in_dir(&index_path, schema)?;
let mut index_writer = index.writer(50_000_000)?;
// we'll only need one doc for this example.
index_writer.add_document(doc!(
title => "Of Mice and Men",
body => "A few miles south of Soledad, the Salinas River drops in close to the hillside \ | identifier_body |
snippet.rs | // # Snippet example
//
// This example shows how to return a representative snippet of
// your hit result.
// Snippet are an extracted of a target document, and returned in HTML format.
// The keyword searched by the user are highlighted with a `<b>` tag.
// ---
// Importing tantivy...
use tantivy::collector::TopDocs;
use tantivy::query::QueryParser;
use tantivy::schema::*;
use tantivy::{doc, Index, Snippet, SnippetGenerator};
use tempfile::TempDir;
fn main() -> tantivy::Result<()> {
// Let's create a temporary directory for the
// sake of this example
let index_path = TempDir::new()?;
// # Defining the schema
let mut schema_builder = Schema::builder();
let title = schema_builder.add_text_field("title", TEXT | STORED);
let body = schema_builder.add_text_field("body", TEXT | STORED);
let schema = schema_builder.build();
// # Indexing documents
let index = Index::create_in_dir(&index_path, schema)?;
let mut index_writer = index.writer(50_000_000)?;
// we'll only need one doc for this example.
index_writer.add_document(doc!(
title => "Of Mice and Men",
body => "A few miles south of Soledad, the Salinas River drops in close to the hillside \
bank and runs deep and green. The water is warm too, for it has slipped twinkling \
over the yellow sands in the sunlight before reaching the narrow pool. On one \
side of the river the golden foothill slopes curve up to the strong and rocky \
Gabilan Mountains, but on the valley side the water is lined with trees—willows \
fresh and green with every spring, carrying in their lower leaf junctures the \
debris of the winter’s flooding; and sycamores with mottled, white, recumbent \
limbs and branches that arch over the pool"
))?;
//...
index_writer.commit()?;
let reader = index.reader()?;
let searcher = reader.searcher();
let query_parser = QueryParser::for_index(&index, vec![title, body]);
let query = query_parser.parse_query("sycamore spring")?;
let top_docs = searcher.search(&query, &TopDocs::with_limit(10))?; | let doc = searcher.doc(doc_address)?;
let snippet = snippet_generator.snippet_from_doc(&doc);
println!("Document score {}:", score);
println!("title: {}", doc.get_first(title).unwrap().text().unwrap());
println!("snippet: {}", snippet.to_html());
println!("custom highlighting: {}", highlight(snippet));
}
Ok(())
}
fn highlight(snippet: Snippet) -> String {
let mut result = String::new();
let mut start_from = 0;
for fragment_range in snippet.highlighted() {
result.push_str(&snippet.fragment()[start_from..fragment_range.start]);
result.push_str(" --> ");
result.push_str(&snippet.fragment()[fragment_range.clone()]);
result.push_str(" <-- ");
start_from = fragment_range.end;
}
result.push_str(&snippet.fragment()[start_from..]);
result
} |
let snippet_generator = SnippetGenerator::create(&searcher, &*query, body)?;
for (score, doc_address) in top_docs { | random_line_split |
snippet.rs | // # Snippet example
//
// This example shows how to return a representative snippet of
// your hit result.
// Snippet are an extracted of a target document, and returned in HTML format.
// The keyword searched by the user are highlighted with a `<b>` tag.
// ---
// Importing tantivy...
use tantivy::collector::TopDocs;
use tantivy::query::QueryParser;
use tantivy::schema::*;
use tantivy::{doc, Index, Snippet, SnippetGenerator};
use tempfile::TempDir;
fn | () -> tantivy::Result<()> {
// Let's create a temporary directory for the
// sake of this example
let index_path = TempDir::new()?;
// # Defining the schema
let mut schema_builder = Schema::builder();
let title = schema_builder.add_text_field("title", TEXT | STORED);
let body = schema_builder.add_text_field("body", TEXT | STORED);
let schema = schema_builder.build();
// # Indexing documents
let index = Index::create_in_dir(&index_path, schema)?;
let mut index_writer = index.writer(50_000_000)?;
// we'll only need one doc for this example.
index_writer.add_document(doc!(
title => "Of Mice and Men",
body => "A few miles south of Soledad, the Salinas River drops in close to the hillside \
bank and runs deep and green. The water is warm too, for it has slipped twinkling \
over the yellow sands in the sunlight before reaching the narrow pool. On one \
side of the river the golden foothill slopes curve up to the strong and rocky \
Gabilan Mountains, but on the valley side the water is lined with trees—willows \
fresh and green with every spring, carrying in their lower leaf junctures the \
debris of the winter’s flooding; and sycamores with mottled, white, recumbent \
limbs and branches that arch over the pool"
))?;
//...
index_writer.commit()?;
let reader = index.reader()?;
let searcher = reader.searcher();
let query_parser = QueryParser::for_index(&index, vec![title, body]);
let query = query_parser.parse_query("sycamore spring")?;
let top_docs = searcher.search(&query, &TopDocs::with_limit(10))?;
let snippet_generator = SnippetGenerator::create(&searcher, &*query, body)?;
for (score, doc_address) in top_docs {
let doc = searcher.doc(doc_address)?;
let snippet = snippet_generator.snippet_from_doc(&doc);
println!("Document score {}:", score);
println!("title: {}", doc.get_first(title).unwrap().text().unwrap());
println!("snippet: {}", snippet.to_html());
println!("custom highlighting: {}", highlight(snippet));
}
Ok(())
}
fn highlight(snippet: Snippet) -> String {
let mut result = String::new();
let mut start_from = 0;
for fragment_range in snippet.highlighted() {
result.push_str(&snippet.fragment()[start_from..fragment_range.start]);
result.push_str(" --> ");
result.push_str(&snippet.fragment()[fragment_range.clone()]);
result.push_str(" <-- ");
start_from = fragment_range.end;
}
result.push_str(&snippet.fragment()[start_from..]);
result
}
| main | identifier_name |
same_struct_name_in_different_namespaces.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct | {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct JS_shadow_Zone {
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_JS_shadow_Zone() {
assert_eq!(
::std::mem::size_of::<JS_shadow_Zone>(),
8usize,
concat!("Size of: ", stringify!(JS_shadow_Zone))
);
assert_eq!(
::std::mem::align_of::<JS_shadow_Zone>(),
4usize,
concat!("Alignment of ", stringify!(JS_shadow_Zone))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<JS_shadow_Zone>())).x as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(JS_shadow_Zone),
"::",
stringify!(x)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<JS_shadow_Zone>())).y as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(JS_shadow_Zone),
"::",
stringify!(y)
)
);
}
| JS_Zone | identifier_name |
same_struct_name_in_different_namespaces.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case, |
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct JS_Zone {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct JS_shadow_Zone {
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_JS_shadow_Zone() {
assert_eq!(
::std::mem::size_of::<JS_shadow_Zone>(),
8usize,
concat!("Size of: ", stringify!(JS_shadow_Zone))
);
assert_eq!(
::std::mem::align_of::<JS_shadow_Zone>(),
4usize,
concat!("Alignment of ", stringify!(JS_shadow_Zone))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<JS_shadow_Zone>())).x as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(JS_shadow_Zone),
"::",
stringify!(x)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<JS_shadow_Zone>())).y as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(JS_shadow_Zone),
"::",
stringify!(y)
)
);
} | non_camel_case_types,
non_upper_case_globals
)] | random_line_split |
main.rs | use std::hash::{Hash, Hasher};
use std::collections::HashSet;
#[derive(Debug, Clone, Copy)]
struct Foo {
elem: usize,
}
impl PartialEq for Foo {
#[inline]
fn eq(&self, other: &Self) -> bool {
self as *const Self == other as *const Self
}
}
impl Eq for Foo {}
impl Hash for Foo {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) |
}
fn main() {
let a = Foo { elem: 5 };
let b = a.clone();
let c = a;
let mut set = HashSet::new();
assert!(a!= b);
assert!(a!= c);
assert!(b!= c);
if!set.insert(a) {
unreachable!();
}
if!set.insert(b) {
unreachable!();
}
if!set.insert(c) {
unreachable!();
}
println!("{:#?}", set);
}
| {
(self as *const Self).hash(state);
} | identifier_body |
main.rs | use std::hash::{Hash, Hasher};
use std::collections::HashSet;
#[derive(Debug, Clone, Copy)]
struct Foo {
elem: usize,
}
impl PartialEq for Foo {
#[inline]
fn eq(&self, other: &Self) -> bool {
self as *const Self == other as *const Self
}
}
impl Eq for Foo {}
impl Hash for Foo {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
(self as *const Self).hash(state);
}
}
| let a = Foo { elem: 5 };
let b = a.clone();
let c = a;
let mut set = HashSet::new();
assert!(a!= b);
assert!(a!= c);
assert!(b!= c);
if!set.insert(a) {
unreachable!();
}
if!set.insert(b) {
unreachable!();
}
if!set.insert(c) {
unreachable!();
}
println!("{:#?}", set);
} |
fn main() { | random_line_split |
main.rs | use std::hash::{Hash, Hasher};
use std::collections::HashSet;
#[derive(Debug, Clone, Copy)]
struct | {
elem: usize,
}
impl PartialEq for Foo {
#[inline]
fn eq(&self, other: &Self) -> bool {
self as *const Self == other as *const Self
}
}
impl Eq for Foo {}
impl Hash for Foo {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
(self as *const Self).hash(state);
}
}
fn main() {
let a = Foo { elem: 5 };
let b = a.clone();
let c = a;
let mut set = HashSet::new();
assert!(a!= b);
assert!(a!= c);
assert!(b!= c);
if!set.insert(a) {
unreachable!();
}
if!set.insert(b) {
unreachable!();
}
if!set.insert(c) {
unreachable!();
}
println!("{:#?}", set);
}
| Foo | identifier_name |
main.rs | use std::hash::{Hash, Hasher};
use std::collections::HashSet;
#[derive(Debug, Clone, Copy)]
struct Foo {
elem: usize,
}
impl PartialEq for Foo {
#[inline]
fn eq(&self, other: &Self) -> bool {
self as *const Self == other as *const Self
}
}
impl Eq for Foo {}
impl Hash for Foo {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
(self as *const Self).hash(state);
}
}
fn main() {
let a = Foo { elem: 5 };
let b = a.clone();
let c = a;
let mut set = HashSet::new();
assert!(a!= b);
assert!(a!= c);
assert!(b!= c);
if!set.insert(a) {
unreachable!();
}
if!set.insert(b) |
if!set.insert(c) {
unreachable!();
}
println!("{:#?}", set);
}
| {
unreachable!();
} | conditional_block |
test_multicast.rs | use mio::*;
use mio::udp::*;
use bytes::{Buf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr}; | const LISTENER: Token = Token(0);
const SENDER: Token = Token(1);
pub struct UdpHandler {
tx: UdpSocket,
rx: UdpSocket,
msg: &'static str,
buf: SliceBuf<'static>,
rx_buf: RingBuf
}
impl UdpHandler {
fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler {
UdpHandler {
tx: tx,
rx: rx,
msg: msg,
buf: SliceBuf::wrap(msg.as_bytes()),
rx_buf: RingBuf::new(1024)
}
}
fn handle_read(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match self.rx.recv_from(&mut self.rx_buf) {
Ok(Some(SocketAddr::V4(addr))) => {
assert_eq!(*addr.ip(), Ipv4Addr::new(127, 0, 0, 1));
}
_ => panic!("unexpected result"),
}
assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg);
event_loop.shutdown();
},
_ => ()
}
}
fn handle_write(&mut self, _: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) {
match token {
SENDER => {
self.tx.send_to(&mut self.buf, &self.rx.local_addr().unwrap()).unwrap();
},
_ => ()
}
}
}
impl Handler for UdpHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: EventSet) {
if events.is_readable() {
self.handle_read(event_loop, token, events);
}
if events.is_writable() {
self.handle_write(event_loop, token, events);
}
}
}
#[test]
pub fn test_multicast() {
debug!("Starting TEST_UDP_CONNECTIONLESS");
let mut event_loop = EventLoop::new().unwrap();
let addr = localhost();
let any = "0.0.0.0:0".parse().unwrap();
let tx = UdpSocket::bound(&any).unwrap();
let rx = UdpSocket::bound(&addr).unwrap();
info!("Joining group 227.1.1.100");
rx.join_multicast(&"227.1.1.100".parse().unwrap()).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast(&"227.1.1.101".parse().unwrap()).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, EventSet::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, EventSet::readable(), PollOpt::edge()).unwrap();
info!("Starting event loop to test with...");
event_loop.run(&mut UdpHandler::new(tx, rx, "hello world")).unwrap();
} | use super::localhost;
| random_line_split |
test_multicast.rs | use mio::*;
use mio::udp::*;
use bytes::{Buf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr};
use super::localhost;
const LISTENER: Token = Token(0);
const SENDER: Token = Token(1);
pub struct UdpHandler {
tx: UdpSocket,
rx: UdpSocket,
msg: &'static str,
buf: SliceBuf<'static>,
rx_buf: RingBuf
}
impl UdpHandler {
fn | (tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler {
UdpHandler {
tx: tx,
rx: rx,
msg: msg,
buf: SliceBuf::wrap(msg.as_bytes()),
rx_buf: RingBuf::new(1024)
}
}
fn handle_read(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match self.rx.recv_from(&mut self.rx_buf) {
Ok(Some(SocketAddr::V4(addr))) => {
assert_eq!(*addr.ip(), Ipv4Addr::new(127, 0, 0, 1));
}
_ => panic!("unexpected result"),
}
assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg);
event_loop.shutdown();
},
_ => ()
}
}
fn handle_write(&mut self, _: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) {
match token {
SENDER => {
self.tx.send_to(&mut self.buf, &self.rx.local_addr().unwrap()).unwrap();
},
_ => ()
}
}
}
impl Handler for UdpHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: EventSet) {
if events.is_readable() {
self.handle_read(event_loop, token, events);
}
if events.is_writable() {
self.handle_write(event_loop, token, events);
}
}
}
#[test]
pub fn test_multicast() {
debug!("Starting TEST_UDP_CONNECTIONLESS");
let mut event_loop = EventLoop::new().unwrap();
let addr = localhost();
let any = "0.0.0.0:0".parse().unwrap();
let tx = UdpSocket::bound(&any).unwrap();
let rx = UdpSocket::bound(&addr).unwrap();
info!("Joining group 227.1.1.100");
rx.join_multicast(&"227.1.1.100".parse().unwrap()).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast(&"227.1.1.101".parse().unwrap()).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, EventSet::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, EventSet::readable(), PollOpt::edge()).unwrap();
info!("Starting event loop to test with...");
event_loop.run(&mut UdpHandler::new(tx, rx, "hello world")).unwrap();
}
| new | identifier_name |
test_multicast.rs | use mio::*;
use mio::udp::*;
use bytes::{Buf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr};
use super::localhost;
const LISTENER: Token = Token(0);
const SENDER: Token = Token(1);
pub struct UdpHandler {
tx: UdpSocket,
rx: UdpSocket,
msg: &'static str,
buf: SliceBuf<'static>,
rx_buf: RingBuf
}
impl UdpHandler {
fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler {
UdpHandler {
tx: tx,
rx: rx,
msg: msg,
buf: SliceBuf::wrap(msg.as_bytes()),
rx_buf: RingBuf::new(1024)
}
}
fn handle_read(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match self.rx.recv_from(&mut self.rx_buf) {
Ok(Some(SocketAddr::V4(addr))) => {
assert_eq!(*addr.ip(), Ipv4Addr::new(127, 0, 0, 1));
}
_ => panic!("unexpected result"),
}
assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg);
event_loop.shutdown();
},
_ => ()
}
}
fn handle_write(&mut self, _: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) |
}
impl Handler for UdpHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: EventSet) {
if events.is_readable() {
self.handle_read(event_loop, token, events);
}
if events.is_writable() {
self.handle_write(event_loop, token, events);
}
}
}
#[test]
pub fn test_multicast() {
debug!("Starting TEST_UDP_CONNECTIONLESS");
let mut event_loop = EventLoop::new().unwrap();
let addr = localhost();
let any = "0.0.0.0:0".parse().unwrap();
let tx = UdpSocket::bound(&any).unwrap();
let rx = UdpSocket::bound(&addr).unwrap();
info!("Joining group 227.1.1.100");
rx.join_multicast(&"227.1.1.100".parse().unwrap()).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast(&"227.1.1.101".parse().unwrap()).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, EventSet::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, EventSet::readable(), PollOpt::edge()).unwrap();
info!("Starting event loop to test with...");
event_loop.run(&mut UdpHandler::new(tx, rx, "hello world")).unwrap();
}
| {
match token {
SENDER => {
self.tx.send_to(&mut self.buf, &self.rx.local_addr().unwrap()).unwrap();
},
_ => ()
}
} | identifier_body |
test_multicast.rs | use mio::*;
use mio::udp::*;
use bytes::{Buf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr};
use super::localhost;
const LISTENER: Token = Token(0);
const SENDER: Token = Token(1);
pub struct UdpHandler {
tx: UdpSocket,
rx: UdpSocket,
msg: &'static str,
buf: SliceBuf<'static>,
rx_buf: RingBuf
}
impl UdpHandler {
fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler {
UdpHandler {
tx: tx,
rx: rx,
msg: msg,
buf: SliceBuf::wrap(msg.as_bytes()),
rx_buf: RingBuf::new(1024)
}
}
fn handle_read(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match self.rx.recv_from(&mut self.rx_buf) {
Ok(Some(SocketAddr::V4(addr))) => {
assert_eq!(*addr.ip(), Ipv4Addr::new(127, 0, 0, 1));
}
_ => panic!("unexpected result"),
}
assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg);
event_loop.shutdown();
},
_ => ()
}
}
fn handle_write(&mut self, _: &mut EventLoop<UdpHandler>, token: Token, _: EventSet) {
match token {
SENDER => {
self.tx.send_to(&mut self.buf, &self.rx.local_addr().unwrap()).unwrap();
},
_ => ()
}
}
}
impl Handler for UdpHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: EventSet) {
if events.is_readable() {
self.handle_read(event_loop, token, events);
}
if events.is_writable() |
}
}
#[test]
pub fn test_multicast() {
debug!("Starting TEST_UDP_CONNECTIONLESS");
let mut event_loop = EventLoop::new().unwrap();
let addr = localhost();
let any = "0.0.0.0:0".parse().unwrap();
let tx = UdpSocket::bound(&any).unwrap();
let rx = UdpSocket::bound(&addr).unwrap();
info!("Joining group 227.1.1.100");
rx.join_multicast(&"227.1.1.100".parse().unwrap()).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast(&"227.1.1.101".parse().unwrap()).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, EventSet::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, EventSet::readable(), PollOpt::edge()).unwrap();
info!("Starting event loop to test with...");
event_loop.run(&mut UdpHandler::new(tx, rx, "hello world")).unwrap();
}
| {
self.handle_write(event_loop, token, events);
} | conditional_block |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::js::{JS, JSRef, Root};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::WorkerGlobalScope;
use dom::window::Window;
use script_task::ScriptChan;
use servo_net::resource_task::ResourceTask;
use js::jsapi::JSContext;
use url::Url;
/// A freely-copyable reference to a rooted global object.
pub enum GlobalRef<'a> {
Window(JSRef<'a, Window>),
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot<'a, 'b> {
WindowRoot(Root<'a, 'b, Window>),
WorkerRoot(Root<'a, 'b, WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[deriving(Encodable)]
#[must_root]
pub enum GlobalField {
WindowField(JS<Window>),
WorkerField(JS<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
Window(ref window) => window.get_cx(),
Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, Window> {
match *self {
Window(window) => window,
Worker(_) => fail!("expected a Window scope"),
}
}
pub fn resource_task(&self) -> ResourceTask {
match *self {
Window(ref window) => window.page().resource_task.deref().clone(),
Worker(ref worker) => worker.resource_task().clone(),
}
}
pub fn get_url(&self) -> Url {
match *self {
Window(ref window) => window.get_url(),
Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan<'b>(&'b self) -> &'b ScriptChan {
match *self {
Window(ref window) => &window.script_chan,
Worker(ref worker) => worker.script_chan(),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
Window(ref window) => window.reflector(),
Worker(ref worker) => worker.reflector(),
}
}
}
impl<'a, 'b> GlobalRoot<'a, 'b> {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn root_ref<'c>(&'c self) -> GlobalRef<'c> {
match *self {
WindowRoot(ref window) => Window(window.root_ref()),
WorkerRoot(ref worker) => Worker(worker.root_ref()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn | (global: &GlobalRef) -> GlobalField {
match *global {
Window(window) => WindowField(JS::from_rooted(window)),
Worker(worker) => WorkerField(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
WindowField(ref window) => WindowRoot(window.root()),
WorkerField(ref worker) => WorkerRoot(worker.root()),
}
}
}
| from_rooted | identifier_name |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::js::{JS, JSRef, Root};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::WorkerGlobalScope;
use dom::window::Window;
use script_task::ScriptChan;
use servo_net::resource_task::ResourceTask;
use js::jsapi::JSContext;
use url::Url;
/// A freely-copyable reference to a rooted global object.
pub enum GlobalRef<'a> {
Window(JSRef<'a, Window>),
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot<'a, 'b> {
WindowRoot(Root<'a, 'b, Window>),
WorkerRoot(Root<'a, 'b, WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[deriving(Encodable)]
#[must_root]
pub enum GlobalField {
WindowField(JS<Window>),
WorkerField(JS<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
Window(ref window) => window.get_cx(),
Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, Window> {
match *self {
Window(window) => window,
Worker(_) => fail!("expected a Window scope"),
}
}
pub fn resource_task(&self) -> ResourceTask {
match *self {
Window(ref window) => window.page().resource_task.deref().clone(),
Worker(ref worker) => worker.resource_task().clone(),
}
}
pub fn get_url(&self) -> Url {
match *self {
Window(ref window) => window.get_url(),
Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan<'b>(&'b self) -> &'b ScriptChan {
match *self {
Window(ref window) => &window.script_chan,
Worker(ref worker) => worker.script_chan(),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
Window(ref window) => window.reflector(),
Worker(ref worker) => worker.reflector(),
}
}
}
impl<'a, 'b> GlobalRoot<'a, 'b> {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn root_ref<'c>(&'c self) -> GlobalRef<'c> {
match *self {
WindowRoot(ref window) => Window(window.root_ref()), | }
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
Window(window) => WindowField(JS::from_rooted(window)),
Worker(worker) => WorkerField(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
WindowField(ref window) => WindowRoot(window.root()),
WorkerField(ref worker) => WorkerRoot(worker.root()),
}
}
} | WorkerRoot(ref worker) => Worker(worker.root_ref()),
} | random_line_split |
util.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::io::{self, Error, ErrorKind};
use rusoto_core::{
region::Region,
request::{HttpClient, HttpConfig},
};
use rusoto_credential::{
AutoRefreshingProvider, AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials,
};
use rusoto_sts::WebIdentityProvider;
use async_trait::async_trait;
#[allow(dead_code)] // This will be used soon, please remove the allow.
const READ_BUF_SIZE: usize = 1024 * 1024 * 2;
pub fn new_http_client() -> io::Result<HttpClient> {
let mut http_config = HttpConfig::new();
// This can greatly improve performance dealing with payloads greater
// than 100MB. See https://github.com/rusoto/rusoto/pull/1227
// for more information.
http_config.read_buf_size(READ_BUF_SIZE);
// It is important to explicitly create the client and not use a global
// See https://github.com/tikv/tikv/issues/7236.
HttpClient::new_with_config(http_config).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("create aws http client error: {}", e),
)
})
}
pub fn get_region(region: &str, endpoint: &str) -> io::Result<Region> {
if!endpoint.is_empty() {
Ok(Region::Custom {
name: region.to_owned(),
endpoint: endpoint.to_owned(),
})
} else if!region.is_empty() {
region.parse::<Region>().map_err(|e| {
Error::new(
ErrorKind::InvalidInput,
format!("invalid aws region format {}: {}", region, e),
)
})
} else {
Ok(Region::default())
}
}
pub struct CredentialsProvider(AutoRefreshingProvider<DefaultCredentialsProvider>);
impl CredentialsProvider {
pub fn new() -> io::Result<CredentialsProvider> {
Ok(CredentialsProvider(
AutoRefreshingProvider::new(DefaultCredentialsProvider::default()).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("create aws credentials provider error: {}", e),
)
})?,
))
}
}
#[async_trait]
impl ProvideAwsCredentials for CredentialsProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
self.0.credentials().await
}
}
// Same as rusoto_credentials::DefaultCredentialsProvider with extra
// rusoto_sts::WebIdentityProvider support.
pub struct DefaultCredentialsProvider {
// Underlying implementation of rusoto_credentials::DefaultCredentialsProvider.
default_provider: ChainProvider,
// Provider IAM support in Kubernetes.
web_identity_provider: WebIdentityProvider,
}
impl Default for DefaultCredentialsProvider {
fn default() -> DefaultCredentialsProvider {
DefaultCredentialsProvider {
default_provider: ChainProvider::new(),
web_identity_provider: WebIdentityProvider::from_k8s_env(),
}
}
}
#[async_trait]
impl ProvideAwsCredentials for DefaultCredentialsProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
// Prefer the web identity provider first for the kubernetes environment.
// Search for both in parallel.
let web_creds = self.web_identity_provider.credentials();
let def_creds = self.default_provider.credentials();
let k8s_error = match web_creds.await { | Err(e) => e,
};
let def_error = match def_creds.await {
res @ Ok(_) => return res,
Err(e) => e,
};
Err(CredentialsError::new(format_args!(
"Couldn't find AWS credentials in default sources ({}) or k8s environment ({}).",
def_error.message, k8s_error.message,
)))
}
} | res @ Ok(_) => return res, | random_line_split |
util.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::io::{self, Error, ErrorKind};
use rusoto_core::{
region::Region,
request::{HttpClient, HttpConfig},
};
use rusoto_credential::{
AutoRefreshingProvider, AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials,
};
use rusoto_sts::WebIdentityProvider;
use async_trait::async_trait;
#[allow(dead_code)] // This will be used soon, please remove the allow.
const READ_BUF_SIZE: usize = 1024 * 1024 * 2;
pub fn new_http_client() -> io::Result<HttpClient> {
let mut http_config = HttpConfig::new();
// This can greatly improve performance dealing with payloads greater
// than 100MB. See https://github.com/rusoto/rusoto/pull/1227
// for more information.
http_config.read_buf_size(READ_BUF_SIZE);
// It is important to explicitly create the client and not use a global
// See https://github.com/tikv/tikv/issues/7236.
HttpClient::new_with_config(http_config).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("create aws http client error: {}", e),
)
})
}
pub fn get_region(region: &str, endpoint: &str) -> io::Result<Region> {
if!endpoint.is_empty() {
Ok(Region::Custom {
name: region.to_owned(),
endpoint: endpoint.to_owned(),
})
} else if!region.is_empty() {
region.parse::<Region>().map_err(|e| {
Error::new(
ErrorKind::InvalidInput,
format!("invalid aws region format {}: {}", region, e),
)
})
} else {
Ok(Region::default())
}
}
pub struct CredentialsProvider(AutoRefreshingProvider<DefaultCredentialsProvider>);
impl CredentialsProvider {
pub fn new() -> io::Result<CredentialsProvider> {
Ok(CredentialsProvider(
AutoRefreshingProvider::new(DefaultCredentialsProvider::default()).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("create aws credentials provider error: {}", e),
)
})?,
))
}
}
#[async_trait]
impl ProvideAwsCredentials for CredentialsProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
self.0.credentials().await
}
}
// Same as rusoto_credentials::DefaultCredentialsProvider with extra
// rusoto_sts::WebIdentityProvider support.
pub struct DefaultCredentialsProvider {
// Underlying implementation of rusoto_credentials::DefaultCredentialsProvider.
default_provider: ChainProvider,
// Provider IAM support in Kubernetes.
web_identity_provider: WebIdentityProvider,
}
impl Default for DefaultCredentialsProvider {
fn default() -> DefaultCredentialsProvider {
DefaultCredentialsProvider {
default_provider: ChainProvider::new(),
web_identity_provider: WebIdentityProvider::from_k8s_env(),
}
}
}
#[async_trait]
impl ProvideAwsCredentials for DefaultCredentialsProvider {
async fn | (&self) -> Result<AwsCredentials, CredentialsError> {
// Prefer the web identity provider first for the kubernetes environment.
// Search for both in parallel.
let web_creds = self.web_identity_provider.credentials();
let def_creds = self.default_provider.credentials();
let k8s_error = match web_creds.await {
res @ Ok(_) => return res,
Err(e) => e,
};
let def_error = match def_creds.await {
res @ Ok(_) => return res,
Err(e) => e,
};
Err(CredentialsError::new(format_args!(
"Couldn't find AWS credentials in default sources ({}) or k8s environment ({}).",
def_error.message, k8s_error.message,
)))
}
}
| credentials | identifier_name |
util.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::io::{self, Error, ErrorKind};
use rusoto_core::{
region::Region,
request::{HttpClient, HttpConfig},
};
use rusoto_credential::{
AutoRefreshingProvider, AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials,
};
use rusoto_sts::WebIdentityProvider;
use async_trait::async_trait;
#[allow(dead_code)] // This will be used soon, please remove the allow.
const READ_BUF_SIZE: usize = 1024 * 1024 * 2;
pub fn new_http_client() -> io::Result<HttpClient> {
let mut http_config = HttpConfig::new();
// This can greatly improve performance dealing with payloads greater
// than 100MB. See https://github.com/rusoto/rusoto/pull/1227
// for more information.
http_config.read_buf_size(READ_BUF_SIZE);
// It is important to explicitly create the client and not use a global
// See https://github.com/tikv/tikv/issues/7236.
HttpClient::new_with_config(http_config).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("create aws http client error: {}", e),
)
})
}
pub fn get_region(region: &str, endpoint: &str) -> io::Result<Region> {
if!endpoint.is_empty() {
Ok(Region::Custom {
name: region.to_owned(),
endpoint: endpoint.to_owned(),
})
} else if!region.is_empty() {
region.parse::<Region>().map_err(|e| {
Error::new(
ErrorKind::InvalidInput,
format!("invalid aws region format {}: {}", region, e),
)
})
} else {
Ok(Region::default())
}
}
pub struct CredentialsProvider(AutoRefreshingProvider<DefaultCredentialsProvider>);
impl CredentialsProvider {
pub fn new() -> io::Result<CredentialsProvider> {
Ok(CredentialsProvider(
AutoRefreshingProvider::new(DefaultCredentialsProvider::default()).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("create aws credentials provider error: {}", e),
)
})?,
))
}
}
#[async_trait]
impl ProvideAwsCredentials for CredentialsProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
self.0.credentials().await
}
}
// Same as rusoto_credentials::DefaultCredentialsProvider with extra
// rusoto_sts::WebIdentityProvider support.
pub struct DefaultCredentialsProvider {
// Underlying implementation of rusoto_credentials::DefaultCredentialsProvider.
default_provider: ChainProvider,
// Provider IAM support in Kubernetes.
web_identity_provider: WebIdentityProvider,
}
impl Default for DefaultCredentialsProvider {
fn default() -> DefaultCredentialsProvider |
}
#[async_trait]
impl ProvideAwsCredentials for DefaultCredentialsProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
// Prefer the web identity provider first for the kubernetes environment.
// Search for both in parallel.
let web_creds = self.web_identity_provider.credentials();
let def_creds = self.default_provider.credentials();
let k8s_error = match web_creds.await {
res @ Ok(_) => return res,
Err(e) => e,
};
let def_error = match def_creds.await {
res @ Ok(_) => return res,
Err(e) => e,
};
Err(CredentialsError::new(format_args!(
"Couldn't find AWS credentials in default sources ({}) or k8s environment ({}).",
def_error.message, k8s_error.message,
)))
}
}
| {
DefaultCredentialsProvider {
default_provider: ChainProvider::new(),
web_identity_provider: WebIdentityProvider::from_k8s_env(),
}
} | identifier_body |
trait-inheritance-cross-trait-call.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo { fn f(&self) -> int; }
trait Bar : Foo { fn g(&self) -> int; }
struct A { x: int }
impl Foo for A { fn f(&self) -> int { 10 } }
impl Bar for A {
// Testing that this impl can call the impl of Foo
fn g(&self) -> int { self.f() }
}
pub fn | () {
let a = &A { x: 3 };
assert!(a.g() == 10);
}
| main | identifier_name |
trait-inheritance-cross-trait-call.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo { fn f(&self) -> int; }
trait Bar : Foo { fn g(&self) -> int; }
| impl Foo for A { fn f(&self) -> int { 10 } }
impl Bar for A {
// Testing that this impl can call the impl of Foo
fn g(&self) -> int { self.f() }
}
pub fn main() {
let a = &A { x: 3 };
assert!(a.g() == 10);
} | struct A { x: int }
| random_line_split |
parse_grammar.rs | use super::grammars::{InputGrammar, PrecedenceEntry, Variable, VariableType};
use super::rules::{Precedence, Rule};
use anyhow::{anyhow, Result};
use serde::Deserialize;
use serde_json::{Map, Value};
#[derive(Deserialize)]
#[serde(tag = "type")]
#[allow(non_camel_case_types)]
enum RuleJSON {
ALIAS {
content: Box<RuleJSON>,
named: bool,
value: String,
},
BLANK,
STRING {
value: String,
},
PATTERN {
value: String,
},
SYMBOL {
name: String,
},
CHOICE {
members: Vec<RuleJSON>,
},
FIELD {
name: String,
content: Box<RuleJSON>,
},
SEQ {
members: Vec<RuleJSON>,
},
REPEAT {
content: Box<RuleJSON>,
},
REPEAT1 {
content: Box<RuleJSON>,
},
PREC_DYNAMIC {
value: i32,
content: Box<RuleJSON>,
},
PREC_LEFT {
value: PrecedenceValueJSON,
content: Box<RuleJSON>,
},
PREC_RIGHT {
value: PrecedenceValueJSON,
content: Box<RuleJSON>,
},
PREC {
value: PrecedenceValueJSON,
content: Box<RuleJSON>,
},
TOKEN {
content: Box<RuleJSON>,
},
IMMEDIATE_TOKEN {
content: Box<RuleJSON>,
},
}
#[derive(Deserialize)]
#[serde(untagged)]
enum PrecedenceValueJSON {
Integer(i32),
Name(String),
}
#[derive(Deserialize)]
pub(crate) struct | {
pub(crate) name: String,
rules: Map<String, Value>,
#[serde(default)]
precedences: Vec<Vec<RuleJSON>>,
#[serde(default)]
conflicts: Vec<Vec<String>>,
#[serde(default)]
externals: Vec<RuleJSON>,
#[serde(default)]
extras: Vec<RuleJSON>,
#[serde(default)]
inline: Vec<String>,
#[serde(default)]
supertypes: Vec<String>,
word: Option<String>,
}
pub(crate) fn parse_grammar(input: &str) -> Result<InputGrammar> {
let grammar_json: GrammarJSON = serde_json::from_str(&input)?;
let mut variables = Vec::with_capacity(grammar_json.rules.len());
for (name, value) in grammar_json.rules {
variables.push(Variable {
name: name.to_owned(),
kind: VariableType::Named,
rule: parse_rule(serde_json::from_value(value)?),
})
}
let mut precedence_orderings = Vec::with_capacity(grammar_json.precedences.len());
for list in grammar_json.precedences {
let mut ordering = Vec::with_capacity(list.len());
for entry in list {
ordering.push(match entry {
RuleJSON::STRING { value } => PrecedenceEntry::Name(value),
RuleJSON::SYMBOL { name } => PrecedenceEntry::Symbol(name),
_ => {
return Err(anyhow!(
"Invalid rule in precedences array. Only strings and symbols are allowed"
))
}
})
}
precedence_orderings.push(ordering);
}
let extra_symbols = grammar_json.extras.into_iter().map(parse_rule).collect();
let external_tokens = grammar_json.externals.into_iter().map(parse_rule).collect();
Ok(InputGrammar {
name: grammar_json.name,
word_token: grammar_json.word,
expected_conflicts: grammar_json.conflicts,
supertype_symbols: grammar_json.supertypes,
variables_to_inline: grammar_json.inline,
precedence_orderings,
variables,
extra_symbols,
external_tokens,
})
}
fn parse_rule(json: RuleJSON) -> Rule {
match json {
RuleJSON::ALIAS {
content,
value,
named,
} => Rule::alias(parse_rule(*content), value, named),
RuleJSON::BLANK => Rule::Blank,
RuleJSON::STRING { value } => Rule::String(value),
RuleJSON::PATTERN { value } => Rule::Pattern(value),
RuleJSON::SYMBOL { name } => Rule::NamedSymbol(name),
RuleJSON::CHOICE { members } => Rule::choice(members.into_iter().map(parse_rule).collect()),
RuleJSON::FIELD { content, name } => Rule::field(name, parse_rule(*content)),
RuleJSON::SEQ { members } => Rule::seq(members.into_iter().map(parse_rule).collect()),
RuleJSON::REPEAT1 { content } => Rule::repeat(parse_rule(*content)),
RuleJSON::REPEAT { content } => {
Rule::choice(vec![Rule::repeat(parse_rule(*content)), Rule::Blank])
}
RuleJSON::PREC { value, content } => Rule::prec(value.into(), parse_rule(*content)),
RuleJSON::PREC_LEFT { value, content } => {
Rule::prec_left(value.into(), parse_rule(*content))
}
RuleJSON::PREC_RIGHT { value, content } => {
Rule::prec_right(value.into(), parse_rule(*content))
}
RuleJSON::PREC_DYNAMIC { value, content } => {
Rule::prec_dynamic(value, parse_rule(*content))
}
RuleJSON::TOKEN { content } => Rule::token(parse_rule(*content)),
RuleJSON::IMMEDIATE_TOKEN { content } => Rule::immediate_token(parse_rule(*content)),
}
}
impl Into<Precedence> for PrecedenceValueJSON {
fn into(self) -> Precedence {
match self {
PrecedenceValueJSON::Integer(i) => Precedence::Integer(i),
PrecedenceValueJSON::Name(i) => Precedence::Name(i),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_grammar() {
let grammar = parse_grammar(
r#"{
"name": "my_lang",
"rules": {
"file": {
"type": "REPEAT1",
"content": {
"type": "SYMBOL",
"name": "statement"
}
},
"statement": {
"type": "STRING",
"value": "foo"
}
}
}"#,
)
.unwrap();
assert_eq!(grammar.name, "my_lang");
assert_eq!(
grammar.variables,
vec![
Variable {
name: "file".to_string(),
kind: VariableType::Named,
rule: Rule::repeat(Rule::NamedSymbol("statement".to_string()))
},
Variable {
name: "statement".to_string(),
kind: VariableType::Named,
rule: Rule::String("foo".to_string())
},
]
);
}
}
| GrammarJSON | identifier_name |
parse_grammar.rs | use super::grammars::{InputGrammar, PrecedenceEntry, Variable, VariableType};
use super::rules::{Precedence, Rule};
use anyhow::{anyhow, Result};
use serde::Deserialize;
use serde_json::{Map, Value};
#[derive(Deserialize)]
#[serde(tag = "type")]
#[allow(non_camel_case_types)]
enum RuleJSON {
ALIAS {
content: Box<RuleJSON>,
named: bool,
value: String,
},
BLANK,
STRING {
value: String,
},
PATTERN {
value: String,
},
SYMBOL {
name: String,
},
CHOICE {
members: Vec<RuleJSON>,
},
FIELD {
name: String,
content: Box<RuleJSON>,
},
SEQ {
members: Vec<RuleJSON>,
},
REPEAT {
content: Box<RuleJSON>,
},
REPEAT1 {
content: Box<RuleJSON>,
},
PREC_DYNAMIC {
value: i32,
content: Box<RuleJSON>,
},
PREC_LEFT {
value: PrecedenceValueJSON,
content: Box<RuleJSON>,
},
PREC_RIGHT {
value: PrecedenceValueJSON,
content: Box<RuleJSON>,
},
PREC {
value: PrecedenceValueJSON,
content: Box<RuleJSON>,
},
TOKEN {
content: Box<RuleJSON>,
},
IMMEDIATE_TOKEN {
content: Box<RuleJSON>,
},
}
#[derive(Deserialize)]
#[serde(untagged)]
enum PrecedenceValueJSON {
Integer(i32),
Name(String),
}
#[derive(Deserialize)]
pub(crate) struct GrammarJSON {
pub(crate) name: String,
rules: Map<String, Value>,
#[serde(default)]
precedences: Vec<Vec<RuleJSON>>,
#[serde(default)]
conflicts: Vec<Vec<String>>,
#[serde(default)]
externals: Vec<RuleJSON>,
#[serde(default)]
extras: Vec<RuleJSON>,
#[serde(default)]
inline: Vec<String>,
#[serde(default)]
supertypes: Vec<String>,
word: Option<String>,
}
pub(crate) fn parse_grammar(input: &str) -> Result<InputGrammar> {
let grammar_json: GrammarJSON = serde_json::from_str(&input)?;
let mut variables = Vec::with_capacity(grammar_json.rules.len());
for (name, value) in grammar_json.rules {
variables.push(Variable {
name: name.to_owned(),
kind: VariableType::Named,
rule: parse_rule(serde_json::from_value(value)?),
})
}
let mut precedence_orderings = Vec::with_capacity(grammar_json.precedences.len());
for list in grammar_json.precedences {
let mut ordering = Vec::with_capacity(list.len());
for entry in list {
ordering.push(match entry {
RuleJSON::STRING { value } => PrecedenceEntry::Name(value),
RuleJSON::SYMBOL { name } => PrecedenceEntry::Symbol(name),
_ => {
return Err(anyhow!(
"Invalid rule in precedences array. Only strings and symbols are allowed"
))
}
})
}
precedence_orderings.push(ordering);
}
let extra_symbols = grammar_json.extras.into_iter().map(parse_rule).collect();
let external_tokens = grammar_json.externals.into_iter().map(parse_rule).collect();
Ok(InputGrammar {
name: grammar_json.name,
word_token: grammar_json.word,
expected_conflicts: grammar_json.conflicts,
supertype_symbols: grammar_json.supertypes,
variables_to_inline: grammar_json.inline,
precedence_orderings,
variables,
extra_symbols,
external_tokens,
})
}
fn parse_rule(json: RuleJSON) -> Rule {
match json {
RuleJSON::ALIAS {
content,
value,
named,
} => Rule::alias(parse_rule(*content), value, named),
RuleJSON::BLANK => Rule::Blank,
RuleJSON::STRING { value } => Rule::String(value),
RuleJSON::PATTERN { value } => Rule::Pattern(value),
RuleJSON::SYMBOL { name } => Rule::NamedSymbol(name),
RuleJSON::CHOICE { members } => Rule::choice(members.into_iter().map(parse_rule).collect()),
RuleJSON::FIELD { content, name } => Rule::field(name, parse_rule(*content)),
RuleJSON::SEQ { members } => Rule::seq(members.into_iter().map(parse_rule).collect()),
RuleJSON::REPEAT1 { content } => Rule::repeat(parse_rule(*content)),
RuleJSON::REPEAT { content } => {
Rule::choice(vec![Rule::repeat(parse_rule(*content)), Rule::Blank])
}
RuleJSON::PREC { value, content } => Rule::prec(value.into(), parse_rule(*content)),
RuleJSON::PREC_LEFT { value, content } => {
Rule::prec_left(value.into(), parse_rule(*content))
}
RuleJSON::PREC_RIGHT { value, content } => {
Rule::prec_right(value.into(), parse_rule(*content))
}
RuleJSON::PREC_DYNAMIC { value, content } => {
Rule::prec_dynamic(value, parse_rule(*content))
}
RuleJSON::TOKEN { content } => Rule::token(parse_rule(*content)),
RuleJSON::IMMEDIATE_TOKEN { content } => Rule::immediate_token(parse_rule(*content)),
}
}
impl Into<Precedence> for PrecedenceValueJSON {
fn into(self) -> Precedence {
match self {
PrecedenceValueJSON::Integer(i) => Precedence::Integer(i),
PrecedenceValueJSON::Name(i) => Precedence::Name(i),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_grammar() {
let grammar = parse_grammar(
r#"{
"name": "my_lang",
"rules": {
"file": { | "type": "REPEAT1",
"content": {
"type": "SYMBOL",
"name": "statement"
}
},
"statement": {
"type": "STRING",
"value": "foo"
}
}
}"#,
)
.unwrap();
assert_eq!(grammar.name, "my_lang");
assert_eq!(
grammar.variables,
vec![
Variable {
name: "file".to_string(),
kind: VariableType::Named,
rule: Rule::repeat(Rule::NamedSymbol("statement".to_string()))
},
Variable {
name: "statement".to_string(),
kind: VariableType::Named,
rule: Rule::String("foo".to_string())
},
]
);
}
} | random_line_split |
|
vec-matching.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(advanced_slice_patterns)]
fn a() {
let x = [1];
match x {
[a] => {
assert_eq!(a, 1);
}
}
}
fn b() { | let x = [1, 2, 3];
match x {
[a, b, c..] => {
assert_eq!(a, 1);
assert_eq!(b, 2);
let expected: &[_] = &[3];
assert_eq!(c, expected);
}
}
match x {
[a.., b, c] => {
let expected: &[_] = &[1];
assert_eq!(a, expected);
assert_eq!(b, 2);
assert_eq!(c, 3);
}
}
match x {
[a, b.., c] => {
assert_eq!(a, 1);
let expected: &[_] = &[2];
assert_eq!(b, expected);
assert_eq!(c, 3);
}
}
match x {
[a, b, c] => {
assert_eq!(a, 1);
assert_eq!(b, 2);
assert_eq!(c, 3);
}
}
}
fn c() {
let x = [1];
match x {
[2,..] => panic!(),
[..] => ()
}
}
fn d() {
let x = [1, 2, 3];
let branch = match x {
[1, 1,..] => 0,
[1, 2, 3,..] => 1,
[1, 2,..] => 2,
_ => 3
};
assert_eq!(branch, 1);
}
fn e() {
let x: &[int] = &[1, 2, 3];
match x {
[1, 2] => (),
[..] => ()
}
}
pub fn main() {
a();
b();
c();
d();
e();
} | random_line_split |
|
vec-matching.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(advanced_slice_patterns)]
fn a() {
let x = [1];
match x {
[a] => {
assert_eq!(a, 1);
}
}
}
fn b() {
let x = [1, 2, 3];
match x {
[a, b, c..] => {
assert_eq!(a, 1);
assert_eq!(b, 2);
let expected: &[_] = &[3];
assert_eq!(c, expected);
}
}
match x {
[a.., b, c] => {
let expected: &[_] = &[1];
assert_eq!(a, expected);
assert_eq!(b, 2);
assert_eq!(c, 3);
}
}
match x {
[a, b.., c] => {
assert_eq!(a, 1);
let expected: &[_] = &[2];
assert_eq!(b, expected);
assert_eq!(c, 3);
}
}
match x {
[a, b, c] => {
assert_eq!(a, 1);
assert_eq!(b, 2);
assert_eq!(c, 3);
}
}
}
fn c() {
let x = [1];
match x {
[2,..] => panic!(),
[..] => ()
}
}
fn d() {
let x = [1, 2, 3];
let branch = match x {
[1, 1,..] => 0,
[1, 2, 3,..] => 1,
[1, 2,..] => 2,
_ => 3
};
assert_eq!(branch, 1);
}
fn e() |
pub fn main() {
a();
b();
c();
d();
e();
}
| {
let x: &[int] = &[1, 2, 3];
match x {
[1, 2] => (),
[..] => ()
}
} | identifier_body |
vec-matching.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(advanced_slice_patterns)]
fn a() {
let x = [1];
match x {
[a] => {
assert_eq!(a, 1);
}
}
}
fn b() {
let x = [1, 2, 3];
match x {
[a, b, c..] => {
assert_eq!(a, 1);
assert_eq!(b, 2);
let expected: &[_] = &[3];
assert_eq!(c, expected);
}
}
match x {
[a.., b, c] => {
let expected: &[_] = &[1];
assert_eq!(a, expected);
assert_eq!(b, 2);
assert_eq!(c, 3);
}
}
match x {
[a, b.., c] => {
assert_eq!(a, 1);
let expected: &[_] = &[2];
assert_eq!(b, expected);
assert_eq!(c, 3);
}
}
match x {
[a, b, c] => {
assert_eq!(a, 1);
assert_eq!(b, 2);
assert_eq!(c, 3);
}
}
}
fn c() {
let x = [1];
match x {
[2,..] => panic!(),
[..] => ()
}
}
fn d() {
let x = [1, 2, 3];
let branch = match x {
[1, 1,..] => 0,
[1, 2, 3,..] => 1,
[1, 2,..] => 2,
_ => 3
};
assert_eq!(branch, 1);
}
fn | () {
let x: &[int] = &[1, 2, 3];
match x {
[1, 2] => (),
[..] => ()
}
}
pub fn main() {
a();
b();
c();
d();
e();
}
| e | identifier_name |
main.rs | fn main() {
println!("Hello, world!");
let mut x: i32 = 5;
x = 10;
print_num(5);
add_num(4, 6);
let x1: i32;
x1 = add_one(7);
let f: fn(i32) -> i32 = add_one;
let ff = add_one;
let x2 = f(6);
let x3 = ff(8);
let x_bool = true;
let y_bool: bool = false;
println!("x_bool's value: {}", x_bool);
let x_char = 'H';
println!("x_char's value: {}", x_char);
let a = [1, 2, 3]; //a: [i32; 3]
let mut m = [1, 2, 3]; //m: [i32; 3]
let aa = [0; 20]; //aa is an array with 0*20
println!("aa has {} elements", a.len());
println!("m's second value is {}", m[1]);
let names = ["Xiaoming", "Xiaohong", "Xiaohua"]; //names: [&str; 3]
println!("The second name is {}", names[1]);
let sum = [0, 1, 2, 3];
let sum_complete = &sum[..]; //A slice containing all of the elements
let sum_middle = &sum[1..4]; //A slice only contain element from 1 to 3
println!("sum_complete's length is {}", sum_complete.len());
println!("sum_middle's length is {}", sum_middle.len());
let (x, y, z) = (1, 2, 3);
println!("x is {}", x);
let tuple_single = (0,); //This is a single element tuple
let var_single = (0); //This is a single variable bindings
println!("var_single is {}", var_single);
let tuple = (1, 2, 3);
let x = tuple.0;
let y = tuple.1;
let z = tuple.2;
println!("x is {}", x);
let x: fn(i32) -> i32 = foo;
let y = x(34);
println!("y is {}", y);
// Line comments are anything after '//' and extend to the end of the line.
// Put a space between the '//' and the comments so that it is more readable.
/// Doc comments using /// instead of //, and support makedown notation inside
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// # fn add_one(x: i32) -> i32 {
/// # x + 1
/// # }
/// ```
fn plus_one(x: i32) -> i32 {
x + 1
}
let x = 7;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six");
}
let y = if x == 5 {
10
} else | ; // y: i32
println!("y is {}", y);
// Or let y = if x == 5 { 10 } else { 15 }; // y: i32
// Rust provide 3 kinds of iterative activity: loop, while, for.
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while!done {
x += x - 3;
println!("x iterative value is {}", x);
if x % 5 == 0 {
done = true;
}
}
// The 'for' loop is used for a particular number of times
for x in 0..10 {
println!("the 'for' loop for x is {}", x); // x: i32
}
// The enumerate function used for keeping track how many times of the 'for' loop execute.
for (index, value) in (5..10).enumerate() {
println!("index is {} and value is {}", index, value);
}
let lines_all = "hello\nworld".lines();
for (linenumber, line) in lines_all.enumerate() {
println!("{}, {}", linenumber, line);
}
// Use break or continue to stop the interation
}
fn print_num(x: i32){
println!("x is {}", x);
}
fn add_num(x: i32, y: i32){
println!("sum is {}", x + y);
}
fn add_one(x: i32) -> i32{
x + 1
}
fn foo(x: i32) -> i32 { x } | {
15
} | conditional_block |
main.rs | fn main() {
println!("Hello, world!");
let mut x: i32 = 5;
x = 10;
print_num(5);
add_num(4, 6);
let x1: i32;
x1 = add_one(7);
let f: fn(i32) -> i32 = add_one;
let ff = add_one;
let x2 = f(6);
let x3 = ff(8);
let x_bool = true;
let y_bool: bool = false;
println!("x_bool's value: {}", x_bool);
let x_char = 'H';
println!("x_char's value: {}", x_char);
let a = [1, 2, 3]; //a: [i32; 3]
let mut m = [1, 2, 3]; //m: [i32; 3]
let aa = [0; 20]; //aa is an array with 0*20
println!("aa has {} elements", a.len());
println!("m's second value is {}", m[1]);
let names = ["Xiaoming", "Xiaohong", "Xiaohua"]; //names: [&str; 3]
println!("The second name is {}", names[1]);
let sum = [0, 1, 2, 3];
let sum_complete = &sum[..]; //A slice containing all of the elements
let sum_middle = &sum[1..4]; //A slice only contain element from 1 to 3
println!("sum_complete's length is {}", sum_complete.len());
println!("sum_middle's length is {}", sum_middle.len());
let (x, y, z) = (1, 2, 3);
println!("x is {}", x);
let tuple_single = (0,); //This is a single element tuple
let var_single = (0); //This is a single variable bindings
println!("var_single is {}", var_single);
let tuple = (1, 2, 3);
let x = tuple.0;
let y = tuple.1;
let z = tuple.2;
println!("x is {}", x);
let x: fn(i32) -> i32 = foo;
let y = x(34);
println!("y is {}", y);
// Line comments are anything after '//' and extend to the end of the line.
// Put a space between the '//' and the comments so that it is more readable.
/// Doc comments using /// instead of //, and support makedown notation inside
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// # fn add_one(x: i32) -> i32 {
/// # x + 1
/// # }
/// ```
fn plus_one(x: i32) -> i32 {
x + 1
}
let x = 7;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six");
}
let y = if x == 5 {
10
} else {
15
}; // y: i32
println!("y is {}", y);
// Or let y = if x == 5 { 10 } else { 15 }; // y: i32
// Rust provide 3 kinds of iterative activity: loop, while, for.
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while!done {
x += x - 3;
println!("x iterative value is {}", x);
if x % 5 == 0 {
done = true;
}
}
// The 'for' loop is used for a particular number of times
for x in 0..10 {
println!("the 'for' loop for x is {}", x); // x: i32
}
// The enumerate function used for keeping track how many times of the 'for' loop execute.
for (index, value) in (5..10).enumerate() {
println!("index is {} and value is {}", index, value);
}
let lines_all = "hello\nworld".lines();
for (linenumber, line) in lines_all.enumerate() {
println!("{}, {}", linenumber, line);
}
// Use break or continue to stop the interation
}
fn print_num(x: i32){
println!("x is {}", x);
}
fn add_num(x: i32, y: i32){
println!("sum is {}", x + y);
}
fn add_one(x: i32) -> i32{
x + 1
}
fn | (x: i32) -> i32 { x } | foo | identifier_name |
main.rs | fn main() {
println!("Hello, world!");
let mut x: i32 = 5;
x = 10;
print_num(5);
add_num(4, 6);
let x1: i32;
x1 = add_one(7);
let f: fn(i32) -> i32 = add_one;
let ff = add_one;
let x2 = f(6);
let x3 = ff(8);
let x_bool = true;
let y_bool: bool = false;
println!("x_bool's value: {}", x_bool);
let x_char = 'H';
println!("x_char's value: {}", x_char);
let a = [1, 2, 3]; //a: [i32; 3]
let mut m = [1, 2, 3]; //m: [i32; 3]
let aa = [0; 20]; //aa is an array with 0*20
println!("aa has {} elements", a.len());
println!("m's second value is {}", m[1]);
let names = ["Xiaoming", "Xiaohong", "Xiaohua"]; //names: [&str; 3]
println!("The second name is {}", names[1]);
let sum = [0, 1, 2, 3];
let sum_complete = &sum[..]; //A slice containing all of the elements
let sum_middle = &sum[1..4]; //A slice only contain element from 1 to 3
println!("sum_complete's length is {}", sum_complete.len());
println!("sum_middle's length is {}", sum_middle.len());
let (x, y, z) = (1, 2, 3);
println!("x is {}", x);
let tuple_single = (0,); //This is a single element tuple
let var_single = (0); //This is a single variable bindings
println!("var_single is {}", var_single);
let tuple = (1, 2, 3);
let x = tuple.0;
let y = tuple.1;
let z = tuple.2;
println!("x is {}", x);
let x: fn(i32) -> i32 = foo;
let y = x(34);
println!("y is {}", y);
// Line comments are anything after '//' and extend to the end of the line.
// Put a space between the '//' and the comments so that it is more readable.
/// Doc comments using /// instead of //, and support makedown notation inside
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// # fn add_one(x: i32) -> i32 {
/// # x + 1
/// # }
/// ```
fn plus_one(x: i32) -> i32 {
x + 1
}
let x = 7;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six");
}
let y = if x == 5 {
10
} else {
15
}; // y: i32
println!("y is {}", y);
// Or let y = if x == 5 { 10 } else { 15 }; // y: i32
// Rust provide 3 kinds of iterative activity: loop, while, for.
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while!done {
x += x - 3;
println!("x iterative value is {}", x);
if x % 5 == 0 {
done = true;
}
}
// The 'for' loop is used for a particular number of times
for x in 0..10 {
println!("the 'for' loop for x is {}", x); // x: i32
}
// The enumerate function used for keeping track how many times of the 'for' loop execute.
for (index, value) in (5..10).enumerate() {
println!("index is {} and value is {}", index, value);
}
let lines_all = "hello\nworld".lines();
for (linenumber, line) in lines_all.enumerate() {
println!("{}, {}", linenumber, line);
}
// Use break or continue to stop the interation
}
fn print_num(x: i32) |
fn add_num(x: i32, y: i32){
println!("sum is {}", x + y);
}
fn add_one(x: i32) -> i32{
x + 1
}
fn foo(x: i32) -> i32 { x } | {
println!("x is {}", x);
} | identifier_body |
main.rs | fn main() {
println!("Hello, world!");
let mut x: i32 = 5;
x = 10;
print_num(5);
add_num(4, 6);
let x1: i32; | let x2 = f(6);
let x3 = ff(8);
let x_bool = true;
let y_bool: bool = false;
println!("x_bool's value: {}", x_bool);
let x_char = 'H';
println!("x_char's value: {}", x_char);
let a = [1, 2, 3]; //a: [i32; 3]
let mut m = [1, 2, 3]; //m: [i32; 3]
let aa = [0; 20]; //aa is an array with 0*20
println!("aa has {} elements", a.len());
println!("m's second value is {}", m[1]);
let names = ["Xiaoming", "Xiaohong", "Xiaohua"]; //names: [&str; 3]
println!("The second name is {}", names[1]);
let sum = [0, 1, 2, 3];
let sum_complete = &sum[..]; //A slice containing all of the elements
let sum_middle = &sum[1..4]; //A slice only contain element from 1 to 3
println!("sum_complete's length is {}", sum_complete.len());
println!("sum_middle's length is {}", sum_middle.len());
let (x, y, z) = (1, 2, 3);
println!("x is {}", x);
let tuple_single = (0,); //This is a single element tuple
let var_single = (0); //This is a single variable bindings
println!("var_single is {}", var_single);
let tuple = (1, 2, 3);
let x = tuple.0;
let y = tuple.1;
let z = tuple.2;
println!("x is {}", x);
let x: fn(i32) -> i32 = foo;
let y = x(34);
println!("y is {}", y);
// Line comments are anything after '//' and extend to the end of the line.
// Put a space between the '//' and the comments so that it is more readable.
/// Doc comments using /// instead of //, and support makedown notation inside
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// # fn add_one(x: i32) -> i32 {
/// # x + 1
/// # }
/// ```
fn plus_one(x: i32) -> i32 {
x + 1
}
let x = 7;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six");
}
let y = if x == 5 {
10
} else {
15
}; // y: i32
println!("y is {}", y);
// Or let y = if x == 5 { 10 } else { 15 }; // y: i32
// Rust provide 3 kinds of iterative activity: loop, while, for.
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while!done {
x += x - 3;
println!("x iterative value is {}", x);
if x % 5 == 0 {
done = true;
}
}
// The 'for' loop is used for a particular number of times
for x in 0..10 {
println!("the 'for' loop for x is {}", x); // x: i32
}
// The enumerate function used for keeping track how many times of the 'for' loop execute.
for (index, value) in (5..10).enumerate() {
println!("index is {} and value is {}", index, value);
}
let lines_all = "hello\nworld".lines();
for (linenumber, line) in lines_all.enumerate() {
println!("{}, {}", linenumber, line);
}
// Use break or continue to stop the interation
}
fn print_num(x: i32){
println!("x is {}", x);
}
fn add_num(x: i32, y: i32){
println!("sum is {}", x + y);
}
fn add_one(x: i32) -> i32{
x + 1
}
fn foo(x: i32) -> i32 { x } | x1 = add_one(7);
let f: fn(i32) -> i32 = add_one;
let ff = add_one; | random_line_split |
if_match.rs | use header::EntityTag;
header! {
#[doc="`If-Match` header, defined in"]
#[doc="[RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1)"]
#[doc=""]
#[doc="The `If-Match` header field makes the request method conditional on"]
#[doc="the recipient origin server either having at least one current"]
#[doc="representation of the target resource, when the field-value is \"*\","]
#[doc="or having a current representation of the target resource that has an"]
#[doc="entity-tag matching a member of the list of entity-tags provided in"]
#[doc="the field-value."]
#[doc=""]
#[doc="An origin server MUST use the strong comparison function when"]
#[doc="comparing entity-tags for `If-Match`, since the client"]
#[doc="intends this precondition to prevent the method from being applied if"]
#[doc="there have been any changes to the representation data."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="If-Match = \"*\" / 1#entity-tag"]
#[doc="```"]
#[doc=""]
#[doc="# Example values"]
#[doc="* `\"xyzzy\"`"]
#[doc="* \"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]
(IfMatch, "If-Match") => {Any / (EntityTag)+}
test_if_match { | test_header!(
test2,
vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""],
Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned()),
EntityTag::new(false, "r2d2xxxx".to_owned()),
EntityTag::new(false, "c3piozzzz".to_owned())])));
test_header!(test3, vec![b"*"], Some(IfMatch::Any));
}
}
bench_header!(star, IfMatch, { vec![b"*".to_vec()] });
bench_header!(single, IfMatch, { vec![b"\"xyzzy\"".to_vec()] });
bench_header!(multi, IfMatch,
{ vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"".to_vec()] }); | test_header!(
test1,
vec![b"\"xyzzy\""],
Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned())]))); | random_line_split |
http_loader.rs |
// If the URL is a view-source scheme then the scheme data contains the
// real URL that should be used for which the source is to be viewed.
// Change our existing URL to that and keep note that we are viewing
// the source rather than rendering the contents of the URL.
let viewing_source = url.scheme == "view-source";
if viewing_source {
let inner_url = load_data.url.non_relative_scheme_data().unwrap();
doc_url = Url::parse(inner_url).unwrap();
url = replace_hosts(&doc_url);
match &*url.scheme {
"http" | "https" => {}
_ => {
let s = format!("The {} scheme with view-source is not supported", url.scheme);
send_error(url, s, start_chan);
return;
}
};
}
// Loop to handle redirects.
loop {
iters = iters + 1;
if &*url.scheme!= "https" && request_must_be_secured(&hsts_list.lock().unwrap(), &url) {
info!("{} is in the strict transport security list, requesting secure host", url);
url = secure_url(&url);
}
if iters > max_redirects {
send_error(url, "too many redirects".to_string(), start_chan);
return;
}
match &*url.scheme {
"http" | "https" => {}
_ => {
let s = format!("{} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan);
return;
}
}
info!("requesting {}", url.serialize());
let ssl_err_string = "Some(OpenSslErrors([UnknownError { library: \"SSL routines\", \
function: \"SSL3_GET_SERVER_CERTIFICATE\", \
reason: \"certificate verify failed\" }]))";
let req = if opts::get().nossl {
Request::with_connector(load_data.method.clone(), url.clone(), &HttpConnector)
} else {
let mut context = SslContext::new(SslMethod::Sslv23).unwrap();
context.set_verify(SSL_VERIFY_PEER, None);
context.set_CA_file(&resources_dir_path().join("certs")).unwrap();
Request::with_connector(load_data.method.clone(), url.clone(),
&HttpsConnector::new(Openssl { context: Arc::new(context) }))
};
let mut req = match req {
Ok(req) => req,
Err(HttpError::Io(ref io_error)) if (
io_error.kind() == io::ErrorKind::Other &&
io_error.description() == "Error in OpenSSL" &&
// FIXME: This incredibly hacky. Make it more robust, and at least test it.
format!("{:?}", io_error.cause()) == ssl_err_string
) => {
let mut image = resources_dir_path();
image.push("badcert.html");
let load_data = LoadData::new(Url::from_file_path(&*image).unwrap(), None);
file_loader::factory(load_data, start_chan, classifier);
return;
},
Err(e) => {
println!("{:?}", e);
send_error(url, e.description().to_string(), start_chan);
return;
}
};
//Ensure that the host header is set from the original url
let host = Host {
hostname: doc_url.serialize_host().unwrap(),
port: doc_url.port_or_default()
};
// Avoid automatically preserving request headers when redirects occur.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=401564 and
// https://bugzilla.mozilla.org/show_bug.cgi?id=216828.
// Only preserve ones which have been explicitly marked as such.
if iters == 1 {
let mut combined_headers = load_data.headers.clone();
combined_headers.extend(load_data.preserved_headers.iter());
*req.headers_mut() = combined_headers;
} else {
*req.headers_mut() = load_data.preserved_headers.clone();
}
req.headers_mut().set(host);
if!req.headers().has::<Accept>() {
let accept = Accept(vec![
qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),
qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_string()), vec![])),
QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)),
QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)),
]);
req.headers_mut().set(accept);
}
let (tx, rx) = ipc::channel().unwrap();
resource_mgr_chan.send(ControlMsg::GetCookiesForUrl(doc_url.clone(),
tx,
CookieSource::HTTP)).unwrap();
if let Some(cookie_list) = rx.recv().unwrap() {
let mut v = Vec::new();
v.push(cookie_list.into_bytes());
req.headers_mut().set_raw("Cookie".to_owned(), v);
}
if!req.headers().has::<AcceptEncoding>() {
req.headers_mut().set_raw("Accept-Encoding".to_owned(), vec![b"gzip, deflate".to_vec()]);
}
if log_enabled!(log::LogLevel::Info) {
info!("{}", load_data.method);
for header in req.headers().iter() {
info!(" - {}", header);
}
info!("{:?}", load_data.data);
}
// Avoid automatically sending request body if a redirect has occurred.
let writer = match load_data.data {
Some(ref data) if iters == 1 => {
req.headers_mut().set(ContentLength(data.len() as u64));
let mut writer = match req.start() {
Ok(w) => w,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
};
match writer.write_all(&*data) {
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
_ => {}
};
writer
},
_ => {
match load_data.method {
Method::Get | Method::Head => (),
_ => req.headers_mut().set(ContentLength(0))
}
match req.start() {
Ok(w) => w,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
}
}
};
// Send an HttpRequest message to devtools with a unique request_id
// TODO: Do this only if load_data has some pipeline_id, and send the pipeline_id in the message
let request_id = uuid::Uuid::new_v4().to_simple_string();
if let Some(ref chan) = devtools_chan {
let net_event = NetworkEvent::HttpRequest(load_data.url.clone(),
load_data.method.clone(),
load_data.headers.clone(),
load_data.data.clone());
chan.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::NetworkEvent(request_id.clone(),
net_event))).unwrap();
}
let mut response = match writer.send() {
Ok(r) => r,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
};
// Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {}, headers:", response.status);
if log_enabled!(log::LogLevel::Info) {
for header in response.headers.iter() {
info!(" - {}", header);
}
}
if let Some(cookies) = response.headers.get_raw("set-cookie") {
for cookie in cookies {
if let Ok(cookies) = String::from_utf8(cookie.clone()) {
resource_mgr_chan.send(ControlMsg::SetCookiesForUrl(doc_url.clone(),
cookies,
CookieSource::HTTP)).unwrap();
}
}
}
if url.scheme == "https" {
if let Some(header) = response.headers.get::<StrictTransportSecurity>() {
if let Some(host) = url.domain() {
info!("adding host {} to the strict transport security list", host);
info!("- max-age {}", header.max_age);
let include_subdomains = if header.include_subdomains {
info!("- includeSubdomains");
IncludeSubdomains::Included
} else {
IncludeSubdomains::NotIncluded
};
resource_mgr_chan.send(
ControlMsg::SetHSTSEntryForHost(
host.to_string(), include_subdomains, header.max_age
)
).unwrap();
}
}
}
if response.status.class() == StatusClass::Redirection {
match response.headers.get::<Location>() {
Some(&Location(ref new_url)) => {
// CORS (https://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
match load_data.cors {
Some(ref c) => {
if c.preflight {
// The preflight lied
send_error(url,
"Preflight fetch inconsistent with main fetch".to_string(),
start_chan);
return;
} else {
// XXXManishearth There are some CORS-related steps here,
// but they don't seem necessary until credentials are implemented
}
}
_ => {}
}
let new_doc_url = match UrlParser::new().base_url(&doc_url).parse(&new_url) {
Ok(u) => u,
Err(e) => {
send_error(doc_url, e.to_string(), start_chan);
return;
}
};
info!("redirecting to {}", new_doc_url);
url = replace_hosts(&new_doc_url);
doc_url = new_doc_url;
// According to https://tools.ietf.org/html/rfc7231#section-6.4.2,
// historically UAs have rewritten POST->GET on 301 and 302 responses.
if load_data.method == Method::Post &&
(response.status == StatusCode::MovedPermanently ||
response.status == StatusCode::Found) {
load_data.method = Method::Get;
}
if redirected_to.contains(&doc_url) {
send_error(doc_url, "redirect loop".to_string(), start_chan);
return;
}
redirected_to.insert(doc_url.clone());
continue;
}
None => ()
}
}
let mut adjusted_headers = response.headers.clone();
if viewing_source {
adjusted_headers.set(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec![])));
}
let mut metadata: Metadata = Metadata::default(doc_url);
metadata.set_content_type(match adjusted_headers.get() {
Some(&ContentType(ref mime)) => Some(mime),
None => None
});
metadata.headers = Some(adjusted_headers);
metadata.status = Some(response.status_raw().clone());
let mut encoding_str: Option<String> = None;
//FIXME: Implement Content-Encoding Header https://github.com/hyperium/hyper/issues/391
if let Some(encodings) = response.headers.get_raw("content-encoding") {
for encoding in encodings {
if let Ok(encodings) = String::from_utf8(encoding.clone()) {
if encodings == "gzip" || encodings == "deflate" {
encoding_str = Some(encodings);
break;
}
}
}
}
// Send an HttpResponse message to devtools with the corresponding request_id
// TODO: Send this message only if load_data has a pipeline_id that is not None
if let Some(ref chan) = devtools_chan {
let net_event_response =
NetworkEvent::HttpResponse(metadata.headers.clone(),
metadata.status.clone(),
None);
chan.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::NetworkEvent(request_id,
net_event_response))).unwrap();
}
match encoding_str {
Some(encoding) => {
if encoding == "gzip" {
let result = GzDecoder::new(response);
match result {
Ok(mut response_decoding) => {
send_data(&mut response_decoding, start_chan, metadata, classifier);
}
Err(err) => {
send_error(metadata.final_url, err.to_string(), start_chan);
return;
}
}
} else if encoding == "deflate" {
let mut response_decoding = DeflateDecoder::new(response);
send_data(&mut response_decoding, start_chan, metadata, classifier);
}
},
None => {
send_data(&mut response, start_chan, metadata, classifier);
}
}
// We didn't get redirected.
break;
}
}
fn send_data<R: Read>(reader: &mut R,
start_chan: LoadConsumer,
metadata: Metadata,
classifier: Arc<MIMEClassifier>) | {
let (progress_chan, mut chunk) = {
let buf = match read_block(reader) {
Ok(ReadResult::Payload(buf)) => buf,
_ => vec!(),
};
let p = match start_sending_sniffed_opt(start_chan, metadata, classifier, &buf) {
Ok(p) => p,
_ => return
};
(p, buf)
};
loop {
if progress_chan.send(Payload(chunk)).is_err() {
// The send errors when the receiver is out of scope,
// which will happen if the fetch has timed out (or has been aborted)
// so we don't need to continue with the loading of the file here.
return;
} | identifier_body |
|
http_loader.rs | ;
use std::boxed::FnBox;
use uuid;
pub fn factory(resource_mgr_chan: IpcSender<ControlMsg>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
hsts_list: Arc<Mutex<HSTSList>>)
-> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> {
box move |load_data, senders, classifier| {
spawn_named("http_loader".to_owned(),
move || load(load_data, senders, classifier, resource_mgr_chan, devtools_chan, hsts_list))
}
}
fn send_error(url: Url, err: String, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
match start_sending_opt(start_chan, metadata) {
Ok(p) => p.send(Done(Err(err))).unwrap(),
_ => {}
};
}
enum ReadResult {
Payload(Vec<u8>),
EOF,
}
fn read_block<R: Read>(reader: &mut R) -> Result<ReadResult, ()> {
let mut buf = vec![0; 1024];
match reader.read(&mut buf) {
Ok(len) if len > 0 => {
unsafe { buf.set_len(len); }
Ok(ReadResult::Payload(buf))
}
Ok(_) => Ok(ReadResult::EOF),
Err(_) => Err(()),
}
}
fn request_must_be_secured(hsts_list: &HSTSList, url: &Url) -> bool {
match url.domain() {
Some(ref h) => {
hsts_list.is_host_secure(h)
},
_ => false
}
}
fn load(mut load_data: LoadData,
start_chan: LoadConsumer,
classifier: Arc<MIMEClassifier>,
resource_mgr_chan: IpcSender<ControlMsg>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
hsts_list: Arc<Mutex<HSTSList>>) {
// FIXME: At the time of writing this FIXME, servo didn't have any central
// location for configuration. If you're reading this and such a
// repository DOES exist, please update this constant to use it.
let max_redirects = 50;
let mut iters = 0;
// URL of the document being loaded, as seen by all the higher-level code.
let mut doc_url = load_data.url.clone();
// URL that we actually fetch from the network, after applying the replacements
// specified in the hosts file.
let mut url = replace_hosts(&load_data.url);
let mut redirected_to = HashSet::new();
// If the URL is a view-source scheme then the scheme data contains the
// real URL that should be used for which the source is to be viewed.
// Change our existing URL to that and keep note that we are viewing
// the source rather than rendering the contents of the URL.
let viewing_source = url.scheme == "view-source";
if viewing_source {
let inner_url = load_data.url.non_relative_scheme_data().unwrap();
doc_url = Url::parse(inner_url).unwrap();
url = replace_hosts(&doc_url);
match &*url.scheme {
"http" | "https" => {}
_ => {
let s = format!("The {} scheme with view-source is not supported", url.scheme);
send_error(url, s, start_chan);
return;
}
};
}
// Loop to handle redirects.
loop {
iters = iters + 1;
if &*url.scheme!= "https" && request_must_be_secured(&hsts_list.lock().unwrap(), &url) {
info!("{} is in the strict transport security list, requesting secure host", url);
url = secure_url(&url);
}
if iters > max_redirects {
send_error(url, "too many redirects".to_string(), start_chan);
return;
}
match &*url.scheme {
"http" | "https" => {}
_ => {
let s = format!("{} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan);
return;
}
}
info!("requesting {}", url.serialize());
let ssl_err_string = "Some(OpenSslErrors([UnknownError { library: \"SSL routines\", \
function: \"SSL3_GET_SERVER_CERTIFICATE\", \
reason: \"certificate verify failed\" }]))";
let req = if opts::get().nossl {
Request::with_connector(load_data.method.clone(), url.clone(), &HttpConnector)
} else {
let mut context = SslContext::new(SslMethod::Sslv23).unwrap();
context.set_verify(SSL_VERIFY_PEER, None);
context.set_CA_file(&resources_dir_path().join("certs")).unwrap();
Request::with_connector(load_data.method.clone(), url.clone(),
&HttpsConnector::new(Openssl { context: Arc::new(context) }))
};
let mut req = match req {
Ok(req) => req,
Err(HttpError::Io(ref io_error)) if (
io_error.kind() == io::ErrorKind::Other &&
io_error.description() == "Error in OpenSSL" &&
// FIXME: This incredibly hacky. Make it more robust, and at least test it.
format!("{:?}", io_error.cause()) == ssl_err_string
) => {
let mut image = resources_dir_path();
image.push("badcert.html");
let load_data = LoadData::new(Url::from_file_path(&*image).unwrap(), None);
file_loader::factory(load_data, start_chan, classifier);
return;
},
Err(e) => {
println!("{:?}", e);
send_error(url, e.description().to_string(), start_chan);
return;
}
};
//Ensure that the host header is set from the original url
let host = Host {
hostname: doc_url.serialize_host().unwrap(),
port: doc_url.port_or_default()
}; | // See https://bugzilla.mozilla.org/show_bug.cgi?id=401564 and
// https://bugzilla.mozilla.org/show_bug.cgi?id=216828.
// Only preserve ones which have been explicitly marked as such.
if iters == 1 {
let mut combined_headers = load_data.headers.clone();
combined_headers.extend(load_data.preserved_headers.iter());
*req.headers_mut() = combined_headers;
} else {
*req.headers_mut() = load_data.preserved_headers.clone();
}
req.headers_mut().set(host);
if!req.headers().has::<Accept>() {
let accept = Accept(vec![
qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),
qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_string()), vec![])),
QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)),
QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)),
]);
req.headers_mut().set(accept);
}
let (tx, rx) = ipc::channel().unwrap();
resource_mgr_chan.send(ControlMsg::GetCookiesForUrl(doc_url.clone(),
tx,
CookieSource::HTTP)).unwrap();
if let Some(cookie_list) = rx.recv().unwrap() {
let mut v = Vec::new();
v.push(cookie_list.into_bytes());
req.headers_mut().set_raw("Cookie".to_owned(), v);
}
if!req.headers().has::<AcceptEncoding>() {
req.headers_mut().set_raw("Accept-Encoding".to_owned(), vec![b"gzip, deflate".to_vec()]);
}
if log_enabled!(log::LogLevel::Info) {
info!("{}", load_data.method);
for header in req.headers().iter() {
info!(" - {}", header);
}
info!("{:?}", load_data.data);
}
// Avoid automatically sending request body if a redirect has occurred.
let writer = match load_data.data {
Some(ref data) if iters == 1 => {
req.headers_mut().set(ContentLength(data.len() as u64));
let mut writer = match req.start() {
Ok(w) => w,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
};
match writer.write_all(&*data) {
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
_ => {}
};
writer
},
_ => {
match load_data.method {
Method::Get | Method::Head => (),
_ => req.headers_mut().set(ContentLength(0))
}
match req.start() {
Ok(w) => w,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
}
}
};
// Send an HttpRequest message to devtools with a unique request_id
// TODO: Do this only if load_data has some pipeline_id, and send the pipeline_id in the message
let request_id = uuid::Uuid::new_v4().to_simple_string();
if let Some(ref chan) = devtools_chan {
let net_event = NetworkEvent::HttpRequest(load_data.url.clone(),
load_data.method.clone(),
load_data.headers.clone(),
load_data.data.clone());
chan.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::NetworkEvent(request_id.clone(),
net_event))).unwrap();
}
let mut response = match writer.send() {
Ok(r) => r,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
};
// Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {}, headers:", response.status);
if log_enabled!(log::LogLevel::Info) {
for header in response.headers.iter() {
info!(" - {}", header);
}
}
if let Some(cookies) = response.headers.get_raw("set-cookie") {
for cookie in cookies {
if let Ok(cookies) = String::from_utf8(cookie.clone()) {
resource_mgr_chan.send(ControlMsg::SetCookiesForUrl(doc_url.clone(),
cookies,
CookieSource::HTTP)).unwrap();
}
}
}
if url.scheme == "https" {
if let Some(header) = response.headers.get::<StrictTransportSecurity>() {
if let Some(host) = url.domain() {
info!("adding host {} to the strict transport security list", host);
info!("- max-age {}", header.max_age);
let include_subdomains = if header.include_subdomains {
info!("- includeSubdomains");
IncludeSubdomains::Included
} else {
IncludeSubdomains::NotIncluded
};
resource_mgr_chan.send(
ControlMsg::SetHSTSEntryForHost(
host.to_string(), include_subdomains, header.max_age
)
).unwrap();
}
}
}
if response.status.class() == StatusClass::Redirection {
match response.headers.get::<Location>() {
Some(&Location(ref new_url)) => {
// CORS (https://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
match load_data.cors {
Some(ref c) => {
if c.preflight {
// The preflight lied
send_error(url,
"Preflight fetch inconsistent with main fetch".to_string(),
start_chan);
return;
} else {
// XXXManishearth There are some CORS-related steps here,
// but they don't seem necessary until credentials are implemented
}
}
_ => {}
}
let new_doc_url = match UrlParser::new().base_url(&doc_url).parse(&new_url) {
Ok(u) => u,
Err(e) => {
send_error(doc_url, e.to_string(), start_chan);
return;
}
};
info!("redirecting to {}", new_doc_url);
url = replace_hosts(&new_doc_url);
doc_url = new_doc_url;
// According to https://tools.ietf.org/html/rfc7231#section-6.4.2,
// historically UAs have rewritten POST->GET on 301 and 302 responses.
if load_data.method == Method::Post &&
(response.status == StatusCode::MovedPermanently ||
response.status == StatusCode::Found) {
load_data.method = Method::Get;
}
if redirected_to.contains(&doc_url) {
send_error(doc_url, "redirect loop".to_string(), start_chan);
return;
}
redirected_to.insert(doc_url.clone());
continue;
}
None => ()
}
}
let mut adjusted_headers = response.headers.clone();
if viewing_source {
adjusted_headers.set(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec![])));
}
let mut metadata: Metadata = Metadata::default(doc_url);
metadata.set_content_type(match adjusted_headers.get() {
Some(&ContentType(ref mime)) => Some(mime),
None => None
});
metadata.headers = Some(adjusted_headers);
metadata.status = Some(response.status_raw().clone());
let mut encoding_str: Option<String> = None;
//FIXME: Implement Content-Encoding Header https://github.com/hyperium/hyper/issues/391
if let Some(encodings) = response.headers.get_raw("content-encoding") {
for encoding in encodings {
if let Ok(encodings) = String::from_utf8(encoding.clone()) {
if encodings == "gzip" || encodings == "deflate" {
encoding_str = Some(encodings);
break;
}
}
}
}
// Send an HttpResponse message to devtools with the corresponding request_id
// TODO: Send this message only if load_data has a pipeline_id that is not None
if let Some(ref chan) = devtools_chan {
let net_event_response =
NetworkEvent::HttpResponse(metadata.headers.clone(),
metadata.status.clone(),
None);
chan.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::NetworkEvent(request_id,
net_event_response))).unwrap();
}
match encoding_str {
Some(encoding) => {
if encoding == "gzip" {
let result = Gz |
// Avoid automatically preserving request headers when redirects occur. | random_line_split |
http_loader.rs | use std::boxed::FnBox;
use uuid;
pub fn factory(resource_mgr_chan: IpcSender<ControlMsg>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
hsts_list: Arc<Mutex<HSTSList>>)
-> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> {
box move |load_data, senders, classifier| {
spawn_named("http_loader".to_owned(),
move || load(load_data, senders, classifier, resource_mgr_chan, devtools_chan, hsts_list))
}
}
fn | (url: Url, err: String, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
match start_sending_opt(start_chan, metadata) {
Ok(p) => p.send(Done(Err(err))).unwrap(),
_ => {}
};
}
enum ReadResult {
Payload(Vec<u8>),
EOF,
}
fn read_block<R: Read>(reader: &mut R) -> Result<ReadResult, ()> {
let mut buf = vec![0; 1024];
match reader.read(&mut buf) {
Ok(len) if len > 0 => {
unsafe { buf.set_len(len); }
Ok(ReadResult::Payload(buf))
}
Ok(_) => Ok(ReadResult::EOF),
Err(_) => Err(()),
}
}
fn request_must_be_secured(hsts_list: &HSTSList, url: &Url) -> bool {
match url.domain() {
Some(ref h) => {
hsts_list.is_host_secure(h)
},
_ => false
}
}
fn load(mut load_data: LoadData,
start_chan: LoadConsumer,
classifier: Arc<MIMEClassifier>,
resource_mgr_chan: IpcSender<ControlMsg>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
hsts_list: Arc<Mutex<HSTSList>>) {
// FIXME: At the time of writing this FIXME, servo didn't have any central
// location for configuration. If you're reading this and such a
// repository DOES exist, please update this constant to use it.
let max_redirects = 50;
let mut iters = 0;
// URL of the document being loaded, as seen by all the higher-level code.
let mut doc_url = load_data.url.clone();
// URL that we actually fetch from the network, after applying the replacements
// specified in the hosts file.
let mut url = replace_hosts(&load_data.url);
let mut redirected_to = HashSet::new();
// If the URL is a view-source scheme then the scheme data contains the
// real URL that should be used for which the source is to be viewed.
// Change our existing URL to that and keep note that we are viewing
// the source rather than rendering the contents of the URL.
let viewing_source = url.scheme == "view-source";
if viewing_source {
let inner_url = load_data.url.non_relative_scheme_data().unwrap();
doc_url = Url::parse(inner_url).unwrap();
url = replace_hosts(&doc_url);
match &*url.scheme {
"http" | "https" => {}
_ => {
let s = format!("The {} scheme with view-source is not supported", url.scheme);
send_error(url, s, start_chan);
return;
}
};
}
// Loop to handle redirects.
loop {
iters = iters + 1;
if &*url.scheme!= "https" && request_must_be_secured(&hsts_list.lock().unwrap(), &url) {
info!("{} is in the strict transport security list, requesting secure host", url);
url = secure_url(&url);
}
if iters > max_redirects {
send_error(url, "too many redirects".to_string(), start_chan);
return;
}
match &*url.scheme {
"http" | "https" => {}
_ => {
let s = format!("{} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan);
return;
}
}
info!("requesting {}", url.serialize());
let ssl_err_string = "Some(OpenSslErrors([UnknownError { library: \"SSL routines\", \
function: \"SSL3_GET_SERVER_CERTIFICATE\", \
reason: \"certificate verify failed\" }]))";
let req = if opts::get().nossl {
Request::with_connector(load_data.method.clone(), url.clone(), &HttpConnector)
} else {
let mut context = SslContext::new(SslMethod::Sslv23).unwrap();
context.set_verify(SSL_VERIFY_PEER, None);
context.set_CA_file(&resources_dir_path().join("certs")).unwrap();
Request::with_connector(load_data.method.clone(), url.clone(),
&HttpsConnector::new(Openssl { context: Arc::new(context) }))
};
let mut req = match req {
Ok(req) => req,
Err(HttpError::Io(ref io_error)) if (
io_error.kind() == io::ErrorKind::Other &&
io_error.description() == "Error in OpenSSL" &&
// FIXME: This incredibly hacky. Make it more robust, and at least test it.
format!("{:?}", io_error.cause()) == ssl_err_string
) => {
let mut image = resources_dir_path();
image.push("badcert.html");
let load_data = LoadData::new(Url::from_file_path(&*image).unwrap(), None);
file_loader::factory(load_data, start_chan, classifier);
return;
},
Err(e) => {
println!("{:?}", e);
send_error(url, e.description().to_string(), start_chan);
return;
}
};
//Ensure that the host header is set from the original url
let host = Host {
hostname: doc_url.serialize_host().unwrap(),
port: doc_url.port_or_default()
};
// Avoid automatically preserving request headers when redirects occur.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=401564 and
// https://bugzilla.mozilla.org/show_bug.cgi?id=216828.
// Only preserve ones which have been explicitly marked as such.
if iters == 1 {
let mut combined_headers = load_data.headers.clone();
combined_headers.extend(load_data.preserved_headers.iter());
*req.headers_mut() = combined_headers;
} else {
*req.headers_mut() = load_data.preserved_headers.clone();
}
req.headers_mut().set(host);
if!req.headers().has::<Accept>() {
let accept = Accept(vec![
qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),
qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_string()), vec![])),
QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)),
QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)),
]);
req.headers_mut().set(accept);
}
let (tx, rx) = ipc::channel().unwrap();
resource_mgr_chan.send(ControlMsg::GetCookiesForUrl(doc_url.clone(),
tx,
CookieSource::HTTP)).unwrap();
if let Some(cookie_list) = rx.recv().unwrap() {
let mut v = Vec::new();
v.push(cookie_list.into_bytes());
req.headers_mut().set_raw("Cookie".to_owned(), v);
}
if!req.headers().has::<AcceptEncoding>() {
req.headers_mut().set_raw("Accept-Encoding".to_owned(), vec![b"gzip, deflate".to_vec()]);
}
if log_enabled!(log::LogLevel::Info) {
info!("{}", load_data.method);
for header in req.headers().iter() {
info!(" - {}", header);
}
info!("{:?}", load_data.data);
}
// Avoid automatically sending request body if a redirect has occurred.
let writer = match load_data.data {
Some(ref data) if iters == 1 => {
req.headers_mut().set(ContentLength(data.len() as u64));
let mut writer = match req.start() {
Ok(w) => w,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
};
match writer.write_all(&*data) {
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
_ => {}
};
writer
},
_ => {
match load_data.method {
Method::Get | Method::Head => (),
_ => req.headers_mut().set(ContentLength(0))
}
match req.start() {
Ok(w) => w,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
}
}
};
// Send an HttpRequest message to devtools with a unique request_id
// TODO: Do this only if load_data has some pipeline_id, and send the pipeline_id in the message
let request_id = uuid::Uuid::new_v4().to_simple_string();
if let Some(ref chan) = devtools_chan {
let net_event = NetworkEvent::HttpRequest(load_data.url.clone(),
load_data.method.clone(),
load_data.headers.clone(),
load_data.data.clone());
chan.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::NetworkEvent(request_id.clone(),
net_event))).unwrap();
}
let mut response = match writer.send() {
Ok(r) => r,
Err(e) => {
send_error(url, e.description().to_string(), start_chan);
return;
}
};
// Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {}, headers:", response.status);
if log_enabled!(log::LogLevel::Info) {
for header in response.headers.iter() {
info!(" - {}", header);
}
}
if let Some(cookies) = response.headers.get_raw("set-cookie") {
for cookie in cookies {
if let Ok(cookies) = String::from_utf8(cookie.clone()) {
resource_mgr_chan.send(ControlMsg::SetCookiesForUrl(doc_url.clone(),
cookies,
CookieSource::HTTP)).unwrap();
}
}
}
if url.scheme == "https" {
if let Some(header) = response.headers.get::<StrictTransportSecurity>() {
if let Some(host) = url.domain() {
info!("adding host {} to the strict transport security list", host);
info!("- max-age {}", header.max_age);
let include_subdomains = if header.include_subdomains {
info!("- includeSubdomains");
IncludeSubdomains::Included
} else {
IncludeSubdomains::NotIncluded
};
resource_mgr_chan.send(
ControlMsg::SetHSTSEntryForHost(
host.to_string(), include_subdomains, header.max_age
)
).unwrap();
}
}
}
if response.status.class() == StatusClass::Redirection {
match response.headers.get::<Location>() {
Some(&Location(ref new_url)) => {
// CORS (https://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
match load_data.cors {
Some(ref c) => {
if c.preflight {
// The preflight lied
send_error(url,
"Preflight fetch inconsistent with main fetch".to_string(),
start_chan);
return;
} else {
// XXXManishearth There are some CORS-related steps here,
// but they don't seem necessary until credentials are implemented
}
}
_ => {}
}
let new_doc_url = match UrlParser::new().base_url(&doc_url).parse(&new_url) {
Ok(u) => u,
Err(e) => {
send_error(doc_url, e.to_string(), start_chan);
return;
}
};
info!("redirecting to {}", new_doc_url);
url = replace_hosts(&new_doc_url);
doc_url = new_doc_url;
// According to https://tools.ietf.org/html/rfc7231#section-6.4.2,
// historically UAs have rewritten POST->GET on 301 and 302 responses.
if load_data.method == Method::Post &&
(response.status == StatusCode::MovedPermanently ||
response.status == StatusCode::Found) {
load_data.method = Method::Get;
}
if redirected_to.contains(&doc_url) {
send_error(doc_url, "redirect loop".to_string(), start_chan);
return;
}
redirected_to.insert(doc_url.clone());
continue;
}
None => ()
}
}
let mut adjusted_headers = response.headers.clone();
if viewing_source {
adjusted_headers.set(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec![])));
}
let mut metadata: Metadata = Metadata::default(doc_url);
metadata.set_content_type(match adjusted_headers.get() {
Some(&ContentType(ref mime)) => Some(mime),
None => None
});
metadata.headers = Some(adjusted_headers);
metadata.status = Some(response.status_raw().clone());
let mut encoding_str: Option<String> = None;
//FIXME: Implement Content-Encoding Header https://github.com/hyperium/hyper/issues/391
if let Some(encodings) = response.headers.get_raw("content-encoding") {
for encoding in encodings {
if let Ok(encodings) = String::from_utf8(encoding.clone()) {
if encodings == "gzip" || encodings == "deflate" {
encoding_str = Some(encodings);
break;
}
}
}
}
// Send an HttpResponse message to devtools with the corresponding request_id
// TODO: Send this message only if load_data has a pipeline_id that is not None
if let Some(ref chan) = devtools_chan {
let net_event_response =
NetworkEvent::HttpResponse(metadata.headers.clone(),
metadata.status.clone(),
None);
chan.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::NetworkEvent(request_id,
net_event_response))).unwrap();
}
match encoding_str {
Some(encoding) => {
if encoding == "gzip" {
let result = G | send_error | identifier_name |
lib.rs | extern crate hyper;
extern crate url;
extern crate serde;
extern crate serde_json;
extern crate hyper_native_tls;
#[macro_use]
extern crate lazy_static;
use hyper::client::{Client};
use hyper::header::{ContentType};
use hyper::client::response::{Response};
use hyper::error::Error as HyperError;
use url::form_urlencoded::{Serializer};
use std::io::Read;
use std::io::Error;
use std::collections::BTreeMap;
use serde_json::error::Error as JsonError;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
#[derive(Debug)]
pub enum CleverbotError {
IncorrectCredentials,
DuplicatedReferenceNames,
Io(HyperError),
Api(String),
Std(Error),
Json(JsonError),
MissingValue(String)
}
impl From<HyperError> for CleverbotError {
fn from(err: HyperError) -> CleverbotError {
CleverbotError::Io(err)
}
}
impl From<Error> for CleverbotError {
fn from(err: Error) -> CleverbotError {
CleverbotError::Std(err)
}
}
impl From<JsonError> for CleverbotError {
fn from(err: JsonError) -> CleverbotError {
CleverbotError::Json(err)
}
}
pub struct Cleverbot {
user: String,
key: String,
pub nick: String,
}
lazy_static! {
static ref CLIENT: Client = Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap()));
}
impl Cleverbot {
/// Creates a new Cleverbot instance.
///
/// * `user` - The API User.
/// * `key` - The API Key.
/// * `nick` - The reference nick, or None.
pub fn new(user: String, key: String, nick: Option<String>) -> Result<Cleverbot, CleverbotError> {
let mut response = {
let mut args = vec![
("user", &*user),
("key", &*key),
];
if let Some(ref nick) = nick { args.push(("nick", &*nick)) };
try!(request("https://cleverbot.io/1.0/create", &*args)) | let opt_result = json.get("status");
let result = match opt_result {
Some(result) => result,
None => return Err(CleverbotError::MissingValue(String::from("status"))),
};
match result.as_ref() {
"success" => {
let json_nick = json.get("nick");
match json_nick {
Some(nick) => Ok(Cleverbot {
user: user,
key: key,
nick: nick.to_string()
}),
None => Err(CleverbotError::MissingValue(String::from("nick"))),
}
},
"Error: API credentials incorrect" => Err(CleverbotError::IncorrectCredentials),
"Error: reference name already exists" => Err(CleverbotError::DuplicatedReferenceNames),
_ => Err(CleverbotError::Api(result.to_owned()))
}
}
/// Sends the bot a message and returns its response. If the nick is not set, it will
/// set it randomly through set_nick_randomly. Returns its response or error string.
///
/// * `message` - The message to send to the bot.
pub fn say(&mut self, message: &str) -> Result<String, CleverbotError> {
let args = vec![
("user", &*self.user),
("key", &*self.key),
("nick", &*self.nick),
("text", message),
];
let mut response = try!(request("https://cleverbot.io/1.0/ask", &*args));
let mut body = String::new();
try!(response.read_to_string(&mut body));
let json: BTreeMap<String, String> = try!(serde_json::from_str(&body));
let opt_result = json.get("status");
let result = match opt_result {
Some(result) => result,
None => return Err(CleverbotError::MissingValue(String::from("status"))),
};
match result.as_ref() {
"success" => {
let json_response = json.get("response");
match json_response {
Some(response) => Ok(response.to_string()),
None => Err(CleverbotError::MissingValue(String::from("nick"))),
}
},
"Error: API credentials incorrect" => Err(CleverbotError::IncorrectCredentials),
"Error: reference name already exists" => Err(CleverbotError::DuplicatedReferenceNames),
_ => Err(CleverbotError::Api(result.to_owned()))
}
}
}
/// Submits a POST request to the URL with the given vec body.
///
/// * `base` - The URL
/// * `args` - A vector representing the request body.
fn request(base: &str, args: &[(&str, &str)]) -> Result<Response, HyperError> {
let mut serializer = Serializer::new(String::new());
for pair in args {
serializer.append_pair(pair.0, pair.1);
}
let body = serializer.finish();
CLIENT.post(base)
.body(&body)
.header(ContentType::form_url_encoded())
.send()
} | };
let mut body = String::new();
try!(response.read_to_string(&mut body));
let json: BTreeMap<String, String> = try!(serde_json::from_str(&body)); | random_line_split |
lib.rs | extern crate hyper;
extern crate url;
extern crate serde;
extern crate serde_json;
extern crate hyper_native_tls;
#[macro_use]
extern crate lazy_static;
use hyper::client::{Client};
use hyper::header::{ContentType};
use hyper::client::response::{Response};
use hyper::error::Error as HyperError;
use url::form_urlencoded::{Serializer};
use std::io::Read;
use std::io::Error;
use std::collections::BTreeMap;
use serde_json::error::Error as JsonError;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
#[derive(Debug)]
pub enum CleverbotError {
IncorrectCredentials,
DuplicatedReferenceNames,
Io(HyperError),
Api(String),
Std(Error),
Json(JsonError),
MissingValue(String)
}
impl From<HyperError> for CleverbotError {
fn from(err: HyperError) -> CleverbotError {
CleverbotError::Io(err)
}
}
impl From<Error> for CleverbotError {
fn from(err: Error) -> CleverbotError |
}
impl From<JsonError> for CleverbotError {
fn from(err: JsonError) -> CleverbotError {
CleverbotError::Json(err)
}
}
pub struct Cleverbot {
user: String,
key: String,
pub nick: String,
}
lazy_static! {
static ref CLIENT: Client = Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap()));
}
impl Cleverbot {
/// Creates a new Cleverbot instance.
///
/// * `user` - The API User.
/// * `key` - The API Key.
/// * `nick` - The reference nick, or None.
pub fn new(user: String, key: String, nick: Option<String>) -> Result<Cleverbot, CleverbotError> {
let mut response = {
let mut args = vec![
("user", &*user),
("key", &*key),
];
if let Some(ref nick) = nick { args.push(("nick", &*nick)) };
try!(request("https://cleverbot.io/1.0/create", &*args))
};
let mut body = String::new();
try!(response.read_to_string(&mut body));
let json: BTreeMap<String, String> = try!(serde_json::from_str(&body));
let opt_result = json.get("status");
let result = match opt_result {
Some(result) => result,
None => return Err(CleverbotError::MissingValue(String::from("status"))),
};
match result.as_ref() {
"success" => {
let json_nick = json.get("nick");
match json_nick {
Some(nick) => Ok(Cleverbot {
user: user,
key: key,
nick: nick.to_string()
}),
None => Err(CleverbotError::MissingValue(String::from("nick"))),
}
},
"Error: API credentials incorrect" => Err(CleverbotError::IncorrectCredentials),
"Error: reference name already exists" => Err(CleverbotError::DuplicatedReferenceNames),
_ => Err(CleverbotError::Api(result.to_owned()))
}
}
/// Sends the bot a message and returns its response. If the nick is not set, it will
/// set it randomly through set_nick_randomly. Returns its response or error string.
///
/// * `message` - The message to send to the bot.
pub fn say(&mut self, message: &str) -> Result<String, CleverbotError> {
let args = vec![
("user", &*self.user),
("key", &*self.key),
("nick", &*self.nick),
("text", message),
];
let mut response = try!(request("https://cleverbot.io/1.0/ask", &*args));
let mut body = String::new();
try!(response.read_to_string(&mut body));
let json: BTreeMap<String, String> = try!(serde_json::from_str(&body));
let opt_result = json.get("status");
let result = match opt_result {
Some(result) => result,
None => return Err(CleverbotError::MissingValue(String::from("status"))),
};
match result.as_ref() {
"success" => {
let json_response = json.get("response");
match json_response {
Some(response) => Ok(response.to_string()),
None => Err(CleverbotError::MissingValue(String::from("nick"))),
}
},
"Error: API credentials incorrect" => Err(CleverbotError::IncorrectCredentials),
"Error: reference name already exists" => Err(CleverbotError::DuplicatedReferenceNames),
_ => Err(CleverbotError::Api(result.to_owned()))
}
}
}
/// Submits a POST request to the URL with the given vec body.
///
/// * `base` - The URL
/// * `args` - A vector representing the request body.
fn request(base: &str, args: &[(&str, &str)]) -> Result<Response, HyperError> {
let mut serializer = Serializer::new(String::new());
for pair in args {
serializer.append_pair(pair.0, pair.1);
}
let body = serializer.finish();
CLIENT.post(base)
.body(&body)
.header(ContentType::form_url_encoded())
.send()
}
| {
CleverbotError::Std(err)
} | identifier_body |
lib.rs | extern crate hyper;
extern crate url;
extern crate serde;
extern crate serde_json;
extern crate hyper_native_tls;
#[macro_use]
extern crate lazy_static;
use hyper::client::{Client};
use hyper::header::{ContentType};
use hyper::client::response::{Response};
use hyper::error::Error as HyperError;
use url::form_urlencoded::{Serializer};
use std::io::Read;
use std::io::Error;
use std::collections::BTreeMap;
use serde_json::error::Error as JsonError;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
#[derive(Debug)]
pub enum CleverbotError {
IncorrectCredentials,
DuplicatedReferenceNames,
Io(HyperError),
Api(String),
Std(Error),
Json(JsonError),
MissingValue(String)
}
impl From<HyperError> for CleverbotError {
fn from(err: HyperError) -> CleverbotError {
CleverbotError::Io(err)
}
}
impl From<Error> for CleverbotError {
fn from(err: Error) -> CleverbotError {
CleverbotError::Std(err)
}
}
impl From<JsonError> for CleverbotError {
fn | (err: JsonError) -> CleverbotError {
CleverbotError::Json(err)
}
}
pub struct Cleverbot {
user: String,
key: String,
pub nick: String,
}
lazy_static! {
static ref CLIENT: Client = Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap()));
}
impl Cleverbot {
/// Creates a new Cleverbot instance.
///
/// * `user` - The API User.
/// * `key` - The API Key.
/// * `nick` - The reference nick, or None.
pub fn new(user: String, key: String, nick: Option<String>) -> Result<Cleverbot, CleverbotError> {
let mut response = {
let mut args = vec![
("user", &*user),
("key", &*key),
];
if let Some(ref nick) = nick { args.push(("nick", &*nick)) };
try!(request("https://cleverbot.io/1.0/create", &*args))
};
let mut body = String::new();
try!(response.read_to_string(&mut body));
let json: BTreeMap<String, String> = try!(serde_json::from_str(&body));
let opt_result = json.get("status");
let result = match opt_result {
Some(result) => result,
None => return Err(CleverbotError::MissingValue(String::from("status"))),
};
match result.as_ref() {
"success" => {
let json_nick = json.get("nick");
match json_nick {
Some(nick) => Ok(Cleverbot {
user: user,
key: key,
nick: nick.to_string()
}),
None => Err(CleverbotError::MissingValue(String::from("nick"))),
}
},
"Error: API credentials incorrect" => Err(CleverbotError::IncorrectCredentials),
"Error: reference name already exists" => Err(CleverbotError::DuplicatedReferenceNames),
_ => Err(CleverbotError::Api(result.to_owned()))
}
}
/// Sends the bot a message and returns its response. If the nick is not set, it will
/// set it randomly through set_nick_randomly. Returns its response or error string.
///
/// * `message` - The message to send to the bot.
pub fn say(&mut self, message: &str) -> Result<String, CleverbotError> {
let args = vec![
("user", &*self.user),
("key", &*self.key),
("nick", &*self.nick),
("text", message),
];
let mut response = try!(request("https://cleverbot.io/1.0/ask", &*args));
let mut body = String::new();
try!(response.read_to_string(&mut body));
let json: BTreeMap<String, String> = try!(serde_json::from_str(&body));
let opt_result = json.get("status");
let result = match opt_result {
Some(result) => result,
None => return Err(CleverbotError::MissingValue(String::from("status"))),
};
match result.as_ref() {
"success" => {
let json_response = json.get("response");
match json_response {
Some(response) => Ok(response.to_string()),
None => Err(CleverbotError::MissingValue(String::from("nick"))),
}
},
"Error: API credentials incorrect" => Err(CleverbotError::IncorrectCredentials),
"Error: reference name already exists" => Err(CleverbotError::DuplicatedReferenceNames),
_ => Err(CleverbotError::Api(result.to_owned()))
}
}
}
/// Submits a POST request to the URL with the given vec body.
///
/// * `base` - The URL
/// * `args` - A vector representing the request body.
fn request(base: &str, args: &[(&str, &str)]) -> Result<Response, HyperError> {
let mut serializer = Serializer::new(String::new());
for pair in args {
serializer.append_pair(pair.0, pair.1);
}
let body = serializer.finish();
CLIENT.post(base)
.body(&body)
.header(ContentType::form_url_encoded())
.send()
}
| from | identifier_name |
mod.rs | // Root Module
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// AEx is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with AEx. If not, see <http://www.gnu.org/licenses/>.
//#[macro_use]
pub mod util; | pub mod fmt;
pub mod io;
//pub mod source;
pub mod target;
//pub mod types; |
pub mod ast; | random_line_split |
loop-proper-liveness.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test1() {
// In this test the outer 'a loop may terminate without `x` getting initialised. Although the
// `x = loop {... }` statement is reached, the value itself ends up never being computed and
// thus leaving `x` uninit.
let x: i32;
'a: loop {
x = loop { break 'a };
}
println!("{:?}", x); //~ ERROR use of possibly uninitialized variable
}
// test2 and test3 should not fail.
fn test2() {
// In this test the `'a` loop will never terminate thus making the use of `x` unreachable.
let x: i32;
'a: loop {
x = loop { continue 'a };
}
println!("{:?}", x);
}
fn test3() {
let x: i32;
// Similarly, the use of variable `x` is unreachable.
'a: loop {
x = loop { return };
}
println!("{:?}", x);
}
fn | () {
}
| main | identifier_name |
loop-proper-liveness.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test1() {
// In this test the outer 'a loop may terminate without `x` getting initialised. Although the
// `x = loop {... }` statement is reached, the value itself ends up never being computed and
// thus leaving `x` uninit.
let x: i32;
'a: loop {
x = loop { break 'a };
}
println!("{:?}", x); //~ ERROR use of possibly uninitialized variable
}
// test2 and test3 should not fail.
fn test2() |
fn test3() {
let x: i32;
// Similarly, the use of variable `x` is unreachable.
'a: loop {
x = loop { return };
}
println!("{:?}", x);
}
fn main() {
}
| {
// In this test the `'a` loop will never terminate thus making the use of `x` unreachable.
let x: i32;
'a: loop {
x = loop { continue 'a };
}
println!("{:?}", x);
} | identifier_body |
loop-proper-liveness.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test1() {
// In this test the outer 'a loop may terminate without `x` getting initialised. Although the
// `x = loop {... }` statement is reached, the value itself ends up never being computed and
// thus leaving `x` uninit.
let x: i32;
'a: loop {
x = loop { break 'a };
}
println!("{:?}", x); //~ ERROR use of possibly uninitialized variable
}
// test2 and test3 should not fail.
fn test2() {
// In this test the `'a` loop will never terminate thus making the use of `x` unreachable.
let x: i32;
'a: loop {
x = loop { continue 'a };
}
println!("{:?}", x);
}
fn test3() {
let x: i32;
// Similarly, the use of variable `x` is unreachable.
'a: loop {
x = loop { return }; | } | }
println!("{:?}", x);
}
fn main() { | random_line_split |
tests.rs | use super::rocket;
use rocket::local::Client;
use rocket::http::Status;
fn test(uri: &str, expected: &str) {
let client = Client::new(rocket()).unwrap();
let mut res = client.get(uri).dispatch();
assert_eq!(res.body_string(), Some(expected.into()));
}
fn test_404(uri: &str) {
let client = Client::new(rocket()).unwrap();
let res = client.get(uri).dispatch();
assert_eq!(res.status(), Status::NotFound);
}
#[test]
fn test_people() | {
test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy");
test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob");
test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George");
test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd",
"Person not found for UUID: e18b3a5c-488f-4159-a240-2101e0da19fd");
test_404("/people/invalid_uuid");
} | identifier_body |
|
tests.rs | use super::rocket;
use rocket::local::Client;
use rocket::http::Status;
fn test(uri: &str, expected: &str) {
let client = Client::new(rocket()).unwrap();
let mut res = client.get(uri).dispatch();
assert_eq!(res.body_string(), Some(expected.into()));
}
fn test_404(uri: &str) { | assert_eq!(res.status(), Status::NotFound);
}
#[test]
fn test_people() {
test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy");
test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob");
test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George");
test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd",
"Person not found for UUID: e18b3a5c-488f-4159-a240-2101e0da19fd");
test_404("/people/invalid_uuid");
} | let client = Client::new(rocket()).unwrap();
let res = client.get(uri).dispatch(); | random_line_split |
tests.rs | use super::rocket;
use rocket::local::Client;
use rocket::http::Status;
fn test(uri: &str, expected: &str) {
let client = Client::new(rocket()).unwrap();
let mut res = client.get(uri).dispatch();
assert_eq!(res.body_string(), Some(expected.into()));
}
fn test_404(uri: &str) {
let client = Client::new(rocket()).unwrap();
let res = client.get(uri).dispatch();
assert_eq!(res.status(), Status::NotFound);
}
#[test]
fn | () {
test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy");
test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob");
test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George");
test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd",
"Person not found for UUID: e18b3a5c-488f-4159-a240-2101e0da19fd");
test_404("/people/invalid_uuid");
}
| test_people | identifier_name |
function-arguments.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print x
// gdb-check:$1 = 111102
// gdb-command:print y
// gdb-check:$2 = true
// gdb-command:continue
// gdb-command:finish
// gdb-command:print a
// gdb-check:$3 = 2000
// gdb-command:print b
// gdb-check:$4 = 3000
fn main() {
fun(111102, true);
nested(2000, 3000);
fn nested(a: i32, b: i64) -> (i32, i64) {
zzz();
(a, b)
}
}
fn fun(x: int, y: bool) -> (int, bool) {
zzz();
(x, y)
}
fn | () {()}
| zzz | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.