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 |
---|---|---|---|---|
usart3.rs | //! Test the USART3 instance
//!
//! Connect the TX and RX pins to run this test
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0" |
use blue_pill::{Serial, stm32f103xx};
use blue_pill::time::Hertz;
use hal::prelude::*;
use nb::Error;
use rtfm::{P0, T0, TMax};
// CONFIGURATION
pub const BAUD_RATE: Hertz = Hertz(115_200);
// RESOURCES
peripherals!(stm32f103xx, {
AFIO: Peripheral {
ceiling: C0,
},
GPIOB: Peripheral {
ceiling: C0,
},
RCC: Peripheral {
ceiling: C0,
},
USART3: Peripheral {
ceiling: C1,
},
});
// INITIALIZATION PHASE
fn init(ref prio: P0, thr: &TMax) {
let afio = &AFIO.access(prio, thr);
let gpiob = &GPIOB.access(prio, thr);
let rcc = &RCC.access(prio, thr);
let usart3 = USART3.access(prio, thr);
let serial = Serial(&*usart3);
serial.init(BAUD_RATE.invert(), afio, None, gpiob, rcc);
const BYTE: u8 = b'A';
assert!(serial.write(BYTE).is_ok());
for _ in 0..1_000 {
match serial.read() {
Ok(byte) => {
assert_eq!(byte, BYTE);
return;
}
Err(Error::Other(e)) => panic!("{:?}", e),
Err(Error::WouldBlock) => continue,
}
}
panic!("Timeout")
}
// IDLE LOOP
fn idle(_prio: P0, _thr: T0) ->! {
// OK
rtfm::bkpt();
// Sleep
loop {
rtfm::wfi();
}
}
// TASKS
tasks!(stm32f103xx, {}); | #[macro_use]
extern crate cortex_m_rtfm as rtfm;
extern crate nb; | random_line_split |
usart3.rs | //! Test the USART3 instance
//!
//! Connect the TX and RX pins to run this test
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
extern crate nb;
use blue_pill::{Serial, stm32f103xx};
use blue_pill::time::Hertz;
use hal::prelude::*;
use nb::Error;
use rtfm::{P0, T0, TMax};
// CONFIGURATION
pub const BAUD_RATE: Hertz = Hertz(115_200);
// RESOURCES
peripherals!(stm32f103xx, {
AFIO: Peripheral {
ceiling: C0,
},
GPIOB: Peripheral {
ceiling: C0,
},
RCC: Peripheral {
ceiling: C0,
},
USART3: Peripheral {
ceiling: C1,
},
});
// INITIALIZATION PHASE
fn init(ref prio: P0, thr: &TMax) {
let afio = &AFIO.access(prio, thr);
let gpiob = &GPIOB.access(prio, thr);
let rcc = &RCC.access(prio, thr);
let usart3 = USART3.access(prio, thr);
let serial = Serial(&*usart3);
serial.init(BAUD_RATE.invert(), afio, None, gpiob, rcc);
const BYTE: u8 = b'A';
assert!(serial.write(BYTE).is_ok());
for _ in 0..1_000 {
match serial.read() {
Ok(byte) => |
Err(Error::Other(e)) => panic!("{:?}", e),
Err(Error::WouldBlock) => continue,
}
}
panic!("Timeout")
}
// IDLE LOOP
fn idle(_prio: P0, _thr: T0) ->! {
// OK
rtfm::bkpt();
// Sleep
loop {
rtfm::wfi();
}
}
// TASKS
tasks!(stm32f103xx, {});
| {
assert_eq!(byte, BYTE);
return;
} | conditional_block |
errors.rs | use self::WhichLine::*;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
use std::str::FromStr;
use lazy_static::lazy_static;
use regex::Regex;
use tracing::*; |
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorKind {
Help,
Error,
Note,
Suggestion,
Warning,
}
impl FromStr for ErrorKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_uppercase();
let part0: &str = s.split(':').next().unwrap();
match part0 {
"HELP" => Ok(ErrorKind::Help),
"ERROR" => Ok(ErrorKind::Error),
"NOTE" => Ok(ErrorKind::Note),
"SUGGESTION" => Ok(ErrorKind::Suggestion),
"WARN" | "WARNING" => Ok(ErrorKind::Warning),
_ => Err(()),
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ErrorKind::Help => write!(f, "help message"),
ErrorKind::Error => write!(f, "error"),
ErrorKind::Note => write!(f, "note"),
ErrorKind::Suggestion => write!(f, "suggestion"),
ErrorKind::Warning => write!(f, "warning"),
}
}
}
#[derive(Debug)]
pub struct Error {
pub line_num: usize,
/// What kind of message we expect (e.g., warning, error, suggestion).
/// `None` if not specified or unknown message kind.
pub kind: Option<ErrorKind>,
pub msg: String,
}
#[derive(PartialEq, Debug)]
enum WhichLine {
ThisLine,
FollowPrevious(usize),
AdjustBackward(usize),
}
/// Looks for either "//~| KIND MESSAGE" or "//~^^... KIND MESSAGE"
/// The former is a "follow" that inherits its target from the preceding line;
/// the latter is an "adjusts" that goes that many lines up.
///
/// Goal is to enable tests both like: //~^^^ ERROR go up three
/// and also //~^ ERROR message one for the preceding line, and
/// //~| ERROR message two for that same line.
///
/// If cfg is not None (i.e., in an incremental test), then we look
/// for `//[X]~` instead, where `X` is the current `cfg`.
pub fn load_errors(testfile: &Path, cfg: Option<&str>) -> Vec<Error> {
let rdr = BufReader::new(File::open(testfile).unwrap());
// `last_nonfollow_error` tracks the most recently seen
// line with an error template that did not use the
// follow-syntax, "//~|...".
//
// (pnkfelix could not find an easy way to compose Iterator::scan
// and Iterator::filter_map to pass along this information into
// `parse_expected`. So instead I am storing that state here and
// updating it in the map callback below.)
let mut last_nonfollow_error = None;
rdr.lines()
.enumerate()
.filter_map(|(line_num, line)| {
parse_expected(last_nonfollow_error, line_num + 1, &line.unwrap(), cfg).map(
|(which, error)| {
match which {
FollowPrevious(_) => {}
_ => last_nonfollow_error = Some(error.line_num),
}
error
},
)
})
.collect()
}
fn parse_expected(
last_nonfollow_error: Option<usize>,
line_num: usize,
line: &str,
cfg: Option<&str>,
) -> Option<(WhichLine, Error)> {
// Matches comments like:
// //~
// //~|
// //~^
// //~^^^^^
// //[cfg1]~
// //[cfg1,cfg2]~^^
lazy_static! {
static ref RE: Regex =
Regex::new(r"//(?:\[(?P<cfgs>[\w,]+)])?~(?P<adjust>\||\^*)").unwrap();
}
let captures = RE.captures(line)?;
match (cfg, captures.name("cfgs")) {
// Only error messages that contain our `cfg` between the square brackets apply to us.
(Some(cfg), Some(filter)) if!filter.as_str().split(',').any(|s| s == cfg) => return None,
(Some(_), Some(_)) => {}
(None, Some(_)) => panic!("Only tests with revisions should use `//[X]~`"),
// If an error has no list of revisions, it applies to all revisions.
(Some(_), None) | (None, None) => {}
}
let (follow, adjusts) = match &captures["adjust"] {
"|" => (true, 0),
circumflexes => (false, circumflexes.len()),
};
// Get the part of the comment after the sigil (e.g. `~^^` or ~|).
let whole_match = captures.get(0).unwrap();
let (_, mut msg) = line.split_at(whole_match.end());
let first_word = msg.split_whitespace().next().expect("Encountered unexpected empty comment");
// If we find `//~ ERROR foo` or something like that, skip the first word.
let kind = first_word.parse::<ErrorKind>().ok();
if kind.is_some() {
msg = &msg.trim_start().split_at(first_word.len()).1;
}
let msg = msg.trim().to_owned();
let (which, line_num) = if follow {
assert_eq!(adjusts, 0, "use either //~| or //~^, not both.");
let line_num = last_nonfollow_error.expect(
"encountered //~| without \
preceding //~^ line.",
);
(FollowPrevious(line_num), line_num)
} else {
let which = if adjusts > 0 { AdjustBackward(adjusts) } else { ThisLine };
let line_num = line_num - adjusts;
(which, line_num)
};
debug!(
"line={} tag={:?} which={:?} kind={:?} msg={:?}",
line_num,
whole_match.as_str(),
which,
kind,
msg
);
Some((which, Error { line_num, kind, msg }))
} | random_line_split |
|
errors.rs | use self::WhichLine::*;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
use std::str::FromStr;
use lazy_static::lazy_static;
use regex::Regex;
use tracing::*;
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorKind {
Help,
Error,
Note,
Suggestion,
Warning,
}
impl FromStr for ErrorKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_uppercase();
let part0: &str = s.split(':').next().unwrap();
match part0 {
"HELP" => Ok(ErrorKind::Help),
"ERROR" => Ok(ErrorKind::Error),
"NOTE" => Ok(ErrorKind::Note),
"SUGGESTION" => Ok(ErrorKind::Suggestion),
"WARN" | "WARNING" => Ok(ErrorKind::Warning),
_ => Err(()),
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ErrorKind::Help => write!(f, "help message"),
ErrorKind::Error => write!(f, "error"),
ErrorKind::Note => write!(f, "note"),
ErrorKind::Suggestion => write!(f, "suggestion"),
ErrorKind::Warning => write!(f, "warning"),
}
}
}
#[derive(Debug)]
pub struct Error {
pub line_num: usize,
/// What kind of message we expect (e.g., warning, error, suggestion).
/// `None` if not specified or unknown message kind.
pub kind: Option<ErrorKind>,
pub msg: String,
}
#[derive(PartialEq, Debug)]
enum WhichLine {
ThisLine,
FollowPrevious(usize),
AdjustBackward(usize),
}
/// Looks for either "//~| KIND MESSAGE" or "//~^^... KIND MESSAGE"
/// The former is a "follow" that inherits its target from the preceding line;
/// the latter is an "adjusts" that goes that many lines up.
///
/// Goal is to enable tests both like: //~^^^ ERROR go up three
/// and also //~^ ERROR message one for the preceding line, and
/// //~| ERROR message two for that same line.
///
/// If cfg is not None (i.e., in an incremental test), then we look
/// for `//[X]~` instead, where `X` is the current `cfg`.
pub fn | (testfile: &Path, cfg: Option<&str>) -> Vec<Error> {
let rdr = BufReader::new(File::open(testfile).unwrap());
// `last_nonfollow_error` tracks the most recently seen
// line with an error template that did not use the
// follow-syntax, "//~|...".
//
// (pnkfelix could not find an easy way to compose Iterator::scan
// and Iterator::filter_map to pass along this information into
// `parse_expected`. So instead I am storing that state here and
// updating it in the map callback below.)
let mut last_nonfollow_error = None;
rdr.lines()
.enumerate()
.filter_map(|(line_num, line)| {
parse_expected(last_nonfollow_error, line_num + 1, &line.unwrap(), cfg).map(
|(which, error)| {
match which {
FollowPrevious(_) => {}
_ => last_nonfollow_error = Some(error.line_num),
}
error
},
)
})
.collect()
}
fn parse_expected(
last_nonfollow_error: Option<usize>,
line_num: usize,
line: &str,
cfg: Option<&str>,
) -> Option<(WhichLine, Error)> {
// Matches comments like:
// //~
// //~|
// //~^
// //~^^^^^
// //[cfg1]~
// //[cfg1,cfg2]~^^
lazy_static! {
static ref RE: Regex =
Regex::new(r"//(?:\[(?P<cfgs>[\w,]+)])?~(?P<adjust>\||\^*)").unwrap();
}
let captures = RE.captures(line)?;
match (cfg, captures.name("cfgs")) {
// Only error messages that contain our `cfg` between the square brackets apply to us.
(Some(cfg), Some(filter)) if!filter.as_str().split(',').any(|s| s == cfg) => return None,
(Some(_), Some(_)) => {}
(None, Some(_)) => panic!("Only tests with revisions should use `//[X]~`"),
// If an error has no list of revisions, it applies to all revisions.
(Some(_), None) | (None, None) => {}
}
let (follow, adjusts) = match &captures["adjust"] {
"|" => (true, 0),
circumflexes => (false, circumflexes.len()),
};
// Get the part of the comment after the sigil (e.g. `~^^` or ~|).
let whole_match = captures.get(0).unwrap();
let (_, mut msg) = line.split_at(whole_match.end());
let first_word = msg.split_whitespace().next().expect("Encountered unexpected empty comment");
// If we find `//~ ERROR foo` or something like that, skip the first word.
let kind = first_word.parse::<ErrorKind>().ok();
if kind.is_some() {
msg = &msg.trim_start().split_at(first_word.len()).1;
}
let msg = msg.trim().to_owned();
let (which, line_num) = if follow {
assert_eq!(adjusts, 0, "use either //~| or //~^, not both.");
let line_num = last_nonfollow_error.expect(
"encountered //~| without \
preceding //~^ line.",
);
(FollowPrevious(line_num), line_num)
} else {
let which = if adjusts > 0 { AdjustBackward(adjusts) } else { ThisLine };
let line_num = line_num - adjusts;
(which, line_num)
};
debug!(
"line={} tag={:?} which={:?} kind={:?} msg={:?}",
line_num,
whole_match.as_str(),
which,
kind,
msg
);
Some((which, Error { line_num, kind, msg }))
}
| load_errors | identifier_name |
errors.rs | use self::WhichLine::*;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
use std::str::FromStr;
use lazy_static::lazy_static;
use regex::Regex;
use tracing::*;
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorKind {
Help,
Error,
Note,
Suggestion,
Warning,
}
impl FromStr for ErrorKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_uppercase();
let part0: &str = s.split(':').next().unwrap();
match part0 {
"HELP" => Ok(ErrorKind::Help),
"ERROR" => Ok(ErrorKind::Error),
"NOTE" => Ok(ErrorKind::Note),
"SUGGESTION" => Ok(ErrorKind::Suggestion),
"WARN" | "WARNING" => Ok(ErrorKind::Warning),
_ => Err(()),
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ErrorKind::Help => write!(f, "help message"),
ErrorKind::Error => write!(f, "error"),
ErrorKind::Note => write!(f, "note"),
ErrorKind::Suggestion => write!(f, "suggestion"),
ErrorKind::Warning => write!(f, "warning"),
}
}
}
#[derive(Debug)]
pub struct Error {
pub line_num: usize,
/// What kind of message we expect (e.g., warning, error, suggestion).
/// `None` if not specified or unknown message kind.
pub kind: Option<ErrorKind>,
pub msg: String,
}
#[derive(PartialEq, Debug)]
enum WhichLine {
ThisLine,
FollowPrevious(usize),
AdjustBackward(usize),
}
/// Looks for either "//~| KIND MESSAGE" or "//~^^... KIND MESSAGE"
/// The former is a "follow" that inherits its target from the preceding line;
/// the latter is an "adjusts" that goes that many lines up.
///
/// Goal is to enable tests both like: //~^^^ ERROR go up three
/// and also //~^ ERROR message one for the preceding line, and
/// //~| ERROR message two for that same line.
///
/// If cfg is not None (i.e., in an incremental test), then we look
/// for `//[X]~` instead, where `X` is the current `cfg`.
pub fn load_errors(testfile: &Path, cfg: Option<&str>) -> Vec<Error> {
let rdr = BufReader::new(File::open(testfile).unwrap());
// `last_nonfollow_error` tracks the most recently seen
// line with an error template that did not use the
// follow-syntax, "//~|...".
//
// (pnkfelix could not find an easy way to compose Iterator::scan
// and Iterator::filter_map to pass along this information into
// `parse_expected`. So instead I am storing that state here and
// updating it in the map callback below.)
let mut last_nonfollow_error = None;
rdr.lines()
.enumerate()
.filter_map(|(line_num, line)| {
parse_expected(last_nonfollow_error, line_num + 1, &line.unwrap(), cfg).map(
|(which, error)| {
match which {
FollowPrevious(_) => {}
_ => last_nonfollow_error = Some(error.line_num),
}
error
},
)
})
.collect()
}
fn parse_expected(
last_nonfollow_error: Option<usize>,
line_num: usize,
line: &str,
cfg: Option<&str>,
) -> Option<(WhichLine, Error)> | (None, Some(_)) => panic!("Only tests with revisions should use `//[X]~`"),
// If an error has no list of revisions, it applies to all revisions.
(Some(_), None) | (None, None) => {}
}
let (follow, adjusts) = match &captures["adjust"] {
"|" => (true, 0),
circumflexes => (false, circumflexes.len()),
};
// Get the part of the comment after the sigil (e.g. `~^^` or ~|).
let whole_match = captures.get(0).unwrap();
let (_, mut msg) = line.split_at(whole_match.end());
let first_word = msg.split_whitespace().next().expect("Encountered unexpected empty comment");
// If we find `//~ ERROR foo` or something like that, skip the first word.
let kind = first_word.parse::<ErrorKind>().ok();
if kind.is_some() {
msg = &msg.trim_start().split_at(first_word.len()).1;
}
let msg = msg.trim().to_owned();
let (which, line_num) = if follow {
assert_eq!(adjusts, 0, "use either //~| or //~^, not both.");
let line_num = last_nonfollow_error.expect(
"encountered //~| without \
preceding //~^ line.",
);
(FollowPrevious(line_num), line_num)
} else {
let which = if adjusts > 0 { AdjustBackward(adjusts) } else { ThisLine };
let line_num = line_num - adjusts;
(which, line_num)
};
debug!(
"line={} tag={:?} which={:?} kind={:?} msg={:?}",
line_num,
whole_match.as_str(),
which,
kind,
msg
);
Some((which, Error { line_num, kind, msg }))
}
| {
// Matches comments like:
// //~
// //~|
// //~^
// //~^^^^^
// //[cfg1]~
// //[cfg1,cfg2]~^^
lazy_static! {
static ref RE: Regex =
Regex::new(r"//(?:\[(?P<cfgs>[\w,]+)])?~(?P<adjust>\||\^*)").unwrap();
}
let captures = RE.captures(line)?;
match (cfg, captures.name("cfgs")) {
// Only error messages that contain our `cfg` between the square brackets apply to us.
(Some(cfg), Some(filter)) if !filter.as_str().split(',').any(|s| s == cfg) => return None,
(Some(_), Some(_)) => {}
| identifier_body |
errors.rs | use self::WhichLine::*;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
use std::str::FromStr;
use lazy_static::lazy_static;
use regex::Regex;
use tracing::*;
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorKind {
Help,
Error,
Note,
Suggestion,
Warning,
}
impl FromStr for ErrorKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_uppercase();
let part0: &str = s.split(':').next().unwrap();
match part0 {
"HELP" => Ok(ErrorKind::Help),
"ERROR" => Ok(ErrorKind::Error),
"NOTE" => Ok(ErrorKind::Note),
"SUGGESTION" => Ok(ErrorKind::Suggestion),
"WARN" | "WARNING" => Ok(ErrorKind::Warning),
_ => Err(()),
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ErrorKind::Help => write!(f, "help message"),
ErrorKind::Error => write!(f, "error"),
ErrorKind::Note => write!(f, "note"),
ErrorKind::Suggestion => write!(f, "suggestion"),
ErrorKind::Warning => write!(f, "warning"),
}
}
}
#[derive(Debug)]
pub struct Error {
pub line_num: usize,
/// What kind of message we expect (e.g., warning, error, suggestion).
/// `None` if not specified or unknown message kind.
pub kind: Option<ErrorKind>,
pub msg: String,
}
#[derive(PartialEq, Debug)]
enum WhichLine {
ThisLine,
FollowPrevious(usize),
AdjustBackward(usize),
}
/// Looks for either "//~| KIND MESSAGE" or "//~^^... KIND MESSAGE"
/// The former is a "follow" that inherits its target from the preceding line;
/// the latter is an "adjusts" that goes that many lines up.
///
/// Goal is to enable tests both like: //~^^^ ERROR go up three
/// and also //~^ ERROR message one for the preceding line, and
/// //~| ERROR message two for that same line.
///
/// If cfg is not None (i.e., in an incremental test), then we look
/// for `//[X]~` instead, where `X` is the current `cfg`.
pub fn load_errors(testfile: &Path, cfg: Option<&str>) -> Vec<Error> {
let rdr = BufReader::new(File::open(testfile).unwrap());
// `last_nonfollow_error` tracks the most recently seen
// line with an error template that did not use the
// follow-syntax, "//~|...".
//
// (pnkfelix could not find an easy way to compose Iterator::scan
// and Iterator::filter_map to pass along this information into
// `parse_expected`. So instead I am storing that state here and
// updating it in the map callback below.)
let mut last_nonfollow_error = None;
rdr.lines()
.enumerate()
.filter_map(|(line_num, line)| {
parse_expected(last_nonfollow_error, line_num + 1, &line.unwrap(), cfg).map(
|(which, error)| {
match which {
FollowPrevious(_) => {}
_ => last_nonfollow_error = Some(error.line_num),
}
error
},
)
})
.collect()
}
fn parse_expected(
last_nonfollow_error: Option<usize>,
line_num: usize,
line: &str,
cfg: Option<&str>,
) -> Option<(WhichLine, Error)> {
// Matches comments like:
// //~
// //~|
// //~^
// //~^^^^^
// //[cfg1]~
// //[cfg1,cfg2]~^^
lazy_static! {
static ref RE: Regex =
Regex::new(r"//(?:\[(?P<cfgs>[\w,]+)])?~(?P<adjust>\||\^*)").unwrap();
}
let captures = RE.captures(line)?;
match (cfg, captures.name("cfgs")) {
// Only error messages that contain our `cfg` between the square brackets apply to us.
(Some(cfg), Some(filter)) if!filter.as_str().split(',').any(|s| s == cfg) => return None,
(Some(_), Some(_)) => {}
(None, Some(_)) => panic!("Only tests with revisions should use `//[X]~`"),
// If an error has no list of revisions, it applies to all revisions.
(Some(_), None) | (None, None) => {}
}
let (follow, adjusts) = match &captures["adjust"] {
"|" => (true, 0),
circumflexes => (false, circumflexes.len()),
};
// Get the part of the comment after the sigil (e.g. `~^^` or ~|).
let whole_match = captures.get(0).unwrap();
let (_, mut msg) = line.split_at(whole_match.end());
let first_word = msg.split_whitespace().next().expect("Encountered unexpected empty comment");
// If we find `//~ ERROR foo` or something like that, skip the first word.
let kind = first_word.parse::<ErrorKind>().ok();
if kind.is_some() {
msg = &msg.trim_start().split_at(first_word.len()).1;
}
let msg = msg.trim().to_owned();
let (which, line_num) = if follow {
assert_eq!(adjusts, 0, "use either //~| or //~^, not both.");
let line_num = last_nonfollow_error.expect(
"encountered //~| without \
preceding //~^ line.",
);
(FollowPrevious(line_num), line_num)
} else {
let which = if adjusts > 0 | else { ThisLine };
let line_num = line_num - adjusts;
(which, line_num)
};
debug!(
"line={} tag={:?} which={:?} kind={:?} msg={:?}",
line_num,
whole_match.as_str(),
which,
kind,
msg
);
Some((which, Error { line_num, kind, msg }))
}
| { AdjustBackward(adjusts) } | conditional_block |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
use servo_config::opts;
use signpost;
#[derive(PartialEq, Clone, PartialOrd, Eq, Ord, Debug, Deserialize, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
if let Err(e) = self.0.send(msg) {
warn!("Error communicating with the time profiler thread: {}", e);
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(PartialEq, Clone, Copy, PartialOrd, Eq, Ord, Deserialize, Serialize, Debug, Hash)]
pub enum ProfilerCategory {
Compositing = 0x00,
LayoutPerform = 0x10,
LayoutStyleRecalc = 0x11,
LayoutTextShaping = 0x12,
LayoutRestyleDamagePropagation = 0x13,
LayoutNonIncrementalReset = 0x14,
LayoutSelectorMatch = 0x15,
LayoutTreeBuilder = 0x16,
LayoutDamagePropagate = 0x17,
LayoutGeneratedContent = 0x18,
LayoutDisplayListSorting = 0x19,
LayoutFloatPlacementSpeculation = 0x1a,
LayoutMain = 0x1b,
LayoutStoreOverflow = 0x1c,
LayoutParallelWarmup = 0x1d,
LayoutDispListBuild = 0x1e,
NetHTTPRequestResponse = 0x30,
PaintingPerTile = 0x41,
PaintingPrepBuff = 0x42,
Painting = 0x43,
ImageDecoding = 0x50,
ImageSaving = 0x51,
ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0x6a,
ScriptParseHTML = 0x6b,
ScriptPlannedNavigation = 0x6c,
ScriptResize = 0x6d,
ScriptSetScrollState = 0x6e,
ScriptSetViewport = 0x6f,
ScriptTimerEvent = 0x70,
ScriptStylesheetLoad = 0x71,
ScriptUpdateReplacedElement = 0x72,
ScriptWebSocketEvent = 0x73,
ScriptWorkerEvent = 0x74,
ScriptServiceWorkerEvent = 0x75,
ScriptParseXML = 0x76,
ScriptEnterFullscreen = 0x77,
ScriptExitFullscreen = 0x78,
ApplicationHeartbeat = 0x90,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T
{
if opts::get().signpost {
signpost::start(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
| let end_time = precise_time_ns();
let end_energy = read_energy_uj();
if opts::get().signpost {
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
send_profile_data(category,
meta,
profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
} | let val = callback();
| random_line_split |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
use servo_config::opts;
use signpost;
#[derive(PartialEq, Clone, PartialOrd, Eq, Ord, Debug, Deserialize, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct | (pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
if let Err(e) = self.0.send(msg) {
warn!("Error communicating with the time profiler thread: {}", e);
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(PartialEq, Clone, Copy, PartialOrd, Eq, Ord, Deserialize, Serialize, Debug, Hash)]
pub enum ProfilerCategory {
Compositing = 0x00,
LayoutPerform = 0x10,
LayoutStyleRecalc = 0x11,
LayoutTextShaping = 0x12,
LayoutRestyleDamagePropagation = 0x13,
LayoutNonIncrementalReset = 0x14,
LayoutSelectorMatch = 0x15,
LayoutTreeBuilder = 0x16,
LayoutDamagePropagate = 0x17,
LayoutGeneratedContent = 0x18,
LayoutDisplayListSorting = 0x19,
LayoutFloatPlacementSpeculation = 0x1a,
LayoutMain = 0x1b,
LayoutStoreOverflow = 0x1c,
LayoutParallelWarmup = 0x1d,
LayoutDispListBuild = 0x1e,
NetHTTPRequestResponse = 0x30,
PaintingPerTile = 0x41,
PaintingPrepBuff = 0x42,
Painting = 0x43,
ImageDecoding = 0x50,
ImageSaving = 0x51,
ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0x6a,
ScriptParseHTML = 0x6b,
ScriptPlannedNavigation = 0x6c,
ScriptResize = 0x6d,
ScriptSetScrollState = 0x6e,
ScriptSetViewport = 0x6f,
ScriptTimerEvent = 0x70,
ScriptStylesheetLoad = 0x71,
ScriptUpdateReplacedElement = 0x72,
ScriptWebSocketEvent = 0x73,
ScriptWorkerEvent = 0x74,
ScriptServiceWorkerEvent = 0x75,
ScriptParseXML = 0x76,
ScriptEnterFullscreen = 0x77,
ScriptExitFullscreen = 0x78,
ApplicationHeartbeat = 0x90,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T
{
if opts::get().signpost {
signpost::start(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
if opts::get().signpost {
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
send_profile_data(category,
meta,
profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
| ProfilerChan | identifier_name |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
use servo_config::opts;
use signpost;
#[derive(PartialEq, Clone, PartialOrd, Eq, Ord, Debug, Deserialize, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
if let Err(e) = self.0.send(msg) {
warn!("Error communicating with the time profiler thread: {}", e);
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(PartialEq, Clone, Copy, PartialOrd, Eq, Ord, Deserialize, Serialize, Debug, Hash)]
pub enum ProfilerCategory {
Compositing = 0x00,
LayoutPerform = 0x10,
LayoutStyleRecalc = 0x11,
LayoutTextShaping = 0x12,
LayoutRestyleDamagePropagation = 0x13,
LayoutNonIncrementalReset = 0x14,
LayoutSelectorMatch = 0x15,
LayoutTreeBuilder = 0x16,
LayoutDamagePropagate = 0x17,
LayoutGeneratedContent = 0x18,
LayoutDisplayListSorting = 0x19,
LayoutFloatPlacementSpeculation = 0x1a,
LayoutMain = 0x1b,
LayoutStoreOverflow = 0x1c,
LayoutParallelWarmup = 0x1d,
LayoutDispListBuild = 0x1e,
NetHTTPRequestResponse = 0x30,
PaintingPerTile = 0x41,
PaintingPrepBuff = 0x42,
Painting = 0x43,
ImageDecoding = 0x50,
ImageSaving = 0x51,
ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0x6a,
ScriptParseHTML = 0x6b,
ScriptPlannedNavigation = 0x6c,
ScriptResize = 0x6d,
ScriptSetScrollState = 0x6e,
ScriptSetViewport = 0x6f,
ScriptTimerEvent = 0x70,
ScriptStylesheetLoad = 0x71,
ScriptUpdateReplacedElement = 0x72,
ScriptWebSocketEvent = 0x73,
ScriptWorkerEvent = 0x74,
ScriptServiceWorkerEvent = 0x75,
ScriptParseXML = 0x76,
ScriptEnterFullscreen = 0x77,
ScriptExitFullscreen = 0x78,
ApplicationHeartbeat = 0x90,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T
{
if opts::get().signpost {
signpost::start(category as u32, &[0, 0, 0, (category as usize) >> 4]);
}
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
if opts::get().signpost |
send_profile_data(category,
meta,
profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
| {
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
} | conditional_block |
config.rs | use std::io::{Read};
use std::rc::Rc;
use std::fs::File;
use std::path::{PathBuf, Path, Component};
use std::collections::BTreeMap;
use rustc_serialize::{Decoder};
use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config};
use quire::validate as V;
use quire::parser::{parse as parse_yaml};
use quire::ast::{Ast, process as process_ast};
use super::containers;
use super::containers::Container;
use super::command::{MainCommand, command_validator};
use super::range::Range;
use super::validate::validate_config;
use super::version::MinimumVagga;
#[derive(RustcDecodable)]
pub struct Config {
pub minimum_vagga: Option<String>,
pub commands: BTreeMap<String, MainCommand>,
pub containers: BTreeMap<String, Container>,
}
impl Config {
pub fn get_container(&self, name: &str) -> Result<&Container, String> {
self.containers.get(name)
.ok_or_else(|| format!("Container {:?} not found", name))
}
}
pub fn | <'a>() -> V::Structure<'a> {
V::Structure::new()
.member("minimum_vagga", MinimumVagga::new()
.optional()
.current_version(env!("VAGGA_VERSION").to_string()))
.member("containers", V::Mapping::new(
V::Scalar::new(),
containers::container_validator()))
.member("commands", V::Mapping::new(
V::Scalar::new(),
command_validator()))
}
fn find_config_path(work_dir: &PathBuf, show_warnings: bool)
-> Option<(PathBuf, PathBuf)>
{
let mut dir = work_dir.clone();
loop {
if show_warnings {
maybe_print_typo_warning(&dir.join(".vagga"));
maybe_print_typo_warning(&dir);
}
let fname = dir.join(".vagga/vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
let fname = dir.join("vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
if!dir.pop() {
return None;
}
}
}
pub fn find_config(work_dir: &PathBuf, show_warnings: bool)
-> Result<(Config, PathBuf), String>
{
let (cfg_dir, filename) = match find_config_path(
work_dir, show_warnings)
{
Some(pair) => pair,
None => return Err(format!(
"Config not found in path {:?}", work_dir)),
};
assert!(cfg_dir.is_absolute());
let cfg = try!(read_config(&filename));
try!(validate_config(&cfg));
return Ok((cfg, cfg_dir));
}
fn include_file(pos: &Pos, include: &Include,
err: &ErrorCollector, options: &Options)
-> Ast
{
match *include {
Include::File { filename } => {
let mut path = PathBuf::from(&*pos.filename);
path.pop(); // pop original filename
for component in Path::new(filename).components() {
match component {
Component::Normal(x) => path.push(x),
_ => {
err.add_error(Error::preprocess_error(pos,
format!("Only relative paths without parent \
directories can be included")));
return Ast::void(pos);
}
}
}
debug!("{} Including {:?}", pos, path);
let mut body = String::new();
File::open(&path)
.and_then(|mut f| f.read_to_string(&mut body))
.map_err(|e| err.add_error(Error::OpenError(path.clone(), e))).ok()
.and_then(|_| {
parse_yaml(Rc::new(path.display().to_string()), &body,
|doc| { process_ast(&options, doc, err) },
).map_err(|e| err.add_error(e)).ok()
})
.unwrap_or_else(|| Ast::void(pos))
}
}
}
pub fn read_config(filename: &Path) -> Result<Config, String> {
let mut opt = Options::default();
opt.allow_include(include_file);
let mut config: Config = try!(
parse_config(filename, &config_validator(), &opt)
.map_err(|e| format!("{}", e)));
for (_, ref mut container) in config.containers.iter_mut() {
if container.uids.len() == 0 {
container.uids.push(Range::new(0, 65535));
}
if container.gids.len() == 0 {
container.gids.push(Range::new(0, 65535));
}
}
return Ok(config);
}
fn maybe_print_typo_warning(dir: &Path) {
if dir.join("vagga.yml").exists() {
warn!("There is vagga.yml file in the {:?}, \
possibly it is a typo. \
Correct configuration file name is vagga.yaml",
dir);
}
}
| config_validator | identifier_name |
config.rs | use std::io::{Read};
use std::rc::Rc;
use std::fs::File;
use std::path::{PathBuf, Path, Component};
use std::collections::BTreeMap;
use rustc_serialize::{Decoder};
use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config};
use quire::validate as V;
use quire::parser::{parse as parse_yaml};
use quire::ast::{Ast, process as process_ast};
use super::containers;
use super::containers::Container;
use super::command::{MainCommand, command_validator};
use super::range::Range;
use super::validate::validate_config;
use super::version::MinimumVagga;
#[derive(RustcDecodable)]
pub struct Config {
pub minimum_vagga: Option<String>,
pub commands: BTreeMap<String, MainCommand>,
pub containers: BTreeMap<String, Container>,
}
impl Config {
pub fn get_container(&self, name: &str) -> Result<&Container, String> {
self.containers.get(name)
.ok_or_else(|| format!("Container {:?} not found", name))
}
}
pub fn config_validator<'a>() -> V::Structure<'a> {
V::Structure::new()
.member("minimum_vagga", MinimumVagga::new()
.optional()
.current_version(env!("VAGGA_VERSION").to_string()))
.member("containers", V::Mapping::new(
V::Scalar::new(),
containers::container_validator()))
.member("commands", V::Mapping::new(
V::Scalar::new(),
command_validator()))
}
fn find_config_path(work_dir: &PathBuf, show_warnings: bool)
-> Option<(PathBuf, PathBuf)>
{
let mut dir = work_dir.clone();
loop {
if show_warnings {
maybe_print_typo_warning(&dir.join(".vagga"));
maybe_print_typo_warning(&dir);
}
let fname = dir.join(".vagga/vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
let fname = dir.join("vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
if!dir.pop() {
return None;
}
}
}
pub fn find_config(work_dir: &PathBuf, show_warnings: bool)
-> Result<(Config, PathBuf), String>
{
let (cfg_dir, filename) = match find_config_path(
work_dir, show_warnings)
{
Some(pair) => pair,
None => return Err(format!(
"Config not found in path {:?}", work_dir)),
};
assert!(cfg_dir.is_absolute());
let cfg = try!(read_config(&filename));
try!(validate_config(&cfg));
return Ok((cfg, cfg_dir));
}
fn include_file(pos: &Pos, include: &Include,
err: &ErrorCollector, options: &Options)
-> Ast
{
match *include {
Include::File { filename } => | .map_err(|e| err.add_error(Error::OpenError(path.clone(), e))).ok()
.and_then(|_| {
parse_yaml(Rc::new(path.display().to_string()), &body,
|doc| { process_ast(&options, doc, err) },
).map_err(|e| err.add_error(e)).ok()
})
.unwrap_or_else(|| Ast::void(pos))
}
}
}
pub fn read_config(filename: &Path) -> Result<Config, String> {
let mut opt = Options::default();
opt.allow_include(include_file);
let mut config: Config = try!(
parse_config(filename, &config_validator(), &opt)
.map_err(|e| format!("{}", e)));
for (_, ref mut container) in config.containers.iter_mut() {
if container.uids.len() == 0 {
container.uids.push(Range::new(0, 65535));
}
if container.gids.len() == 0 {
container.gids.push(Range::new(0, 65535));
}
}
return Ok(config);
}
fn maybe_print_typo_warning(dir: &Path) {
if dir.join("vagga.yml").exists() {
warn!("There is vagga.yml file in the {:?}, \
possibly it is a typo. \
Correct configuration file name is vagga.yaml",
dir);
}
}
| {
let mut path = PathBuf::from(&*pos.filename);
path.pop(); // pop original filename
for component in Path::new(filename).components() {
match component {
Component::Normal(x) => path.push(x),
_ => {
err.add_error(Error::preprocess_error(pos,
format!("Only relative paths without parent \
directories can be included")));
return Ast::void(pos);
}
}
}
debug!("{} Including {:?}", pos, path);
let mut body = String::new();
File::open(&path)
.and_then(|mut f| f.read_to_string(&mut body)) | conditional_block |
config.rs | use std::io::{Read};
use std::rc::Rc;
use std::fs::File;
use std::path::{PathBuf, Path, Component};
use std::collections::BTreeMap;
use rustc_serialize::{Decoder};
use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config};
use quire::validate as V;
use quire::parser::{parse as parse_yaml};
use quire::ast::{Ast, process as process_ast};
use super::containers;
use super::containers::Container;
use super::command::{MainCommand, command_validator};
use super::range::Range;
use super::validate::validate_config;
use super::version::MinimumVagga;
#[derive(RustcDecodable)]
pub struct Config {
pub minimum_vagga: Option<String>,
pub commands: BTreeMap<String, MainCommand>,
pub containers: BTreeMap<String, Container>,
}
impl Config {
pub fn get_container(&self, name: &str) -> Result<&Container, String> {
self.containers.get(name)
.ok_or_else(|| format!("Container {:?} not found", name))
}
}
pub fn config_validator<'a>() -> V::Structure<'a> {
V::Structure::new()
.member("minimum_vagga", MinimumVagga::new()
.optional()
.current_version(env!("VAGGA_VERSION").to_string()))
.member("containers", V::Mapping::new(
V::Scalar::new(),
containers::container_validator()))
.member("commands", V::Mapping::new(
V::Scalar::new(),
command_validator()))
}
fn find_config_path(work_dir: &PathBuf, show_warnings: bool)
-> Option<(PathBuf, PathBuf)>
{
let mut dir = work_dir.clone();
loop {
if show_warnings {
maybe_print_typo_warning(&dir.join(".vagga"));
maybe_print_typo_warning(&dir);
}
let fname = dir.join(".vagga/vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
let fname = dir.join("vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
if!dir.pop() {
return None;
}
}
}
pub fn find_config(work_dir: &PathBuf, show_warnings: bool)
-> Result<(Config, PathBuf), String>
{
let (cfg_dir, filename) = match find_config_path(
work_dir, show_warnings)
{
Some(pair) => pair,
None => return Err(format!(
"Config not found in path {:?}", work_dir)),
};
assert!(cfg_dir.is_absolute());
let cfg = try!(read_config(&filename));
try!(validate_config(&cfg));
return Ok((cfg, cfg_dir));
}
fn include_file(pos: &Pos, include: &Include,
err: &ErrorCollector, options: &Options)
-> Ast
{
match *include {
Include::File { filename } => {
let mut path = PathBuf::from(&*pos.filename);
path.pop(); // pop original filename
for component in Path::new(filename).components() {
match component {
Component::Normal(x) => path.push(x),
_ => {
err.add_error(Error::preprocess_error(pos,
format!("Only relative paths without parent \
directories can be included")));
return Ast::void(pos);
}
}
}
debug!("{} Including {:?}", pos, path);
let mut body = String::new();
File::open(&path)
.and_then(|mut f| f.read_to_string(&mut body))
.map_err(|e| err.add_error(Error::OpenError(path.clone(), e))).ok()
.and_then(|_| {
parse_yaml(Rc::new(path.display().to_string()), &body,
|doc| { process_ast(&options, doc, err) },
).map_err(|e| err.add_error(e)).ok()
})
.unwrap_or_else(|| Ast::void(pos))
}
}
}
pub fn read_config(filename: &Path) -> Result<Config, String> {
let mut opt = Options::default();
opt.allow_include(include_file);
let mut config: Config = try!(
parse_config(filename, &config_validator(), &opt)
.map_err(|e| format!("{}", e)));
for (_, ref mut container) in config.containers.iter_mut() {
if container.uids.len() == 0 {
container.uids.push(Range::new(0, 65535));
}
if container.gids.len() == 0 {
container.gids.push(Range::new(0, 65535));
}
}
return Ok(config); | warn!("There is vagga.yml file in the {:?}, \
possibly it is a typo. \
Correct configuration file name is vagga.yaml",
dir);
}
} | }
fn maybe_print_typo_warning(dir: &Path) {
if dir.join("vagga.yml").exists() { | random_line_split |
config.rs | use std::io::{Read};
use std::rc::Rc;
use std::fs::File;
use std::path::{PathBuf, Path, Component};
use std::collections::BTreeMap;
use rustc_serialize::{Decoder};
use quire::{Options, Include, Error, ErrorCollector, Pos, parse_config};
use quire::validate as V;
use quire::parser::{parse as parse_yaml};
use quire::ast::{Ast, process as process_ast};
use super::containers;
use super::containers::Container;
use super::command::{MainCommand, command_validator};
use super::range::Range;
use super::validate::validate_config;
use super::version::MinimumVagga;
#[derive(RustcDecodable)]
pub struct Config {
pub minimum_vagga: Option<String>,
pub commands: BTreeMap<String, MainCommand>,
pub containers: BTreeMap<String, Container>,
}
impl Config {
pub fn get_container(&self, name: &str) -> Result<&Container, String> {
self.containers.get(name)
.ok_or_else(|| format!("Container {:?} not found", name))
}
}
pub fn config_validator<'a>() -> V::Structure<'a> {
V::Structure::new()
.member("minimum_vagga", MinimumVagga::new()
.optional()
.current_version(env!("VAGGA_VERSION").to_string()))
.member("containers", V::Mapping::new(
V::Scalar::new(),
containers::container_validator()))
.member("commands", V::Mapping::new(
V::Scalar::new(),
command_validator()))
}
fn find_config_path(work_dir: &PathBuf, show_warnings: bool)
-> Option<(PathBuf, PathBuf)>
{
let mut dir = work_dir.clone();
loop {
if show_warnings {
maybe_print_typo_warning(&dir.join(".vagga"));
maybe_print_typo_warning(&dir);
}
let fname = dir.join(".vagga/vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
let fname = dir.join("vagga.yaml");
if fname.exists() {
return Some((dir, fname));
}
if!dir.pop() {
return None;
}
}
}
pub fn find_config(work_dir: &PathBuf, show_warnings: bool)
-> Result<(Config, PathBuf), String>
{
let (cfg_dir, filename) = match find_config_path(
work_dir, show_warnings)
{
Some(pair) => pair,
None => return Err(format!(
"Config not found in path {:?}", work_dir)),
};
assert!(cfg_dir.is_absolute());
let cfg = try!(read_config(&filename));
try!(validate_config(&cfg));
return Ok((cfg, cfg_dir));
}
fn include_file(pos: &Pos, include: &Include,
err: &ErrorCollector, options: &Options)
-> Ast
{
match *include {
Include::File { filename } => {
let mut path = PathBuf::from(&*pos.filename);
path.pop(); // pop original filename
for component in Path::new(filename).components() {
match component {
Component::Normal(x) => path.push(x),
_ => {
err.add_error(Error::preprocess_error(pos,
format!("Only relative paths without parent \
directories can be included")));
return Ast::void(pos);
}
}
}
debug!("{} Including {:?}", pos, path);
let mut body = String::new();
File::open(&path)
.and_then(|mut f| f.read_to_string(&mut body))
.map_err(|e| err.add_error(Error::OpenError(path.clone(), e))).ok()
.and_then(|_| {
parse_yaml(Rc::new(path.display().to_string()), &body,
|doc| { process_ast(&options, doc, err) },
).map_err(|e| err.add_error(e)).ok()
})
.unwrap_or_else(|| Ast::void(pos))
}
}
}
pub fn read_config(filename: &Path) -> Result<Config, String> {
let mut opt = Options::default();
opt.allow_include(include_file);
let mut config: Config = try!(
parse_config(filename, &config_validator(), &opt)
.map_err(|e| format!("{}", e)));
for (_, ref mut container) in config.containers.iter_mut() {
if container.uids.len() == 0 {
container.uids.push(Range::new(0, 65535));
}
if container.gids.len() == 0 {
container.gids.push(Range::new(0, 65535));
}
}
return Ok(config);
}
fn maybe_print_typo_warning(dir: &Path) | {
if dir.join("vagga.yml").exists() {
warn!("There is vagga.yml file in the {:?}, \
possibly it is a typo. \
Correct configuration file name is vagga.yaml",
dir);
}
} | identifier_body |
|
oscsictrl.rs | #[doc = "Register `OSCSICTRL` reader"]
pub struct R(crate::R<OSCSICTRL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<OSCSICTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<OSCSICTRL_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<OSCSICTRL_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `OSCSICTRL` writer"]
pub struct W(crate::W<OSCSICTRL_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<OSCSICTRL_SPEC>;
#[inline(always)]
fn | (&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<OSCSICTRL_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<OSCSICTRL_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Turn OFF the fOSI Clock Source\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWD_A {
#[doc = "0: Enabled"]
VALUE1 = 0,
#[doc = "1: Disabled"]
VALUE2 = 1,
}
impl From<PWD_A> for bool {
#[inline(always)]
fn from(variant: PWD_A) -> Self {
variant as u8!= 0
}
}
#[doc = "Field `PWD` reader - Turn OFF the fOSI Clock Source"]
pub struct PWD_R(crate::FieldReader<bool, PWD_A>);
impl PWD_R {
pub(crate) fn new(bits: bool) -> Self {
PWD_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PWD_A {
match self.bits {
false => PWD_A::VALUE1,
true => PWD_A::VALUE2,
}
}
#[doc = "Checks if the value of the field is `VALUE1`"]
#[inline(always)]
pub fn is_value1(&self) -> bool {
**self == PWD_A::VALUE1
}
#[doc = "Checks if the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool {
**self == PWD_A::VALUE2
}
}
impl core::ops::Deref for PWD_R {
type Target = crate::FieldReader<bool, PWD_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `PWD` writer - Turn OFF the fOSI Clock Source"]
pub struct PWD_W<'a> {
w: &'a mut W,
}
impl<'a> PWD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWD_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Enabled"]
#[inline(always)]
pub fn value1(self) -> &'a mut W {
self.variant(PWD_A::VALUE1)
}
#[doc = "Disabled"]
#[inline(always)]
pub fn value2(self) -> &'a mut W {
self.variant(PWD_A::VALUE2)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits &!0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - Turn OFF the fOSI Clock Source"]
#[inline(always)]
pub fn pwd(&self) -> PWD_R {
PWD_R::new((self.bits & 0x01)!= 0)
}
}
impl W {
#[doc = "Bit 0 - Turn OFF the fOSI Clock Source"]
#[inline(always)]
pub fn pwd(&mut self) -> PWD_W {
PWD_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "fOSI Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [oscsictrl](index.html) module"]
pub struct OSCSICTRL_SPEC;
impl crate::RegisterSpec for OSCSICTRL_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [oscsictrl::R](R) reader structure"]
impl crate::Readable for OSCSICTRL_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [oscsictrl::W](W) writer structure"]
impl crate::Writable for OSCSICTRL_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets OSCSICTRL to value 0x01"]
impl crate::Resettable for OSCSICTRL_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x01
}
}
| deref | identifier_name |
oscsictrl.rs | #[doc = "Register `OSCSICTRL` reader"]
pub struct R(crate::R<OSCSICTRL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<OSCSICTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<OSCSICTRL_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<OSCSICTRL_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `OSCSICTRL` writer"]
pub struct W(crate::W<OSCSICTRL_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<OSCSICTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<OSCSICTRL_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<OSCSICTRL_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Turn OFF the fOSI Clock Source\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWD_A {
#[doc = "0: Enabled"]
VALUE1 = 0,
#[doc = "1: Disabled"]
VALUE2 = 1,
}
impl From<PWD_A> for bool {
#[inline(always)]
fn from(variant: PWD_A) -> Self {
variant as u8!= 0
}
}
#[doc = "Field `PWD` reader - Turn OFF the fOSI Clock Source"]
pub struct PWD_R(crate::FieldReader<bool, PWD_A>);
impl PWD_R {
pub(crate) fn new(bits: bool) -> Self {
PWD_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PWD_A {
match self.bits {
false => PWD_A::VALUE1,
true => PWD_A::VALUE2,
}
}
#[doc = "Checks if the value of the field is `VALUE1`"]
#[inline(always)]
pub fn is_value1(&self) -> bool {
**self == PWD_A::VALUE1
}
#[doc = "Checks if the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool {
**self == PWD_A::VALUE2
}
}
impl core::ops::Deref for PWD_R {
type Target = crate::FieldReader<bool, PWD_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target |
}
#[doc = "Field `PWD` writer - Turn OFF the fOSI Clock Source"]
pub struct PWD_W<'a> {
w: &'a mut W,
}
impl<'a> PWD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWD_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Enabled"]
#[inline(always)]
pub fn value1(self) -> &'a mut W {
self.variant(PWD_A::VALUE1)
}
#[doc = "Disabled"]
#[inline(always)]
pub fn value2(self) -> &'a mut W {
self.variant(PWD_A::VALUE2)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits &!0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - Turn OFF the fOSI Clock Source"]
#[inline(always)]
pub fn pwd(&self) -> PWD_R {
PWD_R::new((self.bits & 0x01)!= 0)
}
}
impl W {
#[doc = "Bit 0 - Turn OFF the fOSI Clock Source"]
#[inline(always)]
pub fn pwd(&mut self) -> PWD_W {
PWD_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "fOSI Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [oscsictrl](index.html) module"]
pub struct OSCSICTRL_SPEC;
impl crate::RegisterSpec for OSCSICTRL_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [oscsictrl::R](R) reader structure"]
impl crate::Readable for OSCSICTRL_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [oscsictrl::W](W) writer structure"]
impl crate::Writable for OSCSICTRL_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets OSCSICTRL to value 0x01"]
impl crate::Resettable for OSCSICTRL_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x01
}
}
| {
&self.0
} | identifier_body |
oscsictrl.rs | #[doc = "Register `OSCSICTRL` reader"]
pub struct R(crate::R<OSCSICTRL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<OSCSICTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target { | #[inline(always)]
fn from(reader: crate::R<OSCSICTRL_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `OSCSICTRL` writer"]
pub struct W(crate::W<OSCSICTRL_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<OSCSICTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<OSCSICTRL_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<OSCSICTRL_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Turn OFF the fOSI Clock Source\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWD_A {
#[doc = "0: Enabled"]
VALUE1 = 0,
#[doc = "1: Disabled"]
VALUE2 = 1,
}
impl From<PWD_A> for bool {
#[inline(always)]
fn from(variant: PWD_A) -> Self {
variant as u8!= 0
}
}
#[doc = "Field `PWD` reader - Turn OFF the fOSI Clock Source"]
pub struct PWD_R(crate::FieldReader<bool, PWD_A>);
impl PWD_R {
pub(crate) fn new(bits: bool) -> Self {
PWD_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PWD_A {
match self.bits {
false => PWD_A::VALUE1,
true => PWD_A::VALUE2,
}
}
#[doc = "Checks if the value of the field is `VALUE1`"]
#[inline(always)]
pub fn is_value1(&self) -> bool {
**self == PWD_A::VALUE1
}
#[doc = "Checks if the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool {
**self == PWD_A::VALUE2
}
}
impl core::ops::Deref for PWD_R {
type Target = crate::FieldReader<bool, PWD_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `PWD` writer - Turn OFF the fOSI Clock Source"]
pub struct PWD_W<'a> {
w: &'a mut W,
}
impl<'a> PWD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWD_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Enabled"]
#[inline(always)]
pub fn value1(self) -> &'a mut W {
self.variant(PWD_A::VALUE1)
}
#[doc = "Disabled"]
#[inline(always)]
pub fn value2(self) -> &'a mut W {
self.variant(PWD_A::VALUE2)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits &!0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - Turn OFF the fOSI Clock Source"]
#[inline(always)]
pub fn pwd(&self) -> PWD_R {
PWD_R::new((self.bits & 0x01)!= 0)
}
}
impl W {
#[doc = "Bit 0 - Turn OFF the fOSI Clock Source"]
#[inline(always)]
pub fn pwd(&mut self) -> PWD_W {
PWD_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "fOSI Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [oscsictrl](index.html) module"]
pub struct OSCSICTRL_SPEC;
impl crate::RegisterSpec for OSCSICTRL_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [oscsictrl::R](R) reader structure"]
impl crate::Readable for OSCSICTRL_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [oscsictrl::W](W) writer structure"]
impl crate::Writable for OSCSICTRL_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets OSCSICTRL to value 0x01"]
impl crate::Resettable for OSCSICTRL_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x01
}
} | &self.0
}
}
impl From<crate::R<OSCSICTRL_SPEC>> for R { | random_line_split |
pl030.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{warn, Event};
use std::convert::TryFrom;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{BusAccessInfo, BusDevice};
// Register offsets
// Data register
const RTCDR: u64 = 0x0;
// Match register
const RTCMR: u64 = 0x4;
// Interrupt status register
const RTCSTAT: u64 = 0x8;
// Interrupt clear register
const RTCEOI: u64 = 0x8;
// Counter load register
const RTCLR: u64 = 0xC;
// Counter register
const RTCCR: u64 = 0x10;
// A single 4K page is mapped for this device
pub const PL030_AMBA_IOMEM_SIZE: u64 = 0x1000;
// AMBA id registers are at the end of the allocated memory space
const AMBA_ID_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x20;
const AMBA_MASK_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x28;
// This is the AMBA id for this device
pub const PL030_AMBA_ID: u32 = 0x00041030;
pub const PL030_AMBA_MASK: u32 = 0x000FFFFF;
/// An emulated ARM pl030 RTC
pub struct Pl030 {
// Event to be used to interrupt the guest for an alarm event
alarm_evt: Event,
// This is the delta we subtract from current time to get the
// counter value
counter_delta_time: u32,
// This is the value that triggers an alarm interrupt when it
// matches with the rtc time
match_value: u32,
// status flag to keep track of whether the interrupt is cleared
// or not
interrupt_active: bool,
}
fn get_epoch_time() -> u32 {
let epoch_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("SystemTime::duration_since failed");
epoch_time.as_secs() as u32
}
impl Pl030 {
/// Constructs a Pl030 device
pub fn new(evt: Event) -> Pl030 {
Pl030 {
alarm_evt: evt,
counter_delta_time: get_epoch_time(),
match_value: 0,
interrupt_active: false,
}
}
}
impl BusDevice for Pl030 {
fn debug_label(&self) -> String {
"Pl030".to_owned()
}
fn write(&mut self, info: BusAccessInfo, data: &[u8]) {
let data_array = match <&[u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size: {} for pl030", data.len());
return;
}
};
let reg_val = u32::from_ne_bytes(*data_array);
match info.offset {
RTCDR => {
warn!("invalid write to read-only RTCDR register");
}
RTCMR => {
self.match_value = reg_val;
// TODO(sonnyrao): here we need to set up a timer for
// when host time equals the value written here and
// fire the interrupt
warn!("Not implemented: VM tried to set an RTC alarm");
}
RTCEOI => {
if reg_val == 0 {
self.interrupt_active = false;
} else {
self.alarm_evt.write(1).unwrap();
self.interrupt_active = true;
}
}
RTCLR => {
// TODO(sonnyrao): if we ever need to let the VM set it's own time
// then we'll need to keep track of the delta between
// the rtc time it sets and the host's rtc time and
// record that here
warn!("Not implemented: VM tried to set the RTC");
}
RTCCR => {
self.counter_delta_time = get_epoch_time();
}
o => panic!("pl030: bad write {}", o),
}
}
fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) {
let data_array = match <&mut [u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size for pl030");
return;
}
};
let reg_content: u32 = match info.offset {
RTCDR => get_epoch_time(),
RTCMR => self.match_value,
RTCSTAT => self.interrupt_active as u32,
RTCLR => {
warn!("invalid read of RTCLR register");
0
}
RTCCR => get_epoch_time() - self.counter_delta_time,
AMBA_ID_OFFSET => PL030_AMBA_ID,
AMBA_MASK_OFFSET => PL030_AMBA_MASK,
o => panic!("pl030: bad read {}", o),
};
*data_array = reg_content.to_ne_bytes();
}
}
#[cfg(test)]
mod tests {
use super::*;
// The RTC device is placed at page 2 in the mmio bus
const AARCH64_RTC_ADDR: u64 = 0x2000;
fn pl030_bus_address(offset: u64) -> BusAccessInfo {
BusAccessInfo {
address: AARCH64_RTC_ADDR + offset,
offset,
id: 0,
}
}
#[test]
fn test_interrupt_status_register() |
#[test]
fn test_match_register() {
let mut device = Pl030::new(Event::new().unwrap());
let mut register = [0, 0, 0, 0];
device.write(pl030_bus_address(RTCMR), &[1, 2, 3, 4]);
device.read(pl030_bus_address(RTCMR), &mut register);
assert_eq!(register, [1, 2, 3, 4]);
}
}
| {
let event = Event::new().unwrap();
let mut device = Pl030::new(event.try_clone().unwrap());
let mut register = [0, 0, 0, 0];
// set interrupt
device.write(pl030_bus_address(RTCEOI), &[1, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [1, 0, 0, 0]);
assert_eq!(event.read().unwrap(), 1);
// clear interrupt
device.write(pl030_bus_address(RTCEOI), &[0, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [0, 0, 0, 0]);
} | identifier_body |
pl030.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{warn, Event};
use std::convert::TryFrom;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{BusAccessInfo, BusDevice};
// Register offsets
// Data register
const RTCDR: u64 = 0x0;
// Match register
const RTCMR: u64 = 0x4;
// Interrupt status register
const RTCSTAT: u64 = 0x8;
// Interrupt clear register
const RTCEOI: u64 = 0x8;
// Counter load register
const RTCLR: u64 = 0xC;
// Counter register
const RTCCR: u64 = 0x10;
// A single 4K page is mapped for this device
pub const PL030_AMBA_IOMEM_SIZE: u64 = 0x1000;
// AMBA id registers are at the end of the allocated memory space
const AMBA_ID_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x20;
const AMBA_MASK_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x28;
// This is the AMBA id for this device
pub const PL030_AMBA_ID: u32 = 0x00041030;
pub const PL030_AMBA_MASK: u32 = 0x000FFFFF;
/// An emulated ARM pl030 RTC | pub struct Pl030 {
// Event to be used to interrupt the guest for an alarm event
alarm_evt: Event,
// This is the delta we subtract from current time to get the
// counter value
counter_delta_time: u32,
// This is the value that triggers an alarm interrupt when it
// matches with the rtc time
match_value: u32,
// status flag to keep track of whether the interrupt is cleared
// or not
interrupt_active: bool,
}
fn get_epoch_time() -> u32 {
let epoch_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("SystemTime::duration_since failed");
epoch_time.as_secs() as u32
}
impl Pl030 {
/// Constructs a Pl030 device
pub fn new(evt: Event) -> Pl030 {
Pl030 {
alarm_evt: evt,
counter_delta_time: get_epoch_time(),
match_value: 0,
interrupt_active: false,
}
}
}
impl BusDevice for Pl030 {
fn debug_label(&self) -> String {
"Pl030".to_owned()
}
fn write(&mut self, info: BusAccessInfo, data: &[u8]) {
let data_array = match <&[u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size: {} for pl030", data.len());
return;
}
};
let reg_val = u32::from_ne_bytes(*data_array);
match info.offset {
RTCDR => {
warn!("invalid write to read-only RTCDR register");
}
RTCMR => {
self.match_value = reg_val;
// TODO(sonnyrao): here we need to set up a timer for
// when host time equals the value written here and
// fire the interrupt
warn!("Not implemented: VM tried to set an RTC alarm");
}
RTCEOI => {
if reg_val == 0 {
self.interrupt_active = false;
} else {
self.alarm_evt.write(1).unwrap();
self.interrupt_active = true;
}
}
RTCLR => {
// TODO(sonnyrao): if we ever need to let the VM set it's own time
// then we'll need to keep track of the delta between
// the rtc time it sets and the host's rtc time and
// record that here
warn!("Not implemented: VM tried to set the RTC");
}
RTCCR => {
self.counter_delta_time = get_epoch_time();
}
o => panic!("pl030: bad write {}", o),
}
}
fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) {
let data_array = match <&mut [u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size for pl030");
return;
}
};
let reg_content: u32 = match info.offset {
RTCDR => get_epoch_time(),
RTCMR => self.match_value,
RTCSTAT => self.interrupt_active as u32,
RTCLR => {
warn!("invalid read of RTCLR register");
0
}
RTCCR => get_epoch_time() - self.counter_delta_time,
AMBA_ID_OFFSET => PL030_AMBA_ID,
AMBA_MASK_OFFSET => PL030_AMBA_MASK,
o => panic!("pl030: bad read {}", o),
};
*data_array = reg_content.to_ne_bytes();
}
}
#[cfg(test)]
mod tests {
use super::*;
// The RTC device is placed at page 2 in the mmio bus
const AARCH64_RTC_ADDR: u64 = 0x2000;
fn pl030_bus_address(offset: u64) -> BusAccessInfo {
BusAccessInfo {
address: AARCH64_RTC_ADDR + offset,
offset,
id: 0,
}
}
#[test]
fn test_interrupt_status_register() {
let event = Event::new().unwrap();
let mut device = Pl030::new(event.try_clone().unwrap());
let mut register = [0, 0, 0, 0];
// set interrupt
device.write(pl030_bus_address(RTCEOI), &[1, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [1, 0, 0, 0]);
assert_eq!(event.read().unwrap(), 1);
// clear interrupt
device.write(pl030_bus_address(RTCEOI), &[0, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [0, 0, 0, 0]);
}
#[test]
fn test_match_register() {
let mut device = Pl030::new(Event::new().unwrap());
let mut register = [0, 0, 0, 0];
device.write(pl030_bus_address(RTCMR), &[1, 2, 3, 4]);
device.read(pl030_bus_address(RTCMR), &mut register);
assert_eq!(register, [1, 2, 3, 4]);
}
} | random_line_split |
|
pl030.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{warn, Event};
use std::convert::TryFrom;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{BusAccessInfo, BusDevice};
// Register offsets
// Data register
const RTCDR: u64 = 0x0;
// Match register
const RTCMR: u64 = 0x4;
// Interrupt status register
const RTCSTAT: u64 = 0x8;
// Interrupt clear register
const RTCEOI: u64 = 0x8;
// Counter load register
const RTCLR: u64 = 0xC;
// Counter register
const RTCCR: u64 = 0x10;
// A single 4K page is mapped for this device
pub const PL030_AMBA_IOMEM_SIZE: u64 = 0x1000;
// AMBA id registers are at the end of the allocated memory space
const AMBA_ID_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x20;
const AMBA_MASK_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x28;
// This is the AMBA id for this device
pub const PL030_AMBA_ID: u32 = 0x00041030;
pub const PL030_AMBA_MASK: u32 = 0x000FFFFF;
/// An emulated ARM pl030 RTC
pub struct | {
// Event to be used to interrupt the guest for an alarm event
alarm_evt: Event,
// This is the delta we subtract from current time to get the
// counter value
counter_delta_time: u32,
// This is the value that triggers an alarm interrupt when it
// matches with the rtc time
match_value: u32,
// status flag to keep track of whether the interrupt is cleared
// or not
interrupt_active: bool,
}
fn get_epoch_time() -> u32 {
let epoch_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("SystemTime::duration_since failed");
epoch_time.as_secs() as u32
}
impl Pl030 {
/// Constructs a Pl030 device
pub fn new(evt: Event) -> Pl030 {
Pl030 {
alarm_evt: evt,
counter_delta_time: get_epoch_time(),
match_value: 0,
interrupt_active: false,
}
}
}
impl BusDevice for Pl030 {
fn debug_label(&self) -> String {
"Pl030".to_owned()
}
fn write(&mut self, info: BusAccessInfo, data: &[u8]) {
let data_array = match <&[u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size: {} for pl030", data.len());
return;
}
};
let reg_val = u32::from_ne_bytes(*data_array);
match info.offset {
RTCDR => {
warn!("invalid write to read-only RTCDR register");
}
RTCMR => {
self.match_value = reg_val;
// TODO(sonnyrao): here we need to set up a timer for
// when host time equals the value written here and
// fire the interrupt
warn!("Not implemented: VM tried to set an RTC alarm");
}
RTCEOI => {
if reg_val == 0 {
self.interrupt_active = false;
} else {
self.alarm_evt.write(1).unwrap();
self.interrupt_active = true;
}
}
RTCLR => {
// TODO(sonnyrao): if we ever need to let the VM set it's own time
// then we'll need to keep track of the delta between
// the rtc time it sets and the host's rtc time and
// record that here
warn!("Not implemented: VM tried to set the RTC");
}
RTCCR => {
self.counter_delta_time = get_epoch_time();
}
o => panic!("pl030: bad write {}", o),
}
}
fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) {
let data_array = match <&mut [u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size for pl030");
return;
}
};
let reg_content: u32 = match info.offset {
RTCDR => get_epoch_time(),
RTCMR => self.match_value,
RTCSTAT => self.interrupt_active as u32,
RTCLR => {
warn!("invalid read of RTCLR register");
0
}
RTCCR => get_epoch_time() - self.counter_delta_time,
AMBA_ID_OFFSET => PL030_AMBA_ID,
AMBA_MASK_OFFSET => PL030_AMBA_MASK,
o => panic!("pl030: bad read {}", o),
};
*data_array = reg_content.to_ne_bytes();
}
}
#[cfg(test)]
mod tests {
use super::*;
// The RTC device is placed at page 2 in the mmio bus
const AARCH64_RTC_ADDR: u64 = 0x2000;
fn pl030_bus_address(offset: u64) -> BusAccessInfo {
BusAccessInfo {
address: AARCH64_RTC_ADDR + offset,
offset,
id: 0,
}
}
#[test]
fn test_interrupt_status_register() {
let event = Event::new().unwrap();
let mut device = Pl030::new(event.try_clone().unwrap());
let mut register = [0, 0, 0, 0];
// set interrupt
device.write(pl030_bus_address(RTCEOI), &[1, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [1, 0, 0, 0]);
assert_eq!(event.read().unwrap(), 1);
// clear interrupt
device.write(pl030_bus_address(RTCEOI), &[0, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [0, 0, 0, 0]);
}
#[test]
fn test_match_register() {
let mut device = Pl030::new(Event::new().unwrap());
let mut register = [0, 0, 0, 0];
device.write(pl030_bus_address(RTCMR), &[1, 2, 3, 4]);
device.read(pl030_bus_address(RTCMR), &mut register);
assert_eq!(register, [1, 2, 3, 4]);
}
}
| Pl030 | identifier_name |
pl030.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{warn, Event};
use std::convert::TryFrom;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{BusAccessInfo, BusDevice};
// Register offsets
// Data register
const RTCDR: u64 = 0x0;
// Match register
const RTCMR: u64 = 0x4;
// Interrupt status register
const RTCSTAT: u64 = 0x8;
// Interrupt clear register
const RTCEOI: u64 = 0x8;
// Counter load register
const RTCLR: u64 = 0xC;
// Counter register
const RTCCR: u64 = 0x10;
// A single 4K page is mapped for this device
pub const PL030_AMBA_IOMEM_SIZE: u64 = 0x1000;
// AMBA id registers are at the end of the allocated memory space
const AMBA_ID_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x20;
const AMBA_MASK_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x28;
// This is the AMBA id for this device
pub const PL030_AMBA_ID: u32 = 0x00041030;
pub const PL030_AMBA_MASK: u32 = 0x000FFFFF;
/// An emulated ARM pl030 RTC
pub struct Pl030 {
// Event to be used to interrupt the guest for an alarm event
alarm_evt: Event,
// This is the delta we subtract from current time to get the
// counter value
counter_delta_time: u32,
// This is the value that triggers an alarm interrupt when it
// matches with the rtc time
match_value: u32,
// status flag to keep track of whether the interrupt is cleared
// or not
interrupt_active: bool,
}
fn get_epoch_time() -> u32 {
let epoch_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("SystemTime::duration_since failed");
epoch_time.as_secs() as u32
}
impl Pl030 {
/// Constructs a Pl030 device
pub fn new(evt: Event) -> Pl030 {
Pl030 {
alarm_evt: evt,
counter_delta_time: get_epoch_time(),
match_value: 0,
interrupt_active: false,
}
}
}
impl BusDevice for Pl030 {
fn debug_label(&self) -> String {
"Pl030".to_owned()
}
fn write(&mut self, info: BusAccessInfo, data: &[u8]) {
let data_array = match <&[u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size: {} for pl030", data.len());
return;
}
};
let reg_val = u32::from_ne_bytes(*data_array);
match info.offset {
RTCDR => {
warn!("invalid write to read-only RTCDR register");
}
RTCMR => {
self.match_value = reg_val;
// TODO(sonnyrao): here we need to set up a timer for
// when host time equals the value written here and
// fire the interrupt
warn!("Not implemented: VM tried to set an RTC alarm");
}
RTCEOI => {
if reg_val == 0 {
self.interrupt_active = false;
} else {
self.alarm_evt.write(1).unwrap();
self.interrupt_active = true;
}
}
RTCLR => {
// TODO(sonnyrao): if we ever need to let the VM set it's own time
// then we'll need to keep track of the delta between
// the rtc time it sets and the host's rtc time and
// record that here
warn!("Not implemented: VM tried to set the RTC");
}
RTCCR => |
o => panic!("pl030: bad write {}", o),
}
}
fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) {
let data_array = match <&mut [u8; 4]>::try_from(data) {
Ok(array) => array,
_ => {
warn!("bad write size for pl030");
return;
}
};
let reg_content: u32 = match info.offset {
RTCDR => get_epoch_time(),
RTCMR => self.match_value,
RTCSTAT => self.interrupt_active as u32,
RTCLR => {
warn!("invalid read of RTCLR register");
0
}
RTCCR => get_epoch_time() - self.counter_delta_time,
AMBA_ID_OFFSET => PL030_AMBA_ID,
AMBA_MASK_OFFSET => PL030_AMBA_MASK,
o => panic!("pl030: bad read {}", o),
};
*data_array = reg_content.to_ne_bytes();
}
}
#[cfg(test)]
mod tests {
use super::*;
// The RTC device is placed at page 2 in the mmio bus
const AARCH64_RTC_ADDR: u64 = 0x2000;
fn pl030_bus_address(offset: u64) -> BusAccessInfo {
BusAccessInfo {
address: AARCH64_RTC_ADDR + offset,
offset,
id: 0,
}
}
#[test]
fn test_interrupt_status_register() {
let event = Event::new().unwrap();
let mut device = Pl030::new(event.try_clone().unwrap());
let mut register = [0, 0, 0, 0];
// set interrupt
device.write(pl030_bus_address(RTCEOI), &[1, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [1, 0, 0, 0]);
assert_eq!(event.read().unwrap(), 1);
// clear interrupt
device.write(pl030_bus_address(RTCEOI), &[0, 0, 0, 0]);
device.read(pl030_bus_address(RTCSTAT), &mut register);
assert_eq!(register, [0, 0, 0, 0]);
}
#[test]
fn test_match_register() {
let mut device = Pl030::new(Event::new().unwrap());
let mut register = [0, 0, 0, 0];
device.write(pl030_bus_address(RTCMR), &[1, 2, 3, 4]);
device.read(pl030_bus_address(RTCMR), &mut register);
assert_eq!(register, [1, 2, 3, 4]);
}
}
| {
self.counter_delta_time = get_epoch_time();
} | conditional_block |
test_multicast.rs | use mio::*;
use mio::deprecated::{EventLoop, Handler};
use mio::udp::*;
use bytes::{Buf, MutBuf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr, Ipv4Addr};
use 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, _: Ready) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } {
Ok(Some((cnt, SocketAddr::V4(addr)))) => {
unsafe { MutBuf::advance(&mut self.rx_buf, cnt); }
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, _: Ready) {
match token {
SENDER => {
let addr = self.rx.local_addr().unwrap();
let cnt = self.tx.send_to(self.buf.bytes(), &addr)
.unwrap().unwrap();
self.buf.advance(cnt);
},
_ => ()
}
}
}
impl Handler for UdpHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: Ready) |
}
#[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::bind(&any).unwrap();
let rx = UdpSocket::bind(&addr).unwrap();
info!("Joining group 227.1.1.100");
let any = "0.0.0.0".parse().unwrap();
rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap();
info!("Starting event loop to test with...");
event_loop.run(&mut UdpHandler::new(tx, rx, "hello world")).unwrap();
}
| {
if events.is_readable() {
self.handle_read(event_loop, token, events);
}
if events.is_writable() {
self.handle_write(event_loop, token, events);
}
} | identifier_body |
test_multicast.rs | use mio::*;
use mio::deprecated::{EventLoop, Handler};
use mio::udp::*;
use bytes::{Buf, MutBuf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr, Ipv4Addr};
use 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, _: Ready) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } {
Ok(Some((cnt, SocketAddr::V4(addr)))) => {
unsafe { MutBuf::advance(&mut self.rx_buf, cnt); }
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, _: Ready) {
match token {
SENDER => {
let addr = self.rx.local_addr().unwrap();
let cnt = self.tx.send_to(self.buf.bytes(), &addr)
.unwrap().unwrap();
self.buf.advance(cnt);
},
_ => ()
}
}
}
impl Handler for UdpHandler {
type Timeout = usize; |
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: Ready) {
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::bind(&any).unwrap();
let rx = UdpSocket::bind(&addr).unwrap();
info!("Joining group 227.1.1.100");
let any = "0.0.0.0".parse().unwrap();
rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap();
info!("Starting event loop to test with...");
event_loop.run(&mut UdpHandler::new(tx, rx, "hello world")).unwrap();
} | type Message = (); | random_line_split |
test_multicast.rs | use mio::*;
use mio::deprecated::{EventLoop, Handler};
use mio::udp::*;
use bytes::{Buf, MutBuf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr, Ipv4Addr};
use 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, _: Ready) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } {
Ok(Some((cnt, SocketAddr::V4(addr)))) => {
unsafe { MutBuf::advance(&mut self.rx_buf, cnt); }
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, _: Ready) {
match token {
SENDER => {
let addr = self.rx.local_addr().unwrap();
let cnt = self.tx.send_to(self.buf.bytes(), &addr)
.unwrap().unwrap();
self.buf.advance(cnt);
},
_ => ()
}
}
}
impl Handler for UdpHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: Ready) {
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::bind(&any).unwrap();
let rx = UdpSocket::bind(&addr).unwrap();
info!("Joining group 227.1.1.100");
let any = "0.0.0.0".parse().unwrap();
rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, Ready::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 |
test_multicast.rs | use mio::*;
use mio::deprecated::{EventLoop, Handler};
use mio::udp::*;
use bytes::{Buf, MutBuf, RingBuf, SliceBuf};
use std::str;
use std::net::{SocketAddr, Ipv4Addr};
use 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, _: Ready) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } {
Ok(Some((cnt, SocketAddr::V4(addr)))) => {
unsafe { MutBuf::advance(&mut self.rx_buf, cnt); }
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, _: Ready) {
match token {
SENDER => {
let addr = self.rx.local_addr().unwrap();
let cnt = self.tx.send_to(self.buf.bytes(), &addr)
.unwrap().unwrap();
self.buf.advance(cnt);
},
_ => ()
}
}
}
impl Handler for UdpHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: Ready) {
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 | () {
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::bind(&any).unwrap();
let rx = UdpSocket::bind(&addr).unwrap();
info!("Joining group 227.1.1.100");
let any = "0.0.0.0".parse().unwrap();
rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap();
info!("Registering SENDER");
event_loop.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
event_loop.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap();
info!("Starting event loop to test with...");
event_loop.run(&mut UdpHandler::new(tx, rx, "hello world")).unwrap();
}
| test_multicast | identifier_name |
types.rs | // of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pub struct NSRect {
pub origin: NSPoint,
pub size: NSSize
}
pub struct NSPoint {
pub x: f64,
pub y: f64
}
pub struct NSSize {
pub width: f64,
pub height: f64
} | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy | random_line_split |
|
types.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pub struct NSRect {
pub origin: NSPoint,
pub size: NSSize
}
pub struct | {
pub x: f64,
pub y: f64
}
pub struct NSSize {
pub width: f64,
pub height: f64
} | NSPoint | identifier_name |
plugins.rs | use std::collections::{BTreeMap, HashMap};
use std::string::FromUtf8Error;
use svgbob::Render;
use thiserror::Error;
use url_path::UrlPath;
/// Plugin info, format:
/// [<selector>] <plugin_name>[@version][://<URI>]
/// example:
/// #table1 csv://data_file.csv
#[allow(dead_code)]
pub struct PluginInfo {
selector: Option<String>,
plugin_name: String,
version: Option<String>,
uri: Option<String>,
}
#[derive(Error, Debug)]
pub enum PluginError {
#[error("Embeded file is not supplied")]
EmbededFilesNotSupplied,
#[error("Embeded file not found: `{0}`")]
EmbedFileNotFound(String),
#[error("Embed file has no extension")]
EmbedFileNoExtension,
#[error("Plugin does not exist: `{0}`")]
PluginNotExist(String),
#[error("Utf8Error: `{0}`")]
Utf8Error(#[from] FromUtf8Error),
}
pub fn get_plugins(
) -> HashMap<String, Box<dyn Fn(&str) -> Result<String, PluginError>>> {
let mut plugins: HashMap<
String,
Box<dyn Fn(&str) -> Result<String, PluginError>>,
> = HashMap::new();
plugins.insert("bob".into(), Box::new(bob_handler));
#[cfg(feature = "csv")]
plugins.insert("csv".into(), Box::new(csv_handler));
plugins
}
/// convert bob ascii diagrams to svg
fn bob_handler(input: &str) -> Result<String, PluginError> {
let cb = svgbob::CellBuffer::from(input);
let (node, width, height): (svgbob::Node<()>, f32, f32) =
cb.get_node_with_size(&svgbob::Settings::default());
let svg = node.render_to_string();
let bob_container = format!(
"<div class='bob_container' style='width:{}px;height:{}px;'>{}</div>",
width, height, svg
);
Ok(bob_container)
}
/// convert csv content into html table
#[cfg(feature = "csv")]
fn csv_handler(s: &str) -> Result<String, PluginError> {
let mut buff = String::new();
let mut rdr = csv::Reader::from_reader(s.as_bytes());
buff.push_str("<table>");
buff.push_str("<thead>");
for header in rdr.headers() {
buff.push_str("<tr>");
for h in header {
buff.push_str(&format!("<th>{}</th>", h));
}
buff.push_str("</tr>");
}
buff.push_str("</thead>");
buff.push_str("</thead>");
buff.push_str("<tbody>");
for record in rdr.records() {
buff.push_str("<tr>");
if let Ok(record) = record {
for value in record.iter() {
buff.push_str(&format!("<td>{}</td>", value));
}
}
buff.push_str("</tr>");
}
buff.push_str("</tbody>");
buff.push_str("</table>");
Ok(buff)
}
pub fn plugin_executor(
plugin_name: &str,
input: &str,
) -> Result<String, PluginError> {
let plugins = get_plugins();
if let Some(handler) = plugins.get(plugin_name) {
handler(input)
} else {
Err(PluginError::PluginNotExist(plugin_name.to_string()))
}
}
pub fn is_in_plugins(plugin_name: &str) -> bool {
let plugins = get_plugins();
if let Some(_handler) = plugins.get(plugin_name) | else {
false
}
}
/// handle the embed of the file with the supplied content
#[cfg(feature = "file")]
pub fn embed_handler(
url: &str,
embed_files: &Option<BTreeMap<String, Vec<u8>>>,
) -> Result<String, PluginError> {
if let Some(embed_files) = embed_files {
let url_path = UrlPath::new(&url);
if let Some(ext) = url_path.extension() {
if is_in_plugins(&ext) {
if let Some(content) = embed_files.get(url) {
let content = String::from_utf8(content.to_owned())?;
plugin_executor(&ext, &content)
} else {
Err(PluginError::EmbedFileNotFound(url.to_string())) // file is not in the embeded files
}
} else {
Err(PluginError::PluginNotExist(ext.to_string()))
}
} else {
Err(PluginError::EmbedFileNoExtension) // no extension on the embeded file
}
} else {
Err(PluginError::EmbededFilesNotSupplied) // no embedded file supplied
}
}
#[cfg(feature = "file")]
pub fn fetch_file_contents(files: Vec<String>) -> BTreeMap<String, Vec<u8>> {
let mut embed_files = BTreeMap::new();
for fname in files {
match file::get(&fname) {
Ok(content) => {
embed_files.insert(fname, content);
}
Err(e) => {
log::error!("fetching file error: {:?}", e);
}
}
}
embed_files
}
| {
true
} | conditional_block |
plugins.rs | use std::collections::{BTreeMap, HashMap};
use std::string::FromUtf8Error;
use svgbob::Render;
use thiserror::Error;
use url_path::UrlPath;
/// Plugin info, format:
/// [<selector>] <plugin_name>[@version][://<URI>]
/// example:
/// #table1 csv://data_file.csv
#[allow(dead_code)]
pub struct PluginInfo {
selector: Option<String>,
plugin_name: String,
version: Option<String>,
uri: Option<String>,
}
#[derive(Error, Debug)]
pub enum PluginError {
#[error("Embeded file is not supplied")]
EmbededFilesNotSupplied,
#[error("Embeded file not found: `{0}`")]
EmbedFileNotFound(String),
#[error("Embed file has no extension")]
EmbedFileNoExtension,
#[error("Plugin does not exist: `{0}`")]
PluginNotExist(String),
#[error("Utf8Error: `{0}`")]
Utf8Error(#[from] FromUtf8Error),
}
pub fn get_plugins(
) -> HashMap<String, Box<dyn Fn(&str) -> Result<String, PluginError>>> {
let mut plugins: HashMap<
String,
Box<dyn Fn(&str) -> Result<String, PluginError>>,
> = HashMap::new();
plugins.insert("bob".into(), Box::new(bob_handler));
#[cfg(feature = "csv")]
plugins.insert("csv".into(), Box::new(csv_handler));
plugins
}
/// convert bob ascii diagrams to svg
fn bob_handler(input: &str) -> Result<String, PluginError> {
let cb = svgbob::CellBuffer::from(input);
let (node, width, height): (svgbob::Node<()>, f32, f32) =
cb.get_node_with_size(&svgbob::Settings::default());
let svg = node.render_to_string();
let bob_container = format!(
"<div class='bob_container' style='width:{}px;height:{}px;'>{}</div>",
width, height, svg
);
Ok(bob_container)
}
/// convert csv content into html table
#[cfg(feature = "csv")]
fn csv_handler(s: &str) -> Result<String, PluginError> {
let mut buff = String::new();
let mut rdr = csv::Reader::from_reader(s.as_bytes());
buff.push_str("<table>");
buff.push_str("<thead>");
for header in rdr.headers() {
buff.push_str("<tr>"); | buff.push_str(&format!("<th>{}</th>", h));
}
buff.push_str("</tr>");
}
buff.push_str("</thead>");
buff.push_str("</thead>");
buff.push_str("<tbody>");
for record in rdr.records() {
buff.push_str("<tr>");
if let Ok(record) = record {
for value in record.iter() {
buff.push_str(&format!("<td>{}</td>", value));
}
}
buff.push_str("</tr>");
}
buff.push_str("</tbody>");
buff.push_str("</table>");
Ok(buff)
}
pub fn plugin_executor(
plugin_name: &str,
input: &str,
) -> Result<String, PluginError> {
let plugins = get_plugins();
if let Some(handler) = plugins.get(plugin_name) {
handler(input)
} else {
Err(PluginError::PluginNotExist(plugin_name.to_string()))
}
}
pub fn is_in_plugins(plugin_name: &str) -> bool {
let plugins = get_plugins();
if let Some(_handler) = plugins.get(plugin_name) {
true
} else {
false
}
}
/// handle the embed of the file with the supplied content
#[cfg(feature = "file")]
pub fn embed_handler(
url: &str,
embed_files: &Option<BTreeMap<String, Vec<u8>>>,
) -> Result<String, PluginError> {
if let Some(embed_files) = embed_files {
let url_path = UrlPath::new(&url);
if let Some(ext) = url_path.extension() {
if is_in_plugins(&ext) {
if let Some(content) = embed_files.get(url) {
let content = String::from_utf8(content.to_owned())?;
plugin_executor(&ext, &content)
} else {
Err(PluginError::EmbedFileNotFound(url.to_string())) // file is not in the embeded files
}
} else {
Err(PluginError::PluginNotExist(ext.to_string()))
}
} else {
Err(PluginError::EmbedFileNoExtension) // no extension on the embeded file
}
} else {
Err(PluginError::EmbededFilesNotSupplied) // no embedded file supplied
}
}
#[cfg(feature = "file")]
pub fn fetch_file_contents(files: Vec<String>) -> BTreeMap<String, Vec<u8>> {
let mut embed_files = BTreeMap::new();
for fname in files {
match file::get(&fname) {
Ok(content) => {
embed_files.insert(fname, content);
}
Err(e) => {
log::error!("fetching file error: {:?}", e);
}
}
}
embed_files
} | for h in header { | random_line_split |
plugins.rs | use std::collections::{BTreeMap, HashMap};
use std::string::FromUtf8Error;
use svgbob::Render;
use thiserror::Error;
use url_path::UrlPath;
/// Plugin info, format:
/// [<selector>] <plugin_name>[@version][://<URI>]
/// example:
/// #table1 csv://data_file.csv
#[allow(dead_code)]
pub struct | {
selector: Option<String>,
plugin_name: String,
version: Option<String>,
uri: Option<String>,
}
#[derive(Error, Debug)]
pub enum PluginError {
#[error("Embeded file is not supplied")]
EmbededFilesNotSupplied,
#[error("Embeded file not found: `{0}`")]
EmbedFileNotFound(String),
#[error("Embed file has no extension")]
EmbedFileNoExtension,
#[error("Plugin does not exist: `{0}`")]
PluginNotExist(String),
#[error("Utf8Error: `{0}`")]
Utf8Error(#[from] FromUtf8Error),
}
pub fn get_plugins(
) -> HashMap<String, Box<dyn Fn(&str) -> Result<String, PluginError>>> {
let mut plugins: HashMap<
String,
Box<dyn Fn(&str) -> Result<String, PluginError>>,
> = HashMap::new();
plugins.insert("bob".into(), Box::new(bob_handler));
#[cfg(feature = "csv")]
plugins.insert("csv".into(), Box::new(csv_handler));
plugins
}
/// convert bob ascii diagrams to svg
fn bob_handler(input: &str) -> Result<String, PluginError> {
let cb = svgbob::CellBuffer::from(input);
let (node, width, height): (svgbob::Node<()>, f32, f32) =
cb.get_node_with_size(&svgbob::Settings::default());
let svg = node.render_to_string();
let bob_container = format!(
"<div class='bob_container' style='width:{}px;height:{}px;'>{}</div>",
width, height, svg
);
Ok(bob_container)
}
/// convert csv content into html table
#[cfg(feature = "csv")]
fn csv_handler(s: &str) -> Result<String, PluginError> {
let mut buff = String::new();
let mut rdr = csv::Reader::from_reader(s.as_bytes());
buff.push_str("<table>");
buff.push_str("<thead>");
for header in rdr.headers() {
buff.push_str("<tr>");
for h in header {
buff.push_str(&format!("<th>{}</th>", h));
}
buff.push_str("</tr>");
}
buff.push_str("</thead>");
buff.push_str("</thead>");
buff.push_str("<tbody>");
for record in rdr.records() {
buff.push_str("<tr>");
if let Ok(record) = record {
for value in record.iter() {
buff.push_str(&format!("<td>{}</td>", value));
}
}
buff.push_str("</tr>");
}
buff.push_str("</tbody>");
buff.push_str("</table>");
Ok(buff)
}
pub fn plugin_executor(
plugin_name: &str,
input: &str,
) -> Result<String, PluginError> {
let plugins = get_plugins();
if let Some(handler) = plugins.get(plugin_name) {
handler(input)
} else {
Err(PluginError::PluginNotExist(plugin_name.to_string()))
}
}
pub fn is_in_plugins(plugin_name: &str) -> bool {
let plugins = get_plugins();
if let Some(_handler) = plugins.get(plugin_name) {
true
} else {
false
}
}
/// handle the embed of the file with the supplied content
#[cfg(feature = "file")]
pub fn embed_handler(
url: &str,
embed_files: &Option<BTreeMap<String, Vec<u8>>>,
) -> Result<String, PluginError> {
if let Some(embed_files) = embed_files {
let url_path = UrlPath::new(&url);
if let Some(ext) = url_path.extension() {
if is_in_plugins(&ext) {
if let Some(content) = embed_files.get(url) {
let content = String::from_utf8(content.to_owned())?;
plugin_executor(&ext, &content)
} else {
Err(PluginError::EmbedFileNotFound(url.to_string())) // file is not in the embeded files
}
} else {
Err(PluginError::PluginNotExist(ext.to_string()))
}
} else {
Err(PluginError::EmbedFileNoExtension) // no extension on the embeded file
}
} else {
Err(PluginError::EmbededFilesNotSupplied) // no embedded file supplied
}
}
#[cfg(feature = "file")]
pub fn fetch_file_contents(files: Vec<String>) -> BTreeMap<String, Vec<u8>> {
let mut embed_files = BTreeMap::new();
for fname in files {
match file::get(&fname) {
Ok(content) => {
embed_files.insert(fname, content);
}
Err(e) => {
log::error!("fetching file error: {:?}", e);
}
}
}
embed_files
}
| PluginInfo | identifier_name |
eq.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.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use std::gc::Gc;
pub fn | (cx: &mut ExtCtxt,
span: Span,
mitem: Gc<MetaItem>,
item: Gc<Item>,
push: |Gc<Item>|) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> {
cs_or(|cx, span, _, _| cx.expr_bool(span, true),
cx, span, substr)
}
macro_rules! md (
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec!(borrowed_self()),
ret_ty: Literal(Path::new(vec!("bool"))),
attributes: attrs,
const_nonmatching: true,
combine_substructure: combine_substructure(|a, b, c| {
$f(a, b, c)
})
}
} }
);
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "cmp", "PartialEq")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
md!("eq", cs_eq),
md!("ne", cs_ne)
)
};
trait_def.expand(cx, mitem, item, push)
}
| expand_deriving_eq | identifier_name |
eq.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.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use std::gc::Gc;
pub fn expand_deriving_eq(cx: &mut ExtCtxt,
span: Span,
mitem: Gc<MetaItem>,
item: Gc<Item>,
push: |Gc<Item>|) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> {
cs_or(|cx, span, _, _| cx.expr_bool(span, true),
cx, span, substr)
}
macro_rules! md (
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec!(borrowed_self()),
ret_ty: Literal(Path::new(vec!("bool"))),
attributes: attrs,
const_nonmatching: true,
combine_substructure: combine_substructure(|a, b, c| {
$f(a, b, c)
})
}
} }
);
let trait_def = TraitDef {
span: span, | methods: vec!(
md!("eq", cs_eq),
md!("ne", cs_ne)
)
};
trait_def.expand(cx, mitem, item, push)
} | attributes: Vec::new(),
path: Path::new(vec!("std", "cmp", "PartialEq")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(), | random_line_split |
eq.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.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use std::gc::Gc;
pub fn expand_deriving_eq(cx: &mut ExtCtxt,
span: Span,
mitem: Gc<MetaItem>,
item: Gc<Item>,
push: |Gc<Item>|) | args: vec!(borrowed_self()),
ret_ty: Literal(Path::new(vec!("bool"))),
attributes: attrs,
const_nonmatching: true,
combine_substructure: combine_substructure(|a, b, c| {
$f(a, b, c)
})
}
} }
);
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "cmp", "PartialEq")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
md!("eq", cs_eq),
md!("ne", cs_ne)
)
};
trait_def.expand(cx, mitem, item, push)
}
| {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> {
cs_or(|cx, span, _, _| cx.expr_bool(span, true),
cx, span, substr)
}
macro_rules! md (
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(), | identifier_body |
storage.rs | use api::{Bool, Id};
request_ref! {
#[derive(Eq, Copy)]
struct Get for ["storage.get"](v => 5.44) -> String {
sized {
user_id: Id = () => {},
global: bool = () => {bool},
}
unsized {
key: str = ("") => {=},
keys: str = ("") => {=},
}
}
}
request_ref! {
#[derive(Eq, Copy)]
struct Set for ["storage.set"](v => 5.44) -> Bool {
sized {
user_id: Id = () => {},
global: bool = () => {bool},
}
unsized {
key: str = ("") => {=},
value: str = ("") => {=},
}
}
}
request! { | #[derive(Eq, Copy)]
struct GetKeys for ["storage.getKeys"](v => 5.44) -> Vec<String> {
user_id: Id = () => {},
global: bool = () => {bool},
offset: usize = (0) => {},
count: usize = (100) => {},
}
} | random_line_split |
|
regs.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::mem;
use super::gdt::{gdt_entry, kvm_segment_from_gdt};
use kvm_bindings::{kvm_fpu, kvm_regs, kvm_sregs};
use kvm_ioctls::VcpuFd;
use vm_memory::{Address, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap};
// Initial pagetables.
const PML4_START: u64 = 0x9000;
const PDPTE_START: u64 = 0xa000;
const PDE_START: u64 = 0xb000;
/// Errors thrown while setting up x86_64 registers.
#[derive(Debug)]
pub enum Error {
/// Failed to get SREGs for this CPU.
GetStatusRegisters(kvm_ioctls::Error),
/// Failed to set base registers for this CPU.
SetBaseRegisters(kvm_ioctls::Error),
/// Failed to configure the FPU.
SetFPURegisters(kvm_ioctls::Error),
/// Failed to set SREGs for this CPU.
SetStatusRegisters(kvm_ioctls::Error),
/// Writing the GDT to RAM failed.
WriteGDT,
/// Writing the IDT to RAM failed.
WriteIDT,
/// Writing PDPTE to RAM failed.
WritePDPTEAddress,
/// Writing PDE to RAM failed.
WritePDEAddress,
/// Writing PML4 to RAM failed.
WritePML4Address,
}
type Result<T> = std::result::Result<T, Error>;
/// Configure Floating-Point Unit (FPU) registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_fpu(vcpu: &VcpuFd) -> Result<()> {
let fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
vcpu.set_fpu(&fpu).map_err(Error::SetFPURegisters)
}
/// Configure base registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
/// * `boot_ip` - Starting instruction pointer.
pub fn setup_regs(vcpu: &VcpuFd, boot_ip: u64) -> Result<()> {
let regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: boot_ip,
// Frame pointer. It gets a snapshot of the stack pointer (rsp) so that when adjustments are
// made to rsp (i.e. reserving space for local variables or pushing values on to the stack),
// local variables and function parameters are still accessible from a constant offset from rbp.
rsp: super::layout::BOOT_STACK_POINTER as u64,
// Starting stack pointer.
rbp: super::layout::BOOT_STACK_POINTER as u64,
// Must point to zero page address per Linux ABI. This is x86_64 specific.
rsi: super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
vcpu.set_regs(®s).map_err(Error::SetBaseRegisters)
}
/// Configures the segment registers and system page tables for a given CPU.
///
/// # Arguments
///
/// * `mem` - The memory that will be passed to the guest.
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_sregs(mem: &GuestMemoryMmap, vcpu: &VcpuFd) -> Result<()> {
let mut sregs: kvm_sregs = vcpu.get_sregs().map_err(Error::GetStatusRegisters)?;
configure_segments_and_sregs(mem, &mut sregs)?;
setup_page_tables(mem, &mut sregs)?; // TODO(dgreid) - Can this be done once per system instead?
vcpu.set_sregs(&sregs).map_err(Error::SetStatusRegisters)
}
const BOOT_GDT_OFFSET: u64 = 0x500;
const BOOT_IDT_OFFSET: u64 = 0x520;
const BOOT_GDT_MAX: usize = 4;
const EFER_LMA: u64 = 0x400;
const EFER_LME: u64 = 0x100;
const X86_CR0_PE: u64 = 0x1;
const X86_CR0_PG: u64 = 0x8000_0000;
const X86_CR4_PAE: u64 = 0x20;
fn write_gdt_table(table: &[u64], guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_gdt_addr = GuestAddress(BOOT_GDT_OFFSET);
for (index, entry) in table.iter().enumerate() {
let addr = guest_mem
.checked_offset(boot_gdt_addr, index * mem::size_of::<u64>())
.ok_or(Error::WriteGDT)?;
guest_mem
.write_obj(*entry, addr)
.map_err(|_| Error::WriteGDT)?;
}
Ok(())
}
fn write_idt_value(val: u64, guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_idt_addr = GuestAddress(BOOT_IDT_OFFSET);
guest_mem
.write_obj(val, boot_idt_addr)
.map_err(|_| Error::WriteIDT)
}
fn configure_segments_and_sregs(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
let code_seg = kvm_segment_from_gdt(gdt_table[1], 1);
let data_seg = kvm_segment_from_gdt(gdt_table[2], 2);
let tss_seg = kvm_segment_from_gdt(gdt_table[3], 3);
// Write segments
write_gdt_table(&gdt_table[..], mem)?;
sregs.gdt.base = BOOT_GDT_OFFSET as u64;
sregs.gdt.limit = mem::size_of_val(&gdt_table) as u16 - 1;
write_idt_value(0, mem)?;
sregs.idt.base = BOOT_IDT_OFFSET as u64;
sregs.idt.limit = mem::size_of::<u64>() as u16 - 1;
sregs.cs = code_seg;
sregs.ds = data_seg;
sregs.es = data_seg;
sregs.fs = data_seg;
sregs.gs = data_seg;
sregs.ss = data_seg;
sregs.tr = tss_seg;
/* 64-bit protected mode */
sregs.cr0 |= X86_CR0_PE;
sregs.efer |= EFER_LME | EFER_LMA;
Ok(())
}
fn setup_page_tables(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
// Puts PML4 right after zero page but aligned to 4k.
let boot_pml4_addr = GuestAddress(PML4_START);
let boot_pdpte_addr = GuestAddress(PDPTE_START);
let boot_pde_addr = GuestAddress(PDE_START);
// Entry covering VA [0..512GB)
mem.write_obj(boot_pdpte_addr.raw_value() as u64 | 0x03, boot_pml4_addr)
.map_err(|_| Error::WritePML4Address)?;
// Entry covering VA [0..1GB)
mem.write_obj(boot_pde_addr.raw_value() as u64 | 0x03, boot_pdpte_addr)
.map_err(|_| Error::WritePDPTEAddress)?;
// 512 2MB entries together covering VA [0..1GB). Note we are assuming
// CPU supports 2MB pages (/proc/cpuinfo has 'pse'). All modern CPUs do.
for i in 0..512 {
mem.write_obj((i << 21) + 0x83u64, boot_pde_addr.unchecked_add(i * 8))
.map_err(|_| Error::WritePDEAddress)?;
}
sregs.cr3 = boot_pml4_addr.raw_value() as u64;
sregs.cr4 |= X86_CR4_PAE;
sregs.cr0 |= X86_CR0_PG;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use kvm_ioctls::Kvm;
use vm_memory::{Bytes, GuestAddress, GuestMemoryMmap};
fn create_guest_mem(mem_size: Option<u64>) -> GuestMemoryMmap {
let page_size = 0x10000usize;
let mem_size = mem_size.unwrap_or(page_size as u64) as usize;
if mem_size % page_size == 0 {
vm_memory::test_utils::create_anon_guest_memory(&[(GuestAddress(0), mem_size)], false)
.unwrap()
} else |
}
fn read_u64(gm: &GuestMemoryMmap, offset: u64) -> u64 {
let read_addr = GuestAddress(offset as u64);
gm.read_obj(read_addr).unwrap()
}
fn validate_segments_and_sregs(gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0x0, read_u64(&gm, BOOT_GDT_OFFSET));
assert_eq!(0xaf_9b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 8));
assert_eq!(0xcf_9300_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 16));
assert_eq!(0x8f_8b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 24));
assert_eq!(0x0, read_u64(&gm, BOOT_IDT_OFFSET));
assert_eq!(0, sregs.cs.base);
assert_eq!(0xfffff, sregs.ds.limit);
assert_eq!(0x10, sregs.es.selector);
assert_eq!(1, sregs.fs.present);
assert_eq!(1, sregs.gs.g);
assert_eq!(0, sregs.ss.avl);
assert_eq!(0, sregs.tr.base);
assert_eq!(0xfffff, sregs.tr.limit);
assert_eq!(0, sregs.tr.avl);
assert!(sregs.cr0 & X86_CR0_PE!= 0);
assert!(sregs.efer & EFER_LME!= 0 && sregs.efer & EFER_LMA!= 0);
}
fn validate_page_tables(gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0xa003, read_u64(&gm, PML4_START));
assert_eq!(0xb003, read_u64(&gm, PDPTE_START));
for i in 0..512 {
assert_eq!((i << 21) + 0x83u64, read_u64(&gm, PDE_START + (i * 8)));
}
assert_eq!(PML4_START as u64, sregs.cr3);
assert!(sregs.cr4 & X86_CR4_PAE!= 0);
assert!(sregs.cr0 & X86_CR0_PG!= 0);
}
#[test]
fn test_setup_fpu() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
setup_fpu(&vcpu).unwrap();
let expected_fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
let actual_fpu: kvm_fpu = vcpu.get_fpu().unwrap();
// TODO: auto-generate kvm related structures with PartialEq on.
assert_eq!(expected_fpu.fcw, actual_fpu.fcw);
// Setting the mxcsr register from kvm_fpu inside setup_fpu does not influence anything.
// See 'kvm_arch_vcpu_ioctl_set_fpu' from arch/x86/kvm/x86.c.
// The mxcsr will stay 0 and the assert below fails. Decide whether or not we should
// remove it at all.
// assert!(expected_fpu.mxcsr == actual_fpu.mxcsr);
}
#[test]
fn test_setup_regs() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let expected_regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: 1,
rsp: super::super::layout::BOOT_STACK_POINTER as u64,
rbp: super::super::layout::BOOT_STACK_POINTER as u64,
rsi: super::super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
setup_regs(&vcpu, expected_regs.rip).unwrap();
let actual_regs: kvm_regs = vcpu.get_regs().unwrap();
assert_eq!(actual_regs, expected_regs);
}
#[test]
fn test_setup_sregs() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let gm = create_guest_mem(None);
assert!(vcpu.set_sregs(&Default::default()).is_ok());
setup_sregs(&gm, &vcpu).unwrap();
let mut sregs: kvm_sregs = vcpu.get_sregs().unwrap();
// for AMD KVM_GET_SREGS returns g = 0 for each kvm_segment.
// We set it to 1, otherwise the test will fail.
sregs.gs.g = 1;
validate_segments_and_sregs(&gm, &sregs);
validate_page_tables(&gm, &sregs);
}
#[test]
fn test_write_gdt_table() {
// Not enough memory for the gdt table to be written.
let gm = create_guest_mem(Some(BOOT_GDT_OFFSET));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_err());
// We allocate exactly the amount needed to write four u64 to `BOOT_GDT_OFFSET`.
let gm = create_guest_mem(Some(
BOOT_GDT_OFFSET + (mem::size_of::<u64>() * BOOT_GDT_MAX) as u64,
));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_ok());
}
#[test]
fn test_write_idt_table() {
// Not enough memory for the a u64 value to fit.
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET));
let val = 0x100;
assert!(write_idt_value(val, &gm).is_err());
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET + mem::size_of::<u64>() as u64));
// We have allocated exactly the amount neded to write an u64 to `BOOT_IDT_OFFSET`.
assert!(write_idt_value(val, &gm).is_ok());
}
#[test]
fn test_configure_segments_and_sregs() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(None);
configure_segments_and_sregs(&gm, &mut sregs).unwrap();
validate_segments_and_sregs(&gm, &sregs);
}
#[test]
fn test_setup_page_tables() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(Some(PML4_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDPTE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(None);
setup_page_tables(&gm, &mut sregs).unwrap();
validate_page_tables(&gm, &sregs);
}
}
| {
vm_memory::test_utils::create_guest_memory_unguarded(
&[(GuestAddress(0), mem_size)],
false,
)
.unwrap()
} | conditional_block |
regs.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::mem;
use super::gdt::{gdt_entry, kvm_segment_from_gdt};
use kvm_bindings::{kvm_fpu, kvm_regs, kvm_sregs};
use kvm_ioctls::VcpuFd;
use vm_memory::{Address, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap};
// Initial pagetables.
const PML4_START: u64 = 0x9000;
const PDPTE_START: u64 = 0xa000;
const PDE_START: u64 = 0xb000;
/// Errors thrown while setting up x86_64 registers.
#[derive(Debug)]
pub enum Error {
/// Failed to get SREGs for this CPU.
GetStatusRegisters(kvm_ioctls::Error),
/// Failed to set base registers for this CPU.
SetBaseRegisters(kvm_ioctls::Error),
/// Failed to configure the FPU.
SetFPURegisters(kvm_ioctls::Error),
/// Failed to set SREGs for this CPU.
SetStatusRegisters(kvm_ioctls::Error),
/// Writing the GDT to RAM failed.
WriteGDT,
/// Writing the IDT to RAM failed.
WriteIDT,
/// Writing PDPTE to RAM failed.
WritePDPTEAddress,
/// Writing PDE to RAM failed.
WritePDEAddress,
/// Writing PML4 to RAM failed.
WritePML4Address,
}
type Result<T> = std::result::Result<T, Error>;
/// Configure Floating-Point Unit (FPU) registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_fpu(vcpu: &VcpuFd) -> Result<()> {
let fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
vcpu.set_fpu(&fpu).map_err(Error::SetFPURegisters)
}
/// Configure base registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
/// * `boot_ip` - Starting instruction pointer.
pub fn setup_regs(vcpu: &VcpuFd, boot_ip: u64) -> Result<()> {
let regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: boot_ip,
// Frame pointer. It gets a snapshot of the stack pointer (rsp) so that when adjustments are
// made to rsp (i.e. reserving space for local variables or pushing values on to the stack),
// local variables and function parameters are still accessible from a constant offset from rbp.
rsp: super::layout::BOOT_STACK_POINTER as u64,
// Starting stack pointer.
rbp: super::layout::BOOT_STACK_POINTER as u64,
// Must point to zero page address per Linux ABI. This is x86_64 specific.
rsi: super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
vcpu.set_regs(®s).map_err(Error::SetBaseRegisters)
}
/// Configures the segment registers and system page tables for a given CPU.
///
/// # Arguments
///
/// * `mem` - The memory that will be passed to the guest.
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_sregs(mem: &GuestMemoryMmap, vcpu: &VcpuFd) -> Result<()> {
let mut sregs: kvm_sregs = vcpu.get_sregs().map_err(Error::GetStatusRegisters)?;
configure_segments_and_sregs(mem, &mut sregs)?;
setup_page_tables(mem, &mut sregs)?; // TODO(dgreid) - Can this be done once per system instead?
vcpu.set_sregs(&sregs).map_err(Error::SetStatusRegisters)
}
const BOOT_GDT_OFFSET: u64 = 0x500;
const BOOT_IDT_OFFSET: u64 = 0x520;
const BOOT_GDT_MAX: usize = 4;
const EFER_LMA: u64 = 0x400;
const EFER_LME: u64 = 0x100;
const X86_CR0_PE: u64 = 0x1;
const X86_CR0_PG: u64 = 0x8000_0000;
const X86_CR4_PAE: u64 = 0x20;
fn write_gdt_table(table: &[u64], guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_gdt_addr = GuestAddress(BOOT_GDT_OFFSET);
for (index, entry) in table.iter().enumerate() {
let addr = guest_mem
.checked_offset(boot_gdt_addr, index * mem::size_of::<u64>())
.ok_or(Error::WriteGDT)?;
guest_mem
.write_obj(*entry, addr)
.map_err(|_| Error::WriteGDT)?;
}
Ok(())
}
fn write_idt_value(val: u64, guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_idt_addr = GuestAddress(BOOT_IDT_OFFSET);
guest_mem
.write_obj(val, boot_idt_addr)
.map_err(|_| Error::WriteIDT)
}
fn configure_segments_and_sregs(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
let code_seg = kvm_segment_from_gdt(gdt_table[1], 1);
let data_seg = kvm_segment_from_gdt(gdt_table[2], 2);
let tss_seg = kvm_segment_from_gdt(gdt_table[3], 3);
// Write segments
write_gdt_table(&gdt_table[..], mem)?;
sregs.gdt.base = BOOT_GDT_OFFSET as u64;
sregs.gdt.limit = mem::size_of_val(&gdt_table) as u16 - 1;
write_idt_value(0, mem)?;
sregs.idt.base = BOOT_IDT_OFFSET as u64;
sregs.idt.limit = mem::size_of::<u64>() as u16 - 1;
sregs.cs = code_seg;
sregs.ds = data_seg;
sregs.es = data_seg;
sregs.fs = data_seg;
sregs.gs = data_seg;
sregs.ss = data_seg;
sregs.tr = tss_seg;
/* 64-bit protected mode */
sregs.cr0 |= X86_CR0_PE;
sregs.efer |= EFER_LME | EFER_LMA;
Ok(())
}
fn setup_page_tables(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
// Puts PML4 right after zero page but aligned to 4k.
let boot_pml4_addr = GuestAddress(PML4_START);
let boot_pdpte_addr = GuestAddress(PDPTE_START);
let boot_pde_addr = GuestAddress(PDE_START);
// Entry covering VA [0..512GB)
mem.write_obj(boot_pdpte_addr.raw_value() as u64 | 0x03, boot_pml4_addr)
.map_err(|_| Error::WritePML4Address)?;
// Entry covering VA [0..1GB)
mem.write_obj(boot_pde_addr.raw_value() as u64 | 0x03, boot_pdpte_addr)
.map_err(|_| Error::WritePDPTEAddress)?;
// 512 2MB entries together covering VA [0..1GB). Note we are assuming
// CPU supports 2MB pages (/proc/cpuinfo has 'pse'). All modern CPUs do.
for i in 0..512 {
mem.write_obj((i << 21) + 0x83u64, boot_pde_addr.unchecked_add(i * 8))
.map_err(|_| Error::WritePDEAddress)?;
}
sregs.cr3 = boot_pml4_addr.raw_value() as u64;
sregs.cr4 |= X86_CR4_PAE;
sregs.cr0 |= X86_CR0_PG;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use kvm_ioctls::Kvm;
use vm_memory::{Bytes, GuestAddress, GuestMemoryMmap};
fn create_guest_mem(mem_size: Option<u64>) -> GuestMemoryMmap {
let page_size = 0x10000usize;
let mem_size = mem_size.unwrap_or(page_size as u64) as usize;
if mem_size % page_size == 0 {
vm_memory::test_utils::create_anon_guest_memory(&[(GuestAddress(0), mem_size)], false)
.unwrap()
} else {
vm_memory::test_utils::create_guest_memory_unguarded(
&[(GuestAddress(0), mem_size)],
false,
)
.unwrap()
}
}
fn read_u64(gm: &GuestMemoryMmap, offset: u64) -> u64 {
let read_addr = GuestAddress(offset as u64);
gm.read_obj(read_addr).unwrap()
}
fn validate_segments_and_sregs(gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0x0, read_u64(&gm, BOOT_GDT_OFFSET));
assert_eq!(0xaf_9b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 8));
assert_eq!(0xcf_9300_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 16));
assert_eq!(0x8f_8b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 24));
assert_eq!(0x0, read_u64(&gm, BOOT_IDT_OFFSET));
assert_eq!(0, sregs.cs.base);
assert_eq!(0xfffff, sregs.ds.limit);
assert_eq!(0x10, sregs.es.selector);
assert_eq!(1, sregs.fs.present);
assert_eq!(1, sregs.gs.g);
assert_eq!(0, sregs.ss.avl);
assert_eq!(0, sregs.tr.base);
assert_eq!(0xfffff, sregs.tr.limit);
assert_eq!(0, sregs.tr.avl);
assert!(sregs.cr0 & X86_CR0_PE!= 0);
assert!(sregs.efer & EFER_LME!= 0 && sregs.efer & EFER_LMA!= 0);
}
fn | (gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0xa003, read_u64(&gm, PML4_START));
assert_eq!(0xb003, read_u64(&gm, PDPTE_START));
for i in 0..512 {
assert_eq!((i << 21) + 0x83u64, read_u64(&gm, PDE_START + (i * 8)));
}
assert_eq!(PML4_START as u64, sregs.cr3);
assert!(sregs.cr4 & X86_CR4_PAE!= 0);
assert!(sregs.cr0 & X86_CR0_PG!= 0);
}
#[test]
fn test_setup_fpu() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
setup_fpu(&vcpu).unwrap();
let expected_fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
let actual_fpu: kvm_fpu = vcpu.get_fpu().unwrap();
// TODO: auto-generate kvm related structures with PartialEq on.
assert_eq!(expected_fpu.fcw, actual_fpu.fcw);
// Setting the mxcsr register from kvm_fpu inside setup_fpu does not influence anything.
// See 'kvm_arch_vcpu_ioctl_set_fpu' from arch/x86/kvm/x86.c.
// The mxcsr will stay 0 and the assert below fails. Decide whether or not we should
// remove it at all.
// assert!(expected_fpu.mxcsr == actual_fpu.mxcsr);
}
#[test]
fn test_setup_regs() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let expected_regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: 1,
rsp: super::super::layout::BOOT_STACK_POINTER as u64,
rbp: super::super::layout::BOOT_STACK_POINTER as u64,
rsi: super::super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
setup_regs(&vcpu, expected_regs.rip).unwrap();
let actual_regs: kvm_regs = vcpu.get_regs().unwrap();
assert_eq!(actual_regs, expected_regs);
}
#[test]
fn test_setup_sregs() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let gm = create_guest_mem(None);
assert!(vcpu.set_sregs(&Default::default()).is_ok());
setup_sregs(&gm, &vcpu).unwrap();
let mut sregs: kvm_sregs = vcpu.get_sregs().unwrap();
// for AMD KVM_GET_SREGS returns g = 0 for each kvm_segment.
// We set it to 1, otherwise the test will fail.
sregs.gs.g = 1;
validate_segments_and_sregs(&gm, &sregs);
validate_page_tables(&gm, &sregs);
}
#[test]
fn test_write_gdt_table() {
// Not enough memory for the gdt table to be written.
let gm = create_guest_mem(Some(BOOT_GDT_OFFSET));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_err());
// We allocate exactly the amount needed to write four u64 to `BOOT_GDT_OFFSET`.
let gm = create_guest_mem(Some(
BOOT_GDT_OFFSET + (mem::size_of::<u64>() * BOOT_GDT_MAX) as u64,
));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_ok());
}
#[test]
fn test_write_idt_table() {
// Not enough memory for the a u64 value to fit.
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET));
let val = 0x100;
assert!(write_idt_value(val, &gm).is_err());
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET + mem::size_of::<u64>() as u64));
// We have allocated exactly the amount neded to write an u64 to `BOOT_IDT_OFFSET`.
assert!(write_idt_value(val, &gm).is_ok());
}
#[test]
fn test_configure_segments_and_sregs() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(None);
configure_segments_and_sregs(&gm, &mut sregs).unwrap();
validate_segments_and_sregs(&gm, &sregs);
}
#[test]
fn test_setup_page_tables() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(Some(PML4_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDPTE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(None);
setup_page_tables(&gm, &mut sregs).unwrap();
validate_page_tables(&gm, &sregs);
}
}
| validate_page_tables | identifier_name |
regs.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::mem;
use super::gdt::{gdt_entry, kvm_segment_from_gdt};
use kvm_bindings::{kvm_fpu, kvm_regs, kvm_sregs};
use kvm_ioctls::VcpuFd;
use vm_memory::{Address, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap};
// Initial pagetables.
const PML4_START: u64 = 0x9000;
const PDPTE_START: u64 = 0xa000;
const PDE_START: u64 = 0xb000;
/// Errors thrown while setting up x86_64 registers.
#[derive(Debug)]
pub enum Error {
/// Failed to get SREGs for this CPU.
GetStatusRegisters(kvm_ioctls::Error),
/// Failed to set base registers for this CPU.
SetBaseRegisters(kvm_ioctls::Error),
/// Failed to configure the FPU.
SetFPURegisters(kvm_ioctls::Error),
/// Failed to set SREGs for this CPU.
SetStatusRegisters(kvm_ioctls::Error),
/// Writing the GDT to RAM failed.
WriteGDT,
/// Writing the IDT to RAM failed.
WriteIDT,
/// Writing PDPTE to RAM failed.
WritePDPTEAddress,
/// Writing PDE to RAM failed.
WritePDEAddress,
/// Writing PML4 to RAM failed.
WritePML4Address,
}
type Result<T> = std::result::Result<T, Error>;
/// Configure Floating-Point Unit (FPU) registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_fpu(vcpu: &VcpuFd) -> Result<()> {
let fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
vcpu.set_fpu(&fpu).map_err(Error::SetFPURegisters)
}
/// Configure base registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
/// * `boot_ip` - Starting instruction pointer.
pub fn setup_regs(vcpu: &VcpuFd, boot_ip: u64) -> Result<()> {
let regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: boot_ip,
// Frame pointer. It gets a snapshot of the stack pointer (rsp) so that when adjustments are
// made to rsp (i.e. reserving space for local variables or pushing values on to the stack),
// local variables and function parameters are still accessible from a constant offset from rbp.
rsp: super::layout::BOOT_STACK_POINTER as u64,
// Starting stack pointer.
rbp: super::layout::BOOT_STACK_POINTER as u64,
// Must point to zero page address per Linux ABI. This is x86_64 specific.
rsi: super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
vcpu.set_regs(®s).map_err(Error::SetBaseRegisters)
}
/// Configures the segment registers and system page tables for a given CPU.
///
/// # Arguments
///
/// * `mem` - The memory that will be passed to the guest.
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_sregs(mem: &GuestMemoryMmap, vcpu: &VcpuFd) -> Result<()> {
let mut sregs: kvm_sregs = vcpu.get_sregs().map_err(Error::GetStatusRegisters)?;
configure_segments_and_sregs(mem, &mut sregs)?;
setup_page_tables(mem, &mut sregs)?; // TODO(dgreid) - Can this be done once per system instead?
vcpu.set_sregs(&sregs).map_err(Error::SetStatusRegisters)
}
const BOOT_GDT_OFFSET: u64 = 0x500;
const BOOT_IDT_OFFSET: u64 = 0x520;
const BOOT_GDT_MAX: usize = 4;
const EFER_LMA: u64 = 0x400;
const EFER_LME: u64 = 0x100;
const X86_CR0_PE: u64 = 0x1;
const X86_CR0_PG: u64 = 0x8000_0000;
const X86_CR4_PAE: u64 = 0x20;
fn write_gdt_table(table: &[u64], guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_gdt_addr = GuestAddress(BOOT_GDT_OFFSET);
for (index, entry) in table.iter().enumerate() {
let addr = guest_mem
.checked_offset(boot_gdt_addr, index * mem::size_of::<u64>())
.ok_or(Error::WriteGDT)?;
guest_mem
.write_obj(*entry, addr)
.map_err(|_| Error::WriteGDT)?;
}
Ok(())
}
fn write_idt_value(val: u64, guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_idt_addr = GuestAddress(BOOT_IDT_OFFSET);
guest_mem
.write_obj(val, boot_idt_addr)
.map_err(|_| Error::WriteIDT)
}
fn configure_segments_and_sregs(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
let code_seg = kvm_segment_from_gdt(gdt_table[1], 1);
let data_seg = kvm_segment_from_gdt(gdt_table[2], 2);
let tss_seg = kvm_segment_from_gdt(gdt_table[3], 3);
// Write segments
write_gdt_table(&gdt_table[..], mem)?;
sregs.gdt.base = BOOT_GDT_OFFSET as u64;
sregs.gdt.limit = mem::size_of_val(&gdt_table) as u16 - 1;
write_idt_value(0, mem)?;
sregs.idt.base = BOOT_IDT_OFFSET as u64;
sregs.idt.limit = mem::size_of::<u64>() as u16 - 1;
sregs.cs = code_seg;
sregs.ds = data_seg;
sregs.es = data_seg;
sregs.fs = data_seg;
sregs.gs = data_seg;
sregs.ss = data_seg;
sregs.tr = tss_seg;
/* 64-bit protected mode */
sregs.cr0 |= X86_CR0_PE;
sregs.efer |= EFER_LME | EFER_LMA;
Ok(())
}
fn setup_page_tables(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
// Puts PML4 right after zero page but aligned to 4k.
let boot_pml4_addr = GuestAddress(PML4_START);
let boot_pdpte_addr = GuestAddress(PDPTE_START);
let boot_pde_addr = GuestAddress(PDE_START);
// Entry covering VA [0..512GB)
mem.write_obj(boot_pdpte_addr.raw_value() as u64 | 0x03, boot_pml4_addr)
.map_err(|_| Error::WritePML4Address)?;
// Entry covering VA [0..1GB)
mem.write_obj(boot_pde_addr.raw_value() as u64 | 0x03, boot_pdpte_addr)
.map_err(|_| Error::WritePDPTEAddress)?;
// 512 2MB entries together covering VA [0..1GB). Note we are assuming
// CPU supports 2MB pages (/proc/cpuinfo has 'pse'). All modern CPUs do.
for i in 0..512 {
mem.write_obj((i << 21) + 0x83u64, boot_pde_addr.unchecked_add(i * 8))
.map_err(|_| Error::WritePDEAddress)?;
}
sregs.cr3 = boot_pml4_addr.raw_value() as u64;
sregs.cr4 |= X86_CR4_PAE;
sregs.cr0 |= X86_CR0_PG;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use kvm_ioctls::Kvm;
use vm_memory::{Bytes, GuestAddress, GuestMemoryMmap};
fn create_guest_mem(mem_size: Option<u64>) -> GuestMemoryMmap {
let page_size = 0x10000usize;
let mem_size = mem_size.unwrap_or(page_size as u64) as usize;
if mem_size % page_size == 0 {
vm_memory::test_utils::create_anon_guest_memory(&[(GuestAddress(0), mem_size)], false)
.unwrap()
} else {
vm_memory::test_utils::create_guest_memory_unguarded(
&[(GuestAddress(0), mem_size)],
false,
)
.unwrap()
}
}
fn read_u64(gm: &GuestMemoryMmap, offset: u64) -> u64 {
let read_addr = GuestAddress(offset as u64);
gm.read_obj(read_addr).unwrap()
}
fn validate_segments_and_sregs(gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0x0, read_u64(&gm, BOOT_GDT_OFFSET));
assert_eq!(0xaf_9b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 8));
assert_eq!(0xcf_9300_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 16));
assert_eq!(0x8f_8b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 24));
assert_eq!(0x0, read_u64(&gm, BOOT_IDT_OFFSET));
assert_eq!(0, sregs.cs.base);
assert_eq!(0xfffff, sregs.ds.limit);
assert_eq!(0x10, sregs.es.selector);
assert_eq!(1, sregs.fs.present);
assert_eq!(1, sregs.gs.g);
assert_eq!(0, sregs.ss.avl);
assert_eq!(0, sregs.tr.base);
assert_eq!(0xfffff, sregs.tr.limit);
assert_eq!(0, sregs.tr.avl);
assert!(sregs.cr0 & X86_CR0_PE!= 0);
assert!(sregs.efer & EFER_LME!= 0 && sregs.efer & EFER_LMA!= 0);
}
fn validate_page_tables(gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0xa003, read_u64(&gm, PML4_START));
assert_eq!(0xb003, read_u64(&gm, PDPTE_START));
for i in 0..512 {
assert_eq!((i << 21) + 0x83u64, read_u64(&gm, PDE_START + (i * 8)));
}
assert_eq!(PML4_START as u64, sregs.cr3);
assert!(sregs.cr4 & X86_CR4_PAE!= 0);
assert!(sregs.cr0 & X86_CR0_PG!= 0);
}
#[test]
fn test_setup_fpu() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
setup_fpu(&vcpu).unwrap();
let expected_fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
let actual_fpu: kvm_fpu = vcpu.get_fpu().unwrap();
// TODO: auto-generate kvm related structures with PartialEq on.
assert_eq!(expected_fpu.fcw, actual_fpu.fcw);
// Setting the mxcsr register from kvm_fpu inside setup_fpu does not influence anything.
// See 'kvm_arch_vcpu_ioctl_set_fpu' from arch/x86/kvm/x86.c.
// The mxcsr will stay 0 and the assert below fails. Decide whether or not we should
// remove it at all.
// assert!(expected_fpu.mxcsr == actual_fpu.mxcsr);
}
#[test]
fn test_setup_regs() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let expected_regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: 1,
rsp: super::super::layout::BOOT_STACK_POINTER as u64,
rbp: super::super::layout::BOOT_STACK_POINTER as u64,
rsi: super::super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
setup_regs(&vcpu, expected_regs.rip).unwrap();
let actual_regs: kvm_regs = vcpu.get_regs().unwrap();
assert_eq!(actual_regs, expected_regs);
}
#[test]
fn test_setup_sregs() { |
assert!(vcpu.set_sregs(&Default::default()).is_ok());
setup_sregs(&gm, &vcpu).unwrap();
let mut sregs: kvm_sregs = vcpu.get_sregs().unwrap();
// for AMD KVM_GET_SREGS returns g = 0 for each kvm_segment.
// We set it to 1, otherwise the test will fail.
sregs.gs.g = 1;
validate_segments_and_sregs(&gm, &sregs);
validate_page_tables(&gm, &sregs);
}
#[test]
fn test_write_gdt_table() {
// Not enough memory for the gdt table to be written.
let gm = create_guest_mem(Some(BOOT_GDT_OFFSET));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_err());
// We allocate exactly the amount needed to write four u64 to `BOOT_GDT_OFFSET`.
let gm = create_guest_mem(Some(
BOOT_GDT_OFFSET + (mem::size_of::<u64>() * BOOT_GDT_MAX) as u64,
));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_ok());
}
#[test]
fn test_write_idt_table() {
// Not enough memory for the a u64 value to fit.
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET));
let val = 0x100;
assert!(write_idt_value(val, &gm).is_err());
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET + mem::size_of::<u64>() as u64));
// We have allocated exactly the amount neded to write an u64 to `BOOT_IDT_OFFSET`.
assert!(write_idt_value(val, &gm).is_ok());
}
#[test]
fn test_configure_segments_and_sregs() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(None);
configure_segments_and_sregs(&gm, &mut sregs).unwrap();
validate_segments_and_sregs(&gm, &sregs);
}
#[test]
fn test_setup_page_tables() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(Some(PML4_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDPTE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(None);
setup_page_tables(&gm, &mut sregs).unwrap();
validate_page_tables(&gm, &sregs);
}
} | let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let gm = create_guest_mem(None); | random_line_split |
regs.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::mem;
use super::gdt::{gdt_entry, kvm_segment_from_gdt};
use kvm_bindings::{kvm_fpu, kvm_regs, kvm_sregs};
use kvm_ioctls::VcpuFd;
use vm_memory::{Address, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap};
// Initial pagetables.
const PML4_START: u64 = 0x9000;
const PDPTE_START: u64 = 0xa000;
const PDE_START: u64 = 0xb000;
/// Errors thrown while setting up x86_64 registers.
#[derive(Debug)]
pub enum Error {
/// Failed to get SREGs for this CPU.
GetStatusRegisters(kvm_ioctls::Error),
/// Failed to set base registers for this CPU.
SetBaseRegisters(kvm_ioctls::Error),
/// Failed to configure the FPU.
SetFPURegisters(kvm_ioctls::Error),
/// Failed to set SREGs for this CPU.
SetStatusRegisters(kvm_ioctls::Error),
/// Writing the GDT to RAM failed.
WriteGDT,
/// Writing the IDT to RAM failed.
WriteIDT,
/// Writing PDPTE to RAM failed.
WritePDPTEAddress,
/// Writing PDE to RAM failed.
WritePDEAddress,
/// Writing PML4 to RAM failed.
WritePML4Address,
}
type Result<T> = std::result::Result<T, Error>;
/// Configure Floating-Point Unit (FPU) registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_fpu(vcpu: &VcpuFd) -> Result<()> {
let fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
vcpu.set_fpu(&fpu).map_err(Error::SetFPURegisters)
}
/// Configure base registers for a given CPU.
///
/// # Arguments
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
/// * `boot_ip` - Starting instruction pointer.
pub fn setup_regs(vcpu: &VcpuFd, boot_ip: u64) -> Result<()> |
/// Configures the segment registers and system page tables for a given CPU.
///
/// # Arguments
///
/// * `mem` - The memory that will be passed to the guest.
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_sregs(mem: &GuestMemoryMmap, vcpu: &VcpuFd) -> Result<()> {
let mut sregs: kvm_sregs = vcpu.get_sregs().map_err(Error::GetStatusRegisters)?;
configure_segments_and_sregs(mem, &mut sregs)?;
setup_page_tables(mem, &mut sregs)?; // TODO(dgreid) - Can this be done once per system instead?
vcpu.set_sregs(&sregs).map_err(Error::SetStatusRegisters)
}
const BOOT_GDT_OFFSET: u64 = 0x500;
const BOOT_IDT_OFFSET: u64 = 0x520;
const BOOT_GDT_MAX: usize = 4;
const EFER_LMA: u64 = 0x400;
const EFER_LME: u64 = 0x100;
const X86_CR0_PE: u64 = 0x1;
const X86_CR0_PG: u64 = 0x8000_0000;
const X86_CR4_PAE: u64 = 0x20;
fn write_gdt_table(table: &[u64], guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_gdt_addr = GuestAddress(BOOT_GDT_OFFSET);
for (index, entry) in table.iter().enumerate() {
let addr = guest_mem
.checked_offset(boot_gdt_addr, index * mem::size_of::<u64>())
.ok_or(Error::WriteGDT)?;
guest_mem
.write_obj(*entry, addr)
.map_err(|_| Error::WriteGDT)?;
}
Ok(())
}
fn write_idt_value(val: u64, guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_idt_addr = GuestAddress(BOOT_IDT_OFFSET);
guest_mem
.write_obj(val, boot_idt_addr)
.map_err(|_| Error::WriteIDT)
}
fn configure_segments_and_sregs(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
let code_seg = kvm_segment_from_gdt(gdt_table[1], 1);
let data_seg = kvm_segment_from_gdt(gdt_table[2], 2);
let tss_seg = kvm_segment_from_gdt(gdt_table[3], 3);
// Write segments
write_gdt_table(&gdt_table[..], mem)?;
sregs.gdt.base = BOOT_GDT_OFFSET as u64;
sregs.gdt.limit = mem::size_of_val(&gdt_table) as u16 - 1;
write_idt_value(0, mem)?;
sregs.idt.base = BOOT_IDT_OFFSET as u64;
sregs.idt.limit = mem::size_of::<u64>() as u16 - 1;
sregs.cs = code_seg;
sregs.ds = data_seg;
sregs.es = data_seg;
sregs.fs = data_seg;
sregs.gs = data_seg;
sregs.ss = data_seg;
sregs.tr = tss_seg;
/* 64-bit protected mode */
sregs.cr0 |= X86_CR0_PE;
sregs.efer |= EFER_LME | EFER_LMA;
Ok(())
}
fn setup_page_tables(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
// Puts PML4 right after zero page but aligned to 4k.
let boot_pml4_addr = GuestAddress(PML4_START);
let boot_pdpte_addr = GuestAddress(PDPTE_START);
let boot_pde_addr = GuestAddress(PDE_START);
// Entry covering VA [0..512GB)
mem.write_obj(boot_pdpte_addr.raw_value() as u64 | 0x03, boot_pml4_addr)
.map_err(|_| Error::WritePML4Address)?;
// Entry covering VA [0..1GB)
mem.write_obj(boot_pde_addr.raw_value() as u64 | 0x03, boot_pdpte_addr)
.map_err(|_| Error::WritePDPTEAddress)?;
// 512 2MB entries together covering VA [0..1GB). Note we are assuming
// CPU supports 2MB pages (/proc/cpuinfo has 'pse'). All modern CPUs do.
for i in 0..512 {
mem.write_obj((i << 21) + 0x83u64, boot_pde_addr.unchecked_add(i * 8))
.map_err(|_| Error::WritePDEAddress)?;
}
sregs.cr3 = boot_pml4_addr.raw_value() as u64;
sregs.cr4 |= X86_CR4_PAE;
sregs.cr0 |= X86_CR0_PG;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use kvm_ioctls::Kvm;
use vm_memory::{Bytes, GuestAddress, GuestMemoryMmap};
fn create_guest_mem(mem_size: Option<u64>) -> GuestMemoryMmap {
let page_size = 0x10000usize;
let mem_size = mem_size.unwrap_or(page_size as u64) as usize;
if mem_size % page_size == 0 {
vm_memory::test_utils::create_anon_guest_memory(&[(GuestAddress(0), mem_size)], false)
.unwrap()
} else {
vm_memory::test_utils::create_guest_memory_unguarded(
&[(GuestAddress(0), mem_size)],
false,
)
.unwrap()
}
}
fn read_u64(gm: &GuestMemoryMmap, offset: u64) -> u64 {
let read_addr = GuestAddress(offset as u64);
gm.read_obj(read_addr).unwrap()
}
fn validate_segments_and_sregs(gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0x0, read_u64(&gm, BOOT_GDT_OFFSET));
assert_eq!(0xaf_9b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 8));
assert_eq!(0xcf_9300_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 16));
assert_eq!(0x8f_8b00_0000_ffff, read_u64(&gm, BOOT_GDT_OFFSET + 24));
assert_eq!(0x0, read_u64(&gm, BOOT_IDT_OFFSET));
assert_eq!(0, sregs.cs.base);
assert_eq!(0xfffff, sregs.ds.limit);
assert_eq!(0x10, sregs.es.selector);
assert_eq!(1, sregs.fs.present);
assert_eq!(1, sregs.gs.g);
assert_eq!(0, sregs.ss.avl);
assert_eq!(0, sregs.tr.base);
assert_eq!(0xfffff, sregs.tr.limit);
assert_eq!(0, sregs.tr.avl);
assert!(sregs.cr0 & X86_CR0_PE!= 0);
assert!(sregs.efer & EFER_LME!= 0 && sregs.efer & EFER_LMA!= 0);
}
fn validate_page_tables(gm: &GuestMemoryMmap, sregs: &kvm_sregs) {
assert_eq!(0xa003, read_u64(&gm, PML4_START));
assert_eq!(0xb003, read_u64(&gm, PDPTE_START));
for i in 0..512 {
assert_eq!((i << 21) + 0x83u64, read_u64(&gm, PDE_START + (i * 8)));
}
assert_eq!(PML4_START as u64, sregs.cr3);
assert!(sregs.cr4 & X86_CR4_PAE!= 0);
assert!(sregs.cr0 & X86_CR0_PG!= 0);
}
#[test]
fn test_setup_fpu() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
setup_fpu(&vcpu).unwrap();
let expected_fpu: kvm_fpu = kvm_fpu {
fcw: 0x37f,
mxcsr: 0x1f80,
..Default::default()
};
let actual_fpu: kvm_fpu = vcpu.get_fpu().unwrap();
// TODO: auto-generate kvm related structures with PartialEq on.
assert_eq!(expected_fpu.fcw, actual_fpu.fcw);
// Setting the mxcsr register from kvm_fpu inside setup_fpu does not influence anything.
// See 'kvm_arch_vcpu_ioctl_set_fpu' from arch/x86/kvm/x86.c.
// The mxcsr will stay 0 and the assert below fails. Decide whether or not we should
// remove it at all.
// assert!(expected_fpu.mxcsr == actual_fpu.mxcsr);
}
#[test]
fn test_setup_regs() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let expected_regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: 1,
rsp: super::super::layout::BOOT_STACK_POINTER as u64,
rbp: super::super::layout::BOOT_STACK_POINTER as u64,
rsi: super::super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
setup_regs(&vcpu, expected_regs.rip).unwrap();
let actual_regs: kvm_regs = vcpu.get_regs().unwrap();
assert_eq!(actual_regs, expected_regs);
}
#[test]
fn test_setup_sregs() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
let vcpu = vm.create_vcpu(0).unwrap();
let gm = create_guest_mem(None);
assert!(vcpu.set_sregs(&Default::default()).is_ok());
setup_sregs(&gm, &vcpu).unwrap();
let mut sregs: kvm_sregs = vcpu.get_sregs().unwrap();
// for AMD KVM_GET_SREGS returns g = 0 for each kvm_segment.
// We set it to 1, otherwise the test will fail.
sregs.gs.g = 1;
validate_segments_and_sregs(&gm, &sregs);
validate_page_tables(&gm, &sregs);
}
#[test]
fn test_write_gdt_table() {
// Not enough memory for the gdt table to be written.
let gm = create_guest_mem(Some(BOOT_GDT_OFFSET));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_err());
// We allocate exactly the amount needed to write four u64 to `BOOT_GDT_OFFSET`.
let gm = create_guest_mem(Some(
BOOT_GDT_OFFSET + (mem::size_of::<u64>() * BOOT_GDT_MAX) as u64,
));
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
assert!(write_gdt_table(&gdt_table, &gm).is_ok());
}
#[test]
fn test_write_idt_table() {
// Not enough memory for the a u64 value to fit.
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET));
let val = 0x100;
assert!(write_idt_value(val, &gm).is_err());
let gm = create_guest_mem(Some(BOOT_IDT_OFFSET + mem::size_of::<u64>() as u64));
// We have allocated exactly the amount neded to write an u64 to `BOOT_IDT_OFFSET`.
assert!(write_idt_value(val, &gm).is_ok());
}
#[test]
fn test_configure_segments_and_sregs() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(None);
configure_segments_and_sregs(&gm, &mut sregs).unwrap();
validate_segments_and_sregs(&gm, &sregs);
}
#[test]
fn test_setup_page_tables() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem(Some(PML4_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDPTE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(Some(PDE_START));
assert!(setup_page_tables(&gm, &mut sregs).is_err());
let gm = create_guest_mem(None);
setup_page_tables(&gm, &mut sregs).unwrap();
validate_page_tables(&gm, &sregs);
}
}
| {
let regs: kvm_regs = kvm_regs {
rflags: 0x0000_0000_0000_0002u64,
rip: boot_ip,
// Frame pointer. It gets a snapshot of the stack pointer (rsp) so that when adjustments are
// made to rsp (i.e. reserving space for local variables or pushing values on to the stack),
// local variables and function parameters are still accessible from a constant offset from rbp.
rsp: super::layout::BOOT_STACK_POINTER as u64,
// Starting stack pointer.
rbp: super::layout::BOOT_STACK_POINTER as u64,
// Must point to zero page address per Linux ABI. This is x86_64 specific.
rsi: super::layout::ZERO_PAGE_START as u64,
..Default::default()
};
vcpu.set_regs(®s).map_err(Error::SetBaseRegisters)
} | identifier_body |
main.rs | #![deny(warnings)]
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate regex;
extern crate term;
extern crate binunit;
use std::io::prelude::*;
fn main() {
let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap());
match binunit.run() {
Ok(mut output) =>
print(&mut output)
,
Err(err) =>
println!("{}\nbinunit failed", err)
}
}
pub fn print(output: &mut Vec<String>) | }
fn print_result_colorized(output: &String) {
let mut term = term::stdout().unwrap();
for capture in regex!(r"(?m)(.*: )(ok|failed)(.*)|.*").captures_iter(output) {
match capture.at(2).unwrap_or("") {
"ok" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
"failed" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
_ => writeln!(term, "{}\n", capture.at(0).unwrap()).unwrap()
}
}
}
fn increment_summary((total, pass, fail): (i32, i32, i32), result: &String) -> (i32, i32, i32) {
if result.contains(": ok") {
(total+1, pass+1, fail)
} else if result.contains(": failed") {
(total+1, pass, fail+1)
} else {
(total, pass, fail)
}
}
fn print_summary(&(_, pass, fail): &(i32, i32, i32)) {
let mut term = term::stdout().unwrap();
write!(term, "\n\n\t").unwrap();
match fail {
0 => {
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "ok").unwrap()
},
_ => {
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "failed").unwrap();
}
}
term.reset().unwrap();
writeln!(term, " -- {} passed, {} failed\n", pass, fail).unwrap();
}
| {
let summary = output.iter()
.fold((0, 0, 0), |a, b| increment_summary(a, b));
output.sort();
println!("");
for item in output.iter().filter(|item| item.contains(": ok")) {
print_result_colorized(&item.trim().to_owned());
}
println!("\n");
for item in output.iter().filter(|item| item.contains(": failed")) {
print_result_colorized(&item.trim().to_owned());
}
print_summary(&summary); | identifier_body |
main.rs | #![deny(warnings)]
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate regex;
extern crate term;
extern crate binunit;
use std::io::prelude::*;
fn main() {
let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap());
match binunit.run() {
Ok(mut output) =>
print(&mut output)
,
Err(err) =>
println!("{}\nbinunit failed", err)
}
}
pub fn | (output: &mut Vec<String>) {
let summary = output.iter()
.fold((0, 0, 0), |a, b| increment_summary(a, b));
output.sort();
println!("");
for item in output.iter().filter(|item| item.contains(": ok")) {
print_result_colorized(&item.trim().to_owned());
}
println!("\n");
for item in output.iter().filter(|item| item.contains(": failed")) {
print_result_colorized(&item.trim().to_owned());
}
print_summary(&summary);
}
fn print_result_colorized(output: &String) {
let mut term = term::stdout().unwrap();
for capture in regex!(r"(?m)(.*: )(ok|failed)(.*)|.*").captures_iter(output) {
match capture.at(2).unwrap_or("") {
"ok" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
"failed" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
_ => writeln!(term, "{}\n", capture.at(0).unwrap()).unwrap()
}
}
}
fn increment_summary((total, pass, fail): (i32, i32, i32), result: &String) -> (i32, i32, i32) {
if result.contains(": ok") {
(total+1, pass+1, fail)
} else if result.contains(": failed") {
(total+1, pass, fail+1)
} else {
(total, pass, fail)
}
}
fn print_summary(&(_, pass, fail): &(i32, i32, i32)) {
let mut term = term::stdout().unwrap();
write!(term, "\n\n\t").unwrap();
match fail {
0 => {
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "ok").unwrap()
},
_ => {
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "failed").unwrap();
}
}
term.reset().unwrap();
writeln!(term, " -- {} passed, {} failed\n", pass, fail).unwrap();
}
| print | identifier_name |
main.rs | #![deny(warnings)]
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate regex;
extern crate term;
extern crate binunit;
use std::io::prelude::*;
fn main() {
let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap());
match binunit.run() {
Ok(mut output) =>
print(&mut output)
,
Err(err) =>
println!("{}\nbinunit failed", err)
}
}
pub fn print(output: &mut Vec<String>) {
let summary = output.iter()
.fold((0, 0, 0), |a, b| increment_summary(a, b));
output.sort();
println!("");
for item in output.iter().filter(|item| item.contains(": ok")) {
print_result_colorized(&item.trim().to_owned());
}
println!("\n");
for item in output.iter().filter(|item| item.contains(": failed")) {
print_result_colorized(&item.trim().to_owned());
}
print_summary(&summary);
}
fn print_result_colorized(output: &String) {
let mut term = term::stdout().unwrap();
for capture in regex!(r"(?m)(.*: )(ok|failed)(.*)|.*").captures_iter(output) {
match capture.at(2).unwrap_or("") {
"ok" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
"failed" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
_ => writeln!(term, "{}\n", capture.at(0).unwrap()).unwrap()
}
}
}
fn increment_summary((total, pass, fail): (i32, i32, i32), result: &String) -> (i32, i32, i32) {
if result.contains(": ok") {
(total+1, pass+1, fail)
} else if result.contains(": failed") {
(total+1, pass, fail+1)
} else |
}
fn print_summary(&(_, pass, fail): &(i32, i32, i32)) {
let mut term = term::stdout().unwrap();
write!(term, "\n\n\t").unwrap();
match fail {
0 => {
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "ok").unwrap()
},
_ => {
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "failed").unwrap();
}
}
term.reset().unwrap();
writeln!(term, " -- {} passed, {} failed\n", pass, fail).unwrap();
}
| {
(total, pass, fail)
} | conditional_block |
main.rs | #![deny(warnings)]
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate regex;
extern crate term;
extern crate binunit;
use std::io::prelude::*;
fn main() {
let binunit = binunit::BinUnit::new(&std::env::current_dir().unwrap());
match binunit.run() {
Ok(mut output) =>
print(&mut output)
,
Err(err) =>
println!("{}\nbinunit failed", err)
}
}
pub fn print(output: &mut Vec<String>) {
let summary = output.iter()
.fold((0, 0, 0), |a, b| increment_summary(a, b));
output.sort();
println!("");
for item in output.iter().filter(|item| item.contains(": ok")) {
print_result_colorized(&item.trim().to_owned());
}
println!("\n");
for item in output.iter().filter(|item| item.contains(": failed")) {
print_result_colorized(&item.trim().to_owned());
}
print_summary(&summary); | fn print_result_colorized(output: &String) {
let mut term = term::stdout().unwrap();
for capture in regex!(r"(?m)(.*: )(ok|failed)(.*)|.*").captures_iter(output) {
match capture.at(2).unwrap_or("") {
"ok" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
"failed" => {
write!(term, "{}", capture.at(1).unwrap()).unwrap();
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "{}", capture.at(2).unwrap()).unwrap();
term.reset().unwrap();
writeln!(term, "{}", capture.at(3).unwrap()).unwrap();
},
_ => writeln!(term, "{}\n", capture.at(0).unwrap()).unwrap()
}
}
}
fn increment_summary((total, pass, fail): (i32, i32, i32), result: &String) -> (i32, i32, i32) {
if result.contains(": ok") {
(total+1, pass+1, fail)
} else if result.contains(": failed") {
(total+1, pass, fail+1)
} else {
(total, pass, fail)
}
}
fn print_summary(&(_, pass, fail): &(i32, i32, i32)) {
let mut term = term::stdout().unwrap();
write!(term, "\n\n\t").unwrap();
match fail {
0 => {
term.fg(term::color::BRIGHT_GREEN).unwrap();
write!(term, "ok").unwrap()
},
_ => {
term.fg(term::color::BRIGHT_RED).unwrap();
write!(term, "failed").unwrap();
}
}
term.reset().unwrap();
writeln!(term, " -- {} passed, {} failed\n", pass, fail).unwrap();
} | }
| random_line_split |
origin.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use servo_rand;
use std::cell::RefCell;
use std::rc::Rc;
use url::{Host, Origin};
use url_serde;
use uuid::Uuid;
/// The origin of an URL
#[derive(Clone, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum ImmutableOrigin {
/// A globally unique identifier
Opaque(OpaqueOrigin),
/// Consists of the URL's scheme, host and port
Tuple(
String,
#[serde(deserialize_with = "url_serde::deserialize", serialize_with = "url_serde::serialize")]
Host,
u16,
)
}
impl ImmutableOrigin {
pub fn new(origin: Origin) -> ImmutableOrigin {
match origin {
Origin::Opaque(_) => ImmutableOrigin::new_opaque(),
Origin::Tuple(scheme, host, port) => ImmutableOrigin::Tuple(scheme, host, port),
}
}
pub fn | (&self, other: &MutableOrigin) -> bool {
self == other.immutable()
}
pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
!other.has_domain() && self == other.immutable()
}
/// Creates a new opaque origin that is only equal to itself.
pub fn new_opaque() -> ImmutableOrigin {
ImmutableOrigin::Opaque(OpaqueOrigin(servo_rand::random_uuid()))
}
pub fn scheme(&self) -> Option<&str> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(ref scheme, _, _) => Some(&**scheme),
}
}
pub fn host(&self) -> Option<&Host> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(_, ref host, _) => Some(host),
}
}
pub fn port(&self) -> Option<u16> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(_, _, port) => Some(port),
}
}
pub fn into_url_origin(self) -> Origin {
match self {
ImmutableOrigin::Opaque(_) => Origin::new_opaque(),
ImmutableOrigin::Tuple(scheme, host, port) => Origin::Tuple(scheme, host, port),
}
}
/// Return whether this origin is a (scheme, host, port) tuple
/// (as opposed to an opaque origin).
pub fn is_tuple(&self) -> bool {
match *self {
ImmutableOrigin::Opaque(..) => false,
ImmutableOrigin::Tuple(..) => true,
}
}
/// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin>
pub fn ascii_serialization(&self) -> String {
self.clone().into_url_origin().ascii_serialization()
}
/// <https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin>
pub fn unicode_serialization(&self) -> String {
self.clone().into_url_origin().unicode_serialization()
}
}
/// Opaque identifier for URLs that have file or other schemes
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct OpaqueOrigin(Uuid);
malloc_size_of_is_0!(OpaqueOrigin);
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
#[derive(Clone, Debug)]
pub struct MutableOrigin(Rc<(ImmutableOrigin, RefCell<Option<Host>>)>);
malloc_size_of_is_0!(MutableOrigin);
impl MutableOrigin {
pub fn new(origin: ImmutableOrigin) -> MutableOrigin {
MutableOrigin(Rc::new((origin, RefCell::new(None))))
}
pub fn immutable(&self) -> &ImmutableOrigin {
&(self.0).0
}
pub fn is_tuple(&self) -> bool {
self.immutable().is_tuple()
}
pub fn scheme(&self) -> Option<&str> {
self.immutable().scheme()
}
pub fn host(&self) -> Option<&Host> {
self.immutable().host()
}
pub fn port(&self) -> Option<u16> {
self.immutable().port()
}
pub fn same_origin(&self, other: &MutableOrigin) -> bool {
self.immutable() == other.immutable()
}
pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
if let Some(ref self_domain) = *(self.0).1.borrow() {
if let Some(ref other_domain) = *(other.0).1.borrow() {
self_domain == other_domain &&
self.immutable().scheme() == other.immutable().scheme()
} else {
false
}
} else {
self.immutable().same_origin_domain(other)
}
}
pub fn domain(&self) -> Option<Host> {
(self.0).1.borrow().clone()
}
pub fn set_domain(&self, domain: Host) {
*(self.0).1.borrow_mut() = Some(domain);
}
pub fn has_domain(&self) -> bool {
(self.0).1.borrow().is_some()
}
pub fn effective_domain(&self) -> Option<Host> {
self.immutable().host()
.map(|host| self.domain().unwrap_or_else(|| host.clone()))
}
}
| same_origin | identifier_name |
origin.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use servo_rand;
use std::cell::RefCell;
use std::rc::Rc;
use url::{Host, Origin};
use url_serde;
use uuid::Uuid;
/// The origin of an URL
#[derive(Clone, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum ImmutableOrigin {
/// A globally unique identifier
Opaque(OpaqueOrigin),
/// Consists of the URL's scheme, host and port
Tuple(
String,
#[serde(deserialize_with = "url_serde::deserialize", serialize_with = "url_serde::serialize")]
Host,
u16,
)
}
impl ImmutableOrigin {
pub fn new(origin: Origin) -> ImmutableOrigin {
match origin {
Origin::Opaque(_) => ImmutableOrigin::new_opaque(),
Origin::Tuple(scheme, host, port) => ImmutableOrigin::Tuple(scheme, host, port),
}
}
pub fn same_origin(&self, other: &MutableOrigin) -> bool {
self == other.immutable()
}
pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
!other.has_domain() && self == other.immutable()
}
/// Creates a new opaque origin that is only equal to itself.
pub fn new_opaque() -> ImmutableOrigin {
ImmutableOrigin::Opaque(OpaqueOrigin(servo_rand::random_uuid()))
}
pub fn scheme(&self) -> Option<&str> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(ref scheme, _, _) => Some(&**scheme),
}
}
pub fn host(&self) -> Option<&Host> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(_, ref host, _) => Some(host),
}
}
pub fn port(&self) -> Option<u16> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(_, _, port) => Some(port),
}
}
pub fn into_url_origin(self) -> Origin {
match self {
ImmutableOrigin::Opaque(_) => Origin::new_opaque(),
ImmutableOrigin::Tuple(scheme, host, port) => Origin::Tuple(scheme, host, port),
}
}
/// Return whether this origin is a (scheme, host, port) tuple
/// (as opposed to an opaque origin).
pub fn is_tuple(&self) -> bool |
/// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin>
pub fn ascii_serialization(&self) -> String {
self.clone().into_url_origin().ascii_serialization()
}
/// <https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin>
pub fn unicode_serialization(&self) -> String {
self.clone().into_url_origin().unicode_serialization()
}
}
/// Opaque identifier for URLs that have file or other schemes
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct OpaqueOrigin(Uuid);
malloc_size_of_is_0!(OpaqueOrigin);
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
#[derive(Clone, Debug)]
pub struct MutableOrigin(Rc<(ImmutableOrigin, RefCell<Option<Host>>)>);
malloc_size_of_is_0!(MutableOrigin);
impl MutableOrigin {
pub fn new(origin: ImmutableOrigin) -> MutableOrigin {
MutableOrigin(Rc::new((origin, RefCell::new(None))))
}
pub fn immutable(&self) -> &ImmutableOrigin {
&(self.0).0
}
pub fn is_tuple(&self) -> bool {
self.immutable().is_tuple()
}
pub fn scheme(&self) -> Option<&str> {
self.immutable().scheme()
}
pub fn host(&self) -> Option<&Host> {
self.immutable().host()
}
pub fn port(&self) -> Option<u16> {
self.immutable().port()
}
pub fn same_origin(&self, other: &MutableOrigin) -> bool {
self.immutable() == other.immutable()
}
pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
if let Some(ref self_domain) = *(self.0).1.borrow() {
if let Some(ref other_domain) = *(other.0).1.borrow() {
self_domain == other_domain &&
self.immutable().scheme() == other.immutable().scheme()
} else {
false
}
} else {
self.immutable().same_origin_domain(other)
}
}
pub fn domain(&self) -> Option<Host> {
(self.0).1.borrow().clone()
}
pub fn set_domain(&self, domain: Host) {
*(self.0).1.borrow_mut() = Some(domain);
}
pub fn has_domain(&self) -> bool {
(self.0).1.borrow().is_some()
}
pub fn effective_domain(&self) -> Option<Host> {
self.immutable().host()
.map(|host| self.domain().unwrap_or_else(|| host.clone()))
}
}
| {
match *self {
ImmutableOrigin::Opaque(..) => false,
ImmutableOrigin::Tuple(..) => true,
}
} | identifier_body |
origin.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use servo_rand;
use std::cell::RefCell;
use std::rc::Rc;
use url::{Host, Origin};
use url_serde;
use uuid::Uuid;
/// The origin of an URL
#[derive(Clone, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum ImmutableOrigin {
/// A globally unique identifier
Opaque(OpaqueOrigin),
/// Consists of the URL's scheme, host and port
Tuple(
String,
#[serde(deserialize_with = "url_serde::deserialize", serialize_with = "url_serde::serialize")]
Host,
u16,
)
}
impl ImmutableOrigin {
pub fn new(origin: Origin) -> ImmutableOrigin {
match origin {
Origin::Opaque(_) => ImmutableOrigin::new_opaque(),
Origin::Tuple(scheme, host, port) => ImmutableOrigin::Tuple(scheme, host, port),
}
}
pub fn same_origin(&self, other: &MutableOrigin) -> bool {
self == other.immutable()
}
pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
!other.has_domain() && self == other.immutable()
}
/// Creates a new opaque origin that is only equal to itself.
pub fn new_opaque() -> ImmutableOrigin {
ImmutableOrigin::Opaque(OpaqueOrigin(servo_rand::random_uuid()))
}
pub fn scheme(&self) -> Option<&str> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(ref scheme, _, _) => Some(&**scheme),
} | ImmutableOrigin::Tuple(_, ref host, _) => Some(host),
}
}
pub fn port(&self) -> Option<u16> {
match *self {
ImmutableOrigin::Opaque(_) => None,
ImmutableOrigin::Tuple(_, _, port) => Some(port),
}
}
pub fn into_url_origin(self) -> Origin {
match self {
ImmutableOrigin::Opaque(_) => Origin::new_opaque(),
ImmutableOrigin::Tuple(scheme, host, port) => Origin::Tuple(scheme, host, port),
}
}
/// Return whether this origin is a (scheme, host, port) tuple
/// (as opposed to an opaque origin).
pub fn is_tuple(&self) -> bool {
match *self {
ImmutableOrigin::Opaque(..) => false,
ImmutableOrigin::Tuple(..) => true,
}
}
/// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin>
pub fn ascii_serialization(&self) -> String {
self.clone().into_url_origin().ascii_serialization()
}
/// <https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin>
pub fn unicode_serialization(&self) -> String {
self.clone().into_url_origin().unicode_serialization()
}
}
/// Opaque identifier for URLs that have file or other schemes
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct OpaqueOrigin(Uuid);
malloc_size_of_is_0!(OpaqueOrigin);
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
#[derive(Clone, Debug)]
pub struct MutableOrigin(Rc<(ImmutableOrigin, RefCell<Option<Host>>)>);
malloc_size_of_is_0!(MutableOrigin);
impl MutableOrigin {
pub fn new(origin: ImmutableOrigin) -> MutableOrigin {
MutableOrigin(Rc::new((origin, RefCell::new(None))))
}
pub fn immutable(&self) -> &ImmutableOrigin {
&(self.0).0
}
pub fn is_tuple(&self) -> bool {
self.immutable().is_tuple()
}
pub fn scheme(&self) -> Option<&str> {
self.immutable().scheme()
}
pub fn host(&self) -> Option<&Host> {
self.immutable().host()
}
pub fn port(&self) -> Option<u16> {
self.immutable().port()
}
pub fn same_origin(&self, other: &MutableOrigin) -> bool {
self.immutable() == other.immutable()
}
pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
if let Some(ref self_domain) = *(self.0).1.borrow() {
if let Some(ref other_domain) = *(other.0).1.borrow() {
self_domain == other_domain &&
self.immutable().scheme() == other.immutable().scheme()
} else {
false
}
} else {
self.immutable().same_origin_domain(other)
}
}
pub fn domain(&self) -> Option<Host> {
(self.0).1.borrow().clone()
}
pub fn set_domain(&self, domain: Host) {
*(self.0).1.borrow_mut() = Some(domain);
}
pub fn has_domain(&self) -> bool {
(self.0).1.borrow().is_some()
}
pub fn effective_domain(&self) -> Option<Host> {
self.immutable().host()
.map(|host| self.domain().unwrap_or_else(|| host.clone()))
}
} | }
pub fn host(&self) -> Option<&Host> {
match *self {
ImmutableOrigin::Opaque(_) => None, | random_line_split |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Bloom operations.
extern crate bigint;
use bigint::{H64, H160, H256, H512, H520, H2048};
use std::mem;
use std::ops::DerefMut;
/// Returns log2.
pub fn log2(x: usize) -> u32 {
if x <= 1 |
let n = x.leading_zeros();
mem::size_of::<usize>() as u32 * 8 - n
}
/// Bloom operations.
pub trait Bloomable: Sized + Default + DerefMut<Target = [u8]> {
/// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`.
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self
where
T: Bloomable;
/// Same as `shift_bloomed` except that `self` is consumed and a new value returned.
fn with_bloomed<T>(mut self, b: &T) -> Self
where
T: Bloomable,
{
self.shift_bloomed(b);
self
}
/// Construct new instance equal to the bloomed value of `b`.
fn from_bloomed<T>(b: &T) -> Self
where
T: Bloomable;
/// Bloom the current value using the bloom parameter `m`.
fn bloom_part<T>(&self, m: usize) -> T
where
T: Bloomable;
/// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed.
fn contains_bloomed<T>(&self, b: &T) -> bool
where
T: Bloomable;
}
macro_rules! impl_bloomable_for_hash {
($name: ident, $size: expr) => {
impl Bloomable for $name {
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: Bloomable {
let bp: Self = b.bloom_part($size);
let new_self = &bp | self;
self.0 = new_self.0;
self
}
fn bloom_part<T>(&self, m: usize) -> T where T: Bloomable + Default {
// numbers of bits
// TODO: move it to some constant
let p = 3;
let bloom_bits = m * 8;
let mask = bloom_bits - 1;
let bloom_bytes = (log2(bloom_bits) + 7) / 8;
// must be a power of 2
assert_eq!(m & (m - 1), 0);
// out of range
assert!(p * bloom_bytes <= $size);
// return type
let mut ret = T::default();
// 'ptr' to out slice
let mut ptr = 0;
// set p number of bits,
// p is equal 3 according to yellowpaper
for _ in 0..p {
let mut index = 0 as usize;
for _ in 0..bloom_bytes {
index = (index << 8) | self.0[ptr] as usize;
ptr += 1;
}
index &= mask;
ret[m - 1 - index / 8] |= 1 << (index % 8);
}
ret
}
fn contains_bloomed<T>(&self, b: &T) -> bool where T: Bloomable {
let bp: Self = b.bloom_part($size);
self.contains(&bp)
}
fn from_bloomed<T>(b: &T) -> Self where T: Bloomable {
b.bloom_part($size)
}
}
}
}
impl_bloomable_for_hash!(H64, 8);
impl_bloomable_for_hash!(H160, 20);
impl_bloomable_for_hash!(H256, 32);
impl_bloomable_for_hash!(H512, 64);
impl_bloomable_for_hash!(H520, 65);
impl_bloomable_for_hash!(H2048, 256);
| {
return 0;
} | conditional_block |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Bloom operations.
extern crate bigint;
use bigint::{H64, H160, H256, H512, H520, H2048};
use std::mem;
use std::ops::DerefMut;
/// Returns log2.
pub fn log2(x: usize) -> u32 {
if x <= 1 {
return 0;
}
let n = x.leading_zeros();
mem::size_of::<usize>() as u32 * 8 - n
}
/// Bloom operations.
pub trait Bloomable: Sized + Default + DerefMut<Target = [u8]> {
/// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`.
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self
where
T: Bloomable;
/// Same as `shift_bloomed` except that `self` is consumed and a new value returned.
fn with_bloomed<T>(mut self, b: &T) -> Self
where
T: Bloomable,
{
self.shift_bloomed(b);
self
}
/// Construct new instance equal to the bloomed value of `b`.
fn from_bloomed<T>(b: &T) -> Self
where
T: Bloomable;
/// Bloom the current value using the bloom parameter `m`. | T: Bloomable;
/// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed.
fn contains_bloomed<T>(&self, b: &T) -> bool
where
T: Bloomable;
}
macro_rules! impl_bloomable_for_hash {
($name: ident, $size: expr) => {
impl Bloomable for $name {
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: Bloomable {
let bp: Self = b.bloom_part($size);
let new_self = &bp | self;
self.0 = new_self.0;
self
}
fn bloom_part<T>(&self, m: usize) -> T where T: Bloomable + Default {
// numbers of bits
// TODO: move it to some constant
let p = 3;
let bloom_bits = m * 8;
let mask = bloom_bits - 1;
let bloom_bytes = (log2(bloom_bits) + 7) / 8;
// must be a power of 2
assert_eq!(m & (m - 1), 0);
// out of range
assert!(p * bloom_bytes <= $size);
// return type
let mut ret = T::default();
// 'ptr' to out slice
let mut ptr = 0;
// set p number of bits,
// p is equal 3 according to yellowpaper
for _ in 0..p {
let mut index = 0 as usize;
for _ in 0..bloom_bytes {
index = (index << 8) | self.0[ptr] as usize;
ptr += 1;
}
index &= mask;
ret[m - 1 - index / 8] |= 1 << (index % 8);
}
ret
}
fn contains_bloomed<T>(&self, b: &T) -> bool where T: Bloomable {
let bp: Self = b.bloom_part($size);
self.contains(&bp)
}
fn from_bloomed<T>(b: &T) -> Self where T: Bloomable {
b.bloom_part($size)
}
}
}
}
impl_bloomable_for_hash!(H64, 8);
impl_bloomable_for_hash!(H160, 20);
impl_bloomable_for_hash!(H256, 32);
impl_bloomable_for_hash!(H512, 64);
impl_bloomable_for_hash!(H520, 65);
impl_bloomable_for_hash!(H2048, 256); | fn bloom_part<T>(&self, m: usize) -> T
where | random_line_split |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Bloom operations.
extern crate bigint;
use bigint::{H64, H160, H256, H512, H520, H2048};
use std::mem;
use std::ops::DerefMut;
/// Returns log2.
pub fn log2(x: usize) -> u32 {
if x <= 1 {
return 0;
}
let n = x.leading_zeros();
mem::size_of::<usize>() as u32 * 8 - n
}
/// Bloom operations.
pub trait Bloomable: Sized + Default + DerefMut<Target = [u8]> {
/// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`.
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self
where
T: Bloomable;
/// Same as `shift_bloomed` except that `self` is consumed and a new value returned.
fn with_bloomed<T>(mut self, b: &T) -> Self
where
T: Bloomable,
|
/// Construct new instance equal to the bloomed value of `b`.
fn from_bloomed<T>(b: &T) -> Self
where
T: Bloomable;
/// Bloom the current value using the bloom parameter `m`.
fn bloom_part<T>(&self, m: usize) -> T
where
T: Bloomable;
/// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed.
fn contains_bloomed<T>(&self, b: &T) -> bool
where
T: Bloomable;
}
macro_rules! impl_bloomable_for_hash {
($name: ident, $size: expr) => {
impl Bloomable for $name {
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: Bloomable {
let bp: Self = b.bloom_part($size);
let new_self = &bp | self;
self.0 = new_self.0;
self
}
fn bloom_part<T>(&self, m: usize) -> T where T: Bloomable + Default {
// numbers of bits
// TODO: move it to some constant
let p = 3;
let bloom_bits = m * 8;
let mask = bloom_bits - 1;
let bloom_bytes = (log2(bloom_bits) + 7) / 8;
// must be a power of 2
assert_eq!(m & (m - 1), 0);
// out of range
assert!(p * bloom_bytes <= $size);
// return type
let mut ret = T::default();
// 'ptr' to out slice
let mut ptr = 0;
// set p number of bits,
// p is equal 3 according to yellowpaper
for _ in 0..p {
let mut index = 0 as usize;
for _ in 0..bloom_bytes {
index = (index << 8) | self.0[ptr] as usize;
ptr += 1;
}
index &= mask;
ret[m - 1 - index / 8] |= 1 << (index % 8);
}
ret
}
fn contains_bloomed<T>(&self, b: &T) -> bool where T: Bloomable {
let bp: Self = b.bloom_part($size);
self.contains(&bp)
}
fn from_bloomed<T>(b: &T) -> Self where T: Bloomable {
b.bloom_part($size)
}
}
}
}
impl_bloomable_for_hash!(H64, 8);
impl_bloomable_for_hash!(H160, 20);
impl_bloomable_for_hash!(H256, 32);
impl_bloomable_for_hash!(H512, 64);
impl_bloomable_for_hash!(H520, 65);
impl_bloomable_for_hash!(H2048, 256);
| {
self.shift_bloomed(b);
self
} | identifier_body |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Bloom operations.
extern crate bigint;
use bigint::{H64, H160, H256, H512, H520, H2048};
use std::mem;
use std::ops::DerefMut;
/// Returns log2.
pub fn log2(x: usize) -> u32 {
if x <= 1 {
return 0;
}
let n = x.leading_zeros();
mem::size_of::<usize>() as u32 * 8 - n
}
/// Bloom operations.
pub trait Bloomable: Sized + Default + DerefMut<Target = [u8]> {
/// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`.
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self
where
T: Bloomable;
/// Same as `shift_bloomed` except that `self` is consumed and a new value returned.
fn | <T>(mut self, b: &T) -> Self
where
T: Bloomable,
{
self.shift_bloomed(b);
self
}
/// Construct new instance equal to the bloomed value of `b`.
fn from_bloomed<T>(b: &T) -> Self
where
T: Bloomable;
/// Bloom the current value using the bloom parameter `m`.
fn bloom_part<T>(&self, m: usize) -> T
where
T: Bloomable;
/// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed.
fn contains_bloomed<T>(&self, b: &T) -> bool
where
T: Bloomable;
}
macro_rules! impl_bloomable_for_hash {
($name: ident, $size: expr) => {
impl Bloomable for $name {
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: Bloomable {
let bp: Self = b.bloom_part($size);
let new_self = &bp | self;
self.0 = new_self.0;
self
}
fn bloom_part<T>(&self, m: usize) -> T where T: Bloomable + Default {
// numbers of bits
// TODO: move it to some constant
let p = 3;
let bloom_bits = m * 8;
let mask = bloom_bits - 1;
let bloom_bytes = (log2(bloom_bits) + 7) / 8;
// must be a power of 2
assert_eq!(m & (m - 1), 0);
// out of range
assert!(p * bloom_bytes <= $size);
// return type
let mut ret = T::default();
// 'ptr' to out slice
let mut ptr = 0;
// set p number of bits,
// p is equal 3 according to yellowpaper
for _ in 0..p {
let mut index = 0 as usize;
for _ in 0..bloom_bytes {
index = (index << 8) | self.0[ptr] as usize;
ptr += 1;
}
index &= mask;
ret[m - 1 - index / 8] |= 1 << (index % 8);
}
ret
}
fn contains_bloomed<T>(&self, b: &T) -> bool where T: Bloomable {
let bp: Self = b.bloom_part($size);
self.contains(&bp)
}
fn from_bloomed<T>(b: &T) -> Self where T: Bloomable {
b.bloom_part($size)
}
}
}
}
impl_bloomable_for_hash!(H64, 8);
impl_bloomable_for_hash!(H160, 20);
impl_bloomable_for_hash!(H256, 32);
impl_bloomable_for_hash!(H512, 64);
impl_bloomable_for_hash!(H520, 65);
impl_bloomable_for_hash!(H2048, 256);
| with_bloomed | identifier_name |
main.rs | extern crate num;
use num::{BigInt, Signed};
// Dumbest iterative approach
fn big_pow(base: &BigInt, exp: BigInt) -> BigInt |
// 5^4^3^2
fn main() {
// Exponent is small enough to not use BigInt
let exp = BigInt::from(num::pow(4, num::pow(3, 2)));
let result = big_pow(&BigInt::from(5), exp).to_string();
let num_length = result.len();
println!("{}", result);
println!("Number has {} digits.", num_length);
assert!(result.starts_with("62060698786608744707"));
assert!(result.ends_with("92256259918212890625"));
}
#[cfg(test)]
mod tests {
use super::big_pow;
use num::BigInt;
#[test]
#[should_panic]
fn negative_exp_test() {
let num = BigInt::from(100);
let exp = BigInt::from(-100);
big_pow(&num, exp);
}
#[test]
fn big_powas() {
assert_eq!(
big_pow(&BigInt::from(100), BigInt::from(100)).to_string(),
"10000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
0000000000000"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(89)).to_string(),
"618970019642690137449562112"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(107)).to_string(),
"162259276829213363391578010288128"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(127)).to_string(),
"170141183460469231731687303715884105728"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(521)).to_string(),
"6864797660130609714981900799081393217269435300143305409394\
46345918554318339765605212255964066145455497729631139148085\
8037121987999716643812574028291115057152"
);
}
}
| {
if exp.is_negative() {
panic!("Negative exponent won't compute!")
}
let mut tmp = base.clone();
for _ in num::range(BigInt::from(1), exp) {
tmp *= base;
}
tmp
} | identifier_body |
main.rs | extern crate num;
use num::{BigInt, Signed};
// Dumbest iterative approach
fn big_pow(base: &BigInt, exp: BigInt) -> BigInt {
if exp.is_negative() |
let mut tmp = base.clone();
for _ in num::range(BigInt::from(1), exp) {
tmp *= base;
}
tmp
}
// 5^4^3^2
fn main() {
// Exponent is small enough to not use BigInt
let exp = BigInt::from(num::pow(4, num::pow(3, 2)));
let result = big_pow(&BigInt::from(5), exp).to_string();
let num_length = result.len();
println!("{}", result);
println!("Number has {} digits.", num_length);
assert!(result.starts_with("62060698786608744707"));
assert!(result.ends_with("92256259918212890625"));
}
#[cfg(test)]
mod tests {
use super::big_pow;
use num::BigInt;
#[test]
#[should_panic]
fn negative_exp_test() {
let num = BigInt::from(100);
let exp = BigInt::from(-100);
big_pow(&num, exp);
}
#[test]
fn big_powas() {
assert_eq!(
big_pow(&BigInt::from(100), BigInt::from(100)).to_string(),
"10000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
0000000000000"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(89)).to_string(),
"618970019642690137449562112"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(107)).to_string(),
"162259276829213363391578010288128"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(127)).to_string(),
"170141183460469231731687303715884105728"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(521)).to_string(),
"6864797660130609714981900799081393217269435300143305409394\
46345918554318339765605212255964066145455497729631139148085\
8037121987999716643812574028291115057152"
);
}
}
| {
panic!("Negative exponent won't compute!")
} | conditional_block |
main.rs | extern crate num;
use num::{BigInt, Signed};
// Dumbest iterative approach
fn big_pow(base: &BigInt, exp: BigInt) -> BigInt {
if exp.is_negative() {
panic!("Negative exponent won't compute!")
}
let mut tmp = base.clone();
for _ in num::range(BigInt::from(1), exp) {
tmp *= base;
}
tmp
}
// 5^4^3^2
fn main() {
// Exponent is small enough to not use BigInt
let exp = BigInt::from(num::pow(4, num::pow(3, 2)));
let result = big_pow(&BigInt::from(5), exp).to_string();
let num_length = result.len();
println!("{}", result);
println!("Number has {} digits.", num_length);
assert!(result.starts_with("62060698786608744707"));
assert!(result.ends_with("92256259918212890625"));
}
#[cfg(test)]
mod tests {
use super::big_pow;
use num::BigInt;
#[test]
#[should_panic]
fn negative_exp_test() {
let num = BigInt::from(100);
let exp = BigInt::from(-100);
big_pow(&num, exp);
}
#[test]
fn | () {
assert_eq!(
big_pow(&BigInt::from(100), BigInt::from(100)).to_string(),
"10000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
0000000000000"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(89)).to_string(),
"618970019642690137449562112"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(107)).to_string(),
"162259276829213363391578010288128"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(127)).to_string(),
"170141183460469231731687303715884105728"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(521)).to_string(),
"6864797660130609714981900799081393217269435300143305409394\
46345918554318339765605212255964066145455497729631139148085\
8037121987999716643812574028291115057152"
);
}
}
| big_powas | identifier_name |
main.rs | extern crate num;
use num::{BigInt, Signed};
// Dumbest iterative approach
fn big_pow(base: &BigInt, exp: BigInt) -> BigInt {
if exp.is_negative() {
panic!("Negative exponent won't compute!")
}
let mut tmp = base.clone();
for _ in num::range(BigInt::from(1), exp) {
tmp *= base;
}
tmp
}
// 5^4^3^2
fn main() {
// Exponent is small enough to not use BigInt
let exp = BigInt::from(num::pow(4, num::pow(3, 2)));
let result = big_pow(&BigInt::from(5), exp).to_string();
let num_length = result.len();
println!("{}", result);
println!("Number has {} digits.", num_length);
assert!(result.starts_with("62060698786608744707"));
assert!(result.ends_with("92256259918212890625"));
}
#[cfg(test)]
mod tests {
use super::big_pow;
use num::BigInt;
#[test]
#[should_panic]
fn negative_exp_test() {
let num = BigInt::from(100); |
#[test]
fn big_powas() {
assert_eq!(
big_pow(&BigInt::from(100), BigInt::from(100)).to_string(),
"10000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000\
0000000000000"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(89)).to_string(),
"618970019642690137449562112"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(107)).to_string(),
"162259276829213363391578010288128"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(127)).to_string(),
"170141183460469231731687303715884105728"
);
assert_eq!(
big_pow(&BigInt::from(2), BigInt::from(521)).to_string(),
"6864797660130609714981900799081393217269435300143305409394\
46345918554318339765605212255964066145455497729631139148085\
8037121987999716643812574028291115057152"
);
}
} | let exp = BigInt::from(-100);
big_pow(&num, exp);
} | random_line_split |
domexception.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMExceptionBinding;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use std::borrow::ToOwned;
use util::str::DOMString;
#[repr(u16)]
#[derive(JSTraceable, Copy, Clone, Debug, HeapSizeOf)]
pub enum DOMErrorName {
IndexSizeError = DOMExceptionConstants::INDEX_SIZE_ERR,
HierarchyRequestError = DOMExceptionConstants::HIERARCHY_REQUEST_ERR,
WrongDocumentError = DOMExceptionConstants::WRONG_DOCUMENT_ERR,
InvalidCharacterError = DOMExceptionConstants::INVALID_CHARACTER_ERR,
NoModificationAllowedError = DOMExceptionConstants::NO_MODIFICATION_ALLOWED_ERR,
NotFoundError = DOMExceptionConstants::NOT_FOUND_ERR,
NotSupportedError = DOMExceptionConstants::NOT_SUPPORTED_ERR,
InUseAttributeError = DOMExceptionConstants::INUSE_ATTRIBUTE_ERR,
InvalidStateError = DOMExceptionConstants::INVALID_STATE_ERR,
SyntaxError = DOMExceptionConstants::SYNTAX_ERR,
InvalidModificationError = DOMExceptionConstants::INVALID_MODIFICATION_ERR,
NamespaceError = DOMExceptionConstants::NAMESPACE_ERR,
InvalidAccessError = DOMExceptionConstants::INVALID_ACCESS_ERR,
SecurityError = DOMExceptionConstants::SECURITY_ERR,
NetworkError = DOMExceptionConstants::NETWORK_ERR,
AbortError = DOMExceptionConstants::ABORT_ERR,
URLMismatchError = DOMExceptionConstants::URL_MISMATCH_ERR,
TypeMismatchError = DOMExceptionConstants::TYPE_MISMATCH_ERR,
QuotaExceededError = DOMExceptionConstants::QUOTA_EXCEEDED_ERR,
TimeoutError = DOMExceptionConstants::TIMEOUT_ERR,
InvalidNodeTypeError = DOMExceptionConstants::INVALID_NODE_TYPE_ERR,
DataCloneError = DOMExceptionConstants::DATA_CLONE_ERR,
EncodingError
}
#[dom_struct]
pub struct DOMException {
reflector_: Reflector,
code: DOMErrorName,
}
impl DOMException {
fn | (code: DOMErrorName) -> DOMException {
DOMException {
reflector_: Reflector::new(),
code: code,
}
}
pub fn new(global: GlobalRef, code: DOMErrorName) -> Root<DOMException> {
reflect_dom_object(box DOMException::new_inherited(code), global, DOMExceptionBinding::Wrap)
}
}
impl DOMExceptionMethods for DOMException {
// https://heycam.github.io/webidl/#dfn-DOMException
fn Code(&self) -> u16 {
match self.code {
// https://heycam.github.io/webidl/#dfn-throw
DOMErrorName::EncodingError => 0,
code => code as u16
}
}
// https://heycam.github.io/webidl/#idl-DOMException-error-names
fn Name(&self) -> DOMString {
DOMString(format!("{:?}", self.code))
}
// https://heycam.github.io/webidl/#error-names
fn Message(&self) -> DOMString {
let message = match self.code {
DOMErrorName::IndexSizeError => "The index is not in the allowed range.",
DOMErrorName::HierarchyRequestError => "The operation would yield an incorrect node tree.",
DOMErrorName::WrongDocumentError => "The object is in the wrong document.",
DOMErrorName::InvalidCharacterError => "The string contains invalid characters.",
DOMErrorName::NoModificationAllowedError => "The object can not be modified.",
DOMErrorName::NotFoundError => "The object can not be found here.",
DOMErrorName::NotSupportedError => "The operation is not supported.",
DOMErrorName::InUseAttributeError => "The attribute already in use.",
DOMErrorName::InvalidStateError => "The object is in an invalid state.",
DOMErrorName::SyntaxError => "The string did not match the expected pattern.",
DOMErrorName::InvalidModificationError => "The object can not be modified in this way.",
DOMErrorName::NamespaceError => "The operation is not allowed by Namespaces in XML.",
DOMErrorName::InvalidAccessError => "The object does not support the operation or argument.",
DOMErrorName::SecurityError => "The operation is insecure.",
DOMErrorName::NetworkError => "A network error occurred.",
DOMErrorName::AbortError => "The operation was aborted.",
DOMErrorName::URLMismatchError => "The given URL does not match another URL.",
DOMErrorName::TypeMismatchError => "The given type does not match any expected type.",
DOMErrorName::QuotaExceededError => "The quota has been exceeded.",
DOMErrorName::TimeoutError => "The operation timed out.",
DOMErrorName::InvalidNodeTypeError =>
"The supplied node is incorrect or has an incorrect ancestor for this operation.",
DOMErrorName::DataCloneError => "The object can not be cloned.",
DOMErrorName::EncodingError => "The encoding operation (either encoded or decoding) failed."
};
DOMString(message.to_owned())
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-error.prototype.tostring
fn Stringifier(&self) -> DOMString {
DOMString(format!("{}: {}", self.Name(), self.Message()))
}
}
| new_inherited | identifier_name |
domexception.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMExceptionBinding;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use std::borrow::ToOwned;
use util::str::DOMString;
#[repr(u16)]
#[derive(JSTraceable, Copy, Clone, Debug, HeapSizeOf)]
pub enum DOMErrorName {
IndexSizeError = DOMExceptionConstants::INDEX_SIZE_ERR,
HierarchyRequestError = DOMExceptionConstants::HIERARCHY_REQUEST_ERR,
WrongDocumentError = DOMExceptionConstants::WRONG_DOCUMENT_ERR,
InvalidCharacterError = DOMExceptionConstants::INVALID_CHARACTER_ERR,
NoModificationAllowedError = DOMExceptionConstants::NO_MODIFICATION_ALLOWED_ERR,
NotFoundError = DOMExceptionConstants::NOT_FOUND_ERR,
NotSupportedError = DOMExceptionConstants::NOT_SUPPORTED_ERR,
InUseAttributeError = DOMExceptionConstants::INUSE_ATTRIBUTE_ERR,
InvalidStateError = DOMExceptionConstants::INVALID_STATE_ERR,
SyntaxError = DOMExceptionConstants::SYNTAX_ERR,
InvalidModificationError = DOMExceptionConstants::INVALID_MODIFICATION_ERR,
NamespaceError = DOMExceptionConstants::NAMESPACE_ERR,
InvalidAccessError = DOMExceptionConstants::INVALID_ACCESS_ERR,
SecurityError = DOMExceptionConstants::SECURITY_ERR,
NetworkError = DOMExceptionConstants::NETWORK_ERR,
AbortError = DOMExceptionConstants::ABORT_ERR,
URLMismatchError = DOMExceptionConstants::URL_MISMATCH_ERR,
TypeMismatchError = DOMExceptionConstants::TYPE_MISMATCH_ERR,
QuotaExceededError = DOMExceptionConstants::QUOTA_EXCEEDED_ERR,
TimeoutError = DOMExceptionConstants::TIMEOUT_ERR,
InvalidNodeTypeError = DOMExceptionConstants::INVALID_NODE_TYPE_ERR,
DataCloneError = DOMExceptionConstants::DATA_CLONE_ERR,
EncodingError
}
#[dom_struct]
pub struct DOMException {
reflector_: Reflector,
code: DOMErrorName,
}
impl DOMException {
fn new_inherited(code: DOMErrorName) -> DOMException {
DOMException {
reflector_: Reflector::new(),
code: code,
}
}
pub fn new(global: GlobalRef, code: DOMErrorName) -> Root<DOMException> {
reflect_dom_object(box DOMException::new_inherited(code), global, DOMExceptionBinding::Wrap)
}
}
impl DOMExceptionMethods for DOMException {
// https://heycam.github.io/webidl/#dfn-DOMException
fn Code(&self) -> u16 |
// https://heycam.github.io/webidl/#idl-DOMException-error-names
fn Name(&self) -> DOMString {
DOMString(format!("{:?}", self.code))
}
// https://heycam.github.io/webidl/#error-names
fn Message(&self) -> DOMString {
let message = match self.code {
DOMErrorName::IndexSizeError => "The index is not in the allowed range.",
DOMErrorName::HierarchyRequestError => "The operation would yield an incorrect node tree.",
DOMErrorName::WrongDocumentError => "The object is in the wrong document.",
DOMErrorName::InvalidCharacterError => "The string contains invalid characters.",
DOMErrorName::NoModificationAllowedError => "The object can not be modified.",
DOMErrorName::NotFoundError => "The object can not be found here.",
DOMErrorName::NotSupportedError => "The operation is not supported.",
DOMErrorName::InUseAttributeError => "The attribute already in use.",
DOMErrorName::InvalidStateError => "The object is in an invalid state.",
DOMErrorName::SyntaxError => "The string did not match the expected pattern.",
DOMErrorName::InvalidModificationError => "The object can not be modified in this way.",
DOMErrorName::NamespaceError => "The operation is not allowed by Namespaces in XML.",
DOMErrorName::InvalidAccessError => "The object does not support the operation or argument.",
DOMErrorName::SecurityError => "The operation is insecure.",
DOMErrorName::NetworkError => "A network error occurred.",
DOMErrorName::AbortError => "The operation was aborted.",
DOMErrorName::URLMismatchError => "The given URL does not match another URL.",
DOMErrorName::TypeMismatchError => "The given type does not match any expected type.",
DOMErrorName::QuotaExceededError => "The quota has been exceeded.",
DOMErrorName::TimeoutError => "The operation timed out.",
DOMErrorName::InvalidNodeTypeError =>
"The supplied node is incorrect or has an incorrect ancestor for this operation.",
DOMErrorName::DataCloneError => "The object can not be cloned.",
DOMErrorName::EncodingError => "The encoding operation (either encoded or decoding) failed."
};
DOMString(message.to_owned())
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-error.prototype.tostring
fn Stringifier(&self) -> DOMString {
DOMString(format!("{}: {}", self.Name(), self.Message()))
}
}
| {
match self.code {
// https://heycam.github.io/webidl/#dfn-throw
DOMErrorName::EncodingError => 0,
code => code as u16
}
} | identifier_body |
domexception.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMExceptionBinding;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use std::borrow::ToOwned;
use util::str::DOMString;
#[repr(u16)]
#[derive(JSTraceable, Copy, Clone, Debug, HeapSizeOf)]
pub enum DOMErrorName {
IndexSizeError = DOMExceptionConstants::INDEX_SIZE_ERR,
HierarchyRequestError = DOMExceptionConstants::HIERARCHY_REQUEST_ERR,
WrongDocumentError = DOMExceptionConstants::WRONG_DOCUMENT_ERR,
InvalidCharacterError = DOMExceptionConstants::INVALID_CHARACTER_ERR,
NoModificationAllowedError = DOMExceptionConstants::NO_MODIFICATION_ALLOWED_ERR,
NotFoundError = DOMExceptionConstants::NOT_FOUND_ERR,
NotSupportedError = DOMExceptionConstants::NOT_SUPPORTED_ERR,
InUseAttributeError = DOMExceptionConstants::INUSE_ATTRIBUTE_ERR,
InvalidStateError = DOMExceptionConstants::INVALID_STATE_ERR,
SyntaxError = DOMExceptionConstants::SYNTAX_ERR,
InvalidModificationError = DOMExceptionConstants::INVALID_MODIFICATION_ERR,
NamespaceError = DOMExceptionConstants::NAMESPACE_ERR,
InvalidAccessError = DOMExceptionConstants::INVALID_ACCESS_ERR, | URLMismatchError = DOMExceptionConstants::URL_MISMATCH_ERR,
TypeMismatchError = DOMExceptionConstants::TYPE_MISMATCH_ERR,
QuotaExceededError = DOMExceptionConstants::QUOTA_EXCEEDED_ERR,
TimeoutError = DOMExceptionConstants::TIMEOUT_ERR,
InvalidNodeTypeError = DOMExceptionConstants::INVALID_NODE_TYPE_ERR,
DataCloneError = DOMExceptionConstants::DATA_CLONE_ERR,
EncodingError
}
#[dom_struct]
pub struct DOMException {
reflector_: Reflector,
code: DOMErrorName,
}
impl DOMException {
fn new_inherited(code: DOMErrorName) -> DOMException {
DOMException {
reflector_: Reflector::new(),
code: code,
}
}
pub fn new(global: GlobalRef, code: DOMErrorName) -> Root<DOMException> {
reflect_dom_object(box DOMException::new_inherited(code), global, DOMExceptionBinding::Wrap)
}
}
impl DOMExceptionMethods for DOMException {
// https://heycam.github.io/webidl/#dfn-DOMException
fn Code(&self) -> u16 {
match self.code {
// https://heycam.github.io/webidl/#dfn-throw
DOMErrorName::EncodingError => 0,
code => code as u16
}
}
// https://heycam.github.io/webidl/#idl-DOMException-error-names
fn Name(&self) -> DOMString {
DOMString(format!("{:?}", self.code))
}
// https://heycam.github.io/webidl/#error-names
fn Message(&self) -> DOMString {
let message = match self.code {
DOMErrorName::IndexSizeError => "The index is not in the allowed range.",
DOMErrorName::HierarchyRequestError => "The operation would yield an incorrect node tree.",
DOMErrorName::WrongDocumentError => "The object is in the wrong document.",
DOMErrorName::InvalidCharacterError => "The string contains invalid characters.",
DOMErrorName::NoModificationAllowedError => "The object can not be modified.",
DOMErrorName::NotFoundError => "The object can not be found here.",
DOMErrorName::NotSupportedError => "The operation is not supported.",
DOMErrorName::InUseAttributeError => "The attribute already in use.",
DOMErrorName::InvalidStateError => "The object is in an invalid state.",
DOMErrorName::SyntaxError => "The string did not match the expected pattern.",
DOMErrorName::InvalidModificationError => "The object can not be modified in this way.",
DOMErrorName::NamespaceError => "The operation is not allowed by Namespaces in XML.",
DOMErrorName::InvalidAccessError => "The object does not support the operation or argument.",
DOMErrorName::SecurityError => "The operation is insecure.",
DOMErrorName::NetworkError => "A network error occurred.",
DOMErrorName::AbortError => "The operation was aborted.",
DOMErrorName::URLMismatchError => "The given URL does not match another URL.",
DOMErrorName::TypeMismatchError => "The given type does not match any expected type.",
DOMErrorName::QuotaExceededError => "The quota has been exceeded.",
DOMErrorName::TimeoutError => "The operation timed out.",
DOMErrorName::InvalidNodeTypeError =>
"The supplied node is incorrect or has an incorrect ancestor for this operation.",
DOMErrorName::DataCloneError => "The object can not be cloned.",
DOMErrorName::EncodingError => "The encoding operation (either encoded or decoding) failed."
};
DOMString(message.to_owned())
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-error.prototype.tostring
fn Stringifier(&self) -> DOMString {
DOMString(format!("{}: {}", self.Name(), self.Message()))
}
} | SecurityError = DOMExceptionConstants::SECURITY_ERR,
NetworkError = DOMExceptionConstants::NETWORK_ERR,
AbortError = DOMExceptionConstants::ABORT_ERR, | random_line_split |
minimal_versions.rs | //! Tests for minimal-version resolution.
//!
//! Note: Some tests are located in the resolver-tests package.
use cargo_test_support::project;
use cargo_test_support::registry::Package;
// Ensure that the "-Z minimal-versions" CLI option works and the minimal
// version of a dependency ends up in the lock file.
#[cargo_test]
fn | () {
Package::new("dep", "1.0.0").publish();
Package::new("dep", "1.1.0").publish();
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
[dependencies]
dep = "1.0"
"#,
)
.file("src/main.rs", "fn main() {}")
.build();
p.cargo("generate-lockfile -Zminimal-versions")
.masquerade_as_nightly_cargo()
.run();
let lock = p.read_lockfile();
assert!(!lock.contains("1.1.0"));
}
| minimal_version_cli | identifier_name |
minimal_versions.rs | //! Tests for minimal-version resolution.
//!
//! Note: Some tests are located in the resolver-tests package.
use cargo_test_support::project;
use cargo_test_support::registry::Package;
// Ensure that the "-Z minimal-versions" CLI option works and the minimal
// version of a dependency ends up in the lock file.
#[cargo_test]
fn minimal_version_cli() {
Package::new("dep", "1.0.0").publish();
Package::new("dep", "1.1.0").publish();
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
[dependencies]
dep = "1.0"
"#,
)
.file("src/main.rs", "fn main() {}") | .masquerade_as_nightly_cargo()
.run();
let lock = p.read_lockfile();
assert!(!lock.contains("1.1.0"));
} | .build();
p.cargo("generate-lockfile -Zminimal-versions") | random_line_split |
minimal_versions.rs | //! Tests for minimal-version resolution.
//!
//! Note: Some tests are located in the resolver-tests package.
use cargo_test_support::project;
use cargo_test_support::registry::Package;
// Ensure that the "-Z minimal-versions" CLI option works and the minimal
// version of a dependency ends up in the lock file.
#[cargo_test]
fn minimal_version_cli() | p.cargo("generate-lockfile -Zminimal-versions")
.masquerade_as_nightly_cargo()
.run();
let lock = p.read_lockfile();
assert!(!lock.contains("1.1.0"));
}
| {
Package::new("dep", "1.0.0").publish();
Package::new("dep", "1.1.0").publish();
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
[dependencies]
dep = "1.0"
"#,
)
.file("src/main.rs", "fn main() {}")
.build();
| identifier_body |
mouse.rs | use std::rc::Rc;
use nalgebra::{Vector2};
use ncollide_geometry::shape::{Cuboid, ShapeHandle2};
use glium::glutin::MouseButton;
use game::object::Object;
use engine::Engine;
use engine::entity::component::*;
use engine::event::{Event, InputState};
pub struct Mouse {
world: WorldComp<Object>,
ev: EventComp<Object>,
phys: PhysicsComp,
pos: (f32, f32),
}
impl Mouse {
pub fn new(engine: &Engine<Object>) -> Object {
let w = WorldCompBuilder::new(engine).build();
let e = EventComp::new(w.id, engine.events.clone());
let p = PhysicsComp::new(w.id,
0,
Vector2::new(0.0, 0.0),
ShapeHandle2::new(Cuboid::new(Vector2::new(0.2, 0.2))),
101,
&engine.scene);
Object::Mouse(Mouse {
world: w,
ev: e,
phys: p,
pos: (0.0, 0.0),
})
}
pub fn | (&mut self, e: Rc<Event>) {
match *e {
Event::Spawn => {
println!("Mouse spawned!");
self.ev.subscribe(Event::MouseMove((0.0, 0.0)));
self.ev.subscribe(Event::MouseInput(InputState::Released, MouseButton::Left));
}
Event::MouseMove(pos) => {
self.phys.set_pos(Vector2::new(pos.0, pos.1));
self.pos = pos;
}
_ => {}
};
}
pub fn id(&self) -> usize {
self.world.id
}
}
| handle_event | identifier_name |
mouse.rs | use std::rc::Rc;
use nalgebra::{Vector2};
use ncollide_geometry::shape::{Cuboid, ShapeHandle2};
use glium::glutin::MouseButton;
use game::object::Object;
use engine::Engine;
use engine::entity::component::*;
use engine::event::{Event, InputState};
pub struct Mouse {
world: WorldComp<Object>, | impl Mouse {
pub fn new(engine: &Engine<Object>) -> Object {
let w = WorldCompBuilder::new(engine).build();
let e = EventComp::new(w.id, engine.events.clone());
let p = PhysicsComp::new(w.id,
0,
Vector2::new(0.0, 0.0),
ShapeHandle2::new(Cuboid::new(Vector2::new(0.2, 0.2))),
101,
&engine.scene);
Object::Mouse(Mouse {
world: w,
ev: e,
phys: p,
pos: (0.0, 0.0),
})
}
pub fn handle_event(&mut self, e: Rc<Event>) {
match *e {
Event::Spawn => {
println!("Mouse spawned!");
self.ev.subscribe(Event::MouseMove((0.0, 0.0)));
self.ev.subscribe(Event::MouseInput(InputState::Released, MouseButton::Left));
}
Event::MouseMove(pos) => {
self.phys.set_pos(Vector2::new(pos.0, pos.1));
self.pos = pos;
}
_ => {}
};
}
pub fn id(&self) -> usize {
self.world.id
}
} | ev: EventComp<Object>,
phys: PhysicsComp,
pos: (f32, f32),
}
| random_line_split |
mouse.rs | use std::rc::Rc;
use nalgebra::{Vector2};
use ncollide_geometry::shape::{Cuboid, ShapeHandle2};
use glium::glutin::MouseButton;
use game::object::Object;
use engine::Engine;
use engine::entity::component::*;
use engine::event::{Event, InputState};
pub struct Mouse {
world: WorldComp<Object>,
ev: EventComp<Object>,
phys: PhysicsComp,
pos: (f32, f32),
}
impl Mouse {
pub fn new(engine: &Engine<Object>) -> Object {
let w = WorldCompBuilder::new(engine).build();
let e = EventComp::new(w.id, engine.events.clone());
let p = PhysicsComp::new(w.id,
0,
Vector2::new(0.0, 0.0),
ShapeHandle2::new(Cuboid::new(Vector2::new(0.2, 0.2))),
101,
&engine.scene);
Object::Mouse(Mouse {
world: w,
ev: e,
phys: p,
pos: (0.0, 0.0),
})
}
pub fn handle_event(&mut self, e: Rc<Event>) {
match *e {
Event::Spawn => {
println!("Mouse spawned!");
self.ev.subscribe(Event::MouseMove((0.0, 0.0)));
self.ev.subscribe(Event::MouseInput(InputState::Released, MouseButton::Left));
}
Event::MouseMove(pos) => {
self.phys.set_pos(Vector2::new(pos.0, pos.1));
self.pos = pos;
}
_ => {}
};
}
pub fn id(&self) -> usize |
}
| {
self.world.id
} | identifier_body |
mouse.rs | use std::rc::Rc;
use nalgebra::{Vector2};
use ncollide_geometry::shape::{Cuboid, ShapeHandle2};
use glium::glutin::MouseButton;
use game::object::Object;
use engine::Engine;
use engine::entity::component::*;
use engine::event::{Event, InputState};
pub struct Mouse {
world: WorldComp<Object>,
ev: EventComp<Object>,
phys: PhysicsComp,
pos: (f32, f32),
}
impl Mouse {
pub fn new(engine: &Engine<Object>) -> Object {
let w = WorldCompBuilder::new(engine).build();
let e = EventComp::new(w.id, engine.events.clone());
let p = PhysicsComp::new(w.id,
0,
Vector2::new(0.0, 0.0),
ShapeHandle2::new(Cuboid::new(Vector2::new(0.2, 0.2))),
101,
&engine.scene);
Object::Mouse(Mouse {
world: w,
ev: e,
phys: p,
pos: (0.0, 0.0),
})
}
pub fn handle_event(&mut self, e: Rc<Event>) {
match *e {
Event::Spawn => {
println!("Mouse spawned!");
self.ev.subscribe(Event::MouseMove((0.0, 0.0)));
self.ev.subscribe(Event::MouseInput(InputState::Released, MouseButton::Left));
}
Event::MouseMove(pos) => {
self.phys.set_pos(Vector2::new(pos.0, pos.1));
self.pos = pos;
}
_ => |
};
}
pub fn id(&self) -> usize {
self.world.id
}
}
| {} | conditional_block |
main.rs | extern crate byteorder;
extern crate elf;
use std::path::PathBuf;
use std::fs::{File, OpenOptions};
use std::io::*;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::process::Command;
static BOOT_FILE_BLOCK_SIZE :u32 = 512;
static BOOT_FILE_HEADER_LENGTH :u32 = 20;
macro_rules! try_IO {
($file_path:ident, $expr:expr) => (match $expr {
Ok(value) => value,
Err(error) => {
println!("Error in {:?}: {:?}", $file_path, error);
return;
}
})
}
fn | () {
let linker_path = match std::env::var("LD") {
Ok(value) => value,
Err(_) => {
println!("Could not find linker");
return;
},
};
let args: Vec<_> = std::env::args().collect();
if args.len() < 5 {
println!("Usage: LD = [linker] build_tool [virtual_offset] [physical_offset] [out.bin] [in1.o] [in2.o] [in3.o]...");
return;
}
let virtual_offset = u64::from_str_radix(&args[1][2..], 16).unwrap();
let physical_offset = u64::from_str_radix(&args[2][2..], 16).unwrap();
let target = &args[3];
if target.len() < 5 || &target[target.len()-4..target.len()]!= ".bin" {
println!("Output filename is invalid");
return;
}
let mut object_files :[Vec<PathBuf>; 2] = [Vec::new(), Vec::new()];
for in_file_path_str in &args[4..] {
let in_file_path = PathBuf::from(in_file_path_str);
let in_file = try_IO!(in_file_path, elf::File::open_path(&in_file_path));
if in_file.ehdr.osabi!= elf::types::ELFOSABI_NONE {
println!("{:?} is of wrong ABI", in_file_path);
return;
}
if in_file.ehdr.data!= elf::types::ELFDATA2LSB {
println!("{:?} is of wrong endianess", in_file_path);
return;
}
match in_file.ehdr.class {
elf::types::ELFCLASS32 => {
if in_file.ehdr.machine!= elf::types::EM_ARM {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[0].push(in_file_path);
},
elf::types::ELFCLASS64 => {
if in_file.ehdr.machine!= elf::types::EM_AARCH64 {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[1].push(in_file_path);
},
elf::types::Class(_) => {
println!("{:?} is of unknown architecture size", in_file_path);
return;
},
};
}
let binary_file_path = PathBuf::from(target);
let mut binary_file = try_IO!(binary_file_path, OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&binary_file_path));
let mut payload_length :u32 = BOOT_FILE_HEADER_LENGTH;
let mut check_sum :u32 = 0;
let mut entry_point :u64 = 0;
let mut virtual_address = virtual_offset+BOOT_FILE_HEADER_LENGTH as u64;
for architecture in 0..2 {
if object_files[architecture].len() == 0 {
continue;
}
let architecture_names = ["32", "64"];
let architecture_target = format!("{}{}", &target[..target.len()-4], architecture_names[architecture]);
let linker_script_file_path = PathBuf::from(format!("{}.lds", architecture_target));
let elf_file_path = PathBuf::from(format!("{}.elf", architecture_target));
let mut linker_script = try_IO!(linker_script_file_path, File::create(&linker_script_file_path));
try_IO!(linker_script_file_path, linker_script.write(b"SECTIONS {\n"));
try_IO!(linker_script_file_path, linker_script.write(format!(" . = 0x{:08X};", virtual_address).as_bytes()));
try_IO!(linker_script_file_path, linker_script.write(b"
.text : { *(.text) }
.rodata : { *(.rodata) }
.data : { *(.data) }
.bss : { *(.bss) }
/DISCARD/ : { *(.ARM.exidx*) }
/DISCARD/ : { *(.comment) }
}"));
println!("Linking: {:?}", elf_file_path);
try_IO!(linker_path, Command::new(&linker_path)
.arg("-flavor").arg("gnu")
.arg("-s")
.arg("--script").arg(linker_script_file_path)
.arg("-o").arg(&elf_file_path)
.args(&object_files[architecture])
.status());
let in_file = try_IO!(elf_file_path, elf::File::open_path(&elf_file_path));
if entry_point == 0 {
entry_point = in_file.ehdr.entry;
}
for section in &in_file.sections {
if section.shdr.size == 0 || section.shdr.shtype!= elf::types::SHT_PROGBITS {
continue;
}
if section.shdr.addr < virtual_address {
println!("{:?} section virtual addresses are in wrong order", elf_file_path);
return;
}
let physical_address = section.shdr.addr-virtual_offset+physical_offset;
payload_length += (section.shdr.addr-virtual_address) as u32;
virtual_address = section.shdr.addr+section.shdr.size;
println!(" {:08X} {:08X} {:08X} {}", section.shdr.addr, section.shdr.addr+section.shdr.size, physical_address, section.shdr.name);
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_address)));
try_IO!(binary_file_path, binary_file.write(§ion.data));
payload_length += section.shdr.size as u32;
}
}
println!("Building: {:?}", binary_file_path);
let needs_trailing_zeros = payload_length%BOOT_FILE_BLOCK_SIZE > 0;
println!(" {} bytes", payload_length);
payload_length = (payload_length+BOOT_FILE_BLOCK_SIZE-1)/BOOT_FILE_BLOCK_SIZE;
println!(" {} blocks of {} bytes", payload_length, BOOT_FILE_BLOCK_SIZE);
payload_length *= BOOT_FILE_BLOCK_SIZE;
println!(" {:08X} entry point", entry_point);
entry_point = (entry_point-virtual_offset)/4;
if entry_point > 0xEFFFFF {
println!("Entry point is out of reach");
return;
}
let mut boot_file_header = [0u8; 20];
let jump_instruction :u32 = if object_files[0].len() > 0
{ 0xEA000000|(entry_point as u32-2) } else
{ 0x14000000|(entry_point as u32) };
(&mut boot_file_header[0..4]).write_u32::<LittleEndian>(jump_instruction).unwrap();
(&mut boot_file_header[4..12]).clone_from_slice(b"eGON.BT0");
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(0x5F0A6C39).unwrap();
(&mut boot_file_header[16..20]).write_u32::<LittleEndian>(payload_length).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header));
if needs_trailing_zeros {
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+payload_length as u64-1)));
try_IO!(binary_file_path, binary_file.write(&[0u8]));
}
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
for _ in 0..payload_length/4 {
let mut buffer = [0u8; 4];
try_IO!(binary_file_path, binary_file.read(&mut buffer));
check_sum = check_sum.wrapping_add((&buffer[0..4]).read_u32::<LittleEndian>().unwrap());
}
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(check_sum).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+12)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header[12..16]));
println!(" {:08X} check sum", check_sum.swap_bytes());
}
| main | identifier_name |
main.rs | extern crate byteorder;
extern crate elf;
use std::path::PathBuf;
use std::fs::{File, OpenOptions};
use std::io::*;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::process::Command;
static BOOT_FILE_BLOCK_SIZE :u32 = 512;
static BOOT_FILE_HEADER_LENGTH :u32 = 20;
macro_rules! try_IO {
($file_path:ident, $expr:expr) => (match $expr {
Ok(value) => value,
Err(error) => {
println!("Error in {:?}: {:?}", $file_path, error);
return;
}
})
}
fn main() {
let linker_path = match std::env::var("LD") {
Ok(value) => value,
Err(_) => {
println!("Could not find linker");
return;
},
};
let args: Vec<_> = std::env::args().collect();
if args.len() < 5 {
println!("Usage: LD = [linker] build_tool [virtual_offset] [physical_offset] [out.bin] [in1.o] [in2.o] [in3.o]...");
return;
}
let virtual_offset = u64::from_str_radix(&args[1][2..], 16).unwrap();
let physical_offset = u64::from_str_radix(&args[2][2..], 16).unwrap();
let target = &args[3];
if target.len() < 5 || &target[target.len()-4..target.len()]!= ".bin" {
println!("Output filename is invalid");
return;
}
let mut object_files :[Vec<PathBuf>; 2] = [Vec::new(), Vec::new()];
for in_file_path_str in &args[4..] {
let in_file_path = PathBuf::from(in_file_path_str);
let in_file = try_IO!(in_file_path, elf::File::open_path(&in_file_path));
if in_file.ehdr.osabi!= elf::types::ELFOSABI_NONE {
println!("{:?} is of wrong ABI", in_file_path);
return;
}
if in_file.ehdr.data!= elf::types::ELFDATA2LSB {
println!("{:?} is of wrong endianess", in_file_path);
return;
}
match in_file.ehdr.class {
elf::types::ELFCLASS32 => {
if in_file.ehdr.machine!= elf::types::EM_ARM {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[0].push(in_file_path);
},
elf::types::ELFCLASS64 => | ,
elf::types::Class(_) => {
println!("{:?} is of unknown architecture size", in_file_path);
return;
},
};
}
let binary_file_path = PathBuf::from(target);
let mut binary_file = try_IO!(binary_file_path, OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&binary_file_path));
let mut payload_length :u32 = BOOT_FILE_HEADER_LENGTH;
let mut check_sum :u32 = 0;
let mut entry_point :u64 = 0;
let mut virtual_address = virtual_offset+BOOT_FILE_HEADER_LENGTH as u64;
for architecture in 0..2 {
if object_files[architecture].len() == 0 {
continue;
}
let architecture_names = ["32", "64"];
let architecture_target = format!("{}{}", &target[..target.len()-4], architecture_names[architecture]);
let linker_script_file_path = PathBuf::from(format!("{}.lds", architecture_target));
let elf_file_path = PathBuf::from(format!("{}.elf", architecture_target));
let mut linker_script = try_IO!(linker_script_file_path, File::create(&linker_script_file_path));
try_IO!(linker_script_file_path, linker_script.write(b"SECTIONS {\n"));
try_IO!(linker_script_file_path, linker_script.write(format!(" . = 0x{:08X};", virtual_address).as_bytes()));
try_IO!(linker_script_file_path, linker_script.write(b"
.text : { *(.text) }
.rodata : { *(.rodata) }
.data : { *(.data) }
.bss : { *(.bss) }
/DISCARD/ : { *(.ARM.exidx*) }
/DISCARD/ : { *(.comment) }
}"));
println!("Linking: {:?}", elf_file_path);
try_IO!(linker_path, Command::new(&linker_path)
.arg("-flavor").arg("gnu")
.arg("-s")
.arg("--script").arg(linker_script_file_path)
.arg("-o").arg(&elf_file_path)
.args(&object_files[architecture])
.status());
let in_file = try_IO!(elf_file_path, elf::File::open_path(&elf_file_path));
if entry_point == 0 {
entry_point = in_file.ehdr.entry;
}
for section in &in_file.sections {
if section.shdr.size == 0 || section.shdr.shtype!= elf::types::SHT_PROGBITS {
continue;
}
if section.shdr.addr < virtual_address {
println!("{:?} section virtual addresses are in wrong order", elf_file_path);
return;
}
let physical_address = section.shdr.addr-virtual_offset+physical_offset;
payload_length += (section.shdr.addr-virtual_address) as u32;
virtual_address = section.shdr.addr+section.shdr.size;
println!(" {:08X} {:08X} {:08X} {}", section.shdr.addr, section.shdr.addr+section.shdr.size, physical_address, section.shdr.name);
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_address)));
try_IO!(binary_file_path, binary_file.write(§ion.data));
payload_length += section.shdr.size as u32;
}
}
println!("Building: {:?}", binary_file_path);
let needs_trailing_zeros = payload_length%BOOT_FILE_BLOCK_SIZE > 0;
println!(" {} bytes", payload_length);
payload_length = (payload_length+BOOT_FILE_BLOCK_SIZE-1)/BOOT_FILE_BLOCK_SIZE;
println!(" {} blocks of {} bytes", payload_length, BOOT_FILE_BLOCK_SIZE);
payload_length *= BOOT_FILE_BLOCK_SIZE;
println!(" {:08X} entry point", entry_point);
entry_point = (entry_point-virtual_offset)/4;
if entry_point > 0xEFFFFF {
println!("Entry point is out of reach");
return;
}
let mut boot_file_header = [0u8; 20];
let jump_instruction :u32 = if object_files[0].len() > 0
{ 0xEA000000|(entry_point as u32-2) } else
{ 0x14000000|(entry_point as u32) };
(&mut boot_file_header[0..4]).write_u32::<LittleEndian>(jump_instruction).unwrap();
(&mut boot_file_header[4..12]).clone_from_slice(b"eGON.BT0");
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(0x5F0A6C39).unwrap();
(&mut boot_file_header[16..20]).write_u32::<LittleEndian>(payload_length).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header));
if needs_trailing_zeros {
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+payload_length as u64-1)));
try_IO!(binary_file_path, binary_file.write(&[0u8]));
}
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
for _ in 0..payload_length/4 {
let mut buffer = [0u8; 4];
try_IO!(binary_file_path, binary_file.read(&mut buffer));
check_sum = check_sum.wrapping_add((&buffer[0..4]).read_u32::<LittleEndian>().unwrap());
}
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(check_sum).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+12)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header[12..16]));
println!(" {:08X} check sum", check_sum.swap_bytes());
}
| {
if in_file.ehdr.machine != elf::types::EM_AARCH64 {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[1].push(in_file_path);
} | conditional_block |
main.rs | extern crate byteorder;
extern crate elf;
use std::path::PathBuf;
use std::fs::{File, OpenOptions};
use std::io::*;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::process::Command;
static BOOT_FILE_BLOCK_SIZE :u32 = 512;
static BOOT_FILE_HEADER_LENGTH :u32 = 20;
macro_rules! try_IO {
($file_path:ident, $expr:expr) => (match $expr {
Ok(value) => value,
Err(error) => {
println!("Error in {:?}: {:?}", $file_path, error);
return;
}
})
}
fn main() {
let linker_path = match std::env::var("LD") {
Ok(value) => value,
Err(_) => {
println!("Could not find linker");
return;
},
};
let args: Vec<_> = std::env::args().collect();
if args.len() < 5 {
println!("Usage: LD = [linker] build_tool [virtual_offset] [physical_offset] [out.bin] [in1.o] [in2.o] [in3.o]...");
return;
}
let virtual_offset = u64::from_str_radix(&args[1][2..], 16).unwrap();
let physical_offset = u64::from_str_radix(&args[2][2..], 16).unwrap();
let target = &args[3];
if target.len() < 5 || &target[target.len()-4..target.len()]!= ".bin" {
println!("Output filename is invalid");
return;
}
let mut object_files :[Vec<PathBuf>; 2] = [Vec::new(), Vec::new()];
for in_file_path_str in &args[4..] {
let in_file_path = PathBuf::from(in_file_path_str);
let in_file = try_IO!(in_file_path, elf::File::open_path(&in_file_path));
if in_file.ehdr.osabi!= elf::types::ELFOSABI_NONE {
println!("{:?} is of wrong ABI", in_file_path);
return;
}
if in_file.ehdr.data!= elf::types::ELFDATA2LSB {
println!("{:?} is of wrong endianess", in_file_path);
return;
}
match in_file.ehdr.class {
elf::types::ELFCLASS32 => {
if in_file.ehdr.machine!= elf::types::EM_ARM {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[0].push(in_file_path);
},
elf::types::ELFCLASS64 => {
if in_file.ehdr.machine!= elf::types::EM_AARCH64 {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[1].push(in_file_path);
},
elf::types::Class(_) => {
println!("{:?} is of unknown architecture size", in_file_path);
return;
},
};
}
let binary_file_path = PathBuf::from(target);
let mut binary_file = try_IO!(binary_file_path, OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&binary_file_path));
let mut payload_length :u32 = BOOT_FILE_HEADER_LENGTH;
let mut check_sum :u32 = 0;
let mut entry_point :u64 = 0;
let mut virtual_address = virtual_offset+BOOT_FILE_HEADER_LENGTH as u64;
for architecture in 0..2 {
if object_files[architecture].len() == 0 {
continue;
}
let architecture_names = ["32", "64"];
let architecture_target = format!("{}{}", &target[..target.len()-4], architecture_names[architecture]);
let linker_script_file_path = PathBuf::from(format!("{}.lds", architecture_target));
let elf_file_path = PathBuf::from(format!("{}.elf", architecture_target));
let mut linker_script = try_IO!(linker_script_file_path, File::create(&linker_script_file_path));
try_IO!(linker_script_file_path, linker_script.write(b"SECTIONS {\n"));
try_IO!(linker_script_file_path, linker_script.write(format!(" . = 0x{:08X};", virtual_address).as_bytes()));
try_IO!(linker_script_file_path, linker_script.write(b"
.text : { *(.text) }
.rodata : { *(.rodata) }
.data : { *(.data) }
.bss : { *(.bss) }
/DISCARD/ : { *(.ARM.exidx*) }
/DISCARD/ : { *(.comment) }
}"));
println!("Linking: {:?}", elf_file_path);
try_IO!(linker_path, Command::new(&linker_path)
.arg("-flavor").arg("gnu")
.arg("-s")
.arg("--script").arg(linker_script_file_path)
.arg("-o").arg(&elf_file_path)
.args(&object_files[architecture])
.status());
let in_file = try_IO!(elf_file_path, elf::File::open_path(&elf_file_path));
if entry_point == 0 {
entry_point = in_file.ehdr.entry;
}
for section in &in_file.sections {
if section.shdr.size == 0 || section.shdr.shtype!= elf::types::SHT_PROGBITS {
continue;
}
if section.shdr.addr < virtual_address {
println!("{:?} section virtual addresses are in wrong order", elf_file_path);
return;
}
let physical_address = section.shdr.addr-virtual_offset+physical_offset;
payload_length += (section.shdr.addr-virtual_address) as u32;
virtual_address = section.shdr.addr+section.shdr.size;
println!(" {:08X} {:08X} {:08X} {}", section.shdr.addr, section.shdr.addr+section.shdr.size, physical_address, section.shdr.name);
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_address)));
try_IO!(binary_file_path, binary_file.write(§ion.data));
payload_length += section.shdr.size as u32;
}
}
println!("Building: {:?}", binary_file_path);
let needs_trailing_zeros = payload_length%BOOT_FILE_BLOCK_SIZE > 0;
println!(" {} bytes", payload_length);
payload_length = (payload_length+BOOT_FILE_BLOCK_SIZE-1)/BOOT_FILE_BLOCK_SIZE;
println!(" {} blocks of {} bytes", payload_length, BOOT_FILE_BLOCK_SIZE);
payload_length *= BOOT_FILE_BLOCK_SIZE;
println!(" {:08X} entry point", entry_point);
entry_point = (entry_point-virtual_offset)/4;
if entry_point > 0xEFFFFF {
println!("Entry point is out of reach");
return;
}
let mut boot_file_header = [0u8; 20];
let jump_instruction :u32 = if object_files[0].len() > 0
{ 0xEA000000|(entry_point as u32-2) } else
{ 0x14000000|(entry_point as u32) };
(&mut boot_file_header[0..4]).write_u32::<LittleEndian>(jump_instruction).unwrap();
(&mut boot_file_header[4..12]).clone_from_slice(b"eGON.BT0");
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(0x5F0A6C39).unwrap(); | if needs_trailing_zeros {
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+payload_length as u64-1)));
try_IO!(binary_file_path, binary_file.write(&[0u8]));
}
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
for _ in 0..payload_length/4 {
let mut buffer = [0u8; 4];
try_IO!(binary_file_path, binary_file.read(&mut buffer));
check_sum = check_sum.wrapping_add((&buffer[0..4]).read_u32::<LittleEndian>().unwrap());
}
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(check_sum).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+12)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header[12..16]));
println!(" {:08X} check sum", check_sum.swap_bytes());
} | (&mut boot_file_header[16..20]).write_u32::<LittleEndian>(payload_length).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header)); | random_line_split |
main.rs | extern crate byteorder;
extern crate elf;
use std::path::PathBuf;
use std::fs::{File, OpenOptions};
use std::io::*;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::process::Command;
static BOOT_FILE_BLOCK_SIZE :u32 = 512;
static BOOT_FILE_HEADER_LENGTH :u32 = 20;
macro_rules! try_IO {
($file_path:ident, $expr:expr) => (match $expr {
Ok(value) => value,
Err(error) => {
println!("Error in {:?}: {:?}", $file_path, error);
return;
}
})
}
fn main() | }
let mut object_files :[Vec<PathBuf>; 2] = [Vec::new(), Vec::new()];
for in_file_path_str in &args[4..] {
let in_file_path = PathBuf::from(in_file_path_str);
let in_file = try_IO!(in_file_path, elf::File::open_path(&in_file_path));
if in_file.ehdr.osabi!= elf::types::ELFOSABI_NONE {
println!("{:?} is of wrong ABI", in_file_path);
return;
}
if in_file.ehdr.data!= elf::types::ELFDATA2LSB {
println!("{:?} is of wrong endianess", in_file_path);
return;
}
match in_file.ehdr.class {
elf::types::ELFCLASS32 => {
if in_file.ehdr.machine!= elf::types::EM_ARM {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[0].push(in_file_path);
},
elf::types::ELFCLASS64 => {
if in_file.ehdr.machine!= elf::types::EM_AARCH64 {
println!("{:?} is of wrong machine architecture", in_file_path);
return;
}
object_files[1].push(in_file_path);
},
elf::types::Class(_) => {
println!("{:?} is of unknown architecture size", in_file_path);
return;
},
};
}
let binary_file_path = PathBuf::from(target);
let mut binary_file = try_IO!(binary_file_path, OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&binary_file_path));
let mut payload_length :u32 = BOOT_FILE_HEADER_LENGTH;
let mut check_sum :u32 = 0;
let mut entry_point :u64 = 0;
let mut virtual_address = virtual_offset+BOOT_FILE_HEADER_LENGTH as u64;
for architecture in 0..2 {
if object_files[architecture].len() == 0 {
continue;
}
let architecture_names = ["32", "64"];
let architecture_target = format!("{}{}", &target[..target.len()-4], architecture_names[architecture]);
let linker_script_file_path = PathBuf::from(format!("{}.lds", architecture_target));
let elf_file_path = PathBuf::from(format!("{}.elf", architecture_target));
let mut linker_script = try_IO!(linker_script_file_path, File::create(&linker_script_file_path));
try_IO!(linker_script_file_path, linker_script.write(b"SECTIONS {\n"));
try_IO!(linker_script_file_path, linker_script.write(format!(" . = 0x{:08X};", virtual_address).as_bytes()));
try_IO!(linker_script_file_path, linker_script.write(b"
.text : { *(.text) }
.rodata : { *(.rodata) }
.data : { *(.data) }
.bss : { *(.bss) }
/DISCARD/ : { *(.ARM.exidx*) }
/DISCARD/ : { *(.comment) }
}"));
println!("Linking: {:?}", elf_file_path);
try_IO!(linker_path, Command::new(&linker_path)
.arg("-flavor").arg("gnu")
.arg("-s")
.arg("--script").arg(linker_script_file_path)
.arg("-o").arg(&elf_file_path)
.args(&object_files[architecture])
.status());
let in_file = try_IO!(elf_file_path, elf::File::open_path(&elf_file_path));
if entry_point == 0 {
entry_point = in_file.ehdr.entry;
}
for section in &in_file.sections {
if section.shdr.size == 0 || section.shdr.shtype!= elf::types::SHT_PROGBITS {
continue;
}
if section.shdr.addr < virtual_address {
println!("{:?} section virtual addresses are in wrong order", elf_file_path);
return;
}
let physical_address = section.shdr.addr-virtual_offset+physical_offset;
payload_length += (section.shdr.addr-virtual_address) as u32;
virtual_address = section.shdr.addr+section.shdr.size;
println!(" {:08X} {:08X} {:08X} {}", section.shdr.addr, section.shdr.addr+section.shdr.size, physical_address, section.shdr.name);
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_address)));
try_IO!(binary_file_path, binary_file.write(§ion.data));
payload_length += section.shdr.size as u32;
}
}
println!("Building: {:?}", binary_file_path);
let needs_trailing_zeros = payload_length%BOOT_FILE_BLOCK_SIZE > 0;
println!(" {} bytes", payload_length);
payload_length = (payload_length+BOOT_FILE_BLOCK_SIZE-1)/BOOT_FILE_BLOCK_SIZE;
println!(" {} blocks of {} bytes", payload_length, BOOT_FILE_BLOCK_SIZE);
payload_length *= BOOT_FILE_BLOCK_SIZE;
println!(" {:08X} entry point", entry_point);
entry_point = (entry_point-virtual_offset)/4;
if entry_point > 0xEFFFFF {
println!("Entry point is out of reach");
return;
}
let mut boot_file_header = [0u8; 20];
let jump_instruction :u32 = if object_files[0].len() > 0
{ 0xEA000000|(entry_point as u32-2) } else
{ 0x14000000|(entry_point as u32) };
(&mut boot_file_header[0..4]).write_u32::<LittleEndian>(jump_instruction).unwrap();
(&mut boot_file_header[4..12]).clone_from_slice(b"eGON.BT0");
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(0x5F0A6C39).unwrap();
(&mut boot_file_header[16..20]).write_u32::<LittleEndian>(payload_length).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header));
if needs_trailing_zeros {
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+payload_length as u64-1)));
try_IO!(binary_file_path, binary_file.write(&[0u8]));
}
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset)));
for _ in 0..payload_length/4 {
let mut buffer = [0u8; 4];
try_IO!(binary_file_path, binary_file.read(&mut buffer));
check_sum = check_sum.wrapping_add((&buffer[0..4]).read_u32::<LittleEndian>().unwrap());
}
(&mut boot_file_header[12..16]).write_u32::<LittleEndian>(check_sum).unwrap();
try_IO!(binary_file_path, binary_file.seek(SeekFrom::Start(physical_offset+12)));
try_IO!(binary_file_path, binary_file.write(&boot_file_header[12..16]));
println!(" {:08X} check sum", check_sum.swap_bytes());
}
| {
let linker_path = match std::env::var("LD") {
Ok(value) => value,
Err(_) => {
println!("Could not find linker");
return;
},
};
let args: Vec<_> = std::env::args().collect();
if args.len() < 5 {
println!("Usage: LD = [linker] build_tool [virtual_offset] [physical_offset] [out.bin] [in1.o] [in2.o] [in3.o] ...");
return;
}
let virtual_offset = u64::from_str_radix(&args[1][2..], 16).unwrap();
let physical_offset = u64::from_str_radix(&args[2][2..], 16).unwrap();
let target = &args[3];
if target.len() < 5 || &target[target.len()-4..target.len()] != ".bin" {
println!("Output filename is invalid");
return; | identifier_body |
args.rs | //! The Windows command line is just a string
//! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string>
//!
//! This module implements the parsing necessary to turn that string into a list of arguments.
#[cfg(test)]
mod tests;
use crate::ffi::OsString;
use crate::fmt;
use crate::marker::PhantomData;
use crate::num::NonZeroU16;
use crate::os::windows::prelude::*;
use crate::path::PathBuf;
use crate::ptr::NonNull;
use crate::sys::c;
use crate::sys::windows::os::current_exe;
use crate::vec;
use core::iter;
pub fn args() -> Args {
// SAFETY: `GetCommandLineW` returns a pointer to a null terminated UTF-16
// string so it's safe for `WStrUnits` to use.
unsafe {
let lp_cmd_line = c::GetCommandLineW();
let parsed_args_list = parse_lp_cmd_line(WStrUnits::new(lp_cmd_line), || {
current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())
});
Args { parsed_args_list: parsed_args_list.into_iter() }
}
}
/// Implements the Windows command-line argument parsing algorithm.
///
/// Microsoft's documentation for the Windows CLI argument format can be found at
/// <https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments>
///
/// A more in-depth explanation is here:
/// <https://daviddeley.com/autohotkey/parameters/parameters.htm#WIN>
///
/// Windows includes a function to do command line parsing in shell32.dll.
/// However, this is not used for two reasons:
///
/// 1. Linking with that DLL causes the process to be registered as a GUI application.
/// GUI applications add a bunch of overhead, even if no windows are drawn. See
/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
///
/// 2. It does not follow the modern C/C++ argv rules outlined in the first two links above.
///
/// This function was tested for equivalence to the C/C++ parsing rules using an
/// extensive test suite available at
/// <https://github.com/ChrisDenton/winarg/tree/std>.
fn parse_lp_cmd_line<'a, F: Fn() -> OsString>(
lp_cmd_line: Option<WStrUnits<'a>>,
exe_name: F,
) -> Vec<OsString> {
const BACKSLASH: NonZeroU16 = NonZeroU16::new(b'\\' as u16).unwrap();
const QUOTE: NonZeroU16 = NonZeroU16::new(b'"' as u16).unwrap();
const TAB: NonZeroU16 = NonZeroU16::new(b'\t' as u16).unwrap();
const SPACE: NonZeroU16 = NonZeroU16::new(b''as u16).unwrap();
let mut ret_val = Vec::new();
// If the cmd line pointer is null or it points to an empty string then
// return the name of the executable as argv[0].
if lp_cmd_line.as_ref().and_then(|cmd| cmd.peek()).is_none() {
ret_val.push(exe_name());
return ret_val;
}
let mut code_units = lp_cmd_line.unwrap();
// The executable name at the beginning is special.
let mut in_quotes = false;
let mut cur = Vec::new();
for w in &mut code_units {
match w {
// A quote mark always toggles `in_quotes` no matter what because
// there are no escape characters when parsing the executable name.
QUOTE => in_quotes =!in_quotes,
// If not `in_quotes` then whitespace ends argv[0].
SPACE | TAB if!in_quotes => break,
// In all other cases the code unit is taken literally.
_ => cur.push(w.get()),
}
}
// Skip whitespace.
code_units.advance_while(|w| w == SPACE || w == TAB);
ret_val.push(OsString::from_wide(&cur));
// Parse the arguments according to these rules:
// * All code units are taken literally except space, tab, quote and backslash.
// * When not `in_quotes`, space and tab separate arguments. Consecutive spaces and tabs are
// treated as a single separator.
// * A space or tab `in_quotes` is taken literally.
// * A quote toggles `in_quotes` mode unless it's escaped. An escaped quote is taken literally.
// * A quote can be escaped if preceded by an odd number of backslashes.
// * If any number of backslashes is immediately followed by a quote then the number of
// backslashes is halved (rounding down).
// * Backslashes not followed by a quote are all taken literally.
// * If `in_quotes` then a quote can also be escaped using another quote
// (i.e. two consecutive quotes become one literal quote).
let mut cur = Vec::new();
let mut in_quotes = false;
while let Some(w) = code_units.next() {
match w {
// If not `in_quotes`, a space or tab ends the argument.
SPACE | TAB if!in_quotes => {
ret_val.push(OsString::from_wide(&cur[..]));
cur.truncate(0);
// Skip whitespace.
code_units.advance_while(|w| w == SPACE || w == TAB);
}
// Backslashes can escape quotes or backslashes but only if consecutive backslashes are followed by a quote.
BACKSLASH => {
let backslash_count = code_units.advance_while(|w| w == BACKSLASH) + 1;
if code_units.peek() == Some(QUOTE) {
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count / 2));
// The quote is escaped if there are an odd number of backslashes.
if backslash_count % 2 == 1 {
code_units.next();
cur.push(QUOTE.get());
}
} else {
// If there is no quote on the end then there is no escaping.
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count));
}
}
// If `in_quotes` and not backslash escaped (see above) then a quote either
// unsets `in_quote` or is escaped by another quote.
QUOTE if in_quotes => match code_units.peek() {
// Two consecutive quotes when `in_quotes` produces one literal quote.
Some(QUOTE) => {
cur.push(QUOTE.get());
code_units.next();
}
// Otherwise set `in_quotes`.
Some(_) => in_quotes = false,
// The end of the command line.
// Push `cur` even if empty, which we do by breaking while `in_quotes` is still set.
None => break,
},
// If not `in_quotes` and not BACKSLASH escaped (see above) then a quote sets `in_quote`.
QUOTE => in_quotes = true,
// Everything else is always taken literally.
_ => cur.push(w.get()),
}
}
// Push the final argument, if any.
if!cur.is_empty() || in_quotes {
ret_val.push(OsString::from_wide(&cur[..]));
}
ret_val
}
pub struct Args {
parsed_args_list: vec::IntoIter<OsString>,
}
impl fmt::Debug for Args {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.parsed_args_list.as_slice().fmt(f)
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.parsed_args_list.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.parsed_args_list.size_hint()
}
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> {
self.parsed_args_list.next_back()
}
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize {
self.parsed_args_list.len()
}
}
/// A safe iterator over a LPWSTR
/// (aka a pointer to a series of UTF-16 code units terminated by a NULL).
struct WStrUnits<'a> {
// The pointer must never be null...
lpwstr: NonNull<u16>,
//...and the memory it points to must be valid for this lifetime.
lifetime: PhantomData<&'a [u16]>,
}
impl WStrUnits<'_> {
/// Create the iterator. Returns `None` if `lpwstr` is null.
///
/// SAFETY: `lpwstr` must point to a null-terminated wide string that lives
/// at least as long as the lifetime of this struct.
unsafe fn | (lpwstr: *const u16) -> Option<Self> {
Some(Self { lpwstr: NonNull::new(lpwstr as _)?, lifetime: PhantomData })
}
fn peek(&self) -> Option<NonZeroU16> {
// SAFETY: It's always safe to read the current item because we don't
// ever move out of the array's bounds.
unsafe { NonZeroU16::new(*self.lpwstr.as_ptr()) }
}
/// Advance the iterator while `predicate` returns true.
/// Returns the number of items it advanced by.
fn advance_while<P: FnMut(NonZeroU16) -> bool>(&mut self, mut predicate: P) -> usize {
let mut counter = 0;
while let Some(w) = self.peek() {
if!predicate(w) {
break;
}
counter += 1;
self.next();
}
counter
}
}
impl Iterator for WStrUnits<'_> {
// This can never return zero as that marks the end of the string.
type Item = NonZeroU16;
fn next(&mut self) -> Option<NonZeroU16> {
// SAFETY: If NULL is reached we immediately return.
// Therefore it's safe to advance the pointer after that.
unsafe {
let next = self.peek()?;
self.lpwstr = NonNull::new_unchecked(self.lpwstr.as_ptr().add(1));
Some(next)
}
}
}
| new | identifier_name |
args.rs | //! The Windows command line is just a string
//! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string>
//!
//! This module implements the parsing necessary to turn that string into a list of arguments.
#[cfg(test)]
mod tests;
use crate::ffi::OsString;
use crate::fmt;
use crate::marker::PhantomData;
use crate::num::NonZeroU16;
use crate::os::windows::prelude::*;
use crate::path::PathBuf;
use crate::ptr::NonNull;
use crate::sys::c;
use crate::sys::windows::os::current_exe;
use crate::vec;
use core::iter;
pub fn args() -> Args {
// SAFETY: `GetCommandLineW` returns a pointer to a null terminated UTF-16
// string so it's safe for `WStrUnits` to use.
unsafe {
let lp_cmd_line = c::GetCommandLineW();
let parsed_args_list = parse_lp_cmd_line(WStrUnits::new(lp_cmd_line), || {
current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())
});
Args { parsed_args_list: parsed_args_list.into_iter() }
}
}
/// Implements the Windows command-line argument parsing algorithm.
///
/// Microsoft's documentation for the Windows CLI argument format can be found at
/// <https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments>
///
/// A more in-depth explanation is here:
/// <https://daviddeley.com/autohotkey/parameters/parameters.htm#WIN>
///
/// Windows includes a function to do command line parsing in shell32.dll.
/// However, this is not used for two reasons:
///
/// 1. Linking with that DLL causes the process to be registered as a GUI application.
/// GUI applications add a bunch of overhead, even if no windows are drawn. See
/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
///
/// 2. It does not follow the modern C/C++ argv rules outlined in the first two links above.
///
/// This function was tested for equivalence to the C/C++ parsing rules using an
/// extensive test suite available at
/// <https://github.com/ChrisDenton/winarg/tree/std>.
fn parse_lp_cmd_line<'a, F: Fn() -> OsString>(
lp_cmd_line: Option<WStrUnits<'a>>,
exe_name: F,
) -> Vec<OsString> | // A quote mark always toggles `in_quotes` no matter what because
// there are no escape characters when parsing the executable name.
QUOTE => in_quotes =!in_quotes,
// If not `in_quotes` then whitespace ends argv[0].
SPACE | TAB if!in_quotes => break,
// In all other cases the code unit is taken literally.
_ => cur.push(w.get()),
}
}
// Skip whitespace.
code_units.advance_while(|w| w == SPACE || w == TAB);
ret_val.push(OsString::from_wide(&cur));
// Parse the arguments according to these rules:
// * All code units are taken literally except space, tab, quote and backslash.
// * When not `in_quotes`, space and tab separate arguments. Consecutive spaces and tabs are
// treated as a single separator.
// * A space or tab `in_quotes` is taken literally.
// * A quote toggles `in_quotes` mode unless it's escaped. An escaped quote is taken literally.
// * A quote can be escaped if preceded by an odd number of backslashes.
// * If any number of backslashes is immediately followed by a quote then the number of
// backslashes is halved (rounding down).
// * Backslashes not followed by a quote are all taken literally.
// * If `in_quotes` then a quote can also be escaped using another quote
// (i.e. two consecutive quotes become one literal quote).
let mut cur = Vec::new();
let mut in_quotes = false;
while let Some(w) = code_units.next() {
match w {
// If not `in_quotes`, a space or tab ends the argument.
SPACE | TAB if!in_quotes => {
ret_val.push(OsString::from_wide(&cur[..]));
cur.truncate(0);
// Skip whitespace.
code_units.advance_while(|w| w == SPACE || w == TAB);
}
// Backslashes can escape quotes or backslashes but only if consecutive backslashes are followed by a quote.
BACKSLASH => {
let backslash_count = code_units.advance_while(|w| w == BACKSLASH) + 1;
if code_units.peek() == Some(QUOTE) {
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count / 2));
// The quote is escaped if there are an odd number of backslashes.
if backslash_count % 2 == 1 {
code_units.next();
cur.push(QUOTE.get());
}
} else {
// If there is no quote on the end then there is no escaping.
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count));
}
}
// If `in_quotes` and not backslash escaped (see above) then a quote either
// unsets `in_quote` or is escaped by another quote.
QUOTE if in_quotes => match code_units.peek() {
// Two consecutive quotes when `in_quotes` produces one literal quote.
Some(QUOTE) => {
cur.push(QUOTE.get());
code_units.next();
}
// Otherwise set `in_quotes`.
Some(_) => in_quotes = false,
// The end of the command line.
// Push `cur` even if empty, which we do by breaking while `in_quotes` is still set.
None => break,
},
// If not `in_quotes` and not BACKSLASH escaped (see above) then a quote sets `in_quote`.
QUOTE => in_quotes = true,
// Everything else is always taken literally.
_ => cur.push(w.get()),
}
}
// Push the final argument, if any.
if!cur.is_empty() || in_quotes {
ret_val.push(OsString::from_wide(&cur[..]));
}
ret_val
}
pub struct Args {
parsed_args_list: vec::IntoIter<OsString>,
}
impl fmt::Debug for Args {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.parsed_args_list.as_slice().fmt(f)
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.parsed_args_list.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.parsed_args_list.size_hint()
}
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> {
self.parsed_args_list.next_back()
}
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize {
self.parsed_args_list.len()
}
}
/// A safe iterator over a LPWSTR
/// (aka a pointer to a series of UTF-16 code units terminated by a NULL).
struct WStrUnits<'a> {
// The pointer must never be null...
lpwstr: NonNull<u16>,
//...and the memory it points to must be valid for this lifetime.
lifetime: PhantomData<&'a [u16]>,
}
impl WStrUnits<'_> {
/// Create the iterator. Returns `None` if `lpwstr` is null.
///
/// SAFETY: `lpwstr` must point to a null-terminated wide string that lives
/// at least as long as the lifetime of this struct.
unsafe fn new(lpwstr: *const u16) -> Option<Self> {
Some(Self { lpwstr: NonNull::new(lpwstr as _)?, lifetime: PhantomData })
}
fn peek(&self) -> Option<NonZeroU16> {
// SAFETY: It's always safe to read the current item because we don't
// ever move out of the array's bounds.
unsafe { NonZeroU16::new(*self.lpwstr.as_ptr()) }
}
/// Advance the iterator while `predicate` returns true.
/// Returns the number of items it advanced by.
fn advance_while<P: FnMut(NonZeroU16) -> bool>(&mut self, mut predicate: P) -> usize {
let mut counter = 0;
while let Some(w) = self.peek() {
if!predicate(w) {
break;
}
counter += 1;
self.next();
}
counter
}
}
impl Iterator for WStrUnits<'_> {
// This can never return zero as that marks the end of the string.
type Item = NonZeroU16;
fn next(&mut self) -> Option<NonZeroU16> {
// SAFETY: If NULL is reached we immediately return.
// Therefore it's safe to advance the pointer after that.
unsafe {
let next = self.peek()?;
self.lpwstr = NonNull::new_unchecked(self.lpwstr.as_ptr().add(1));
Some(next)
}
}
}
| {
const BACKSLASH: NonZeroU16 = NonZeroU16::new(b'\\' as u16).unwrap();
const QUOTE: NonZeroU16 = NonZeroU16::new(b'"' as u16).unwrap();
const TAB: NonZeroU16 = NonZeroU16::new(b'\t' as u16).unwrap();
const SPACE: NonZeroU16 = NonZeroU16::new(b' ' as u16).unwrap();
let mut ret_val = Vec::new();
// If the cmd line pointer is null or it points to an empty string then
// return the name of the executable as argv[0].
if lp_cmd_line.as_ref().and_then(|cmd| cmd.peek()).is_none() {
ret_val.push(exe_name());
return ret_val;
}
let mut code_units = lp_cmd_line.unwrap();
// The executable name at the beginning is special.
let mut in_quotes = false;
let mut cur = Vec::new();
for w in &mut code_units {
match w { | identifier_body |
args.rs | //! The Windows command line is just a string
//! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string>
//!
//! This module implements the parsing necessary to turn that string into a list of arguments.
#[cfg(test)]
mod tests;
use crate::ffi::OsString;
use crate::fmt;
use crate::marker::PhantomData;
use crate::num::NonZeroU16;
use crate::os::windows::prelude::*;
use crate::path::PathBuf;
use crate::ptr::NonNull;
use crate::sys::c;
use crate::sys::windows::os::current_exe;
use crate::vec;
use core::iter;
pub fn args() -> Args {
// SAFETY: `GetCommandLineW` returns a pointer to a null terminated UTF-16
// string so it's safe for `WStrUnits` to use.
unsafe {
let lp_cmd_line = c::GetCommandLineW();
let parsed_args_list = parse_lp_cmd_line(WStrUnits::new(lp_cmd_line), || {
current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())
});
Args { parsed_args_list: parsed_args_list.into_iter() }
}
}
/// Implements the Windows command-line argument parsing algorithm.
///
/// Microsoft's documentation for the Windows CLI argument format can be found at
/// <https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments>
///
/// A more in-depth explanation is here:
/// <https://daviddeley.com/autohotkey/parameters/parameters.htm#WIN>
///
/// Windows includes a function to do command line parsing in shell32.dll.
/// However, this is not used for two reasons:
///
/// 1. Linking with that DLL causes the process to be registered as a GUI application.
/// GUI applications add a bunch of overhead, even if no windows are drawn. See
/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
///
/// 2. It does not follow the modern C/C++ argv rules outlined in the first two links above.
///
/// This function was tested for equivalence to the C/C++ parsing rules using an
/// extensive test suite available at
/// <https://github.com/ChrisDenton/winarg/tree/std>.
fn parse_lp_cmd_line<'a, F: Fn() -> OsString>(
lp_cmd_line: Option<WStrUnits<'a>>,
exe_name: F,
) -> Vec<OsString> {
const BACKSLASH: NonZeroU16 = NonZeroU16::new(b'\\' as u16).unwrap();
const QUOTE: NonZeroU16 = NonZeroU16::new(b'"' as u16).unwrap();
const TAB: NonZeroU16 = NonZeroU16::new(b'\t' as u16).unwrap();
const SPACE: NonZeroU16 = NonZeroU16::new(b''as u16).unwrap();
let mut ret_val = Vec::new();
// If the cmd line pointer is null or it points to an empty string then
// return the name of the executable as argv[0].
if lp_cmd_line.as_ref().and_then(|cmd| cmd.peek()).is_none() {
ret_val.push(exe_name());
return ret_val;
}
let mut code_units = lp_cmd_line.unwrap();
// The executable name at the beginning is special.
let mut in_quotes = false;
let mut cur = Vec::new();
for w in &mut code_units {
match w {
// A quote mark always toggles `in_quotes` no matter what because
// there are no escape characters when parsing the executable name.
QUOTE => in_quotes =!in_quotes,
// If not `in_quotes` then whitespace ends argv[0].
SPACE | TAB if!in_quotes => break,
// In all other cases the code unit is taken literally.
_ => cur.push(w.get()),
}
}
// Skip whitespace.
code_units.advance_while(|w| w == SPACE || w == TAB);
ret_val.push(OsString::from_wide(&cur));
// Parse the arguments according to these rules:
// * All code units are taken literally except space, tab, quote and backslash.
// * When not `in_quotes`, space and tab separate arguments. Consecutive spaces and tabs are
// treated as a single separator.
// * A space or tab `in_quotes` is taken literally.
// * A quote toggles `in_quotes` mode unless it's escaped. An escaped quote is taken literally.
// * A quote can be escaped if preceded by an odd number of backslashes.
// * If any number of backslashes is immediately followed by a quote then the number of
// backslashes is halved (rounding down).
// * Backslashes not followed by a quote are all taken literally.
// * If `in_quotes` then a quote can also be escaped using another quote
// (i.e. two consecutive quotes become one literal quote).
let mut cur = Vec::new();
let mut in_quotes = false;
while let Some(w) = code_units.next() {
match w {
// If not `in_quotes`, a space or tab ends the argument.
SPACE | TAB if!in_quotes => {
ret_val.push(OsString::from_wide(&cur[..]));
cur.truncate(0);
// Skip whitespace.
code_units.advance_while(|w| w == SPACE || w == TAB);
}
// Backslashes can escape quotes or backslashes but only if consecutive backslashes are followed by a quote.
BACKSLASH => {
let backslash_count = code_units.advance_while(|w| w == BACKSLASH) + 1;
if code_units.peek() == Some(QUOTE) {
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count / 2));
// The quote is escaped if there are an odd number of backslashes.
if backslash_count % 2 == 1 {
code_units.next();
cur.push(QUOTE.get());
}
} else {
// If there is no quote on the end then there is no escaping.
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count));
}
}
// If `in_quotes` and not backslash escaped (see above) then a quote either
// unsets `in_quote` or is escaped by another quote.
QUOTE if in_quotes => match code_units.peek() {
// Two consecutive quotes when `in_quotes` produces one literal quote.
Some(QUOTE) => {
cur.push(QUOTE.get());
code_units.next();
}
// Otherwise set `in_quotes`. | },
// If not `in_quotes` and not BACKSLASH escaped (see above) then a quote sets `in_quote`.
QUOTE => in_quotes = true,
// Everything else is always taken literally.
_ => cur.push(w.get()),
}
}
// Push the final argument, if any.
if!cur.is_empty() || in_quotes {
ret_val.push(OsString::from_wide(&cur[..]));
}
ret_val
}
pub struct Args {
parsed_args_list: vec::IntoIter<OsString>,
}
impl fmt::Debug for Args {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.parsed_args_list.as_slice().fmt(f)
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.parsed_args_list.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.parsed_args_list.size_hint()
}
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> {
self.parsed_args_list.next_back()
}
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize {
self.parsed_args_list.len()
}
}
/// A safe iterator over a LPWSTR
/// (aka a pointer to a series of UTF-16 code units terminated by a NULL).
struct WStrUnits<'a> {
// The pointer must never be null...
lpwstr: NonNull<u16>,
//...and the memory it points to must be valid for this lifetime.
lifetime: PhantomData<&'a [u16]>,
}
impl WStrUnits<'_> {
/// Create the iterator. Returns `None` if `lpwstr` is null.
///
/// SAFETY: `lpwstr` must point to a null-terminated wide string that lives
/// at least as long as the lifetime of this struct.
unsafe fn new(lpwstr: *const u16) -> Option<Self> {
Some(Self { lpwstr: NonNull::new(lpwstr as _)?, lifetime: PhantomData })
}
fn peek(&self) -> Option<NonZeroU16> {
// SAFETY: It's always safe to read the current item because we don't
// ever move out of the array's bounds.
unsafe { NonZeroU16::new(*self.lpwstr.as_ptr()) }
}
/// Advance the iterator while `predicate` returns true.
/// Returns the number of items it advanced by.
fn advance_while<P: FnMut(NonZeroU16) -> bool>(&mut self, mut predicate: P) -> usize {
let mut counter = 0;
while let Some(w) = self.peek() {
if!predicate(w) {
break;
}
counter += 1;
self.next();
}
counter
}
}
impl Iterator for WStrUnits<'_> {
// This can never return zero as that marks the end of the string.
type Item = NonZeroU16;
fn next(&mut self) -> Option<NonZeroU16> {
// SAFETY: If NULL is reached we immediately return.
// Therefore it's safe to advance the pointer after that.
unsafe {
let next = self.peek()?;
self.lpwstr = NonNull::new_unchecked(self.lpwstr.as_ptr().add(1));
Some(next)
}
}
} | Some(_) => in_quotes = false,
// The end of the command line.
// Push `cur` even if empty, which we do by breaking while `in_quotes` is still set.
None => break, | random_line_split |
ifchanged_block.rs | use std::io::Write;
use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt};
use liquid_core::Language;
use liquid_core::Renderable;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::Template;
use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter};
#[derive(Copy, Clone, Debug, Default)]
pub struct IfChangedBlock;
impl IfChangedBlock {
pub fn new() -> Self |
}
impl BlockReflection for IfChangedBlock {
fn start_tag(&self) -> &str {
"ifchanged"
}
fn end_tag(&self) -> &str {
"endifchanged"
}
fn description(&self) -> &str {
""
}
}
impl ParseBlock for IfChangedBlock {
fn parse(
&self,
mut arguments: TagTokenIter<'_>,
mut tokens: TagBlock<'_, '_>,
options: &Language,
) -> Result<Box<dyn Renderable>> {
// no arguments should be supplied, trying to supply them is an error
arguments.expect_nothing()?;
let if_changed = Template::new(tokens.parse_all(options)?);
tokens.assert_empty();
Ok(Box::new(IfChanged { if_changed }))
}
fn reflection(&self) -> &dyn BlockReflection {
self
}
}
#[derive(Debug)]
struct IfChanged {
if_changed: Template,
}
impl IfChanged {
fn trace(&self) -> String {
"{{% ifchanged %}}".to_owned()
}
}
impl Renderable for IfChanged {
fn render_to(&self, writer: &mut dyn Write, runtime: &dyn Runtime) -> Result<()> {
let mut rendered = Vec::new();
self.if_changed
.render_to(&mut rendered, runtime)
.trace_with(|| self.trace().into())?;
let rendered = String::from_utf8(rendered).expect("render only writes UTF-8");
if runtime
.registers()
.get_mut::<ChangedRegister>()
.has_changed(&rendered)
{
write!(writer, "{}", rendered).replace("Failed to render")?;
}
Ok(())
}
}
/// Remembers the content of the last rendered `ifstate` block.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ChangedRegister {
last_rendered: Option<String>,
}
impl ChangedRegister {
/// Checks whether or not a new rendered `&str` is different from
/// `last_rendered` and updates `last_rendered` value to the new value.
fn has_changed(&mut self, rendered: &str) -> bool {
let has_changed = if let Some(last_rendered) = &self.last_rendered {
last_rendered!= rendered
} else {
true
};
self.last_rendered = Some(rendered.to_owned());
has_changed
}
}
#[cfg(test)]
mod test {
use super::*;
use liquid_core::parser;
use liquid_core::runtime;
use liquid_core::runtime::RuntimeBuilder;
use crate::stdlib;
fn options() -> Language {
let mut options = Language::default();
options
.blocks
.register("ifchanged".to_string(), IfChangedBlock.into());
options
.blocks
.register("for".to_string(), stdlib::ForBlock.into());
options
.blocks
.register("if".to_string(), stdlib::IfBlock.into());
options
}
#[test]
fn test_ifchanged_block() {
let text = concat!(
"{% for a in (0..10) %}",
"{% ifchanged %}",
"\nHey! ",
"{% if a > 5 %}",
"Numbers are now bigger than 5!",
"{% endif %}",
"{% endifchanged %}",
"{% endfor %}",
);
let template = parser::parse(text, &options())
.map(runtime::Template::new)
.unwrap();
let runtime = RuntimeBuilder::new().build();
let output = template.render(&runtime).unwrap();
assert_eq!(output, "\nHey! \nHey! Numbers are now bigger than 5!");
}
}
| {
Self::default()
} | identifier_body |
ifchanged_block.rs | use std::io::Write;
use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt};
use liquid_core::Language;
use liquid_core::Renderable;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::Template;
use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter};
#[derive(Copy, Clone, Debug, Default)]
pub struct IfChangedBlock;
impl IfChangedBlock {
pub fn new() -> Self {
Self::default()
}
}
impl BlockReflection for IfChangedBlock {
fn start_tag(&self) -> &str {
"ifchanged"
}
fn end_tag(&self) -> &str {
"endifchanged"
}
fn description(&self) -> &str {
""
}
}
impl ParseBlock for IfChangedBlock {
fn parse(
&self,
mut arguments: TagTokenIter<'_>,
mut tokens: TagBlock<'_, '_>,
options: &Language,
) -> Result<Box<dyn Renderable>> {
// no arguments should be supplied, trying to supply them is an error
arguments.expect_nothing()?;
let if_changed = Template::new(tokens.parse_all(options)?);
tokens.assert_empty();
Ok(Box::new(IfChanged { if_changed }))
}
fn reflection(&self) -> &dyn BlockReflection {
self
}
}
#[derive(Debug)]
struct IfChanged {
if_changed: Template,
}
impl IfChanged {
fn trace(&self) -> String {
"{{% ifchanged %}}".to_owned()
}
}
impl Renderable for IfChanged {
fn render_to(&self, writer: &mut dyn Write, runtime: &dyn Runtime) -> Result<()> {
let mut rendered = Vec::new();
self.if_changed
.render_to(&mut rendered, runtime)
.trace_with(|| self.trace().into())?;
let rendered = String::from_utf8(rendered).expect("render only writes UTF-8");
if runtime
.registers()
.get_mut::<ChangedRegister>()
.has_changed(&rendered)
{
write!(writer, "{}", rendered).replace("Failed to render")?;
}
Ok(())
}
}
/// Remembers the content of the last rendered `ifstate` block.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ChangedRegister {
last_rendered: Option<String>,
}
| let has_changed = if let Some(last_rendered) = &self.last_rendered {
last_rendered!= rendered
} else {
true
};
self.last_rendered = Some(rendered.to_owned());
has_changed
}
}
#[cfg(test)]
mod test {
use super::*;
use liquid_core::parser;
use liquid_core::runtime;
use liquid_core::runtime::RuntimeBuilder;
use crate::stdlib;
fn options() -> Language {
let mut options = Language::default();
options
.blocks
.register("ifchanged".to_string(), IfChangedBlock.into());
options
.blocks
.register("for".to_string(), stdlib::ForBlock.into());
options
.blocks
.register("if".to_string(), stdlib::IfBlock.into());
options
}
#[test]
fn test_ifchanged_block() {
let text = concat!(
"{% for a in (0..10) %}",
"{% ifchanged %}",
"\nHey! ",
"{% if a > 5 %}",
"Numbers are now bigger than 5!",
"{% endif %}",
"{% endifchanged %}",
"{% endfor %}",
);
let template = parser::parse(text, &options())
.map(runtime::Template::new)
.unwrap();
let runtime = RuntimeBuilder::new().build();
let output = template.render(&runtime).unwrap();
assert_eq!(output, "\nHey! \nHey! Numbers are now bigger than 5!");
}
} | impl ChangedRegister {
/// Checks whether or not a new rendered `&str` is different from
/// `last_rendered` and updates `last_rendered` value to the new value.
fn has_changed(&mut self, rendered: &str) -> bool { | random_line_split |
ifchanged_block.rs | use std::io::Write;
use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt};
use liquid_core::Language;
use liquid_core::Renderable;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::Template;
use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter};
#[derive(Copy, Clone, Debug, Default)]
pub struct IfChangedBlock;
impl IfChangedBlock {
pub fn new() -> Self {
Self::default()
}
}
impl BlockReflection for IfChangedBlock {
fn start_tag(&self) -> &str {
"ifchanged"
}
fn end_tag(&self) -> &str {
"endifchanged"
}
fn description(&self) -> &str {
""
}
}
impl ParseBlock for IfChangedBlock {
fn parse(
&self,
mut arguments: TagTokenIter<'_>,
mut tokens: TagBlock<'_, '_>,
options: &Language,
) -> Result<Box<dyn Renderable>> {
// no arguments should be supplied, trying to supply them is an error
arguments.expect_nothing()?;
let if_changed = Template::new(tokens.parse_all(options)?);
tokens.assert_empty();
Ok(Box::new(IfChanged { if_changed }))
}
fn reflection(&self) -> &dyn BlockReflection {
self
}
}
#[derive(Debug)]
struct IfChanged {
if_changed: Template,
}
impl IfChanged {
fn trace(&self) -> String {
"{{% ifchanged %}}".to_owned()
}
}
impl Renderable for IfChanged {
fn render_to(&self, writer: &mut dyn Write, runtime: &dyn Runtime) -> Result<()> {
let mut rendered = Vec::new();
self.if_changed
.render_to(&mut rendered, runtime)
.trace_with(|| self.trace().into())?;
let rendered = String::from_utf8(rendered).expect("render only writes UTF-8");
if runtime
.registers()
.get_mut::<ChangedRegister>()
.has_changed(&rendered)
{
write!(writer, "{}", rendered).replace("Failed to render")?;
}
Ok(())
}
}
/// Remembers the content of the last rendered `ifstate` block.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ChangedRegister {
last_rendered: Option<String>,
}
impl ChangedRegister {
/// Checks whether or not a new rendered `&str` is different from
/// `last_rendered` and updates `last_rendered` value to the new value.
fn has_changed(&mut self, rendered: &str) -> bool {
let has_changed = if let Some(last_rendered) = &self.last_rendered {
last_rendered!= rendered
} else {
true
};
self.last_rendered = Some(rendered.to_owned());
has_changed
}
}
#[cfg(test)]
mod test {
use super::*;
use liquid_core::parser;
use liquid_core::runtime;
use liquid_core::runtime::RuntimeBuilder;
use crate::stdlib;
fn | () -> Language {
let mut options = Language::default();
options
.blocks
.register("ifchanged".to_string(), IfChangedBlock.into());
options
.blocks
.register("for".to_string(), stdlib::ForBlock.into());
options
.blocks
.register("if".to_string(), stdlib::IfBlock.into());
options
}
#[test]
fn test_ifchanged_block() {
let text = concat!(
"{% for a in (0..10) %}",
"{% ifchanged %}",
"\nHey! ",
"{% if a > 5 %}",
"Numbers are now bigger than 5!",
"{% endif %}",
"{% endifchanged %}",
"{% endfor %}",
);
let template = parser::parse(text, &options())
.map(runtime::Template::new)
.unwrap();
let runtime = RuntimeBuilder::new().build();
let output = template.render(&runtime).unwrap();
assert_eq!(output, "\nHey! \nHey! Numbers are now bigger than 5!");
}
}
| options | identifier_name |
ifchanged_block.rs | use std::io::Write;
use liquid_core::error::{ResultLiquidExt, ResultLiquidReplaceExt};
use liquid_core::Language;
use liquid_core::Renderable;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::Template;
use liquid_core::{BlockReflection, ParseBlock, TagBlock, TagTokenIter};
#[derive(Copy, Clone, Debug, Default)]
pub struct IfChangedBlock;
impl IfChangedBlock {
pub fn new() -> Self {
Self::default()
}
}
impl BlockReflection for IfChangedBlock {
fn start_tag(&self) -> &str {
"ifchanged"
}
fn end_tag(&self) -> &str {
"endifchanged"
}
fn description(&self) -> &str {
""
}
}
impl ParseBlock for IfChangedBlock {
fn parse(
&self,
mut arguments: TagTokenIter<'_>,
mut tokens: TagBlock<'_, '_>,
options: &Language,
) -> Result<Box<dyn Renderable>> {
// no arguments should be supplied, trying to supply them is an error
arguments.expect_nothing()?;
let if_changed = Template::new(tokens.parse_all(options)?);
tokens.assert_empty();
Ok(Box::new(IfChanged { if_changed }))
}
fn reflection(&self) -> &dyn BlockReflection {
self
}
}
#[derive(Debug)]
struct IfChanged {
if_changed: Template,
}
impl IfChanged {
fn trace(&self) -> String {
"{{% ifchanged %}}".to_owned()
}
}
impl Renderable for IfChanged {
fn render_to(&self, writer: &mut dyn Write, runtime: &dyn Runtime) -> Result<()> {
let mut rendered = Vec::new();
self.if_changed
.render_to(&mut rendered, runtime)
.trace_with(|| self.trace().into())?;
let rendered = String::from_utf8(rendered).expect("render only writes UTF-8");
if runtime
.registers()
.get_mut::<ChangedRegister>()
.has_changed(&rendered)
{
write!(writer, "{}", rendered).replace("Failed to render")?;
}
Ok(())
}
}
/// Remembers the content of the last rendered `ifstate` block.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ChangedRegister {
last_rendered: Option<String>,
}
impl ChangedRegister {
/// Checks whether or not a new rendered `&str` is different from
/// `last_rendered` and updates `last_rendered` value to the new value.
fn has_changed(&mut self, rendered: &str) -> bool {
let has_changed = if let Some(last_rendered) = &self.last_rendered {
last_rendered!= rendered
} else | ;
self.last_rendered = Some(rendered.to_owned());
has_changed
}
}
#[cfg(test)]
mod test {
use super::*;
use liquid_core::parser;
use liquid_core::runtime;
use liquid_core::runtime::RuntimeBuilder;
use crate::stdlib;
fn options() -> Language {
let mut options = Language::default();
options
.blocks
.register("ifchanged".to_string(), IfChangedBlock.into());
options
.blocks
.register("for".to_string(), stdlib::ForBlock.into());
options
.blocks
.register("if".to_string(), stdlib::IfBlock.into());
options
}
#[test]
fn test_ifchanged_block() {
let text = concat!(
"{% for a in (0..10) %}",
"{% ifchanged %}",
"\nHey! ",
"{% if a > 5 %}",
"Numbers are now bigger than 5!",
"{% endif %}",
"{% endifchanged %}",
"{% endfor %}",
);
let template = parser::parse(text, &options())
.map(runtime::Template::new)
.unwrap();
let runtime = RuntimeBuilder::new().build();
let output = template.render(&runtime).unwrap();
assert_eq!(output, "\nHey! \nHey! Numbers are now bigger than 5!");
}
}
| {
true
} | 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 http://mozilla.org/MPL/2.0/. */
use devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace};
use script_thread::ScriptThread;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use style::attr::{AttrIdentifier, AttrValue};
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>,
/// the element that owns this attribute.
owner: MutNullableJS<Element>,
}
impl Attr {
fn new_inherited(local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Attr {
Attr {
reflector_: Reflector::new(),
identifier: AttrIdentifier {
local_name: local_name,
name: name,
namespace: namespace,
prefix: prefix,
},
value: DOMRefCell::new(value),
owner: MutNullableJS::new(owner),
}
}
pub fn new(window: &Window,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Root<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name,
value,
name,
namespace,
prefix,
owner),
window,
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &LocalName {
&self.identifier.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.identifier.namespace
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
self.identifier.prefix.as_ref()
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&**self.local_name())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
DOMString::from(&**self.value())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
if let Some(owner) = self.owner() {
let value = owner.parse_attribute(&self.identifier.namespace,
self.local_name(),
value);
self.set_value(value, &owner);
} else {
*self.value.borrow_mut() = AttrValue::String(value.into());
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&*self.identifier.name)
}
// https://dom.spec.whatwg.org/#dom-attr-nodename
fn NodeName(&self) -> DOMString {
self.Name()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
match self.identifier.namespace {
ns!() => None,
ref url => Some(DOMString::from(&**url)),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
self.prefix().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
let new_value = DOMString::from(&*value);
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation);
if owner.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(owner, reaction);
}
assert!(Some(owner) == self.owner().r());
owner.will_mutate_attr(self);
self.swap_value(&mut value);
if self.identifier.namespace == ns!() {
vtable_for(owner.upcast())
.attribute_mutated(self, AttributeMutation::Set(Some(&value)));
}
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn identifier(&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ns = &self.identifier.namespace;
match (self.owner(), owner) {
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.identifier.local_name).r()!= Some(self))
}
(Some(old), Some(new)) => assert!(&*old == new),
_ => {},
}
self.owner.set(owner);
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (*self.identifier.namespace).to_owned(),
name: String::from(self.Name()),
value: String::from(self.Value()),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> LocalName;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
} | #[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> LocalName {
(*self.unsafe_get()).identifier.local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
} | 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 http://mozilla.org/MPL/2.0/. */
use devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace};
use script_thread::ScriptThread;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use style::attr::{AttrIdentifier, AttrValue};
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>,
/// the element that owns this attribute.
owner: MutNullableJS<Element>,
}
impl Attr {
fn new_inherited(local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Attr {
Attr {
reflector_: Reflector::new(),
identifier: AttrIdentifier {
local_name: local_name,
name: name,
namespace: namespace,
prefix: prefix,
},
value: DOMRefCell::new(value),
owner: MutNullableJS::new(owner),
}
}
pub fn new(window: &Window,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Root<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name,
value,
name,
namespace,
prefix,
owner),
window,
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &LocalName {
&self.identifier.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.identifier.namespace
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
self.identifier.prefix.as_ref()
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&**self.local_name())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
DOMString::from(&**self.value())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
if let Some(owner) = self.owner() {
let value = owner.parse_attribute(&self.identifier.namespace,
self.local_name(),
value);
self.set_value(value, &owner);
} else {
*self.value.borrow_mut() = AttrValue::String(value.into());
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString |
// https://dom.spec.whatwg.org/#dom-attr-nodename
fn NodeName(&self) -> DOMString {
self.Name()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
match self.identifier.namespace {
ns!() => None,
ref url => Some(DOMString::from(&**url)),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
self.prefix().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
let new_value = DOMString::from(&*value);
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation);
if owner.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(owner, reaction);
}
assert!(Some(owner) == self.owner().r());
owner.will_mutate_attr(self);
self.swap_value(&mut value);
if self.identifier.namespace == ns!() {
vtable_for(owner.upcast())
.attribute_mutated(self, AttributeMutation::Set(Some(&value)));
}
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn identifier(&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ns = &self.identifier.namespace;
match (self.owner(), owner) {
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.identifier.local_name).r()!= Some(self))
}
(Some(old), Some(new)) => assert!(&*old == new),
_ => {},
}
self.owner.set(owner);
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (*self.identifier.namespace).to_owned(),
name: String::from(self.Name()),
value: String::from(self.Value()),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> LocalName;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> LocalName {
(*self.unsafe_get()).identifier.local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
| {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&*self.identifier.name)
} | 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 http://mozilla.org/MPL/2.0/. */
use devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace};
use script_thread::ScriptThread;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use style::attr::{AttrIdentifier, AttrValue};
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>,
/// the element that owns this attribute.
owner: MutNullableJS<Element>,
}
impl Attr {
fn new_inherited(local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Attr {
Attr {
reflector_: Reflector::new(),
identifier: AttrIdentifier {
local_name: local_name,
name: name,
namespace: namespace,
prefix: prefix,
},
value: DOMRefCell::new(value),
owner: MutNullableJS::new(owner),
}
}
pub fn new(window: &Window,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Root<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name,
value,
name,
namespace,
prefix,
owner),
window,
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &LocalName {
&self.identifier.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.identifier.namespace
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
self.identifier.prefix.as_ref()
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&**self.local_name())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
DOMString::from(&**self.value())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
if let Some(owner) = self.owner() {
let value = owner.parse_attribute(&self.identifier.namespace,
self.local_name(),
value);
self.set_value(value, &owner);
} else {
*self.value.borrow_mut() = AttrValue::String(value.into());
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&*self.identifier.name)
}
// https://dom.spec.whatwg.org/#dom-attr-nodename
fn NodeName(&self) -> DOMString {
self.Name()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
match self.identifier.namespace {
ns!() => None,
ref url => Some(DOMString::from(&**url)),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
self.prefix().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
let new_value = DOMString::from(&*value);
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation);
if owner.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(owner, reaction);
}
assert!(Some(owner) == self.owner().r());
owner.will_mutate_attr(self);
self.swap_value(&mut value);
if self.identifier.namespace == ns!() {
vtable_for(owner.upcast())
.attribute_mutated(self, AttributeMutation::Set(Some(&value)));
}
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn | (&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ns = &self.identifier.namespace;
match (self.owner(), owner) {
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.identifier.local_name).r()!= Some(self))
}
(Some(old), Some(new)) => assert!(&*old == new),
_ => {},
}
self.owner.set(owner);
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (*self.identifier.namespace).to_owned(),
name: String::from(self.Name()),
value: String::from(self.Value()),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> LocalName;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> LocalName {
(*self.unsafe_get()).identifier.local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
| identifier | identifier_name |
p114.rs | //! [Problem 114](https://projecteuler.net/problem=114) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn get_cnt((n, m): (u32, u32), map: &mut HashMap<(u32, u32), u64>) -> u64 {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
sum += get_cnt((n - (len + i) - 1, m), map); // red block and black block
} else |
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn solve() -> String {
let mut map = HashMap::new();
get_cnt((50, 3), &mut map).to_string()
}
problem!("16475640049", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt((1, 3), &mut map));
assert_eq!(1, get_cnt((2, 3), &mut map));
assert_eq!(2, get_cnt((3, 3), &mut map));
assert_eq!(4, get_cnt((4, 3), &mut map));
assert_eq!(17, get_cnt((7, 3), &mut map));
}
}
| {
sum += 1;
} | conditional_block |
p114.rs | //! [Problem 114](https://projecteuler.net/problem=114) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn get_cnt((n, m): (u32, u32), map: &mut HashMap<(u32, u32), u64>) -> u64 {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
sum += get_cnt((n - (len + i) - 1, m), map); // red block and black block
} else {
sum += 1;
}
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn | () -> String {
let mut map = HashMap::new();
get_cnt((50, 3), &mut map).to_string()
}
problem!("16475640049", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt((1, 3), &mut map));
assert_eq!(1, get_cnt((2, 3), &mut map));
assert_eq!(2, get_cnt((3, 3), &mut map));
assert_eq!(4, get_cnt((4, 3), &mut map));
assert_eq!(17, get_cnt((7, 3), &mut map));
}
}
| solve | identifier_name |
p114.rs | //! [Problem 114](https://projecteuler.net/problem=114) solver. | unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn get_cnt((n, m): (u32, u32), map: &mut HashMap<(u32, u32), u64>) -> u64 {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
sum += get_cnt((n - (len + i) - 1, m), map); // red block and black block
} else {
sum += 1;
}
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn solve() -> String {
let mut map = HashMap::new();
get_cnt((50, 3), &mut map).to_string()
}
problem!("16475640049", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt((1, 3), &mut map));
assert_eq!(1, get_cnt((2, 3), &mut map));
assert_eq!(2, get_cnt((3, 3), &mut map));
assert_eq!(4, get_cnt((4, 3), &mut map));
assert_eq!(17, get_cnt((7, 3), &mut map));
}
} |
# solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn get_cnt((n, m): (u32, u32), map: &mut HashMap<(u32, u32), u64>) -> u64 {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
sum += get_cnt((n - (len + i) - 1, m), map); // red block and black block
} else {
sum += 1;
}
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn solve() -> String |
problem!("16475640049", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt((1, 3), &mut map));
assert_eq!(1, get_cnt((2, 3), &mut map));
assert_eq!(2, get_cnt((3, 3), &mut map));
assert_eq!(4, get_cnt((4, 3), &mut map));
assert_eq!(17, get_cnt((7, 3), &mut map));
}
}
| {
let mut map = HashMap::new();
get_cnt((50, 3), &mut map).to_string()
} | identifier_body |
tweeter.rs | use futures::prelude::*;
use irc::client::prelude::*;
use std::time::Duration;
// NOTE: you can find an asynchronous version of this example with `IrcReactor` in `tooter.rs`.
#[tokio::main]
async fn | () -> irc::error::Result<()> {
let config = Config {
nickname: Some("pickles".to_owned()),
server: Some("irc.mozilla.org".to_owned()),
channels: vec!["#rust-spam".to_owned()],
..Default::default()
};
let mut client = Client::from_config(config).await?;
client.identify()?;
let mut stream = client.stream()?;
let mut interval = tokio::time::interval(Duration::from_secs(10)).fuse();
loop {
futures::select! {
m = stream.select_next_some() => {
println!("{}", m?);
}
_ = interval.select_next_some() => {
client.send_privmsg("#rust-spam", "TWEET TWEET")?;
}
}
}
}
| main | identifier_name |
tweeter.rs | use futures::prelude::*;
use irc::client::prelude::*;
use std::time::Duration;
// NOTE: you can find an asynchronous version of this example with `IrcReactor` in `tooter.rs`.
#[tokio::main]
async fn main() -> irc::error::Result<()> { | };
let mut client = Client::from_config(config).await?;
client.identify()?;
let mut stream = client.stream()?;
let mut interval = tokio::time::interval(Duration::from_secs(10)).fuse();
loop {
futures::select! {
m = stream.select_next_some() => {
println!("{}", m?);
}
_ = interval.select_next_some() => {
client.send_privmsg("#rust-spam", "TWEET TWEET")?;
}
}
}
} | let config = Config {
nickname: Some("pickles".to_owned()),
server: Some("irc.mozilla.org".to_owned()),
channels: vec!["#rust-spam".to_owned()],
..Default::default() | random_line_split |
tweeter.rs | use futures::prelude::*;
use irc::client::prelude::*;
use std::time::Duration;
// NOTE: you can find an asynchronous version of this example with `IrcReactor` in `tooter.rs`.
#[tokio::main]
async fn main() -> irc::error::Result<()> | client.send_privmsg("#rust-spam", "TWEET TWEET")?;
}
}
}
}
| {
let config = Config {
nickname: Some("pickles".to_owned()),
server: Some("irc.mozilla.org".to_owned()),
channels: vec!["#rust-spam".to_owned()],
..Default::default()
};
let mut client = Client::from_config(config).await?;
client.identify()?;
let mut stream = client.stream()?;
let mut interval = tokio::time::interval(Duration::from_secs(10)).fuse();
loop {
futures::select! {
m = stream.select_next_some() => {
println!("{}", m?);
}
_ = interval.select_next_some() => { | identifier_body |
main.rs | // Copyright (c) 2015-2019 William (B.J.) Snow Orvis
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod fractaldata;
pub mod pistonrendering;
pub mod work_multiplexer;
fn main() {
// Command line arguments specification
let mut app = clap::App::new("fractal")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Renders fractals in another window.");
app = fractaldata::add_subcommands(app);
app = app.arg(
clap::Arg::with_name("loglevel")
.takes_value(true)
.help("Choose log level")
.long("loglevel")
.value_name("LEVEL")
.default_value("INFO"),
);
let matches = app.get_matches();
simple_logger::SimpleLogger::new()
.with_level(
matches
.value_of("loglevel")
.map(|s| fractaldata::parse_arg::<log::LevelFilter>("loglevel", s))
.unwrap()
.unwrap(),
)
.with_module_level("gfx_device_gl", log::LevelFilter::Warn)
.init()
.unwrap();
let result = fractaldata::run_subcommand(&matches);
match result {
Ok(_) => |
Err(e) => {
use std::io::{stderr, Write};
writeln!(&mut stderr(), "{}", e).unwrap();
std::process::exit(1);
}
}
}
| {} | conditional_block |
main.rs | // Copyright (c) 2015-2019 William (B.J.) Snow Orvis
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod fractaldata;
pub mod pistonrendering;
pub mod work_multiplexer;
fn main() | matches
.value_of("loglevel")
.map(|s| fractaldata::parse_arg::<log::LevelFilter>("loglevel", s))
.unwrap()
.unwrap(),
)
.with_module_level("gfx_device_gl", log::LevelFilter::Warn)
.init()
.unwrap();
let result = fractaldata::run_subcommand(&matches);
match result {
Ok(_) => {}
Err(e) => {
use std::io::{stderr, Write};
writeln!(&mut stderr(), "{}", e).unwrap();
std::process::exit(1);
}
}
}
| {
// Command line arguments specification
let mut app = clap::App::new("fractal")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Renders fractals in another window.");
app = fractaldata::add_subcommands(app);
app = app.arg(
clap::Arg::with_name("loglevel")
.takes_value(true)
.help("Choose log level")
.long("loglevel")
.value_name("LEVEL")
.default_value("INFO"),
);
let matches = app.get_matches();
simple_logger::SimpleLogger::new()
.with_level( | identifier_body |
main.rs | // Copyright (c) 2015-2019 William (B.J.) Snow Orvis
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod fractaldata;
pub mod pistonrendering;
pub mod work_multiplexer;
fn main() {
// Command line arguments specification
let mut app = clap::App::new("fractal")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Renders fractals in another window.");
app = fractaldata::add_subcommands(app);
app = app.arg(
clap::Arg::with_name("loglevel")
.takes_value(true)
.help("Choose log level")
.long("loglevel")
.value_name("LEVEL")
.default_value("INFO"),
);
let matches = app.get_matches();
simple_logger::SimpleLogger::new()
.with_level(
matches
.value_of("loglevel")
.map(|s| fractaldata::parse_arg::<log::LevelFilter>("loglevel", s))
.unwrap()
.unwrap(),
)
.with_module_level("gfx_device_gl", log::LevelFilter::Warn)
.init()
.unwrap();
let result = fractaldata::run_subcommand(&matches);
match result {
Ok(_) => {}
Err(e) => {
use std::io::{stderr, Write};
writeln!(&mut stderr(), "{}", e).unwrap();
std::process::exit(1);
}
}
} | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
main.rs | // Copyright (c) 2015-2019 William (B.J.) Snow Orvis
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod fractaldata;
pub mod pistonrendering;
pub mod work_multiplexer;
fn | () {
// Command line arguments specification
let mut app = clap::App::new("fractal")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Renders fractals in another window.");
app = fractaldata::add_subcommands(app);
app = app.arg(
clap::Arg::with_name("loglevel")
.takes_value(true)
.help("Choose log level")
.long("loglevel")
.value_name("LEVEL")
.default_value("INFO"),
);
let matches = app.get_matches();
simple_logger::SimpleLogger::new()
.with_level(
matches
.value_of("loglevel")
.map(|s| fractaldata::parse_arg::<log::LevelFilter>("loglevel", s))
.unwrap()
.unwrap(),
)
.with_module_level("gfx_device_gl", log::LevelFilter::Warn)
.init()
.unwrap();
let result = fractaldata::run_subcommand(&matches);
match result {
Ok(_) => {}
Err(e) => {
use std::io::{stderr, Write};
writeln!(&mut stderr(), "{}", e).unwrap();
std::process::exit(1);
}
}
}
| main | identifier_name |
store.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::result::Result as RResult;
use anyhow::Result;
use chrono::NaiveDateTime;
use uuid::Uuid;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;
use libimagstore::iter::Entries;
use crate::status::Status;
use crate::priority::Priority;
use crate::builder::TodoBuilder;
pub trait TodoStore<'a> {
fn todo_builder(&self) -> TodoBuilder;
fn create_todo(&'a self,
status: Status, | hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>;
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>>;
fn get_todos(&self) -> Result<Entries>;
}
impl<'a> TodoStore<'a> for Store {
/// Get a TodoBuilder instance, which can be used to build a todo object.
///
/// The TodoBuilder::new() constructor is not exposed, this function should be used instead.
fn todo_builder(&self) -> TodoBuilder {
TodoBuilder::new()
}
/// Create a new todo entry
///
/// # Warning
///
/// If check_sanity is set to false, this does not sanity-check the scheduled/hidden/due dates.
/// This might result in unintended behaviour (hidden after due date, scheduled before hidden
/// date... etc)
///
/// An user of this function might want to use `date_sanity_check()` to perform sanity checks
/// before calling TodoStore::create_todo() and show the Err(String) as a warning to user in an
/// interactive way.
fn create_todo(&'a self,
status: Status,
scheduled: Option<NaiveDateTime>,
hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>
{
TodoBuilder::new()
.with_status(Some(status))
.with_uuid(Some(Uuid::new_v4()))
.with_scheduled(scheduled)
.with_hidden(hidden)
.with_due(due)
.with_prio(prio)
.with_check_sanity(check_sanity)
.build(&self)
}
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>> {
let uuid_s = format!("{}", uuid.to_hyphenated_ref()); // TODO: not how it is supposed to be
debug!("Created new UUID for todo = {}", uuid_s);
let id = crate::module_path::new_id(uuid_s)?;
self.get(id)
}
/// Get all todos using Store::entries()
fn get_todos(&self) -> Result<Entries> {
self.entries().and_then(|es| es.in_collection("todo"))
}
}
/// Perform a sanity check on the scheduled/hidden/due dates
///
/// This function returns a String as error, which can be shown as a warning to the user or as an
/// error.
pub fn date_sanity_check(scheduled: Option<&NaiveDateTime>,
hidden: Option<&NaiveDateTime>,
due: Option<&NaiveDateTime>)
-> RResult<(), String>
{
if let (Some(sched), Some(hid)) = (scheduled.as_ref(), hidden.as_ref()) {
if sched > hid {
return Err(format!("Scheduled date after hidden date: {s}, {h}",
s = sched,
h = hid))
}
}
if let (Some(hid), Some(due)) = (hidden.as_ref(), due.as_ref()) {
if hid > due {
return Err(format!("Hidden date after due date: {h}, {d}",
h = hid,
d = due))
}
}
if let (Some(sched), Some(due)) = (scheduled.as_ref(), due.as_ref()) {
if sched > due {
return Err(format!("Scheduled date after due date: {s}, {d}",
s = sched,
d = due))
}
}
Ok(())
} | scheduled: Option<NaiveDateTime>, | random_line_split |
store.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::result::Result as RResult;
use anyhow::Result;
use chrono::NaiveDateTime;
use uuid::Uuid;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;
use libimagstore::iter::Entries;
use crate::status::Status;
use crate::priority::Priority;
use crate::builder::TodoBuilder;
pub trait TodoStore<'a> {
fn todo_builder(&self) -> TodoBuilder;
fn create_todo(&'a self,
status: Status,
scheduled: Option<NaiveDateTime>,
hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>;
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>>;
fn get_todos(&self) -> Result<Entries>;
}
impl<'a> TodoStore<'a> for Store {
/// Get a TodoBuilder instance, which can be used to build a todo object.
///
/// The TodoBuilder::new() constructor is not exposed, this function should be used instead.
fn todo_builder(&self) -> TodoBuilder |
/// Create a new todo entry
///
/// # Warning
///
/// If check_sanity is set to false, this does not sanity-check the scheduled/hidden/due dates.
/// This might result in unintended behaviour (hidden after due date, scheduled before hidden
/// date... etc)
///
/// An user of this function might want to use `date_sanity_check()` to perform sanity checks
/// before calling TodoStore::create_todo() and show the Err(String) as a warning to user in an
/// interactive way.
fn create_todo(&'a self,
status: Status,
scheduled: Option<NaiveDateTime>,
hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>
{
TodoBuilder::new()
.with_status(Some(status))
.with_uuid(Some(Uuid::new_v4()))
.with_scheduled(scheduled)
.with_hidden(hidden)
.with_due(due)
.with_prio(prio)
.with_check_sanity(check_sanity)
.build(&self)
}
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>> {
let uuid_s = format!("{}", uuid.to_hyphenated_ref()); // TODO: not how it is supposed to be
debug!("Created new UUID for todo = {}", uuid_s);
let id = crate::module_path::new_id(uuid_s)?;
self.get(id)
}
/// Get all todos using Store::entries()
fn get_todos(&self) -> Result<Entries> {
self.entries().and_then(|es| es.in_collection("todo"))
}
}
/// Perform a sanity check on the scheduled/hidden/due dates
///
/// This function returns a String as error, which can be shown as a warning to the user or as an
/// error.
pub fn date_sanity_check(scheduled: Option<&NaiveDateTime>,
hidden: Option<&NaiveDateTime>,
due: Option<&NaiveDateTime>)
-> RResult<(), String>
{
if let (Some(sched), Some(hid)) = (scheduled.as_ref(), hidden.as_ref()) {
if sched > hid {
return Err(format!("Scheduled date after hidden date: {s}, {h}",
s = sched,
h = hid))
}
}
if let (Some(hid), Some(due)) = (hidden.as_ref(), due.as_ref()) {
if hid > due {
return Err(format!("Hidden date after due date: {h}, {d}",
h = hid,
d = due))
}
}
if let (Some(sched), Some(due)) = (scheduled.as_ref(), due.as_ref()) {
if sched > due {
return Err(format!("Scheduled date after due date: {s}, {d}",
s = sched,
d = due))
}
}
Ok(())
}
| {
TodoBuilder::new()
} | identifier_body |
store.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::result::Result as RResult;
use anyhow::Result;
use chrono::NaiveDateTime;
use uuid::Uuid;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;
use libimagstore::iter::Entries;
use crate::status::Status;
use crate::priority::Priority;
use crate::builder::TodoBuilder;
pub trait TodoStore<'a> {
fn todo_builder(&self) -> TodoBuilder;
fn create_todo(&'a self,
status: Status,
scheduled: Option<NaiveDateTime>,
hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>;
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>>;
fn get_todos(&self) -> Result<Entries>;
}
impl<'a> TodoStore<'a> for Store {
/// Get a TodoBuilder instance, which can be used to build a todo object.
///
/// The TodoBuilder::new() constructor is not exposed, this function should be used instead.
fn todo_builder(&self) -> TodoBuilder {
TodoBuilder::new()
}
/// Create a new todo entry
///
/// # Warning
///
/// If check_sanity is set to false, this does not sanity-check the scheduled/hidden/due dates.
/// This might result in unintended behaviour (hidden after due date, scheduled before hidden
/// date... etc)
///
/// An user of this function might want to use `date_sanity_check()` to perform sanity checks
/// before calling TodoStore::create_todo() and show the Err(String) as a warning to user in an
/// interactive way.
fn create_todo(&'a self,
status: Status,
scheduled: Option<NaiveDateTime>,
hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>
{
TodoBuilder::new()
.with_status(Some(status))
.with_uuid(Some(Uuid::new_v4()))
.with_scheduled(scheduled)
.with_hidden(hidden)
.with_due(due)
.with_prio(prio)
.with_check_sanity(check_sanity)
.build(&self)
}
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>> {
let uuid_s = format!("{}", uuid.to_hyphenated_ref()); // TODO: not how it is supposed to be
debug!("Created new UUID for todo = {}", uuid_s);
let id = crate::module_path::new_id(uuid_s)?;
self.get(id)
}
/// Get all todos using Store::entries()
fn get_todos(&self) -> Result<Entries> {
self.entries().and_then(|es| es.in_collection("todo"))
}
}
/// Perform a sanity check on the scheduled/hidden/due dates
///
/// This function returns a String as error, which can be shown as a warning to the user or as an
/// error.
pub fn date_sanity_check(scheduled: Option<&NaiveDateTime>,
hidden: Option<&NaiveDateTime>,
due: Option<&NaiveDateTime>)
-> RResult<(), String>
{
if let (Some(sched), Some(hid)) = (scheduled.as_ref(), hidden.as_ref()) {
if sched > hid {
return Err(format!("Scheduled date after hidden date: {s}, {h}",
s = sched,
h = hid))
}
}
if let (Some(hid), Some(due)) = (hidden.as_ref(), due.as_ref()) {
if hid > due |
}
if let (Some(sched), Some(due)) = (scheduled.as_ref(), due.as_ref()) {
if sched > due {
return Err(format!("Scheduled date after due date: {s}, {d}",
s = sched,
d = due))
}
}
Ok(())
}
| {
return Err(format!("Hidden date after due date: {h}, {d}",
h = hid,
d = due))
} | conditional_block |
store.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::result::Result as RResult;
use anyhow::Result;
use chrono::NaiveDateTime;
use uuid::Uuid;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;
use libimagstore::iter::Entries;
use crate::status::Status;
use crate::priority::Priority;
use crate::builder::TodoBuilder;
pub trait TodoStore<'a> {
fn todo_builder(&self) -> TodoBuilder;
fn create_todo(&'a self,
status: Status,
scheduled: Option<NaiveDateTime>,
hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>;
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>>;
fn get_todos(&self) -> Result<Entries>;
}
impl<'a> TodoStore<'a> for Store {
/// Get a TodoBuilder instance, which can be used to build a todo object.
///
/// The TodoBuilder::new() constructor is not exposed, this function should be used instead.
fn todo_builder(&self) -> TodoBuilder {
TodoBuilder::new()
}
/// Create a new todo entry
///
/// # Warning
///
/// If check_sanity is set to false, this does not sanity-check the scheduled/hidden/due dates.
/// This might result in unintended behaviour (hidden after due date, scheduled before hidden
/// date... etc)
///
/// An user of this function might want to use `date_sanity_check()` to perform sanity checks
/// before calling TodoStore::create_todo() and show the Err(String) as a warning to user in an
/// interactive way.
fn | (&'a self,
status: Status,
scheduled: Option<NaiveDateTime>,
hidden: Option<NaiveDateTime>,
due: Option<NaiveDateTime>,
prio: Option<Priority>,
check_sanity: bool) -> Result<FileLockEntry<'a>>
{
TodoBuilder::new()
.with_status(Some(status))
.with_uuid(Some(Uuid::new_v4()))
.with_scheduled(scheduled)
.with_hidden(hidden)
.with_due(due)
.with_prio(prio)
.with_check_sanity(check_sanity)
.build(&self)
}
fn get_todo_by_uuid(&'a self, uuid: &Uuid) -> Result<Option<FileLockEntry<'a>>> {
let uuid_s = format!("{}", uuid.to_hyphenated_ref()); // TODO: not how it is supposed to be
debug!("Created new UUID for todo = {}", uuid_s);
let id = crate::module_path::new_id(uuid_s)?;
self.get(id)
}
/// Get all todos using Store::entries()
fn get_todos(&self) -> Result<Entries> {
self.entries().and_then(|es| es.in_collection("todo"))
}
}
/// Perform a sanity check on the scheduled/hidden/due dates
///
/// This function returns a String as error, which can be shown as a warning to the user or as an
/// error.
pub fn date_sanity_check(scheduled: Option<&NaiveDateTime>,
hidden: Option<&NaiveDateTime>,
due: Option<&NaiveDateTime>)
-> RResult<(), String>
{
if let (Some(sched), Some(hid)) = (scheduled.as_ref(), hidden.as_ref()) {
if sched > hid {
return Err(format!("Scheduled date after hidden date: {s}, {h}",
s = sched,
h = hid))
}
}
if let (Some(hid), Some(due)) = (hidden.as_ref(), due.as_ref()) {
if hid > due {
return Err(format!("Hidden date after due date: {h}, {d}",
h = hid,
d = due))
}
}
if let (Some(sched), Some(due)) = (scheduled.as_ref(), due.as_ref()) {
if sched > due {
return Err(format!("Scheduled date after due date: {s}, {d}",
s = sched,
d = due))
}
}
Ok(())
}
| create_todo | identifier_name |
finally.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.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
# Example
```
do || {
...
}.finally {
always_run_this();
}
```
*/
use ops::Drop;
#[cfg(test)] use task::{failing, spawn};
pub trait Finally<T> {
fn finally(&self, dtor: &fn()) -> T;
}
macro_rules! finally_fn {
($fnty:ty) => {
impl<T> Finally<T> for $fnty {
fn finally(&self, dtor: &fn()) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
}
}
impl<'self,T> Finally<T> for &'self fn() -> T {
fn finally(&self, dtor: &fn()) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
finally_fn!(~fn() -> T)
finally_fn!(extern "Rust" fn() -> T)
struct Finallyalizer<'self> {
dtor: &'self fn()
}
#[unsafe_destructor]
impl<'self> Drop for Finallyalizer<'self> {
fn drop(&mut self) {
(self.dtor)();
}
}
#[test]
fn test_success() {
let mut i = 0;
do (|| {
i = 10;
}).finally {
assert!(!failing());
assert_eq!(i, 10);
i = 20;
}
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
do (|| {
i = 10;
fail2!();
}).finally {
assert!(failing());
assert_eq!(i, 10);
}
}
#[test]
fn test_retval() {
let closure: &fn() -> int = || 10;
let i = do closure.finally { };
assert_eq!(i, 10);
}
#[test]
fn test_compact() { | }
#[test]
fn test_owned() {
fn spawn_with_finalizer(f: ~fn()) {
do spawn { do f.finally { } }
}
let owned: ~fn() = || { };
spawn_with_finalizer(owned);
} | fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
do_some_fallible_work.finally(
but_always_run_this_function); | random_line_split |
finally.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.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
# Example
```
do || {
...
}.finally {
always_run_this();
}
```
*/
use ops::Drop;
#[cfg(test)] use task::{failing, spawn};
pub trait Finally<T> {
fn finally(&self, dtor: &fn()) -> T;
}
macro_rules! finally_fn {
($fnty:ty) => {
impl<T> Finally<T> for $fnty {
fn finally(&self, dtor: &fn()) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
}
}
impl<'self,T> Finally<T> for &'self fn() -> T {
fn | (&self, dtor: &fn()) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
finally_fn!(~fn() -> T)
finally_fn!(extern "Rust" fn() -> T)
struct Finallyalizer<'self> {
dtor: &'self fn()
}
#[unsafe_destructor]
impl<'self> Drop for Finallyalizer<'self> {
fn drop(&mut self) {
(self.dtor)();
}
}
#[test]
fn test_success() {
let mut i = 0;
do (|| {
i = 10;
}).finally {
assert!(!failing());
assert_eq!(i, 10);
i = 20;
}
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
do (|| {
i = 10;
fail2!();
}).finally {
assert!(failing());
assert_eq!(i, 10);
}
}
#[test]
fn test_retval() {
let closure: &fn() -> int = || 10;
let i = do closure.finally { };
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
do_some_fallible_work.finally(
but_always_run_this_function);
}
#[test]
fn test_owned() {
fn spawn_with_finalizer(f: ~fn()) {
do spawn { do f.finally { } }
}
let owned: ~fn() = || { };
spawn_with_finalizer(owned);
}
| finally | identifier_name |
finally.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.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
# Example
```
do || {
...
}.finally {
always_run_this();
}
```
*/
use ops::Drop;
#[cfg(test)] use task::{failing, spawn};
pub trait Finally<T> {
fn finally(&self, dtor: &fn()) -> T;
}
macro_rules! finally_fn {
($fnty:ty) => {
impl<T> Finally<T> for $fnty {
fn finally(&self, dtor: &fn()) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
}
}
impl<'self,T> Finally<T> for &'self fn() -> T {
fn finally(&self, dtor: &fn()) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
finally_fn!(~fn() -> T)
finally_fn!(extern "Rust" fn() -> T)
struct Finallyalizer<'self> {
dtor: &'self fn()
}
#[unsafe_destructor]
impl<'self> Drop for Finallyalizer<'self> {
fn drop(&mut self) {
(self.dtor)();
}
}
#[test]
fn test_success() {
let mut i = 0;
do (|| {
i = 10;
}).finally {
assert!(!failing());
assert_eq!(i, 10);
i = 20;
}
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() |
#[test]
fn test_retval() {
let closure: &fn() -> int = || 10;
let i = do closure.finally { };
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
do_some_fallible_work.finally(
but_always_run_this_function);
}
#[test]
fn test_owned() {
fn spawn_with_finalizer(f: ~fn()) {
do spawn { do f.finally { } }
}
let owned: ~fn() = || { };
spawn_with_finalizer(owned);
}
| {
let mut i = 0;
do (|| {
i = 10;
fail2!();
}).finally {
assert!(failing());
assert_eq!(i, 10);
}
} | identifier_body |
mod.rs | extern crate udt;
pub mod crypto;
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian};
use core::ops::DerefMut;
use std::fmt;
use std::io::Cursor;
use std::net::{UdpSocket, SocketAddr, IpAddr};
use std::str;
use std::sync::{Arc, Mutex};
use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily};
// TODO config
const UDT_BUF_SIZE: i32 = 4096000;
pub const MAX_MESSAGE_SIZE: usize = 1024000;
fn new_udt_socket() -> UdtSocket {
udt::init();
let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
sock.setsockopt(UdtOpts::UDP_RCVBUF, UDT_BUF_SIZE).unwrap();
sock.setsockopt(UdtOpts::UDP_SNDBUF, UDT_BUF_SIZE).unwrap();
sock
}
trait ExactIO {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError>;
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
}
impl ExactIO for UdtSocket {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < buf.len() {
total += try!(self.send(&buf[total..])) as usize;
}
Ok(())
}
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < len {
let remaining = len - total;
total += try!(self.recv(&mut buf[total..], remaining)) as usize;
}
Ok(())
}
}
fn send(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
// FIXME don't unwrap, create an Error struct that can handle everything
if let Ok(sealed_len) = crypto.seal(buf, len) {
assert!(sealed_len <= u32::max_value() as usize, "single chunk must be 32-bit length");
let mut wtr = vec![];
wtr.write_u32::<LittleEndian>(sealed_len as u32).unwrap();
wtr.extend_from_slice(&buf[..sealed_len]);
sock.send_exact(&wtr)
} else {
Err(UdtError { | }
}
fn recv(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8]) -> Result<usize, UdtError> {
let mut len_buf = vec![0u8; 4];
try!(sock.recv_exact(&mut len_buf, 4)); // u32
let mut rdr = Cursor::new(len_buf);
let len = rdr.read_u32::<LittleEndian>().unwrap() as usize;
try!(sock.recv_exact(buf, len));
crypto.open(&mut buf[..len]).map_err(|_| {
UdtError {
err_code: -1,
err_msg: String::from("decryption failure"),
}
})
}
#[derive(Copy,Clone)]
pub struct PortRange {
start: u16,
end: u16,
}
pub struct Server {
pub ip_addr: IpAddr,
pub port: u16,
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
pub struct Client {
addr: SocketAddr,
sock: UdtSocket,
crypto: crypto::Handler,
}
pub struct ServerConnection {
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
impl Client {
pub fn new(addr: SocketAddr, key: &[u8]) -> Client {
let sock = new_udt_socket();
Client {
addr: addr,
sock: sock,
crypto: crypto::Handler::new(key),
}
}
pub fn connect(&self) -> Result<(), UdtError> {
self.sock.connect(self.addr)
}
}
pub trait Transceiver {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError>;
fn close(&self) -> Result<(), UdtError>;
}
impl Transceiver for Client {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
send(&self.sock, &mut self.crypto, buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
recv(&self.sock, &mut self.crypto, buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Transceiver for ServerConnection {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
send(&self.sock, crypto.deref_mut(), buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
recv(&self.sock, crypto.deref_mut(), buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Server {
pub fn get_open_port(range: &PortRange) -> Result<u16, ()> {
for p in range.start..range.end {
if let Ok(_) = UdpSocket::bind(&format!("0.0.0.0:{}", p)[..]) {
return Ok(p);
}
}
Err(())
}
pub fn new(ip_addr: IpAddr, port: u16, key: &[u8]) -> Server {
let sock = new_udt_socket();
sock.bind(SocketAddr::new(ip_addr, port)).unwrap();
Server {
sock: sock,
ip_addr: ip_addr,
port: port,
crypto: Arc::new(Mutex::new(crypto::Handler::new(key))),
}
}
pub fn listen(&self) -> Result<(), UdtError> {
self.sock.listen(1)
}
pub fn accept(&self) -> Result<ServerConnection, UdtError> {
self.sock.accept().map(move |(sock, _)| {
ServerConnection {
crypto: self.crypto.clone(),
sock: sock,
}
})
}
}
impl ServerConnection {
pub fn getpeer(&self) -> Result<SocketAddr, UdtError> {
self.sock.getpeername()
}
}
impl PortRange {
fn new(start: u16, end: u16) -> Result<PortRange, String> {
if start > end {
Err("range end must be greater than or equal to start".into())
} else {
Ok(PortRange {
start: start,
end: end,
})
}
}
pub fn from(s: &str) -> Result<PortRange, String> {
let sections: Vec<&str> = s.split('-').collect();
if sections.len()!= 2 {
return Err("Range must be specified in the form of \"<start>-<end>\"".into());
}
let (start, end) = (sections[0].parse::<u16>(), sections[1].parse::<u16>());
if start.is_err() || end.is_err() {
return Err("improperly formatted port range".into());
}
PortRange::new(start.unwrap(), end.unwrap())
}
}
impl fmt::Display for PortRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{}", self.start, self.end)
}
} | err_code: -1,
err_msg: "encryption failure".into(),
}) | random_line_split |
mod.rs | extern crate udt;
pub mod crypto;
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian};
use core::ops::DerefMut;
use std::fmt;
use std::io::Cursor;
use std::net::{UdpSocket, SocketAddr, IpAddr};
use std::str;
use std::sync::{Arc, Mutex};
use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily};
// TODO config
const UDT_BUF_SIZE: i32 = 4096000;
pub const MAX_MESSAGE_SIZE: usize = 1024000;
fn new_udt_socket() -> UdtSocket {
udt::init();
let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
sock.setsockopt(UdtOpts::UDP_RCVBUF, UDT_BUF_SIZE).unwrap();
sock.setsockopt(UdtOpts::UDP_SNDBUF, UDT_BUF_SIZE).unwrap();
sock
}
trait ExactIO {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError>;
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
}
impl ExactIO for UdtSocket {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < buf.len() {
total += try!(self.send(&buf[total..])) as usize;
}
Ok(())
}
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < len {
let remaining = len - total;
total += try!(self.recv(&mut buf[total..], remaining)) as usize;
}
Ok(())
}
}
fn send(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
// FIXME don't unwrap, create an Error struct that can handle everything
if let Ok(sealed_len) = crypto.seal(buf, len) {
assert!(sealed_len <= u32::max_value() as usize, "single chunk must be 32-bit length");
let mut wtr = vec![];
wtr.write_u32::<LittleEndian>(sealed_len as u32).unwrap();
wtr.extend_from_slice(&buf[..sealed_len]);
sock.send_exact(&wtr)
} else {
Err(UdtError {
err_code: -1,
err_msg: "encryption failure".into(),
})
}
}
fn recv(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8]) -> Result<usize, UdtError> {
let mut len_buf = vec![0u8; 4];
try!(sock.recv_exact(&mut len_buf, 4)); // u32
let mut rdr = Cursor::new(len_buf);
let len = rdr.read_u32::<LittleEndian>().unwrap() as usize;
try!(sock.recv_exact(buf, len));
crypto.open(&mut buf[..len]).map_err(|_| {
UdtError {
err_code: -1,
err_msg: String::from("decryption failure"),
}
})
}
#[derive(Copy,Clone)]
pub struct PortRange {
start: u16,
end: u16,
}
pub struct Server {
pub ip_addr: IpAddr,
pub port: u16,
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
pub struct Client {
addr: SocketAddr,
sock: UdtSocket,
crypto: crypto::Handler,
}
pub struct ServerConnection {
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
impl Client {
pub fn new(addr: SocketAddr, key: &[u8]) -> Client {
let sock = new_udt_socket();
Client {
addr: addr,
sock: sock,
crypto: crypto::Handler::new(key),
}
}
pub fn connect(&self) -> Result<(), UdtError> {
self.sock.connect(self.addr)
}
}
pub trait Transceiver {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError>;
fn close(&self) -> Result<(), UdtError>;
}
impl Transceiver for Client {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
send(&self.sock, &mut self.crypto, buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
recv(&self.sock, &mut self.crypto, buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Transceiver for ServerConnection {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
send(&self.sock, crypto.deref_mut(), buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
recv(&self.sock, crypto.deref_mut(), buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Server {
pub fn get_open_port(range: &PortRange) -> Result<u16, ()> |
pub fn new(ip_addr: IpAddr, port: u16, key: &[u8]) -> Server {
let sock = new_udt_socket();
sock.bind(SocketAddr::new(ip_addr, port)).unwrap();
Server {
sock: sock,
ip_addr: ip_addr,
port: port,
crypto: Arc::new(Mutex::new(crypto::Handler::new(key))),
}
}
pub fn listen(&self) -> Result<(), UdtError> {
self.sock.listen(1)
}
pub fn accept(&self) -> Result<ServerConnection, UdtError> {
self.sock.accept().map(move |(sock, _)| {
ServerConnection {
crypto: self.crypto.clone(),
sock: sock,
}
})
}
}
impl ServerConnection {
pub fn getpeer(&self) -> Result<SocketAddr, UdtError> {
self.sock.getpeername()
}
}
impl PortRange {
fn new(start: u16, end: u16) -> Result<PortRange, String> {
if start > end {
Err("range end must be greater than or equal to start".into())
} else {
Ok(PortRange {
start: start,
end: end,
})
}
}
pub fn from(s: &str) -> Result<PortRange, String> {
let sections: Vec<&str> = s.split('-').collect();
if sections.len()!= 2 {
return Err("Range must be specified in the form of \"<start>-<end>\"".into());
}
let (start, end) = (sections[0].parse::<u16>(), sections[1].parse::<u16>());
if start.is_err() || end.is_err() {
return Err("improperly formatted port range".into());
}
PortRange::new(start.unwrap(), end.unwrap())
}
}
impl fmt::Display for PortRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{}", self.start, self.end)
}
}
| {
for p in range.start..range.end {
if let Ok(_) = UdpSocket::bind(&format!("0.0.0.0:{}", p)[..]) {
return Ok(p);
}
}
Err(())
} | identifier_body |
mod.rs | extern crate udt;
pub mod crypto;
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian};
use core::ops::DerefMut;
use std::fmt;
use std::io::Cursor;
use std::net::{UdpSocket, SocketAddr, IpAddr};
use std::str;
use std::sync::{Arc, Mutex};
use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily};
// TODO config
const UDT_BUF_SIZE: i32 = 4096000;
pub const MAX_MESSAGE_SIZE: usize = 1024000;
fn new_udt_socket() -> UdtSocket {
udt::init();
let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
sock.setsockopt(UdtOpts::UDP_RCVBUF, UDT_BUF_SIZE).unwrap();
sock.setsockopt(UdtOpts::UDP_SNDBUF, UDT_BUF_SIZE).unwrap();
sock
}
trait ExactIO {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError>;
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
}
impl ExactIO for UdtSocket {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < buf.len() {
total += try!(self.send(&buf[total..])) as usize;
}
Ok(())
}
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < len {
let remaining = len - total;
total += try!(self.recv(&mut buf[total..], remaining)) as usize;
}
Ok(())
}
}
fn send(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
// FIXME don't unwrap, create an Error struct that can handle everything
if let Ok(sealed_len) = crypto.seal(buf, len) {
assert!(sealed_len <= u32::max_value() as usize, "single chunk must be 32-bit length");
let mut wtr = vec![];
wtr.write_u32::<LittleEndian>(sealed_len as u32).unwrap();
wtr.extend_from_slice(&buf[..sealed_len]);
sock.send_exact(&wtr)
} else {
Err(UdtError {
err_code: -1,
err_msg: "encryption failure".into(),
})
}
}
fn recv(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8]) -> Result<usize, UdtError> {
let mut len_buf = vec![0u8; 4];
try!(sock.recv_exact(&mut len_buf, 4)); // u32
let mut rdr = Cursor::new(len_buf);
let len = rdr.read_u32::<LittleEndian>().unwrap() as usize;
try!(sock.recv_exact(buf, len));
crypto.open(&mut buf[..len]).map_err(|_| {
UdtError {
err_code: -1,
err_msg: String::from("decryption failure"),
}
})
}
#[derive(Copy,Clone)]
pub struct PortRange {
start: u16,
end: u16,
}
pub struct Server {
pub ip_addr: IpAddr,
pub port: u16,
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
pub struct Client {
addr: SocketAddr,
sock: UdtSocket,
crypto: crypto::Handler,
}
pub struct ServerConnection {
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
impl Client {
pub fn new(addr: SocketAddr, key: &[u8]) -> Client {
let sock = new_udt_socket();
Client {
addr: addr,
sock: sock,
crypto: crypto::Handler::new(key),
}
}
pub fn connect(&self) -> Result<(), UdtError> {
self.sock.connect(self.addr)
}
}
pub trait Transceiver {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError>;
fn close(&self) -> Result<(), UdtError>;
}
impl Transceiver for Client {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
send(&self.sock, &mut self.crypto, buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
recv(&self.sock, &mut self.crypto, buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Transceiver for ServerConnection {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
send(&self.sock, crypto.deref_mut(), buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
recv(&self.sock, crypto.deref_mut(), buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Server {
pub fn get_open_port(range: &PortRange) -> Result<u16, ()> {
for p in range.start..range.end {
if let Ok(_) = UdpSocket::bind(&format!("0.0.0.0:{}", p)[..]) |
}
Err(())
}
pub fn new(ip_addr: IpAddr, port: u16, key: &[u8]) -> Server {
let sock = new_udt_socket();
sock.bind(SocketAddr::new(ip_addr, port)).unwrap();
Server {
sock: sock,
ip_addr: ip_addr,
port: port,
crypto: Arc::new(Mutex::new(crypto::Handler::new(key))),
}
}
pub fn listen(&self) -> Result<(), UdtError> {
self.sock.listen(1)
}
pub fn accept(&self) -> Result<ServerConnection, UdtError> {
self.sock.accept().map(move |(sock, _)| {
ServerConnection {
crypto: self.crypto.clone(),
sock: sock,
}
})
}
}
impl ServerConnection {
pub fn getpeer(&self) -> Result<SocketAddr, UdtError> {
self.sock.getpeername()
}
}
impl PortRange {
fn new(start: u16, end: u16) -> Result<PortRange, String> {
if start > end {
Err("range end must be greater than or equal to start".into())
} else {
Ok(PortRange {
start: start,
end: end,
})
}
}
pub fn from(s: &str) -> Result<PortRange, String> {
let sections: Vec<&str> = s.split('-').collect();
if sections.len()!= 2 {
return Err("Range must be specified in the form of \"<start>-<end>\"".into());
}
let (start, end) = (sections[0].parse::<u16>(), sections[1].parse::<u16>());
if start.is_err() || end.is_err() {
return Err("improperly formatted port range".into());
}
PortRange::new(start.unwrap(), end.unwrap())
}
}
impl fmt::Display for PortRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{}", self.start, self.end)
}
}
| {
return Ok(p);
} | conditional_block |
mod.rs | extern crate udt;
pub mod crypto;
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian};
use core::ops::DerefMut;
use std::fmt;
use std::io::Cursor;
use std::net::{UdpSocket, SocketAddr, IpAddr};
use std::str;
use std::sync::{Arc, Mutex};
use udt::{UdtSocket, UdtError, UdtOpts, SocketType, SocketFamily};
// TODO config
const UDT_BUF_SIZE: i32 = 4096000;
pub const MAX_MESSAGE_SIZE: usize = 1024000;
fn new_udt_socket() -> UdtSocket {
udt::init();
let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
sock.setsockopt(UdtOpts::UDP_RCVBUF, UDT_BUF_SIZE).unwrap();
sock.setsockopt(UdtOpts::UDP_SNDBUF, UDT_BUF_SIZE).unwrap();
sock
}
trait ExactIO {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError>;
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
}
impl ExactIO for UdtSocket {
fn send_exact(&self, buf: &[u8]) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < buf.len() {
total += try!(self.send(&buf[total..])) as usize;
}
Ok(())
}
fn recv_exact(&self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mut total: usize = 0;
while total < len {
let remaining = len - total;
total += try!(self.recv(&mut buf[total..], remaining)) as usize;
}
Ok(())
}
}
fn send(sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
// FIXME don't unwrap, create an Error struct that can handle everything
if let Ok(sealed_len) = crypto.seal(buf, len) {
assert!(sealed_len <= u32::max_value() as usize, "single chunk must be 32-bit length");
let mut wtr = vec![];
wtr.write_u32::<LittleEndian>(sealed_len as u32).unwrap();
wtr.extend_from_slice(&buf[..sealed_len]);
sock.send_exact(&wtr)
} else {
Err(UdtError {
err_code: -1,
err_msg: "encryption failure".into(),
})
}
}
fn | (sock: &UdtSocket, crypto: &mut crypto::Handler, buf: &mut [u8]) -> Result<usize, UdtError> {
let mut len_buf = vec![0u8; 4];
try!(sock.recv_exact(&mut len_buf, 4)); // u32
let mut rdr = Cursor::new(len_buf);
let len = rdr.read_u32::<LittleEndian>().unwrap() as usize;
try!(sock.recv_exact(buf, len));
crypto.open(&mut buf[..len]).map_err(|_| {
UdtError {
err_code: -1,
err_msg: String::from("decryption failure"),
}
})
}
#[derive(Copy,Clone)]
pub struct PortRange {
start: u16,
end: u16,
}
pub struct Server {
pub ip_addr: IpAddr,
pub port: u16,
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
pub struct Client {
addr: SocketAddr,
sock: UdtSocket,
crypto: crypto::Handler,
}
pub struct ServerConnection {
crypto: Arc<Mutex<crypto::Handler>>,
sock: UdtSocket,
}
impl Client {
pub fn new(addr: SocketAddr, key: &[u8]) -> Client {
let sock = new_udt_socket();
Client {
addr: addr,
sock: sock,
crypto: crypto::Handler::new(key),
}
}
pub fn connect(&self) -> Result<(), UdtError> {
self.sock.connect(self.addr)
}
}
pub trait Transceiver {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError>;
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError>;
fn close(&self) -> Result<(), UdtError>;
}
impl Transceiver for Client {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
send(&self.sock, &mut self.crypto, buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
recv(&self.sock, &mut self.crypto, buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Transceiver for ServerConnection {
fn send(&mut self, buf: &mut [u8], len: usize) -> Result<(), UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
send(&self.sock, crypto.deref_mut(), buf, len)
}
fn recv(&mut self, buf: &mut [u8]) -> Result<usize, UdtError> {
let mutex = &self.crypto;
let mut crypto = mutex.lock().unwrap();
recv(&self.sock, crypto.deref_mut(), buf)
}
fn close(&self) -> Result<(), UdtError> {
self.sock.close()
}
}
impl Server {
pub fn get_open_port(range: &PortRange) -> Result<u16, ()> {
for p in range.start..range.end {
if let Ok(_) = UdpSocket::bind(&format!("0.0.0.0:{}", p)[..]) {
return Ok(p);
}
}
Err(())
}
pub fn new(ip_addr: IpAddr, port: u16, key: &[u8]) -> Server {
let sock = new_udt_socket();
sock.bind(SocketAddr::new(ip_addr, port)).unwrap();
Server {
sock: sock,
ip_addr: ip_addr,
port: port,
crypto: Arc::new(Mutex::new(crypto::Handler::new(key))),
}
}
pub fn listen(&self) -> Result<(), UdtError> {
self.sock.listen(1)
}
pub fn accept(&self) -> Result<ServerConnection, UdtError> {
self.sock.accept().map(move |(sock, _)| {
ServerConnection {
crypto: self.crypto.clone(),
sock: sock,
}
})
}
}
impl ServerConnection {
pub fn getpeer(&self) -> Result<SocketAddr, UdtError> {
self.sock.getpeername()
}
}
impl PortRange {
fn new(start: u16, end: u16) -> Result<PortRange, String> {
if start > end {
Err("range end must be greater than or equal to start".into())
} else {
Ok(PortRange {
start: start,
end: end,
})
}
}
pub fn from(s: &str) -> Result<PortRange, String> {
let sections: Vec<&str> = s.split('-').collect();
if sections.len()!= 2 {
return Err("Range must be specified in the form of \"<start>-<end>\"".into());
}
let (start, end) = (sections[0].parse::<u16>(), sections[1].parse::<u16>());
if start.is_err() || end.is_err() {
return Err("improperly formatted port range".into());
}
PortRange::new(start.unwrap(), end.unwrap())
}
}
impl fmt::Display for PortRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{}", self.start, self.end)
}
}
| recv | identifier_name |
load_distr_uniform.rs | extern crate rand;
use self::rand::distributions::{IndependentSample, Range};
#[derive(Clone, Debug)]
pub struct LoadDistrUniform < T > {
_buf: Vec< T >,
}
impl < T > Default for LoadDistrUniform < T > {
fn default() -> Self |
}
impl < T > LoadDistrUniform < T > {
pub fn load( & mut self, t: T ) -> Result< (), &'static str > {
self._buf.push( t );
Ok( () )
}
pub fn apply< F >( & mut self, mut f: F ) -> Result< (), &'static str >
where F: FnMut( & T ) -> bool
{
if self._buf.len() > 0 {
let between = Range::new( 0, self._buf.len() );
let mut rng = rand::thread_rng();
let i = between.ind_sample( & mut rng );
f( & self._buf[ i ] );
}
self._buf.clear();
Ok( () )
}
}
| {
Self {
_buf: vec![],
}
} | identifier_body |
load_distr_uniform.rs | extern crate rand;
use self::rand::distributions::{IndependentSample, Range}; | pub struct LoadDistrUniform < T > {
_buf: Vec< T >,
}
impl < T > Default for LoadDistrUniform < T > {
fn default() -> Self {
Self {
_buf: vec![],
}
}
}
impl < T > LoadDistrUniform < T > {
pub fn load( & mut self, t: T ) -> Result< (), &'static str > {
self._buf.push( t );
Ok( () )
}
pub fn apply< F >( & mut self, mut f: F ) -> Result< (), &'static str >
where F: FnMut( & T ) -> bool
{
if self._buf.len() > 0 {
let between = Range::new( 0, self._buf.len() );
let mut rng = rand::thread_rng();
let i = between.ind_sample( & mut rng );
f( & self._buf[ i ] );
}
self._buf.clear();
Ok( () )
}
} |
#[derive(Clone, Debug)] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.