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 |
---|---|---|---|---|
unsound_collection_transmute.rs
|
use super::utils::is_layout_incompatible;
use super::UNSOUND_COLLECTION_TRANSMUTE;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::match_any_diagnostic_items;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use rustc_span::symbol::{sym, Symbol};
// used to check for UNSOUND_COLLECTION_TRANSMUTE
static COLLECTIONS: &[Symbol] = &[
sym::Vec,
sym::VecDeque,
sym::BinaryHeap,
sym::BTreeSet,
sym::BTreeMap,
sym::HashSet,
sym::HashMap,
];
/// Checks for `unsound_collection_transmute` lint.
/// Returns `true` if it's triggered, otherwise returns `false`.
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> bool
|
true
} else {
false
}
},
_ => false,
}
}
|
{
match (&from_ty.kind(), &to_ty.kind()) {
(ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
if from_adt.did != to_adt.did || match_any_diagnostic_items(cx, to_adt.did, COLLECTIONS).is_none() {
return false;
}
if from_substs
.types()
.zip(to_substs.types())
.any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty))
{
span_lint(
cx,
UNSOUND_COLLECTION_TRANSMUTE,
e.span,
&format!(
"transmute from `{}` to `{}` with mismatched layout is unsound",
from_ty, to_ty
),
);
|
identifier_body
|
unsound_collection_transmute.rs
|
use super::utils::is_layout_incompatible;
use super::UNSOUND_COLLECTION_TRANSMUTE;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::match_any_diagnostic_items;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use rustc_span::symbol::{sym, Symbol};
// used to check for UNSOUND_COLLECTION_TRANSMUTE
static COLLECTIONS: &[Symbol] = &[
sym::Vec,
sym::VecDeque,
sym::BinaryHeap,
sym::BTreeSet,
sym::BTreeMap,
sym::HashSet,
sym::HashMap,
];
/// Checks for `unsound_collection_transmute` lint.
/// Returns `true` if it's triggered, otherwise returns `false`.
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> bool {
match (&from_ty.kind(), &to_ty.kind()) {
(ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
if from_adt.did!= to_adt.did || match_any_diagnostic_items(cx, to_adt.did, COLLECTIONS).is_none() {
return false;
}
|
.zip(to_substs.types())
.any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty))
{
span_lint(
cx,
UNSOUND_COLLECTION_TRANSMUTE,
e.span,
&format!(
"transmute from `{}` to `{}` with mismatched layout is unsound",
from_ty, to_ty
),
);
true
} else {
false
}
},
_ => false,
}
}
|
if from_substs
.types()
|
random_line_split
|
unsound_collection_transmute.rs
|
use super::utils::is_layout_incompatible;
use super::UNSOUND_COLLECTION_TRANSMUTE;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::match_any_diagnostic_items;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use rustc_span::symbol::{sym, Symbol};
// used to check for UNSOUND_COLLECTION_TRANSMUTE
static COLLECTIONS: &[Symbol] = &[
sym::Vec,
sym::VecDeque,
sym::BinaryHeap,
sym::BTreeSet,
sym::BTreeMap,
sym::HashSet,
sym::HashMap,
];
/// Checks for `unsound_collection_transmute` lint.
/// Returns `true` if it's triggered, otherwise returns `false`.
pub(super) fn
|
<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> bool {
match (&from_ty.kind(), &to_ty.kind()) {
(ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
if from_adt.did!= to_adt.did || match_any_diagnostic_items(cx, to_adt.did, COLLECTIONS).is_none() {
return false;
}
if from_substs
.types()
.zip(to_substs.types())
.any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty))
{
span_lint(
cx,
UNSOUND_COLLECTION_TRANSMUTE,
e.span,
&format!(
"transmute from `{}` to `{}` with mismatched layout is unsound",
from_ty, to_ty
),
);
true
} else {
false
}
},
_ => false,
}
}
|
check
|
identifier_name
|
libbuild.rs
|
#[allow(dead_code)]
const VERSION_ENVVAR: &'static str = "PLAN_VERSION";
#[allow(dead_code)]
mod builder {
use std::env;
use std::process::Command;
use super::VERSION_ENVVAR;
pub fn common() {
super::version::write_file(version());
}
pub fn version() -> String {
match env::var(VERSION_ENVVAR) {
Ok(ver) => ver,
_ => read_git_version(),
}
}
fn read_git_version() -> String {
let child = Command::new("git")
.arg("rev-parse")
.arg("HEAD")
.output()
.expect("Failed to spawn child");
String::from_utf8_lossy(&child.stdout).into_owned()
}
}
#[allow(dead_code)]
mod habitat {
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use super::VERSION_ENVVAR;
pub fn common() {
super::version::write_file(version());
}
pub fn version() -> String {
match env::var(VERSION_ENVVAR) {
Ok(ver) => ver,
_ => read_common_version(),
}
}
fn read_common_version() -> String {
let ver_file = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
.parent()
.unwrap()
.parent()
.unwrap()
.join("VERSION");
|
.expect("Failed to read line from version file");
ver
}
}
#[allow(dead_code)]
mod util {
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
pub fn write_out_dir_file<P, S>(filename: P, content: S)
where
P: AsRef<Path>,
S: AsRef<str>,
{
let mut f = File::create(
Path::new(&env::var("OUT_DIR").expect("Failed to read OUT_DIR environment variable"))
.join(filename),
).expect("Failed to create OUT_DIR file");
f.write_all(content.as_ref().trim().as_bytes())
.expect("Failed to write to OUT_DIR file");
}
}
#[allow(dead_code)]
mod version {
pub fn write_file<S: AsRef<str>>(version: S) {
super::util::write_out_dir_file("VERSION", version);
}
}
|
let f = File::open(ver_file).expect("Failed to open version file");
let mut reader = BufReader::new(f);
let mut ver = String::new();
reader
.read_line(&mut ver)
|
random_line_split
|
libbuild.rs
|
#[allow(dead_code)]
const VERSION_ENVVAR: &'static str = "PLAN_VERSION";
#[allow(dead_code)]
mod builder {
use std::env;
use std::process::Command;
use super::VERSION_ENVVAR;
pub fn common() {
super::version::write_file(version());
}
pub fn version() -> String {
match env::var(VERSION_ENVVAR) {
Ok(ver) => ver,
_ => read_git_version(),
}
}
fn read_git_version() -> String {
let child = Command::new("git")
.arg("rev-parse")
.arg("HEAD")
.output()
.expect("Failed to spawn child");
String::from_utf8_lossy(&child.stdout).into_owned()
}
}
#[allow(dead_code)]
mod habitat {
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use super::VERSION_ENVVAR;
pub fn common() {
super::version::write_file(version());
}
pub fn version() -> String {
match env::var(VERSION_ENVVAR) {
Ok(ver) => ver,
_ => read_common_version(),
}
}
fn read_common_version() -> String {
let ver_file = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
.parent()
.unwrap()
.parent()
.unwrap()
.join("VERSION");
let f = File::open(ver_file).expect("Failed to open version file");
let mut reader = BufReader::new(f);
let mut ver = String::new();
reader
.read_line(&mut ver)
.expect("Failed to read line from version file");
ver
}
}
#[allow(dead_code)]
mod util {
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
pub fn write_out_dir_file<P, S>(filename: P, content: S)
where
P: AsRef<Path>,
S: AsRef<str>,
{
let mut f = File::create(
Path::new(&env::var("OUT_DIR").expect("Failed to read OUT_DIR environment variable"))
.join(filename),
).expect("Failed to create OUT_DIR file");
f.write_all(content.as_ref().trim().as_bytes())
.expect("Failed to write to OUT_DIR file");
}
}
#[allow(dead_code)]
mod version {
pub fn write_file<S: AsRef<str>>(version: S)
|
}
|
{
super::util::write_out_dir_file("VERSION", version);
}
|
identifier_body
|
libbuild.rs
|
#[allow(dead_code)]
const VERSION_ENVVAR: &'static str = "PLAN_VERSION";
#[allow(dead_code)]
mod builder {
use std::env;
use std::process::Command;
use super::VERSION_ENVVAR;
pub fn common() {
super::version::write_file(version());
}
pub fn version() -> String {
match env::var(VERSION_ENVVAR) {
Ok(ver) => ver,
_ => read_git_version(),
}
}
fn read_git_version() -> String {
let child = Command::new("git")
.arg("rev-parse")
.arg("HEAD")
.output()
.expect("Failed to spawn child");
String::from_utf8_lossy(&child.stdout).into_owned()
}
}
#[allow(dead_code)]
mod habitat {
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use super::VERSION_ENVVAR;
pub fn common() {
super::version::write_file(version());
}
pub fn version() -> String {
match env::var(VERSION_ENVVAR) {
Ok(ver) => ver,
_ => read_common_version(),
}
}
fn read_common_version() -> String {
let ver_file = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
.parent()
.unwrap()
.parent()
.unwrap()
.join("VERSION");
let f = File::open(ver_file).expect("Failed to open version file");
let mut reader = BufReader::new(f);
let mut ver = String::new();
reader
.read_line(&mut ver)
.expect("Failed to read line from version file");
ver
}
}
#[allow(dead_code)]
mod util {
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
pub fn write_out_dir_file<P, S>(filename: P, content: S)
where
P: AsRef<Path>,
S: AsRef<str>,
{
let mut f = File::create(
Path::new(&env::var("OUT_DIR").expect("Failed to read OUT_DIR environment variable"))
.join(filename),
).expect("Failed to create OUT_DIR file");
f.write_all(content.as_ref().trim().as_bytes())
.expect("Failed to write to OUT_DIR file");
}
}
#[allow(dead_code)]
mod version {
pub fn
|
<S: AsRef<str>>(version: S) {
super::util::write_out_dir_file("VERSION", version);
}
}
|
write_file
|
identifier_name
|
varlink_grammar.rs
|
pub use grammar::*;
peg::parser! {
grammar grammar() for str {
/* Modeled after ECMA-262, 5th ed., 7.2. */
rule whitespace() -> &'input str
= quiet!{$([''| '\t' | '\u{00A0}' | '\u{FEFF}' | '\u{1680}' | '\u{180E}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' ])}
/ expected!("whitespace")
/* Modeled after ECMA-262, 5th ed., 7.3. */
rule eol_r() -> &'input str
= $( "\n" )
/ $( "\r\n" )
/ $( "\r" )
/ $( "\u{2028}" )
/ $( "\u{2029}" )
rule comment() -> &'input str
= quiet!{
$( "#" (!['\n' | '\r' | '\u{2028}' | '\u{2029}' ][_])* eol_r() )
}
/ expected!("<comment>")
rule eol() -> &'input str
= quiet!{ $( whitespace()* eol_r() ) }
/ quiet! { $( comment() ) }
/ expected!("<newline>")
rule wce() -> &'input str
= quiet! { $( whitespace() / comment() / eol_r() ) }
/ expected!("<newline> <whitespace> or <comment>")
rule field_name() -> &'input str
= $( ['a'..='z' | 'A'..='Z'] ( "_"? ['a'..='z' | 'A'..='Z' | '0'..='9'] )* )
rule name() -> &'input str
= $( ['A'..='Z']['a'..='z' | 'A'..='Z' | '0'..='9']* )
rule interface_name() -> &'input str /* no hyphen at begin and end */
= quiet! { $( ['a'..='z'] ( ['-']*['a'..='z' | '0'..='9'] )* ( ['.']['a'..='z' | '0'..='9'] (['-']*['a'..='z' | '0'..='9'])* )+ ) }
/ expected!("<reverse domain name>")
rule array() -> ()
= "[]"
rule dict() -> ()
= "[string]"
rule option() -> ()
= "?"
use crate::VType;
use crate::VTypeExt;
rule btype() -> VTypeExt<'input>
= "bool" { VTypeExt::Plain(VType::Bool)}
/ "int" { VTypeExt::Plain(VType::Int)}
/ "float" { VTypeExt::Plain(VType::Float)}
/ "string" { VTypeExt::Plain(VType::String)}
/ "object" { VTypeExt::Plain(VType::Object)}
/ t:$(name()) { VTypeExt::Plain(VType::Typename(t))}
/ v:vstruct() { VTypeExt::Plain(VType::Struct(Box::new(v)))}
/ v:venum() { VTypeExt::Plain(VType::Enum(Box::new(v)))}
rule type_() -> VTypeExt<'input>
= v:btype() { v }
/ a:array() v:type_() { VTypeExt::Array(Box::new(v)) }
/ a:dict() v:type_() { VTypeExt::Dict(Box::new(v)) }
/ o:option() v:btype() { VTypeExt::Option(Box::new(v)) }
/ o:option() a:array() v:type_() { VTypeExt::Option(Box::new(VTypeExt::Array(Box::new(v)))) }
/ o:option() a:dict() v:type_() { VTypeExt::Option(Box::new(VTypeExt::Dict(Box::new(v)))) }
use crate::Argument;
rule object_field() -> Argument<'input>
= wce()* n:$(field_name()) wce()* [':'] wce()* v:type_() { Argument { name : n, vtype : v } }
use crate::VStruct;
rule vstruct() -> VStruct<'input>
= ['('] wce()* e:object_field() ** [','] wce()* [')'] { VStruct{ elts: e} }
use crate::VEnum;
rule venum() -> VEnum<'input>
= ['('] wce()* v:field_name() ** ( [','] wce()* ) wce()* [')'] { VEnum { elts: v } }
|
use crate::trim_doc;
rule vtypedef() -> Typedef<'input>
= d:$(wce()*) "type" wce()+ n:$(name()) wce()* v:vstruct() {
Typedef{name: n, doc: trim_doc(d), elt: VStructOrEnum::VStruct(Box::new(v))}
}
/ d:$(wce()*) "type" wce()+ n:$(name()) wce()* v:venum() {
Typedef{name: n, doc: trim_doc(d), elt: VStructOrEnum::VEnum(Box::new(v))}
}
use crate::VError;
rule error() -> VError<'input>
= d:$(wce()*) "error" wce()+ n:$(name()) wce()* p:vstruct() { VError{name: n, doc: trim_doc(d), parm: p} }
use crate::Method;
rule method() -> Method<'input>
= d:$(wce()*) "method" wce()+ n:$(name()) wce()* i:vstruct() wce()* "->" wce()* o:vstruct() {
Method {
name: n,
doc: trim_doc(d),
input: i,
output: o
}
}
use crate::MethodOrTypedefOrError;
rule member() -> MethodOrTypedefOrError<'input>
= m:method() { MethodOrTypedefOrError::Method(m) }
/ t:vtypedef() { MethodOrTypedefOrError::Typedef(t) }
/ e:error() { MethodOrTypedefOrError::Error(e) }
use crate::IDL;
pub rule ParseInterface() -> IDL<'input>
= d:$(wce()*) "interface" wce()+ n:$interface_name() eol() mt:(member()++ eol()) wce()* {
IDL::from_token(__input, n, mt, trim_doc(d))
}
}
}
|
use crate::Typedef;
use crate::VStructOrEnum;
|
random_line_split
|
hrtb-parse.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we can parse all the various places that a `for` keyword
// can appear representing universal quantification.
#![feature(unboxed_closures)]
#![allow(unused_variables)]
#![allow(dead_code)]
trait Get<A,R> {
fn get(&self, arg: A) -> R;
}
// Parse HRTB with explicit `for` in a where-clause:
fn foo00<T>(t: T)
where T : for<'a> Get<&'a int, &'a int>
{
}
fn foo01<T: for<'a> Get<&'a int, &'a int>>(t: T)
{
}
// Parse HRTB with explicit `for` in various sorts of types:
fn foo10(t: Box<for<'a> Get<int, int>>)
|
fn foo11(t: Box<for<'a> Get(int) -> int>) { }
fn foo20(t: for<'a> fn(int) -> int) { }
fn foo21(t: for<'a> unsafe fn(int) -> int) { }
fn foo22(t: for<'a> extern "C" fn(int) -> int) { }
fn foo23(t: for<'a> unsafe extern "C" fn(int) -> int) { }
fn foo30(t: for<'a> |int| -> int) { }
fn foo31(t: for<'a> unsafe |int| -> int) { }
//fn foo40(t: for<'a> proc(int) -> int) { }
fn main() {
}
|
{ }
|
identifier_body
|
hrtb-parse.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we can parse all the various places that a `for` keyword
// can appear representing universal quantification.
#![feature(unboxed_closures)]
#![allow(unused_variables)]
#![allow(dead_code)]
trait Get<A,R> {
fn get(&self, arg: A) -> R;
}
// Parse HRTB with explicit `for` in a where-clause:
fn foo00<T>(t: T)
where T : for<'a> Get<&'a int, &'a int>
{
}
fn
|
<T: for<'a> Get<&'a int, &'a int>>(t: T)
{
}
// Parse HRTB with explicit `for` in various sorts of types:
fn foo10(t: Box<for<'a> Get<int, int>>) { }
fn foo11(t: Box<for<'a> Get(int) -> int>) { }
fn foo20(t: for<'a> fn(int) -> int) { }
fn foo21(t: for<'a> unsafe fn(int) -> int) { }
fn foo22(t: for<'a> extern "C" fn(int) -> int) { }
fn foo23(t: for<'a> unsafe extern "C" fn(int) -> int) { }
fn foo30(t: for<'a> |int| -> int) { }
fn foo31(t: for<'a> unsafe |int| -> int) { }
//fn foo40(t: for<'a> proc(int) -> int) { }
fn main() {
}
|
foo01
|
identifier_name
|
hrtb-parse.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we can parse all the various places that a `for` keyword
// can appear representing universal quantification.
#![feature(unboxed_closures)]
#![allow(unused_variables)]
#![allow(dead_code)]
|
fn foo00<T>(t: T)
where T : for<'a> Get<&'a int, &'a int>
{
}
fn foo01<T: for<'a> Get<&'a int, &'a int>>(t: T)
{
}
// Parse HRTB with explicit `for` in various sorts of types:
fn foo10(t: Box<for<'a> Get<int, int>>) { }
fn foo11(t: Box<for<'a> Get(int) -> int>) { }
fn foo20(t: for<'a> fn(int) -> int) { }
fn foo21(t: for<'a> unsafe fn(int) -> int) { }
fn foo22(t: for<'a> extern "C" fn(int) -> int) { }
fn foo23(t: for<'a> unsafe extern "C" fn(int) -> int) { }
fn foo30(t: for<'a> |int| -> int) { }
fn foo31(t: for<'a> unsafe |int| -> int) { }
//fn foo40(t: for<'a> proc(int) -> int) { }
fn main() {
}
|
trait Get<A,R> {
fn get(&self, arg: A) -> R;
}
// Parse HRTB with explicit `for` in a where-clause:
|
random_line_split
|
logger.rs
|
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use crate::PythonLogLevel;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write as FmtWrite;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use arc_swap::ArcSwap;
use chrono::Timelike;
use colored::*;
use lazy_static::lazy_static;
use log::{debug, log, set_logger, set_max_level, Level, LevelFilter, Log, Metadata, Record};
use parking_lot::Mutex;
use regex::Regex;
const TIME_FORMAT_STR: &str = "%H:%M:%S";
lazy_static! {
pub static ref PANTS_LOGGER: PantsLogger = PantsLogger::new();
}
struct Inner {
per_run_logs: Mutex<Option<File>>,
log_file: Mutex<Option<File>>,
global_level: LevelFilter,
show_rust_3rdparty_logs: bool,
show_target: bool,
log_level_filters: HashMap<String, log::LevelFilter>,
literal_filters: Vec<String>,
regex_filters: Vec<Regex>,
}
pub struct PantsLogger(ArcSwap<Inner>);
impl PantsLogger {
pub fn new() -> PantsLogger {
PantsLogger(ArcSwap::from(Arc::new(Inner {
per_run_logs: Mutex::new(None),
log_file: Mutex::new(None),
global_level: LevelFilter::Off,
show_rust_3rdparty_logs: true,
show_target: false,
log_level_filters: HashMap::new(),
literal_filters: Vec::new(),
regex_filters: Vec::new(),
})))
}
pub fn init(
max_level: u64,
show_rust_3rdparty_logs: bool,
show_target: bool,
log_levels_by_target: HashMap<String, u64>,
literal_filters: Vec<String>,
regex_filters: Vec<Regex>,
log_file_path: PathBuf,
) -> Result<(), String> {
let log_level_filters = log_levels_by_target
.iter()
.map(|(k, v)| {
let python_level: PythonLogLevel = (*v).try_into().unwrap_or_else(|e| {
panic!("Unrecognized log level from python: {}: {}", v, e);
});
let level: log::LevelFilter = python_level.into();
(k.clone(), level)
})
.collect::<HashMap<_, _>>();
let max_python_level: PythonLogLevel = max_level
.try_into()
.map_err(|e| format!("Unrecognised log level from Python: {}: {}", max_level, e))?;
let global_level: LevelFilter = max_python_level.into();
let log_file = OpenOptions::new()
.create(true)
.append(true)
.open(log_file_path)
.map_err(|err| format!("Error opening pantsd logfile: {}", err))?;
PANTS_LOGGER.0.store(Arc::new(Inner {
per_run_logs: Mutex::default(),
log_file: Mutex::new(Some(log_file)),
global_level,
show_rust_3rdparty_logs,
show_target,
log_level_filters,
literal_filters,
regex_filters,
}));
if set_logger(&*PANTS_LOGGER).is_err() {
debug!("Logging already initialized.");
}
// TODO this should be whatever the most verbose log level specified in log_levels_by_target -
// but I'm not sure if it's actually much of a gain over just setting this to Trace.
set_max_level(LevelFilter::Trace);
// We make per-destination decisions about whether to render color, and should never use
// environment variables to decide.
colored::control::set_override(true);
Ok(())
}
pub fn set_per_run_logs(&self, per_run_log_path: Option<PathBuf>) {
match per_run_log_path {
None => {
*self.0.load().per_run_logs.lock() = None;
}
Some(path) => {
let file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|err| format!("Error opening per-run logfile: {}", err))
.unwrap();
*self.0.load().per_run_logs.lock() = Some(file);
}
};
}
/// log_from_python is only used in the Python FFI, which in turn is only called within the
/// Python `NativeHandler` class. Every logging call from Python should get proxied through this
/// function, which translates the log message into the Rust log paradigm provided by
/// the `log` crate.
pub fn log_from_python(message: &str, python_level: u64, target: &str) -> Result<(), String> {
let level: PythonLogLevel = python_level.try_into().map_err(|err| format!("{}", err))?;
log!(target: target, level.into(), "{}", message);
Ok(())
}
}
impl Log for PantsLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
let inner = self.0.load();
let enabled_globally = metadata.level() <= inner.global_level;
let enabled_for_target = inner
.log_level_filters
.get(metadata.target())
.map(|lf| metadata.level() <= *lf)
.unwrap_or(false);
enabled_globally || enabled_for_target
}
fn log(&self, record: &Record) {
if!self.enabled(record.metadata()) {
return;
}
let inner = self.0.load();
let mut should_log = inner.show_rust_3rdparty_logs;
if!should_log {
if let Some(module_path) = record.module_path() {
for pants_package in super::pants_packages::PANTS_PACKAGE_NAMES {
if &module_path.split("::").next().unwrap() == pants_package {
should_log = true;
break;
}
}
} else {
should_log = true;
}
}
if!should_log {
return;
}
let log_msg = format!("{}", record.args());
if inner
.literal_filters
.iter()
.any(|filt| log_msg.starts_with(filt))
{
return;
}
if inner.regex_filters.iter().any(|re| re.is_match(&log_msg)) {
return;
}
let destination = stdio::get_destination();
// Build the message string.
let log_string = {
let mut log_string = {
let cur_date = chrono::Local::now();
format!(
"{}.{:02}",
cur_date.format(TIME_FORMAT_STR),
cur_date.time().nanosecond() / 10_000_000 // Two decimal places of precision.
)
};
let use_color = destination.stderr_use_color();
let level = record.level();
let level_marker = match level {
_ if!use_color => format!("[{}]", level).normal().clear(),
Level::Info => format!("[{}]", level).normal(),
Level::Error => format!("[{}]", level).red(),
Level::Warn => format!("[{}]", level).yellow(),
Level::Debug => format!("[{}]", level).green(),
Level::Trace => format!("[{}]", level).magenta(),
};
write!(log_string, " {}", level_marker).unwrap();
if inner.show_target {
write!(log_string, " ({})", record.target()).unwrap();
};
writeln!(log_string, " {}", log_msg).unwrap();
log_string
};
let log_bytes = log_string.as_bytes();
{
let mut maybe_per_run_file = inner.per_run_logs.lock();
if let Some(ref mut file) = *maybe_per_run_file {
// deliberately ignore errors writing to per-run log file
let _ = file.write_all(log_bytes);
}
}
// Attempt to write to stdio, and write to the pantsd log if we fail (either because we don't
// have a valid stdio instance, or because of an error).
if destination.write_stderr_raw(log_bytes).is_err() {
let mut maybe_file = inner.log_file.lock();
if let Some(ref mut file) = *maybe_file {
match file.write_all(log_bytes) {
Ok(()) => (),
Err(e) => {
// If we've failed to write to stdio, but also to our log file, our only recourse is to
// try to write to a different file.
debug_log!("fatal.log", "Failed to write to log file {:?}: {}", file, e);
}
}
}
}
}
fn
|
(&self) {}
}
|
flush
|
identifier_name
|
logger.rs
|
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use crate::PythonLogLevel;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write as FmtWrite;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use arc_swap::ArcSwap;
use chrono::Timelike;
use colored::*;
use lazy_static::lazy_static;
use log::{debug, log, set_logger, set_max_level, Level, LevelFilter, Log, Metadata, Record};
use parking_lot::Mutex;
use regex::Regex;
const TIME_FORMAT_STR: &str = "%H:%M:%S";
lazy_static! {
pub static ref PANTS_LOGGER: PantsLogger = PantsLogger::new();
}
struct Inner {
per_run_logs: Mutex<Option<File>>,
log_file: Mutex<Option<File>>,
global_level: LevelFilter,
show_rust_3rdparty_logs: bool,
show_target: bool,
log_level_filters: HashMap<String, log::LevelFilter>,
literal_filters: Vec<String>,
regex_filters: Vec<Regex>,
}
pub struct PantsLogger(ArcSwap<Inner>);
impl PantsLogger {
pub fn new() -> PantsLogger {
PantsLogger(ArcSwap::from(Arc::new(Inner {
per_run_logs: Mutex::new(None),
log_file: Mutex::new(None),
global_level: LevelFilter::Off,
show_rust_3rdparty_logs: true,
show_target: false,
log_level_filters: HashMap::new(),
literal_filters: Vec::new(),
regex_filters: Vec::new(),
})))
}
pub fn init(
max_level: u64,
show_rust_3rdparty_logs: bool,
show_target: bool,
log_levels_by_target: HashMap<String, u64>,
literal_filters: Vec<String>,
regex_filters: Vec<Regex>,
log_file_path: PathBuf,
) -> Result<(), String> {
let log_level_filters = log_levels_by_target
.iter()
.map(|(k, v)| {
let python_level: PythonLogLevel = (*v).try_into().unwrap_or_else(|e| {
panic!("Unrecognized log level from python: {}: {}", v, e);
});
let level: log::LevelFilter = python_level.into();
(k.clone(), level)
})
.collect::<HashMap<_, _>>();
let max_python_level: PythonLogLevel = max_level
.try_into()
.map_err(|e| format!("Unrecognised log level from Python: {}: {}", max_level, e))?;
let global_level: LevelFilter = max_python_level.into();
let log_file = OpenOptions::new()
.create(true)
.append(true)
.open(log_file_path)
.map_err(|err| format!("Error opening pantsd logfile: {}", err))?;
PANTS_LOGGER.0.store(Arc::new(Inner {
per_run_logs: Mutex::default(),
log_file: Mutex::new(Some(log_file)),
global_level,
show_rust_3rdparty_logs,
show_target,
log_level_filters,
literal_filters,
regex_filters,
}));
if set_logger(&*PANTS_LOGGER).is_err() {
debug!("Logging already initialized.");
}
// TODO this should be whatever the most verbose log level specified in log_levels_by_target -
// but I'm not sure if it's actually much of a gain over just setting this to Trace.
set_max_level(LevelFilter::Trace);
// We make per-destination decisions about whether to render color, and should never use
// environment variables to decide.
colored::control::set_override(true);
Ok(())
}
pub fn set_per_run_logs(&self, per_run_log_path: Option<PathBuf>) {
match per_run_log_path {
None => {
*self.0.load().per_run_logs.lock() = None;
}
Some(path) => {
let file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|err| format!("Error opening per-run logfile: {}", err))
.unwrap();
*self.0.load().per_run_logs.lock() = Some(file);
}
};
}
/// log_from_python is only used in the Python FFI, which in turn is only called within the
/// Python `NativeHandler` class. Every logging call from Python should get proxied through this
/// function, which translates the log message into the Rust log paradigm provided by
/// the `log` crate.
pub fn log_from_python(message: &str, python_level: u64, target: &str) -> Result<(), String> {
let level: PythonLogLevel = python_level.try_into().map_err(|err| format!("{}", err))?;
log!(target: target, level.into(), "{}", message);
Ok(())
}
}
impl Log for PantsLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
let inner = self.0.load();
let enabled_globally = metadata.level() <= inner.global_level;
let enabled_for_target = inner
.log_level_filters
.get(metadata.target())
.map(|lf| metadata.level() <= *lf)
.unwrap_or(false);
enabled_globally || enabled_for_target
}
fn log(&self, record: &Record) {
if!self.enabled(record.metadata()) {
return;
}
let inner = self.0.load();
let mut should_log = inner.show_rust_3rdparty_logs;
if!should_log {
if let Some(module_path) = record.module_path() {
for pants_package in super::pants_packages::PANTS_PACKAGE_NAMES {
if &module_path.split("::").next().unwrap() == pants_package {
should_log = true;
break;
}
}
} else {
should_log = true;
}
}
if!should_log {
return;
}
let log_msg = format!("{}", record.args());
if inner
.literal_filters
.iter()
.any(|filt| log_msg.starts_with(filt))
{
return;
}
if inner.regex_filters.iter().any(|re| re.is_match(&log_msg)) {
return;
}
let destination = stdio::get_destination();
// Build the message string.
let log_string = {
let mut log_string = {
let cur_date = chrono::Local::now();
format!(
"{}.{:02}",
cur_date.format(TIME_FORMAT_STR),
cur_date.time().nanosecond() / 10_000_000 // Two decimal places of precision.
)
};
let use_color = destination.stderr_use_color();
let level = record.level();
let level_marker = match level {
_ if!use_color => format!("[{}]", level).normal().clear(),
Level::Info => format!("[{}]", level).normal(),
Level::Error => format!("[{}]", level).red(),
Level::Warn => format!("[{}]", level).yellow(),
Level::Debug => format!("[{}]", level).green(),
Level::Trace => format!("[{}]", level).magenta(),
};
write!(log_string, " {}", level_marker).unwrap();
if inner.show_target {
write!(log_string, " ({})", record.target()).unwrap();
};
writeln!(log_string, " {}", log_msg).unwrap();
log_string
};
let log_bytes = log_string.as_bytes();
{
let mut maybe_per_run_file = inner.per_run_logs.lock();
if let Some(ref mut file) = *maybe_per_run_file {
// deliberately ignore errors writing to per-run log file
let _ = file.write_all(log_bytes);
}
|
// Attempt to write to stdio, and write to the pantsd log if we fail (either because we don't
// have a valid stdio instance, or because of an error).
if destination.write_stderr_raw(log_bytes).is_err() {
let mut maybe_file = inner.log_file.lock();
if let Some(ref mut file) = *maybe_file {
match file.write_all(log_bytes) {
Ok(()) => (),
Err(e) => {
// If we've failed to write to stdio, but also to our log file, our only recourse is to
// try to write to a different file.
debug_log!("fatal.log", "Failed to write to log file {:?}: {}", file, e);
}
}
}
}
}
fn flush(&self) {}
}
|
}
|
random_line_split
|
logger.rs
|
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use crate::PythonLogLevel;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write as FmtWrite;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use arc_swap::ArcSwap;
use chrono::Timelike;
use colored::*;
use lazy_static::lazy_static;
use log::{debug, log, set_logger, set_max_level, Level, LevelFilter, Log, Metadata, Record};
use parking_lot::Mutex;
use regex::Regex;
const TIME_FORMAT_STR: &str = "%H:%M:%S";
lazy_static! {
pub static ref PANTS_LOGGER: PantsLogger = PantsLogger::new();
}
struct Inner {
per_run_logs: Mutex<Option<File>>,
log_file: Mutex<Option<File>>,
global_level: LevelFilter,
show_rust_3rdparty_logs: bool,
show_target: bool,
log_level_filters: HashMap<String, log::LevelFilter>,
literal_filters: Vec<String>,
regex_filters: Vec<Regex>,
}
pub struct PantsLogger(ArcSwap<Inner>);
impl PantsLogger {
pub fn new() -> PantsLogger {
PantsLogger(ArcSwap::from(Arc::new(Inner {
per_run_logs: Mutex::new(None),
log_file: Mutex::new(None),
global_level: LevelFilter::Off,
show_rust_3rdparty_logs: true,
show_target: false,
log_level_filters: HashMap::new(),
literal_filters: Vec::new(),
regex_filters: Vec::new(),
})))
}
pub fn init(
max_level: u64,
show_rust_3rdparty_logs: bool,
show_target: bool,
log_levels_by_target: HashMap<String, u64>,
literal_filters: Vec<String>,
regex_filters: Vec<Regex>,
log_file_path: PathBuf,
) -> Result<(), String> {
let log_level_filters = log_levels_by_target
.iter()
.map(|(k, v)| {
let python_level: PythonLogLevel = (*v).try_into().unwrap_or_else(|e| {
panic!("Unrecognized log level from python: {}: {}", v, e);
});
let level: log::LevelFilter = python_level.into();
(k.clone(), level)
})
.collect::<HashMap<_, _>>();
let max_python_level: PythonLogLevel = max_level
.try_into()
.map_err(|e| format!("Unrecognised log level from Python: {}: {}", max_level, e))?;
let global_level: LevelFilter = max_python_level.into();
let log_file = OpenOptions::new()
.create(true)
.append(true)
.open(log_file_path)
.map_err(|err| format!("Error opening pantsd logfile: {}", err))?;
PANTS_LOGGER.0.store(Arc::new(Inner {
per_run_logs: Mutex::default(),
log_file: Mutex::new(Some(log_file)),
global_level,
show_rust_3rdparty_logs,
show_target,
log_level_filters,
literal_filters,
regex_filters,
}));
if set_logger(&*PANTS_LOGGER).is_err() {
debug!("Logging already initialized.");
}
// TODO this should be whatever the most verbose log level specified in log_levels_by_target -
// but I'm not sure if it's actually much of a gain over just setting this to Trace.
set_max_level(LevelFilter::Trace);
// We make per-destination decisions about whether to render color, and should never use
// environment variables to decide.
colored::control::set_override(true);
Ok(())
}
pub fn set_per_run_logs(&self, per_run_log_path: Option<PathBuf>) {
match per_run_log_path {
None => {
*self.0.load().per_run_logs.lock() = None;
}
Some(path) => {
let file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|err| format!("Error opening per-run logfile: {}", err))
.unwrap();
*self.0.load().per_run_logs.lock() = Some(file);
}
};
}
/// log_from_python is only used in the Python FFI, which in turn is only called within the
/// Python `NativeHandler` class. Every logging call from Python should get proxied through this
/// function, which translates the log message into the Rust log paradigm provided by
/// the `log` crate.
pub fn log_from_python(message: &str, python_level: u64, target: &str) -> Result<(), String> {
let level: PythonLogLevel = python_level.try_into().map_err(|err| format!("{}", err))?;
log!(target: target, level.into(), "{}", message);
Ok(())
}
}
impl Log for PantsLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
let inner = self.0.load();
let enabled_globally = metadata.level() <= inner.global_level;
let enabled_for_target = inner
.log_level_filters
.get(metadata.target())
.map(|lf| metadata.level() <= *lf)
.unwrap_or(false);
enabled_globally || enabled_for_target
}
fn log(&self, record: &Record) {
if!self.enabled(record.metadata()) {
return;
}
let inner = self.0.load();
let mut should_log = inner.show_rust_3rdparty_logs;
if!should_log {
if let Some(module_path) = record.module_path() {
for pants_package in super::pants_packages::PANTS_PACKAGE_NAMES {
if &module_path.split("::").next().unwrap() == pants_package {
should_log = true;
break;
}
}
} else {
should_log = true;
}
}
if!should_log {
return;
}
let log_msg = format!("{}", record.args());
if inner
.literal_filters
.iter()
.any(|filt| log_msg.starts_with(filt))
{
return;
}
if inner.regex_filters.iter().any(|re| re.is_match(&log_msg)) {
return;
}
let destination = stdio::get_destination();
// Build the message string.
let log_string = {
let mut log_string = {
let cur_date = chrono::Local::now();
format!(
"{}.{:02}",
cur_date.format(TIME_FORMAT_STR),
cur_date.time().nanosecond() / 10_000_000 // Two decimal places of precision.
)
};
let use_color = destination.stderr_use_color();
let level = record.level();
let level_marker = match level {
_ if!use_color => format!("[{}]", level).normal().clear(),
Level::Info => format!("[{}]", level).normal(),
Level::Error => format!("[{}]", level).red(),
Level::Warn => format!("[{}]", level).yellow(),
Level::Debug => format!("[{}]", level).green(),
Level::Trace => format!("[{}]", level).magenta(),
};
write!(log_string, " {}", level_marker).unwrap();
if inner.show_target
|
;
writeln!(log_string, " {}", log_msg).unwrap();
log_string
};
let log_bytes = log_string.as_bytes();
{
let mut maybe_per_run_file = inner.per_run_logs.lock();
if let Some(ref mut file) = *maybe_per_run_file {
// deliberately ignore errors writing to per-run log file
let _ = file.write_all(log_bytes);
}
}
// Attempt to write to stdio, and write to the pantsd log if we fail (either because we don't
// have a valid stdio instance, or because of an error).
if destination.write_stderr_raw(log_bytes).is_err() {
let mut maybe_file = inner.log_file.lock();
if let Some(ref mut file) = *maybe_file {
match file.write_all(log_bytes) {
Ok(()) => (),
Err(e) => {
// If we've failed to write to stdio, but also to our log file, our only recourse is to
// try to write to a different file.
debug_log!("fatal.log", "Failed to write to log file {:?}: {}", file, e);
}
}
}
}
}
fn flush(&self) {}
}
|
{
write!(log_string, " ({})", record.target()).unwrap();
}
|
conditional_block
|
lib.rs
|
// @Author: Cha Dowon <dowon>
// @Date: 2016-11-20T11:01:12-05:00
// @Project: BeAM
// @Filename: lib.rs
// @Last modified by: dowon
// @Last modified time: 2016-11-20T11:03:21-05:00
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#[macro_use]
extern crate error_chain;
extern crate log;
pub mod errors {
error_chain! {
}
}
// Nalgebra for math
extern crate nalgebra as na;
extern crate image;
extern crate futures;
use futures::prelude::*;
// extern crate threadpool;
pub use self::light::*;
pub use self::scene::*;
pub use self::material::*;
pub use self::geometry::*;
// pub mod device;
// mod render;
// mod kernel;
mod util;
mod camera;
mod finish;
mod light;
mod scene;
mod material;
mod geometry;
mod ray;
mod types;
mod texture;
/**
* Imports
*/
use std::fs::File;
use std::path::Path;
use std::sync::mpsc::channel;
use std::sync::Arc;
use image::{RgbaImage, ImageBuffer};
use geometry::object::Intersection;
use ::types::{Vec3f, Color, TColor};
pub use ray::Ray;
use texture::Texture;
pub fn render(scene: &mut Scene) {
let future = render_async(scene);
}
fn render_async(scene: &mut Scene) -> Box<Future<Item=u32,Error=String>> {
unimplemented!()
}
struct RenderPayload {
// future
// scene
scene: Arc<Scene>
// bvh
}
struct RenderState<'s> {
scene: &'s Scene,
intersection: &'s Intersection,
recursion_level: usize,
ior: f64,
viewer: Vec3f,
reflected: Vec3f,
r: Vec3f,
texture: &'s Texture
}
fn render_scene(payload: RenderPayload)
|
// let color = shoot_ray(&state, ray);
// scene.canvas().set_pixel(x, y, color);
}
// Increment future
}
}
fn shoot_ray(state: &mut RenderState, ray: Ray) { // -> TColor {
if state.recursion_level == 0 {
// return black
}
{
state.recursion_level -= 1;
}
/*
let intersection = {
// let bvh = &state.bvh;
// bvh.intersection(ray)
};
if let Some(intersection) = intersection {
// Found an intersection
}
*/
// TColor::from_channels(0.0, 0.0, 0.0, 1.0)
}
fn evaluate_specular(state: &RenderState) -> Color {
if let Some(ref finish) = state.texture.finish() {
}
Color::black()
}
pub enum SampleMode {
None,
Uniform(i32),
Random(i32)
}
pub struct RenderConfig {
pub scene_name: &'static str, // Input scene dir
pub output_name: &'static str, // Output file name
pub width: u32, // Width of final image
pub height: u32, // Height of final image
pub sample_mode: SampleMode, // Anti aliasing sampling mode
pub format: image::ImageFormat // Ext of output image
}
fn gamma_encode(color: Color) -> Color {
let gamma = 1.0 / 2.4;
unimplemented!();
// let mut out = Color::new_zeros(4);
// out.index(0) = if color.x <= 0.0031308 { 12.92 * color.x } else { 1.055 * std::math::pow(color.x, gamma) - 0.055 };
// out.y = (color.y <= 0.0031308f )? 12.92 * color.y : 1.055 * std::pow(color.y, gamma) - 0.055;
// out.z = (color.z <= 0.0031308f )? 12.92 * color.z : 1.055 * std::pow(color.z, gamma) - 0.055;
// out.w = (color.w <= 0.0031308f )? 12.92 * color.w : 1.055 * std::pow(color.z, gamma) - 0.055;
}
const MAX_TRACE_DEPTH: i32 = 2;
fn trace(scene: &Scene, ray: &Ray, depth: i32) -> Vec4f {
// Base case
// Return black if max trace depth is hit
if depth > MAX_TRACE_DEPTH {
return Vec4f::new(0.0, 0.0, 0.0, 0.0);
}
/*
let hit_data = match scene.intersect_surfaces(ray, None) {
Some(result) => result,
None => return Vec4f::new(0.0, 0.0, 0.0, 0.0)
};
// Local illumination calculation (ambient, specular, diffuse)
// Additionally calculates shadows
let local_color = local_shading(scene, ray, &hit_data);
let material_name = hit_data.hit_item.material();
let reflection_coef = 0.5;
*/
// let reflection_coef = match scene.get_material(material_name) {
// Some(material) => material.reflectivity(),
// None => 0.0
// };
/*
if reflection_coef > 0.0 {
let incident = -ray.direction();
// Vector3f dir = incident - data.normal * (2.0f * data.normal.dot(incident));
// Ray reflectionRay(data.hit_point, dir.normalized());
// Vector4f reflect = Trace(reflectionRay, depth + 1);
// local = Utility::lerp(local, reflect, reflectionCoef);
}
*/
Vec4f::new(0.0, 0.0, 0.0, 0.0)
// local_color
}
|
{
// Precalculate bouding box transformations, etc
let RenderPayload {
scene,
..
} = payload;
// Iterate through each pixel
let (width, height) = (512, 512);
// let (width, height) = scene.canvas_dimensions();
// let (region_x, region_y) = scene.region_position();
// let (outer_width, outer_height) = scene.outer_dimensions();
'outer: for y in 0..height {
'inner: for x in 0..width {
//let nx = ( x + region_x ) / (outer_width - 1);
//let ny = ( y + region_y ) / (outer_height - 1);
//let ray = scene.camera.ray(nx, ny);
|
identifier_body
|
lib.rs
|
// @Author: Cha Dowon <dowon>
// @Date: 2016-11-20T11:01:12-05:00
// @Project: BeAM
// @Filename: lib.rs
// @Last modified by: dowon
// @Last modified time: 2016-11-20T11:03:21-05:00
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#[macro_use]
extern crate error_chain;
extern crate log;
pub mod errors {
error_chain! {
}
}
// Nalgebra for math
extern crate nalgebra as na;
extern crate image;
extern crate futures;
use futures::prelude::*;
// extern crate threadpool;
pub use self::light::*;
pub use self::scene::*;
pub use self::material::*;
pub use self::geometry::*;
// pub mod device;
// mod render;
// mod kernel;
mod util;
mod camera;
mod finish;
mod light;
mod scene;
mod material;
mod geometry;
mod ray;
mod types;
mod texture;
/**
* Imports
*/
use std::fs::File;
use std::path::Path;
use std::sync::mpsc::channel;
use std::sync::Arc;
use image::{RgbaImage, ImageBuffer};
use geometry::object::Intersection;
use ::types::{Vec3f, Color, TColor};
pub use ray::Ray;
use texture::Texture;
pub fn render(scene: &mut Scene) {
let future = render_async(scene);
}
fn render_async(scene: &mut Scene) -> Box<Future<Item=u32,Error=String>> {
unimplemented!()
}
struct RenderPayload {
// future
// scene
scene: Arc<Scene>
// bvh
}
struct RenderState<'s> {
scene: &'s Scene,
intersection: &'s Intersection,
recursion_level: usize,
ior: f64,
viewer: Vec3f,
reflected: Vec3f,
r: Vec3f,
texture: &'s Texture
}
fn render_scene(payload: RenderPayload) {
// Precalculate bouding box transformations, etc
let RenderPayload {
scene,
..
} = payload;
// Iterate through each pixel
let (width, height) = (512, 512);
// let (width, height) = scene.canvas_dimensions();
// let (region_x, region_y) = scene.region_position();
// let (outer_width, outer_height) = scene.outer_dimensions();
'outer: for y in 0..height {
'inner: for x in 0..width {
//let nx = ( x + region_x ) / (outer_width - 1);
//let ny = ( y + region_y ) / (outer_height - 1);
//let ray = scene.camera.ray(nx, ny);
// let color = shoot_ray(&state, ray);
// scene.canvas().set_pixel(x, y, color);
}
// Increment future
}
}
fn shoot_ray(state: &mut RenderState, ray: Ray) { // -> TColor {
if state.recursion_level == 0 {
// return black
}
{
state.recursion_level -= 1;
}
/*
let intersection = {
// let bvh = &state.bvh;
// bvh.intersection(ray)
};
if let Some(intersection) = intersection {
// Found an intersection
}
*/
// TColor::from_channels(0.0, 0.0, 0.0, 1.0)
}
fn evaluate_specular(state: &RenderState) -> Color {
if let Some(ref finish) = state.texture.finish() {
}
Color::black()
}
pub enum
|
{
None,
Uniform(i32),
Random(i32)
}
pub struct RenderConfig {
pub scene_name: &'static str, // Input scene dir
pub output_name: &'static str, // Output file name
pub width: u32, // Width of final image
pub height: u32, // Height of final image
pub sample_mode: SampleMode, // Anti aliasing sampling mode
pub format: image::ImageFormat // Ext of output image
}
fn gamma_encode(color: Color) -> Color {
let gamma = 1.0 / 2.4;
unimplemented!();
// let mut out = Color::new_zeros(4);
// out.index(0) = if color.x <= 0.0031308 { 12.92 * color.x } else { 1.055 * std::math::pow(color.x, gamma) - 0.055 };
// out.y = (color.y <= 0.0031308f )? 12.92 * color.y : 1.055 * std::pow(color.y, gamma) - 0.055;
// out.z = (color.z <= 0.0031308f )? 12.92 * color.z : 1.055 * std::pow(color.z, gamma) - 0.055;
// out.w = (color.w <= 0.0031308f )? 12.92 * color.w : 1.055 * std::pow(color.z, gamma) - 0.055;
}
const MAX_TRACE_DEPTH: i32 = 2;
fn trace(scene: &Scene, ray: &Ray, depth: i32) -> Vec4f {
// Base case
// Return black if max trace depth is hit
if depth > MAX_TRACE_DEPTH {
return Vec4f::new(0.0, 0.0, 0.0, 0.0);
}
/*
let hit_data = match scene.intersect_surfaces(ray, None) {
Some(result) => result,
None => return Vec4f::new(0.0, 0.0, 0.0, 0.0)
};
// Local illumination calculation (ambient, specular, diffuse)
// Additionally calculates shadows
let local_color = local_shading(scene, ray, &hit_data);
let material_name = hit_data.hit_item.material();
let reflection_coef = 0.5;
*/
// let reflection_coef = match scene.get_material(material_name) {
// Some(material) => material.reflectivity(),
// None => 0.0
// };
/*
if reflection_coef > 0.0 {
let incident = -ray.direction();
// Vector3f dir = incident - data.normal * (2.0f * data.normal.dot(incident));
// Ray reflectionRay(data.hit_point, dir.normalized());
// Vector4f reflect = Trace(reflectionRay, depth + 1);
// local = Utility::lerp(local, reflect, reflectionCoef);
}
*/
Vec4f::new(0.0, 0.0, 0.0, 0.0)
// local_color
}
|
SampleMode
|
identifier_name
|
lib.rs
|
// @Author: Cha Dowon <dowon>
// @Date: 2016-11-20T11:01:12-05:00
// @Project: BeAM
// @Filename: lib.rs
// @Last modified by: dowon
// @Last modified time: 2016-11-20T11:03:21-05:00
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#[macro_use]
extern crate error_chain;
extern crate log;
pub mod errors {
error_chain! {
}
}
// Nalgebra for math
extern crate nalgebra as na;
extern crate image;
extern crate futures;
use futures::prelude::*;
// extern crate threadpool;
pub use self::light::*;
pub use self::scene::*;
pub use self::material::*;
pub use self::geometry::*;
// pub mod device;
// mod render;
// mod kernel;
mod util;
mod camera;
mod finish;
mod light;
mod scene;
mod material;
mod geometry;
mod ray;
mod types;
mod texture;
/**
* Imports
*/
use std::fs::File;
use std::path::Path;
use std::sync::mpsc::channel;
use std::sync::Arc;
use image::{RgbaImage, ImageBuffer};
use geometry::object::Intersection;
use ::types::{Vec3f, Color, TColor};
pub use ray::Ray;
use texture::Texture;
pub fn render(scene: &mut Scene) {
let future = render_async(scene);
}
fn render_async(scene: &mut Scene) -> Box<Future<Item=u32,Error=String>> {
unimplemented!()
}
struct RenderPayload {
// future
// scene
scene: Arc<Scene>
// bvh
}
struct RenderState<'s> {
scene: &'s Scene,
intersection: &'s Intersection,
recursion_level: usize,
ior: f64,
viewer: Vec3f,
reflected: Vec3f,
r: Vec3f,
texture: &'s Texture
}
fn render_scene(payload: RenderPayload) {
// Precalculate bouding box transformations, etc
let RenderPayload {
scene,
..
} = payload;
// Iterate through each pixel
let (width, height) = (512, 512);
// let (width, height) = scene.canvas_dimensions();
// let (region_x, region_y) = scene.region_position();
// let (outer_width, outer_height) = scene.outer_dimensions();
'outer: for y in 0..height {
'inner: for x in 0..width {
//let nx = ( x + region_x ) / (outer_width - 1);
//let ny = ( y + region_y ) / (outer_height - 1);
//let ray = scene.camera.ray(nx, ny);
// let color = shoot_ray(&state, ray);
// scene.canvas().set_pixel(x, y, color);
}
// Increment future
}
}
fn shoot_ray(state: &mut RenderState, ray: Ray) { // -> TColor {
if state.recursion_level == 0
|
{
state.recursion_level -= 1;
}
/*
let intersection = {
// let bvh = &state.bvh;
// bvh.intersection(ray)
};
if let Some(intersection) = intersection {
// Found an intersection
}
*/
// TColor::from_channels(0.0, 0.0, 0.0, 1.0)
}
fn evaluate_specular(state: &RenderState) -> Color {
if let Some(ref finish) = state.texture.finish() {
}
Color::black()
}
pub enum SampleMode {
None,
Uniform(i32),
Random(i32)
}
pub struct RenderConfig {
pub scene_name: &'static str, // Input scene dir
pub output_name: &'static str, // Output file name
pub width: u32, // Width of final image
pub height: u32, // Height of final image
pub sample_mode: SampleMode, // Anti aliasing sampling mode
pub format: image::ImageFormat // Ext of output image
}
fn gamma_encode(color: Color) -> Color {
let gamma = 1.0 / 2.4;
unimplemented!();
// let mut out = Color::new_zeros(4);
// out.index(0) = if color.x <= 0.0031308 { 12.92 * color.x } else { 1.055 * std::math::pow(color.x, gamma) - 0.055 };
// out.y = (color.y <= 0.0031308f )? 12.92 * color.y : 1.055 * std::pow(color.y, gamma) - 0.055;
// out.z = (color.z <= 0.0031308f )? 12.92 * color.z : 1.055 * std::pow(color.z, gamma) - 0.055;
// out.w = (color.w <= 0.0031308f )? 12.92 * color.w : 1.055 * std::pow(color.z, gamma) - 0.055;
}
const MAX_TRACE_DEPTH: i32 = 2;
fn trace(scene: &Scene, ray: &Ray, depth: i32) -> Vec4f {
// Base case
// Return black if max trace depth is hit
if depth > MAX_TRACE_DEPTH {
return Vec4f::new(0.0, 0.0, 0.0, 0.0);
}
/*
let hit_data = match scene.intersect_surfaces(ray, None) {
Some(result) => result,
None => return Vec4f::new(0.0, 0.0, 0.0, 0.0)
};
// Local illumination calculation (ambient, specular, diffuse)
// Additionally calculates shadows
let local_color = local_shading(scene, ray, &hit_data);
let material_name = hit_data.hit_item.material();
let reflection_coef = 0.5;
*/
// let reflection_coef = match scene.get_material(material_name) {
// Some(material) => material.reflectivity(),
// None => 0.0
// };
/*
if reflection_coef > 0.0 {
let incident = -ray.direction();
// Vector3f dir = incident - data.normal * (2.0f * data.normal.dot(incident));
// Ray reflectionRay(data.hit_point, dir.normalized());
// Vector4f reflect = Trace(reflectionRay, depth + 1);
// local = Utility::lerp(local, reflect, reflectionCoef);
}
*/
Vec4f::new(0.0, 0.0, 0.0, 0.0)
// local_color
}
|
{
// return black
}
|
conditional_block
|
lib.rs
|
// @Author: Cha Dowon <dowon>
// @Date: 2016-11-20T11:01:12-05:00
// @Project: BeAM
// @Filename: lib.rs
// @Last modified by: dowon
// @Last modified time: 2016-11-20T11:03:21-05:00
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#[macro_use]
extern crate error_chain;
extern crate log;
pub mod errors {
error_chain! {
}
}
// Nalgebra for math
extern crate nalgebra as na;
extern crate image;
extern crate futures;
use futures::prelude::*;
// extern crate threadpool;
pub use self::light::*;
pub use self::scene::*;
pub use self::material::*;
pub use self::geometry::*;
// pub mod device;
// mod render;
// mod kernel;
mod util;
mod camera;
mod finish;
mod light;
mod scene;
mod material;
mod geometry;
mod ray;
mod types;
mod texture;
/**
* Imports
*/
use std::fs::File;
use std::path::Path;
use std::sync::mpsc::channel;
use std::sync::Arc;
use image::{RgbaImage, ImageBuffer};
use geometry::object::Intersection;
use ::types::{Vec3f, Color, TColor};
pub use ray::Ray;
use texture::Texture;
pub fn render(scene: &mut Scene) {
let future = render_async(scene);
}
fn render_async(scene: &mut Scene) -> Box<Future<Item=u32,Error=String>> {
unimplemented!()
}
struct RenderPayload {
// future
// scene
scene: Arc<Scene>
// bvh
}
struct RenderState<'s> {
scene: &'s Scene,
intersection: &'s Intersection,
recursion_level: usize,
ior: f64,
viewer: Vec3f,
reflected: Vec3f,
r: Vec3f,
texture: &'s Texture
}
fn render_scene(payload: RenderPayload) {
// Precalculate bouding box transformations, etc
let RenderPayload {
scene,
..
} = payload;
// Iterate through each pixel
let (width, height) = (512, 512);
// let (width, height) = scene.canvas_dimensions();
// let (region_x, region_y) = scene.region_position();
// let (outer_width, outer_height) = scene.outer_dimensions();
'outer: for y in 0..height {
'inner: for x in 0..width {
//let nx = ( x + region_x ) / (outer_width - 1);
//let ny = ( y + region_y ) / (outer_height - 1);
//let ray = scene.camera.ray(nx, ny);
// let color = shoot_ray(&state, ray);
// scene.canvas().set_pixel(x, y, color);
|
}
// Increment future
}
}
fn shoot_ray(state: &mut RenderState, ray: Ray) { // -> TColor {
if state.recursion_level == 0 {
// return black
}
{
state.recursion_level -= 1;
}
/*
let intersection = {
// let bvh = &state.bvh;
// bvh.intersection(ray)
};
if let Some(intersection) = intersection {
// Found an intersection
}
*/
// TColor::from_channels(0.0, 0.0, 0.0, 1.0)
}
fn evaluate_specular(state: &RenderState) -> Color {
if let Some(ref finish) = state.texture.finish() {
}
Color::black()
}
pub enum SampleMode {
None,
Uniform(i32),
Random(i32)
}
pub struct RenderConfig {
pub scene_name: &'static str, // Input scene dir
pub output_name: &'static str, // Output file name
pub width: u32, // Width of final image
pub height: u32, // Height of final image
pub sample_mode: SampleMode, // Anti aliasing sampling mode
pub format: image::ImageFormat // Ext of output image
}
fn gamma_encode(color: Color) -> Color {
let gamma = 1.0 / 2.4;
unimplemented!();
// let mut out = Color::new_zeros(4);
// out.index(0) = if color.x <= 0.0031308 { 12.92 * color.x } else { 1.055 * std::math::pow(color.x, gamma) - 0.055 };
// out.y = (color.y <= 0.0031308f )? 12.92 * color.y : 1.055 * std::pow(color.y, gamma) - 0.055;
// out.z = (color.z <= 0.0031308f )? 12.92 * color.z : 1.055 * std::pow(color.z, gamma) - 0.055;
// out.w = (color.w <= 0.0031308f )? 12.92 * color.w : 1.055 * std::pow(color.z, gamma) - 0.055;
}
const MAX_TRACE_DEPTH: i32 = 2;
fn trace(scene: &Scene, ray: &Ray, depth: i32) -> Vec4f {
// Base case
// Return black if max trace depth is hit
if depth > MAX_TRACE_DEPTH {
return Vec4f::new(0.0, 0.0, 0.0, 0.0);
}
/*
let hit_data = match scene.intersect_surfaces(ray, None) {
Some(result) => result,
None => return Vec4f::new(0.0, 0.0, 0.0, 0.0)
};
// Local illumination calculation (ambient, specular, diffuse)
// Additionally calculates shadows
let local_color = local_shading(scene, ray, &hit_data);
let material_name = hit_data.hit_item.material();
let reflection_coef = 0.5;
*/
// let reflection_coef = match scene.get_material(material_name) {
// Some(material) => material.reflectivity(),
// None => 0.0
// };
/*
if reflection_coef > 0.0 {
let incident = -ray.direction();
// Vector3f dir = incident - data.normal * (2.0f * data.normal.dot(incident));
// Ray reflectionRay(data.hit_point, dir.normalized());
// Vector4f reflect = Trace(reflectionRay, depth + 1);
// local = Utility::lerp(local, reflect, reflectionCoef);
}
*/
Vec4f::new(0.0, 0.0, 0.0, 0.0)
// local_color
}
|
random_line_split
|
|
checkout.rs
|
use crate::{Command, CommandBoxClone, WorkOption, WorkResult};
use color_printer::{Color, ColorPrinter, ColorSpec};
use command_derive::CommandBoxClone;
use gitlib::GitRepo;
use std::{io::Write, path::PathBuf};
#[derive(Clone, CommandBoxClone)]
pub struct CheckoutCommand {
branch: String,
}
impl CheckoutCommand {
pub fn
|
(branch: String) -> Self {
Self { branch }
}
}
struct CheckoutCommandResult {
branch: String,
path: PathBuf,
}
impl Command for CheckoutCommand {
fn process(&self, repo: GitRepo) -> WorkOption {
if let Ok(true) = repo.checkout(&self.branch) {
let result = CheckoutCommandResult {
path: repo.path().into(),
branch: self.branch.clone(),
};
Some(Box::new(result))
} else {
None
}
}
}
impl WorkResult for CheckoutCommandResult {
fn print(&self, printer: &mut ColorPrinter<'_>) {
let mut cs = ColorSpec::new();
cs.set_intense(true);
cs.set_fg(Some(Color::Yellow));
printer.color_context(&cs, |h| write!(h, " {}", self.branch).expect("write fail"));
writeln!(printer, " - {}", self.path.display()).expect("write fail");
}
}
|
new
|
identifier_name
|
checkout.rs
|
use crate::{Command, CommandBoxClone, WorkOption, WorkResult};
use color_printer::{Color, ColorPrinter, ColorSpec};
use command_derive::CommandBoxClone;
|
branch: String,
}
impl CheckoutCommand {
pub fn new(branch: String) -> Self {
Self { branch }
}
}
struct CheckoutCommandResult {
branch: String,
path: PathBuf,
}
impl Command for CheckoutCommand {
fn process(&self, repo: GitRepo) -> WorkOption {
if let Ok(true) = repo.checkout(&self.branch) {
let result = CheckoutCommandResult {
path: repo.path().into(),
branch: self.branch.clone(),
};
Some(Box::new(result))
} else {
None
}
}
}
impl WorkResult for CheckoutCommandResult {
fn print(&self, printer: &mut ColorPrinter<'_>) {
let mut cs = ColorSpec::new();
cs.set_intense(true);
cs.set_fg(Some(Color::Yellow));
printer.color_context(&cs, |h| write!(h, " {}", self.branch).expect("write fail"));
writeln!(printer, " - {}", self.path.display()).expect("write fail");
}
}
|
use gitlib::GitRepo;
use std::{io::Write, path::PathBuf};
#[derive(Clone, CommandBoxClone)]
pub struct CheckoutCommand {
|
random_line_split
|
checkout.rs
|
use crate::{Command, CommandBoxClone, WorkOption, WorkResult};
use color_printer::{Color, ColorPrinter, ColorSpec};
use command_derive::CommandBoxClone;
use gitlib::GitRepo;
use std::{io::Write, path::PathBuf};
#[derive(Clone, CommandBoxClone)]
pub struct CheckoutCommand {
branch: String,
}
impl CheckoutCommand {
pub fn new(branch: String) -> Self {
Self { branch }
}
}
struct CheckoutCommandResult {
branch: String,
path: PathBuf,
}
impl Command for CheckoutCommand {
fn process(&self, repo: GitRepo) -> WorkOption {
if let Ok(true) = repo.checkout(&self.branch)
|
else {
None
}
}
}
impl WorkResult for CheckoutCommandResult {
fn print(&self, printer: &mut ColorPrinter<'_>) {
let mut cs = ColorSpec::new();
cs.set_intense(true);
cs.set_fg(Some(Color::Yellow));
printer.color_context(&cs, |h| write!(h, " {}", self.branch).expect("write fail"));
writeln!(printer, " - {}", self.path.display()).expect("write fail");
}
}
|
{
let result = CheckoutCommandResult {
path: repo.path().into(),
branch: self.branch.clone(),
};
Some(Box::new(result))
}
|
conditional_block
|
dst-bad-assign-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Forbid assignment into a dynamically sized type.
struct Fat<T:?Sized> {
f1: isize,
f2: &'static str,
ptr: T
}
#[derive(PartialEq,Eq)]
struct Bar;
#[derive(PartialEq,Eq)]
struct Bar1 {
f: isize
}
trait ToBar {
fn to_bar(&self) -> Bar;
fn to_val(&self) -> isize;
}
impl ToBar for Bar1 {
fn to_bar(&self) -> Bar {
Bar
}
fn
|
(&self) -> isize {
self.f
}
}
pub fn main() {
// Assignment.
let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let z: Box<ToBar> = Box::new(Bar1 {f: 36});
f5.ptr = *z;
//~^ ERROR the trait `core::marker::Sized` is not implemented
}
|
to_val
|
identifier_name
|
dst-bad-assign-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Forbid assignment into a dynamically sized type.
struct Fat<T:?Sized> {
f1: isize,
f2: &'static str,
ptr: T
}
#[derive(PartialEq,Eq)]
struct Bar;
#[derive(PartialEq,Eq)]
struct Bar1 {
f: isize
}
trait ToBar {
fn to_bar(&self) -> Bar;
fn to_val(&self) -> isize;
}
impl ToBar for Bar1 {
fn to_bar(&self) -> Bar
|
fn to_val(&self) -> isize {
self.f
}
}
pub fn main() {
// Assignment.
let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let z: Box<ToBar> = Box::new(Bar1 {f: 36});
f5.ptr = *z;
//~^ ERROR the trait `core::marker::Sized` is not implemented
}
|
{
Bar
}
|
identifier_body
|
dst-bad-assign-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Forbid assignment into a dynamically sized type.
struct Fat<T:?Sized> {
f1: isize,
f2: &'static str,
ptr: T
}
#[derive(PartialEq,Eq)]
struct Bar;
#[derive(PartialEq,Eq)]
struct Bar1 {
f: isize
}
trait ToBar {
fn to_bar(&self) -> Bar;
|
Bar
}
fn to_val(&self) -> isize {
self.f
}
}
pub fn main() {
// Assignment.
let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let z: Box<ToBar> = Box::new(Bar1 {f: 36});
f5.ptr = *z;
//~^ ERROR the trait `core::marker::Sized` is not implemented
}
|
fn to_val(&self) -> isize;
}
impl ToBar for Bar1 {
fn to_bar(&self) -> Bar {
|
random_line_split
|
content_type.rs
|
use mime::Mime;
header! {
/// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
///
/// The `Content-Type` header field indicates the media type of the
/// associated representation: either the representation enclosed in the
/// message payload or the selected representation, as determined by the
/// message semantics. The indicated media type defines both the data
/// format and how that data is intended to be processed by a recipient,
/// within the scope of the received message semantics, after any content
/// codings indicated by Content-Encoding are decoded.
///
/// Although the `mime` crate allows the mime options to be any slice, this crate
/// forces the use of Vec. This is to make sure the same header can't have more than 1 type. If
/// this is an issue, it's possible to implement `Header` on a custom struct.
///
/// # ABNF
/// ```plain
/// Content-Type = media-type
/// ```
///
/// # Example values
/// * `text/html; charset=ISO-8859-4`
///
/// # Examples
|
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))
/// );
/// ```
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Application, SubLevel::Json,
/// vec![(Attr::Charset, Value::Utf8)]))
/// );
/// ```
(ContentType, "Content-Type") => [Mime]
test_content_type {
test_header!(
test1,
// FIXME: Should be b"text/html; charset=ISO-8859-4" but mime crate lowercases
// the whole value so parsing and formatting the value gives a different result
vec![b"text/html; charset=iso-8859-4"],
Some(HeaderField(Mime(
TopLevel::Text,
SubLevel::Html,
vec![(Attr::Charset, Value::Ext("iso-8859-4".to_owned()))]))));
}
}
impl ContentType {
/// A constructor to easily create a `Content-Type: application/json` header.
#[inline]
pub fn json() -> ContentType {
ContentType(mime!(Application/Json))
}
/// A constructor to easily create a `Content-Type: text/plain; charset=utf-8` header.
#[inline]
pub fn plaintext() -> ContentType {
ContentType(mime!(Text/Plain; Charset=Utf8))
}
/// A constructor to easily create a `Content-Type: text/html; charset=utf-8` header.
#[inline]
pub fn html() -> ContentType {
ContentType(mime!(Text/Html; Charset=Utf8))
}
/// A constructor to easily create a `Content-Type: application/www-form-url-encoded` header.
#[inline]
pub fn form_url_encoded() -> ContentType {
ContentType(mime!(Application/WwwFormUrlEncoded))
}
/// A constructor to easily create a `Content-Type: image/jpeg` header.
#[inline]
pub fn jpeg() -> ContentType {
ContentType(mime!(Image/Jpeg))
}
/// A constructor to easily create a `Content-Type: image/png` header.
#[inline]
pub fn png() -> ContentType {
ContentType(mime!(Image/Png))
}
}
bench_header!(bench, ContentType, { vec![b"application/json; charset=utf-8".to_vec()] });
|
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel};
|
random_line_split
|
content_type.rs
|
use mime::Mime;
header! {
/// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
///
/// The `Content-Type` header field indicates the media type of the
/// associated representation: either the representation enclosed in the
/// message payload or the selected representation, as determined by the
/// message semantics. The indicated media type defines both the data
/// format and how that data is intended to be processed by a recipient,
/// within the scope of the received message semantics, after any content
/// codings indicated by Content-Encoding are decoded.
///
/// Although the `mime` crate allows the mime options to be any slice, this crate
/// forces the use of Vec. This is to make sure the same header can't have more than 1 type. If
/// this is an issue, it's possible to implement `Header` on a custom struct.
///
/// # ABNF
/// ```plain
/// Content-Type = media-type
/// ```
///
/// # Example values
/// * `text/html; charset=ISO-8859-4`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))
/// );
/// ```
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Application, SubLevel::Json,
/// vec![(Attr::Charset, Value::Utf8)]))
/// );
/// ```
(ContentType, "Content-Type") => [Mime]
test_content_type {
test_header!(
test1,
// FIXME: Should be b"text/html; charset=ISO-8859-4" but mime crate lowercases
// the whole value so parsing and formatting the value gives a different result
vec![b"text/html; charset=iso-8859-4"],
Some(HeaderField(Mime(
TopLevel::Text,
SubLevel::Html,
vec![(Attr::Charset, Value::Ext("iso-8859-4".to_owned()))]))));
}
}
impl ContentType {
/// A constructor to easily create a `Content-Type: application/json` header.
#[inline]
pub fn json() -> ContentType {
ContentType(mime!(Application/Json))
}
/// A constructor to easily create a `Content-Type: text/plain; charset=utf-8` header.
#[inline]
pub fn plaintext() -> ContentType {
ContentType(mime!(Text/Plain; Charset=Utf8))
}
/// A constructor to easily create a `Content-Type: text/html; charset=utf-8` header.
#[inline]
pub fn html() -> ContentType
|
/// A constructor to easily create a `Content-Type: application/www-form-url-encoded` header.
#[inline]
pub fn form_url_encoded() -> ContentType {
ContentType(mime!(Application/WwwFormUrlEncoded))
}
/// A constructor to easily create a `Content-Type: image/jpeg` header.
#[inline]
pub fn jpeg() -> ContentType {
ContentType(mime!(Image/Jpeg))
}
/// A constructor to easily create a `Content-Type: image/png` header.
#[inline]
pub fn png() -> ContentType {
ContentType(mime!(Image/Png))
}
}
bench_header!(bench, ContentType, { vec![b"application/json; charset=utf-8".to_vec()] });
|
{
ContentType(mime!(Text/Html; Charset=Utf8))
}
|
identifier_body
|
content_type.rs
|
use mime::Mime;
header! {
/// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
///
/// The `Content-Type` header field indicates the media type of the
/// associated representation: either the representation enclosed in the
/// message payload or the selected representation, as determined by the
/// message semantics. The indicated media type defines both the data
/// format and how that data is intended to be processed by a recipient,
/// within the scope of the received message semantics, after any content
/// codings indicated by Content-Encoding are decoded.
///
/// Although the `mime` crate allows the mime options to be any slice, this crate
/// forces the use of Vec. This is to make sure the same header can't have more than 1 type. If
/// this is an issue, it's possible to implement `Header` on a custom struct.
///
/// # ABNF
/// ```plain
/// Content-Type = media-type
/// ```
///
/// # Example values
/// * `text/html; charset=ISO-8859-4`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))
/// );
/// ```
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Application, SubLevel::Json,
/// vec![(Attr::Charset, Value::Utf8)]))
/// );
/// ```
(ContentType, "Content-Type") => [Mime]
test_content_type {
test_header!(
test1,
// FIXME: Should be b"text/html; charset=ISO-8859-4" but mime crate lowercases
// the whole value so parsing and formatting the value gives a different result
vec![b"text/html; charset=iso-8859-4"],
Some(HeaderField(Mime(
TopLevel::Text,
SubLevel::Html,
vec![(Attr::Charset, Value::Ext("iso-8859-4".to_owned()))]))));
}
}
impl ContentType {
/// A constructor to easily create a `Content-Type: application/json` header.
#[inline]
pub fn json() -> ContentType {
ContentType(mime!(Application/Json))
}
/// A constructor to easily create a `Content-Type: text/plain; charset=utf-8` header.
#[inline]
pub fn
|
() -> ContentType {
ContentType(mime!(Text/Plain; Charset=Utf8))
}
/// A constructor to easily create a `Content-Type: text/html; charset=utf-8` header.
#[inline]
pub fn html() -> ContentType {
ContentType(mime!(Text/Html; Charset=Utf8))
}
/// A constructor to easily create a `Content-Type: application/www-form-url-encoded` header.
#[inline]
pub fn form_url_encoded() -> ContentType {
ContentType(mime!(Application/WwwFormUrlEncoded))
}
/// A constructor to easily create a `Content-Type: image/jpeg` header.
#[inline]
pub fn jpeg() -> ContentType {
ContentType(mime!(Image/Jpeg))
}
/// A constructor to easily create a `Content-Type: image/png` header.
#[inline]
pub fn png() -> ContentType {
ContentType(mime!(Image/Png))
}
}
bench_header!(bench, ContentType, { vec![b"application/json; charset=utf-8".to_vec()] });
|
plaintext
|
identifier_name
|
huge-largest-array.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1);
}
#[cfg(target_pointer_width = "64")]
pub fn main() {
assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1);
}
|
use std::mem::size_of;
#[cfg(target_pointer_width = "32")]
pub fn main() {
|
random_line_split
|
huge-largest-array.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem::size_of;
#[cfg(target_pointer_width = "32")]
pub fn main()
|
#[cfg(target_pointer_width = "64")]
pub fn main() {
assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1);
}
|
{
assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1);
}
|
identifier_body
|
huge-largest-array.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem::size_of;
#[cfg(target_pointer_width = "32")]
pub fn main() {
assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1);
}
#[cfg(target_pointer_width = "64")]
pub fn
|
() {
assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1);
}
|
main
|
identifier_name
|
coerce-match-calls.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that coercions are propagated through match and if expressions.
// pretty-expanded FIXME #23616
use std::boxed::Box;
pub fn
|
() {
let _: Box<[isize]> = if true { Box::new([1, 2, 3]) } else { Box::new([1]) };
let _: Box<[isize]> = match true { true => Box::new([1, 2, 3]), false => Box::new([1]) };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
|
main
|
identifier_name
|
coerce-match-calls.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that coercions are propagated through match and if expressions.
// pretty-expanded FIXME #23616
use std::boxed::Box;
pub fn main() {
let _: Box<[isize]> = if true { Box::new([1, 2, 3]) } else { Box::new([1]) };
|
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
|
let _: Box<[isize]> = match true { true => Box::new([1, 2, 3]), false => Box::new([1]) };
|
random_line_split
|
coerce-match-calls.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that coercions are propagated through match and if expressions.
// pretty-expanded FIXME #23616
use std::boxed::Box;
pub fn main()
|
{
let _: Box<[isize]> = if true { Box::new([1, 2, 3]) } else { Box::new([1]) };
let _: Box<[isize]> = match true { true => Box::new([1, 2, 3]), false => Box::new([1]) };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
|
identifier_body
|
|
orf.rs
|
// Copyright 2014-2016 Johannes Köster, Martin Larralde.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! One-way orf finder algorithm.
//!
//! Complexity: O(n).
//!
//! # Example
//!
//! ```
//! use bio::seq_analysis::orf::{Finder, Orf};
//! let start_codons = vec!(b"ATG");
//! let stop_codons = vec!(b"TGA", b"TAG", b"TAA");
//! let min_len = 50;
//! let finder = Finder::new(start_codons, stop_codons, min_len);
//!
//! let sequence = b"ACGGCTAGAAAAGGCTAGAAAA";
//!
//! for Orf{start, end, offset} in finder.find_all(sequence) {
//! let orf = &sequence[start..end];
//! //...do something with orf sequence...
//! }
//! ```
//!
//! Right now the only way to check the reverse strand for orf is to use
//! the `alphabet::dna::RevComp` struct and to check for both sequences.
//! But that's not so performance friendly, as the reverse complementation and the orf research
//! could go on at the same time.
use std::collections::VecDeque;
use std::iter;
use utils::{IntoTextIterator, TextIterator};
/// An implementation of a naive algorithm finder
pub struct Finder {
start_codons: Vec<VecDeque<u8>>,
stop_codons: Vec<VecDeque<u8>>,
min_len: usize,
}
impl Finder {
/// Create a new instance of a finder for the given start and stop codons and a particular length
pub fn new<'a>(
start_codons: Vec<&'a [u8; 3]>,
stop_codons: Vec<&'a [u8; 3]>,
min_len: usize,
) -> Self {
Finder {
start_codons: start_codons.into_iter() // Convert start_ and
.map(|x| { // stop_codons from
x.into_iter() // Vec<&[u8;3]> to
.map(|&x| x as u8) // Vec<VecDeque<u8>>
.collect::<VecDeque<u8>>() // so they can be
}) // easily compared
.collect(), // with codon built
stop_codons: stop_codons.into_iter() // from IntoTextIterator
.map(|x| { // object.
x.into_iter()
.map(|&x| x as u8)
.collect::<VecDeque<u8>>()
})
.collect(),
min_len,
}
}
/// Find all orfs in the given sequence
pub fn find_all<'a, I: IntoTextIterator<'a>>(&'a self, seq: I) -> Matches<I::IntoIter> {
Matches {
finder: self,
state: State::new(),
seq: seq.into_iter().enumerate(),
}
}
}
/// An orf representation with start and end position of said orf,
/// as well as offset of the reading frame (1,2,3) and strand location
// (current: +, reverse complementary: -).
pub struct Orf {
pub start: usize,
pub end: usize,
pub offset: i8,
}
/// The current algorithm state.
struct State {
start_pos: [Option<usize>; 3],
codon: VecDeque<u8>,
}
impl State {
/// Create new state.
pub fn new() -> Self {
State {
start_pos: [None, None, None],
codon: VecDeque::new(),
}
}
}
/// Iterator over offset, start position, end position and sequence of matched orfs.
pub struct Matches<'a, I: TextIterator<'a>> {
finder: &'a Finder,
state: State,
seq: iter::Enumerate<I>,
}
impl<'a, I: Iterator<Item = &'a u8>> Iterator for Matches<'a, I> {
type Item = Orf;
fn next(&mut self) -> Option<Orf> {
let mut result: Option<Orf> = None;
|
for (index, &nuc) in self.seq.by_ref() {
// update the codon
if self.state.codon.len() >= 3 {
self.state.codon.pop_front();
}
self.state.codon.push_back(nuc);
offset = (index + 1) % 3;
// inside orf
if self.state.start_pos[offset].is_some() {
// check if leaving orf
if self.finder.stop_codons.contains(&self.state.codon) {
// check if length is sufficient
if index + 1 - self.state.start_pos[offset].unwrap() > self.finder.min_len {
// build results
result = Some(Orf {
start: self.state.start_pos[offset].unwrap() - 2,
end: index + 1,
offset: offset as i8,
});
}
// reinitialize
self.state.start_pos[offset] = None;
}
// check if entering orf
} else if self.finder.start_codons.contains(&self.state.codon) {
self.state.start_pos[offset] = Some(index);
}
if result.is_some() {
return result;
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_orf() {
let start_codons = vec![b"ATG"];
let stop_codons = vec![b"TGA", b"TAG", b"TAA"];
let min_len = 50;
let finder = Finder::new(start_codons, stop_codons, min_len);
let sequence = b"ACGGCTAGAAAAGGCTAGAAAA";
for Orf { start, end,.. } in finder.find_all(sequence) {
let _ = &sequence[start..end];
}
}
}
|
let mut offset: usize;
|
random_line_split
|
orf.rs
|
// Copyright 2014-2016 Johannes Köster, Martin Larralde.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! One-way orf finder algorithm.
//!
//! Complexity: O(n).
//!
//! # Example
//!
//! ```
//! use bio::seq_analysis::orf::{Finder, Orf};
//! let start_codons = vec!(b"ATG");
//! let stop_codons = vec!(b"TGA", b"TAG", b"TAA");
//! let min_len = 50;
//! let finder = Finder::new(start_codons, stop_codons, min_len);
//!
//! let sequence = b"ACGGCTAGAAAAGGCTAGAAAA";
//!
//! for Orf{start, end, offset} in finder.find_all(sequence) {
//! let orf = &sequence[start..end];
//! //...do something with orf sequence...
//! }
//! ```
//!
//! Right now the only way to check the reverse strand for orf is to use
//! the `alphabet::dna::RevComp` struct and to check for both sequences.
//! But that's not so performance friendly, as the reverse complementation and the orf research
//! could go on at the same time.
use std::collections::VecDeque;
use std::iter;
use utils::{IntoTextIterator, TextIterator};
/// An implementation of a naive algorithm finder
pub struct Finder {
start_codons: Vec<VecDeque<u8>>,
stop_codons: Vec<VecDeque<u8>>,
min_len: usize,
}
impl Finder {
/// Create a new instance of a finder for the given start and stop codons and a particular length
pub fn new<'a>(
start_codons: Vec<&'a [u8; 3]>,
stop_codons: Vec<&'a [u8; 3]>,
min_len: usize,
) -> Self {
Finder {
start_codons: start_codons.into_iter() // Convert start_ and
.map(|x| { // stop_codons from
x.into_iter() // Vec<&[u8;3]> to
.map(|&x| x as u8) // Vec<VecDeque<u8>>
.collect::<VecDeque<u8>>() // so they can be
}) // easily compared
.collect(), // with codon built
stop_codons: stop_codons.into_iter() // from IntoTextIterator
.map(|x| { // object.
x.into_iter()
.map(|&x| x as u8)
.collect::<VecDeque<u8>>()
})
.collect(),
min_len,
}
}
/// Find all orfs in the given sequence
pub fn find_all<'a, I: IntoTextIterator<'a>>(&'a self, seq: I) -> Matches<I::IntoIter> {
Matches {
finder: self,
state: State::new(),
seq: seq.into_iter().enumerate(),
}
}
}
/// An orf representation with start and end position of said orf,
/// as well as offset of the reading frame (1,2,3) and strand location
// (current: +, reverse complementary: -).
pub struct Orf {
pub start: usize,
pub end: usize,
pub offset: i8,
}
/// The current algorithm state.
struct State {
start_pos: [Option<usize>; 3],
codon: VecDeque<u8>,
}
impl State {
/// Create new state.
pub fn new() -> Self {
State {
start_pos: [None, None, None],
codon: VecDeque::new(),
}
}
}
/// Iterator over offset, start position, end position and sequence of matched orfs.
pub struct Matches<'a, I: TextIterator<'a>> {
finder: &'a Finder,
state: State,
seq: iter::Enumerate<I>,
}
impl<'a, I: Iterator<Item = &'a u8>> Iterator for Matches<'a, I> {
type Item = Orf;
fn next(&mut self) -> Option<Orf> {
let mut result: Option<Orf> = None;
let mut offset: usize;
for (index, &nuc) in self.seq.by_ref() {
// update the codon
if self.state.codon.len() >= 3 {
self.state.codon.pop_front();
}
self.state.codon.push_back(nuc);
offset = (index + 1) % 3;
// inside orf
if self.state.start_pos[offset].is_some() {
|
else if self.finder.start_codons.contains(&self.state.codon) {
self.state.start_pos[offset] = Some(index);
}
if result.is_some() {
return result;
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_orf() {
let start_codons = vec![b"ATG"];
let stop_codons = vec![b"TGA", b"TAG", b"TAA"];
let min_len = 50;
let finder = Finder::new(start_codons, stop_codons, min_len);
let sequence = b"ACGGCTAGAAAAGGCTAGAAAA";
for Orf { start, end,.. } in finder.find_all(sequence) {
let _ = &sequence[start..end];
}
}
}
|
// check if leaving orf
if self.finder.stop_codons.contains(&self.state.codon) {
// check if length is sufficient
if index + 1 - self.state.start_pos[offset].unwrap() > self.finder.min_len {
// build results
result = Some(Orf {
start: self.state.start_pos[offset].unwrap() - 2,
end: index + 1,
offset: offset as i8,
});
}
// reinitialize
self.state.start_pos[offset] = None;
}
// check if entering orf
}
|
conditional_block
|
orf.rs
|
// Copyright 2014-2016 Johannes Köster, Martin Larralde.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! One-way orf finder algorithm.
//!
//! Complexity: O(n).
//!
//! # Example
//!
//! ```
//! use bio::seq_analysis::orf::{Finder, Orf};
//! let start_codons = vec!(b"ATG");
//! let stop_codons = vec!(b"TGA", b"TAG", b"TAA");
//! let min_len = 50;
//! let finder = Finder::new(start_codons, stop_codons, min_len);
//!
//! let sequence = b"ACGGCTAGAAAAGGCTAGAAAA";
//!
//! for Orf{start, end, offset} in finder.find_all(sequence) {
//! let orf = &sequence[start..end];
//! //...do something with orf sequence...
//! }
//! ```
//!
//! Right now the only way to check the reverse strand for orf is to use
//! the `alphabet::dna::RevComp` struct and to check for both sequences.
//! But that's not so performance friendly, as the reverse complementation and the orf research
//! could go on at the same time.
use std::collections::VecDeque;
use std::iter;
use utils::{IntoTextIterator, TextIterator};
/// An implementation of a naive algorithm finder
pub struct Finder {
start_codons: Vec<VecDeque<u8>>,
stop_codons: Vec<VecDeque<u8>>,
min_len: usize,
}
impl Finder {
/// Create a new instance of a finder for the given start and stop codons and a particular length
pub fn new<'a>(
start_codons: Vec<&'a [u8; 3]>,
stop_codons: Vec<&'a [u8; 3]>,
min_len: usize,
) -> Self {
Finder {
start_codons: start_codons.into_iter() // Convert start_ and
.map(|x| { // stop_codons from
x.into_iter() // Vec<&[u8;3]> to
.map(|&x| x as u8) // Vec<VecDeque<u8>>
.collect::<VecDeque<u8>>() // so they can be
}) // easily compared
.collect(), // with codon built
stop_codons: stop_codons.into_iter() // from IntoTextIterator
.map(|x| { // object.
x.into_iter()
.map(|&x| x as u8)
.collect::<VecDeque<u8>>()
})
.collect(),
min_len,
}
}
/// Find all orfs in the given sequence
pub fn find_all<'a, I: IntoTextIterator<'a>>(&'a self, seq: I) -> Matches<I::IntoIter> {
Matches {
finder: self,
state: State::new(),
seq: seq.into_iter().enumerate(),
}
}
}
/// An orf representation with start and end position of said orf,
/// as well as offset of the reading frame (1,2,3) and strand location
// (current: +, reverse complementary: -).
pub struct O
|
{
pub start: usize,
pub end: usize,
pub offset: i8,
}
/// The current algorithm state.
struct State {
start_pos: [Option<usize>; 3],
codon: VecDeque<u8>,
}
impl State {
/// Create new state.
pub fn new() -> Self {
State {
start_pos: [None, None, None],
codon: VecDeque::new(),
}
}
}
/// Iterator over offset, start position, end position and sequence of matched orfs.
pub struct Matches<'a, I: TextIterator<'a>> {
finder: &'a Finder,
state: State,
seq: iter::Enumerate<I>,
}
impl<'a, I: Iterator<Item = &'a u8>> Iterator for Matches<'a, I> {
type Item = Orf;
fn next(&mut self) -> Option<Orf> {
let mut result: Option<Orf> = None;
let mut offset: usize;
for (index, &nuc) in self.seq.by_ref() {
// update the codon
if self.state.codon.len() >= 3 {
self.state.codon.pop_front();
}
self.state.codon.push_back(nuc);
offset = (index + 1) % 3;
// inside orf
if self.state.start_pos[offset].is_some() {
// check if leaving orf
if self.finder.stop_codons.contains(&self.state.codon) {
// check if length is sufficient
if index + 1 - self.state.start_pos[offset].unwrap() > self.finder.min_len {
// build results
result = Some(Orf {
start: self.state.start_pos[offset].unwrap() - 2,
end: index + 1,
offset: offset as i8,
});
}
// reinitialize
self.state.start_pos[offset] = None;
}
// check if entering orf
} else if self.finder.start_codons.contains(&self.state.codon) {
self.state.start_pos[offset] = Some(index);
}
if result.is_some() {
return result;
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_orf() {
let start_codons = vec![b"ATG"];
let stop_codons = vec![b"TGA", b"TAG", b"TAA"];
let min_len = 50;
let finder = Finder::new(start_codons, stop_codons, min_len);
let sequence = b"ACGGCTAGAAAAGGCTAGAAAA";
for Orf { start, end,.. } in finder.find_all(sequence) {
let _ = &sequence[start..end];
}
}
}
|
rf
|
identifier_name
|
addpd.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
|
use ::Reg::*;
use ::RegScale::*;
fn addpd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 219], OperandSize::Dword)
}
fn addpd_2() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(IndirectDisplaced(EDX, 627557726, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 154, 94, 197, 103, 37], OperandSize::Dword)
}
fn addpd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 227], OperandSize::Qword)
}
fn addpd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RSI, 1752855980, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 142, 172, 117, 122, 104], OperandSize::Qword)
}
|
use ::Operand::*;
|
random_line_split
|
addpd.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn addpd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 219], OperandSize::Dword)
}
fn addpd_2()
|
fn addpd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 227], OperandSize::Qword)
}
fn addpd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RSI, 1752855980, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 142, 172, 117, 122, 104], OperandSize::Qword)
}
|
{
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(IndirectDisplaced(EDX, 627557726, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 154, 94, 197, 103, 37], OperandSize::Dword)
}
|
identifier_body
|
addpd.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn addpd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 219], OperandSize::Dword)
}
fn
|
() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(IndirectDisplaced(EDX, 627557726, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 154, 94, 197, 103, 37], OperandSize::Dword)
}
fn addpd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 227], OperandSize::Qword)
}
fn addpd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RSI, 1752855980, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 142, 172, 117, 122, 104], OperandSize::Qword)
}
|
addpd_2
|
identifier_name
|
output_buffer.rs
|
use sys::*;
use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions.
pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}
impl OutputBuffer for [u8] {
fn buf_len<T>(&self) -> T
where
T: BufferLength,
{
T::from_usize(min(self.len(), T::max_value()))
}
fn mut_buf_ptr(&mut self) -> *mut u8 {
if self.is_empty() {
null_mut()
} else {
self.as_mut_ptr()
}
}
}
pub trait BufferLength {
fn max_value() -> usize;
fn from_usize(len: usize) -> Self;
}
impl BufferLength for SQLSMALLINT {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self
|
}
impl BufferLength for SQLLEN {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
|
{
len as Self
}
|
identifier_body
|
output_buffer.rs
|
use sys::*;
|
pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}
impl OutputBuffer for [u8] {
fn buf_len<T>(&self) -> T
where
T: BufferLength,
{
T::from_usize(min(self.len(), T::max_value()))
}
fn mut_buf_ptr(&mut self) -> *mut u8 {
if self.is_empty() {
null_mut()
} else {
self.as_mut_ptr()
}
}
}
pub trait BufferLength {
fn max_value() -> usize;
fn from_usize(len: usize) -> Self;
}
impl BufferLength for SQLSMALLINT {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
impl BufferLength for SQLLEN {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
|
use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions.
|
random_line_split
|
output_buffer.rs
|
use sys::*;
use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions.
pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}
impl OutputBuffer for [u8] {
fn buf_len<T>(&self) -> T
where
T: BufferLength,
{
T::from_usize(min(self.len(), T::max_value()))
}
fn
|
(&mut self) -> *mut u8 {
if self.is_empty() {
null_mut()
} else {
self.as_mut_ptr()
}
}
}
pub trait BufferLength {
fn max_value() -> usize;
fn from_usize(len: usize) -> Self;
}
impl BufferLength for SQLSMALLINT {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
impl BufferLength for SQLLEN {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
|
mut_buf_ptr
|
identifier_name
|
output_buffer.rs
|
use sys::*;
use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions.
pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}
impl OutputBuffer for [u8] {
fn buf_len<T>(&self) -> T
where
T: BufferLength,
{
T::from_usize(min(self.len(), T::max_value()))
}
fn mut_buf_ptr(&mut self) -> *mut u8 {
if self.is_empty()
|
else {
self.as_mut_ptr()
}
}
}
pub trait BufferLength {
fn max_value() -> usize;
fn from_usize(len: usize) -> Self;
}
impl BufferLength for SQLSMALLINT {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
impl BufferLength for SQLLEN {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
|
{
null_mut()
}
|
conditional_block
|
auto_args.rs
|
// Copyright 2015, 2016 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/>.
//! Automatically serialize and deserialize parameters around a strongly-typed function.
// because we reuse the type names as idents in the macros as a dirty hack to
// work around `concat_idents!` being unstable.
#![allow(non_snake_case)]
use super::errors;
use jsonrpc_core::{Error, Params, Value, from_params, to_value};
use serde::{Serialize, Deserialize};
/// Auto-generates an RPC trait from trait definition.
///
/// This just copies out all the methods, docs, and adds another
/// function `to_delegate` which will automatically wrap each strongly-typed
/// function in a wrapper which handles parameter and output type serialization.
///
/// RPC functions may come in a couple forms: async and synchronous.
/// These are parsed with the custom `#[rpc]` attribute, which must follow
/// documentation.
///
/// ## The #[rpc] attribute
///
/// Valid forms:
/// - `#[rpc(name = "name_here")]` (a synchronous rpc function which should be bound to the given name)
/// - `#[rpc(async, name = "name_here")]` (an async rpc function which should be bound to the given name)
///
/// Synchronous function format:
/// `fn foo(&self, Param1, Param2, Param3) -> Out`.
///
/// Asynchronous RPC functions must come in this form:
/// `fn foo(&self, Param1, Param2, Param3, Ready<Out>);
///
/// Anything else will be rejected by the code generator.
macro_rules! build_rpc_trait {
// entry-point. todo: make another for traits w/ bounds.
(
$(#[$t_attr: meta])*
pub trait $name: ident {
$(
$( #[doc=$m_doc:expr] )*
#[ rpc( $($t:tt)* ) ]
fn $m_name: ident ( $($p: tt)* ) $( -> Result<$out: ty, Error> )* ;
)*
}
) => {
$(#[$t_attr])*
pub trait $name: Sized + Send + Sync +'static {
$(
$(#[doc=$m_doc])*
fn $m_name ( $($p)* ) $( -> Result<$out, Error> )* ;
)*
/// Transform this into an `IoDelegate`, automatically wrapping
/// the parameters.
fn to_delegate(self) -> ::jsonrpc_core::IoDelegate<Self> {
let mut del = ::jsonrpc_core::IoDelegate::new(self.into());
$(
build_rpc_trait!(WRAP del =>
( $($t)* )
fn $m_name ( $($p)* ) $( -> Result<$out, Error> )*
);
)*
del
}
}
};
( WRAP $del: expr =>
(name = $name: expr)
fn $method: ident (&self $(, $param: ty)*) -> Result<$out: ty, Error>
) => {
$del.add_method($name, move |base, params| {
(Self::$method as fn(&_ $(, $param)*) -> Result<$out, Error>).wrap_rpc(base, params)
})
};
( WRAP $del: expr =>
(async, name = $name: expr)
fn $method: ident (&self, Ready<$out: ty> $(, $param: ty)*)
) => {
$del.add_async_method($name, move |base, params, ready| {
(Self::$method as fn(&_, Ready<$out> $(, $param)*)).wrap_rpc(base, params, ready)
})
};
}
/// A wrapper type without an implementation of `Deserialize`
/// which allows a special implementation of `Wrap` for functions
/// that take a trailing default parameter.
pub struct Trailing<T: Default + Deserialize>(pub T);
/// A wrapper type for `jsonrpc_core`'s weakly-typed `Ready` struct.
pub struct Ready<T: Serialize> {
inner: ::jsonrpc_core::Ready,
_marker: ::std::marker::PhantomData<T>,
}
impl<T: Serialize> From<::jsonrpc_core::Ready> for Ready<T> {
fn from(ready: ::jsonrpc_core::Ready) -> Self {
Ready { inner: ready, _marker: ::std::marker::PhantomData }
}
}
impl<T: Serialize> Ready<T> {
/// Respond withthe asynchronous result.
pub fn ready(self, result: Result<T, Error>) {
self.inner.ready(result.map(to_value))
}
}
/// Wrapper trait for synchronous RPC functions.
pub trait Wrap<B: Send + Sync +'static> {
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error>;
}
/// Wrapper trait for asynchronous RPC functions.
pub trait WrapAsync<B: Send + Sync +'static> {
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready);
}
// special impl for no parameters.
impl<B, OUT> Wrap<B> for fn(&B) -> Result<OUT, Error>
where B: Send + Sync +'static, OUT: Serialize
{
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error> {
::v1::helpers::params::expect_no_params(params)
.and_then(|()| (self)(base))
.map(to_value)
}
}
impl<B, OUT> WrapAsync<B> for fn(&B, Ready<OUT>)
where B: Send + Sync +'static, OUT: Serialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready) {
match ::v1::helpers::params::expect_no_params(params) {
Ok(()) => (self)(base, ready.into()),
Err(e) => ready.ready(Err(e)),
}
}
}
// creates a wrapper implementation which deserializes the parameters,
// calls the function with concrete type, and serializes the output.
macro_rules! wrap {
($($x: ident),+) => {
// synchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
> Wrap<BASE> for fn(&BASE, $($x,)+) -> Result<OUT, Error> {
fn wrap_rpc(&self, base: &BASE, params: Params) -> Result<Value, Error> {
from_params::<($($x,)+)>(params).and_then(|($($x,)+)| {
(self)(base, $($x,)+)
}).map(to_value)
}
}
// asynchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
> WrapAsync<BASE> for fn(&BASE, Ready<OUT>, $($x,)+ ) {
fn wrap_rpc(&self, base: &BASE, params: Params, ready: ::jsonrpc_core::Ready) {
match from_params::<($($x,)+)>(params) {
Ok(($($x,)+)) => (self)(base, ready.into(), $($x,)+),
Err(e) => ready.ready(Err(e)),
}
}
}
}
}
// special impl for no parameters other than block parameter.
impl<B, OUT, T> Wrap<B> for fn(&B, Trailing<T>) -> Result<OUT, Error>
where B: Send + Sync +'static, OUT: Serialize, T: Default + Deserialize
{
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error> {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return Err(errors::invalid_params("not an array", "")),
};
let (id,) = match len {
0 => (T::default(),),
1 => try!(from_params::<(T,)>(params)),
_ => return Err(Error::invalid_params()),
};
(self)(base, Trailing(id)).map(to_value)
}
}
impl<B, OUT, T> WrapAsync<B> for fn(&B, Ready<OUT>, Trailing<T>)
where B: Send + Sync +'static, OUT: Serialize, T: Default + Deserialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready) {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return ready.ready(Err(errors::invalid_params("not an array", ""))),
};
let id = match len {
0 => Ok((T::default(),)),
1 => from_params::<(T,)>(params),
_ => Err(Error::invalid_params()),
};
match id {
Ok((id,)) => (self)(base, ready.into(), Trailing(id)),
Err(e) => ready.ready(Err(e)),
}
}
}
// similar to `wrap!`, but handles a single default trailing parameter
// accepts an additional argument indicating the number of non-trailing parameters.
macro_rules! wrap_with_trailing {
($num: expr, $($x: ident),+) => {
// synchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
TRAILING: Default + Deserialize,
> Wrap<BASE> for fn(&BASE, $($x,)+ Trailing<TRAILING>) -> Result<OUT, Error> {
fn wrap_rpc(&self, base: &BASE, params: Params) -> Result<Value, Error> {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return Err(errors::invalid_params("not an array", "")),
};
let params = match len - $num {
0 => from_params::<($($x,)+)>(params)
.map(|($($x,)+)| ($($x,)+ TRAILING::default())),
1 => from_params::<($($x,)+ TRAILING)>(params)
.map(|($($x,)+ id)| ($($x,)+ id)),
_ => Err(Error::invalid_params()),
};
let ($($x,)+ id) = try!(params);
(self)(base, $($x,)+ Trailing(id)).map(to_value)
}
}
// asynchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
TRAILING: Default + Deserialize,
> WrapAsync<BASE> for fn(&BASE, Ready<OUT>, $($x,)+ Trailing<TRAILING>) {
fn wrap_rpc(&self, base: &BASE, params: Params, ready: ::jsonrpc_core::Ready) {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return ready.ready(Err(errors::invalid_params("not an array", ""))),
};
let params = match len - $num {
0 => from_params::<($($x,)+)>(params)
|
};
match params {
Ok(($($x,)+ id)) => (self)(base, ready.into(), $($x,)+ Trailing(id)),
Err(e) => ready.ready(Err(e))
}
}
}
}
}
wrap!(A, B, C, D, E);
wrap!(A, B, C, D);
wrap!(A, B, C);
wrap!(A, B);
wrap!(A);
wrap_with_trailing!(5, A, B, C, D, E);
wrap_with_trailing!(4, A, B, C, D);
wrap_with_trailing!(3, A, B, C);
wrap_with_trailing!(2, A, B);
wrap_with_trailing!(1, A);
|
.map(|($($x,)+)| ($($x,)+ TRAILING::default())),
1 => from_params::<($($x,)+ TRAILING)>(params)
.map(|($($x,)+ id)| ($($x,)+ id)),
_ => Err(Error::invalid_params()),
|
random_line_split
|
auto_args.rs
|
// Copyright 2015, 2016 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/>.
//! Automatically serialize and deserialize parameters around a strongly-typed function.
// because we reuse the type names as idents in the macros as a dirty hack to
// work around `concat_idents!` being unstable.
#![allow(non_snake_case)]
use super::errors;
use jsonrpc_core::{Error, Params, Value, from_params, to_value};
use serde::{Serialize, Deserialize};
/// Auto-generates an RPC trait from trait definition.
///
/// This just copies out all the methods, docs, and adds another
/// function `to_delegate` which will automatically wrap each strongly-typed
/// function in a wrapper which handles parameter and output type serialization.
///
/// RPC functions may come in a couple forms: async and synchronous.
/// These are parsed with the custom `#[rpc]` attribute, which must follow
/// documentation.
///
/// ## The #[rpc] attribute
///
/// Valid forms:
/// - `#[rpc(name = "name_here")]` (a synchronous rpc function which should be bound to the given name)
/// - `#[rpc(async, name = "name_here")]` (an async rpc function which should be bound to the given name)
///
/// Synchronous function format:
/// `fn foo(&self, Param1, Param2, Param3) -> Out`.
///
/// Asynchronous RPC functions must come in this form:
/// `fn foo(&self, Param1, Param2, Param3, Ready<Out>);
///
/// Anything else will be rejected by the code generator.
macro_rules! build_rpc_trait {
// entry-point. todo: make another for traits w/ bounds.
(
$(#[$t_attr: meta])*
pub trait $name: ident {
$(
$( #[doc=$m_doc:expr] )*
#[ rpc( $($t:tt)* ) ]
fn $m_name: ident ( $($p: tt)* ) $( -> Result<$out: ty, Error> )* ;
)*
}
) => {
$(#[$t_attr])*
pub trait $name: Sized + Send + Sync +'static {
$(
$(#[doc=$m_doc])*
fn $m_name ( $($p)* ) $( -> Result<$out, Error> )* ;
)*
/// Transform this into an `IoDelegate`, automatically wrapping
/// the parameters.
fn to_delegate(self) -> ::jsonrpc_core::IoDelegate<Self> {
let mut del = ::jsonrpc_core::IoDelegate::new(self.into());
$(
build_rpc_trait!(WRAP del =>
( $($t)* )
fn $m_name ( $($p)* ) $( -> Result<$out, Error> )*
);
)*
del
}
}
};
( WRAP $del: expr =>
(name = $name: expr)
fn $method: ident (&self $(, $param: ty)*) -> Result<$out: ty, Error>
) => {
$del.add_method($name, move |base, params| {
(Self::$method as fn(&_ $(, $param)*) -> Result<$out, Error>).wrap_rpc(base, params)
})
};
( WRAP $del: expr =>
(async, name = $name: expr)
fn $method: ident (&self, Ready<$out: ty> $(, $param: ty)*)
) => {
$del.add_async_method($name, move |base, params, ready| {
(Self::$method as fn(&_, Ready<$out> $(, $param)*)).wrap_rpc(base, params, ready)
})
};
}
/// A wrapper type without an implementation of `Deserialize`
/// which allows a special implementation of `Wrap` for functions
/// that take a trailing default parameter.
pub struct Trailing<T: Default + Deserialize>(pub T);
/// A wrapper type for `jsonrpc_core`'s weakly-typed `Ready` struct.
pub struct Ready<T: Serialize> {
inner: ::jsonrpc_core::Ready,
_marker: ::std::marker::PhantomData<T>,
}
impl<T: Serialize> From<::jsonrpc_core::Ready> for Ready<T> {
fn from(ready: ::jsonrpc_core::Ready) -> Self {
Ready { inner: ready, _marker: ::std::marker::PhantomData }
}
}
impl<T: Serialize> Ready<T> {
/// Respond withthe asynchronous result.
pub fn ready(self, result: Result<T, Error>) {
self.inner.ready(result.map(to_value))
}
}
/// Wrapper trait for synchronous RPC functions.
pub trait Wrap<B: Send + Sync +'static> {
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error>;
}
/// Wrapper trait for asynchronous RPC functions.
pub trait WrapAsync<B: Send + Sync +'static> {
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready);
}
// special impl for no parameters.
impl<B, OUT> Wrap<B> for fn(&B) -> Result<OUT, Error>
where B: Send + Sync +'static, OUT: Serialize
{
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error> {
::v1::helpers::params::expect_no_params(params)
.and_then(|()| (self)(base))
.map(to_value)
}
}
impl<B, OUT> WrapAsync<B> for fn(&B, Ready<OUT>)
where B: Send + Sync +'static, OUT: Serialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready) {
match ::v1::helpers::params::expect_no_params(params) {
Ok(()) => (self)(base, ready.into()),
Err(e) => ready.ready(Err(e)),
}
}
}
// creates a wrapper implementation which deserializes the parameters,
// calls the function with concrete type, and serializes the output.
macro_rules! wrap {
($($x: ident),+) => {
// synchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
> Wrap<BASE> for fn(&BASE, $($x,)+) -> Result<OUT, Error> {
fn wrap_rpc(&self, base: &BASE, params: Params) -> Result<Value, Error> {
from_params::<($($x,)+)>(params).and_then(|($($x,)+)| {
(self)(base, $($x,)+)
}).map(to_value)
}
}
// asynchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
> WrapAsync<BASE> for fn(&BASE, Ready<OUT>, $($x,)+ ) {
fn wrap_rpc(&self, base: &BASE, params: Params, ready: ::jsonrpc_core::Ready) {
match from_params::<($($x,)+)>(params) {
Ok(($($x,)+)) => (self)(base, ready.into(), $($x,)+),
Err(e) => ready.ready(Err(e)),
}
}
}
}
}
// special impl for no parameters other than block parameter.
impl<B, OUT, T> Wrap<B> for fn(&B, Trailing<T>) -> Result<OUT, Error>
where B: Send + Sync +'static, OUT: Serialize, T: Default + Deserialize
{
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error>
|
}
impl<B, OUT, T> WrapAsync<B> for fn(&B, Ready<OUT>, Trailing<T>)
where B: Send + Sync +'static, OUT: Serialize, T: Default + Deserialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready) {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return ready.ready(Err(errors::invalid_params("not an array", ""))),
};
let id = match len {
0 => Ok((T::default(),)),
1 => from_params::<(T,)>(params),
_ => Err(Error::invalid_params()),
};
match id {
Ok((id,)) => (self)(base, ready.into(), Trailing(id)),
Err(e) => ready.ready(Err(e)),
}
}
}
// similar to `wrap!`, but handles a single default trailing parameter
// accepts an additional argument indicating the number of non-trailing parameters.
macro_rules! wrap_with_trailing {
($num: expr, $($x: ident),+) => {
// synchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
TRAILING: Default + Deserialize,
> Wrap<BASE> for fn(&BASE, $($x,)+ Trailing<TRAILING>) -> Result<OUT, Error> {
fn wrap_rpc(&self, base: &BASE, params: Params) -> Result<Value, Error> {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return Err(errors::invalid_params("not an array", "")),
};
let params = match len - $num {
0 => from_params::<($($x,)+)>(params)
.map(|($($x,)+)| ($($x,)+ TRAILING::default())),
1 => from_params::<($($x,)+ TRAILING)>(params)
.map(|($($x,)+ id)| ($($x,)+ id)),
_ => Err(Error::invalid_params()),
};
let ($($x,)+ id) = try!(params);
(self)(base, $($x,)+ Trailing(id)).map(to_value)
}
}
// asynchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
TRAILING: Default + Deserialize,
> WrapAsync<BASE> for fn(&BASE, Ready<OUT>, $($x,)+ Trailing<TRAILING>) {
fn wrap_rpc(&self, base: &BASE, params: Params, ready: ::jsonrpc_core::Ready) {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return ready.ready(Err(errors::invalid_params("not an array", ""))),
};
let params = match len - $num {
0 => from_params::<($($x,)+)>(params)
.map(|($($x,)+)| ($($x,)+ TRAILING::default())),
1 => from_params::<($($x,)+ TRAILING)>(params)
.map(|($($x,)+ id)| ($($x,)+ id)),
_ => Err(Error::invalid_params()),
};
match params {
Ok(($($x,)+ id)) => (self)(base, ready.into(), $($x,)+ Trailing(id)),
Err(e) => ready.ready(Err(e))
}
}
}
}
}
wrap!(A, B, C, D, E);
wrap!(A, B, C, D);
wrap!(A, B, C);
wrap!(A, B);
wrap!(A);
wrap_with_trailing!(5, A, B, C, D, E);
wrap_with_trailing!(4, A, B, C, D);
wrap_with_trailing!(3, A, B, C);
wrap_with_trailing!(2, A, B);
wrap_with_trailing!(1, A);
|
{
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return Err(errors::invalid_params("not an array", "")),
};
let (id,) = match len {
0 => (T::default(),),
1 => try!(from_params::<(T,)>(params)),
_ => return Err(Error::invalid_params()),
};
(self)(base, Trailing(id)).map(to_value)
}
|
identifier_body
|
auto_args.rs
|
// Copyright 2015, 2016 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/>.
//! Automatically serialize and deserialize parameters around a strongly-typed function.
// because we reuse the type names as idents in the macros as a dirty hack to
// work around `concat_idents!` being unstable.
#![allow(non_snake_case)]
use super::errors;
use jsonrpc_core::{Error, Params, Value, from_params, to_value};
use serde::{Serialize, Deserialize};
/// Auto-generates an RPC trait from trait definition.
///
/// This just copies out all the methods, docs, and adds another
/// function `to_delegate` which will automatically wrap each strongly-typed
/// function in a wrapper which handles parameter and output type serialization.
///
/// RPC functions may come in a couple forms: async and synchronous.
/// These are parsed with the custom `#[rpc]` attribute, which must follow
/// documentation.
///
/// ## The #[rpc] attribute
///
/// Valid forms:
/// - `#[rpc(name = "name_here")]` (a synchronous rpc function which should be bound to the given name)
/// - `#[rpc(async, name = "name_here")]` (an async rpc function which should be bound to the given name)
///
/// Synchronous function format:
/// `fn foo(&self, Param1, Param2, Param3) -> Out`.
///
/// Asynchronous RPC functions must come in this form:
/// `fn foo(&self, Param1, Param2, Param3, Ready<Out>);
///
/// Anything else will be rejected by the code generator.
macro_rules! build_rpc_trait {
// entry-point. todo: make another for traits w/ bounds.
(
$(#[$t_attr: meta])*
pub trait $name: ident {
$(
$( #[doc=$m_doc:expr] )*
#[ rpc( $($t:tt)* ) ]
fn $m_name: ident ( $($p: tt)* ) $( -> Result<$out: ty, Error> )* ;
)*
}
) => {
$(#[$t_attr])*
pub trait $name: Sized + Send + Sync +'static {
$(
$(#[doc=$m_doc])*
fn $m_name ( $($p)* ) $( -> Result<$out, Error> )* ;
)*
/// Transform this into an `IoDelegate`, automatically wrapping
/// the parameters.
fn to_delegate(self) -> ::jsonrpc_core::IoDelegate<Self> {
let mut del = ::jsonrpc_core::IoDelegate::new(self.into());
$(
build_rpc_trait!(WRAP del =>
( $($t)* )
fn $m_name ( $($p)* ) $( -> Result<$out, Error> )*
);
)*
del
}
}
};
( WRAP $del: expr =>
(name = $name: expr)
fn $method: ident (&self $(, $param: ty)*) -> Result<$out: ty, Error>
) => {
$del.add_method($name, move |base, params| {
(Self::$method as fn(&_ $(, $param)*) -> Result<$out, Error>).wrap_rpc(base, params)
})
};
( WRAP $del: expr =>
(async, name = $name: expr)
fn $method: ident (&self, Ready<$out: ty> $(, $param: ty)*)
) => {
$del.add_async_method($name, move |base, params, ready| {
(Self::$method as fn(&_, Ready<$out> $(, $param)*)).wrap_rpc(base, params, ready)
})
};
}
/// A wrapper type without an implementation of `Deserialize`
/// which allows a special implementation of `Wrap` for functions
/// that take a trailing default parameter.
pub struct Trailing<T: Default + Deserialize>(pub T);
/// A wrapper type for `jsonrpc_core`'s weakly-typed `Ready` struct.
pub struct Ready<T: Serialize> {
inner: ::jsonrpc_core::Ready,
_marker: ::std::marker::PhantomData<T>,
}
impl<T: Serialize> From<::jsonrpc_core::Ready> for Ready<T> {
fn from(ready: ::jsonrpc_core::Ready) -> Self {
Ready { inner: ready, _marker: ::std::marker::PhantomData }
}
}
impl<T: Serialize> Ready<T> {
/// Respond withthe asynchronous result.
pub fn ready(self, result: Result<T, Error>) {
self.inner.ready(result.map(to_value))
}
}
/// Wrapper trait for synchronous RPC functions.
pub trait Wrap<B: Send + Sync +'static> {
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error>;
}
/// Wrapper trait for asynchronous RPC functions.
pub trait WrapAsync<B: Send + Sync +'static> {
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready);
}
// special impl for no parameters.
impl<B, OUT> Wrap<B> for fn(&B) -> Result<OUT, Error>
where B: Send + Sync +'static, OUT: Serialize
{
fn
|
(&self, base: &B, params: Params) -> Result<Value, Error> {
::v1::helpers::params::expect_no_params(params)
.and_then(|()| (self)(base))
.map(to_value)
}
}
impl<B, OUT> WrapAsync<B> for fn(&B, Ready<OUT>)
where B: Send + Sync +'static, OUT: Serialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready) {
match ::v1::helpers::params::expect_no_params(params) {
Ok(()) => (self)(base, ready.into()),
Err(e) => ready.ready(Err(e)),
}
}
}
// creates a wrapper implementation which deserializes the parameters,
// calls the function with concrete type, and serializes the output.
macro_rules! wrap {
($($x: ident),+) => {
// synchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
> Wrap<BASE> for fn(&BASE, $($x,)+) -> Result<OUT, Error> {
fn wrap_rpc(&self, base: &BASE, params: Params) -> Result<Value, Error> {
from_params::<($($x,)+)>(params).and_then(|($($x,)+)| {
(self)(base, $($x,)+)
}).map(to_value)
}
}
// asynchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
> WrapAsync<BASE> for fn(&BASE, Ready<OUT>, $($x,)+ ) {
fn wrap_rpc(&self, base: &BASE, params: Params, ready: ::jsonrpc_core::Ready) {
match from_params::<($($x,)+)>(params) {
Ok(($($x,)+)) => (self)(base, ready.into(), $($x,)+),
Err(e) => ready.ready(Err(e)),
}
}
}
}
}
// special impl for no parameters other than block parameter.
impl<B, OUT, T> Wrap<B> for fn(&B, Trailing<T>) -> Result<OUT, Error>
where B: Send + Sync +'static, OUT: Serialize, T: Default + Deserialize
{
fn wrap_rpc(&self, base: &B, params: Params) -> Result<Value, Error> {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return Err(errors::invalid_params("not an array", "")),
};
let (id,) = match len {
0 => (T::default(),),
1 => try!(from_params::<(T,)>(params)),
_ => return Err(Error::invalid_params()),
};
(self)(base, Trailing(id)).map(to_value)
}
}
impl<B, OUT, T> WrapAsync<B> for fn(&B, Ready<OUT>, Trailing<T>)
where B: Send + Sync +'static, OUT: Serialize, T: Default + Deserialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready) {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return ready.ready(Err(errors::invalid_params("not an array", ""))),
};
let id = match len {
0 => Ok((T::default(),)),
1 => from_params::<(T,)>(params),
_ => Err(Error::invalid_params()),
};
match id {
Ok((id,)) => (self)(base, ready.into(), Trailing(id)),
Err(e) => ready.ready(Err(e)),
}
}
}
// similar to `wrap!`, but handles a single default trailing parameter
// accepts an additional argument indicating the number of non-trailing parameters.
macro_rules! wrap_with_trailing {
($num: expr, $($x: ident),+) => {
// synchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
TRAILING: Default + Deserialize,
> Wrap<BASE> for fn(&BASE, $($x,)+ Trailing<TRAILING>) -> Result<OUT, Error> {
fn wrap_rpc(&self, base: &BASE, params: Params) -> Result<Value, Error> {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return Err(errors::invalid_params("not an array", "")),
};
let params = match len - $num {
0 => from_params::<($($x,)+)>(params)
.map(|($($x,)+)| ($($x,)+ TRAILING::default())),
1 => from_params::<($($x,)+ TRAILING)>(params)
.map(|($($x,)+ id)| ($($x,)+ id)),
_ => Err(Error::invalid_params()),
};
let ($($x,)+ id) = try!(params);
(self)(base, $($x,)+ Trailing(id)).map(to_value)
}
}
// asynchronous implementation
impl <
BASE: Send + Sync +'static,
OUT: Serialize,
$($x: Deserialize,)+
TRAILING: Default + Deserialize,
> WrapAsync<BASE> for fn(&BASE, Ready<OUT>, $($x,)+ Trailing<TRAILING>) {
fn wrap_rpc(&self, base: &BASE, params: Params, ready: ::jsonrpc_core::Ready) {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return ready.ready(Err(errors::invalid_params("not an array", ""))),
};
let params = match len - $num {
0 => from_params::<($($x,)+)>(params)
.map(|($($x,)+)| ($($x,)+ TRAILING::default())),
1 => from_params::<($($x,)+ TRAILING)>(params)
.map(|($($x,)+ id)| ($($x,)+ id)),
_ => Err(Error::invalid_params()),
};
match params {
Ok(($($x,)+ id)) => (self)(base, ready.into(), $($x,)+ Trailing(id)),
Err(e) => ready.ready(Err(e))
}
}
}
}
}
wrap!(A, B, C, D, E);
wrap!(A, B, C, D);
wrap!(A, B, C);
wrap!(A, B);
wrap!(A);
wrap_with_trailing!(5, A, B, C, D, E);
wrap_with_trailing!(4, A, B, C, D);
wrap_with_trailing!(3, A, B, C);
wrap_with_trailing!(2, A, B);
wrap_with_trailing!(1, A);
|
wrap_rpc
|
identifier_name
|
indent.rs
|
//! Indentation functions
use remacs_macros::lisp_fn;
use remacs_sys;
use lisp::LispObject;
use lisp::defsubr;
/// Return the horizontal position of point.
/// Beginning of line is column 0.
/// This is calculated by adding together the widths of all the
/// displayed representations of the character between the start of
/// the previous line and point (e.g., control characters will have a
/// width of 2 or 4, tabs will have a variable width). Ignores finite
|
/// end of line when `selective-display' is t. Text that has an
/// invisible property is considered as having width 0, unless
/// `buffer-invisibility-spec' specifies that it is replaced by an
/// ellipsis.
#[lisp_fn]
pub fn current_column() -> LispObject {
LispObject::from_natnum(unsafe { remacs_sys::current_column() })
}
include!(concat!(env!("OUT_DIR"), "/indent_exports.rs"));
|
/// width of frame, which means that this function may return values
/// greater than (frame-width). Whether the line is visible (if
/// `selective-display' is t) has no effect; however, ^M is treated as
|
random_line_split
|
indent.rs
|
//! Indentation functions
use remacs_macros::lisp_fn;
use remacs_sys;
use lisp::LispObject;
use lisp::defsubr;
/// Return the horizontal position of point.
/// Beginning of line is column 0.
/// This is calculated by adding together the widths of all the
/// displayed representations of the character between the start of
/// the previous line and point (e.g., control characters will have a
/// width of 2 or 4, tabs will have a variable width). Ignores finite
/// width of frame, which means that this function may return values
/// greater than (frame-width). Whether the line is visible (if
/// `selective-display' is t) has no effect; however, ^M is treated as
/// end of line when `selective-display' is t. Text that has an
/// invisible property is considered as having width 0, unless
/// `buffer-invisibility-spec' specifies that it is replaced by an
/// ellipsis.
#[lisp_fn]
pub fn current_column() -> LispObject
|
include!(concat!(env!("OUT_DIR"), "/indent_exports.rs"));
|
{
LispObject::from_natnum(unsafe { remacs_sys::current_column() })
}
|
identifier_body
|
indent.rs
|
//! Indentation functions
use remacs_macros::lisp_fn;
use remacs_sys;
use lisp::LispObject;
use lisp::defsubr;
/// Return the horizontal position of point.
/// Beginning of line is column 0.
/// This is calculated by adding together the widths of all the
/// displayed representations of the character between the start of
/// the previous line and point (e.g., control characters will have a
/// width of 2 or 4, tabs will have a variable width). Ignores finite
/// width of frame, which means that this function may return values
/// greater than (frame-width). Whether the line is visible (if
/// `selective-display' is t) has no effect; however, ^M is treated as
/// end of line when `selective-display' is t. Text that has an
/// invisible property is considered as having width 0, unless
/// `buffer-invisibility-spec' specifies that it is replaced by an
/// ellipsis.
#[lisp_fn]
pub fn
|
() -> LispObject {
LispObject::from_natnum(unsafe { remacs_sys::current_column() })
}
include!(concat!(env!("OUT_DIR"), "/indent_exports.rs"));
|
current_column
|
identifier_name
|
glue.rs
|
//!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value) {
let layout = bx.layout_of(t);
debug!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
if!layout.is_unsized() {
let size = bx.const_usize(layout.size.bytes());
let align = bx.const_usize(layout.align.abi.bytes());
return (size, align);
}
match t.kind() {
ty::Dynamic(..) => {
// load size/align from vtable
let vtable = info.unwrap();
(
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE)
.get_usize(bx, vtable),
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN)
.get_usize(bx, vtable),
)
}
ty::Slice(_) | ty::Str => {
let unit = layout.field(bx, 0);
// The info in this case is the length of the str, so the size is that
// times the unit size.
(
bx.mul(info.unwrap(), bx.const_usize(unit.size.bytes())),
bx.const_usize(unit.align.abi.bytes()),
)
}
_ => {
// First get the size of all statically known fields.
// Don't use size_of because it also rounds up to alignment, which we
// want to avoid, as the unsized field's alignment could be smaller.
assert!(!t.is_simd());
debug!("DST {} layout: {:?}", t, layout);
let i = layout.fields.count() - 1;
let sized_size = layout.fields.offset(i).bytes();
let sized_align = layout.align.abi.bytes();
debug!("DST {} statically sized prefix size: {} align: {}", t, sized_size, sized_align);
let sized_size = bx.const_usize(sized_size);
let sized_align = bx.const_usize(sized_align);
// Recurse to get the size of the dynamically sized field (must be
// the last field).
let field_ty = layout.field(bx, i).ty;
let (unsized_size, mut unsized_align) = size_and_align_of_dst(bx, field_ty, info);
// FIXME (#26403, #27023): We should be adding padding
// to `sized_size` (to accommodate the `unsized_align`
// required of the unsized field that follows) before
// summing it with `sized_size`. (Note that since #26403
// is unfixed, we do not yet add the necessary padding
// here. But this is where the add would go.)
// Return the sum of sizes and max of aligns.
let size = bx.add(sized_size, unsized_size);
// Packed types ignore the alignment of their fields.
if let ty::Adt(def, _) = t.kind()
|
// Choose max of two known alignments (combined value must
// be aligned according to more restrictive of the two).
let align = match (
bx.const_to_opt_u128(sized_align, false),
bx.const_to_opt_u128(unsized_align, false),
) {
(Some(sized_align), Some(unsized_align)) => {
// If both alignments are constant, (the sized_align should always be), then
// pick the correct alignment statically.
bx.const_usize(std::cmp::max(sized_align, unsized_align) as u64)
}
_ => {
let cmp = bx.icmp(IntPredicate::IntUGT, sized_align, unsized_align);
bx.select(cmp, sized_align, unsized_align)
}
};
// Issue #27023: must add any necessary padding to `size`
// (to make it a multiple of `align`) before returning it.
//
// Namely, the returned size should be, in C notation:
//
// `size + ((size & (align-1))? align : 0)`
//
// emulated via the semi-standard fast bit trick:
//
// `(size + (align-1)) & -align`
let one = bx.const_usize(1);
let addend = bx.sub(align, one);
let add = bx.add(size, addend);
let neg = bx.neg(align);
let size = bx.and(add, neg);
(size, align)
}
}
}
|
{
if def.repr.packed() {
unsized_align = sized_align;
}
}
|
conditional_block
|
glue.rs
|
//!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value) {
let layout = bx.layout_of(t);
debug!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
if!layout.is_unsized() {
let size = bx.const_usize(layout.size.bytes());
let align = bx.const_usize(layout.align.abi.bytes());
return (size, align);
}
match t.kind() {
ty::Dynamic(..) => {
// load size/align from vtable
let vtable = info.unwrap();
(
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE)
.get_usize(bx, vtable),
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN)
.get_usize(bx, vtable),
)
}
ty::Slice(_) | ty::Str => {
let unit = layout.field(bx, 0);
// The info in this case is the length of the str, so the size is that
// times the unit size.
(
bx.mul(info.unwrap(), bx.const_usize(unit.size.bytes())),
bx.const_usize(unit.align.abi.bytes()),
)
}
_ => {
// First get the size of all statically known fields.
// Don't use size_of because it also rounds up to alignment, which we
// want to avoid, as the unsized field's alignment could be smaller.
assert!(!t.is_simd());
debug!("DST {} layout: {:?}", t, layout);
let i = layout.fields.count() - 1;
let sized_size = layout.fields.offset(i).bytes();
let sized_align = layout.align.abi.bytes();
debug!("DST {} statically sized prefix size: {} align: {}", t, sized_size, sized_align);
let sized_size = bx.const_usize(sized_size);
let sized_align = bx.const_usize(sized_align);
// Recurse to get the size of the dynamically sized field (must be
// the last field).
let field_ty = layout.field(bx, i).ty;
let (unsized_size, mut unsized_align) = size_and_align_of_dst(bx, field_ty, info);
// FIXME (#26403, #27023): We should be adding padding
// to `sized_size` (to accommodate the `unsized_align`
// required of the unsized field that follows) before
// summing it with `sized_size`. (Note that since #26403
// is unfixed, we do not yet add the necessary padding
// here. But this is where the add would go.)
// Return the sum of sizes and max of aligns.
let size = bx.add(sized_size, unsized_size);
// Packed types ignore the alignment of their fields.
if let ty::Adt(def, _) = t.kind() {
if def.repr.packed() {
unsized_align = sized_align;
}
}
// Choose max of two known alignments (combined value must
// be aligned according to more restrictive of the two).
let align = match (
bx.const_to_opt_u128(sized_align, false),
bx.const_to_opt_u128(unsized_align, false),
|
) {
(Some(sized_align), Some(unsized_align)) => {
// If both alignments are constant, (the sized_align should always be), then
// pick the correct alignment statically.
bx.const_usize(std::cmp::max(sized_align, unsized_align) as u64)
}
_ => {
let cmp = bx.icmp(IntPredicate::IntUGT, sized_align, unsized_align);
bx.select(cmp, sized_align, unsized_align)
}
};
// Issue #27023: must add any necessary padding to `size`
// (to make it a multiple of `align`) before returning it.
//
// Namely, the returned size should be, in C notation:
//
// `size + ((size & (align-1))? align : 0)`
//
// emulated via the semi-standard fast bit trick:
//
// `(size + (align-1)) & -align`
let one = bx.const_usize(1);
let addend = bx.sub(align, one);
let add = bx.add(size, addend);
let neg = bx.neg(align);
let size = bx.and(add, neg);
(size, align)
}
}
}
|
random_line_split
|
|
glue.rs
|
//!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn
|
<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value) {
let layout = bx.layout_of(t);
debug!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
if!layout.is_unsized() {
let size = bx.const_usize(layout.size.bytes());
let align = bx.const_usize(layout.align.abi.bytes());
return (size, align);
}
match t.kind() {
ty::Dynamic(..) => {
// load size/align from vtable
let vtable = info.unwrap();
(
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE)
.get_usize(bx, vtable),
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN)
.get_usize(bx, vtable),
)
}
ty::Slice(_) | ty::Str => {
let unit = layout.field(bx, 0);
// The info in this case is the length of the str, so the size is that
// times the unit size.
(
bx.mul(info.unwrap(), bx.const_usize(unit.size.bytes())),
bx.const_usize(unit.align.abi.bytes()),
)
}
_ => {
// First get the size of all statically known fields.
// Don't use size_of because it also rounds up to alignment, which we
// want to avoid, as the unsized field's alignment could be smaller.
assert!(!t.is_simd());
debug!("DST {} layout: {:?}", t, layout);
let i = layout.fields.count() - 1;
let sized_size = layout.fields.offset(i).bytes();
let sized_align = layout.align.abi.bytes();
debug!("DST {} statically sized prefix size: {} align: {}", t, sized_size, sized_align);
let sized_size = bx.const_usize(sized_size);
let sized_align = bx.const_usize(sized_align);
// Recurse to get the size of the dynamically sized field (must be
// the last field).
let field_ty = layout.field(bx, i).ty;
let (unsized_size, mut unsized_align) = size_and_align_of_dst(bx, field_ty, info);
// FIXME (#26403, #27023): We should be adding padding
// to `sized_size` (to accommodate the `unsized_align`
// required of the unsized field that follows) before
// summing it with `sized_size`. (Note that since #26403
// is unfixed, we do not yet add the necessary padding
// here. But this is where the add would go.)
// Return the sum of sizes and max of aligns.
let size = bx.add(sized_size, unsized_size);
// Packed types ignore the alignment of their fields.
if let ty::Adt(def, _) = t.kind() {
if def.repr.packed() {
unsized_align = sized_align;
}
}
// Choose max of two known alignments (combined value must
// be aligned according to more restrictive of the two).
let align = match (
bx.const_to_opt_u128(sized_align, false),
bx.const_to_opt_u128(unsized_align, false),
) {
(Some(sized_align), Some(unsized_align)) => {
// If both alignments are constant, (the sized_align should always be), then
// pick the correct alignment statically.
bx.const_usize(std::cmp::max(sized_align, unsized_align) as u64)
}
_ => {
let cmp = bx.icmp(IntPredicate::IntUGT, sized_align, unsized_align);
bx.select(cmp, sized_align, unsized_align)
}
};
// Issue #27023: must add any necessary padding to `size`
// (to make it a multiple of `align`) before returning it.
//
// Namely, the returned size should be, in C notation:
//
// `size + ((size & (align-1))? align : 0)`
//
// emulated via the semi-standard fast bit trick:
//
// `(size + (align-1)) & -align`
let one = bx.const_usize(1);
let addend = bx.sub(align, one);
let add = bx.add(size, addend);
let neg = bx.neg(align);
let size = bx.and(add, neg);
(size, align)
}
}
}
|
size_and_align_of_dst
|
identifier_name
|
glue.rs
|
//!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value)
|
let unit = layout.field(bx, 0);
// The info in this case is the length of the str, so the size is that
// times the unit size.
(
bx.mul(info.unwrap(), bx.const_usize(unit.size.bytes())),
bx.const_usize(unit.align.abi.bytes()),
)
}
_ => {
// First get the size of all statically known fields.
// Don't use size_of because it also rounds up to alignment, which we
// want to avoid, as the unsized field's alignment could be smaller.
assert!(!t.is_simd());
debug!("DST {} layout: {:?}", t, layout);
let i = layout.fields.count() - 1;
let sized_size = layout.fields.offset(i).bytes();
let sized_align = layout.align.abi.bytes();
debug!("DST {} statically sized prefix size: {} align: {}", t, sized_size, sized_align);
let sized_size = bx.const_usize(sized_size);
let sized_align = bx.const_usize(sized_align);
// Recurse to get the size of the dynamically sized field (must be
// the last field).
let field_ty = layout.field(bx, i).ty;
let (unsized_size, mut unsized_align) = size_and_align_of_dst(bx, field_ty, info);
// FIXME (#26403, #27023): We should be adding padding
// to `sized_size` (to accommodate the `unsized_align`
// required of the unsized field that follows) before
// summing it with `sized_size`. (Note that since #26403
// is unfixed, we do not yet add the necessary padding
// here. But this is where the add would go.)
// Return the sum of sizes and max of aligns.
let size = bx.add(sized_size, unsized_size);
// Packed types ignore the alignment of their fields.
if let ty::Adt(def, _) = t.kind() {
if def.repr.packed() {
unsized_align = sized_align;
}
}
// Choose max of two known alignments (combined value must
// be aligned according to more restrictive of the two).
let align = match (
bx.const_to_opt_u128(sized_align, false),
bx.const_to_opt_u128(unsized_align, false),
) {
(Some(sized_align), Some(unsized_align)) => {
// If both alignments are constant, (the sized_align should always be), then
// pick the correct alignment statically.
bx.const_usize(std::cmp::max(sized_align, unsized_align) as u64)
}
_ => {
let cmp = bx.icmp(IntPredicate::IntUGT, sized_align, unsized_align);
bx.select(cmp, sized_align, unsized_align)
}
};
// Issue #27023: must add any necessary padding to `size`
// (to make it a multiple of `align`) before returning it.
//
// Namely, the returned size should be, in C notation:
//
// `size + ((size & (align-1))? align : 0)`
//
// emulated via the semi-standard fast bit trick:
//
// `(size + (align-1)) & -align`
let one = bx.const_usize(1);
let addend = bx.sub(align, one);
let add = bx.add(size, addend);
let neg = bx.neg(align);
let size = bx.and(add, neg);
(size, align)
}
}
}
|
{
let layout = bx.layout_of(t);
debug!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
if !layout.is_unsized() {
let size = bx.const_usize(layout.size.bytes());
let align = bx.const_usize(layout.align.abi.bytes());
return (size, align);
}
match t.kind() {
ty::Dynamic(..) => {
// load size/align from vtable
let vtable = info.unwrap();
(
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE)
.get_usize(bx, vtable),
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN)
.get_usize(bx, vtable),
)
}
ty::Slice(_) | ty::Str => {
|
identifier_body
|
inferred-suffix-in-pattern-range.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main() {
|
0.. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(x_message, ~"lots");
let y = 2i;
let y_message = match y {
0.. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(y_message, ~"lots");
let z = 1u64;
let z_message = match z {
0.. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(z_message, ~"not many");
}
|
let x = 2;
let x_message = match x {
|
random_line_split
|
inferred-suffix-in-pattern-range.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn
|
() {
let x = 2;
let x_message = match x {
0.. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(x_message, ~"lots");
let y = 2i;
let y_message = match y {
0.. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(y_message, ~"lots");
let z = 1u64;
let z_message = match z {
0.. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(z_message, ~"not many");
}
|
main
|
identifier_name
|
inferred-suffix-in-pattern-range.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main()
|
assert_eq!(z_message, ~"not many");
}
|
{
let x = 2;
let x_message = match x {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(x_message, ~"lots");
let y = 2i;
let y_message = match y {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(y_message, ~"lots");
let z = 1u64;
let z_message = match z {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
|
identifier_body
|
resource_task.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/. */
//! A task that takes a URL and streams back the binary data.
use about_loader;
use data_loader;
use file_loader;
use http_loader;
use cookie_storage::CookieStorage;
use cookie;
use mime_classifier::MIMEClassifier;
use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieSource};
use net_traits::{Metadata, ProgressMsg, ResourceTask, AsyncResponseTarget, ResponseAction};
use net_traits::ProgressMsg::Done;
use util::opts;
use util::task::spawn_named;
use url::Url;
use hsts::{HSTSList, HSTSEntry, preload_hsts_domains};
use devtools_traits::{DevtoolsControlMsg};
use hyper::header::{ContentType, Header, SetCookie, UserAgent};
use hyper::mime::{Mime, TopLevel, SubLevel};
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use std::borrow::ToOwned;
use std::boxed::FnBox;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::mpsc::{channel, Sender};
pub enum ProgressSender {
Channel(IpcSender<ProgressMsg>),
Listener(AsyncResponseTarget),
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()),
ProgressSender::Listener(ref b) => {
let action = match msg {
ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf),
ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status),
};
b.invoke_with_listener(action);
Ok(())
}
}
}
}
/// For use by loaders in responding to a Load message.
pub fn start_sending(start_chan: LoadConsumer, metadata: Metadata) -> ProgressSender {
start_sending_opt(start_chan, metadata).ok().unwrap()
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>)
-> ProgressSender {
start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body).ok().unwrap()
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>)
-> Result<ProgressSender, ()> {
if opts::get().sniff_mime_types {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut nosniff = false;
let mut check_for_apache_bug = false;
if let Some(ref headers) = metadata.headers {
if let Some(ref raw_content_type) = headers.get_raw("content-type") {
if raw_content_type.len() > 0 {
let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1];
check_for_apache_bug = last_raw_content_type == b"text/plain"
|| last_raw_content_type == b"text/plain; charset=ISO-8859-1"
|| last_raw_content_type == b"text/plain; charset=iso-8859-1"
|| last_raw_content_type == b"text/plain; charset=UTF-8";
}
}
if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") {
nosniff = raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff");
}
}
let supplied_type =
metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| {
(format!("{}", toplevel), format!("{}", sublevel))
});
metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type,
&partial_body).map(|(toplevel, sublevel)| {
let mime_tp: TopLevel = toplevel.parse().unwrap();
let mime_sb: SubLevel = sublevel.parse().unwrap();
ContentType(Mime(mime_tp, mime_sb, vec!()))
});
}
start_sending_opt(start_chan, metadata)
}
/// For use by loaders in responding to a Load message.
pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> {
match start_chan {
LoadConsumer::Channel(start_chan) => {
let (progress_chan, progress_port) = ipc::channel().unwrap();
let result = start_chan.send(LoadResponse {
metadata: metadata,
progress_port: progress_port,
});
match result {
Ok(_) => Ok(ProgressSender::Channel(progress_chan)),
Err(_) => Err(())
}
}
LoadConsumer::Listener(target) => {
target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata));
Ok(ProgressSender::Listener(target))
}
}
}
/// Create a ResourceTask
pub fn new_resource_task(user_agent: Option<String>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask {
let hsts_preload = match preload_hsts_domains() {
Some(list) => list,
None => HSTSList::new()
};
let (setup_chan, setup_port) = ipc::channel().unwrap();
let setup_chan_clone = setup_chan.clone();
spawn_named("ResourceManager".to_owned(), move || {
let resource_manager = ResourceManager::new(
user_agent, setup_chan_clone, hsts_preload, devtools_chan
);
let mut channel_manager = ResourceChannelManager {
from_client: setup_port,
resource_manager: resource_manager
};
channel_manager.start();
});
setup_chan
}
struct ResourceChannelManager {
from_client: IpcReceiver<ControlMsg>,
resource_manager: ResourceManager
}
impl ResourceChannelManager {
fn start(&mut self) {
loop {
match self.from_client.recv().unwrap() {
ControlMsg::Load(load_data, consumer) => {
self.resource_manager.load(load_data, consumer)
}
ControlMsg::SetCookiesForUrl(request, cookie_list, source) => {
self.resource_manager.set_cookies_for_url(request, cookie_list, source)
}
ControlMsg::GetCookiesForUrl(url, consumer, source) => {
consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap();
}
ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => {
if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) {
self.resource_manager.add_hsts_entry(entry)
}
}
ControlMsg::Exit => {
break
}
}
}
}
}
pub struct ResourceManager {
user_agent: Option<String>,
cookie_storage: CookieStorage,
resource_task: IpcSender<ControlMsg>,
mime_classifier: Arc<MIMEClassifier>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
hsts_list: Arc<Mutex<HSTSList>>
}
impl ResourceManager {
pub fn new(user_agent: Option<String>,
resource_task: IpcSender<ControlMsg>,
hsts_list: HSTSList,
devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager {
ResourceManager {
user_agent: user_agent,
cookie_storage: CookieStorage::new(),
resource_task: resource_task,
mime_classifier: Arc::new(MIMEClassifier::new()),
devtools_chan: devtools_channel,
hsts_list: Arc::new(Mutex::new(hsts_list))
}
}
}
impl ResourceManager {
fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource) {
let header = Header::parse_header(&[cookie_list.into_bytes()]);
if let Ok(SetCookie(cookies)) = header {
for bare_cookie in cookies.into_iter() {
if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) {
self.cookie_storage.push(cookie, source);
}
}
}
}
pub fn add_hsts_entry(&mut self, entry: HSTSEntry) {
self.hsts_list.lock().unwrap().push(entry);
}
pub fn
|
(&self, host: &str) -> bool {
self.hsts_list.lock().unwrap().is_host_secure(host)
}
fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) {
self.user_agent.as_ref().map(|ua| {
load_data.preserved_headers.set(UserAgent(ua.clone()));
});
fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>))
-> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> {
box move |load_data, senders, classifier| {
factory(load_data, senders, classifier)
}
}
let loader = match &*load_data.url.scheme {
"file" => from_factory(file_loader::factory),
"http" | "https" | "view-source" =>
http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()),
"data" => from_factory(data_loader::factory),
"about" => from_factory(about_loader::factory),
_ => {
debug!("resource_task: no loader for scheme {}", load_data.url.scheme);
start_sending(consumer, Metadata::default(load_data.url))
.send(ProgressMsg::Done(Err("no loader for scheme".to_string()))).unwrap();
return
}
};
debug!("resource_task: loading url: {}", load_data.url.serialize());
loader.call_box((load_data, consumer, self.mime_classifier.clone()));
}
}
|
is_host_sts
|
identifier_name
|
resource_task.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/. */
//! A task that takes a URL and streams back the binary data.
use about_loader;
use data_loader;
use file_loader;
use http_loader;
use cookie_storage::CookieStorage;
use cookie;
use mime_classifier::MIMEClassifier;
use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieSource};
use net_traits::{Metadata, ProgressMsg, ResourceTask, AsyncResponseTarget, ResponseAction};
use net_traits::ProgressMsg::Done;
use util::opts;
use util::task::spawn_named;
use url::Url;
use hsts::{HSTSList, HSTSEntry, preload_hsts_domains};
use devtools_traits::{DevtoolsControlMsg};
use hyper::header::{ContentType, Header, SetCookie, UserAgent};
use hyper::mime::{Mime, TopLevel, SubLevel};
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use std::borrow::ToOwned;
use std::boxed::FnBox;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::mpsc::{channel, Sender};
pub enum ProgressSender {
Channel(IpcSender<ProgressMsg>),
Listener(AsyncResponseTarget),
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()),
ProgressSender::Listener(ref b) => {
let action = match msg {
ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf),
ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status),
};
b.invoke_with_listener(action);
Ok(())
}
}
}
}
/// For use by loaders in responding to a Load message.
pub fn start_sending(start_chan: LoadConsumer, metadata: Metadata) -> ProgressSender {
start_sending_opt(start_chan, metadata).ok().unwrap()
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>)
-> ProgressSender {
start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body).ok().unwrap()
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata,
classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>)
-> Result<ProgressSender, ()> {
if opts::get().sniff_mime_types {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut nosniff = false;
let mut check_for_apache_bug = false;
if let Some(ref headers) = metadata.headers {
if let Some(ref raw_content_type) = headers.get_raw("content-type") {
if raw_content_type.len() > 0 {
let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1];
check_for_apache_bug = last_raw_content_type == b"text/plain"
|| last_raw_content_type == b"text/plain; charset=ISO-8859-1"
|| last_raw_content_type == b"text/plain; charset=iso-8859-1"
|| last_raw_content_type == b"text/plain; charset=UTF-8";
}
}
if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") {
nosniff = raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff");
}
}
let supplied_type =
metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| {
(format!("{}", toplevel), format!("{}", sublevel))
});
metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type,
&partial_body).map(|(toplevel, sublevel)| {
let mime_tp: TopLevel = toplevel.parse().unwrap();
let mime_sb: SubLevel = sublevel.parse().unwrap();
ContentType(Mime(mime_tp, mime_sb, vec!()))
});
}
start_sending_opt(start_chan, metadata)
}
/// For use by loaders in responding to a Load message.
pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> {
match start_chan {
LoadConsumer::Channel(start_chan) => {
let (progress_chan, progress_port) = ipc::channel().unwrap();
|
match result {
Ok(_) => Ok(ProgressSender::Channel(progress_chan)),
Err(_) => Err(())
}
}
LoadConsumer::Listener(target) => {
target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata));
Ok(ProgressSender::Listener(target))
}
}
}
/// Create a ResourceTask
pub fn new_resource_task(user_agent: Option<String>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask {
let hsts_preload = match preload_hsts_domains() {
Some(list) => list,
None => HSTSList::new()
};
let (setup_chan, setup_port) = ipc::channel().unwrap();
let setup_chan_clone = setup_chan.clone();
spawn_named("ResourceManager".to_owned(), move || {
let resource_manager = ResourceManager::new(
user_agent, setup_chan_clone, hsts_preload, devtools_chan
);
let mut channel_manager = ResourceChannelManager {
from_client: setup_port,
resource_manager: resource_manager
};
channel_manager.start();
});
setup_chan
}
struct ResourceChannelManager {
from_client: IpcReceiver<ControlMsg>,
resource_manager: ResourceManager
}
impl ResourceChannelManager {
fn start(&mut self) {
loop {
match self.from_client.recv().unwrap() {
ControlMsg::Load(load_data, consumer) => {
self.resource_manager.load(load_data, consumer)
}
ControlMsg::SetCookiesForUrl(request, cookie_list, source) => {
self.resource_manager.set_cookies_for_url(request, cookie_list, source)
}
ControlMsg::GetCookiesForUrl(url, consumer, source) => {
consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap();
}
ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => {
if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) {
self.resource_manager.add_hsts_entry(entry)
}
}
ControlMsg::Exit => {
break
}
}
}
}
}
pub struct ResourceManager {
user_agent: Option<String>,
cookie_storage: CookieStorage,
resource_task: IpcSender<ControlMsg>,
mime_classifier: Arc<MIMEClassifier>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
hsts_list: Arc<Mutex<HSTSList>>
}
impl ResourceManager {
pub fn new(user_agent: Option<String>,
resource_task: IpcSender<ControlMsg>,
hsts_list: HSTSList,
devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager {
ResourceManager {
user_agent: user_agent,
cookie_storage: CookieStorage::new(),
resource_task: resource_task,
mime_classifier: Arc::new(MIMEClassifier::new()),
devtools_chan: devtools_channel,
hsts_list: Arc::new(Mutex::new(hsts_list))
}
}
}
impl ResourceManager {
fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource) {
let header = Header::parse_header(&[cookie_list.into_bytes()]);
if let Ok(SetCookie(cookies)) = header {
for bare_cookie in cookies.into_iter() {
if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) {
self.cookie_storage.push(cookie, source);
}
}
}
}
pub fn add_hsts_entry(&mut self, entry: HSTSEntry) {
self.hsts_list.lock().unwrap().push(entry);
}
pub fn is_host_sts(&self, host: &str) -> bool {
self.hsts_list.lock().unwrap().is_host_secure(host)
}
fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) {
self.user_agent.as_ref().map(|ua| {
load_data.preserved_headers.set(UserAgent(ua.clone()));
});
fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>))
-> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> {
box move |load_data, senders, classifier| {
factory(load_data, senders, classifier)
}
}
let loader = match &*load_data.url.scheme {
"file" => from_factory(file_loader::factory),
"http" | "https" | "view-source" =>
http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()),
"data" => from_factory(data_loader::factory),
"about" => from_factory(about_loader::factory),
_ => {
debug!("resource_task: no loader for scheme {}", load_data.url.scheme);
start_sending(consumer, Metadata::default(load_data.url))
.send(ProgressMsg::Done(Err("no loader for scheme".to_string()))).unwrap();
return
}
};
debug!("resource_task: loading url: {}", load_data.url.serialize());
loader.call_box((load_data, consumer, self.mime_classifier.clone()));
}
}
|
let result = start_chan.send(LoadResponse {
metadata: metadata,
progress_port: progress_port,
});
|
random_line_split
|
stats.rs
|
// Copyright (c) 2015-2017 Ivo Wetzel
// 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.
// Internal Dependencies ------------------------------------------------------
use ::Config;
/// A structure containing stats data average of the course of one second.
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Stats {
/// Average number of bytes received over the last second.
pub bytes_sent: u32,
/// Average number of bytes received over the last second.
pub bytes_received: u32
}
impl Stats {
pub fn reset(&mut self) {
self.bytes_sent = 0;
self.bytes_received = 0;
}
}
impl Default for Stats {
fn default() -> Stats {
Stats {
bytes_sent: 0,
bytes_received: 0
}
}
}
/// Structure to keep track of per second average stats of a Client or Server.
///
/// Uses a list of buckets and caluclates the average each time a new value is
/// pushed into the bucket list `O(1)`.
#[derive(Debug)]
pub struct StatsCollector {
/// Internal tick value
tick: u64,
/// The collectors's configuration
config: Config,
/// Internal stat buckets for O(1) average calculation
buckets: Vec<Stats>,
/// Internal stat average for the current tick
averages: Stats
}
impl StatsCollector {
/// Creates a new stats object which averages incoming data over the given
/// number of ticks per second.
pub fn new(config: Config) -> StatsCollector {
StatsCollector {
tick: 0,
config: config,
buckets: (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>(),
averages: Stats::default()
}
}
/// Overrides the collector's existing configuration.
pub fn set_config(&mut self, config: Config) {
self.config = config;
self.buckets = (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>()
}
/// Sets the number of bytes sent for the current tick.
pub fn set_bytes_sent(&mut self, bytes: u32) {
let old_index = (self.tick as i32 + 1) % (self.config.send_rate + 1) as i32;
let old_bytes = self.buckets[old_index as usize].bytes_sent;
self.averages.bytes_sent = (self.averages.bytes_sent - old_bytes) + bytes;
self.buckets[self.tick as usize].bytes_sent = bytes;
}
/// Sets the number of bytes received for the current tick.
pub fn set_bytes_received(&mut self, bytes: u32) {
let old_index = (self.tick as i32 + 1) % (self.config.send_rate + 1) as i32;
let old_bytes = self.buckets[old_index as usize].bytes_received;
self.averages.bytes_received = (self.averages.bytes_received - old_bytes) + bytes;
self.buckets[self.tick as usize].bytes_received = bytes;
}
|
/// Returns the calculated averages from the last tick.
pub fn average(&self) -> Stats {
self.averages
}
/// Resets the internal data used for average calculation, but does not
/// reset the last calculated averages.
pub fn reset(&mut self) {
self.averages.bytes_sent = 0;
self.averages.bytes_received = 0;
for d in &mut self.buckets {
d.reset();
}
}
}
|
/// Steps the internal tick value used for average calculation.
pub fn tick(&mut self) {
self.tick = (self.tick + 1) % (self.config.send_rate + 1);
}
|
random_line_split
|
stats.rs
|
// Copyright (c) 2015-2017 Ivo Wetzel
// 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.
// Internal Dependencies ------------------------------------------------------
use ::Config;
/// A structure containing stats data average of the course of one second.
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Stats {
/// Average number of bytes received over the last second.
pub bytes_sent: u32,
/// Average number of bytes received over the last second.
pub bytes_received: u32
}
impl Stats {
pub fn reset(&mut self) {
self.bytes_sent = 0;
self.bytes_received = 0;
}
}
impl Default for Stats {
fn default() -> Stats {
Stats {
bytes_sent: 0,
bytes_received: 0
}
}
}
/// Structure to keep track of per second average stats of a Client or Server.
///
/// Uses a list of buckets and caluclates the average each time a new value is
/// pushed into the bucket list `O(1)`.
#[derive(Debug)]
pub struct StatsCollector {
/// Internal tick value
tick: u64,
/// The collectors's configuration
config: Config,
/// Internal stat buckets for O(1) average calculation
buckets: Vec<Stats>,
/// Internal stat average for the current tick
averages: Stats
}
impl StatsCollector {
/// Creates a new stats object which averages incoming data over the given
/// number of ticks per second.
pub fn
|
(config: Config) -> StatsCollector {
StatsCollector {
tick: 0,
config: config,
buckets: (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>(),
averages: Stats::default()
}
}
/// Overrides the collector's existing configuration.
pub fn set_config(&mut self, config: Config) {
self.config = config;
self.buckets = (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>()
}
/// Sets the number of bytes sent for the current tick.
pub fn set_bytes_sent(&mut self, bytes: u32) {
let old_index = (self.tick as i32 + 1) % (self.config.send_rate + 1) as i32;
let old_bytes = self.buckets[old_index as usize].bytes_sent;
self.averages.bytes_sent = (self.averages.bytes_sent - old_bytes) + bytes;
self.buckets[self.tick as usize].bytes_sent = bytes;
}
/// Sets the number of bytes received for the current tick.
pub fn set_bytes_received(&mut self, bytes: u32) {
let old_index = (self.tick as i32 + 1) % (self.config.send_rate + 1) as i32;
let old_bytes = self.buckets[old_index as usize].bytes_received;
self.averages.bytes_received = (self.averages.bytes_received - old_bytes) + bytes;
self.buckets[self.tick as usize].bytes_received = bytes;
}
/// Steps the internal tick value used for average calculation.
pub fn tick(&mut self) {
self.tick = (self.tick + 1) % (self.config.send_rate + 1);
}
/// Returns the calculated averages from the last tick.
pub fn average(&self) -> Stats {
self.averages
}
/// Resets the internal data used for average calculation, but does not
/// reset the last calculated averages.
pub fn reset(&mut self) {
self.averages.bytes_sent = 0;
self.averages.bytes_received = 0;
for d in &mut self.buckets {
d.reset();
}
}
}
|
new
|
identifier_name
|
stats.rs
|
// Copyright (c) 2015-2017 Ivo Wetzel
// 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.
// Internal Dependencies ------------------------------------------------------
use ::Config;
/// A structure containing stats data average of the course of one second.
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Stats {
/// Average number of bytes received over the last second.
pub bytes_sent: u32,
/// Average number of bytes received over the last second.
pub bytes_received: u32
}
impl Stats {
pub fn reset(&mut self) {
self.bytes_sent = 0;
self.bytes_received = 0;
}
}
impl Default for Stats {
fn default() -> Stats {
Stats {
bytes_sent: 0,
bytes_received: 0
}
}
}
/// Structure to keep track of per second average stats of a Client or Server.
///
/// Uses a list of buckets and caluclates the average each time a new value is
/// pushed into the bucket list `O(1)`.
#[derive(Debug)]
pub struct StatsCollector {
/// Internal tick value
tick: u64,
/// The collectors's configuration
config: Config,
/// Internal stat buckets for O(1) average calculation
buckets: Vec<Stats>,
/// Internal stat average for the current tick
averages: Stats
}
impl StatsCollector {
/// Creates a new stats object which averages incoming data over the given
/// number of ticks per second.
pub fn new(config: Config) -> StatsCollector {
StatsCollector {
tick: 0,
config: config,
buckets: (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>(),
averages: Stats::default()
}
}
/// Overrides the collector's existing configuration.
pub fn set_config(&mut self, config: Config)
|
/// Sets the number of bytes sent for the current tick.
pub fn set_bytes_sent(&mut self, bytes: u32) {
let old_index = (self.tick as i32 + 1) % (self.config.send_rate + 1) as i32;
let old_bytes = self.buckets[old_index as usize].bytes_sent;
self.averages.bytes_sent = (self.averages.bytes_sent - old_bytes) + bytes;
self.buckets[self.tick as usize].bytes_sent = bytes;
}
/// Sets the number of bytes received for the current tick.
pub fn set_bytes_received(&mut self, bytes: u32) {
let old_index = (self.tick as i32 + 1) % (self.config.send_rate + 1) as i32;
let old_bytes = self.buckets[old_index as usize].bytes_received;
self.averages.bytes_received = (self.averages.bytes_received - old_bytes) + bytes;
self.buckets[self.tick as usize].bytes_received = bytes;
}
/// Steps the internal tick value used for average calculation.
pub fn tick(&mut self) {
self.tick = (self.tick + 1) % (self.config.send_rate + 1);
}
/// Returns the calculated averages from the last tick.
pub fn average(&self) -> Stats {
self.averages
}
/// Resets the internal data used for average calculation, but does not
/// reset the last calculated averages.
pub fn reset(&mut self) {
self.averages.bytes_sent = 0;
self.averages.bytes_received = 0;
for d in &mut self.buckets {
d.reset();
}
}
}
|
{
self.config = config;
self.buckets = (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>()
}
|
identifier_body
|
lib.rs
|
//! Clients for comunicating with a [Kafka](http://kafka.apache.org/)
//! cluster. These are:
//!
//! - `kafka::producer::Producer` - for sending message to Kafka
//! - `kafka::consumer::Consumer` - for retrieving/consuming messages from Kafka
//! - `kafka::client::KafkaClient` - a lower-level, general purpose client leaving you with more power but also more resposibility
//!
//! See module level documentation corresponding to each client individually.
#![cfg_attr(feature = "nightly", feature(test))]
extern crate byteorder;
extern crate crc;
extern crate ref_slice;
extern crate fnv;
#[macro_use]
extern crate log;
#[cfg(feature = "security")]
extern crate openssl;
#[cfg(feature = "gzip")]
extern crate flate2;
#[cfg(feature = "snappy")]
extern crate snappy;
#[cfg(all(test, feature = "nightly"))]
extern crate test;
pub mod error;
pub mod client;
mod client_internals;
pub mod consumer;
pub mod producer;
mod utils;
mod codecs;
mod protocol;
mod compression;
pub use self::error::{Error, Result};
trait KafkaClientInternals {
fn internal_produce_messages<'a, 'b, I, J>(
|
where J: AsRef<client::ProduceMessage<'a, 'b>>, I: IntoIterator<Item=J>;
}
|
&mut self, ack: client::RequiredAcks, ack_timeout: i32, messages: I)
-> Result<Vec<client::TopicPartitionOffset>>
|
random_line_split
|
notifications.rs
|
use crate::AppState;
use actix_web::{HttpResponse, Json, State};
use log::{debug, warn};
use potboiler_common::{db, types::Log};
use serde_derive::Deserialize;
use std::{
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
thread,
};
use url::Url;
#[derive(Clone, Debug)]
pub struct Notifications {
notifiers: Arc<RwLock<Vec<String>>>,
}
impl Notifications {
pub fn new(conn: &db::Connection) -> Notifications {
let mut notifiers = Vec::new();
for row in &conn
.query("select url from notifications")
.expect("notifications select works")
{
let url: String = row.get("url");
notifiers.push(url);
}
Notifications {
notifiers: Arc::new(RwLock::new(notifiers)),
}
}
pub fn notify_everyone(&self, log_arc: &Arc<Log>) {
for notifier in self.notifiers.read().unwrap().deref() {
let local_log = log_arc.clone();
let local_notifier = notifier.clone();
thread::spawn(move || {
let client = reqwest::Client::new();
debug!("Notifying {:?}", local_notifier);
let res = client.post(&local_notifier).json(&local_log.deref()).send();
match res {
Ok(val) => {
if val.status()!= reqwest::StatusCode::NO_CONTENT {
warn!("Failed to notify {:?}: {:?}", &local_notifier, val.status());
}
|
});
}
}
}
#[derive(Deserialize)]
pub struct UrlJson {
url: String,
}
pub fn log_register(state: State<AppState>, body: Json<UrlJson>) -> HttpResponse {
let conn = state.pool.get().unwrap();
let url = &body.url;
debug!("Registering {:?}", url);
match Url::parse(url) {
Err(_) => HttpResponse::BadRequest().reason("Bad URL").finish(),
Ok(_) => match conn.execute(&format!("insert into notifications (url) values('{}')", &url)) {
Ok(_) => {
state
.notifications
.notifiers
.write()
.unwrap()
.deref_mut()
.push(url.to_string());
HttpResponse::Created().finish()
}
Err(db::Error::UniqueViolation) => HttpResponse::Created().finish(),
Err(err) => HttpResponse::BadRequest().body(format!("Some other error: {}", err)),
},
}
}
pub fn log_deregister(state: State<AppState>, body: Json<UrlJson>) -> HttpResponse {
let conn = state.pool.get().unwrap();
let url = &body.url;
let res = conn
.execute(&format!("delete from notifications where url = '{}'", url))
.expect("delete worked");
if res == 1 {
HttpResponse::NoContent().finish()
} else {
HttpResponse::NotFound().finish()
}
}
|
}
Err(val) => {
warn!("Failed to notify {:?}: {:?}", &local_notifier, val);
}
};
|
random_line_split
|
notifications.rs
|
use crate::AppState;
use actix_web::{HttpResponse, Json, State};
use log::{debug, warn};
use potboiler_common::{db, types::Log};
use serde_derive::Deserialize;
use std::{
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
thread,
};
use url::Url;
#[derive(Clone, Debug)]
pub struct
|
{
notifiers: Arc<RwLock<Vec<String>>>,
}
impl Notifications {
pub fn new(conn: &db::Connection) -> Notifications {
let mut notifiers = Vec::new();
for row in &conn
.query("select url from notifications")
.expect("notifications select works")
{
let url: String = row.get("url");
notifiers.push(url);
}
Notifications {
notifiers: Arc::new(RwLock::new(notifiers)),
}
}
pub fn notify_everyone(&self, log_arc: &Arc<Log>) {
for notifier in self.notifiers.read().unwrap().deref() {
let local_log = log_arc.clone();
let local_notifier = notifier.clone();
thread::spawn(move || {
let client = reqwest::Client::new();
debug!("Notifying {:?}", local_notifier);
let res = client.post(&local_notifier).json(&local_log.deref()).send();
match res {
Ok(val) => {
if val.status()!= reqwest::StatusCode::NO_CONTENT {
warn!("Failed to notify {:?}: {:?}", &local_notifier, val.status());
}
}
Err(val) => {
warn!("Failed to notify {:?}: {:?}", &local_notifier, val);
}
};
});
}
}
}
#[derive(Deserialize)]
pub struct UrlJson {
url: String,
}
pub fn log_register(state: State<AppState>, body: Json<UrlJson>) -> HttpResponse {
let conn = state.pool.get().unwrap();
let url = &body.url;
debug!("Registering {:?}", url);
match Url::parse(url) {
Err(_) => HttpResponse::BadRequest().reason("Bad URL").finish(),
Ok(_) => match conn.execute(&format!("insert into notifications (url) values('{}')", &url)) {
Ok(_) => {
state
.notifications
.notifiers
.write()
.unwrap()
.deref_mut()
.push(url.to_string());
HttpResponse::Created().finish()
}
Err(db::Error::UniqueViolation) => HttpResponse::Created().finish(),
Err(err) => HttpResponse::BadRequest().body(format!("Some other error: {}", err)),
},
}
}
pub fn log_deregister(state: State<AppState>, body: Json<UrlJson>) -> HttpResponse {
let conn = state.pool.get().unwrap();
let url = &body.url;
let res = conn
.execute(&format!("delete from notifications where url = '{}'", url))
.expect("delete worked");
if res == 1 {
HttpResponse::NoContent().finish()
} else {
HttpResponse::NotFound().finish()
}
}
|
Notifications
|
identifier_name
|
notifications.rs
|
use crate::AppState;
use actix_web::{HttpResponse, Json, State};
use log::{debug, warn};
use potboiler_common::{db, types::Log};
use serde_derive::Deserialize;
use std::{
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
thread,
};
use url::Url;
#[derive(Clone, Debug)]
pub struct Notifications {
notifiers: Arc<RwLock<Vec<String>>>,
}
impl Notifications {
pub fn new(conn: &db::Connection) -> Notifications {
let mut notifiers = Vec::new();
for row in &conn
.query("select url from notifications")
.expect("notifications select works")
{
let url: String = row.get("url");
notifiers.push(url);
}
Notifications {
notifiers: Arc::new(RwLock::new(notifiers)),
}
}
pub fn notify_everyone(&self, log_arc: &Arc<Log>) {
for notifier in self.notifiers.read().unwrap().deref() {
let local_log = log_arc.clone();
let local_notifier = notifier.clone();
thread::spawn(move || {
let client = reqwest::Client::new();
debug!("Notifying {:?}", local_notifier);
let res = client.post(&local_notifier).json(&local_log.deref()).send();
match res {
Ok(val) => {
if val.status()!= reqwest::StatusCode::NO_CONTENT {
warn!("Failed to notify {:?}: {:?}", &local_notifier, val.status());
}
}
Err(val) => {
warn!("Failed to notify {:?}: {:?}", &local_notifier, val);
}
};
});
}
}
}
#[derive(Deserialize)]
pub struct UrlJson {
url: String,
}
pub fn log_register(state: State<AppState>, body: Json<UrlJson>) -> HttpResponse {
let conn = state.pool.get().unwrap();
let url = &body.url;
debug!("Registering {:?}", url);
match Url::parse(url) {
Err(_) => HttpResponse::BadRequest().reason("Bad URL").finish(),
Ok(_) => match conn.execute(&format!("insert into notifications (url) values('{}')", &url)) {
Ok(_) => {
state
.notifications
.notifiers
.write()
.unwrap()
.deref_mut()
.push(url.to_string());
HttpResponse::Created().finish()
}
Err(db::Error::UniqueViolation) => HttpResponse::Created().finish(),
Err(err) => HttpResponse::BadRequest().body(format!("Some other error: {}", err)),
},
}
}
pub fn log_deregister(state: State<AppState>, body: Json<UrlJson>) -> HttpResponse {
let conn = state.pool.get().unwrap();
let url = &body.url;
let res = conn
.execute(&format!("delete from notifications where url = '{}'", url))
.expect("delete worked");
if res == 1
|
else {
HttpResponse::NotFound().finish()
}
}
|
{
HttpResponse::NoContent().finish()
}
|
conditional_block
|
atomic_fence_acq.rs
|
#![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_fence_acq;
use core::intrinsics::atomic_fence_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_fence_acq();
struct A<T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A<T> {}
impl<T> A<T> {
fn new(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_fence_acq_test {
($init:expr, $value:expr, $result:expr) => ({
let value: T = $init;
|
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data.clone();
thread::spawn(move || {
let ptr: *mut T = clone.v.get();
unsafe { *ptr = $value; }
unsafe { atomic_fence_rel() };
});
thread::sleep_ms(10);
unsafe { atomic_fence_acq() };
let ptr: *mut T = data.v.get();
assert_eq!(unsafe { *ptr }, $value);
})
}
#[test]
fn atomic_fence_acq_test1() {
atomic_fence_acq_test!( 68, 500, 500 );
}
}
|
let a: A<T> = A::<T>::new(value);
|
random_line_split
|
atomic_fence_acq.rs
|
#![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_fence_acq;
use core::intrinsics::atomic_fence_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_fence_acq();
struct A<T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A<T> {}
impl<T> A<T> {
fn new(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_fence_acq_test {
($init:expr, $value:expr, $result:expr) => ({
let value: T = $init;
let a: A<T> = A::<T>::new(value);
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data.clone();
thread::spawn(move || {
let ptr: *mut T = clone.v.get();
unsafe { *ptr = $value; }
unsafe { atomic_fence_rel() };
});
thread::sleep_ms(10);
unsafe { atomic_fence_acq() };
let ptr: *mut T = data.v.get();
assert_eq!(unsafe { *ptr }, $value);
})
}
#[test]
fn atomic_fence_acq_test1()
|
}
|
{
atomic_fence_acq_test!( 68, 500, 500 );
}
|
identifier_body
|
atomic_fence_acq.rs
|
#![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_fence_acq;
use core::intrinsics::atomic_fence_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_fence_acq();
struct A<T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A<T> {}
impl<T> A<T> {
fn
|
(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_fence_acq_test {
($init:expr, $value:expr, $result:expr) => ({
let value: T = $init;
let a: A<T> = A::<T>::new(value);
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data.clone();
thread::spawn(move || {
let ptr: *mut T = clone.v.get();
unsafe { *ptr = $value; }
unsafe { atomic_fence_rel() };
});
thread::sleep_ms(10);
unsafe { atomic_fence_acq() };
let ptr: *mut T = data.v.get();
assert_eq!(unsafe { *ptr }, $value);
})
}
#[test]
fn atomic_fence_acq_test1() {
atomic_fence_acq_test!( 68, 500, 500 );
}
}
|
new
|
identifier_name
|
raw.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Android-specific raw type definitions
use os::raw::{c_uint, c_uchar, c_ulonglong, c_longlong, c_ulong};
use os::unix::raw::{uid_t, gid_t};
pub type blkcnt_t = u32;
pub type blksize_t = u32;
pub type dev_t = u32;
pub type ino_t = u32;
pub type mode_t = u16;
pub type nlink_t = u16;
pub type off_t = i32;
pub type time_t = i32;
#[repr(C)]
pub struct stat {
pub st_dev: c_ulonglong,
pub __pad0: [c_uchar; 4],
pub __st_ino: ino_t,
pub st_mode: c_uint,
pub st_nlink: c_uint,
pub st_uid: uid_t,
pub st_gid: gid_t,
pub st_rdev: c_ulonglong,
pub __pad3: [c_uchar; 4],
pub st_size: c_longlong,
pub st_blksize: blksize_t,
pub st_blocks: c_ulonglong,
pub st_atime: time_t,
|
pub st_ino: c_ulonglong,
}
|
pub st_atime_nsec: c_ulong,
pub st_mtime: time_t,
pub st_mtime_nsec: c_ulong,
pub st_ctime: time_t,
pub st_ctime_nsec: c_ulong,
|
random_line_split
|
raw.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Android-specific raw type definitions
use os::raw::{c_uint, c_uchar, c_ulonglong, c_longlong, c_ulong};
use os::unix::raw::{uid_t, gid_t};
pub type blkcnt_t = u32;
pub type blksize_t = u32;
pub type dev_t = u32;
pub type ino_t = u32;
pub type mode_t = u16;
pub type nlink_t = u16;
pub type off_t = i32;
pub type time_t = i32;
#[repr(C)]
pub struct
|
{
pub st_dev: c_ulonglong,
pub __pad0: [c_uchar; 4],
pub __st_ino: ino_t,
pub st_mode: c_uint,
pub st_nlink: c_uint,
pub st_uid: uid_t,
pub st_gid: gid_t,
pub st_rdev: c_ulonglong,
pub __pad3: [c_uchar; 4],
pub st_size: c_longlong,
pub st_blksize: blksize_t,
pub st_blocks: c_ulonglong,
pub st_atime: time_t,
pub st_atime_nsec: c_ulong,
pub st_mtime: time_t,
pub st_mtime_nsec: c_ulong,
pub st_ctime: time_t,
pub st_ctime_nsec: c_ulong,
pub st_ino: c_ulonglong,
}
|
stat
|
identifier_name
|
checkrust.rs
|
// Copyright 2018 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.
#![crate_type = "staticlib"]
#![feature(c_variadic)]
#![feature(rustc_private)]
extern crate libc;
use libc::{c_char, c_double, c_int, c_long, c_longlong};
use std::ffi::VaList;
use std::ffi::{CString, CStr};
macro_rules! continue_if {
($cond:expr) => {
if!($cond) {
return 0xff;
}
}
}
unsafe fn compare_c_str(ptr: *const c_char, val: &str) -> bool {
let cstr0 = CStr::from_ptr(ptr);
let cstr1 = CString::new(val).unwrap();
&*cstr1 == cstr0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_longlong>() == 1);
continue_if!(ap.arg::<c_int>() == 2);
continue_if!(ap.arg::<c_longlong>() == 3);
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_1(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_int>() == -1);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(ap.arg::<c_char>() == '4' as c_char);
continue_if!(ap.arg::<c_char>() == ';' as c_char);
continue_if!(ap.arg::<c_int>() == 0x32);
continue_if!(ap.arg::<c_int>() == 0x10000001);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Valid!"));
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_2(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 3.14f64.floor());
continue_if!(ap.arg::<c_long>() == 12);
continue_if!(ap.arg::<c_char>() == 'a' as c_char);
continue_if!(ap.arg::<c_double>().floor() == 6.18f64.floor());
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Hello"));
continue_if!(ap.arg::<c_int>() == 42);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "World"));
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_copy_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 6.28f64.floor());
continue_if!(ap.arg::<c_int>() == 16);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Skip Me!"));
ap.copy(|mut ap| {
if compare_c_str(ap.arg::<*const c_char>(), "Correct")
|
else {
0xff
}
})
}
|
{
0
}
|
conditional_block
|
checkrust.rs
|
// Copyright 2018 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.
#![crate_type = "staticlib"]
#![feature(c_variadic)]
#![feature(rustc_private)]
extern crate libc;
use libc::{c_char, c_double, c_int, c_long, c_longlong};
use std::ffi::VaList;
use std::ffi::{CString, CStr};
macro_rules! continue_if {
($cond:expr) => {
if!($cond) {
return 0xff;
}
}
}
unsafe fn compare_c_str(ptr: *const c_char, val: &str) -> bool {
let cstr0 = CStr::from_ptr(ptr);
let cstr1 = CString::new(val).unwrap();
&*cstr1 == cstr0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_longlong>() == 1);
continue_if!(ap.arg::<c_int>() == 2);
continue_if!(ap.arg::<c_longlong>() == 3);
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_1(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_int>() == -1);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(ap.arg::<c_char>() == '4' as c_char);
continue_if!(ap.arg::<c_char>() == ';' as c_char);
continue_if!(ap.arg::<c_int>() == 0x32);
continue_if!(ap.arg::<c_int>() == 0x10000001);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Valid!"));
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_2(mut ap: VaList) -> usize
|
#[no_mangle]
pub unsafe extern "C" fn check_list_copy_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 6.28f64.floor());
continue_if!(ap.arg::<c_int>() == 16);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Skip Me!"));
ap.copy(|mut ap| {
if compare_c_str(ap.arg::<*const c_char>(), "Correct") {
0
} else {
0xff
}
})
}
|
{
continue_if!(ap.arg::<c_double>().floor() == 3.14f64.floor());
continue_if!(ap.arg::<c_long>() == 12);
continue_if!(ap.arg::<c_char>() == 'a' as c_char);
continue_if!(ap.arg::<c_double>().floor() == 6.18f64.floor());
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Hello"));
continue_if!(ap.arg::<c_int>() == 42);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "World"));
0
}
|
identifier_body
|
checkrust.rs
|
// Copyright 2018 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.
#![crate_type = "staticlib"]
#![feature(c_variadic)]
#![feature(rustc_private)]
extern crate libc;
use libc::{c_char, c_double, c_int, c_long, c_longlong};
use std::ffi::VaList;
use std::ffi::{CString, CStr};
macro_rules! continue_if {
($cond:expr) => {
if!($cond) {
return 0xff;
}
}
}
unsafe fn compare_c_str(ptr: *const c_char, val: &str) -> bool {
let cstr0 = CStr::from_ptr(ptr);
let cstr1 = CString::new(val).unwrap();
&*cstr1 == cstr0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_longlong>() == 1);
continue_if!(ap.arg::<c_int>() == 2);
continue_if!(ap.arg::<c_longlong>() == 3);
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_1(mut ap: VaList) -> usize {
|
continue_if!(ap.arg::<c_int>() == 0x10000001);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Valid!"));
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_2(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 3.14f64.floor());
continue_if!(ap.arg::<c_long>() == 12);
continue_if!(ap.arg::<c_char>() == 'a' as c_char);
continue_if!(ap.arg::<c_double>().floor() == 6.18f64.floor());
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Hello"));
continue_if!(ap.arg::<c_int>() == 42);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "World"));
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_copy_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 6.28f64.floor());
continue_if!(ap.arg::<c_int>() == 16);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Skip Me!"));
ap.copy(|mut ap| {
if compare_c_str(ap.arg::<*const c_char>(), "Correct") {
0
} else {
0xff
}
})
}
|
continue_if!(ap.arg::<c_int>() == -1);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(ap.arg::<c_char>() == '4' as c_char);
continue_if!(ap.arg::<c_char>() == ';' as c_char);
continue_if!(ap.arg::<c_int>() == 0x32);
|
random_line_split
|
checkrust.rs
|
// Copyright 2018 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.
#![crate_type = "staticlib"]
#![feature(c_variadic)]
#![feature(rustc_private)]
extern crate libc;
use libc::{c_char, c_double, c_int, c_long, c_longlong};
use std::ffi::VaList;
use std::ffi::{CString, CStr};
macro_rules! continue_if {
($cond:expr) => {
if!($cond) {
return 0xff;
}
}
}
unsafe fn compare_c_str(ptr: *const c_char, val: &str) -> bool {
let cstr0 = CStr::from_ptr(ptr);
let cstr1 = CString::new(val).unwrap();
&*cstr1 == cstr0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_longlong>() == 1);
continue_if!(ap.arg::<c_int>() == 2);
continue_if!(ap.arg::<c_longlong>() == 3);
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_1(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_int>() == -1);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(ap.arg::<c_char>() == '4' as c_char);
continue_if!(ap.arg::<c_char>() == ';' as c_char);
continue_if!(ap.arg::<c_int>() == 0x32);
continue_if!(ap.arg::<c_int>() == 0x10000001);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Valid!"));
0
}
#[no_mangle]
pub unsafe extern "C" fn
|
(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 3.14f64.floor());
continue_if!(ap.arg::<c_long>() == 12);
continue_if!(ap.arg::<c_char>() == 'a' as c_char);
continue_if!(ap.arg::<c_double>().floor() == 6.18f64.floor());
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Hello"));
continue_if!(ap.arg::<c_int>() == 42);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "World"));
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_copy_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 6.28f64.floor());
continue_if!(ap.arg::<c_int>() == 16);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Skip Me!"));
ap.copy(|mut ap| {
if compare_c_str(ap.arg::<*const c_char>(), "Correct") {
0
} else {
0xff
}
})
}
|
check_list_2
|
identifier_name
|
task-comm-14.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() {
let (tx, rx) = channel();
// Spawn 10 threads each sending us back one isize.
let mut i = 10;
while (i > 0) {
println!("{}", i);
let tx = tx.clone();
thread::spawn({let i = i; move|| { child(i, &tx) }});
i = i - 1;
}
// Spawned threads are likely killed before they get a chance to send
// anything back, so we deadlock here.
i = 10;
while (i > 0) {
println!("{}", i);
rx.recv().unwrap();
i = i - 1;
}
println!("main thread exiting");
}
fn child(x: isize, tx: &Sender<isize>) {
println!("{}", x);
tx.send(x).unwrap();
}
|
#![feature(std_misc)]
|
random_line_split
|
task-comm-14.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(std_misc)]
use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() {
let (tx, rx) = channel();
// Spawn 10 threads each sending us back one isize.
let mut i = 10;
while (i > 0) {
println!("{}", i);
let tx = tx.clone();
thread::spawn({let i = i; move|| { child(i, &tx) }});
i = i - 1;
}
// Spawned threads are likely killed before they get a chance to send
// anything back, so we deadlock here.
i = 10;
while (i > 0) {
println!("{}", i);
rx.recv().unwrap();
i = i - 1;
}
println!("main thread exiting");
}
fn
|
(x: isize, tx: &Sender<isize>) {
println!("{}", x);
tx.send(x).unwrap();
}
|
child
|
identifier_name
|
task-comm-14.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(std_misc)]
use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main()
|
}
println!("main thread exiting");
}
fn child(x: isize, tx: &Sender<isize>) {
println!("{}", x);
tx.send(x).unwrap();
}
|
{
let (tx, rx) = channel();
// Spawn 10 threads each sending us back one isize.
let mut i = 10;
while (i > 0) {
println!("{}", i);
let tx = tx.clone();
thread::spawn({let i = i; move|| { child(i, &tx) }});
i = i - 1;
}
// Spawned threads are likely killed before they get a chance to send
// anything back, so we deadlock here.
i = 10;
while (i > 0) {
println!("{}", i);
rx.recv().unwrap();
i = i - 1;
|
identifier_body
|
repos.rs
|
use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn
|
() -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let handle = rt.executor();
rt.block_on(
github
.user_repos("softprops")
.iter(&Default::default())
.for_each(move |repo| {
println!("{}", repo.name);
let f = repo.languages(github.clone()).map(|langs| {
for (language, bytes_of_code) in langs {
println!("{}: {} bytes", language, bytes_of_code)
}
});
handle.spawn(f.map_err(|_| ()));
Ok(())
}),
)?;
Ok(())
}
_ => Err("example missing GITHUB_TOKEN".into()),
}
}
|
main
|
identifier_name
|
repos.rs
|
use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()>
|
});
handle.spawn(f.map_err(|_| ()));
Ok(())
}),
)?;
Ok(())
}
_ => Err("example missing GITHUB_TOKEN".into()),
}
}
|
{
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let handle = rt.executor();
rt.block_on(
github
.user_repos("softprops")
.iter(&Default::default())
.for_each(move |repo| {
println!("{}", repo.name);
let f = repo.languages(github.clone()).map(|langs| {
for (language, bytes_of_code) in langs {
println!("{}: {} bytes", language, bytes_of_code)
}
|
identifier_body
|
repos.rs
|
use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) =>
|
}),
)?;
Ok(())
}
_ => Err("example missing GITHUB_TOKEN".into()),
}
}
|
{
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let handle = rt.executor();
rt.block_on(
github
.user_repos("softprops")
.iter(&Default::default())
.for_each(move |repo| {
println!("{}", repo.name);
let f = repo.languages(github.clone()).map(|langs| {
for (language, bytes_of_code) in langs {
println!("{}: {} bytes", language, bytes_of_code)
}
});
handle.spawn(f.map_err(|_| ()));
Ok(())
|
conditional_block
|
repos.rs
|
use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let handle = rt.executor();
rt.block_on(
github
.user_repos("softprops")
.iter(&Default::default())
.for_each(move |repo| {
|
let f = repo.languages(github.clone()).map(|langs| {
for (language, bytes_of_code) in langs {
println!("{}: {} bytes", language, bytes_of_code)
}
});
handle.spawn(f.map_err(|_| ()));
Ok(())
}),
)?;
Ok(())
}
_ => Err("example missing GITHUB_TOKEN".into()),
}
}
|
println!("{}", repo.name);
|
random_line_split
|
span-preservation.rs
|
// For each of these, we should get the appropriate type mismatch error message,
// and the function should be echoed.
// aux-build:test-macros.rs
#[macro_use]
extern crate test_macros;
#[recollect_attr]
fn a() {
let x: usize = "hello"; //~ ERROR mismatched types
}
#[recollect_attr]
fn b(x: Option<isize>) -> usize {
match x {
Some(x) => { return x }, //~ ERROR mismatched types
None => 10
}
}
#[recollect_attr]
fn c() {
struct Foo {
a: usize
}
struct
|
{
a: usize,
b: usize
}
let x = Foo { a: 10isize }; //~ ERROR mismatched types
let y = Foo { a: 10, b: 10isize }; //~ ERROR has no field named `b`
}
#[recollect_attr]
extern "C" fn bar() {
0 //~ ERROR mismatched types
}
#[recollect_attr]
extern "C" fn baz() {
0 //~ ERROR mismatched types
}
#[recollect_attr]
extern "Rust" fn rust_abi() {
0 //~ ERROR mismatched types
}
#[recollect_attr]
extern "\x43" fn c_abi_escaped() {
0 //~ ERROR mismatched types
}
fn main() {}
|
Bar
|
identifier_name
|
span-preservation.rs
|
// For each of these, we should get the appropriate type mismatch error message,
// and the function should be echoed.
// aux-build:test-macros.rs
#[macro_use]
extern crate test_macros;
#[recollect_attr]
fn a() {
let x: usize = "hello"; //~ ERROR mismatched types
}
#[recollect_attr]
fn b(x: Option<isize>) -> usize {
match x {
Some(x) => { return x }, //~ ERROR mismatched types
None => 10
}
}
#[recollect_attr]
fn c() {
struct Foo {
a: usize
}
struct Bar {
a: usize,
b: usize
}
let x = Foo { a: 10isize }; //~ ERROR mismatched types
let y = Foo { a: 10, b: 10isize }; //~ ERROR has no field named `b`
}
#[recollect_attr]
extern "C" fn bar() {
0 //~ ERROR mismatched types
}
#[recollect_attr]
extern "C" fn baz()
|
#[recollect_attr]
extern "Rust" fn rust_abi() {
0 //~ ERROR mismatched types
}
#[recollect_attr]
extern "\x43" fn c_abi_escaped() {
0 //~ ERROR mismatched types
}
fn main() {}
|
{
0 //~ ERROR mismatched types
}
|
identifier_body
|
rowiterator.rs
|
// Copyright 2016 Claus Matzinger
//
// 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
//
|
extern crate serde_json;
use row::Row;
use std::collections::HashMap;
use self::serde_json::Value;
use std::rc::Rc;
#[derive(Debug)]
pub struct RowIterator {
rows: Vec<Value>,
header: Rc<HashMap<String, usize>>,
}
impl RowIterator {
pub fn new(mut rows: Vec<Value>, header: HashMap<String, usize>) -> RowIterator {
let headers = Rc::new(header);
rows.reverse();
RowIterator {
rows: rows,
header: headers,
}
}
pub fn len(&self) -> usize {
self.rows.len()
}
}
impl Iterator for RowIterator {
type Item = Row;
fn next(&mut self) -> Option<Row> {
match self.rows.pop() {
Some(i) => Some(Row::new(i.as_array().unwrap().to_vec(), self.header.clone())),
_ => None,
}
}
}
|
// 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.
|
random_line_split
|
rowiterator.rs
|
// Copyright 2016 Claus Matzinger
//
// 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.
extern crate serde_json;
use row::Row;
use std::collections::HashMap;
use self::serde_json::Value;
use std::rc::Rc;
#[derive(Debug)]
pub struct
|
{
rows: Vec<Value>,
header: Rc<HashMap<String, usize>>,
}
impl RowIterator {
pub fn new(mut rows: Vec<Value>, header: HashMap<String, usize>) -> RowIterator {
let headers = Rc::new(header);
rows.reverse();
RowIterator {
rows: rows,
header: headers,
}
}
pub fn len(&self) -> usize {
self.rows.len()
}
}
impl Iterator for RowIterator {
type Item = Row;
fn next(&mut self) -> Option<Row> {
match self.rows.pop() {
Some(i) => Some(Row::new(i.as_array().unwrap().to_vec(), self.header.clone())),
_ => None,
}
}
}
|
RowIterator
|
identifier_name
|
rowiterator.rs
|
// Copyright 2016 Claus Matzinger
//
// 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.
extern crate serde_json;
use row::Row;
use std::collections::HashMap;
use self::serde_json::Value;
use std::rc::Rc;
#[derive(Debug)]
pub struct RowIterator {
rows: Vec<Value>,
header: Rc<HashMap<String, usize>>,
}
impl RowIterator {
pub fn new(mut rows: Vec<Value>, header: HashMap<String, usize>) -> RowIterator
|
pub fn len(&self) -> usize {
self.rows.len()
}
}
impl Iterator for RowIterator {
type Item = Row;
fn next(&mut self) -> Option<Row> {
match self.rows.pop() {
Some(i) => Some(Row::new(i.as_array().unwrap().to_vec(), self.header.clone())),
_ => None,
}
}
}
|
{
let headers = Rc::new(header);
rows.reverse();
RowIterator {
rows: rows,
header: headers,
}
}
|
identifier_body
|
reset.rs
|
// Copyright 2021 lowRISC contributors.
//
// 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
//
// https://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.
//
// SPDX-License-Identifier: Apache-2.0
//! Data related to resets.
use crate::io::Read;
use crate::io::Write;
use crate::protocol::wire::FromWireError;
use crate::protocol::wire::FromWire;
use crate::protocol::wire::ToWireError;
use crate::protocol::wire::ToWire;
/// The source of the last reset.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct ResetSource {
/// Power on reset
pub power_on_reset: bool,
/// Low power exit
pub low_power_reset: bool,
/// Watchdog reset
pub watchdog_reset: bool,
/// Lockup reset
pub lockup_reset: bool,
/// SYSRESET
pub sysreset: bool,
/// Software initiated reset through PMU_GLOBAL_RESET
pub software_reset: bool,
/// Fast burnout circuit
pub fast_burnout_circuit: bool,
/// Security breach reset
pub security_breach_reset: bool,
|
pub const RESET_SOURCE_LEN: usize = 8;
impl<'a> FromWire<'a> for ResetSource {
fn from_wire<R: Read<'a>>(mut r: R) -> Result<Self, FromWireError> {
let power_on_reset = r.read_be::<u8>()?!= 0;
let low_power_reset = r.read_be::<u8>()?!= 0;
let watchdog_reset = r.read_be::<u8>()?!= 0;
let lockup_reset = r.read_be::<u8>()?!= 0;
let sysreset = r.read_be::<u8>()?!= 0;
let software_reset = r.read_be::<u8>()?!= 0;
let fast_burnout_circuit = r.read_be::<u8>()?!= 0;
let security_breach_reset = r.read_be::<u8>()?!= 0;
Ok(Self {
power_on_reset,
low_power_reset,
watchdog_reset,
lockup_reset,
sysreset,
software_reset,
fast_burnout_circuit,
security_breach_reset,
})
}
}
impl ToWire for ResetSource {
fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> {
w.write_be(if self.power_on_reset { 1 } else { 0u8 })?;
w.write_be(if self.low_power_reset { 1 } else { 0u8 })?;
w.write_be(if self.watchdog_reset { 1 } else { 0u8 })?;
w.write_be(if self.lockup_reset { 1 } else { 0u8 })?;
w.write_be(if self.sysreset { 1 } else { 0u8 })?;
w.write_be(if self.software_reset { 1 } else { 0u8 })?;
w.write_be(if self.fast_burnout_circuit { 1 } else { 0u8 })?;
w.write_be(if self.security_breach_reset { 1 } else { 0u8 })?;
Ok(())
}
}
|
}
/// The length of a ResetSource on the wire, in bytes.
|
random_line_split
|
reset.rs
|
// Copyright 2021 lowRISC contributors.
//
// 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
//
// https://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.
//
// SPDX-License-Identifier: Apache-2.0
//! Data related to resets.
use crate::io::Read;
use crate::io::Write;
use crate::protocol::wire::FromWireError;
use crate::protocol::wire::FromWire;
use crate::protocol::wire::ToWireError;
use crate::protocol::wire::ToWire;
/// The source of the last reset.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct ResetSource {
/// Power on reset
pub power_on_reset: bool,
/// Low power exit
pub low_power_reset: bool,
/// Watchdog reset
pub watchdog_reset: bool,
/// Lockup reset
pub lockup_reset: bool,
/// SYSRESET
pub sysreset: bool,
/// Software initiated reset through PMU_GLOBAL_RESET
pub software_reset: bool,
/// Fast burnout circuit
pub fast_burnout_circuit: bool,
/// Security breach reset
pub security_breach_reset: bool,
}
/// The length of a ResetSource on the wire, in bytes.
pub const RESET_SOURCE_LEN: usize = 8;
impl<'a> FromWire<'a> for ResetSource {
fn from_wire<R: Read<'a>>(mut r: R) -> Result<Self, FromWireError> {
let power_on_reset = r.read_be::<u8>()?!= 0;
let low_power_reset = r.read_be::<u8>()?!= 0;
let watchdog_reset = r.read_be::<u8>()?!= 0;
let lockup_reset = r.read_be::<u8>()?!= 0;
let sysreset = r.read_be::<u8>()?!= 0;
let software_reset = r.read_be::<u8>()?!= 0;
let fast_burnout_circuit = r.read_be::<u8>()?!= 0;
let security_breach_reset = r.read_be::<u8>()?!= 0;
Ok(Self {
power_on_reset,
low_power_reset,
watchdog_reset,
lockup_reset,
sysreset,
software_reset,
fast_burnout_circuit,
security_breach_reset,
})
}
}
impl ToWire for ResetSource {
fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> {
w.write_be(if self.power_on_reset { 1 } else { 0u8 })?;
w.write_be(if self.low_power_reset { 1 } else { 0u8 })?;
w.write_be(if self.watchdog_reset
|
else { 0u8 })?;
w.write_be(if self.lockup_reset { 1 } else { 0u8 })?;
w.write_be(if self.sysreset { 1 } else { 0u8 })?;
w.write_be(if self.software_reset { 1 } else { 0u8 })?;
w.write_be(if self.fast_burnout_circuit { 1 } else { 0u8 })?;
w.write_be(if self.security_breach_reset { 1 } else { 0u8 })?;
Ok(())
}
}
|
{ 1 }
|
conditional_block
|
reset.rs
|
// Copyright 2021 lowRISC contributors.
//
// 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
//
// https://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.
//
// SPDX-License-Identifier: Apache-2.0
//! Data related to resets.
use crate::io::Read;
use crate::io::Write;
use crate::protocol::wire::FromWireError;
use crate::protocol::wire::FromWire;
use crate::protocol::wire::ToWireError;
use crate::protocol::wire::ToWire;
/// The source of the last reset.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct ResetSource {
/// Power on reset
pub power_on_reset: bool,
/// Low power exit
pub low_power_reset: bool,
/// Watchdog reset
pub watchdog_reset: bool,
/// Lockup reset
pub lockup_reset: bool,
/// SYSRESET
pub sysreset: bool,
/// Software initiated reset through PMU_GLOBAL_RESET
pub software_reset: bool,
/// Fast burnout circuit
pub fast_burnout_circuit: bool,
/// Security breach reset
pub security_breach_reset: bool,
}
/// The length of a ResetSource on the wire, in bytes.
pub const RESET_SOURCE_LEN: usize = 8;
impl<'a> FromWire<'a> for ResetSource {
fn
|
<R: Read<'a>>(mut r: R) -> Result<Self, FromWireError> {
let power_on_reset = r.read_be::<u8>()?!= 0;
let low_power_reset = r.read_be::<u8>()?!= 0;
let watchdog_reset = r.read_be::<u8>()?!= 0;
let lockup_reset = r.read_be::<u8>()?!= 0;
let sysreset = r.read_be::<u8>()?!= 0;
let software_reset = r.read_be::<u8>()?!= 0;
let fast_burnout_circuit = r.read_be::<u8>()?!= 0;
let security_breach_reset = r.read_be::<u8>()?!= 0;
Ok(Self {
power_on_reset,
low_power_reset,
watchdog_reset,
lockup_reset,
sysreset,
software_reset,
fast_burnout_circuit,
security_breach_reset,
})
}
}
impl ToWire for ResetSource {
fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> {
w.write_be(if self.power_on_reset { 1 } else { 0u8 })?;
w.write_be(if self.low_power_reset { 1 } else { 0u8 })?;
w.write_be(if self.watchdog_reset { 1 } else { 0u8 })?;
w.write_be(if self.lockup_reset { 1 } else { 0u8 })?;
w.write_be(if self.sysreset { 1 } else { 0u8 })?;
w.write_be(if self.software_reset { 1 } else { 0u8 })?;
w.write_be(if self.fast_burnout_circuit { 1 } else { 0u8 })?;
w.write_be(if self.security_breach_reset { 1 } else { 0u8 })?;
Ok(())
}
}
|
from_wire
|
identifier_name
|
reset.rs
|
// Copyright 2021 lowRISC contributors.
//
// 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
//
// https://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.
//
// SPDX-License-Identifier: Apache-2.0
//! Data related to resets.
use crate::io::Read;
use crate::io::Write;
use crate::protocol::wire::FromWireError;
use crate::protocol::wire::FromWire;
use crate::protocol::wire::ToWireError;
use crate::protocol::wire::ToWire;
/// The source of the last reset.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct ResetSource {
/// Power on reset
pub power_on_reset: bool,
/// Low power exit
pub low_power_reset: bool,
/// Watchdog reset
pub watchdog_reset: bool,
/// Lockup reset
pub lockup_reset: bool,
/// SYSRESET
pub sysreset: bool,
/// Software initiated reset through PMU_GLOBAL_RESET
pub software_reset: bool,
/// Fast burnout circuit
pub fast_burnout_circuit: bool,
/// Security breach reset
pub security_breach_reset: bool,
}
/// The length of a ResetSource on the wire, in bytes.
pub const RESET_SOURCE_LEN: usize = 8;
impl<'a> FromWire<'a> for ResetSource {
fn from_wire<R: Read<'a>>(mut r: R) -> Result<Self, FromWireError> {
let power_on_reset = r.read_be::<u8>()?!= 0;
let low_power_reset = r.read_be::<u8>()?!= 0;
let watchdog_reset = r.read_be::<u8>()?!= 0;
let lockup_reset = r.read_be::<u8>()?!= 0;
let sysreset = r.read_be::<u8>()?!= 0;
let software_reset = r.read_be::<u8>()?!= 0;
let fast_burnout_circuit = r.read_be::<u8>()?!= 0;
let security_breach_reset = r.read_be::<u8>()?!= 0;
Ok(Self {
power_on_reset,
low_power_reset,
watchdog_reset,
lockup_reset,
sysreset,
software_reset,
fast_burnout_circuit,
security_breach_reset,
})
}
}
impl ToWire for ResetSource {
fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError>
|
}
|
{
w.write_be(if self.power_on_reset { 1 } else { 0u8 })?;
w.write_be(if self.low_power_reset { 1 } else { 0u8 })?;
w.write_be(if self.watchdog_reset { 1 } else { 0u8 })?;
w.write_be(if self.lockup_reset { 1 } else { 0u8 })?;
w.write_be(if self.sysreset { 1 } else { 0u8 })?;
w.write_be(if self.software_reset { 1 } else { 0u8 })?;
w.write_be(if self.fast_burnout_circuit { 1 } else { 0u8 })?;
w.write_be(if self.security_breach_reset { 1 } else { 0u8 })?;
Ok(())
}
|
identifier_body
|
osm2mimir.rs
|
use clap::Parser;
use futures::stream::StreamExt;
use mimir::domain::model::configuration::ContainerConfig;
use snafu::{ResultExt, Snafu};
use tracing::{instrument, warn};
use mimir::adapters::secondary::elasticsearch::{self, ElasticsearchStorage};
use mimir::domain::ports::primary::{generate_index::GenerateIndex, list_documents::ListDocuments};
use mimir::domain::ports::secondary::remote::Remote;
use mimirsbrunn::admin_geofinder::AdminGeoFinder;
use mimirsbrunn::osm_reader::street::streets;
use mimirsbrunn::settings::osm2mimir as settings;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Settings (Configuration or CLI) Error: {}", source))]
Settings { source: settings::Error },
#[snafu(display("OSM PBF Reader Error: {}", source))]
OsmPbfReader {
source: mimirsbrunn::osm_reader::Error,
},
#[snafu(display("Elasticsearch Connection Pool {}", source))]
ElasticsearchConnection {
source: mimir::domain::ports::secondary::remote::Error,
},
#[snafu(display("Street Extraction from OSM PBF Error {}", source))]
StreetOsmExtraction {
source: mimirsbrunn::osm_reader::street::Error,
},
#[snafu(display("Street Index Creation Error {}", source))]
StreetIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(display("Poi Extraction from OSM PBF Error {}", source))]
PoiOsmExtraction {
source: mimirsbrunn::osm_reader::poi::Error,
},
#[snafu(display("Poi Index Creation Error {}", source))]
PoiIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(display("Elasticsearch Configuration {}", source))]
StreetElasticsearchConfiguration { source: common::config::Error },
#[snafu(display("Execution Error {}", source))]
Execution { source: Box<dyn std::error::Error> },
}
fn main() -> Result<(), Error> {
let opts = settings::Opts::parse();
let settings = settings::Settings::new(&opts).context(SettingsSnafu)?;
match opts.cmd {
settings::Command::Run => mimirsbrunn::utils::launch::launch_with_runtime(
settings.nb_threads,
run(opts, settings),
)
.context(ExecutionSnafu),
settings::Command::Config => {
println!("{}", serde_json::to_string_pretty(&settings).unwrap());
Ok(())
}
}
}
async fn run(
opts: settings::Opts,
settings: settings::Settings,
) -> Result<(), Box<dyn std::error::Error>> {
let mut osm_reader =
mimirsbrunn::osm_reader::make_osm_reader(&opts.input).context(OsmPbfReaderSnafu)?;
let client = elasticsearch::remote::connection_pool_url(&settings.elasticsearch.url)
.conn(settings.elasticsearch.clone())
.await
.context(ElasticsearchConnectionSnafu)?;
let admins_geofinder: AdminGeoFinder = match client.list_documents().await {
Ok(stream) => {
stream
.map(|admin| admin.expect("could not parse admin"))
.collect()
.await
}
Err(err) => {
warn!(
"administratives regions not found in Elasticsearch. {:?}",
err
);
std::iter::empty().collect()
}
};
if settings.streets.import {
let streets = streets(
&mut osm_reader,
&admins_geofinder,
&settings.streets.exclusions,
#[cfg(feature = "db-storage")]
settings.database.as_ref(),
)
.context(StreetOsmExtractionSnafu)?;
import_streets(streets, &client, &settings.container_street).await?;
}
if settings.pois.import
|
Ok(())
}
#[instrument(skip_all)]
async fn import_streets(
streets: Vec<places::street::Street>,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
let streets = streets
.into_iter()
.map(|street| street.set_weight_from_admins());
let _index = client
.generate_index(config, futures::stream::iter(streets))
.await
.context(StreetIndexCreationSnafu)?;
Ok(())
}
#[instrument(skip_all)]
async fn import_pois(
osm_reader: &mut mimirsbrunn::osm_reader::OsmPbfReader,
admins_geofinder: &AdminGeoFinder,
poi_config: &mimirsbrunn::osm_reader::poi::PoiConfig,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
// This function rely on AdminGeoFinder::get_objs_and_deps
// which use all available cpu/cores to decode osm file and cannot be limited by tokio runtime
let pois = mimirsbrunn::osm_reader::poi::pois(osm_reader, poi_config, admins_geofinder)
.context(PoiOsmExtractionSnafu)?;
let pois: Vec<places::poi::Poi> = futures::stream::iter(pois)
.map(mimirsbrunn::osm_reader::poi::compute_weight)
.then(|poi| mimirsbrunn::osm_reader::poi::add_address(client, poi))
.collect()
.await;
let _ = client
.generate_index(config, futures::stream::iter(pois))
.await
.context(PoiIndexCreationSnafu)?;
Ok(())
}
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::elasticsearch::ElasticsearchStorage;
// use common::config::load_es_config_for;
// use common::document::ContainerDocument;
// use futures::TryStreamExt;
// use mimir::domain::model::query::Query;
// use mimir::domain::ports::primary::list_documents::ListDocuments;
// use mimir::domain::ports::primary::search_documents::SearchDocuments;
// use mimir::{adapters::secondary::elasticsearch::remote, utils::docker};
// use mimirsbrunn::admin::index_cosmogony;
// use places::{admin::Admin, street::Street, Place};
// use serial_test::serial;
// use structopt::StructOpt;
//
// fn elasticsearch_test_url() -> String {
// std::env::var(elasticsearch::remote::ES_TEST_KEY).expect("env var")
// }
//
// async fn index_cosmogony_admins(client: &ElasticsearchStorage) {
// index_cosmogony(
// "./tests/fixtures/cosmogony.json".into(),
// vec![],
// load_es_config_for(
// None,
// None,
// vec!["container.dataset=osm2mimir-test".into()],
// String::from("fr"),
// )
// .unwrap(),
// client,
// )
// .await
// .unwrap()
// }
//
// #[tokio::test]
// #[serial]
// async fn should_correctly_index_osm_streets_and_pois() {
// docker::initialize()
// .await
// .expect("elasticsearch docker initialization");
//
// // Now we query the index we just created. Since it's a small cosmogony file with few entries,
// // we'll just list all the documents in the index, and check them.
// let pool = remote::connection_test_pool()
// .await
// .expect("Elasticsearch Connection Pool");
//
// let client = pool
// .conn(ES_DEFAULT_TIMEOUT, ES_DEFAULT_VERSION_REQ)
// .await
// .expect("Elasticsearch Connection Established");
//
// index_cosmogony_admins(&client).await;
//
// let storage_args = if cfg!(feature = "db-storage") {
// vec!["--db-file=test-db.sqlite3", "--db-buffer-size=10"]
// } else {
// vec![]
// };
//
// let args = Args::from_iter(
// [
// "osm2mimir",
// "--input=./tests/fixtures/osm_fixture.osm.pbf",
// "--dataset=osm2mimir-test",
// "--import-way=true",
// "--import-poi=true",
// &format!("-c={}", elasticsearch_test_url()),
// ]
// .iter()
// .copied()
// .chain(storage_args),
// );
//
// let _res = mimirsbrunn::utils::launch_async_args(run, args).await;
//
// let search = |query: &str| {
// let client = client.clone();
// let query: String = query.into();
// async move {
// client
// .search_documents(
// vec![
// Street::static_doc_type().into(),
// Poi::static_doc_type().into(),
// ],
// Query::QueryString(format!("full_label.prefix:({})", query)),
// )
// .await
// .unwrap()
// .into_iter()
// .map(|json| serde_json::from_value::<Place>(json).unwrap())
// .collect::<Vec<Place>>()
// }
// };
//
// let streets: Vec<Street> = client
// .list_documents()
// .await
// .unwrap()
// .try_collect()
// .await
// .unwrap();
// assert_eq!(streets.len(), 13);
//
// // Basic street search
// let results = search("Rue des Près").await;
// assert_eq!(results[0].label(), "Rue des Près (Livry-sur-Seine)");
// assert_eq!(
// results
// .iter()
// .filter(
// |place| place.is_street() && place.label() == "Rue des Près (Livry-sur-Seine)"
// )
// .count(),
// 1,
// "Only 1 'Rue des Près' is expected"
// );
//
// // All ways with same name in the same city are merged into a single street
// let results = search("Rue du Four à Chaux").await;
// assert_eq!(
// results.iter()
// .filter(|place| place.label() == "Rue du Four à Chaux (Livry-sur-Seine)")
// .count(),
// 1,
// "Only 1 'Rue du Four à Chaux' is expected as all ways the same name should be merged into 1 street."
// );
// assert_eq!(
// results[0].id(),
// "street:osm:way:40812939",
// "The way with minimum way_id should be used as street id."
// );
//
// // Street admin is based on a middle node.
// // (Here the first node is located outside Melun)
// let results = search("Rue Marcel Houdet").await;
// assert_eq!(results[0].label(), "Rue Marcel Houdet (Melun)");
// assert!(results[0]
// .admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|a| a.name == "Melun"));
//
// // Basic search for Poi by label
// let res = search("Le-Mée-sur-Seine Courtilleraies").await;
// assert_eq!(
// res[0].poi().expect("Place should be a poi").poi_type.id,
// "poi_type:amenity:post_office"
// );
//
// // highway=bus_stop should not be indexed
// let res = search("Grand Châtelet").await;
// assert!(
// res.is_empty(),
// "'Grand Châtelet' (highway=bus_stop) should not be found."
// );
//
// // "Rue de Villiers" is at the exact neighborhood between two cities, a
// // document must be added for both.
// let results = search("Rue de Villiers").await;
// assert!(["Neuilly-sur-Seine", "Levallois-Perret"]
// .iter()
// .all(|city| {
// results.iter().any(|poi| {
// poi.admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|admin| &admin.name == city)
// })
// }));
// }
// }
|
{
import_pois(
&mut osm_reader,
&admins_geofinder,
&settings.pois.config.clone().unwrap_or_default(),
&client,
&settings.container_poi,
)
.await?;
}
|
conditional_block
|
osm2mimir.rs
|
use clap::Parser;
use futures::stream::StreamExt;
use mimir::domain::model::configuration::ContainerConfig;
use snafu::{ResultExt, Snafu};
use tracing::{instrument, warn};
use mimir::adapters::secondary::elasticsearch::{self, ElasticsearchStorage};
use mimir::domain::ports::primary::{generate_index::GenerateIndex, list_documents::ListDocuments};
use mimir::domain::ports::secondary::remote::Remote;
use mimirsbrunn::admin_geofinder::AdminGeoFinder;
use mimirsbrunn::osm_reader::street::streets;
use mimirsbrunn::settings::osm2mimir as settings;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Settings (Configuration or CLI) Error: {}", source))]
Settings { source: settings::Error },
#[snafu(display("OSM PBF Reader Error: {}", source))]
OsmPbfReader {
source: mimirsbrunn::osm_reader::Error,
},
#[snafu(display("Elasticsearch Connection Pool {}", source))]
ElasticsearchConnection {
source: mimir::domain::ports::secondary::remote::Error,
},
#[snafu(display("Street Extraction from OSM PBF Error {}", source))]
StreetOsmExtraction {
source: mimirsbrunn::osm_reader::street::Error,
},
#[snafu(display("Street Index Creation Error {}", source))]
StreetIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(display("Poi Extraction from OSM PBF Error {}", source))]
PoiOsmExtraction {
source: mimirsbrunn::osm_reader::poi::Error,
},
#[snafu(display("Poi Index Creation Error {}", source))]
PoiIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(display("Elasticsearch Configuration {}", source))]
StreetElasticsearchConfiguration { source: common::config::Error },
#[snafu(display("Execution Error {}", source))]
Execution { source: Box<dyn std::error::Error> },
}
fn main() -> Result<(), Error> {
let opts = settings::Opts::parse();
let settings = settings::Settings::new(&opts).context(SettingsSnafu)?;
match opts.cmd {
settings::Command::Run => mimirsbrunn::utils::launch::launch_with_runtime(
settings.nb_threads,
run(opts, settings),
)
.context(ExecutionSnafu),
settings::Command::Config => {
println!("{}", serde_json::to_string_pretty(&settings).unwrap());
Ok(())
}
}
}
async fn run(
opts: settings::Opts,
settings: settings::Settings,
) -> Result<(), Box<dyn std::error::Error>> {
let mut osm_reader =
mimirsbrunn::osm_reader::make_osm_reader(&opts.input).context(OsmPbfReaderSnafu)?;
let client = elasticsearch::remote::connection_pool_url(&settings.elasticsearch.url)
.conn(settings.elasticsearch.clone())
.await
.context(ElasticsearchConnectionSnafu)?;
let admins_geofinder: AdminGeoFinder = match client.list_documents().await {
Ok(stream) => {
stream
.map(|admin| admin.expect("could not parse admin"))
.collect()
.await
}
Err(err) => {
warn!(
"administratives regions not found in Elasticsearch. {:?}",
err
);
std::iter::empty().collect()
}
};
if settings.streets.import {
let streets = streets(
&mut osm_reader,
&admins_geofinder,
&settings.streets.exclusions,
#[cfg(feature = "db-storage")]
settings.database.as_ref(),
)
.context(StreetOsmExtractionSnafu)?;
import_streets(streets, &client, &settings.container_street).await?;
}
if settings.pois.import {
import_pois(
&mut osm_reader,
&admins_geofinder,
&settings.pois.config.clone().unwrap_or_default(),
&client,
&settings.container_poi,
)
.await?;
}
Ok(())
}
#[instrument(skip_all)]
async fn import_streets(
streets: Vec<places::street::Street>,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
let streets = streets
.into_iter()
.map(|street| street.set_weight_from_admins());
let _index = client
.generate_index(config, futures::stream::iter(streets))
.await
.context(StreetIndexCreationSnafu)?;
Ok(())
}
#[instrument(skip_all)]
async fn import_pois(
osm_reader: &mut mimirsbrunn::osm_reader::OsmPbfReader,
admins_geofinder: &AdminGeoFinder,
poi_config: &mimirsbrunn::osm_reader::poi::PoiConfig,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error>
|
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::elasticsearch::ElasticsearchStorage;
// use common::config::load_es_config_for;
// use common::document::ContainerDocument;
// use futures::TryStreamExt;
// use mimir::domain::model::query::Query;
// use mimir::domain::ports::primary::list_documents::ListDocuments;
// use mimir::domain::ports::primary::search_documents::SearchDocuments;
// use mimir::{adapters::secondary::elasticsearch::remote, utils::docker};
// use mimirsbrunn::admin::index_cosmogony;
// use places::{admin::Admin, street::Street, Place};
// use serial_test::serial;
// use structopt::StructOpt;
//
// fn elasticsearch_test_url() -> String {
// std::env::var(elasticsearch::remote::ES_TEST_KEY).expect("env var")
// }
//
// async fn index_cosmogony_admins(client: &ElasticsearchStorage) {
// index_cosmogony(
// "./tests/fixtures/cosmogony.json".into(),
// vec![],
// load_es_config_for(
// None,
// None,
// vec!["container.dataset=osm2mimir-test".into()],
// String::from("fr"),
// )
// .unwrap(),
// client,
// )
// .await
// .unwrap()
// }
//
// #[tokio::test]
// #[serial]
// async fn should_correctly_index_osm_streets_and_pois() {
// docker::initialize()
// .await
// .expect("elasticsearch docker initialization");
//
// // Now we query the index we just created. Since it's a small cosmogony file with few entries,
// // we'll just list all the documents in the index, and check them.
// let pool = remote::connection_test_pool()
// .await
// .expect("Elasticsearch Connection Pool");
//
// let client = pool
// .conn(ES_DEFAULT_TIMEOUT, ES_DEFAULT_VERSION_REQ)
// .await
// .expect("Elasticsearch Connection Established");
//
// index_cosmogony_admins(&client).await;
//
// let storage_args = if cfg!(feature = "db-storage") {
// vec!["--db-file=test-db.sqlite3", "--db-buffer-size=10"]
// } else {
// vec![]
// };
//
// let args = Args::from_iter(
// [
// "osm2mimir",
// "--input=./tests/fixtures/osm_fixture.osm.pbf",
// "--dataset=osm2mimir-test",
// "--import-way=true",
// "--import-poi=true",
// &format!("-c={}", elasticsearch_test_url()),
// ]
// .iter()
// .copied()
// .chain(storage_args),
// );
//
// let _res = mimirsbrunn::utils::launch_async_args(run, args).await;
//
// let search = |query: &str| {
// let client = client.clone();
// let query: String = query.into();
// async move {
// client
// .search_documents(
// vec![
// Street::static_doc_type().into(),
// Poi::static_doc_type().into(),
// ],
// Query::QueryString(format!("full_label.prefix:({})", query)),
// )
// .await
// .unwrap()
// .into_iter()
// .map(|json| serde_json::from_value::<Place>(json).unwrap())
// .collect::<Vec<Place>>()
// }
// };
//
// let streets: Vec<Street> = client
// .list_documents()
// .await
// .unwrap()
// .try_collect()
// .await
// .unwrap();
// assert_eq!(streets.len(), 13);
//
// // Basic street search
// let results = search("Rue des Près").await;
// assert_eq!(results[0].label(), "Rue des Près (Livry-sur-Seine)");
// assert_eq!(
// results
// .iter()
// .filter(
// |place| place.is_street() && place.label() == "Rue des Près (Livry-sur-Seine)"
// )
// .count(),
// 1,
// "Only 1 'Rue des Près' is expected"
// );
//
// // All ways with same name in the same city are merged into a single street
// let results = search("Rue du Four à Chaux").await;
// assert_eq!(
// results.iter()
// .filter(|place| place.label() == "Rue du Four à Chaux (Livry-sur-Seine)")
// .count(),
// 1,
// "Only 1 'Rue du Four à Chaux' is expected as all ways the same name should be merged into 1 street."
// );
// assert_eq!(
// results[0].id(),
// "street:osm:way:40812939",
// "The way with minimum way_id should be used as street id."
// );
//
// // Street admin is based on a middle node.
// // (Here the first node is located outside Melun)
// let results = search("Rue Marcel Houdet").await;
// assert_eq!(results[0].label(), "Rue Marcel Houdet (Melun)");
// assert!(results[0]
// .admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|a| a.name == "Melun"));
//
// // Basic search for Poi by label
// let res = search("Le-Mée-sur-Seine Courtilleraies").await;
// assert_eq!(
// res[0].poi().expect("Place should be a poi").poi_type.id,
// "poi_type:amenity:post_office"
// );
//
// // highway=bus_stop should not be indexed
// let res = search("Grand Châtelet").await;
// assert!(
// res.is_empty(),
// "'Grand Châtelet' (highway=bus_stop) should not be found."
// );
//
// // "Rue de Villiers" is at the exact neighborhood between two cities, a
// // document must be added for both.
// let results = search("Rue de Villiers").await;
// assert!(["Neuilly-sur-Seine", "Levallois-Perret"]
// .iter()
// .all(|city| {
// results.iter().any(|poi| {
// poi.admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|admin| &admin.name == city)
// })
// }));
// }
// }
|
{
// This function rely on AdminGeoFinder::get_objs_and_deps
// which use all available cpu/cores to decode osm file and cannot be limited by tokio runtime
let pois = mimirsbrunn::osm_reader::poi::pois(osm_reader, poi_config, admins_geofinder)
.context(PoiOsmExtractionSnafu)?;
let pois: Vec<places::poi::Poi> = futures::stream::iter(pois)
.map(mimirsbrunn::osm_reader::poi::compute_weight)
.then(|poi| mimirsbrunn::osm_reader::poi::add_address(client, poi))
.collect()
.await;
let _ = client
.generate_index(config, futures::stream::iter(pois))
.await
.context(PoiIndexCreationSnafu)?;
Ok(())
}
|
identifier_body
|
osm2mimir.rs
|
use clap::Parser;
use futures::stream::StreamExt;
use mimir::domain::model::configuration::ContainerConfig;
use snafu::{ResultExt, Snafu};
use tracing::{instrument, warn};
use mimir::adapters::secondary::elasticsearch::{self, ElasticsearchStorage};
use mimir::domain::ports::primary::{generate_index::GenerateIndex, list_documents::ListDocuments};
use mimir::domain::ports::secondary::remote::Remote;
use mimirsbrunn::admin_geofinder::AdminGeoFinder;
use mimirsbrunn::osm_reader::street::streets;
use mimirsbrunn::settings::osm2mimir as settings;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Settings (Configuration or CLI) Error: {}", source))]
Settings { source: settings::Error },
#[snafu(display("OSM PBF Reader Error: {}", source))]
OsmPbfReader {
source: mimirsbrunn::osm_reader::Error,
},
#[snafu(display("Elasticsearch Connection Pool {}", source))]
ElasticsearchConnection {
source: mimir::domain::ports::secondary::remote::Error,
},
#[snafu(display("Street Extraction from OSM PBF Error {}", source))]
StreetOsmExtraction {
source: mimirsbrunn::osm_reader::street::Error,
},
#[snafu(display("Street Index Creation Error {}", source))]
|
},
#[snafu(display("Poi Extraction from OSM PBF Error {}", source))]
PoiOsmExtraction {
source: mimirsbrunn::osm_reader::poi::Error,
},
#[snafu(display("Poi Index Creation Error {}", source))]
PoiIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(display("Elasticsearch Configuration {}", source))]
StreetElasticsearchConfiguration { source: common::config::Error },
#[snafu(display("Execution Error {}", source))]
Execution { source: Box<dyn std::error::Error> },
}
fn main() -> Result<(), Error> {
let opts = settings::Opts::parse();
let settings = settings::Settings::new(&opts).context(SettingsSnafu)?;
match opts.cmd {
settings::Command::Run => mimirsbrunn::utils::launch::launch_with_runtime(
settings.nb_threads,
run(opts, settings),
)
.context(ExecutionSnafu),
settings::Command::Config => {
println!("{}", serde_json::to_string_pretty(&settings).unwrap());
Ok(())
}
}
}
async fn run(
opts: settings::Opts,
settings: settings::Settings,
) -> Result<(), Box<dyn std::error::Error>> {
let mut osm_reader =
mimirsbrunn::osm_reader::make_osm_reader(&opts.input).context(OsmPbfReaderSnafu)?;
let client = elasticsearch::remote::connection_pool_url(&settings.elasticsearch.url)
.conn(settings.elasticsearch.clone())
.await
.context(ElasticsearchConnectionSnafu)?;
let admins_geofinder: AdminGeoFinder = match client.list_documents().await {
Ok(stream) => {
stream
.map(|admin| admin.expect("could not parse admin"))
.collect()
.await
}
Err(err) => {
warn!(
"administratives regions not found in Elasticsearch. {:?}",
err
);
std::iter::empty().collect()
}
};
if settings.streets.import {
let streets = streets(
&mut osm_reader,
&admins_geofinder,
&settings.streets.exclusions,
#[cfg(feature = "db-storage")]
settings.database.as_ref(),
)
.context(StreetOsmExtractionSnafu)?;
import_streets(streets, &client, &settings.container_street).await?;
}
if settings.pois.import {
import_pois(
&mut osm_reader,
&admins_geofinder,
&settings.pois.config.clone().unwrap_or_default(),
&client,
&settings.container_poi,
)
.await?;
}
Ok(())
}
#[instrument(skip_all)]
async fn import_streets(
streets: Vec<places::street::Street>,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
let streets = streets
.into_iter()
.map(|street| street.set_weight_from_admins());
let _index = client
.generate_index(config, futures::stream::iter(streets))
.await
.context(StreetIndexCreationSnafu)?;
Ok(())
}
#[instrument(skip_all)]
async fn import_pois(
osm_reader: &mut mimirsbrunn::osm_reader::OsmPbfReader,
admins_geofinder: &AdminGeoFinder,
poi_config: &mimirsbrunn::osm_reader::poi::PoiConfig,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
// This function rely on AdminGeoFinder::get_objs_and_deps
// which use all available cpu/cores to decode osm file and cannot be limited by tokio runtime
let pois = mimirsbrunn::osm_reader::poi::pois(osm_reader, poi_config, admins_geofinder)
.context(PoiOsmExtractionSnafu)?;
let pois: Vec<places::poi::Poi> = futures::stream::iter(pois)
.map(mimirsbrunn::osm_reader::poi::compute_weight)
.then(|poi| mimirsbrunn::osm_reader::poi::add_address(client, poi))
.collect()
.await;
let _ = client
.generate_index(config, futures::stream::iter(pois))
.await
.context(PoiIndexCreationSnafu)?;
Ok(())
}
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::elasticsearch::ElasticsearchStorage;
// use common::config::load_es_config_for;
// use common::document::ContainerDocument;
// use futures::TryStreamExt;
// use mimir::domain::model::query::Query;
// use mimir::domain::ports::primary::list_documents::ListDocuments;
// use mimir::domain::ports::primary::search_documents::SearchDocuments;
// use mimir::{adapters::secondary::elasticsearch::remote, utils::docker};
// use mimirsbrunn::admin::index_cosmogony;
// use places::{admin::Admin, street::Street, Place};
// use serial_test::serial;
// use structopt::StructOpt;
//
// fn elasticsearch_test_url() -> String {
// std::env::var(elasticsearch::remote::ES_TEST_KEY).expect("env var")
// }
//
// async fn index_cosmogony_admins(client: &ElasticsearchStorage) {
// index_cosmogony(
// "./tests/fixtures/cosmogony.json".into(),
// vec![],
// load_es_config_for(
// None,
// None,
// vec!["container.dataset=osm2mimir-test".into()],
// String::from("fr"),
// )
// .unwrap(),
// client,
// )
// .await
// .unwrap()
// }
//
// #[tokio::test]
// #[serial]
// async fn should_correctly_index_osm_streets_and_pois() {
// docker::initialize()
// .await
// .expect("elasticsearch docker initialization");
//
// // Now we query the index we just created. Since it's a small cosmogony file with few entries,
// // we'll just list all the documents in the index, and check them.
// let pool = remote::connection_test_pool()
// .await
// .expect("Elasticsearch Connection Pool");
//
// let client = pool
// .conn(ES_DEFAULT_TIMEOUT, ES_DEFAULT_VERSION_REQ)
// .await
// .expect("Elasticsearch Connection Established");
//
// index_cosmogony_admins(&client).await;
//
// let storage_args = if cfg!(feature = "db-storage") {
// vec!["--db-file=test-db.sqlite3", "--db-buffer-size=10"]
// } else {
// vec![]
// };
//
// let args = Args::from_iter(
// [
// "osm2mimir",
// "--input=./tests/fixtures/osm_fixture.osm.pbf",
// "--dataset=osm2mimir-test",
// "--import-way=true",
// "--import-poi=true",
// &format!("-c={}", elasticsearch_test_url()),
// ]
// .iter()
// .copied()
// .chain(storage_args),
// );
//
// let _res = mimirsbrunn::utils::launch_async_args(run, args).await;
//
// let search = |query: &str| {
// let client = client.clone();
// let query: String = query.into();
// async move {
// client
// .search_documents(
// vec![
// Street::static_doc_type().into(),
// Poi::static_doc_type().into(),
// ],
// Query::QueryString(format!("full_label.prefix:({})", query)),
// )
// .await
// .unwrap()
// .into_iter()
// .map(|json| serde_json::from_value::<Place>(json).unwrap())
// .collect::<Vec<Place>>()
// }
// };
//
// let streets: Vec<Street> = client
// .list_documents()
// .await
// .unwrap()
// .try_collect()
// .await
// .unwrap();
// assert_eq!(streets.len(), 13);
//
// // Basic street search
// let results = search("Rue des Près").await;
// assert_eq!(results[0].label(), "Rue des Près (Livry-sur-Seine)");
// assert_eq!(
// results
// .iter()
// .filter(
// |place| place.is_street() && place.label() == "Rue des Près (Livry-sur-Seine)"
// )
// .count(),
// 1,
// "Only 1 'Rue des Près' is expected"
// );
//
// // All ways with same name in the same city are merged into a single street
// let results = search("Rue du Four à Chaux").await;
// assert_eq!(
// results.iter()
// .filter(|place| place.label() == "Rue du Four à Chaux (Livry-sur-Seine)")
// .count(),
// 1,
// "Only 1 'Rue du Four à Chaux' is expected as all ways the same name should be merged into 1 street."
// );
// assert_eq!(
// results[0].id(),
// "street:osm:way:40812939",
// "The way with minimum way_id should be used as street id."
// );
//
// // Street admin is based on a middle node.
// // (Here the first node is located outside Melun)
// let results = search("Rue Marcel Houdet").await;
// assert_eq!(results[0].label(), "Rue Marcel Houdet (Melun)");
// assert!(results[0]
// .admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|a| a.name == "Melun"));
//
// // Basic search for Poi by label
// let res = search("Le-Mée-sur-Seine Courtilleraies").await;
// assert_eq!(
// res[0].poi().expect("Place should be a poi").poi_type.id,
// "poi_type:amenity:post_office"
// );
//
// // highway=bus_stop should not be indexed
// let res = search("Grand Châtelet").await;
// assert!(
// res.is_empty(),
// "'Grand Châtelet' (highway=bus_stop) should not be found."
// );
//
// // "Rue de Villiers" is at the exact neighborhood between two cities, a
// // document must be added for both.
// let results = search("Rue de Villiers").await;
// assert!(["Neuilly-sur-Seine", "Levallois-Perret"]
// .iter()
// .all(|city| {
// results.iter().any(|poi| {
// poi.admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|admin| &admin.name == city)
// })
// }));
// }
// }
|
StreetIndexCreation {
source: mimir::domain::model::error::Error,
|
random_line_split
|
osm2mimir.rs
|
use clap::Parser;
use futures::stream::StreamExt;
use mimir::domain::model::configuration::ContainerConfig;
use snafu::{ResultExt, Snafu};
use tracing::{instrument, warn};
use mimir::adapters::secondary::elasticsearch::{self, ElasticsearchStorage};
use mimir::domain::ports::primary::{generate_index::GenerateIndex, list_documents::ListDocuments};
use mimir::domain::ports::secondary::remote::Remote;
use mimirsbrunn::admin_geofinder::AdminGeoFinder;
use mimirsbrunn::osm_reader::street::streets;
use mimirsbrunn::settings::osm2mimir as settings;
#[derive(Debug, Snafu)]
pub enum
|
{
#[snafu(display("Settings (Configuration or CLI) Error: {}", source))]
Settings { source: settings::Error },
#[snafu(display("OSM PBF Reader Error: {}", source))]
OsmPbfReader {
source: mimirsbrunn::osm_reader::Error,
},
#[snafu(display("Elasticsearch Connection Pool {}", source))]
ElasticsearchConnection {
source: mimir::domain::ports::secondary::remote::Error,
},
#[snafu(display("Street Extraction from OSM PBF Error {}", source))]
StreetOsmExtraction {
source: mimirsbrunn::osm_reader::street::Error,
},
#[snafu(display("Street Index Creation Error {}", source))]
StreetIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(display("Poi Extraction from OSM PBF Error {}", source))]
PoiOsmExtraction {
source: mimirsbrunn::osm_reader::poi::Error,
},
#[snafu(display("Poi Index Creation Error {}", source))]
PoiIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(display("Elasticsearch Configuration {}", source))]
StreetElasticsearchConfiguration { source: common::config::Error },
#[snafu(display("Execution Error {}", source))]
Execution { source: Box<dyn std::error::Error> },
}
fn main() -> Result<(), Error> {
let opts = settings::Opts::parse();
let settings = settings::Settings::new(&opts).context(SettingsSnafu)?;
match opts.cmd {
settings::Command::Run => mimirsbrunn::utils::launch::launch_with_runtime(
settings.nb_threads,
run(opts, settings),
)
.context(ExecutionSnafu),
settings::Command::Config => {
println!("{}", serde_json::to_string_pretty(&settings).unwrap());
Ok(())
}
}
}
async fn run(
opts: settings::Opts,
settings: settings::Settings,
) -> Result<(), Box<dyn std::error::Error>> {
let mut osm_reader =
mimirsbrunn::osm_reader::make_osm_reader(&opts.input).context(OsmPbfReaderSnafu)?;
let client = elasticsearch::remote::connection_pool_url(&settings.elasticsearch.url)
.conn(settings.elasticsearch.clone())
.await
.context(ElasticsearchConnectionSnafu)?;
let admins_geofinder: AdminGeoFinder = match client.list_documents().await {
Ok(stream) => {
stream
.map(|admin| admin.expect("could not parse admin"))
.collect()
.await
}
Err(err) => {
warn!(
"administratives regions not found in Elasticsearch. {:?}",
err
);
std::iter::empty().collect()
}
};
if settings.streets.import {
let streets = streets(
&mut osm_reader,
&admins_geofinder,
&settings.streets.exclusions,
#[cfg(feature = "db-storage")]
settings.database.as_ref(),
)
.context(StreetOsmExtractionSnafu)?;
import_streets(streets, &client, &settings.container_street).await?;
}
if settings.pois.import {
import_pois(
&mut osm_reader,
&admins_geofinder,
&settings.pois.config.clone().unwrap_or_default(),
&client,
&settings.container_poi,
)
.await?;
}
Ok(())
}
#[instrument(skip_all)]
async fn import_streets(
streets: Vec<places::street::Street>,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
let streets = streets
.into_iter()
.map(|street| street.set_weight_from_admins());
let _index = client
.generate_index(config, futures::stream::iter(streets))
.await
.context(StreetIndexCreationSnafu)?;
Ok(())
}
#[instrument(skip_all)]
async fn import_pois(
osm_reader: &mut mimirsbrunn::osm_reader::OsmPbfReader,
admins_geofinder: &AdminGeoFinder,
poi_config: &mimirsbrunn::osm_reader::poi::PoiConfig,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
// This function rely on AdminGeoFinder::get_objs_and_deps
// which use all available cpu/cores to decode osm file and cannot be limited by tokio runtime
let pois = mimirsbrunn::osm_reader::poi::pois(osm_reader, poi_config, admins_geofinder)
.context(PoiOsmExtractionSnafu)?;
let pois: Vec<places::poi::Poi> = futures::stream::iter(pois)
.map(mimirsbrunn::osm_reader::poi::compute_weight)
.then(|poi| mimirsbrunn::osm_reader::poi::add_address(client, poi))
.collect()
.await;
let _ = client
.generate_index(config, futures::stream::iter(pois))
.await
.context(PoiIndexCreationSnafu)?;
Ok(())
}
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::elasticsearch::ElasticsearchStorage;
// use common::config::load_es_config_for;
// use common::document::ContainerDocument;
// use futures::TryStreamExt;
// use mimir::domain::model::query::Query;
// use mimir::domain::ports::primary::list_documents::ListDocuments;
// use mimir::domain::ports::primary::search_documents::SearchDocuments;
// use mimir::{adapters::secondary::elasticsearch::remote, utils::docker};
// use mimirsbrunn::admin::index_cosmogony;
// use places::{admin::Admin, street::Street, Place};
// use serial_test::serial;
// use structopt::StructOpt;
//
// fn elasticsearch_test_url() -> String {
// std::env::var(elasticsearch::remote::ES_TEST_KEY).expect("env var")
// }
//
// async fn index_cosmogony_admins(client: &ElasticsearchStorage) {
// index_cosmogony(
// "./tests/fixtures/cosmogony.json".into(),
// vec![],
// load_es_config_for(
// None,
// None,
// vec!["container.dataset=osm2mimir-test".into()],
// String::from("fr"),
// )
// .unwrap(),
// client,
// )
// .await
// .unwrap()
// }
//
// #[tokio::test]
// #[serial]
// async fn should_correctly_index_osm_streets_and_pois() {
// docker::initialize()
// .await
// .expect("elasticsearch docker initialization");
//
// // Now we query the index we just created. Since it's a small cosmogony file with few entries,
// // we'll just list all the documents in the index, and check them.
// let pool = remote::connection_test_pool()
// .await
// .expect("Elasticsearch Connection Pool");
//
// let client = pool
// .conn(ES_DEFAULT_TIMEOUT, ES_DEFAULT_VERSION_REQ)
// .await
// .expect("Elasticsearch Connection Established");
//
// index_cosmogony_admins(&client).await;
//
// let storage_args = if cfg!(feature = "db-storage") {
// vec!["--db-file=test-db.sqlite3", "--db-buffer-size=10"]
// } else {
// vec![]
// };
//
// let args = Args::from_iter(
// [
// "osm2mimir",
// "--input=./tests/fixtures/osm_fixture.osm.pbf",
// "--dataset=osm2mimir-test",
// "--import-way=true",
// "--import-poi=true",
// &format!("-c={}", elasticsearch_test_url()),
// ]
// .iter()
// .copied()
// .chain(storage_args),
// );
//
// let _res = mimirsbrunn::utils::launch_async_args(run, args).await;
//
// let search = |query: &str| {
// let client = client.clone();
// let query: String = query.into();
// async move {
// client
// .search_documents(
// vec![
// Street::static_doc_type().into(),
// Poi::static_doc_type().into(),
// ],
// Query::QueryString(format!("full_label.prefix:({})", query)),
// )
// .await
// .unwrap()
// .into_iter()
// .map(|json| serde_json::from_value::<Place>(json).unwrap())
// .collect::<Vec<Place>>()
// }
// };
//
// let streets: Vec<Street> = client
// .list_documents()
// .await
// .unwrap()
// .try_collect()
// .await
// .unwrap();
// assert_eq!(streets.len(), 13);
//
// // Basic street search
// let results = search("Rue des Près").await;
// assert_eq!(results[0].label(), "Rue des Près (Livry-sur-Seine)");
// assert_eq!(
// results
// .iter()
// .filter(
// |place| place.is_street() && place.label() == "Rue des Près (Livry-sur-Seine)"
// )
// .count(),
// 1,
// "Only 1 'Rue des Près' is expected"
// );
//
// // All ways with same name in the same city are merged into a single street
// let results = search("Rue du Four à Chaux").await;
// assert_eq!(
// results.iter()
// .filter(|place| place.label() == "Rue du Four à Chaux (Livry-sur-Seine)")
// .count(),
// 1,
// "Only 1 'Rue du Four à Chaux' is expected as all ways the same name should be merged into 1 street."
// );
// assert_eq!(
// results[0].id(),
// "street:osm:way:40812939",
// "The way with minimum way_id should be used as street id."
// );
//
// // Street admin is based on a middle node.
// // (Here the first node is located outside Melun)
// let results = search("Rue Marcel Houdet").await;
// assert_eq!(results[0].label(), "Rue Marcel Houdet (Melun)");
// assert!(results[0]
// .admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|a| a.name == "Melun"));
//
// // Basic search for Poi by label
// let res = search("Le-Mée-sur-Seine Courtilleraies").await;
// assert_eq!(
// res[0].poi().expect("Place should be a poi").poi_type.id,
// "poi_type:amenity:post_office"
// );
//
// // highway=bus_stop should not be indexed
// let res = search("Grand Châtelet").await;
// assert!(
// res.is_empty(),
// "'Grand Châtelet' (highway=bus_stop) should not be found."
// );
//
// // "Rue de Villiers" is at the exact neighborhood between two cities, a
// // document must be added for both.
// let results = search("Rue de Villiers").await;
// assert!(["Neuilly-sur-Seine", "Levallois-Perret"]
// .iter()
// .all(|city| {
// results.iter().any(|poi| {
// poi.admins()
// .iter()
// .filter(|a| a.is_city())
// .any(|admin| &admin.name == city)
// })
// }));
// }
// }
|
Error
|
identifier_name
|
unix.rs
|
extern crate thermal_printer;
extern crate serial;
extern crate serial_embedded_hal;
use serial::{Baud19200, Bits8, ParityNone, Stop1, FlowNone};
use serial_embedded_hal::{Serial, PortSettings};
use thermal_printer::prelude::*;
use std::thread::sleep;
fn main() {
println!("Opening serial port...");
let port_settings = PortSettings {
|
};
println!("Serial port open");
let port = Serial::new("/dev/tty.usbserial-A700eX73", &port_settings)
.expect("Failed to open serial port");
let (tx_port, _) = port.split();
let mut printer = ThermalPrinter::new(tx_port);
printer.configure(11, 120, 40);
println!("Feeding 3 lines");
printer.feed_n(3).expect("Feed lines failed");
println!("Running self test");
printer.run_test().expect("Self test failed");
sleep(std::time::Duration::from_secs(1));
println!("Done!")
}
|
baud_rate: Baud19200,
char_size: Bits8,
parity: ParityNone,
stop_bits: Stop1,
flow_control: FlowNone,
|
random_line_split
|
unix.rs
|
extern crate thermal_printer;
extern crate serial;
extern crate serial_embedded_hal;
use serial::{Baud19200, Bits8, ParityNone, Stop1, FlowNone};
use serial_embedded_hal::{Serial, PortSettings};
use thermal_printer::prelude::*;
use std::thread::sleep;
fn main()
|
printer.configure(11, 120, 40);
println!("Feeding 3 lines");
printer.feed_n(3).expect("Feed lines failed");
println!("Running self test");
printer.run_test().expect("Self test failed");
sleep(std::time::Duration::from_secs(1));
println!("Done!")
}
|
{
println!("Opening serial port...");
let port_settings = PortSettings {
baud_rate: Baud19200,
char_size: Bits8,
parity: ParityNone,
stop_bits: Stop1,
flow_control: FlowNone,
};
println!("Serial port open");
let port = Serial::new("/dev/tty.usbserial-A700eX73", &port_settings)
.expect("Failed to open serial port");
let (tx_port, _) = port.split();
let mut printer = ThermalPrinter::new(tx_port);
|
identifier_body
|
unix.rs
|
extern crate thermal_printer;
extern crate serial;
extern crate serial_embedded_hal;
use serial::{Baud19200, Bits8, ParityNone, Stop1, FlowNone};
use serial_embedded_hal::{Serial, PortSettings};
use thermal_printer::prelude::*;
use std::thread::sleep;
fn
|
() {
println!("Opening serial port...");
let port_settings = PortSettings {
baud_rate: Baud19200,
char_size: Bits8,
parity: ParityNone,
stop_bits: Stop1,
flow_control: FlowNone,
};
println!("Serial port open");
let port = Serial::new("/dev/tty.usbserial-A700eX73", &port_settings)
.expect("Failed to open serial port");
let (tx_port, _) = port.split();
let mut printer = ThermalPrinter::new(tx_port);
printer.configure(11, 120, 40);
println!("Feeding 3 lines");
printer.feed_n(3).expect("Feed lines failed");
println!("Running self test");
printer.run_test().expect("Self test failed");
sleep(std::time::Duration::from_secs(1));
println!("Done!")
}
|
main
|
identifier_name
|
main.rs
|
// --- Day 7: Internet Protocol Version 7 ---
//
// While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping).
//
// An IP supports TLS if it has an Autonomous Bridge Bypass Annotation, or ABBA. An ABBA is any four-character sequence which consists of a pair of two different characters followed by the reverse of that pair, such as xyyx or abba. However, the IP also must not have an ABBA within any hypernet sequences, which are contained by square brackets.
//
// For example:
//
// abba[mnop]qrst supports TLS (abba outside square brackets).
// abcd[bddb]xyyx does not support TLS (bddb is within square brackets, even though xyyx is outside square brackets).
// aaaa[qwer]tyui does not support TLS (aaaa is invalid; the interior characters must be different).
// ioxxoj[asdfgh]zxcvbn supports TLS (oxxo is outside square brackets, even though it's within a larger string).
// How many IPs in your puzzle input support TLS?
//
// --- Part Two ---
//
// You would also like to know which IPs support SSL (super-secret listening).
//
// An IP supports SSL if it has an Area-Broadcast Accessor, or ABA, anywhere in the supernet sequences (outside any square bracketed sections), and a corresponding Byte Allocation Block, or BAB, anywhere in the hypernet sequences. An ABA is any three-character sequence which consists of the same character twice with a different character between them, such as xyx or aba. A corresponding BAB is the same characters but in reversed positions: yxy and bab, respectively.
//
// For example:
//
// aba[bab]xyz supports SSL (aba outside square brackets with corresponding bab within square brackets).
// xyx[xyx]xyx does not support SSL (xyx, but no corresponding yxy).
// aaa[kek]eke supports SSL (eke in supernet with corresponding kek in hypernet; the aaa sequence is not related, because the interior character must be different).
// zazbz[bzb]cdb supports SSL (zaz has no corresponding aza, but zbz has a corresponding bzb, even though zaz and zbz overlap).
//
// How many IPs in your puzzle input support SSL?
//
extern crate regex;
#[macro_use]
extern crate lazy_static;
mod ip_address;
mod part_a_validator;
mod part_b_validator;
use std::io::prelude::*;
use std::fs::File;
use ip_address::IPAddress;
use part_a_validator::PartAValidator;
use part_b_validator::PartBValidator;
fn main()
|
{
// read input from file
let mut f = File::open("input.txt").unwrap();
let mut input = String::new();
f.read_to_string(&mut input).ok();
// parse lines to IPAddress objects
let addresses: Vec<IPAddress> = input.lines().map(|l| l.parse().unwrap()).collect();
// figure out answer A
let part_a_validator = PartAValidator{};
let answer_a: Vec<&IPAddress> = addresses.iter().filter(|a| a.is_valid(&part_a_validator)).collect();
println!("[PART A] answer: {}", answer_a.len());
// figure out answer B
let part_b_validator = PartBValidator{};
let answer_b: Vec<&IPAddress> = addresses.iter().filter(|a| a.is_valid(&part_b_validator)).collect();
println!("[PART B] answer: {}", answer_b.len());
}
|
identifier_body
|
|
main.rs
|
// --- Day 7: Internet Protocol Version 7 ---
//
// While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping).
//
// An IP supports TLS if it has an Autonomous Bridge Bypass Annotation, or ABBA. An ABBA is any four-character sequence which consists of a pair of two different characters followed by the reverse of that pair, such as xyyx or abba. However, the IP also must not have an ABBA within any hypernet sequences, which are contained by square brackets.
//
// For example:
//
// abba[mnop]qrst supports TLS (abba outside square brackets).
// abcd[bddb]xyyx does not support TLS (bddb is within square brackets, even though xyyx is outside square brackets).
// aaaa[qwer]tyui does not support TLS (aaaa is invalid; the interior characters must be different).
// ioxxoj[asdfgh]zxcvbn supports TLS (oxxo is outside square brackets, even though it's within a larger string).
// How many IPs in your puzzle input support TLS?
//
// --- Part Two ---
//
// You would also like to know which IPs support SSL (super-secret listening).
//
// An IP supports SSL if it has an Area-Broadcast Accessor, or ABA, anywhere in the supernet sequences (outside any square bracketed sections), and a corresponding Byte Allocation Block, or BAB, anywhere in the hypernet sequences. An ABA is any three-character sequence which consists of the same character twice with a different character between them, such as xyx or aba. A corresponding BAB is the same characters but in reversed positions: yxy and bab, respectively.
//
// For example:
//
// aba[bab]xyz supports SSL (aba outside square brackets with corresponding bab within square brackets).
// xyx[xyx]xyx does not support SSL (xyx, but no corresponding yxy).
// aaa[kek]eke supports SSL (eke in supernet with corresponding kek in hypernet; the aaa sequence is not related, because the interior character must be different).
// zazbz[bzb]cdb supports SSL (zaz has no corresponding aza, but zbz has a corresponding bzb, even though zaz and zbz overlap).
//
// How many IPs in your puzzle input support SSL?
//
extern crate regex;
#[macro_use]
extern crate lazy_static;
mod ip_address;
mod part_a_validator;
mod part_b_validator;
use std::io::prelude::*;
use std::fs::File;
use ip_address::IPAddress;
use part_a_validator::PartAValidator;
use part_b_validator::PartBValidator;
fn
|
() {
// read input from file
let mut f = File::open("input.txt").unwrap();
let mut input = String::new();
f.read_to_string(&mut input).ok();
// parse lines to IPAddress objects
let addresses: Vec<IPAddress> = input.lines().map(|l| l.parse().unwrap()).collect();
// figure out answer A
let part_a_validator = PartAValidator{};
let answer_a: Vec<&IPAddress> = addresses.iter().filter(|a| a.is_valid(&part_a_validator)).collect();
println!("[PART A] answer: {}", answer_a.len());
// figure out answer B
let part_b_validator = PartBValidator{};
let answer_b: Vec<&IPAddress> = addresses.iter().filter(|a| a.is_valid(&part_b_validator)).collect();
println!("[PART B] answer: {}", answer_b.len());
}
|
main
|
identifier_name
|
main.rs
|
// --- Day 7: Internet Protocol Version 7 ---
//
// While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping).
//
// An IP supports TLS if it has an Autonomous Bridge Bypass Annotation, or ABBA. An ABBA is any four-character sequence which consists of a pair of two different characters followed by the reverse of that pair, such as xyyx or abba. However, the IP also must not have an ABBA within any hypernet sequences, which are contained by square brackets.
//
// For example:
//
// abba[mnop]qrst supports TLS (abba outside square brackets).
// abcd[bddb]xyyx does not support TLS (bddb is within square brackets, even though xyyx is outside square brackets).
// aaaa[qwer]tyui does not support TLS (aaaa is invalid; the interior characters must be different).
// ioxxoj[asdfgh]zxcvbn supports TLS (oxxo is outside square brackets, even though it's within a larger string).
// How many IPs in your puzzle input support TLS?
//
// --- Part Two ---
//
// You would also like to know which IPs support SSL (super-secret listening).
//
|
// xyx[xyx]xyx does not support SSL (xyx, but no corresponding yxy).
// aaa[kek]eke supports SSL (eke in supernet with corresponding kek in hypernet; the aaa sequence is not related, because the interior character must be different).
// zazbz[bzb]cdb supports SSL (zaz has no corresponding aza, but zbz has a corresponding bzb, even though zaz and zbz overlap).
//
// How many IPs in your puzzle input support SSL?
//
extern crate regex;
#[macro_use]
extern crate lazy_static;
mod ip_address;
mod part_a_validator;
mod part_b_validator;
use std::io::prelude::*;
use std::fs::File;
use ip_address::IPAddress;
use part_a_validator::PartAValidator;
use part_b_validator::PartBValidator;
fn main() {
// read input from file
let mut f = File::open("input.txt").unwrap();
let mut input = String::new();
f.read_to_string(&mut input).ok();
// parse lines to IPAddress objects
let addresses: Vec<IPAddress> = input.lines().map(|l| l.parse().unwrap()).collect();
// figure out answer A
let part_a_validator = PartAValidator{};
let answer_a: Vec<&IPAddress> = addresses.iter().filter(|a| a.is_valid(&part_a_validator)).collect();
println!("[PART A] answer: {}", answer_a.len());
// figure out answer B
let part_b_validator = PartBValidator{};
let answer_b: Vec<&IPAddress> = addresses.iter().filter(|a| a.is_valid(&part_b_validator)).collect();
println!("[PART B] answer: {}", answer_b.len());
}
|
// An IP supports SSL if it has an Area-Broadcast Accessor, or ABA, anywhere in the supernet sequences (outside any square bracketed sections), and a corresponding Byte Allocation Block, or BAB, anywhere in the hypernet sequences. An ABA is any three-character sequence which consists of the same character twice with a different character between them, such as xyx or aba. A corresponding BAB is the same characters but in reversed positions: yxy and bab, respectively.
//
// For example:
//
// aba[bab]xyz supports SSL (aba outside square brackets with corresponding bab within square brackets).
|
random_line_split
|
skin.rs
|
// Copyright 2015 Birunthan Mohanathas
//
// Licensed under the MIT license <http://opensource.org/licenses/MIT>. This
// file may not be copied, modified, or distributed except according to those
// terms.
use measure::Measureable;
pub struct Skin<'a> {
name: String,
measures: Vec<Box<Measureable<'a> + 'a>>,
}
impl<'a> Skin<'a> {
pub fn new(name: &str) -> Skin {
Skin {
name: name.to_string(),
measures: Vec::new(),
}
}
pub fn name(&self) -> &str {
self.name.as_slice()
}
pub fn add_measure(&mut self, measure: Box<Measureable<'a> + 'a>) {
self.measures.push(measure);
}
pub fn
|
(&self) -> &Vec<Box<Measureable<'a> + 'a>> {
&self.measures
}
}
#[test]
fn test_name() {
let skin = Skin::new("skin");
assert_eq!("skin", skin.name());
}
#[test]
fn test_add_measure() {
use time_measure::TimeMeasure;
let mut skin = Skin::new("skin");
skin.add_measure(Box::new(TimeMeasure::new("foo")));
assert_eq!(1, skin.measures().len());
}
|
measures
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.