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
keystore.rs
#![allow(non_snake_case)] use serde_json::{self, Value}; use request::Handler; use error::ConsulResult; use std::error::Error; pub struct Keystore{ handler: Handler }
} } pub fn set_key(&self, key: String, value: String) -> ConsulResult<()> { self.handler.put(&key, value, Some("application/json"))?; Ok(()) } pub fn acquire_lock(&self, key: String, address: String, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?acquire={}", key, session_id); let result = self.handler.put(&uri, address, Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } } pub fn release_lock(&self, key: String, address: &str, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?release={}", key, session_id); let result = self.handler.put(&uri, address.to_owned(), Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } } pub fn get_key(&self, key: String) -> ConsulResult<Option<String>> { let result = self.handler.get(&key)?; let json_data: Value = serde_json::from_str(&result) .map_err(|e| e.description().to_owned())?; let v_json = json_data.as_array().unwrap(); Ok(super::get_string(&v_json[0], &["Value"])) } pub fn delete_key(&self, key: String) { self.handler.delete(&key).unwrap(); } }
impl Keystore { pub fn new(address: &str) -> Keystore { Keystore { handler: Handler::new(&format!("{}/v1/kv", address))
random_line_split
keystore.rs
#![allow(non_snake_case)] use serde_json::{self, Value}; use request::Handler; use error::ConsulResult; use std::error::Error; pub struct Keystore{ handler: Handler } impl Keystore { pub fn new(address: &str) -> Keystore { Keystore { handler: Handler::new(&format!("{}/v1/kv", address)) } } pub fn set_key(&self, key: String, value: String) -> ConsulResult<()> { self.handler.put(&key, value, Some("application/json"))?; Ok(()) } pub fn acquire_lock(&self, key: String, address: String, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?acquire={}", key, session_id); let result = self.handler.put(&uri, address, Some("application/json"))?; if result == "true" { Ok(true) } else
} pub fn release_lock(&self, key: String, address: &str, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?release={}", key, session_id); let result = self.handler.put(&uri, address.to_owned(), Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } } pub fn get_key(&self, key: String) -> ConsulResult<Option<String>> { let result = self.handler.get(&key)?; let json_data: Value = serde_json::from_str(&result) .map_err(|e| e.description().to_owned())?; let v_json = json_data.as_array().unwrap(); Ok(super::get_string(&v_json[0], &["Value"])) } pub fn delete_key(&self, key: String) { self.handler.delete(&key).unwrap(); } }
{ Ok(false) }
conditional_block
keystore.rs
#![allow(non_snake_case)] use serde_json::{self, Value}; use request::Handler; use error::ConsulResult; use std::error::Error; pub struct Keystore{ handler: Handler } impl Keystore { pub fn new(address: &str) -> Keystore { Keystore { handler: Handler::new(&format!("{}/v1/kv", address)) } } pub fn set_key(&self, key: String, value: String) -> ConsulResult<()> { self.handler.put(&key, value, Some("application/json"))?; Ok(()) } pub fn acquire_lock(&self, key: String, address: String, session_id: &String) -> ConsulResult<bool>
pub fn release_lock(&self, key: String, address: &str, session_id: &String) -> ConsulResult<bool> { let uri = format!("{}?release={}", key, session_id); let result = self.handler.put(&uri, address.to_owned(), Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } } pub fn get_key(&self, key: String) -> ConsulResult<Option<String>> { let result = self.handler.get(&key)?; let json_data: Value = serde_json::from_str(&result) .map_err(|e| e.description().to_owned())?; let v_json = json_data.as_array().unwrap(); Ok(super::get_string(&v_json[0], &["Value"])) } pub fn delete_key(&self, key: String) { self.handler.delete(&key).unwrap(); } }
{ let uri = format!("{}?acquire={}", key, session_id); let result = self.handler.put(&uri, address, Some("application/json"))?; if result == "true" { Ok(true) } else { Ok(false) } }
identifier_body
re_builder.rs
// Copyright 2014-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. /// The set of user configurable options for compiling zero or more regexes. #[derive(Clone, Debug)] pub struct
{ pub pats: Vec<String>, pub size_limit: usize, pub dfa_size_limit: usize, pub case_insensitive: bool, pub multi_line: bool, pub dot_matches_new_line: bool, pub swap_greed: bool, pub ignore_whitespace: bool, pub unicode: bool, } impl Default for RegexOptions { fn default() -> Self { RegexOptions { pats: vec![], size_limit: 10 * (1<<20), dfa_size_limit: 2 * (1<<20), case_insensitive: false, multi_line: false, dot_matches_new_line: false, swap_greed: false, ignore_whitespace: false, unicode: true, } } } macro_rules! define_builder { ($name:ident, $regex_mod:ident, $unicode:expr, $only_utf8:expr) => { pub mod $name { use error::Error; use exec::ExecBuilder; use super::RegexOptions; use $regex_mod::Regex; /// A configurable builder for a regular expression. /// /// A builder can be used to configure how the regex is built, for example, by /// setting the default flags (which can be overridden in the expression /// itself) or setting various limits. pub struct RegexBuilder(RegexOptions); impl RegexBuilder { /// Create a new regular expression builder with the given pattern. /// /// If the pattern is invalid, then an error will be returned when /// `compile` is called. pub fn new(pattern: &str) -> RegexBuilder { let mut builder = RegexBuilder(RegexOptions::default()); builder.0.pats.push(pattern.to_owned()); builder.0.unicode = $unicode; builder } /// Consume the builder and compile the regular expression. /// /// Note that calling `as_str` on the resulting `Regex` will produce the /// pattern given to `new` verbatim. Notably, it will not incorporate any /// of the flags set on this builder. pub fn compile(self) -> Result<Regex, Error> { ExecBuilder::new_options(self.0) .only_utf8($only_utf8) .build() .map(Regex::from) } /// Set the value for the case insensitive (`i`) flag. pub fn case_insensitive(mut self, yes: bool) -> RegexBuilder { self.0.case_insensitive = yes; self } /// Set the value for the multi-line matching (`m`) flag. pub fn multi_line(mut self, yes: bool) -> RegexBuilder { self.0.multi_line = yes; self } /// Set the value for the any character (`s`) flag, where in `.` matches /// anything when `s` is set and matches anything except for new line when /// it is not set (the default). /// /// N.B. "matches anything" means "any byte" for `regex::bytes::Regex` /// expressions and means "any Unicode codepoint" for `regex::Regex` /// expressions. pub fn dot_matches_new_line(mut self, yes: bool) -> RegexBuilder { self.0.dot_matches_new_line = yes; self } /// Set the value for the greedy swap (`U`) flag. pub fn swap_greed(mut self, yes: bool) -> RegexBuilder { self.0.swap_greed = yes; self } /// Set the value for the ignore whitespace (`x`) flag. pub fn ignore_whitespace(mut self, yes: bool) -> RegexBuilder { self.0.ignore_whitespace = yes; self } /// Set the value for the Unicode (`u`) flag. /// /// For byte based regular expressions, this is disabled by default. pub fn unicode(mut self, yes: bool) -> RegexBuilder { self.0.unicode = yes; self } /// Set the approximate size limit of the compiled regular expression. /// /// This roughly corresponds to the number of bytes occupied by a single /// compiled program. If the program exceeds this number, then a /// compilation error is returned. pub fn size_limit(mut self, limit: usize) -> RegexBuilder { self.0.size_limit = limit; self } /// Set the approximate size of the cache used by the DFA. /// /// This roughly corresponds to the number of bytes that the DFA will /// use while searching. /// /// Note that this is a *per thread* limit. There is no way to set a global /// limit. In particular, if a regex is used from multiple threads /// simulanteously, then each thread may use up to the number of bytes /// specified here. pub fn dfa_size_limit(mut self, limit: usize) -> RegexBuilder { self.0.dfa_size_limit = limit; self } } } } } define_builder!(bytes, re_bytes, false, false); define_builder!(unicode, re_unicode, true, true);
RegexOptions
identifier_name
re_builder.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// except according to those terms. /// The set of user configurable options for compiling zero or more regexes. #[derive(Clone, Debug)] pub struct RegexOptions { pub pats: Vec<String>, pub size_limit: usize, pub dfa_size_limit: usize, pub case_insensitive: bool, pub multi_line: bool, pub dot_matches_new_line: bool, pub swap_greed: bool, pub ignore_whitespace: bool, pub unicode: bool, } impl Default for RegexOptions { fn default() -> Self { RegexOptions { pats: vec![], size_limit: 10 * (1<<20), dfa_size_limit: 2 * (1<<20), case_insensitive: false, multi_line: false, dot_matches_new_line: false, swap_greed: false, ignore_whitespace: false, unicode: true, } } } macro_rules! define_builder { ($name:ident, $regex_mod:ident, $unicode:expr, $only_utf8:expr) => { pub mod $name { use error::Error; use exec::ExecBuilder; use super::RegexOptions; use $regex_mod::Regex; /// A configurable builder for a regular expression. /// /// A builder can be used to configure how the regex is built, for example, by /// setting the default flags (which can be overridden in the expression /// itself) or setting various limits. pub struct RegexBuilder(RegexOptions); impl RegexBuilder { /// Create a new regular expression builder with the given pattern. /// /// If the pattern is invalid, then an error will be returned when /// `compile` is called. pub fn new(pattern: &str) -> RegexBuilder { let mut builder = RegexBuilder(RegexOptions::default()); builder.0.pats.push(pattern.to_owned()); builder.0.unicode = $unicode; builder } /// Consume the builder and compile the regular expression. /// /// Note that calling `as_str` on the resulting `Regex` will produce the /// pattern given to `new` verbatim. Notably, it will not incorporate any /// of the flags set on this builder. pub fn compile(self) -> Result<Regex, Error> { ExecBuilder::new_options(self.0) .only_utf8($only_utf8) .build() .map(Regex::from) } /// Set the value for the case insensitive (`i`) flag. pub fn case_insensitive(mut self, yes: bool) -> RegexBuilder { self.0.case_insensitive = yes; self } /// Set the value for the multi-line matching (`m`) flag. pub fn multi_line(mut self, yes: bool) -> RegexBuilder { self.0.multi_line = yes; self } /// Set the value for the any character (`s`) flag, where in `.` matches /// anything when `s` is set and matches anything except for new line when /// it is not set (the default). /// /// N.B. "matches anything" means "any byte" for `regex::bytes::Regex` /// expressions and means "any Unicode codepoint" for `regex::Regex` /// expressions. pub fn dot_matches_new_line(mut self, yes: bool) -> RegexBuilder { self.0.dot_matches_new_line = yes; self } /// Set the value for the greedy swap (`U`) flag. pub fn swap_greed(mut self, yes: bool) -> RegexBuilder { self.0.swap_greed = yes; self } /// Set the value for the ignore whitespace (`x`) flag. pub fn ignore_whitespace(mut self, yes: bool) -> RegexBuilder { self.0.ignore_whitespace = yes; self } /// Set the value for the Unicode (`u`) flag. /// /// For byte based regular expressions, this is disabled by default. pub fn unicode(mut self, yes: bool) -> RegexBuilder { self.0.unicode = yes; self } /// Set the approximate size limit of the compiled regular expression. /// /// This roughly corresponds to the number of bytes occupied by a single /// compiled program. If the program exceeds this number, then a /// compilation error is returned. pub fn size_limit(mut self, limit: usize) -> RegexBuilder { self.0.size_limit = limit; self } /// Set the approximate size of the cache used by the DFA. /// /// This roughly corresponds to the number of bytes that the DFA will /// use while searching. /// /// Note that this is a *per thread* limit. There is no way to set a global /// limit. In particular, if a regex is used from multiple threads /// simulanteously, then each thread may use up to the number of bytes /// specified here. pub fn dfa_size_limit(mut self, limit: usize) -> RegexBuilder { self.0.dfa_size_limit = limit; self } } } } } define_builder!(bytes, re_bytes, false, false); define_builder!(unicode, re_unicode, true, true);
// 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
random_line_split
main.rs
use std::env; use std::process::exit; use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::io::prelude::*; use std::collections::HashMap; enum OpcodeType { LocRequired, LocAndLabelRequred, NothingRequired, NotAnOpcode } static PROG_NAME: &'static str = "acslasmc v0.1"; static PROG_NAME_LINE: &'static str = "acslasmc v0.1 -- ACSL Assembly to C compiler"; static HEADER: &'static str = "\ #include<stdio.h> int get_mem_size(); int MOD = 1000000; int main() { int MEM_SIZE = get_mem_size(); int acc = 0; int mem[MEM_SIZE]; for (int i=0; i<MEM_SIZE; i++) { mem[i] = 0; } "; static PRE_FOOTER: &'static str = "\ } int get_mem_size() { "; static FOOTER: &'static str = "}"; fn main() { let status = encapsulated_main(); exit(status); } fn encapsulated_main() -> i32 { println!("{}", PROG_NAME_LINE); let mut args = env::args(); let input_file_path = match args.nth(1) { Some(x) => x, None => { println!("Please pass a source file with ACSL assembly code and a target file for generated C code as arguments."); return 2; } }; let output_file_path = match args.next() { Some(x) => x, None => format!("{}_output.c", input_file_path) }; let mut reader = BufReader::new( match File::open(&input_file_path) { Ok(x) => x, Err(_) => { println!("Failed to open source file '{}'.", input_file_path); return 3; } } ); println!("Source file: '{}'.", input_file_path); let mut writer = BufWriter::new( match File::create(&output_file_path) { Ok(x) => x, Err(_) => { println!("Failed to open output file '{}'.", output_file_path); return 3; } } ); println!("Output file: '{}'.", output_file_path); let mut counter: u32 = 0; let mut var_map: HashMap<String, u32> = HashMap::new(); let mut buffer = String::new(); let mut line_count: u32 = 1; // Write the beginnings of the C code writeln!(writer, "// generated from ACSL assembly source '{}' by {}\n{}", input_file_path, PROG_NAME, HEADER).unwrap(); loop { match reader.read_line(&mut buffer) { Ok(bytes_read) => { if bytes_read <= 0 { break; } }, Err(_) => panic!("Failed to read line!") } { let comps: Vec<_> = buffer.trim().split(' ').collect(); let translated = match process_comps(&comps, &mut var_map, &mut counter) { Ok(x) => x, Err(x) => { println!("line {}: error: {}", line_count, x); println!("Compilation failed."); return 1; } }; writeln!(writer, " {}", translated).unwrap(); } line_count += 1; buffer.clear(); } // Write some ending C code writeln!(writer, "{} return {};\n{}\n", PRE_FOOTER, var_map.len(), FOOTER).unwrap(); println!("You may pass the generated C source to a C compiler to run it: e.g."); println!("gcc {of} -o {of}.out &&./{of}.out", of = output_file_path); println!("Compilation complete."); return 0; } fn process_comps(comps: &Vec<&str>, var_map: &mut HashMap<String, u32>, counter: &mut u32) -> Result<String, String> { match opcode_type(match comps.get(0) { Some(x) => x, None => return Ok(String::new()) // blank line, go to next one }) { OpcodeType::LocRequired => return trans(var_map, counter, "", comps[0], match comps.get(1) { None => return Err(format!("missing loc: loc is required for opcode {}", comps[0])), Some(x) => x }), OpcodeType::NothingRequired => return trans(var_map, counter, "", comps[0], ""), OpcodeType::LocAndLabelRequred => return Err(format!("missing label: label is required for opcode {}", comps[0])), OpcodeType::NotAnOpcode => match opcode_type(match comps.get(1) { Some(x) => x, None => return Err(format!("missing opcode, only label provided")) }) { OpcodeType::LocRequired | OpcodeType::LocAndLabelRequred => return trans(var_map, counter, comps[0], comps[1], match comps.get(2) { Some(x) => x, None => return Err(format!("missing loc: loc is required for opcode {}", comps[1])) }), OpcodeType::NothingRequired => return trans(var_map, counter, comps[0], comps[1], ""), OpcodeType::NotAnOpcode => return Err(format!("invalid opcode: {}", comps[1])) } } } fn trans(var_map: &mut HashMap<String, u32>, counter: &mut u32, label: &str, opcode: &str, loc: &str) -> Result<String, String> { let read_loc: String = match loc.chars().nth(0) { Some(x) if x == '=' => loc.split_at(1).1.to_owned(), Some(_) => match var_map.get(&loc.to_owned()) { Some(y) => format!("mem[{}]", y), None => String::new() }, None => String::new() }; let action = match opcode { "LOAD" => format!("acc = {read_loc};", read_loc = read_loc), "STORE" => { let res_loc = req_mem(var_map, counter, loc); format!("mem[{res_loc}] = acc;", res_loc = res_loc) }, "ADD" => format!("acc = (acc + {read_loc}) % MOD;", read_loc = read_loc), "SUB" => format!("acc = (acc - {read_loc}) % MOD;", read_loc = read_loc), "MULT" => format!("acc = (acc * {read_loc}) % MOD;", read_loc = read_loc), "DIV" => format!("acc = (acc / {read_loc}) % MOD;", read_loc = read_loc), "BE" => format!("if (acc == 0) goto {raw_loc};", raw_loc = loc), "BU" => format!("if (acc > 0) goto {raw_loc};", raw_loc = loc), "BL" => format!("if (acc < 0) goto {raw_loc};", raw_loc = loc), "END" => "return 0;".to_owned(), // Ignore LOC field // TODO: Implement READ opcode "READ" => return Err("READ is unimplemented".to_owned()), "PRINT" => format!("printf(\"%d\\n\", {read_loc});", read_loc = read_loc), "DC" => { let label_loc = req_mem(var_map, counter, label); format!("mem[{label_loc}] = {raw_loc};", label_loc = label_loc, raw_loc = loc) }, _ => "".to_owned() }; // Process the labels let mut statement = String::new(); if opcode!= "DC" && label!= "" { statement.push_str(label); statement.push_str(":;\n "); } Ok(format!("{}{}", statement, action)) } fn
(var_map: &mut HashMap<String, u32>, counter: &mut u32, loc: &str) -> u32 { let owned_loc = loc.to_owned(); match var_map.get(&owned_loc) { Some(x) => return *x, None => () } var_map.insert(owned_loc, *counter); *counter += 1; *counter - 1 } fn opcode_type(potential_opcode: &str) -> OpcodeType { match potential_opcode { "LOAD" | "STORE" | "ADD" | "SUB" | "MULT" | "DIV" | "BE" | "BG" | "BL" | "BU" | "READ" | "PRINT" => OpcodeType::LocRequired, "END" => OpcodeType::NothingRequired, "DC" => OpcodeType::LocAndLabelRequred, _ => OpcodeType::NotAnOpcode } }
req_mem
identifier_name
main.rs
use std::env; use std::process::exit; use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::io::prelude::*; use std::collections::HashMap; enum OpcodeType { LocRequired, LocAndLabelRequred, NothingRequired, NotAnOpcode } static PROG_NAME: &'static str = "acslasmc v0.1"; static PROG_NAME_LINE: &'static str = "acslasmc v0.1 -- ACSL Assembly to C compiler"; static HEADER: &'static str = "\ #include<stdio.h> int get_mem_size(); int MOD = 1000000; int main() { int MEM_SIZE = get_mem_size(); int acc = 0; int mem[MEM_SIZE]; for (int i=0; i<MEM_SIZE; i++) { mem[i] = 0; } "; static PRE_FOOTER: &'static str = "\ } int get_mem_size() { "; static FOOTER: &'static str = "}"; fn main() { let status = encapsulated_main(); exit(status); }
println!("{}", PROG_NAME_LINE); let mut args = env::args(); let input_file_path = match args.nth(1) { Some(x) => x, None => { println!("Please pass a source file with ACSL assembly code and a target file for generated C code as arguments."); return 2; } }; let output_file_path = match args.next() { Some(x) => x, None => format!("{}_output.c", input_file_path) }; let mut reader = BufReader::new( match File::open(&input_file_path) { Ok(x) => x, Err(_) => { println!("Failed to open source file '{}'.", input_file_path); return 3; } } ); println!("Source file: '{}'.", input_file_path); let mut writer = BufWriter::new( match File::create(&output_file_path) { Ok(x) => x, Err(_) => { println!("Failed to open output file '{}'.", output_file_path); return 3; } } ); println!("Output file: '{}'.", output_file_path); let mut counter: u32 = 0; let mut var_map: HashMap<String, u32> = HashMap::new(); let mut buffer = String::new(); let mut line_count: u32 = 1; // Write the beginnings of the C code writeln!(writer, "// generated from ACSL assembly source '{}' by {}\n{}", input_file_path, PROG_NAME, HEADER).unwrap(); loop { match reader.read_line(&mut buffer) { Ok(bytes_read) => { if bytes_read <= 0 { break; } }, Err(_) => panic!("Failed to read line!") } { let comps: Vec<_> = buffer.trim().split(' ').collect(); let translated = match process_comps(&comps, &mut var_map, &mut counter) { Ok(x) => x, Err(x) => { println!("line {}: error: {}", line_count, x); println!("Compilation failed."); return 1; } }; writeln!(writer, " {}", translated).unwrap(); } line_count += 1; buffer.clear(); } // Write some ending C code writeln!(writer, "{} return {};\n{}\n", PRE_FOOTER, var_map.len(), FOOTER).unwrap(); println!("You may pass the generated C source to a C compiler to run it: e.g."); println!("gcc {of} -o {of}.out &&./{of}.out", of = output_file_path); println!("Compilation complete."); return 0; } fn process_comps(comps: &Vec<&str>, var_map: &mut HashMap<String, u32>, counter: &mut u32) -> Result<String, String> { match opcode_type(match comps.get(0) { Some(x) => x, None => return Ok(String::new()) // blank line, go to next one }) { OpcodeType::LocRequired => return trans(var_map, counter, "", comps[0], match comps.get(1) { None => return Err(format!("missing loc: loc is required for opcode {}", comps[0])), Some(x) => x }), OpcodeType::NothingRequired => return trans(var_map, counter, "", comps[0], ""), OpcodeType::LocAndLabelRequred => return Err(format!("missing label: label is required for opcode {}", comps[0])), OpcodeType::NotAnOpcode => match opcode_type(match comps.get(1) { Some(x) => x, None => return Err(format!("missing opcode, only label provided")) }) { OpcodeType::LocRequired | OpcodeType::LocAndLabelRequred => return trans(var_map, counter, comps[0], comps[1], match comps.get(2) { Some(x) => x, None => return Err(format!("missing loc: loc is required for opcode {}", comps[1])) }), OpcodeType::NothingRequired => return trans(var_map, counter, comps[0], comps[1], ""), OpcodeType::NotAnOpcode => return Err(format!("invalid opcode: {}", comps[1])) } } } fn trans(var_map: &mut HashMap<String, u32>, counter: &mut u32, label: &str, opcode: &str, loc: &str) -> Result<String, String> { let read_loc: String = match loc.chars().nth(0) { Some(x) if x == '=' => loc.split_at(1).1.to_owned(), Some(_) => match var_map.get(&loc.to_owned()) { Some(y) => format!("mem[{}]", y), None => String::new() }, None => String::new() }; let action = match opcode { "LOAD" => format!("acc = {read_loc};", read_loc = read_loc), "STORE" => { let res_loc = req_mem(var_map, counter, loc); format!("mem[{res_loc}] = acc;", res_loc = res_loc) }, "ADD" => format!("acc = (acc + {read_loc}) % MOD;", read_loc = read_loc), "SUB" => format!("acc = (acc - {read_loc}) % MOD;", read_loc = read_loc), "MULT" => format!("acc = (acc * {read_loc}) % MOD;", read_loc = read_loc), "DIV" => format!("acc = (acc / {read_loc}) % MOD;", read_loc = read_loc), "BE" => format!("if (acc == 0) goto {raw_loc};", raw_loc = loc), "BU" => format!("if (acc > 0) goto {raw_loc};", raw_loc = loc), "BL" => format!("if (acc < 0) goto {raw_loc};", raw_loc = loc), "END" => "return 0;".to_owned(), // Ignore LOC field // TODO: Implement READ opcode "READ" => return Err("READ is unimplemented".to_owned()), "PRINT" => format!("printf(\"%d\\n\", {read_loc});", read_loc = read_loc), "DC" => { let label_loc = req_mem(var_map, counter, label); format!("mem[{label_loc}] = {raw_loc};", label_loc = label_loc, raw_loc = loc) }, _ => "".to_owned() }; // Process the labels let mut statement = String::new(); if opcode!= "DC" && label!= "" { statement.push_str(label); statement.push_str(":;\n "); } Ok(format!("{}{}", statement, action)) } fn req_mem(var_map: &mut HashMap<String, u32>, counter: &mut u32, loc: &str) -> u32 { let owned_loc = loc.to_owned(); match var_map.get(&owned_loc) { Some(x) => return *x, None => () } var_map.insert(owned_loc, *counter); *counter += 1; *counter - 1 } fn opcode_type(potential_opcode: &str) -> OpcodeType { match potential_opcode { "LOAD" | "STORE" | "ADD" | "SUB" | "MULT" | "DIV" | "BE" | "BG" | "BL" | "BU" | "READ" | "PRINT" => OpcodeType::LocRequired, "END" => OpcodeType::NothingRequired, "DC" => OpcodeType::LocAndLabelRequred, _ => OpcodeType::NotAnOpcode } }
fn encapsulated_main() -> i32 {
random_line_split
main.rs
use std::env; use std::process::exit; use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::io::prelude::*; use std::collections::HashMap; enum OpcodeType { LocRequired, LocAndLabelRequred, NothingRequired, NotAnOpcode } static PROG_NAME: &'static str = "acslasmc v0.1"; static PROG_NAME_LINE: &'static str = "acslasmc v0.1 -- ACSL Assembly to C compiler"; static HEADER: &'static str = "\ #include<stdio.h> int get_mem_size(); int MOD = 1000000; int main() { int MEM_SIZE = get_mem_size(); int acc = 0; int mem[MEM_SIZE]; for (int i=0; i<MEM_SIZE; i++) { mem[i] = 0; } "; static PRE_FOOTER: &'static str = "\ } int get_mem_size() { "; static FOOTER: &'static str = "}"; fn main() { let status = encapsulated_main(); exit(status); } fn encapsulated_main() -> i32 { println!("{}", PROG_NAME_LINE); let mut args = env::args(); let input_file_path = match args.nth(1) { Some(x) => x, None => { println!("Please pass a source file with ACSL assembly code and a target file for generated C code as arguments."); return 2; } }; let output_file_path = match args.next() { Some(x) => x, None => format!("{}_output.c", input_file_path) }; let mut reader = BufReader::new( match File::open(&input_file_path) { Ok(x) => x, Err(_) => { println!("Failed to open source file '{}'.", input_file_path); return 3; } } ); println!("Source file: '{}'.", input_file_path); let mut writer = BufWriter::new( match File::create(&output_file_path) { Ok(x) => x, Err(_) => { println!("Failed to open output file '{}'.", output_file_path); return 3; } } ); println!("Output file: '{}'.", output_file_path); let mut counter: u32 = 0; let mut var_map: HashMap<String, u32> = HashMap::new(); let mut buffer = String::new(); let mut line_count: u32 = 1; // Write the beginnings of the C code writeln!(writer, "// generated from ACSL assembly source '{}' by {}\n{}", input_file_path, PROG_NAME, HEADER).unwrap(); loop { match reader.read_line(&mut buffer) { Ok(bytes_read) => { if bytes_read <= 0 { break; } }, Err(_) => panic!("Failed to read line!") } { let comps: Vec<_> = buffer.trim().split(' ').collect(); let translated = match process_comps(&comps, &mut var_map, &mut counter) { Ok(x) => x, Err(x) => { println!("line {}: error: {}", line_count, x); println!("Compilation failed."); return 1; } }; writeln!(writer, " {}", translated).unwrap(); } line_count += 1; buffer.clear(); } // Write some ending C code writeln!(writer, "{} return {};\n{}\n", PRE_FOOTER, var_map.len(), FOOTER).unwrap(); println!("You may pass the generated C source to a C compiler to run it: e.g."); println!("gcc {of} -o {of}.out &&./{of}.out", of = output_file_path); println!("Compilation complete."); return 0; } fn process_comps(comps: &Vec<&str>, var_map: &mut HashMap<String, u32>, counter: &mut u32) -> Result<String, String> { match opcode_type(match comps.get(0) { Some(x) => x, None => return Ok(String::new()) // blank line, go to next one }) { OpcodeType::LocRequired => return trans(var_map, counter, "", comps[0], match comps.get(1) { None => return Err(format!("missing loc: loc is required for opcode {}", comps[0])), Some(x) => x }), OpcodeType::NothingRequired => return trans(var_map, counter, "", comps[0], ""), OpcodeType::LocAndLabelRequred => return Err(format!("missing label: label is required for opcode {}", comps[0])), OpcodeType::NotAnOpcode => match opcode_type(match comps.get(1) { Some(x) => x, None => return Err(format!("missing opcode, only label provided")) }) { OpcodeType::LocRequired | OpcodeType::LocAndLabelRequred => return trans(var_map, counter, comps[0], comps[1], match comps.get(2) { Some(x) => x, None => return Err(format!("missing loc: loc is required for opcode {}", comps[1])) }), OpcodeType::NothingRequired => return trans(var_map, counter, comps[0], comps[1], ""), OpcodeType::NotAnOpcode => return Err(format!("invalid opcode: {}", comps[1])) } } } fn trans(var_map: &mut HashMap<String, u32>, counter: &mut u32, label: &str, opcode: &str, loc: &str) -> Result<String, String> { let read_loc: String = match loc.chars().nth(0) { Some(x) if x == '=' => loc.split_at(1).1.to_owned(), Some(_) => match var_map.get(&loc.to_owned()) { Some(y) => format!("mem[{}]", y), None => String::new() }, None => String::new() }; let action = match opcode { "LOAD" => format!("acc = {read_loc};", read_loc = read_loc), "STORE" => { let res_loc = req_mem(var_map, counter, loc); format!("mem[{res_loc}] = acc;", res_loc = res_loc) }, "ADD" => format!("acc = (acc + {read_loc}) % MOD;", read_loc = read_loc), "SUB" => format!("acc = (acc - {read_loc}) % MOD;", read_loc = read_loc), "MULT" => format!("acc = (acc * {read_loc}) % MOD;", read_loc = read_loc), "DIV" => format!("acc = (acc / {read_loc}) % MOD;", read_loc = read_loc), "BE" => format!("if (acc == 0) goto {raw_loc};", raw_loc = loc), "BU" => format!("if (acc > 0) goto {raw_loc};", raw_loc = loc), "BL" => format!("if (acc < 0) goto {raw_loc};", raw_loc = loc), "END" => "return 0;".to_owned(), // Ignore LOC field // TODO: Implement READ opcode "READ" => return Err("READ is unimplemented".to_owned()), "PRINT" => format!("printf(\"%d\\n\", {read_loc});", read_loc = read_loc), "DC" => { let label_loc = req_mem(var_map, counter, label); format!("mem[{label_loc}] = {raw_loc};", label_loc = label_loc, raw_loc = loc) }, _ => "".to_owned() }; // Process the labels let mut statement = String::new(); if opcode!= "DC" && label!= "" { statement.push_str(label); statement.push_str(":;\n "); } Ok(format!("{}{}", statement, action)) } fn req_mem(var_map: &mut HashMap<String, u32>, counter: &mut u32, loc: &str) -> u32
fn opcode_type(potential_opcode: &str) -> OpcodeType { match potential_opcode { "LOAD" | "STORE" | "ADD" | "SUB" | "MULT" | "DIV" | "BE" | "BG" | "BL" | "BU" | "READ" | "PRINT" => OpcodeType::LocRequired, "END" => OpcodeType::NothingRequired, "DC" => OpcodeType::LocAndLabelRequred, _ => OpcodeType::NotAnOpcode } }
{ let owned_loc = loc.to_owned(); match var_map.get(&owned_loc) { Some(x) => return *x, None => () } var_map.insert(owned_loc, *counter); *counter += 1; *counter - 1 }
identifier_body
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout) { // FIXME: this may not work if the character is not in the cache, but this is needed to compile let mut member = match env.cache().read().member(*timeout.server_id, *timeout.user_id) { Some(m) => m, None => { warn!("could not get member for timeout check: missing in cache"); return; }, }; if let Err(e) = member.remove_role(env.http(), *timeout.role_id) { warn!("could not remove timeout role from {}: {}", *timeout.user_id, e); } if let Err(e) = crate::bot::with_connection(|c| diesel::delete(timeout).execute(c)) { warn!("could not delete timeout {}: {}", timeout.id, e); } }
env.config.read().timeouts.role_check_interval.unwrap_or(300) } else { self.ran_once = true; 0 }; thread::sleep(Duration::seconds(sleep).to_std().unwrap()); let now = Utc::now(); let next_five_minutes = (now + Duration::minutes(5)).timestamp(); let mut timeouts: Vec<Timeout> = match crate::bot::with_connection(|c| crate::database::schema::timeouts::dsl::timeouts.load(c)) { Ok(t) => t, Err(e) => { warn!("could not load timeouts: {}", e); continue; }, }; timeouts.retain(|t| t.ends() <= next_five_minutes); if timeouts.is_empty() { continue; } let thread_env = Arc::clone(&env); std::thread::spawn(move || { for (wait, timeout) in Wait::new(timeouts.into_iter().map(|t| (t.ends(), t))) { std::thread::sleep(Duration::seconds(wait).to_std().unwrap()); remove_timeout(&thread_env, &timeout); } }); } } }
impl RunsTask for TimeoutCheckTask { fn start(mut self, env: Arc<BotEnv>) { loop { let sleep = if self.ran_once {
random_line_split
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout) { // FIXME: this may not work if the character is not in the cache, but this is needed to compile let mut member = match env.cache().read().member(*timeout.server_id, *timeout.user_id) { Some(m) => m, None => { warn!("could not get member for timeout check: missing in cache"); return; }, }; if let Err(e) = member.remove_role(env.http(), *timeout.role_id) { warn!("could not remove timeout role from {}: {}", *timeout.user_id, e); } if let Err(e) = crate::bot::with_connection(|c| diesel::delete(timeout).execute(c)) { warn!("could not delete timeout {}: {}", timeout.id, e); } } impl RunsTask for TimeoutCheckTask { fn
(mut self, env: Arc<BotEnv>) { loop { let sleep = if self.ran_once { env.config.read().timeouts.role_check_interval.unwrap_or(300) } else { self.ran_once = true; 0 }; thread::sleep(Duration::seconds(sleep).to_std().unwrap()); let now = Utc::now(); let next_five_minutes = (now + Duration::minutes(5)).timestamp(); let mut timeouts: Vec<Timeout> = match crate::bot::with_connection(|c| crate::database::schema::timeouts::dsl::timeouts.load(c)) { Ok(t) => t, Err(e) => { warn!("could not load timeouts: {}", e); continue; }, }; timeouts.retain(|t| t.ends() <= next_five_minutes); if timeouts.is_empty() { continue; } let thread_env = Arc::clone(&env); std::thread::spawn(move || { for (wait, timeout) in Wait::new(timeouts.into_iter().map(|t| (t.ends(), t))) { std::thread::sleep(Duration::seconds(wait).to_std().unwrap()); remove_timeout(&thread_env, &timeout); } }); } } }
start
identifier_name
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout) { // FIXME: this may not work if the character is not in the cache, but this is needed to compile let mut member = match env.cache().read().member(*timeout.server_id, *timeout.user_id) { Some(m) => m, None => { warn!("could not get member for timeout check: missing in cache"); return; }, }; if let Err(e) = member.remove_role(env.http(), *timeout.role_id) { warn!("could not remove timeout role from {}: {}", *timeout.user_id, e); } if let Err(e) = crate::bot::with_connection(|c| diesel::delete(timeout).execute(c)) { warn!("could not delete timeout {}: {}", timeout.id, e); } } impl RunsTask for TimeoutCheckTask { fn start(mut self, env: Arc<BotEnv>) { loop { let sleep = if self.ran_once { env.config.read().timeouts.role_check_interval.unwrap_or(300) } else { self.ran_once = true; 0 }; thread::sleep(Duration::seconds(sleep).to_std().unwrap()); let now = Utc::now(); let next_five_minutes = (now + Duration::minutes(5)).timestamp(); let mut timeouts: Vec<Timeout> = match crate::bot::with_connection(|c| crate::database::schema::timeouts::dsl::timeouts.load(c)) { Ok(t) => t, Err(e) =>
, }; timeouts.retain(|t| t.ends() <= next_five_minutes); if timeouts.is_empty() { continue; } let thread_env = Arc::clone(&env); std::thread::spawn(move || { for (wait, timeout) in Wait::new(timeouts.into_iter().map(|t| (t.ends(), t))) { std::thread::sleep(Duration::seconds(wait).to_std().unwrap()); remove_timeout(&thread_env, &timeout); } }); } } }
{ warn!("could not load timeouts: {}", e); continue; }
conditional_block
timeout_check.rs
use crate::{ bot::BotEnv, tasks::{RunsTask, Wait}, database::models::Timeout, }; use chrono::{ Duration, prelude::*, }; use diesel::prelude::*; use std::{ sync::Arc, thread, }; #[derive(Default)] pub struct TimeoutCheckTask { ran_once: bool, } pub fn remove_timeout(env: &BotEnv, timeout: &Timeout)
impl RunsTask for TimeoutCheckTask { fn start(mut self, env: Arc<BotEnv>) { loop { let sleep = if self.ran_once { env.config.read().timeouts.role_check_interval.unwrap_or(300) } else { self.ran_once = true; 0 }; thread::sleep(Duration::seconds(sleep).to_std().unwrap()); let now = Utc::now(); let next_five_minutes = (now + Duration::minutes(5)).timestamp(); let mut timeouts: Vec<Timeout> = match crate::bot::with_connection(|c| crate::database::schema::timeouts::dsl::timeouts.load(c)) { Ok(t) => t, Err(e) => { warn!("could not load timeouts: {}", e); continue; }, }; timeouts.retain(|t| t.ends() <= next_five_minutes); if timeouts.is_empty() { continue; } let thread_env = Arc::clone(&env); std::thread::spawn(move || { for (wait, timeout) in Wait::new(timeouts.into_iter().map(|t| (t.ends(), t))) { std::thread::sleep(Duration::seconds(wait).to_std().unwrap()); remove_timeout(&thread_env, &timeout); } }); } } }
{ // FIXME: this may not work if the character is not in the cache, but this is needed to compile let mut member = match env.cache().read().member(*timeout.server_id, *timeout.user_id) { Some(m) => m, None => { warn!("could not get member for timeout check: missing in cache"); return; }, }; if let Err(e) = member.remove_role(env.http(), *timeout.role_id) { warn!("could not remove timeout role from {}: {}", *timeout.user_id, e); } if let Err(e) = crate::bot::with_connection(|c| diesel::delete(timeout).execute(c)) { warn!("could not delete timeout {}: {}", timeout.id, e); } }
identifier_body
mut_.rs
use std::fmt::{self, Debug}; use std::marker; use std::mem; use std::ops::{Index, IndexMut, Deref}; use base; use base::Stride as Base; /// A mutable strided slice. This is equivalent to `&mut [T]`, that /// only refers to every `n`th `T`. /// /// This can be viewed as an immutable strided slice via the `Deref` /// implementation, and so many methods are available through that /// type. /// /// Many functions in this API take `self` and consume it. The /// `reborrow` method is a key part of ensuring that ownership doesn't /// disappear completely: it converts a reference /// `&'b mut MutStride<'a, T>` into a `MutStride<'b, T>`, that is, gives a /// by-value slice with a shorter lifetime. This can then be passed /// directly into the functions that consume `self` without losing /// control of the original slice. #[repr(C)] #[derive(PartialEq, Eq, PartialOrd, Ord)] // FIXME: marker types pub struct Stride<'a,T: 'a> { base: Base<'a, T>, _marker: marker::PhantomData<&'a mut T>, } unsafe impl<'a, T: Sync> Sync for Stride<'a, T> {} unsafe impl<'a, T: Send> Send for Stride<'a, T> {} impl<'a, T: Debug> Debug for Stride<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.base.fmt(f) } } impl<'a, T> Stride<'a, T> { #[inline(always)] fn new_raw(base: Base<'a, T>) -> Stride<'a, T> { Stride { base: base, _marker: marker::PhantomData } } /// Creates a new strided slice directly from a conventional /// slice. The return value has stride 1. #[inline(always)] pub fn new(x: &'a mut [T]) -> Stride<'a, T> { Stride::new_raw(Base::new(x.as_mut_ptr(), x.len(), 1)) } /// Returns the number of elements accessible in `self`. #[inline(always)] pub fn len(&self) -> usize { self.base.len() } /// Returns the offset between successive elements of `self` as a /// count of *elements*, not bytes. #[inline(always)] pub fn stride(&self) -> usize { self.base.stride() / mem::size_of::<T>() } /// Returns a pointer to the first element of this strided slice. /// /// NB. one must be careful since only every `self.stride()`th /// element is guaranteed to have unique access via this object; /// the others may be under the control of some other strided /// slice. #[inline(always)] pub fn as_mut_ptr(&mut self) -> *mut T { self.base.as_mut_ptr() } /// Creates a temporary copy of this strided slice. /// /// This is an explicit form of the reborrowing the compiler does /// implicitly for conventional `&mut` pointers. This is designed /// to allow the by-value `self` methods to be used without losing /// access to the slice. #[inline(always)] pub fn reborrow<'b>(&'b mut self) -> Stride<'b, T> { Stride::new_raw(self.base) } /// Breaks this strided slice into two strided slices pointing to /// alternate elements. /// /// That is, it doubles the stride and (approximately) halves the /// length. A slice pointing to values `[1, 2, 3, 4, 5]` becomes /// two slices `[1, 3, 5]` and `[2, 4]`. This is guaranteed to /// succeed even for mismatched lengths, and even if `self` has /// only zero or one elements. #[inline] pub fn substrides2_mut(self) -> (Stride<'a, T>, Stride<'a, T>) { let (l, r) = self.base.substrides2(); (Stride::new_raw(l), Stride::new_raw(r)) } /// Returns an iterator over `n` strided subslices of `self` each /// pointing to every `n`th element, starting at successive /// offsets. /// /// Calling `substrides(3)` on a slice pointing to `[1, 2, 3, 4, 5, 6, /// 7]` will yield, in turn, `[1, 4, 7]`, `[2, 5]` and finally /// `[3, 6]`. Like with `split2` this is guaranteed to succeed /// (return `n` strided slices) even if `self` has fewer than `n` /// elements. #[inline] pub fn substrides_mut(self, n: usize) -> Substrides<'a, T> { Substrides { base: self.base.substrides(n), } } /// Returns a reference to the `n`th element of `self`, or `None` /// if `n` is out-of-bounds. #[inline] pub fn get_mut<'b>(&'b mut self, n: usize) -> Option<&'b mut T> { self.base.get_mut(n).map(|r| &mut *r) } /// Returns an iterator over references to each successive element /// of `self`. /// /// See also `into_iter` which gives the references the maximum /// possible lifetime at the expense of consume the slice. #[inline] pub fn iter_mut<'b>(&'b mut self) -> ::MutItems<'b, T> { self.reborrow().into_iter() } /// Returns an iterator over reference to each successive element /// of `self`, with the maximum possible lifetime. /// /// See also `iter_mut` which avoids consuming `self` at the /// expense of shorter lifetimes. #[inline] pub fn into_iter(mut self) -> ::MutItems<'a, T> { self.base.iter_mut() } /// Returns a strided slice containing only the elements from /// indices `from` (inclusive) to `to` (exclusive). /// /// # Panic /// /// Panics if `from > to` or if `to > self.len()`. #[inline] pub fn slice_mut(self, from: usize, to: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice(from, to)) } /// Returns a strided slice containing only the elements from /// index `from` (inclusive). /// /// # Panic /// /// Panics if `from > self.len()`. #[inline] pub fn slice_from_mut(self, from: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice_from(from)) } /// Returns a strided slice containing only the elements to /// index `to` (exclusive). /// /// # Panic /// /// Panics if `to > self.len()`. #[inline] pub fn slice_to_mut(self, to: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice_to(to)) } /// Returns two strided slices, the first with elements up to /// `idx` (exclusive) and the second with elements from `idx`. /// /// This is semantically equivalent to `(self.slice_to(idx), /// self.slice_from(idx))`. /// /// # Panic /// /// Panics if `idx > self.len()`. #[inline] pub fn split_at_mut(self, idx: usize) -> (Stride<'a, T>, Stride<'a, T>) { let (l, r) = self.base.split_at(idx); (Stride::new_raw(l), Stride::new_raw(r)) } } impl<'a, T> Index<usize> for Stride<'a, T> { type Output = T; fn index<'b>(&'b self, n: usize) -> &'b T { & (**self)[n] } }
impl<'a, T> IndexMut<usize> for Stride<'a, T> { fn index_mut<'b>(&'b mut self, n: usize) -> &'b mut T { self.get_mut(n).expect("Stride.index_mut: index out of bounds") } } impl<'a, T> Deref for Stride<'a, T> { type Target = ::imm::Stride<'a, T>; fn deref<'b>(&'b self) -> &'b ::imm::Stride<'a, T> { unsafe { mem::transmute(self) } } } /// An iterator over `n` mutable substrides of a given stride, each of /// which points to every `n`th element starting at successive /// offsets. pub struct Substrides<'a, T: 'a> { base: base::Substrides<'a, T>, } impl<'a, T> Iterator for Substrides<'a, T> { type Item = Stride<'a, T>; fn next(&mut self) -> Option<Stride<'a, T>> { match self.base.next() { Some(s) => Some(Stride::new_raw(s)), None => None } } fn size_hint(&self) -> (usize, Option<usize>) { self.base.size_hint() } } #[cfg(test)] mod tests { use super::Stride; make_tests!(substrides2_mut, substrides_mut, slice_mut, slice_to_mut, slice_from_mut, split_at_mut, get_mut, iter_mut, mut); #[test] fn reborrow() { let v = &mut [1u8, 2, 3, 4, 5]; let mut s = Stride::new(v); eq!(s.reborrow(), [1,2,3,4,5]); eq!(s.reborrow(), [1,2,3,4,5]); } }
random_line_split
mut_.rs
use std::fmt::{self, Debug}; use std::marker; use std::mem; use std::ops::{Index, IndexMut, Deref}; use base; use base::Stride as Base; /// A mutable strided slice. This is equivalent to `&mut [T]`, that /// only refers to every `n`th `T`. /// /// This can be viewed as an immutable strided slice via the `Deref` /// implementation, and so many methods are available through that /// type. /// /// Many functions in this API take `self` and consume it. The /// `reborrow` method is a key part of ensuring that ownership doesn't /// disappear completely: it converts a reference /// `&'b mut MutStride<'a, T>` into a `MutStride<'b, T>`, that is, gives a /// by-value slice with a shorter lifetime. This can then be passed /// directly into the functions that consume `self` without losing /// control of the original slice. #[repr(C)] #[derive(PartialEq, Eq, PartialOrd, Ord)] // FIXME: marker types pub struct Stride<'a,T: 'a> { base: Base<'a, T>, _marker: marker::PhantomData<&'a mut T>, } unsafe impl<'a, T: Sync> Sync for Stride<'a, T> {} unsafe impl<'a, T: Send> Send for Stride<'a, T> {} impl<'a, T: Debug> Debug for Stride<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.base.fmt(f) } } impl<'a, T> Stride<'a, T> { #[inline(always)] fn new_raw(base: Base<'a, T>) -> Stride<'a, T> { Stride { base: base, _marker: marker::PhantomData } } /// Creates a new strided slice directly from a conventional /// slice. The return value has stride 1. #[inline(always)] pub fn new(x: &'a mut [T]) -> Stride<'a, T> { Stride::new_raw(Base::new(x.as_mut_ptr(), x.len(), 1)) } /// Returns the number of elements accessible in `self`. #[inline(always)] pub fn len(&self) -> usize { self.base.len() } /// Returns the offset between successive elements of `self` as a /// count of *elements*, not bytes. #[inline(always)] pub fn stride(&self) -> usize { self.base.stride() / mem::size_of::<T>() } /// Returns a pointer to the first element of this strided slice. /// /// NB. one must be careful since only every `self.stride()`th /// element is guaranteed to have unique access via this object; /// the others may be under the control of some other strided /// slice. #[inline(always)] pub fn as_mut_ptr(&mut self) -> *mut T { self.base.as_mut_ptr() } /// Creates a temporary copy of this strided slice. /// /// This is an explicit form of the reborrowing the compiler does /// implicitly for conventional `&mut` pointers. This is designed /// to allow the by-value `self` methods to be used without losing /// access to the slice. #[inline(always)] pub fn reborrow<'b>(&'b mut self) -> Stride<'b, T> { Stride::new_raw(self.base) } /// Breaks this strided slice into two strided slices pointing to /// alternate elements. /// /// That is, it doubles the stride and (approximately) halves the /// length. A slice pointing to values `[1, 2, 3, 4, 5]` becomes /// two slices `[1, 3, 5]` and `[2, 4]`. This is guaranteed to /// succeed even for mismatched lengths, and even if `self` has /// only zero or one elements. #[inline] pub fn substrides2_mut(self) -> (Stride<'a, T>, Stride<'a, T>) { let (l, r) = self.base.substrides2(); (Stride::new_raw(l), Stride::new_raw(r)) } /// Returns an iterator over `n` strided subslices of `self` each /// pointing to every `n`th element, starting at successive /// offsets. /// /// Calling `substrides(3)` on a slice pointing to `[1, 2, 3, 4, 5, 6, /// 7]` will yield, in turn, `[1, 4, 7]`, `[2, 5]` and finally /// `[3, 6]`. Like with `split2` this is guaranteed to succeed /// (return `n` strided slices) even if `self` has fewer than `n` /// elements. #[inline] pub fn substrides_mut(self, n: usize) -> Substrides<'a, T> { Substrides { base: self.base.substrides(n), } } /// Returns a reference to the `n`th element of `self`, or `None` /// if `n` is out-of-bounds. #[inline] pub fn get_mut<'b>(&'b mut self, n: usize) -> Option<&'b mut T> { self.base.get_mut(n).map(|r| &mut *r) } /// Returns an iterator over references to each successive element /// of `self`. /// /// See also `into_iter` which gives the references the maximum /// possible lifetime at the expense of consume the slice. #[inline] pub fn iter_mut<'b>(&'b mut self) -> ::MutItems<'b, T> { self.reborrow().into_iter() } /// Returns an iterator over reference to each successive element /// of `self`, with the maximum possible lifetime. /// /// See also `iter_mut` which avoids consuming `self` at the /// expense of shorter lifetimes. #[inline] pub fn into_iter(mut self) -> ::MutItems<'a, T> { self.base.iter_mut() } /// Returns a strided slice containing only the elements from /// indices `from` (inclusive) to `to` (exclusive). /// /// # Panic /// /// Panics if `from > to` or if `to > self.len()`. #[inline] pub fn slice_mut(self, from: usize, to: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice(from, to)) } /// Returns a strided slice containing only the elements from /// index `from` (inclusive). /// /// # Panic /// /// Panics if `from > self.len()`. #[inline] pub fn slice_from_mut(self, from: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice_from(from)) } /// Returns a strided slice containing only the elements to /// index `to` (exclusive). /// /// # Panic /// /// Panics if `to > self.len()`. #[inline] pub fn slice_to_mut(self, to: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice_to(to)) } /// Returns two strided slices, the first with elements up to /// `idx` (exclusive) and the second with elements from `idx`. /// /// This is semantically equivalent to `(self.slice_to(idx), /// self.slice_from(idx))`. /// /// # Panic /// /// Panics if `idx > self.len()`. #[inline] pub fn split_at_mut(self, idx: usize) -> (Stride<'a, T>, Stride<'a, T>) { let (l, r) = self.base.split_at(idx); (Stride::new_raw(l), Stride::new_raw(r)) } } impl<'a, T> Index<usize> for Stride<'a, T> { type Output = T; fn index<'b>(&'b self, n: usize) -> &'b T { & (**self)[n] } } impl<'a, T> IndexMut<usize> for Stride<'a, T> { fn index_mut<'b>(&'b mut self, n: usize) -> &'b mut T { self.get_mut(n).expect("Stride.index_mut: index out of bounds") } } impl<'a, T> Deref for Stride<'a, T> { type Target = ::imm::Stride<'a, T>; fn deref<'b>(&'b self) -> &'b ::imm::Stride<'a, T> { unsafe { mem::transmute(self) } } } /// An iterator over `n` mutable substrides of a given stride, each of /// which points to every `n`th element starting at successive /// offsets. pub struct Substrides<'a, T: 'a> { base: base::Substrides<'a, T>, } impl<'a, T> Iterator for Substrides<'a, T> { type Item = Stride<'a, T>; fn next(&mut self) -> Option<Stride<'a, T>> { match self.base.next() { Some(s) => Some(Stride::new_raw(s)), None => None } } fn size_hint(&self) -> (usize, Option<usize>) { self.base.size_hint() } } #[cfg(test)] mod tests { use super::Stride; make_tests!(substrides2_mut, substrides_mut, slice_mut, slice_to_mut, slice_from_mut, split_at_mut, get_mut, iter_mut, mut); #[test] fn
() { let v = &mut [1u8, 2, 3, 4, 5]; let mut s = Stride::new(v); eq!(s.reborrow(), [1,2,3,4,5]); eq!(s.reborrow(), [1,2,3,4,5]); } }
reborrow
identifier_name
mut_.rs
use std::fmt::{self, Debug}; use std::marker; use std::mem; use std::ops::{Index, IndexMut, Deref}; use base; use base::Stride as Base; /// A mutable strided slice. This is equivalent to `&mut [T]`, that /// only refers to every `n`th `T`. /// /// This can be viewed as an immutable strided slice via the `Deref` /// implementation, and so many methods are available through that /// type. /// /// Many functions in this API take `self` and consume it. The /// `reborrow` method is a key part of ensuring that ownership doesn't /// disappear completely: it converts a reference /// `&'b mut MutStride<'a, T>` into a `MutStride<'b, T>`, that is, gives a /// by-value slice with a shorter lifetime. This can then be passed /// directly into the functions that consume `self` without losing /// control of the original slice. #[repr(C)] #[derive(PartialEq, Eq, PartialOrd, Ord)] // FIXME: marker types pub struct Stride<'a,T: 'a> { base: Base<'a, T>, _marker: marker::PhantomData<&'a mut T>, } unsafe impl<'a, T: Sync> Sync for Stride<'a, T> {} unsafe impl<'a, T: Send> Send for Stride<'a, T> {} impl<'a, T: Debug> Debug for Stride<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.base.fmt(f) } } impl<'a, T> Stride<'a, T> { #[inline(always)] fn new_raw(base: Base<'a, T>) -> Stride<'a, T> { Stride { base: base, _marker: marker::PhantomData } } /// Creates a new strided slice directly from a conventional /// slice. The return value has stride 1. #[inline(always)] pub fn new(x: &'a mut [T]) -> Stride<'a, T> { Stride::new_raw(Base::new(x.as_mut_ptr(), x.len(), 1)) } /// Returns the number of elements accessible in `self`. #[inline(always)] pub fn len(&self) -> usize { self.base.len() } /// Returns the offset between successive elements of `self` as a /// count of *elements*, not bytes. #[inline(always)] pub fn stride(&self) -> usize { self.base.stride() / mem::size_of::<T>() } /// Returns a pointer to the first element of this strided slice. /// /// NB. one must be careful since only every `self.stride()`th /// element is guaranteed to have unique access via this object; /// the others may be under the control of some other strided /// slice. #[inline(always)] pub fn as_mut_ptr(&mut self) -> *mut T { self.base.as_mut_ptr() } /// Creates a temporary copy of this strided slice. /// /// This is an explicit form of the reborrowing the compiler does /// implicitly for conventional `&mut` pointers. This is designed /// to allow the by-value `self` methods to be used without losing /// access to the slice. #[inline(always)] pub fn reborrow<'b>(&'b mut self) -> Stride<'b, T> { Stride::new_raw(self.base) } /// Breaks this strided slice into two strided slices pointing to /// alternate elements. /// /// That is, it doubles the stride and (approximately) halves the /// length. A slice pointing to values `[1, 2, 3, 4, 5]` becomes /// two slices `[1, 3, 5]` and `[2, 4]`. This is guaranteed to /// succeed even for mismatched lengths, and even if `self` has /// only zero or one elements. #[inline] pub fn substrides2_mut(self) -> (Stride<'a, T>, Stride<'a, T>) { let (l, r) = self.base.substrides2(); (Stride::new_raw(l), Stride::new_raw(r)) } /// Returns an iterator over `n` strided subslices of `self` each /// pointing to every `n`th element, starting at successive /// offsets. /// /// Calling `substrides(3)` on a slice pointing to `[1, 2, 3, 4, 5, 6, /// 7]` will yield, in turn, `[1, 4, 7]`, `[2, 5]` and finally /// `[3, 6]`. Like with `split2` this is guaranteed to succeed /// (return `n` strided slices) even if `self` has fewer than `n` /// elements. #[inline] pub fn substrides_mut(self, n: usize) -> Substrides<'a, T> { Substrides { base: self.base.substrides(n), } } /// Returns a reference to the `n`th element of `self`, or `None` /// if `n` is out-of-bounds. #[inline] pub fn get_mut<'b>(&'b mut self, n: usize) -> Option<&'b mut T> { self.base.get_mut(n).map(|r| &mut *r) } /// Returns an iterator over references to each successive element /// of `self`. /// /// See also `into_iter` which gives the references the maximum /// possible lifetime at the expense of consume the slice. #[inline] pub fn iter_mut<'b>(&'b mut self) -> ::MutItems<'b, T> { self.reborrow().into_iter() } /// Returns an iterator over reference to each successive element /// of `self`, with the maximum possible lifetime. /// /// See also `iter_mut` which avoids consuming `self` at the /// expense of shorter lifetimes. #[inline] pub fn into_iter(mut self) -> ::MutItems<'a, T> { self.base.iter_mut() } /// Returns a strided slice containing only the elements from /// indices `from` (inclusive) to `to` (exclusive). /// /// # Panic /// /// Panics if `from > to` or if `to > self.len()`. #[inline] pub fn slice_mut(self, from: usize, to: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice(from, to)) } /// Returns a strided slice containing only the elements from /// index `from` (inclusive). /// /// # Panic /// /// Panics if `from > self.len()`. #[inline] pub fn slice_from_mut(self, from: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice_from(from)) } /// Returns a strided slice containing only the elements to /// index `to` (exclusive). /// /// # Panic /// /// Panics if `to > self.len()`. #[inline] pub fn slice_to_mut(self, to: usize) -> Stride<'a, T> { Stride::new_raw(self.base.slice_to(to)) } /// Returns two strided slices, the first with elements up to /// `idx` (exclusive) and the second with elements from `idx`. /// /// This is semantically equivalent to `(self.slice_to(idx), /// self.slice_from(idx))`. /// /// # Panic /// /// Panics if `idx > self.len()`. #[inline] pub fn split_at_mut(self, idx: usize) -> (Stride<'a, T>, Stride<'a, T>) { let (l, r) = self.base.split_at(idx); (Stride::new_raw(l), Stride::new_raw(r)) } } impl<'a, T> Index<usize> for Stride<'a, T> { type Output = T; fn index<'b>(&'b self, n: usize) -> &'b T { & (**self)[n] } } impl<'a, T> IndexMut<usize> for Stride<'a, T> { fn index_mut<'b>(&'b mut self, n: usize) -> &'b mut T { self.get_mut(n).expect("Stride.index_mut: index out of bounds") } } impl<'a, T> Deref for Stride<'a, T> { type Target = ::imm::Stride<'a, T>; fn deref<'b>(&'b self) -> &'b ::imm::Stride<'a, T>
} /// An iterator over `n` mutable substrides of a given stride, each of /// which points to every `n`th element starting at successive /// offsets. pub struct Substrides<'a, T: 'a> { base: base::Substrides<'a, T>, } impl<'a, T> Iterator for Substrides<'a, T> { type Item = Stride<'a, T>; fn next(&mut self) -> Option<Stride<'a, T>> { match self.base.next() { Some(s) => Some(Stride::new_raw(s)), None => None } } fn size_hint(&self) -> (usize, Option<usize>) { self.base.size_hint() } } #[cfg(test)] mod tests { use super::Stride; make_tests!(substrides2_mut, substrides_mut, slice_mut, slice_to_mut, slice_from_mut, split_at_mut, get_mut, iter_mut, mut); #[test] fn reborrow() { let v = &mut [1u8, 2, 3, 4, 5]; let mut s = Stride::new(v); eq!(s.reborrow(), [1,2,3,4,5]); eq!(s.reborrow(), [1,2,3,4,5]); } }
{ unsafe { mem::transmute(self) } }
identifier_body
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLExtraData}; use gecko_bindings::structs::mozilla::css::URLValueData; use gecko_bindings::structs::root::{nsStyleImageRequest, RustString}; use gecko_bindings::structs::root::mozilla::css::ImageValue; use gecko_bindings::sugar::refptr::RefPtr; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use parser::ParserContext; use servo_arc::{Arc, RawOffsetArc}; use std::fmt; use std::mem; use style_traits::{ToCss, ParseError}; /// A specified url() value for gecko. Gecko does not eagerly resolve SpecifiedUrls. #[derive(Clone, Debug, PartialEq)] pub struct SpecifiedUrl { /// The URL in unresolved string form. /// /// Refcounted since cloning this should be cheap and data: uris can be /// really large. serialization: Arc<String>, /// The URL extra data. pub extra_data: RefPtr<URLExtraData>, /// Cache ImageValue, if any, so that we can reuse it while rematching a /// a property with this specified url value. pub image_value: Option<RefPtr<ImageValue>>, } trivial_to_computed_value!(SpecifiedUrl); impl SpecifiedUrl { /// Try to parse a URL from a string value that is a valid CSS token for a /// URL. /// /// Returns `Err` in the case that extra_data is incomplete. pub fn parse_from_string<'a>(url: String, context: &ParserContext) -> Result<Self, ParseError<'a>> { Ok(SpecifiedUrl { serialization: Arc::new(url), extra_data: context.url_data.clone(), image_value: None, }) } /// Returns true if the URL is definitely invalid. We don't eagerly resolve /// URLs in gecko, so we just return false here. /// use its |resolved| status. pub fn is_invalid(&self) -> bool { false } /// Convert from URLValueData to SpecifiedUrl. pub unsafe fn from_url_value_data(url: &URLValueData) -> Result<SpecifiedUrl, ()> { Ok(SpecifiedUrl { serialization: if url.mUsingRustString { let arc_type = url.mStrings.mRustString.as_ref() as *const _ as *const RawOffsetArc<String>; Arc::from_raw_offset((*arc_type).clone()) } else { Arc::new(url.mStrings.mString.as_ref().to_string()) }, extra_data: url.mExtraData.to_safe(), image_value: None, }) }
/// Convert from nsStyleImageRequest to SpecifiedUrl. pub unsafe fn from_image_request(image_request: &nsStyleImageRequest) -> Result<SpecifiedUrl, ()> { if image_request.mImageValue.mRawPtr.is_null() { return Err(()); } let image_value = image_request.mImageValue.mRawPtr.as_ref().unwrap(); let ref url_value_data = image_value._base; let mut result = try!(Self::from_url_value_data(url_value_data)); result.build_image_value(); Ok(result) } /// Returns true if this URL looks like a fragment. /// See https://drafts.csswg.org/css-values/#local-urls pub fn is_fragment(&self) -> bool { self.as_str().chars().next().map_or(false, |c| c == '#') } /// Return the resolved url as string, or the empty string if it's invalid. /// /// FIXME(bholley): This returns the unresolved URL while the servo version /// returns the resolved URL. pub fn as_str(&self) -> &str { &*self.serialization } /// Little helper for Gecko's ffi. pub fn as_slice_components(&self) -> (*const u8, usize) { (self.serialization.as_str().as_ptr(), self.serialization.as_str().len()) } /// Create a bundled URI suitable for sending to Gecko /// to be constructed into a css::URLValue pub fn for_ffi(&self) -> ServoBundledURI { let (ptr, len) = self.as_slice_components(); ServoBundledURI { mURLString: ptr, mURLStringLength: len as u32, mExtraData: self.extra_data.get(), } } /// Build and carry an image value on request. pub fn build_image_value(&mut self) { use gecko_bindings::bindings::Gecko_ImageValue_Create; debug_assert_eq!(self.image_value, None); self.image_value = { unsafe { let arc_offset = Arc::into_raw_offset(self.serialization.clone()); let ptr = Gecko_ImageValue_Create( self.for_ffi(), mem::transmute::<_, RawOffsetArc<RustString>>(arc_offset)); // We do not expect Gecko_ImageValue_Create returns null. debug_assert!(!ptr.is_null()); Some(RefPtr::from_addrefed(ptr)) } } } } impl ToCss for SpecifiedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("url(")?; self.serialization.to_css(dest)?; dest.write_str(")") } } impl MallocSizeOf for SpecifiedUrl { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { use gecko_bindings::bindings::Gecko_ImageValue_SizeOfIncludingThis; let mut n = 0; // XXX: measure `serialization` once bug 1397971 lands // We ignore `extra_data`, because RefPtr is tricky, and there aren't // many of them in practise (sharing is common). if let Some(ref image_value) = self.image_value { // Although this is a RefPtr, this is the primary reference because // SpecifiedUrl is responsible for creating the image_value. So we // measure unconditionally here. n += unsafe { Gecko_ImageValue_SizeOfIncludingThis(image_value.clone().get()) }; } n } }
random_line_split
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLExtraData}; use gecko_bindings::structs::mozilla::css::URLValueData; use gecko_bindings::structs::root::{nsStyleImageRequest, RustString}; use gecko_bindings::structs::root::mozilla::css::ImageValue; use gecko_bindings::sugar::refptr::RefPtr; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use parser::ParserContext; use servo_arc::{Arc, RawOffsetArc}; use std::fmt; use std::mem; use style_traits::{ToCss, ParseError}; /// A specified url() value for gecko. Gecko does not eagerly resolve SpecifiedUrls. #[derive(Clone, Debug, PartialEq)] pub struct SpecifiedUrl { /// The URL in unresolved string form. /// /// Refcounted since cloning this should be cheap and data: uris can be /// really large. serialization: Arc<String>, /// The URL extra data. pub extra_data: RefPtr<URLExtraData>, /// Cache ImageValue, if any, so that we can reuse it while rematching a /// a property with this specified url value. pub image_value: Option<RefPtr<ImageValue>>, } trivial_to_computed_value!(SpecifiedUrl); impl SpecifiedUrl { /// Try to parse a URL from a string value that is a valid CSS token for a /// URL. /// /// Returns `Err` in the case that extra_data is incomplete. pub fn parse_from_string<'a>(url: String, context: &ParserContext) -> Result<Self, ParseError<'a>> { Ok(SpecifiedUrl { serialization: Arc::new(url), extra_data: context.url_data.clone(), image_value: None, }) } /// Returns true if the URL is definitely invalid. We don't eagerly resolve /// URLs in gecko, so we just return false here. /// use its |resolved| status. pub fn is_invalid(&self) -> bool { false } /// Convert from URLValueData to SpecifiedUrl. pub unsafe fn from_url_value_data(url: &URLValueData) -> Result<SpecifiedUrl, ()> { Ok(SpecifiedUrl { serialization: if url.mUsingRustString { let arc_type = url.mStrings.mRustString.as_ref() as *const _ as *const RawOffsetArc<String>; Arc::from_raw_offset((*arc_type).clone()) } else { Arc::new(url.mStrings.mString.as_ref().to_string()) }, extra_data: url.mExtraData.to_safe(), image_value: None, }) } /// Convert from nsStyleImageRequest to SpecifiedUrl. pub unsafe fn from_image_request(image_request: &nsStyleImageRequest) -> Result<SpecifiedUrl, ()> { if image_request.mImageValue.mRawPtr.is_null() { return Err(()); } let image_value = image_request.mImageValue.mRawPtr.as_ref().unwrap(); let ref url_value_data = image_value._base; let mut result = try!(Self::from_url_value_data(url_value_data)); result.build_image_value(); Ok(result) } /// Returns true if this URL looks like a fragment. /// See https://drafts.csswg.org/css-values/#local-urls pub fn is_fragment(&self) -> bool { self.as_str().chars().next().map_or(false, |c| c == '#') } /// Return the resolved url as string, or the empty string if it's invalid. /// /// FIXME(bholley): This returns the unresolved URL while the servo version /// returns the resolved URL. pub fn as_str(&self) -> &str { &*self.serialization } /// Little helper for Gecko's ffi. pub fn as_slice_components(&self) -> (*const u8, usize) { (self.serialization.as_str().as_ptr(), self.serialization.as_str().len()) } /// Create a bundled URI suitable for sending to Gecko /// to be constructed into a css::URLValue pub fn for_ffi(&self) -> ServoBundledURI { let (ptr, len) = self.as_slice_components(); ServoBundledURI { mURLString: ptr, mURLStringLength: len as u32, mExtraData: self.extra_data.get(), } } /// Build and carry an image value on request. pub fn build_image_value(&mut self) { use gecko_bindings::bindings::Gecko_ImageValue_Create; debug_assert_eq!(self.image_value, None); self.image_value = { unsafe { let arc_offset = Arc::into_raw_offset(self.serialization.clone()); let ptr = Gecko_ImageValue_Create( self.for_ffi(), mem::transmute::<_, RawOffsetArc<RustString>>(arc_offset)); // We do not expect Gecko_ImageValue_Create returns null. debug_assert!(!ptr.is_null()); Some(RefPtr::from_addrefed(ptr)) } } } } impl ToCss for SpecifiedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("url(")?; self.serialization.to_css(dest)?; dest.write_str(")") } } impl MallocSizeOf for SpecifiedUrl { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize
}
{ use gecko_bindings::bindings::Gecko_ImageValue_SizeOfIncludingThis; let mut n = 0; // XXX: measure `serialization` once bug 1397971 lands // We ignore `extra_data`, because RefPtr is tricky, and there aren't // many of them in practise (sharing is common). if let Some(ref image_value) = self.image_value { // Although this is a RefPtr, this is the primary reference because // SpecifiedUrl is responsible for creating the image_value. So we // measure unconditionally here. n += unsafe { Gecko_ImageValue_SizeOfIncludingThis(image_value.clone().get()) }; } n }
identifier_body
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLExtraData}; use gecko_bindings::structs::mozilla::css::URLValueData; use gecko_bindings::structs::root::{nsStyleImageRequest, RustString}; use gecko_bindings::structs::root::mozilla::css::ImageValue; use gecko_bindings::sugar::refptr::RefPtr; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use parser::ParserContext; use servo_arc::{Arc, RawOffsetArc}; use std::fmt; use std::mem; use style_traits::{ToCss, ParseError}; /// A specified url() value for gecko. Gecko does not eagerly resolve SpecifiedUrls. #[derive(Clone, Debug, PartialEq)] pub struct SpecifiedUrl { /// The URL in unresolved string form. /// /// Refcounted since cloning this should be cheap and data: uris can be /// really large. serialization: Arc<String>, /// The URL extra data. pub extra_data: RefPtr<URLExtraData>, /// Cache ImageValue, if any, so that we can reuse it while rematching a /// a property with this specified url value. pub image_value: Option<RefPtr<ImageValue>>, } trivial_to_computed_value!(SpecifiedUrl); impl SpecifiedUrl { /// Try to parse a URL from a string value that is a valid CSS token for a /// URL. /// /// Returns `Err` in the case that extra_data is incomplete. pub fn parse_from_string<'a>(url: String, context: &ParserContext) -> Result<Self, ParseError<'a>> { Ok(SpecifiedUrl { serialization: Arc::new(url), extra_data: context.url_data.clone(), image_value: None, }) } /// Returns true if the URL is definitely invalid. We don't eagerly resolve /// URLs in gecko, so we just return false here. /// use its |resolved| status. pub fn is_invalid(&self) -> bool { false } /// Convert from URLValueData to SpecifiedUrl. pub unsafe fn from_url_value_data(url: &URLValueData) -> Result<SpecifiedUrl, ()> { Ok(SpecifiedUrl { serialization: if url.mUsingRustString { let arc_type = url.mStrings.mRustString.as_ref() as *const _ as *const RawOffsetArc<String>; Arc::from_raw_offset((*arc_type).clone()) } else { Arc::new(url.mStrings.mString.as_ref().to_string()) }, extra_data: url.mExtraData.to_safe(), image_value: None, }) } /// Convert from nsStyleImageRequest to SpecifiedUrl. pub unsafe fn from_image_request(image_request: &nsStyleImageRequest) -> Result<SpecifiedUrl, ()> { if image_request.mImageValue.mRawPtr.is_null() { return Err(()); } let image_value = image_request.mImageValue.mRawPtr.as_ref().unwrap(); let ref url_value_data = image_value._base; let mut result = try!(Self::from_url_value_data(url_value_data)); result.build_image_value(); Ok(result) } /// Returns true if this URL looks like a fragment. /// See https://drafts.csswg.org/css-values/#local-urls pub fn is_fragment(&self) -> bool { self.as_str().chars().next().map_or(false, |c| c == '#') } /// Return the resolved url as string, or the empty string if it's invalid. /// /// FIXME(bholley): This returns the unresolved URL while the servo version /// returns the resolved URL. pub fn as_str(&self) -> &str { &*self.serialization } /// Little helper for Gecko's ffi. pub fn as_slice_components(&self) -> (*const u8, usize) { (self.serialization.as_str().as_ptr(), self.serialization.as_str().len()) } /// Create a bundled URI suitable for sending to Gecko /// to be constructed into a css::URLValue pub fn for_ffi(&self) -> ServoBundledURI { let (ptr, len) = self.as_slice_components(); ServoBundledURI { mURLString: ptr, mURLStringLength: len as u32, mExtraData: self.extra_data.get(), } } /// Build and carry an image value on request. pub fn
(&mut self) { use gecko_bindings::bindings::Gecko_ImageValue_Create; debug_assert_eq!(self.image_value, None); self.image_value = { unsafe { let arc_offset = Arc::into_raw_offset(self.serialization.clone()); let ptr = Gecko_ImageValue_Create( self.for_ffi(), mem::transmute::<_, RawOffsetArc<RustString>>(arc_offset)); // We do not expect Gecko_ImageValue_Create returns null. debug_assert!(!ptr.is_null()); Some(RefPtr::from_addrefed(ptr)) } } } } impl ToCss for SpecifiedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("url(")?; self.serialization.to_css(dest)?; dest.write_str(")") } } impl MallocSizeOf for SpecifiedUrl { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { use gecko_bindings::bindings::Gecko_ImageValue_SizeOfIncludingThis; let mut n = 0; // XXX: measure `serialization` once bug 1397971 lands // We ignore `extra_data`, because RefPtr is tricky, and there aren't // many of them in practise (sharing is common). if let Some(ref image_value) = self.image_value { // Although this is a RefPtr, this is the primary reference because // SpecifiedUrl is responsible for creating the image_value. So we // measure unconditionally here. n += unsafe { Gecko_ImageValue_SizeOfIncludingThis(image_value.clone().get()) }; } n } }
build_image_value
identifier_name
url.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/. */ //! Common handling for the specified value CSS url() values. use gecko_bindings::structs::{ServoBundledURI, URLExtraData}; use gecko_bindings::structs::mozilla::css::URLValueData; use gecko_bindings::structs::root::{nsStyleImageRequest, RustString}; use gecko_bindings::structs::root::mozilla::css::ImageValue; use gecko_bindings::sugar::refptr::RefPtr; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use parser::ParserContext; use servo_arc::{Arc, RawOffsetArc}; use std::fmt; use std::mem; use style_traits::{ToCss, ParseError}; /// A specified url() value for gecko. Gecko does not eagerly resolve SpecifiedUrls. #[derive(Clone, Debug, PartialEq)] pub struct SpecifiedUrl { /// The URL in unresolved string form. /// /// Refcounted since cloning this should be cheap and data: uris can be /// really large. serialization: Arc<String>, /// The URL extra data. pub extra_data: RefPtr<URLExtraData>, /// Cache ImageValue, if any, so that we can reuse it while rematching a /// a property with this specified url value. pub image_value: Option<RefPtr<ImageValue>>, } trivial_to_computed_value!(SpecifiedUrl); impl SpecifiedUrl { /// Try to parse a URL from a string value that is a valid CSS token for a /// URL. /// /// Returns `Err` in the case that extra_data is incomplete. pub fn parse_from_string<'a>(url: String, context: &ParserContext) -> Result<Self, ParseError<'a>> { Ok(SpecifiedUrl { serialization: Arc::new(url), extra_data: context.url_data.clone(), image_value: None, }) } /// Returns true if the URL is definitely invalid. We don't eagerly resolve /// URLs in gecko, so we just return false here. /// use its |resolved| status. pub fn is_invalid(&self) -> bool { false } /// Convert from URLValueData to SpecifiedUrl. pub unsafe fn from_url_value_data(url: &URLValueData) -> Result<SpecifiedUrl, ()> { Ok(SpecifiedUrl { serialization: if url.mUsingRustString { let arc_type = url.mStrings.mRustString.as_ref() as *const _ as *const RawOffsetArc<String>; Arc::from_raw_offset((*arc_type).clone()) } else { Arc::new(url.mStrings.mString.as_ref().to_string()) }, extra_data: url.mExtraData.to_safe(), image_value: None, }) } /// Convert from nsStyleImageRequest to SpecifiedUrl. pub unsafe fn from_image_request(image_request: &nsStyleImageRequest) -> Result<SpecifiedUrl, ()> { if image_request.mImageValue.mRawPtr.is_null()
let image_value = image_request.mImageValue.mRawPtr.as_ref().unwrap(); let ref url_value_data = image_value._base; let mut result = try!(Self::from_url_value_data(url_value_data)); result.build_image_value(); Ok(result) } /// Returns true if this URL looks like a fragment. /// See https://drafts.csswg.org/css-values/#local-urls pub fn is_fragment(&self) -> bool { self.as_str().chars().next().map_or(false, |c| c == '#') } /// Return the resolved url as string, or the empty string if it's invalid. /// /// FIXME(bholley): This returns the unresolved URL while the servo version /// returns the resolved URL. pub fn as_str(&self) -> &str { &*self.serialization } /// Little helper for Gecko's ffi. pub fn as_slice_components(&self) -> (*const u8, usize) { (self.serialization.as_str().as_ptr(), self.serialization.as_str().len()) } /// Create a bundled URI suitable for sending to Gecko /// to be constructed into a css::URLValue pub fn for_ffi(&self) -> ServoBundledURI { let (ptr, len) = self.as_slice_components(); ServoBundledURI { mURLString: ptr, mURLStringLength: len as u32, mExtraData: self.extra_data.get(), } } /// Build and carry an image value on request. pub fn build_image_value(&mut self) { use gecko_bindings::bindings::Gecko_ImageValue_Create; debug_assert_eq!(self.image_value, None); self.image_value = { unsafe { let arc_offset = Arc::into_raw_offset(self.serialization.clone()); let ptr = Gecko_ImageValue_Create( self.for_ffi(), mem::transmute::<_, RawOffsetArc<RustString>>(arc_offset)); // We do not expect Gecko_ImageValue_Create returns null. debug_assert!(!ptr.is_null()); Some(RefPtr::from_addrefed(ptr)) } } } } impl ToCss for SpecifiedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("url(")?; self.serialization.to_css(dest)?; dest.write_str(")") } } impl MallocSizeOf for SpecifiedUrl { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { use gecko_bindings::bindings::Gecko_ImageValue_SizeOfIncludingThis; let mut n = 0; // XXX: measure `serialization` once bug 1397971 lands // We ignore `extra_data`, because RefPtr is tricky, and there aren't // many of them in practise (sharing is common). if let Some(ref image_value) = self.image_value { // Although this is a RefPtr, this is the primary reference because // SpecifiedUrl is responsible for creating the image_value. So we // measure unconditionally here. n += unsafe { Gecko_ImageValue_SizeOfIncludingThis(image_value.clone().get()) }; } n } }
{ return Err(()); }
conditional_block
node.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program 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. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use bytes::*; use hashdb::DBValue; use rlp::*; /// Partial node key type. pub type HashKey = Vec<u8>; pub type NodeKey = Vec<u8>; /// Type of node in the avl and essential information thereof. #[derive(Eq, PartialEq, Debug, Clone)] pub enum
<'a> { /// Null avl node; could be an empty root or an empty branch entry. Empty, /// Leaf node; has key slice and value. Value may not be empty. Leaf(NodeKey, &'a [u8]), /// Branch node; has a key, 2 child nodes (each possibly null) and a height. Branch(u32, NodeKey, [&'a [u8]; 2]), } impl<'a> Node<'a> { /// Decode the `node_rlp` and return the Node. pub fn decoded(node_rlp: &'a [u8]) -> Self { let r = Rlp::new(node_rlp); match r.prototype() { // either leaf or extension - decode first item with NibbleSlice::??? // and use is_leaf return to figure out which. // if leaf, second item is a value (is_data()) // if extension, second item is a node (either SHA3 to be looked up and // fed back into this function or inline RLP which can be fed back into this function). Prototype::List(2) => { Node::Leaf(r.at(0).data().to_vec(), r.at(1).data()) } // branch - first 16 are nodes, 17th is a value (or empty). Prototype::List(4) => { let mut nodes = [&[] as &[u8]; 2]; for i in 0..2 { nodes[i] = r.at(i).as_raw(); } let height: u32 = decode(r.at(2).data()); Node::Branch(height, r.at(3).data().to_vec(), nodes) } // an empty branch index. Prototype::Data(0) => Node::Empty, // something went wrong. _ => panic!("Rlp is not valid."), } } /// Encode the node into RLP. /// /// Will always return the direct node RLP even if it's 32 or more bytes. To get the /// RLP which would be valid for using in another node, use `encoded_and_added()`. pub fn encoded(&self) -> Bytes { match *self { Node::Leaf(ref key, ref value) => { let mut stream = RlpStream::new_list(2); stream.append(key); stream.append(value); stream.out() } Node::Branch(ref height, ref key, ref nodes) => { let mut stream = RlpStream::new_list(4); for i in 0..2 { stream.append_raw(nodes[i], 1); } stream.append(height); stream.append(key); stream.out() } Node::Empty => { let mut stream = RlpStream::new(); stream.append_empty_data(); stream.out() } } } } /// An owning node type. Useful for avl iterators. #[derive(Debug, PartialEq, Eq)] pub enum OwnedNode { /// Empty avl node. Empty, /// Leaf node: partial key and value. Leaf(NodeKey, DBValue), /// Branch node: a key, 2 children and a height. Branch(u32, NodeKey, [HashKey; 2]), } impl Clone for OwnedNode { fn clone(&self) -> Self { match *self { OwnedNode::Empty => OwnedNode::Empty, OwnedNode::Leaf(ref k, ref v) => OwnedNode::Leaf(k.clone(), v.clone()), OwnedNode::Branch(h, ref k, ref c) => { let mut children = [HashKey::new(), HashKey::new()]; for (owned, borrowed) in children.iter_mut().zip(c.iter()) { *owned = borrowed.clone() } OwnedNode::Branch(h, k.clone(), children) } } } } impl<'a> From<Node<'a>> for OwnedNode { fn from(node: Node<'a>) -> Self { match node { Node::Empty => OwnedNode::Empty, Node::Leaf(k, v) => OwnedNode::Leaf(k.into(), DBValue::from_slice(v)), Node::Branch(h, k, c) => { let mut children = [HashKey::new(), HashKey::new()]; for (owned, borrowed) in children.iter_mut().zip(c.iter()) { *owned = borrowed.to_vec() } OwnedNode::Branch(h, k.into(), children) } } } }
Node
identifier_name
node.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program 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. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use bytes::*; use hashdb::DBValue; use rlp::*; /// Partial node key type. pub type HashKey = Vec<u8>; pub type NodeKey = Vec<u8>; /// Type of node in the avl and essential information thereof. #[derive(Eq, PartialEq, Debug, Clone)] pub enum Node<'a> { /// Null avl node; could be an empty root or an empty branch entry. Empty, /// Leaf node; has key slice and value. Value may not be empty. Leaf(NodeKey, &'a [u8]), /// Branch node; has a key, 2 child nodes (each possibly null) and a height. Branch(u32, NodeKey, [&'a [u8]; 2]), } impl<'a> Node<'a> { /// Decode the `node_rlp` and return the Node. pub fn decoded(node_rlp: &'a [u8]) -> Self
// an empty branch index. Prototype::Data(0) => Node::Empty, // something went wrong. _ => panic!("Rlp is not valid."), } } /// Encode the node into RLP. /// /// Will always return the direct node RLP even if it's 32 or more bytes. To get the /// RLP which would be valid for using in another node, use `encoded_and_added()`. pub fn encoded(&self) -> Bytes { match *self { Node::Leaf(ref key, ref value) => { let mut stream = RlpStream::new_list(2); stream.append(key); stream.append(value); stream.out() } Node::Branch(ref height, ref key, ref nodes) => { let mut stream = RlpStream::new_list(4); for i in 0..2 { stream.append_raw(nodes[i], 1); } stream.append(height); stream.append(key); stream.out() } Node::Empty => { let mut stream = RlpStream::new(); stream.append_empty_data(); stream.out() } } } } /// An owning node type. Useful for avl iterators. #[derive(Debug, PartialEq, Eq)] pub enum OwnedNode { /// Empty avl node. Empty, /// Leaf node: partial key and value. Leaf(NodeKey, DBValue), /// Branch node: a key, 2 children and a height. Branch(u32, NodeKey, [HashKey; 2]), } impl Clone for OwnedNode { fn clone(&self) -> Self { match *self { OwnedNode::Empty => OwnedNode::Empty, OwnedNode::Leaf(ref k, ref v) => OwnedNode::Leaf(k.clone(), v.clone()), OwnedNode::Branch(h, ref k, ref c) => { let mut children = [HashKey::new(), HashKey::new()]; for (owned, borrowed) in children.iter_mut().zip(c.iter()) { *owned = borrowed.clone() } OwnedNode::Branch(h, k.clone(), children) } } } } impl<'a> From<Node<'a>> for OwnedNode { fn from(node: Node<'a>) -> Self { match node { Node::Empty => OwnedNode::Empty, Node::Leaf(k, v) => OwnedNode::Leaf(k.into(), DBValue::from_slice(v)), Node::Branch(h, k, c) => { let mut children = [HashKey::new(), HashKey::new()]; for (owned, borrowed) in children.iter_mut().zip(c.iter()) { *owned = borrowed.to_vec() } OwnedNode::Branch(h, k.into(), children) } } } }
{ let r = Rlp::new(node_rlp); match r.prototype() { // either leaf or extension - decode first item with NibbleSlice::??? // and use is_leaf return to figure out which. // if leaf, second item is a value (is_data()) // if extension, second item is a node (either SHA3 to be looked up and // fed back into this function or inline RLP which can be fed back into this function). Prototype::List(2) => { Node::Leaf(r.at(0).data().to_vec(), r.at(1).data()) } // branch - first 16 are nodes, 17th is a value (or empty). Prototype::List(4) => { let mut nodes = [&[] as &[u8]; 2]; for i in 0..2 { nodes[i] = r.at(i).as_raw(); } let height: u32 = decode(r.at(2).data()); Node::Branch(height, r.at(3).data().to_vec(), nodes) }
identifier_body
node.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program 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. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use bytes::*; use hashdb::DBValue; use rlp::*; /// Partial node key type. pub type HashKey = Vec<u8>; pub type NodeKey = Vec<u8>; /// Type of node in the avl and essential information thereof. #[derive(Eq, PartialEq, Debug, Clone)] pub enum Node<'a> { /// Null avl node; could be an empty root or an empty branch entry. Empty, /// Leaf node; has key slice and value. Value may not be empty. Leaf(NodeKey, &'a [u8]), /// Branch node; has a key, 2 child nodes (each possibly null) and a height. Branch(u32, NodeKey, [&'a [u8]; 2]), } impl<'a> Node<'a> { /// Decode the `node_rlp` and return the Node. pub fn decoded(node_rlp: &'a [u8]) -> Self { let r = Rlp::new(node_rlp); match r.prototype() { // either leaf or extension - decode first item with NibbleSlice::??? // and use is_leaf return to figure out which. // if leaf, second item is a value (is_data()) // if extension, second item is a node (either SHA3 to be looked up and // fed back into this function or inline RLP which can be fed back into this function). Prototype::List(2) => { Node::Leaf(r.at(0).data().to_vec(), r.at(1).data()) } // branch - first 16 are nodes, 17th is a value (or empty). Prototype::List(4) => { let mut nodes = [&[] as &[u8]; 2]; for i in 0..2 { nodes[i] = r.at(i).as_raw(); } let height: u32 = decode(r.at(2).data()); Node::Branch(height, r.at(3).data().to_vec(), nodes) } // an empty branch index. Prototype::Data(0) => Node::Empty, // something went wrong. _ => panic!("Rlp is not valid."), } } /// Encode the node into RLP. /// /// Will always return the direct node RLP even if it's 32 or more bytes. To get the /// RLP which would be valid for using in another node, use `encoded_and_added()`. pub fn encoded(&self) -> Bytes { match *self { Node::Leaf(ref key, ref value) => { let mut stream = RlpStream::new_list(2); stream.append(key); stream.append(value); stream.out() } Node::Branch(ref height, ref key, ref nodes) => { let mut stream = RlpStream::new_list(4); for i in 0..2 { stream.append_raw(nodes[i], 1); } stream.append(height); stream.append(key); stream.out() } Node::Empty => { let mut stream = RlpStream::new(); stream.append_empty_data(); stream.out() } } } } /// An owning node type. Useful for avl iterators. #[derive(Debug, PartialEq, Eq)] pub enum OwnedNode { /// Empty avl node. Empty, /// Leaf node: partial key and value. Leaf(NodeKey, DBValue), /// Branch node: a key, 2 children and a height. Branch(u32, NodeKey, [HashKey; 2]), } impl Clone for OwnedNode { fn clone(&self) -> Self { match *self { OwnedNode::Empty => OwnedNode::Empty, OwnedNode::Leaf(ref k, ref v) => OwnedNode::Leaf(k.clone(), v.clone()), OwnedNode::Branch(h, ref k, ref c) => { let mut children = [HashKey::new(), HashKey::new()]; for (owned, borrowed) in children.iter_mut().zip(c.iter()) { *owned = borrowed.clone()
} } impl<'a> From<Node<'a>> for OwnedNode { fn from(node: Node<'a>) -> Self { match node { Node::Empty => OwnedNode::Empty, Node::Leaf(k, v) => OwnedNode::Leaf(k.into(), DBValue::from_slice(v)), Node::Branch(h, k, c) => { let mut children = [HashKey::new(), HashKey::new()]; for (owned, borrowed) in children.iter_mut().zip(c.iter()) { *owned = borrowed.to_vec() } OwnedNode::Branch(h, k.into(), children) } } } }
} OwnedNode::Branch(h, k.clone(), children) } }
random_line_split
polygonal.rs
use super::misc::isint; pub struct Polys { n: u64, step: u8 } pub fn polys(s: u8) -> Polys { Polys { n: 1, step: s - 2 } } impl Iterator for Polys { type Item = u64; fn next(&mut self) -> Option<u64> { let ans = Some(self.n); self.n += self.step as u64; ans } } pub fn tris() -> Polys { polys(3) } pub fn sqrs() -> Polys { polys(4) } pub fn pentas() -> Polys { polys(5) } pub fn hexas() -> Polys { polys(6) } pub fn ispoly(s: u8, x: u64) -> bool { polys(s).take_while(|&y| y <= x).any(|y| y == x) } pub fn istri(x: u64) -> bool { isint((((x * 8 + 1) as f64).sqrt() - 1.0) / 2.0) } pub fn issqr(x: u64) -> bool { isint( ( x as f64).sqrt()) } pub fn ispenta(x: u64) -> bool { isint((((x * 24 + 1) as f64).sqrt() + 1.0) / 6.0) } pub fn ishexa(x: u64) -> bool { isint((((x * 8 + 1) as f64).sqrt() + 1.0) / 4.0) } pub fn poly(s: u8, x: u64) -> u64 { let s = s as u64; ((s - 2) * x * x - (s - 4) * x) / 2 } pub fn tri(x: u64) -> u64 { x * (x + 1) / 2 } pub fn sqr(x: u64) -> u64
pub fn penta(x: u64) -> u64 { x * (3 * x - 1) / 2 } pub fn hexa(x: u64) -> u64 { x * (2 * x - 1) }
{ x * x }
identifier_body
polygonal.rs
use super::misc::isint; pub struct Polys { n: u64, step: u8 } pub fn polys(s: u8) -> Polys { Polys { n: 1, step: s - 2 } } impl Iterator for Polys { type Item = u64; fn next(&mut self) -> Option<u64> { let ans = Some(self.n); self.n += self.step as u64; ans } } pub fn tris() -> Polys { polys(3) } pub fn sqrs() -> Polys { polys(4) } pub fn pentas() -> Polys { polys(5) } pub fn hexas() -> Polys { polys(6) } pub fn ispoly(s: u8, x: u64) -> bool { polys(s).take_while(|&y| y <= x).any(|y| y == x) } pub fn istri(x: u64) -> bool { isint((((x * 8 + 1) as f64).sqrt() - 1.0) / 2.0) } pub fn issqr(x: u64) -> bool { isint( ( x as f64).sqrt()) }
pub fn poly(s: u8, x: u64) -> u64 { let s = s as u64; ((s - 2) * x * x - (s - 4) * x) / 2 } pub fn tri(x: u64) -> u64 { x * (x + 1) / 2 } pub fn sqr(x: u64) -> u64 { x * x } pub fn penta(x: u64) -> u64 { x * (3 * x - 1) / 2 } pub fn hexa(x: u64) -> u64 { x * (2 * x - 1) }
pub fn ispenta(x: u64) -> bool { isint((((x * 24 + 1) as f64).sqrt() + 1.0) / 6.0) } pub fn ishexa(x: u64) -> bool { isint((((x * 8 + 1) as f64).sqrt() + 1.0) / 4.0) }
random_line_split
polygonal.rs
use super::misc::isint; pub struct Polys { n: u64, step: u8 } pub fn polys(s: u8) -> Polys { Polys { n: 1, step: s - 2 } } impl Iterator for Polys { type Item = u64; fn next(&mut self) -> Option<u64> { let ans = Some(self.n); self.n += self.step as u64; ans } } pub fn tris() -> Polys { polys(3) } pub fn sqrs() -> Polys { polys(4) } pub fn pentas() -> Polys { polys(5) } pub fn hexas() -> Polys { polys(6) } pub fn ispoly(s: u8, x: u64) -> bool { polys(s).take_while(|&y| y <= x).any(|y| y == x) } pub fn istri(x: u64) -> bool { isint((((x * 8 + 1) as f64).sqrt() - 1.0) / 2.0) } pub fn issqr(x: u64) -> bool { isint( ( x as f64).sqrt()) } pub fn ispenta(x: u64) -> bool { isint((((x * 24 + 1) as f64).sqrt() + 1.0) / 6.0) } pub fn ishexa(x: u64) -> bool { isint((((x * 8 + 1) as f64).sqrt() + 1.0) / 4.0) } pub fn poly(s: u8, x: u64) -> u64 { let s = s as u64; ((s - 2) * x * x - (s - 4) * x) / 2 } pub fn tri(x: u64) -> u64 { x * (x + 1) / 2 } pub fn
(x: u64) -> u64 { x * x } pub fn penta(x: u64) -> u64 { x * (3 * x - 1) / 2 } pub fn hexa(x: u64) -> u64 { x * (2 * x - 1) }
sqr
identifier_name
server.rs
//! Server API //! //! # Decode PING Base Frame from client //! //! ``` //! # extern crate bytes; //! # extern crate tokio_io; //! # extern crate twist; //! # //! # use bytes::BytesMut; //! # use twist::server::{BaseFrameCodec, OpCode};
//! # //! # const PING: [u8; 6] = [0x89, 0x80, 0x00, 0x00, 0x00, 0x01]; //! # //! # fn main() { //! let ping_vec = PING.to_vec(); //! let mut eb = BytesMut::with_capacity(256); //! eb.extend(ping_vec); //! let mut fc: BaseFrameCodec = Default::default(); //! let mut encoded = BytesMut::with_capacity(256); //! //! if let Ok(Some(frame)) = fc.decode(&mut eb) { //! assert!(frame.fin()); //! assert!(!frame.rsv1()); //! assert!(!frame.rsv2()); //! assert!(!frame.rsv3()); //! // All frames from client must be masked. //! assert!(frame.masked()); //! assert!(frame.opcode() == OpCode::Ping); //! assert!(frame.mask() == 1); //! assert!(frame.payload_length() == 0); //! assert!(frame.extension_data().is_none()); //! assert!(frame.application_data().is_empty()); //! //! if fc.encode(frame, &mut encoded).is_ok() { //! for (a, b) in encoded.iter().zip(PING.to_vec().iter()) { //! assert!(a == b); //! } //! } //! } else { //! assert!(false); //! } //! # } //! ``` // Common Codec Exports pub use codec::Twist as TwistCodec; pub use codec::base::FrameCodec as BaseFrameCodec; // Server Only Codec Exports pub use codec::server::handshake::FrameCodec as HandshakeCodec; // Common Frame Exports pub use frame::WebSocket as WebSocketFrame; pub use frame::base::Frame as BaseFrame; pub use frame::base::OpCode; // Server Only Frame Exports pub use frame::server::request::Frame as HandshakeRequestFrame; pub use frame::server::response::Frame as HandshakeResponseFrame; // Protocol Exports pub use proto::server::WebSocketProtocol;
//! # use tokio_io::codec::{Decoder, Encoder};
random_line_split
moves-based-on-type-match-bindings.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. // Tests that bindings to move-by-default values trigger moves of the // discriminant. Also tests that the compiler explains the move in // terms of the binding, not the discriminant.
fn touch<A>(_a: &A) {} fn f10() { let x = Foo {f: "hi".to_owned()}; let y = match x { Foo {f} => {} //~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
struct Foo<A> { f: A } fn guard(_s: StrBuf) -> bool {fail!()}
random_line_split
moves-based-on-type-match-bindings.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. // Tests that bindings to move-by-default values trigger moves of the // discriminant. Also tests that the compiler explains the move in // terms of the binding, not the discriminant. struct Foo<A> { f: A } fn guard(_s: StrBuf) -> bool {fail!()} fn touch<A>(_a: &A) {} fn f10() { let x = Foo {f: "hi".to_owned()}; let y = match x { Foo {f} =>
//~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
{}
conditional_block
moves-based-on-type-match-bindings.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. // Tests that bindings to move-by-default values trigger moves of the // discriminant. Also tests that the compiler explains the move in // terms of the binding, not the discriminant. struct Foo<A> { f: A } fn guard(_s: StrBuf) -> bool {fail!()} fn
<A>(_a: &A) {} fn f10() { let x = Foo {f: "hi".to_owned()}; let y = match x { Foo {f} => {} //~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
touch
identifier_name
moves-based-on-type-match-bindings.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. // Tests that bindings to move-by-default values trigger moves of the // discriminant. Also tests that the compiler explains the move in // terms of the binding, not the discriminant. struct Foo<A> { f: A } fn guard(_s: StrBuf) -> bool {fail!()} fn touch<A>(_a: &A)
fn f10() { let x = Foo {f: "hi".to_owned()}; let y = match x { Foo {f} => {} //~ NOTE moved here }; touch(&x); //~ ERROR use of partially moved value: `x` } fn main() {}
{}
identifier_body
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ //! Parser registration functions and common interface use std; use crate::core::{DetectEngineState,Flow,AppLayerEventType,AppLayerDecoderEvents,AppProto}; use crate::filecontainer::FileContainer; use crate::applayer; use std::os::raw::{c_void,c_char,c_int}; #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxConfig { /// config: log flags log_flags: u8, } impl AppLayerTxConfig { pub fn new() -> Self { Self { log_flags: 0, } } pub fn add_log_flags(&mut self, flags: u8) { self.log_flags |= flags; } pub fn set_log_flags(&mut self, flags: u8) { self.log_flags = flags; } pub fn get_log_flags(&self) -> u8 { self.log_flags } } #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxData { /// config: log flags pub config: AppLayerTxConfig, /// logger flags for tx logging api logged: LoggerFlags, /// detection engine flags for use by detection engine detect_flags_ts: u64, detect_flags_tc: u64, } impl AppLayerTxData { pub fn new() -> Self { Self { config: AppLayerTxConfig::new(), logged: LoggerFlags::new(), detect_flags_ts: 0, detect_flags_tc: 0, } } } #[macro_export] macro_rules!export_tx_data_get { ($name:ident, $type:ty) => { #[no_mangle] pub unsafe extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut crate::applayer::AppLayerTxData { let tx = &mut *(tx as *mut $type); &mut tx.tx_data } } } #[repr(C)] #[derive(Debug,PartialEq,Copy,Clone)] pub struct AppLayerResult { pub status: i32, pub consumed: u32, pub needed: u32, } impl AppLayerResult { /// parser has successfully processed in the input, and has consumed all of it pub fn ok() -> AppLayerResult { return AppLayerResult { status: 0, consumed: 0, needed: 0, }; } /// parser has hit an unrecoverable error. Returning this to the API /// leads to no further calls to the parser. pub fn err() -> AppLayerResult { return AppLayerResult { status: -1, consumed: 0, needed: 0, }; } /// parser needs more data. Through 'consumed' it will indicate how many /// of the input bytes it has consumed. Through 'needed' it will indicate /// how many more bytes it needs before getting called again. /// Note: consumed should never be more than the input len /// needed + consumed should be more than the input len pub fn incomplete(consumed: u32, needed: u32) -> AppLayerResult { return AppLayerResult { status: 1, consumed: consumed, needed: needed, }; } pub fn is_ok(self) -> bool { self.status == 0 } pub fn is_incomplete(self) -> bool { self.status == 1 } pub fn is_err(self) -> bool { self.status == -1 } } impl From<bool> for AppLayerResult { fn from(v: bool) -> Self { if v == false { Self::err() } else { Self::ok() } } } impl From<i32> for AppLayerResult { fn from(v: i32) -> Self { if v < 0
else { Self::ok() } } } /// Rust parser declaration #[repr(C)] pub struct RustParser { /// Parser name. pub name: *const c_char, /// Default port pub default_port: *const c_char, /// IP Protocol (core::IPPROTO_UDP, core::IPPROTO_TCP, etc.) pub ipproto: c_int, /// Probing function, for packets going to server pub probe_ts: Option<ProbeFn>, /// Probing function, for packets going to client pub probe_tc: Option<ProbeFn>, /// Minimum frame depth for probing pub min_depth: u16, /// Maximum frame depth for probing pub max_depth: u16, /// Allocation function for a new state pub state_new: StateAllocFn, /// Function called to free a state pub state_free: StateFreeFn, /// Parsing function, for packets going to server pub parse_ts: ParseFn, /// Parsing function, for packets going to client pub parse_tc: ParseFn, /// Get the current transaction count pub get_tx_count: StateGetTxCntFn, /// Get a transaction pub get_tx: StateGetTxFn, /// Function called to free a transaction pub tx_free: StateTxFreeFn, /// Function returning the current transaction completion status pub tx_get_comp_st: StateGetTxCompletionStatusFn, /// Function returning the current transaction progress pub tx_get_progress: StateGetProgressFn, /// Function called to get a detection state pub get_de_state: GetDetectStateFn, /// Function called to set a detection state pub set_de_state: SetDetectStateFn, /// Function to get events pub get_events: Option<GetEventsFn>, /// Function to get an event id from a description pub get_eventinfo: Option<GetEventInfoFn>, /// Function to get an event description from an event id pub get_eventinfo_byid: Option<GetEventInfoByIdFn>, /// Function to allocate local storage pub localstorage_new: Option<LocalStorageNewFn>, /// Function to free local storage pub localstorage_free: Option<LocalStorageFreeFn>, /// Function to get files pub get_files: Option<GetFilesFn>, /// Function to get the TX iterator pub get_tx_iterator: Option<GetTxIteratorFn>, pub get_tx_data: GetTxDataFn, // Function to apply config to a TX. Optional. Normal (bidirectional) // transactions don't need to set this. It is meant for cases where // the requests and responses are not sharing tx. It is then up to // the implementation to make sure the config is applied correctly. pub apply_tx_config: Option<ApplyTxConfigFn>, pub flags: u32, /// Function to handle the end of data coming on one of the sides /// due to the stream reaching its 'depth' limit. pub truncate: Option<TruncateFn>, } /// Create a slice, given a buffer and a length /// /// UNSAFE! #[macro_export] macro_rules! build_slice { ($buf:ident, $len:expr) => ( unsafe{ std::slice::from_raw_parts($buf, $len) } ); } /// Cast pointer to a variable, as a mutable reference to an object /// /// UNSAFE! #[macro_export] macro_rules! cast_pointer { ($ptr:ident, $ty:ty) => ( unsafe{ &mut *($ptr as *mut $ty) } ); } pub type ParseFn = extern "C" fn (flow: *const Flow, state: *mut c_void, pstate: *mut c_void, input: *const u8, input_len: u32, data: *const c_void, flags: u8) -> AppLayerResult; pub type ProbeFn = extern "C" fn (flow: *const Flow,direction: u8,input:*const u8, input_len: u32, rdir: *mut u8) -> AppProto; pub type StateAllocFn = extern "C" fn (*mut c_void, AppProto) -> *mut c_void; pub type StateFreeFn = extern "C" fn (*mut c_void); pub type StateTxFreeFn = extern "C" fn (*mut c_void, u64); pub type StateGetTxFn = extern "C" fn (*mut c_void, u64) -> *mut c_void; pub type StateGetTxCntFn = extern "C" fn (*mut c_void) -> u64; pub type StateGetTxCompletionStatusFn = extern "C" fn (u8) -> c_int; pub type StateGetProgressFn = extern "C" fn (*mut c_void, u8) -> c_int; pub type GetDetectStateFn = extern "C" fn (*mut c_void) -> *mut DetectEngineState; pub type SetDetectStateFn = extern "C" fn (*mut c_void, &mut DetectEngineState) -> c_int; pub type GetEventInfoFn = extern "C" fn (*const c_char, *mut c_int, *mut AppLayerEventType) -> c_int; pub type GetEventInfoByIdFn = extern "C" fn (c_int, *mut *const c_char, *mut AppLayerEventType) -> i8; pub type GetEventsFn = extern "C" fn (*mut c_void) -> *mut AppLayerDecoderEvents; pub type LocalStorageNewFn = extern "C" fn () -> *mut c_void; pub type LocalStorageFreeFn = extern "C" fn (*mut c_void); pub type GetFilesFn = extern "C" fn (*mut c_void, u8) -> *mut FileContainer; pub type GetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, state: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> AppLayerGetTxIterTuple; pub type GetTxDataFn = unsafe extern "C" fn(*mut c_void) -> *mut AppLayerTxData; pub type ApplyTxConfigFn = unsafe extern "C" fn (*mut c_void, *mut c_void, c_int, AppLayerTxConfig); pub type TruncateFn = unsafe extern "C" fn (*mut c_void, u8); // Defined in app-layer-register.h extern { pub fn AppLayerRegisterProtocolDetection(parser: *const RustParser, enable_default: c_int) -> AppProto; pub fn AppLayerRegisterParser(parser: *const RustParser, alproto: AppProto) -> c_int; } // Defined in app-layer-detect-proto.h extern { pub fn AppLayerProtoDetectConfProtoDetectionEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; } // Defined in app-layer-parser.h pub const APP_LAYER_PARSER_EOF : u8 = 0b0; pub const APP_LAYER_PARSER_NO_INSPECTION : u8 = 0b1; pub const APP_LAYER_PARSER_NO_REASSEMBLY : u8 = 0b10; pub const APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD : u8 = 0b100; pub const APP_LAYER_PARSER_BYPASS_READY : u8 = 0b1000; pub const APP_LAYER_PARSER_OPT_ACCEPT_GAPS: u32 = BIT_U32!(0); pub const APP_LAYER_PARSER_OPT_UNIDIR_TXS: u32 = BIT_U32!(1); pub type AppLayerGetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, alstate: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> applayer::AppLayerGetTxIterTuple; extern { pub fn AppLayerParserStateSetFlag(state: *mut c_void, flag: u8); pub fn AppLayerParserStateIssetFlag(state: *mut c_void, flag: u8) -> c_int; pub fn AppLayerParserConfParserEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; pub fn AppLayerParserRegisterGetTxIterator(ipproto: u8, alproto: AppProto, fun: AppLayerGetTxIteratorFn); pub fn AppLayerParserRegisterOptionFlags(ipproto: u8, alproto: AppProto, flags: u32); } #[repr(C)] pub struct AppLayerGetTxIterTuple { tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool, } impl AppLayerGetTxIterTuple { pub fn with_values(tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool) -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: tx_ptr, tx_id: tx_id, has_next: has_next, } } pub fn not_found() -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: std::ptr::null_mut(), tx_id: 0, has_next: false, } } } /// LoggerFlags tracks which loggers have already been executed. #[repr(C)] #[derive(Debug,PartialEq)] pub struct LoggerFlags { flags: u32, } impl LoggerFlags { pub fn new() -> LoggerFlags { return LoggerFlags{ flags: 0, } } pub fn get(&self) -> u32 { self.flags } pub fn set(&mut self, bits: u32) { self.flags = bits; } } /// Export a function to get the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_get_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, $type); match tx.de_state { Some(ds) => { return ds; }, None => { return std::ptr::null_mut(); } } } ) } /// Export a function to set the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_set_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState) -> std::os::raw::c_int { let tx = cast_pointer!(tx, $type); tx.de_state = Some(de_state); 0 } ) }
{ Self::err() }
conditional_block
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ //! Parser registration functions and common interface use std; use crate::core::{DetectEngineState,Flow,AppLayerEventType,AppLayerDecoderEvents,AppProto}; use crate::filecontainer::FileContainer; use crate::applayer; use std::os::raw::{c_void,c_char,c_int}; #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxConfig { /// config: log flags log_flags: u8, } impl AppLayerTxConfig { pub fn new() -> Self { Self { log_flags: 0, } } pub fn add_log_flags(&mut self, flags: u8) { self.log_flags |= flags; } pub fn set_log_flags(&mut self, flags: u8) { self.log_flags = flags; } pub fn get_log_flags(&self) -> u8 { self.log_flags } } #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxData { /// config: log flags pub config: AppLayerTxConfig, /// logger flags for tx logging api logged: LoggerFlags, /// detection engine flags for use by detection engine detect_flags_ts: u64, detect_flags_tc: u64, } impl AppLayerTxData { pub fn new() -> Self { Self { config: AppLayerTxConfig::new(), logged: LoggerFlags::new(), detect_flags_ts: 0, detect_flags_tc: 0, } } } #[macro_export] macro_rules!export_tx_data_get { ($name:ident, $type:ty) => { #[no_mangle] pub unsafe extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut crate::applayer::AppLayerTxData { let tx = &mut *(tx as *mut $type); &mut tx.tx_data } } } #[repr(C)] #[derive(Debug,PartialEq,Copy,Clone)] pub struct AppLayerResult { pub status: i32, pub consumed: u32, pub needed: u32, } impl AppLayerResult { /// parser has successfully processed in the input, and has consumed all of it pub fn ok() -> AppLayerResult { return AppLayerResult { status: 0, consumed: 0, needed: 0, }; } /// parser has hit an unrecoverable error. Returning this to the API /// leads to no further calls to the parser. pub fn err() -> AppLayerResult { return AppLayerResult { status: -1, consumed: 0, needed: 0, }; } /// parser needs more data. Through 'consumed' it will indicate how many /// of the input bytes it has consumed. Through 'needed' it will indicate /// how many more bytes it needs before getting called again. /// Note: consumed should never be more than the input len /// needed + consumed should be more than the input len pub fn incomplete(consumed: u32, needed: u32) -> AppLayerResult { return AppLayerResult { status: 1, consumed: consumed, needed: needed, }; } pub fn is_ok(self) -> bool { self.status == 0 } pub fn is_incomplete(self) -> bool { self.status == 1 } pub fn is_err(self) -> bool { self.status == -1 } } impl From<bool> for AppLayerResult { fn from(v: bool) -> Self { if v == false { Self::err() } else { Self::ok() } } } impl From<i32> for AppLayerResult { fn from(v: i32) -> Self { if v < 0 { Self::err() } else { Self::ok() } } } /// Rust parser declaration #[repr(C)] pub struct RustParser { /// Parser name. pub name: *const c_char, /// Default port pub default_port: *const c_char, /// IP Protocol (core::IPPROTO_UDP, core::IPPROTO_TCP, etc.) pub ipproto: c_int, /// Probing function, for packets going to server pub probe_ts: Option<ProbeFn>, /// Probing function, for packets going to client pub probe_tc: Option<ProbeFn>, /// Minimum frame depth for probing pub min_depth: u16, /// Maximum frame depth for probing pub max_depth: u16, /// Allocation function for a new state pub state_new: StateAllocFn, /// Function called to free a state pub state_free: StateFreeFn, /// Parsing function, for packets going to server pub parse_ts: ParseFn, /// Parsing function, for packets going to client pub parse_tc: ParseFn, /// Get the current transaction count pub get_tx_count: StateGetTxCntFn, /// Get a transaction pub get_tx: StateGetTxFn, /// Function called to free a transaction pub tx_free: StateTxFreeFn, /// Function returning the current transaction completion status pub tx_get_comp_st: StateGetTxCompletionStatusFn, /// Function returning the current transaction progress pub tx_get_progress: StateGetProgressFn, /// Function called to get a detection state pub get_de_state: GetDetectStateFn, /// Function called to set a detection state pub set_de_state: SetDetectStateFn, /// Function to get events pub get_events: Option<GetEventsFn>, /// Function to get an event id from a description pub get_eventinfo: Option<GetEventInfoFn>, /// Function to get an event description from an event id pub get_eventinfo_byid: Option<GetEventInfoByIdFn>, /// Function to allocate local storage pub localstorage_new: Option<LocalStorageNewFn>, /// Function to free local storage pub localstorage_free: Option<LocalStorageFreeFn>, /// Function to get files pub get_files: Option<GetFilesFn>, /// Function to get the TX iterator pub get_tx_iterator: Option<GetTxIteratorFn>, pub get_tx_data: GetTxDataFn, // Function to apply config to a TX. Optional. Normal (bidirectional) // transactions don't need to set this. It is meant for cases where // the requests and responses are not sharing tx. It is then up to // the implementation to make sure the config is applied correctly. pub apply_tx_config: Option<ApplyTxConfigFn>, pub flags: u32, /// Function to handle the end of data coming on one of the sides /// due to the stream reaching its 'depth' limit. pub truncate: Option<TruncateFn>, } /// Create a slice, given a buffer and a length /// /// UNSAFE! #[macro_export] macro_rules! build_slice { ($buf:ident, $len:expr) => ( unsafe{ std::slice::from_raw_parts($buf, $len) } ); } /// Cast pointer to a variable, as a mutable reference to an object /// /// UNSAFE! #[macro_export] macro_rules! cast_pointer { ($ptr:ident, $ty:ty) => ( unsafe{ &mut *($ptr as *mut $ty) } ); } pub type ParseFn = extern "C" fn (flow: *const Flow, state: *mut c_void, pstate: *mut c_void, input: *const u8, input_len: u32, data: *const c_void, flags: u8) -> AppLayerResult; pub type ProbeFn = extern "C" fn (flow: *const Flow,direction: u8,input:*const u8, input_len: u32, rdir: *mut u8) -> AppProto; pub type StateAllocFn = extern "C" fn (*mut c_void, AppProto) -> *mut c_void; pub type StateFreeFn = extern "C" fn (*mut c_void); pub type StateTxFreeFn = extern "C" fn (*mut c_void, u64); pub type StateGetTxFn = extern "C" fn (*mut c_void, u64) -> *mut c_void; pub type StateGetTxCntFn = extern "C" fn (*mut c_void) -> u64; pub type StateGetTxCompletionStatusFn = extern "C" fn (u8) -> c_int; pub type StateGetProgressFn = extern "C" fn (*mut c_void, u8) -> c_int; pub type GetDetectStateFn = extern "C" fn (*mut c_void) -> *mut DetectEngineState; pub type SetDetectStateFn = extern "C" fn (*mut c_void, &mut DetectEngineState) -> c_int; pub type GetEventInfoFn = extern "C" fn (*const c_char, *mut c_int, *mut AppLayerEventType) -> c_int; pub type GetEventInfoByIdFn = extern "C" fn (c_int, *mut *const c_char, *mut AppLayerEventType) -> i8; pub type GetEventsFn = extern "C" fn (*mut c_void) -> *mut AppLayerDecoderEvents; pub type LocalStorageNewFn = extern "C" fn () -> *mut c_void; pub type LocalStorageFreeFn = extern "C" fn (*mut c_void); pub type GetFilesFn = extern "C" fn (*mut c_void, u8) -> *mut FileContainer; pub type GetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, state: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> AppLayerGetTxIterTuple; pub type GetTxDataFn = unsafe extern "C" fn(*mut c_void) -> *mut AppLayerTxData; pub type ApplyTxConfigFn = unsafe extern "C" fn (*mut c_void, *mut c_void, c_int, AppLayerTxConfig); pub type TruncateFn = unsafe extern "C" fn (*mut c_void, u8); // Defined in app-layer-register.h extern { pub fn AppLayerRegisterProtocolDetection(parser: *const RustParser, enable_default: c_int) -> AppProto; pub fn AppLayerRegisterParser(parser: *const RustParser, alproto: AppProto) -> c_int; } // Defined in app-layer-detect-proto.h extern { pub fn AppLayerProtoDetectConfProtoDetectionEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; } // Defined in app-layer-parser.h pub const APP_LAYER_PARSER_EOF : u8 = 0b0; pub const APP_LAYER_PARSER_NO_INSPECTION : u8 = 0b1; pub const APP_LAYER_PARSER_NO_REASSEMBLY : u8 = 0b10; pub const APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD : u8 = 0b100; pub const APP_LAYER_PARSER_BYPASS_READY : u8 = 0b1000; pub const APP_LAYER_PARSER_OPT_ACCEPT_GAPS: u32 = BIT_U32!(0); pub const APP_LAYER_PARSER_OPT_UNIDIR_TXS: u32 = BIT_U32!(1); pub type AppLayerGetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, alstate: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> applayer::AppLayerGetTxIterTuple; extern { pub fn AppLayerParserStateSetFlag(state: *mut c_void, flag: u8); pub fn AppLayerParserStateIssetFlag(state: *mut c_void, flag: u8) -> c_int; pub fn AppLayerParserConfParserEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; pub fn AppLayerParserRegisterGetTxIterator(ipproto: u8, alproto: AppProto, fun: AppLayerGetTxIteratorFn); pub fn AppLayerParserRegisterOptionFlags(ipproto: u8, alproto: AppProto, flags: u32); } #[repr(C)] pub struct AppLayerGetTxIterTuple { tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool, } impl AppLayerGetTxIterTuple { pub fn
(tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool) -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: tx_ptr, tx_id: tx_id, has_next: has_next, } } pub fn not_found() -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: std::ptr::null_mut(), tx_id: 0, has_next: false, } } } /// LoggerFlags tracks which loggers have already been executed. #[repr(C)] #[derive(Debug,PartialEq)] pub struct LoggerFlags { flags: u32, } impl LoggerFlags { pub fn new() -> LoggerFlags { return LoggerFlags{ flags: 0, } } pub fn get(&self) -> u32 { self.flags } pub fn set(&mut self, bits: u32) { self.flags = bits; } } /// Export a function to get the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_get_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, $type); match tx.de_state { Some(ds) => { return ds; }, None => { return std::ptr::null_mut(); } } } ) } /// Export a function to set the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_set_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState) -> std::os::raw::c_int { let tx = cast_pointer!(tx, $type); tx.de_state = Some(de_state); 0 } ) }
with_values
identifier_name
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ //! Parser registration functions and common interface use std; use crate::core::{DetectEngineState,Flow,AppLayerEventType,AppLayerDecoderEvents,AppProto}; use crate::filecontainer::FileContainer; use crate::applayer; use std::os::raw::{c_void,c_char,c_int}; #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxConfig { /// config: log flags log_flags: u8, } impl AppLayerTxConfig { pub fn new() -> Self { Self { log_flags: 0, } } pub fn add_log_flags(&mut self, flags: u8) { self.log_flags |= flags; } pub fn set_log_flags(&mut self, flags: u8) { self.log_flags = flags; } pub fn get_log_flags(&self) -> u8 { self.log_flags } } #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxData { /// config: log flags pub config: AppLayerTxConfig, /// logger flags for tx logging api logged: LoggerFlags, /// detection engine flags for use by detection engine detect_flags_ts: u64, detect_flags_tc: u64, } impl AppLayerTxData { pub fn new() -> Self { Self { config: AppLayerTxConfig::new(), logged: LoggerFlags::new(), detect_flags_ts: 0, detect_flags_tc: 0, } } } #[macro_export] macro_rules!export_tx_data_get { ($name:ident, $type:ty) => { #[no_mangle] pub unsafe extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut crate::applayer::AppLayerTxData { let tx = &mut *(tx as *mut $type); &mut tx.tx_data } } } #[repr(C)] #[derive(Debug,PartialEq,Copy,Clone)] pub struct AppLayerResult { pub status: i32, pub consumed: u32, pub needed: u32, } impl AppLayerResult { /// parser has successfully processed in the input, and has consumed all of it pub fn ok() -> AppLayerResult { return AppLayerResult { status: 0, consumed: 0, needed: 0, }; } /// parser has hit an unrecoverable error. Returning this to the API /// leads to no further calls to the parser. pub fn err() -> AppLayerResult { return AppLayerResult { status: -1, consumed: 0, needed: 0, }; } /// parser needs more data. Through 'consumed' it will indicate how many /// of the input bytes it has consumed. Through 'needed' it will indicate /// how many more bytes it needs before getting called again. /// Note: consumed should never be more than the input len /// needed + consumed should be more than the input len pub fn incomplete(consumed: u32, needed: u32) -> AppLayerResult { return AppLayerResult { status: 1, consumed: consumed, needed: needed, }; } pub fn is_ok(self) -> bool { self.status == 0 } pub fn is_incomplete(self) -> bool { self.status == 1 } pub fn is_err(self) -> bool { self.status == -1 } } impl From<bool> for AppLayerResult { fn from(v: bool) -> Self { if v == false { Self::err() } else { Self::ok() } } } impl From<i32> for AppLayerResult { fn from(v: i32) -> Self { if v < 0 { Self::err() } else { Self::ok() } } } /// Rust parser declaration #[repr(C)] pub struct RustParser { /// Parser name. pub name: *const c_char, /// Default port pub default_port: *const c_char, /// IP Protocol (core::IPPROTO_UDP, core::IPPROTO_TCP, etc.) pub ipproto: c_int, /// Probing function, for packets going to server pub probe_ts: Option<ProbeFn>, /// Probing function, for packets going to client pub probe_tc: Option<ProbeFn>, /// Minimum frame depth for probing pub min_depth: u16, /// Maximum frame depth for probing pub max_depth: u16, /// Allocation function for a new state pub state_new: StateAllocFn, /// Function called to free a state pub state_free: StateFreeFn, /// Parsing function, for packets going to server pub parse_ts: ParseFn, /// Parsing function, for packets going to client pub parse_tc: ParseFn, /// Get the current transaction count pub get_tx_count: StateGetTxCntFn, /// Get a transaction pub get_tx: StateGetTxFn, /// Function called to free a transaction pub tx_free: StateTxFreeFn, /// Function returning the current transaction completion status pub tx_get_comp_st: StateGetTxCompletionStatusFn, /// Function returning the current transaction progress pub tx_get_progress: StateGetProgressFn, /// Function called to get a detection state pub get_de_state: GetDetectStateFn, /// Function called to set a detection state pub set_de_state: SetDetectStateFn, /// Function to get events pub get_events: Option<GetEventsFn>, /// Function to get an event id from a description pub get_eventinfo: Option<GetEventInfoFn>, /// Function to get an event description from an event id pub get_eventinfo_byid: Option<GetEventInfoByIdFn>, /// Function to allocate local storage pub localstorage_new: Option<LocalStorageNewFn>, /// Function to free local storage pub localstorage_free: Option<LocalStorageFreeFn>, /// Function to get files pub get_files: Option<GetFilesFn>, /// Function to get the TX iterator pub get_tx_iterator: Option<GetTxIteratorFn>, pub get_tx_data: GetTxDataFn, // Function to apply config to a TX. Optional. Normal (bidirectional) // transactions don't need to set this. It is meant for cases where // the requests and responses are not sharing tx. It is then up to // the implementation to make sure the config is applied correctly. pub apply_tx_config: Option<ApplyTxConfigFn>, pub flags: u32, /// Function to handle the end of data coming on one of the sides /// due to the stream reaching its 'depth' limit. pub truncate: Option<TruncateFn>, } /// Create a slice, given a buffer and a length /// /// UNSAFE! #[macro_export] macro_rules! build_slice { ($buf:ident, $len:expr) => ( unsafe{ std::slice::from_raw_parts($buf, $len) } ); } /// Cast pointer to a variable, as a mutable reference to an object /// /// UNSAFE! #[macro_export] macro_rules! cast_pointer { ($ptr:ident, $ty:ty) => ( unsafe{ &mut *($ptr as *mut $ty) } ); } pub type ParseFn = extern "C" fn (flow: *const Flow, state: *mut c_void, pstate: *mut c_void, input: *const u8, input_len: u32, data: *const c_void, flags: u8) -> AppLayerResult; pub type ProbeFn = extern "C" fn (flow: *const Flow,direction: u8,input:*const u8, input_len: u32, rdir: *mut u8) -> AppProto; pub type StateAllocFn = extern "C" fn (*mut c_void, AppProto) -> *mut c_void; pub type StateFreeFn = extern "C" fn (*mut c_void); pub type StateTxFreeFn = extern "C" fn (*mut c_void, u64); pub type StateGetTxFn = extern "C" fn (*mut c_void, u64) -> *mut c_void; pub type StateGetTxCntFn = extern "C" fn (*mut c_void) -> u64; pub type StateGetTxCompletionStatusFn = extern "C" fn (u8) -> c_int; pub type StateGetProgressFn = extern "C" fn (*mut c_void, u8) -> c_int; pub type GetDetectStateFn = extern "C" fn (*mut c_void) -> *mut DetectEngineState; pub type SetDetectStateFn = extern "C" fn (*mut c_void, &mut DetectEngineState) -> c_int; pub type GetEventInfoFn = extern "C" fn (*const c_char, *mut c_int, *mut AppLayerEventType) -> c_int; pub type GetEventInfoByIdFn = extern "C" fn (c_int, *mut *const c_char, *mut AppLayerEventType) -> i8; pub type GetEventsFn = extern "C" fn (*mut c_void) -> *mut AppLayerDecoderEvents; pub type LocalStorageNewFn = extern "C" fn () -> *mut c_void; pub type LocalStorageFreeFn = extern "C" fn (*mut c_void); pub type GetFilesFn = extern "C" fn (*mut c_void, u8) -> *mut FileContainer; pub type GetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, state: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> AppLayerGetTxIterTuple; pub type GetTxDataFn = unsafe extern "C" fn(*mut c_void) -> *mut AppLayerTxData; pub type ApplyTxConfigFn = unsafe extern "C" fn (*mut c_void, *mut c_void, c_int, AppLayerTxConfig); pub type TruncateFn = unsafe extern "C" fn (*mut c_void, u8); // Defined in app-layer-register.h extern { pub fn AppLayerRegisterProtocolDetection(parser: *const RustParser, enable_default: c_int) -> AppProto; pub fn AppLayerRegisterParser(parser: *const RustParser, alproto: AppProto) -> c_int; } // Defined in app-layer-detect-proto.h extern { pub fn AppLayerProtoDetectConfProtoDetectionEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; } // Defined in app-layer-parser.h pub const APP_LAYER_PARSER_EOF : u8 = 0b0; pub const APP_LAYER_PARSER_NO_INSPECTION : u8 = 0b1; pub const APP_LAYER_PARSER_NO_REASSEMBLY : u8 = 0b10; pub const APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD : u8 = 0b100; pub const APP_LAYER_PARSER_BYPASS_READY : u8 = 0b1000; pub const APP_LAYER_PARSER_OPT_ACCEPT_GAPS: u32 = BIT_U32!(0); pub const APP_LAYER_PARSER_OPT_UNIDIR_TXS: u32 = BIT_U32!(1); pub type AppLayerGetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, alstate: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> applayer::AppLayerGetTxIterTuple; extern { pub fn AppLayerParserStateSetFlag(state: *mut c_void, flag: u8); pub fn AppLayerParserStateIssetFlag(state: *mut c_void, flag: u8) -> c_int; pub fn AppLayerParserConfParserEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; pub fn AppLayerParserRegisterGetTxIterator(ipproto: u8, alproto: AppProto, fun: AppLayerGetTxIteratorFn); pub fn AppLayerParserRegisterOptionFlags(ipproto: u8, alproto: AppProto, flags: u32); } #[repr(C)] pub struct AppLayerGetTxIterTuple { tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool, } impl AppLayerGetTxIterTuple { pub fn with_values(tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool) -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: tx_ptr, tx_id: tx_id, has_next: has_next, } } pub fn not_found() -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple {
} /// LoggerFlags tracks which loggers have already been executed. #[repr(C)] #[derive(Debug,PartialEq)] pub struct LoggerFlags { flags: u32, } impl LoggerFlags { pub fn new() -> LoggerFlags { return LoggerFlags{ flags: 0, } } pub fn get(&self) -> u32 { self.flags } pub fn set(&mut self, bits: u32) { self.flags = bits; } } /// Export a function to get the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_get_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, $type); match tx.de_state { Some(ds) => { return ds; }, None => { return std::ptr::null_mut(); } } } ) } /// Export a function to set the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_set_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState) -> std::os::raw::c_int { let tx = cast_pointer!(tx, $type); tx.de_state = Some(de_state); 0 } ) }
tx_ptr: std::ptr::null_mut(), tx_id: 0, has_next: false, } }
random_line_split
applayer.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ //! Parser registration functions and common interface use std; use crate::core::{DetectEngineState,Flow,AppLayerEventType,AppLayerDecoderEvents,AppProto}; use crate::filecontainer::FileContainer; use crate::applayer; use std::os::raw::{c_void,c_char,c_int}; #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxConfig { /// config: log flags log_flags: u8, } impl AppLayerTxConfig { pub fn new() -> Self { Self { log_flags: 0, } } pub fn add_log_flags(&mut self, flags: u8)
pub fn set_log_flags(&mut self, flags: u8) { self.log_flags = flags; } pub fn get_log_flags(&self) -> u8 { self.log_flags } } #[repr(C)] #[derive(Debug,PartialEq)] pub struct AppLayerTxData { /// config: log flags pub config: AppLayerTxConfig, /// logger flags for tx logging api logged: LoggerFlags, /// detection engine flags for use by detection engine detect_flags_ts: u64, detect_flags_tc: u64, } impl AppLayerTxData { pub fn new() -> Self { Self { config: AppLayerTxConfig::new(), logged: LoggerFlags::new(), detect_flags_ts: 0, detect_flags_tc: 0, } } } #[macro_export] macro_rules!export_tx_data_get { ($name:ident, $type:ty) => { #[no_mangle] pub unsafe extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut crate::applayer::AppLayerTxData { let tx = &mut *(tx as *mut $type); &mut tx.tx_data } } } #[repr(C)] #[derive(Debug,PartialEq,Copy,Clone)] pub struct AppLayerResult { pub status: i32, pub consumed: u32, pub needed: u32, } impl AppLayerResult { /// parser has successfully processed in the input, and has consumed all of it pub fn ok() -> AppLayerResult { return AppLayerResult { status: 0, consumed: 0, needed: 0, }; } /// parser has hit an unrecoverable error. Returning this to the API /// leads to no further calls to the parser. pub fn err() -> AppLayerResult { return AppLayerResult { status: -1, consumed: 0, needed: 0, }; } /// parser needs more data. Through 'consumed' it will indicate how many /// of the input bytes it has consumed. Through 'needed' it will indicate /// how many more bytes it needs before getting called again. /// Note: consumed should never be more than the input len /// needed + consumed should be more than the input len pub fn incomplete(consumed: u32, needed: u32) -> AppLayerResult { return AppLayerResult { status: 1, consumed: consumed, needed: needed, }; } pub fn is_ok(self) -> bool { self.status == 0 } pub fn is_incomplete(self) -> bool { self.status == 1 } pub fn is_err(self) -> bool { self.status == -1 } } impl From<bool> for AppLayerResult { fn from(v: bool) -> Self { if v == false { Self::err() } else { Self::ok() } } } impl From<i32> for AppLayerResult { fn from(v: i32) -> Self { if v < 0 { Self::err() } else { Self::ok() } } } /// Rust parser declaration #[repr(C)] pub struct RustParser { /// Parser name. pub name: *const c_char, /// Default port pub default_port: *const c_char, /// IP Protocol (core::IPPROTO_UDP, core::IPPROTO_TCP, etc.) pub ipproto: c_int, /// Probing function, for packets going to server pub probe_ts: Option<ProbeFn>, /// Probing function, for packets going to client pub probe_tc: Option<ProbeFn>, /// Minimum frame depth for probing pub min_depth: u16, /// Maximum frame depth for probing pub max_depth: u16, /// Allocation function for a new state pub state_new: StateAllocFn, /// Function called to free a state pub state_free: StateFreeFn, /// Parsing function, for packets going to server pub parse_ts: ParseFn, /// Parsing function, for packets going to client pub parse_tc: ParseFn, /// Get the current transaction count pub get_tx_count: StateGetTxCntFn, /// Get a transaction pub get_tx: StateGetTxFn, /// Function called to free a transaction pub tx_free: StateTxFreeFn, /// Function returning the current transaction completion status pub tx_get_comp_st: StateGetTxCompletionStatusFn, /// Function returning the current transaction progress pub tx_get_progress: StateGetProgressFn, /// Function called to get a detection state pub get_de_state: GetDetectStateFn, /// Function called to set a detection state pub set_de_state: SetDetectStateFn, /// Function to get events pub get_events: Option<GetEventsFn>, /// Function to get an event id from a description pub get_eventinfo: Option<GetEventInfoFn>, /// Function to get an event description from an event id pub get_eventinfo_byid: Option<GetEventInfoByIdFn>, /// Function to allocate local storage pub localstorage_new: Option<LocalStorageNewFn>, /// Function to free local storage pub localstorage_free: Option<LocalStorageFreeFn>, /// Function to get files pub get_files: Option<GetFilesFn>, /// Function to get the TX iterator pub get_tx_iterator: Option<GetTxIteratorFn>, pub get_tx_data: GetTxDataFn, // Function to apply config to a TX. Optional. Normal (bidirectional) // transactions don't need to set this. It is meant for cases where // the requests and responses are not sharing tx. It is then up to // the implementation to make sure the config is applied correctly. pub apply_tx_config: Option<ApplyTxConfigFn>, pub flags: u32, /// Function to handle the end of data coming on one of the sides /// due to the stream reaching its 'depth' limit. pub truncate: Option<TruncateFn>, } /// Create a slice, given a buffer and a length /// /// UNSAFE! #[macro_export] macro_rules! build_slice { ($buf:ident, $len:expr) => ( unsafe{ std::slice::from_raw_parts($buf, $len) } ); } /// Cast pointer to a variable, as a mutable reference to an object /// /// UNSAFE! #[macro_export] macro_rules! cast_pointer { ($ptr:ident, $ty:ty) => ( unsafe{ &mut *($ptr as *mut $ty) } ); } pub type ParseFn = extern "C" fn (flow: *const Flow, state: *mut c_void, pstate: *mut c_void, input: *const u8, input_len: u32, data: *const c_void, flags: u8) -> AppLayerResult; pub type ProbeFn = extern "C" fn (flow: *const Flow,direction: u8,input:*const u8, input_len: u32, rdir: *mut u8) -> AppProto; pub type StateAllocFn = extern "C" fn (*mut c_void, AppProto) -> *mut c_void; pub type StateFreeFn = extern "C" fn (*mut c_void); pub type StateTxFreeFn = extern "C" fn (*mut c_void, u64); pub type StateGetTxFn = extern "C" fn (*mut c_void, u64) -> *mut c_void; pub type StateGetTxCntFn = extern "C" fn (*mut c_void) -> u64; pub type StateGetTxCompletionStatusFn = extern "C" fn (u8) -> c_int; pub type StateGetProgressFn = extern "C" fn (*mut c_void, u8) -> c_int; pub type GetDetectStateFn = extern "C" fn (*mut c_void) -> *mut DetectEngineState; pub type SetDetectStateFn = extern "C" fn (*mut c_void, &mut DetectEngineState) -> c_int; pub type GetEventInfoFn = extern "C" fn (*const c_char, *mut c_int, *mut AppLayerEventType) -> c_int; pub type GetEventInfoByIdFn = extern "C" fn (c_int, *mut *const c_char, *mut AppLayerEventType) -> i8; pub type GetEventsFn = extern "C" fn (*mut c_void) -> *mut AppLayerDecoderEvents; pub type LocalStorageNewFn = extern "C" fn () -> *mut c_void; pub type LocalStorageFreeFn = extern "C" fn (*mut c_void); pub type GetFilesFn = extern "C" fn (*mut c_void, u8) -> *mut FileContainer; pub type GetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, state: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> AppLayerGetTxIterTuple; pub type GetTxDataFn = unsafe extern "C" fn(*mut c_void) -> *mut AppLayerTxData; pub type ApplyTxConfigFn = unsafe extern "C" fn (*mut c_void, *mut c_void, c_int, AppLayerTxConfig); pub type TruncateFn = unsafe extern "C" fn (*mut c_void, u8); // Defined in app-layer-register.h extern { pub fn AppLayerRegisterProtocolDetection(parser: *const RustParser, enable_default: c_int) -> AppProto; pub fn AppLayerRegisterParser(parser: *const RustParser, alproto: AppProto) -> c_int; } // Defined in app-layer-detect-proto.h extern { pub fn AppLayerProtoDetectConfProtoDetectionEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; } // Defined in app-layer-parser.h pub const APP_LAYER_PARSER_EOF : u8 = 0b0; pub const APP_LAYER_PARSER_NO_INSPECTION : u8 = 0b1; pub const APP_LAYER_PARSER_NO_REASSEMBLY : u8 = 0b10; pub const APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD : u8 = 0b100; pub const APP_LAYER_PARSER_BYPASS_READY : u8 = 0b1000; pub const APP_LAYER_PARSER_OPT_ACCEPT_GAPS: u32 = BIT_U32!(0); pub const APP_LAYER_PARSER_OPT_UNIDIR_TXS: u32 = BIT_U32!(1); pub type AppLayerGetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto, alstate: *mut c_void, min_tx_id: u64, max_tx_id: u64, istate: &mut u64) -> applayer::AppLayerGetTxIterTuple; extern { pub fn AppLayerParserStateSetFlag(state: *mut c_void, flag: u8); pub fn AppLayerParserStateIssetFlag(state: *mut c_void, flag: u8) -> c_int; pub fn AppLayerParserConfParserEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int; pub fn AppLayerParserRegisterGetTxIterator(ipproto: u8, alproto: AppProto, fun: AppLayerGetTxIteratorFn); pub fn AppLayerParserRegisterOptionFlags(ipproto: u8, alproto: AppProto, flags: u32); } #[repr(C)] pub struct AppLayerGetTxIterTuple { tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool, } impl AppLayerGetTxIterTuple { pub fn with_values(tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool) -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: tx_ptr, tx_id: tx_id, has_next: has_next, } } pub fn not_found() -> AppLayerGetTxIterTuple { AppLayerGetTxIterTuple { tx_ptr: std::ptr::null_mut(), tx_id: 0, has_next: false, } } } /// LoggerFlags tracks which loggers have already been executed. #[repr(C)] #[derive(Debug,PartialEq)] pub struct LoggerFlags { flags: u32, } impl LoggerFlags { pub fn new() -> LoggerFlags { return LoggerFlags{ flags: 0, } } pub fn get(&self) -> u32 { self.flags } pub fn set(&mut self, bits: u32) { self.flags = bits; } } /// Export a function to get the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_get_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, $type); match tx.de_state { Some(ds) => { return ds; }, None => { return std::ptr::null_mut(); } } } ) } /// Export a function to set the DetectEngineState on a struct. #[macro_export] macro_rules!export_tx_set_detect_state { ($name:ident, $type:ty) => ( #[no_mangle] pub extern "C" fn $name(tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState) -> std::os::raw::c_int { let tx = cast_pointer!(tx, $type); tx.de_state = Some(de_state); 0 } ) }
{ self.log_flags |= flags; }
identifier_body
fn.rs
// One input reference with lifetime `'a` which must live // at least as long as the function. fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } // Mutable references are possible with lifetimes as well. fn add_one<'a>(x: &'a mut i32) { *x += 1;
fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { println!("`print_multi`: x is {}, y is {}", x, y); } // This is invalid. An `i32` would be created, a reference // would be created, then immediately the data would be // dropped leaving a reference to invalid data to be returned. // // The reason the problem is caught is because of the restriction // `<'a>` imposes: `'a` must live longer than the function. //fn invalid_output<'a>() -> &'a i32 { &7 } // While returning references without input is banned, returning // references that have been passed in are perfectly acceptable. // One restriction is the correct lifetime must be returned. fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x } fn main() { let x = 7; let y = 9; print_one(&x); print_multi(&x, &y); let z = pass_x(&x, &y); print_one(z); let mut t = 3; add_one(&mut t); print_one(&t); }
} // Multiple elements with different lifetimes. In this case, it // would be fine for both to have the same lifetime `'a`, but // in more complex cases, different lifetimes may be required.
random_line_split
fn.rs
// One input reference with lifetime `'a` which must live // at least as long as the function. fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } // Mutable references are possible with lifetimes as well. fn add_one<'a>(x: &'a mut i32) { *x += 1; } // Multiple elements with different lifetimes. In this case, it // would be fine for both to have the same lifetime `'a`, but // in more complex cases, different lifetimes may be required. fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { println!("`print_multi`: x is {}, y is {}", x, y); } // This is invalid. An `i32` would be created, a reference // would be created, then immediately the data would be // dropped leaving a reference to invalid data to be returned. // // The reason the problem is caught is because of the restriction // `<'a>` imposes: `'a` must live longer than the function. //fn invalid_output<'a>() -> &'a i32 { &7 } // While returning references without input is banned, returning // references that have been passed in are perfectly acceptable. // One restriction is the correct lifetime must be returned. fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x } fn
() { let x = 7; let y = 9; print_one(&x); print_multi(&x, &y); let z = pass_x(&x, &y); print_one(z); let mut t = 3; add_one(&mut t); print_one(&t); }
main
identifier_name
fn.rs
// One input reference with lifetime `'a` which must live // at least as long as the function. fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } // Mutable references are possible with lifetimes as well. fn add_one<'a>(x: &'a mut i32)
// Multiple elements with different lifetimes. In this case, it // would be fine for both to have the same lifetime `'a`, but // in more complex cases, different lifetimes may be required. fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { println!("`print_multi`: x is {}, y is {}", x, y); } // This is invalid. An `i32` would be created, a reference // would be created, then immediately the data would be // dropped leaving a reference to invalid data to be returned. // // The reason the problem is caught is because of the restriction // `<'a>` imposes: `'a` must live longer than the function. //fn invalid_output<'a>() -> &'a i32 { &7 } // While returning references without input is banned, returning // references that have been passed in are perfectly acceptable. // One restriction is the correct lifetime must be returned. fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x } fn main() { let x = 7; let y = 9; print_one(&x); print_multi(&x, &y); let z = pass_x(&x, &y); print_one(z); let mut t = 3; add_one(&mut t); print_one(&t); }
{ *x += 1; }
identifier_body
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The normal and derived distributions. use num::Real; use rand::{Rng, Rand, Open01}; use rand::distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; /// A wrapper around an `f64` to generate N(0, 1) random numbers /// (a.k.a. a standard normal, or Gaussian). /// /// See `Normal` for the general normal distribution. That this has to /// be unwrapped before use as an `f64` (using either `*` or /// `cast::transmute` is safe). /// /// Implemented via the ZIGNOR variant[1] of the Ziggurat method. /// /// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to /// Generate Normal Random /// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield /// College, Oxford pub struct StandardNormal(f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { // compute a random number in the tail by hand // strange initial conditions, because the loop is not // do-while, so the condition should be true on the first // run, they get overwritten anyway (0 < 1, so these are // good). let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } /// The normal distribution `N(mean, std_dev**2)`. /// /// This uses the ZIGNOR variant of the Ziggurat method, see /// `StandardNormal` for more details. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{Normal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let normal = Normal::new(2.0, 3.0); /// let v = normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from a N(2, 9) distribution", v) /// ``` pub struct Normal { priv mean: f64, priv std_dev: f64 } impl Normal { /// Construct a new `Normal` distribution with the given mean and /// standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } /// The log-normal distribution `ln N(mean, std_dev**2)`. /// /// If `X` is log-normal distributed, then `ln(X)` is `N(mean, /// std_dev**2)` distributed. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{LogNormal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let log_normal = LogNormal::new(2.0, 3.0); /// let v = log_normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from an ln N(2, 9) distribution", v) /// ``` pub struct LogNormal { priv norm: Normal } impl LogNormal { /// Construct a new `LogNormal` distribution with the given mean /// and standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use prelude::*; use rand::*; use super::*; use rand::distributions::*; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn
() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { use extra::test::BenchHarness; use mem::size_of; use prelude::*; use rand::{XorShiftRng, RAND_BENCH_N}; use rand::distributions::*; use super::*; #[bench] fn rand_normal(bh: &mut BenchHarness) { let mut rng = XorShiftRng::new(); let mut normal = Normal::new(-2.71828, 3.14159); bh.iter(|| { for _ in range(0, RAND_BENCH_N) { normal.sample(&mut rng); } }); bh.bytes = size_of::<f64>() as u64 * RAND_BENCH_N; } }
test_log_normal
identifier_name
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The normal and derived distributions. use num::Real; use rand::{Rng, Rand, Open01}; use rand::distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; /// A wrapper around an `f64` to generate N(0, 1) random numbers /// (a.k.a. a standard normal, or Gaussian). /// /// See `Normal` for the general normal distribution. That this has to /// be unwrapped before use as an `f64` (using either `*` or /// `cast::transmute` is safe). /// /// Implemented via the ZIGNOR variant[1] of the Ziggurat method. /// /// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to /// Generate Normal Random /// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield /// College, Oxford pub struct StandardNormal(f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { // compute a random number in the tail by hand // strange initial conditions, because the loop is not // do-while, so the condition should be true on the first // run, they get overwritten anyway (0 < 1, so these are // good). let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else
} StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } /// The normal distribution `N(mean, std_dev**2)`. /// /// This uses the ZIGNOR variant of the Ziggurat method, see /// `StandardNormal` for more details. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{Normal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let normal = Normal::new(2.0, 3.0); /// let v = normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from a N(2, 9) distribution", v) /// ``` pub struct Normal { priv mean: f64, priv std_dev: f64 } impl Normal { /// Construct a new `Normal` distribution with the given mean and /// standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } /// The log-normal distribution `ln N(mean, std_dev**2)`. /// /// If `X` is log-normal distributed, then `ln(X)` is `N(mean, /// std_dev**2)` distributed. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{LogNormal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let log_normal = LogNormal::new(2.0, 3.0); /// let v = log_normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from an ln N(2, 9) distribution", v) /// ``` pub struct LogNormal { priv norm: Normal } impl LogNormal { /// Construct a new `LogNormal` distribution with the given mean /// and standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use prelude::*; use rand::*; use super::*; use rand::distributions::*; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { use extra::test::BenchHarness; use mem::size_of; use prelude::*; use rand::{XorShiftRng, RAND_BENCH_N}; use rand::distributions::*; use super::*; #[bench] fn rand_normal(bh: &mut BenchHarness) { let mut rng = XorShiftRng::new(); let mut normal = Normal::new(-2.71828, 3.14159); bh.iter(|| { for _ in range(0, RAND_BENCH_N) { normal.sample(&mut rng); } }); bh.bytes = size_of::<f64>() as u64 * RAND_BENCH_N; } }
{ ziggurat_tables::ZIG_NORM_R - x }
conditional_block
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The normal and derived distributions. use num::Real; use rand::{Rng, Rand, Open01}; use rand::distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; /// A wrapper around an `f64` to generate N(0, 1) random numbers /// (a.k.a. a standard normal, or Gaussian). /// /// See `Normal` for the general normal distribution. That this has to /// be unwrapped before use as an `f64` (using either `*` or /// `cast::transmute` is safe). /// /// Implemented via the ZIGNOR variant[1] of the Ziggurat method. /// /// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to /// Generate Normal Random /// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield /// College, Oxford pub struct StandardNormal(f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { // compute a random number in the tail by hand // strange initial conditions, because the loop is not // do-while, so the condition should be true on the first // run, they get overwritten anyway (0 < 1, so these are // good). let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln();
if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } /// The normal distribution `N(mean, std_dev**2)`. /// /// This uses the ZIGNOR variant of the Ziggurat method, see /// `StandardNormal` for more details. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{Normal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let normal = Normal::new(2.0, 3.0); /// let v = normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from a N(2, 9) distribution", v) /// ``` pub struct Normal { priv mean: f64, priv std_dev: f64 } impl Normal { /// Construct a new `Normal` distribution with the given mean and /// standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } /// The log-normal distribution `ln N(mean, std_dev**2)`. /// /// If `X` is log-normal distributed, then `ln(X)` is `N(mean, /// std_dev**2)` distributed. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{LogNormal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let log_normal = LogNormal::new(2.0, 3.0); /// let v = log_normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from an ln N(2, 9) distribution", v) /// ``` pub struct LogNormal { priv norm: Normal } impl LogNormal { /// Construct a new `LogNormal` distribution with the given mean /// and standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use prelude::*; use rand::*; use super::*; use rand::distributions::*; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { use extra::test::BenchHarness; use mem::size_of; use prelude::*; use rand::{XorShiftRng, RAND_BENCH_N}; use rand::distributions::*; use super::*; #[bench] fn rand_normal(bh: &mut BenchHarness) { let mut rng = XorShiftRng::new(); let mut normal = Normal::new(-2.71828, 3.14159); bh.iter(|| { for _ in range(0, RAND_BENCH_N) { normal.sample(&mut rng); } }); bh.bytes = size_of::<f64>() as u64 * RAND_BENCH_N; } }
}
random_line_split
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The normal and derived distributions. use num::Real; use rand::{Rng, Rand, Open01}; use rand::distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; /// A wrapper around an `f64` to generate N(0, 1) random numbers /// (a.k.a. a standard normal, or Gaussian). /// /// See `Normal` for the general normal distribution. That this has to /// be unwrapped before use as an `f64` (using either `*` or /// `cast::transmute` is safe). /// /// Implemented via the ZIGNOR variant[1] of the Ziggurat method. /// /// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to /// Generate Normal Random /// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield /// College, Oxford pub struct StandardNormal(f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { // compute a random number in the tail by hand // strange initial conditions, because the loop is not // do-while, so the condition should be true on the first // run, they get overwritten anyway (0 < 1, so these are // good). let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } /// The normal distribution `N(mean, std_dev**2)`. /// /// This uses the ZIGNOR variant of the Ziggurat method, see /// `StandardNormal` for more details. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{Normal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let normal = Normal::new(2.0, 3.0); /// let v = normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from a N(2, 9) distribution", v) /// ``` pub struct Normal { priv mean: f64, priv std_dev: f64 } impl Normal { /// Construct a new `Normal` distribution with the given mean and /// standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> Normal
} impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } /// The log-normal distribution `ln N(mean, std_dev**2)`. /// /// If `X` is log-normal distributed, then `ln(X)` is `N(mean, /// std_dev**2)` distributed. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{LogNormal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let log_normal = LogNormal::new(2.0, 3.0); /// let v = log_normal.ind_sample(&mut rand::task_rng()); /// println!("{} is from an ln N(2, 9) distribution", v) /// ``` pub struct LogNormal { priv norm: Normal } impl LogNormal { /// Construct a new `LogNormal` distribution with the given mean /// and standard deviation. Fails if `std_dev < 0`. pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use prelude::*; use rand::*; use super::*; use rand::distributions::*; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = task_rng(); for _ in range(0, 1000) { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } } #[cfg(test)] mod bench { use extra::test::BenchHarness; use mem::size_of; use prelude::*; use rand::{XorShiftRng, RAND_BENCH_N}; use rand::distributions::*; use super::*; #[bench] fn rand_normal(bh: &mut BenchHarness) { let mut rng = XorShiftRng::new(); let mut normal = Normal::new(-2.71828, 3.14159); bh.iter(|| { for _ in range(0, RAND_BENCH_N) { normal.sample(&mut rng); } }); bh.bytes = size_of::<f64>() as u64 * RAND_BENCH_N; } }
{ assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } }
identifier_body
lift.rs
#![allow(dead_code, unused)] #![feature(type_ascription)] use std::collections::linked_list::LinkedList; use std::collections::vec_deque::VecDeque; use std::collections::{BinaryHeap, BTreeSet, HashSet}; pub trait Higher<A> { type B; //current type inside higher type, i.e Vec<B> type C; //swapped higher type, i.e C = Vec<A> } /// macro to lift types #[macro_export] macro_rules! lift { ($t:ident) => { impl<A,C> Higher<A> for $t<C> { type B = C; type C = $t<A>; } } } // lifting types lift!(Vec); lift!(Option); lift!(Box); lift!(LinkedList); lift!(BinaryHeap); lift!(BTreeSet); lift!(VecDeque); lift!(HashSet); ///`SemiGroup` trait ///requires one function: ///add: &self -> &A -> A pub trait SemiGroup { type A; fn add(&self, b: &Self::A) -> Self::A; } ///`Monoid` trait ///requires one function: ///id: &self -> A pub trait Monoid : SemiGroup { fn id() -> Self::A; } ///`Foldable` trait ///requires an accumulator type `A` ///a function foldr: &self -> `Self::A` `f: F` -> `Self::A` pub trait Foldable { type A; //accumulator type fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A where F: FnMut(Self::A, &Self::A) -> Self::A; } /// `Functor` trait, similar to Haskell's functor class /// requires a function fmap of type: &self -> Fn(`&Self::B`) -> A /// e.g `Some(2).fmap(|x| x*x) = Some(4)` /// `None.fmap(|x| x*x) = None` pub trait Functor<A>: Higher<A> { fn fmap<F>(&self, f: F) -> Self::C where F: Fn(&Self::B) -> A; } ///`Applicative` trait, similar to Haskell's applicative class ///requires two functions: ///raise (normally pure): lifts a B to an A<B> i.e `Option::lift(2) = Some(2)` ///apply (<*> in haskell): applies an applicative functor i.e `Some(2).apply(Some(f)) = Some(f(2))` pub trait Applicative<A> : Higher<A> { fn raise(x: A) -> Self::C where Self: Higher<A, B=A>; fn apply<F>(&self, <Self as Higher<F>>::C) -> <Self as Higher<A>>::C where F: Fn(&<Self as Higher<A>>::B) -> A, Self: Higher<F>; //kinda ugly } /// `Monad trait`, similar to Haskell's monad class /// requires two functions: /// lift (usually return but return is reserved): lifts an B to an A<B>, i.e `Option::lift(2) = Some(2)` /// bind: maps an A<B> to an A<C> i.e `Some(2).bind(|x| Some(x+1)) = Some(3)` pub trait Monad<A>: Higher<A> { fn lift(x: A) -> Self::C where Self: Higher<A, B = A>; fn bind<F>(&self, F) -> Self::C where F: FnMut(&Self::B) -> Self::C; } //macros // ///A quick macro to functorize types implementing Iter #[macro_export] macro_rules! functorize { ($t:ident) => { impl<A,B> Functor<A> for $t<B> { fn fmap<F>(&self, f:F) -> $t<A> where F: Fn(&B) -> A { self.iter().map(f).collect::<$t<A>>() } } } } ///A macro to implement monoid for numeric semigroups #[macro_export] macro_rules! monoid_num { ($t:ident, $z:expr) => { impl Monoid for $t { fn id() -> Self::A { $z } } }
($t:ident) => { impl<T: Clone> Monoid for $t<T> { fn id() -> Self::A { $t::new() } } } } ///Macro to implement ordered SemiGroups like BTreeSet which have a new method #[macro_export] macro_rules! monoid_ord { ($t:ident) => { impl<T: Clone + Ord> Monoid for $t<T> { fn id() -> Self::A { $t::new() } } } } ///Macro to implement fold for iterables #[macro_export] macro_rules! foldable { ($t:ident) => { impl<T> Foldable for $t<T> { type A = T; fn foldr<F>(&self, accum: Self::A, f: F) -> Self::A where F: FnMut(Self::A, &Self::A) -> Self::A { self.iter().fold(accum, f) } } } } ///Macro to implement semigroup for numerics #[macro_export] macro_rules! semigroup_num { ($t:ident) => { impl SemiGroup for $t { type A = $t; fn add(&self, b: &Self::A) -> Self::A { self + b } } } } ///Macro for implementing SemiGroup for types that implement Extend #[macro_export] macro_rules! semigroup { ($t:ident) => { impl<T: Clone> SemiGroup for $t<T> { type A = $t<T>; fn add(&self, b: &Self::A) -> Self::A { let mut ret = $t::new(); ret.extend(self.iter().cloned()); ret.extend(b.iter().cloned()); ret } } } } ///A macro for implementing SemiGroups for types that need Ord and implement Extended #[macro_export] macro_rules! semigroup_ord { ($t:ident) => { impl<T: Clone + Ord> SemiGroup for $t<T> { type A = $t<T>; fn add(&self, b: &Self::A) -> Self::A { let mut ret = $t::new(); ret.extend(self.iter().cloned()); ret.extend(b.iter().cloned()); ret } } } }
} ///A macro to implement monoid for Semigroups which have a new method #[macro_export] macro_rules! monoid {
random_line_split
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { if self.inner.is_empty() { return None; } let end = self.inner.len(); let next_end = self.inner .find(self.end_char) .unwrap_or(end); let (delimited, rest) = self.inner.split_at(next_end); let next_start = rest.find(self.start_char) .map(|p| p + 1) .unwrap_or(end - delimited.len()); self.inner = &rest[next_start..]; Some(delimited) } } fn exteriors(s: &str) -> Delimited { Delimited { inner: &s, start_char: ']',
let start = s.find('[').map(|p| p + 1).unwrap_or(s.len()); Delimited { inner: &s[start..], start_char: '[', end_char: ']', } } struct SearchWindows<'a> { current: Option<&'a str>, inner: Delimited<'a>, get_window: Box<Fn(&str) -> Option<&str>>, predicate: Box<Fn(&str) -> bool>, } impl<'a> SearchWindows<'a> { fn new<F, P>(mut delimiters: Delimited<'a>, get: F, pred: P) -> SearchWindows<'a> where F:'static + Fn(&str) -> Option<&str>, P:'static + Fn(&str) -> bool { SearchWindows { current: delimiters.next(), inner: delimiters, get_window: Box::new(get), predicate: Box::new(pred), } } } impl<'a> Iterator for SearchWindows<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { while self.current.is_some() { while let Some(win) = (self.get_window)(self.current.unwrap()) { self.current = Some(advance(self.current.unwrap())); if (self.predicate)(win) { return Some(win); } } self.current = self.inner.next(); } None } } fn abbas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 4), is_abba) } fn anti_abbas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 4), is_abba) } fn abas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 3), is_aba) } fn anti_abas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 3), is_aba) } fn advance(s: &str) -> &str { let mut iter = s.chars(); iter.next(); iter.as_str() } fn window(s: &str, len: usize) -> Option<&str> { if len == 0 { return None; } s.char_indices().nth(len - 1).map(|(idx, ch)| &s[..idx + ch.len_utf8()]) } fn is_abba(candidate: &str) -> bool { if candidate.len()!= 4 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); let d = iter.next().unwrap(); a == d && b == c && a!= b } fn is_aba(candidate: &str) -> bool { if candidate.len()!= 3 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); a == c && a!= b } fn is_corresponding_bab(aba: &str, candidate: &str) -> bool { if aba.len()!= 3 || candidate.len()!= 3 { return false; } let mut cand_iter = candidate.chars(); let a = cand_iter.next().unwrap(); let b = cand_iter.next().unwrap(); let c = cand_iter.next().unwrap(); let mut aba_iter = aba.chars(); aba_iter.next() == Some(b) && aba_iter.next() == Some(a) && aba_iter.next() == Some(b) && a == c } fn supports_tls(candidate: &str) -> bool { anti_abbas(candidate).next().is_none() && abbas(candidate).next().is_some() } fn supports_ssl(candidate: &str) -> bool { abas(candidate).any(|aba| { anti_abas(candidate).any(|bab| is_corresponding_bab(aba, bab)) }) } fn parse_args() -> std::io::Result<Box<Read>> { let source = clap::App::new("Day 07") .author("Devon Hollowood") .arg(clap::Arg::with_name("ips") .index(1) .short("f") .long("ips") .help("file to read IPs from. Reads from stdin otherwise") .takes_value(true)) .get_matches() .value_of_os("ips") .map(|str| str.to_owned()); match source { Some(filename) => Ok(Box::new(File::open(filename)?)), None => Ok(Box::new(std::io::stdin())), } } fn read_ips<R: Read>(source: &mut R) -> std::io::Result<Vec<String>> { let mut contents = String::new(); source.read_to_string(&mut contents)?; Ok(contents.lines().map(|line| line.trim().to_owned()).collect()) } fn main() { let mut source = parse_args() .unwrap_or_else(|err| panic!("Error reading file: {}", err)); let ips = read_ips(&mut source) .unwrap_or_else(|err| panic!("Error reading ips: {}", err)); let n_support_tls = ips.iter().filter(|ip| supports_tls(&ip)).count(); let n_support_ssl = ips.iter().filter(|ip| supports_ssl(&ip)).count(); println!("# of IPs supporting TLS: {}", n_support_tls); println!("# of IPs supporting SSL: {}", n_support_ssl); }
end_char: '[', } } fn interiors(s: &str) -> Delimited {
random_line_split
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { if self.inner.is_empty()
let end = self.inner.len(); let next_end = self.inner .find(self.end_char) .unwrap_or(end); let (delimited, rest) = self.inner.split_at(next_end); let next_start = rest.find(self.start_char) .map(|p| p + 1) .unwrap_or(end - delimited.len()); self.inner = &rest[next_start..]; Some(delimited) } } fn exteriors(s: &str) -> Delimited { Delimited { inner: &s, start_char: ']', end_char: '[', } } fn interiors(s: &str) -> Delimited { let start = s.find('[').map(|p| p + 1).unwrap_or(s.len()); Delimited { inner: &s[start..], start_char: '[', end_char: ']', } } struct SearchWindows<'a> { current: Option<&'a str>, inner: Delimited<'a>, get_window: Box<Fn(&str) -> Option<&str>>, predicate: Box<Fn(&str) -> bool>, } impl<'a> SearchWindows<'a> { fn new<F, P>(mut delimiters: Delimited<'a>, get: F, pred: P) -> SearchWindows<'a> where F:'static + Fn(&str) -> Option<&str>, P:'static + Fn(&str) -> bool { SearchWindows { current: delimiters.next(), inner: delimiters, get_window: Box::new(get), predicate: Box::new(pred), } } } impl<'a> Iterator for SearchWindows<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { while self.current.is_some() { while let Some(win) = (self.get_window)(self.current.unwrap()) { self.current = Some(advance(self.current.unwrap())); if (self.predicate)(win) { return Some(win); } } self.current = self.inner.next(); } None } } fn abbas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 4), is_abba) } fn anti_abbas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 4), is_abba) } fn abas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 3), is_aba) } fn anti_abas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 3), is_aba) } fn advance(s: &str) -> &str { let mut iter = s.chars(); iter.next(); iter.as_str() } fn window(s: &str, len: usize) -> Option<&str> { if len == 0 { return None; } s.char_indices().nth(len - 1).map(|(idx, ch)| &s[..idx + ch.len_utf8()]) } fn is_abba(candidate: &str) -> bool { if candidate.len()!= 4 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); let d = iter.next().unwrap(); a == d && b == c && a!= b } fn is_aba(candidate: &str) -> bool { if candidate.len()!= 3 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); a == c && a!= b } fn is_corresponding_bab(aba: &str, candidate: &str) -> bool { if aba.len()!= 3 || candidate.len()!= 3 { return false; } let mut cand_iter = candidate.chars(); let a = cand_iter.next().unwrap(); let b = cand_iter.next().unwrap(); let c = cand_iter.next().unwrap(); let mut aba_iter = aba.chars(); aba_iter.next() == Some(b) && aba_iter.next() == Some(a) && aba_iter.next() == Some(b) && a == c } fn supports_tls(candidate: &str) -> bool { anti_abbas(candidate).next().is_none() && abbas(candidate).next().is_some() } fn supports_ssl(candidate: &str) -> bool { abas(candidate).any(|aba| { anti_abas(candidate).any(|bab| is_corresponding_bab(aba, bab)) }) } fn parse_args() -> std::io::Result<Box<Read>> { let source = clap::App::new("Day 07") .author("Devon Hollowood") .arg(clap::Arg::with_name("ips") .index(1) .short("f") .long("ips") .help("file to read IPs from. Reads from stdin otherwise") .takes_value(true)) .get_matches() .value_of_os("ips") .map(|str| str.to_owned()); match source { Some(filename) => Ok(Box::new(File::open(filename)?)), None => Ok(Box::new(std::io::stdin())), } } fn read_ips<R: Read>(source: &mut R) -> std::io::Result<Vec<String>> { let mut contents = String::new(); source.read_to_string(&mut contents)?; Ok(contents.lines().map(|line| line.trim().to_owned()).collect()) } fn main() { let mut source = parse_args() .unwrap_or_else(|err| panic!("Error reading file: {}", err)); let ips = read_ips(&mut source) .unwrap_or_else(|err| panic!("Error reading ips: {}", err)); let n_support_tls = ips.iter().filter(|ip| supports_tls(&ip)).count(); let n_support_ssl = ips.iter().filter(|ip| supports_ssl(&ip)).count(); println!("# of IPs supporting TLS: {}", n_support_tls); println!("# of IPs supporting SSL: {}", n_support_ssl); }
{ return None; }
conditional_block
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { if self.inner.is_empty() { return None; } let end = self.inner.len(); let next_end = self.inner .find(self.end_char) .unwrap_or(end); let (delimited, rest) = self.inner.split_at(next_end); let next_start = rest.find(self.start_char) .map(|p| p + 1) .unwrap_or(end - delimited.len()); self.inner = &rest[next_start..]; Some(delimited) } } fn exteriors(s: &str) -> Delimited { Delimited { inner: &s, start_char: ']', end_char: '[', } } fn interiors(s: &str) -> Delimited { let start = s.find('[').map(|p| p + 1).unwrap_or(s.len()); Delimited { inner: &s[start..], start_char: '[', end_char: ']', } } struct SearchWindows<'a> { current: Option<&'a str>, inner: Delimited<'a>, get_window: Box<Fn(&str) -> Option<&str>>, predicate: Box<Fn(&str) -> bool>, } impl<'a> SearchWindows<'a> { fn new<F, P>(mut delimiters: Delimited<'a>, get: F, pred: P) -> SearchWindows<'a> where F:'static + Fn(&str) -> Option<&str>, P:'static + Fn(&str) -> bool { SearchWindows { current: delimiters.next(), inner: delimiters, get_window: Box::new(get), predicate: Box::new(pred), } } } impl<'a> Iterator for SearchWindows<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { while self.current.is_some() { while let Some(win) = (self.get_window)(self.current.unwrap()) { self.current = Some(advance(self.current.unwrap())); if (self.predicate)(win) { return Some(win); } } self.current = self.inner.next(); } None } } fn abbas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 4), is_abba) } fn anti_abbas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 4), is_abba) } fn abas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 3), is_aba) } fn anti_abas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 3), is_aba) } fn advance(s: &str) -> &str { let mut iter = s.chars(); iter.next(); iter.as_str() } fn window(s: &str, len: usize) -> Option<&str> { if len == 0 { return None; } s.char_indices().nth(len - 1).map(|(idx, ch)| &s[..idx + ch.len_utf8()]) } fn is_abba(candidate: &str) -> bool { if candidate.len()!= 4 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); let d = iter.next().unwrap(); a == d && b == c && a!= b } fn is_aba(candidate: &str) -> bool { if candidate.len()!= 3 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); a == c && a!= b } fn is_corresponding_bab(aba: &str, candidate: &str) -> bool
fn supports_tls(candidate: &str) -> bool { anti_abbas(candidate).next().is_none() && abbas(candidate).next().is_some() } fn supports_ssl(candidate: &str) -> bool { abas(candidate).any(|aba| { anti_abas(candidate).any(|bab| is_corresponding_bab(aba, bab)) }) } fn parse_args() -> std::io::Result<Box<Read>> { let source = clap::App::new("Day 07") .author("Devon Hollowood") .arg(clap::Arg::with_name("ips") .index(1) .short("f") .long("ips") .help("file to read IPs from. Reads from stdin otherwise") .takes_value(true)) .get_matches() .value_of_os("ips") .map(|str| str.to_owned()); match source { Some(filename) => Ok(Box::new(File::open(filename)?)), None => Ok(Box::new(std::io::stdin())), } } fn read_ips<R: Read>(source: &mut R) -> std::io::Result<Vec<String>> { let mut contents = String::new(); source.read_to_string(&mut contents)?; Ok(contents.lines().map(|line| line.trim().to_owned()).collect()) } fn main() { let mut source = parse_args() .unwrap_or_else(|err| panic!("Error reading file: {}", err)); let ips = read_ips(&mut source) .unwrap_or_else(|err| panic!("Error reading ips: {}", err)); let n_support_tls = ips.iter().filter(|ip| supports_tls(&ip)).count(); let n_support_ssl = ips.iter().filter(|ip| supports_ssl(&ip)).count(); println!("# of IPs supporting TLS: {}", n_support_tls); println!("# of IPs supporting SSL: {}", n_support_ssl); }
{ if aba.len() != 3 || candidate.len() != 3 { return false; } let mut cand_iter = candidate.chars(); let a = cand_iter.next().unwrap(); let b = cand_iter.next().unwrap(); let c = cand_iter.next().unwrap(); let mut aba_iter = aba.chars(); aba_iter.next() == Some(b) && aba_iter.next() == Some(a) && aba_iter.next() == Some(b) && a == c }
identifier_body
main.rs
extern crate clap; use std::io::prelude::*; use std::fs::File; #[derive(Debug)] /// Iterator over parts of str in delimiters struct Delimited<'a> { inner: &'a str, start_char: char, end_char: char, } impl<'a> Iterator for Delimited<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { if self.inner.is_empty() { return None; } let end = self.inner.len(); let next_end = self.inner .find(self.end_char) .unwrap_or(end); let (delimited, rest) = self.inner.split_at(next_end); let next_start = rest.find(self.start_char) .map(|p| p + 1) .unwrap_or(end - delimited.len()); self.inner = &rest[next_start..]; Some(delimited) } } fn exteriors(s: &str) -> Delimited { Delimited { inner: &s, start_char: ']', end_char: '[', } } fn interiors(s: &str) -> Delimited { let start = s.find('[').map(|p| p + 1).unwrap_or(s.len()); Delimited { inner: &s[start..], start_char: '[', end_char: ']', } } struct SearchWindows<'a> { current: Option<&'a str>, inner: Delimited<'a>, get_window: Box<Fn(&str) -> Option<&str>>, predicate: Box<Fn(&str) -> bool>, } impl<'a> SearchWindows<'a> { fn
<F, P>(mut delimiters: Delimited<'a>, get: F, pred: P) -> SearchWindows<'a> where F:'static + Fn(&str) -> Option<&str>, P:'static + Fn(&str) -> bool { SearchWindows { current: delimiters.next(), inner: delimiters, get_window: Box::new(get), predicate: Box::new(pred), } } } impl<'a> Iterator for SearchWindows<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { while self.current.is_some() { while let Some(win) = (self.get_window)(self.current.unwrap()) { self.current = Some(advance(self.current.unwrap())); if (self.predicate)(win) { return Some(win); } } self.current = self.inner.next(); } None } } fn abbas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 4), is_abba) } fn anti_abbas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 4), is_abba) } fn abas(s: &str) -> SearchWindows { SearchWindows::new(exteriors(s), |st| window(st, 3), is_aba) } fn anti_abas(s: &str) -> SearchWindows { SearchWindows::new(interiors(s), |st| window(st, 3), is_aba) } fn advance(s: &str) -> &str { let mut iter = s.chars(); iter.next(); iter.as_str() } fn window(s: &str, len: usize) -> Option<&str> { if len == 0 { return None; } s.char_indices().nth(len - 1).map(|(idx, ch)| &s[..idx + ch.len_utf8()]) } fn is_abba(candidate: &str) -> bool { if candidate.len()!= 4 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); let d = iter.next().unwrap(); a == d && b == c && a!= b } fn is_aba(candidate: &str) -> bool { if candidate.len()!= 3 { return false; } let mut iter = candidate.chars(); let a = iter.next().unwrap(); let b = iter.next().unwrap(); let c = iter.next().unwrap(); a == c && a!= b } fn is_corresponding_bab(aba: &str, candidate: &str) -> bool { if aba.len()!= 3 || candidate.len()!= 3 { return false; } let mut cand_iter = candidate.chars(); let a = cand_iter.next().unwrap(); let b = cand_iter.next().unwrap(); let c = cand_iter.next().unwrap(); let mut aba_iter = aba.chars(); aba_iter.next() == Some(b) && aba_iter.next() == Some(a) && aba_iter.next() == Some(b) && a == c } fn supports_tls(candidate: &str) -> bool { anti_abbas(candidate).next().is_none() && abbas(candidate).next().is_some() } fn supports_ssl(candidate: &str) -> bool { abas(candidate).any(|aba| { anti_abas(candidate).any(|bab| is_corresponding_bab(aba, bab)) }) } fn parse_args() -> std::io::Result<Box<Read>> { let source = clap::App::new("Day 07") .author("Devon Hollowood") .arg(clap::Arg::with_name("ips") .index(1) .short("f") .long("ips") .help("file to read IPs from. Reads from stdin otherwise") .takes_value(true)) .get_matches() .value_of_os("ips") .map(|str| str.to_owned()); match source { Some(filename) => Ok(Box::new(File::open(filename)?)), None => Ok(Box::new(std::io::stdin())), } } fn read_ips<R: Read>(source: &mut R) -> std::io::Result<Vec<String>> { let mut contents = String::new(); source.read_to_string(&mut contents)?; Ok(contents.lines().map(|line| line.trim().to_owned()).collect()) } fn main() { let mut source = parse_args() .unwrap_or_else(|err| panic!("Error reading file: {}", err)); let ips = read_ips(&mut source) .unwrap_or_else(|err| panic!("Error reading ips: {}", err)); let n_support_tls = ips.iter().filter(|ip| supports_tls(&ip)).count(); let n_support_ssl = ips.iter().filter(|ip| supports_ssl(&ip)).count(); println!("# of IPs supporting TLS: {}", n_support_tls); println!("# of IPs supporting SSL: {}", n_support_ssl); }
new
identifier_name
mod.rs
//! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //! ## `Header` and `HeaderFormat` //! //! Consider a Do Not Track header. It can be true or false, but it represents //! that via the numerals `1` and `0`. //! //! ``` //! use std::fmt; //! use hyper::header::{Header, HeaderFormat}; //! //! #[derive(Debug, Clone, Copy)] //! struct Dnt(bool); //! //! impl Header for Dnt { //! fn header_name() -> &'static str { //! "DNT" //! } //! //! fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<Dnt> { //! if raw.len() == 1 { //! let line = &raw[0]; //! if line.len() == 1 { //! let byte = line[0]; //! match byte { //! b'0' => return Ok(Dnt(true)), //! b'1' => return Ok(Dnt(false)), //! _ => () //! } //! } //! } //! Err(hyper::Error::Header) //! } //! } //! //! impl HeaderFormat for Dnt { //! fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { //! if self.0 { //! f.write_str("1") //! } else { //! f.write_str("0") //! } //! } //! } //! ``` use std::any::Any; use std::borrow::{Cow, ToOwned}; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; use std::iter::{FromIterator, IntoIterator}; use std::ops::{Deref, DerefMut}; use std::{mem, fmt}; use {httparse, traitobject}; use typeable::Typeable; use unicase::UniCase; use self::internals::Item; pub use self::shared::*; pub use self::common::*; mod common; mod internals; mod shared; pub mod parsing; type HeaderName = UniCase<CowStr>; /// A trait for any object that will represent a header field and value. /// /// This trait represents the construction and identification of headers, /// and contains trait-object unsafe methods. pub trait Header: Clone + Any + Send + Sync { /// Returns the name of the header field this belongs to. /// /// This will become an associated constant once available. fn header_name() -> &'static str; /// Parse a header from a raw stream of bytes. /// /// It's possible that a request can include a header field more than once, /// and in that case, the slice will have a length greater than 1. However, /// it's not necessarily the case that a Header is *allowed* to have more /// than one field value. If that's the case, you **should** return `None` /// if `raw.len() > 1`. fn parse_header(raw: &[Vec<u8>]) -> ::Result<Self>; } /// A trait for any object that will represent a header field and value. /// /// This trait represents the formatting of a Header for output to a TcpStream. pub trait HeaderFormat: fmt::Debug + HeaderClone + Any + Typeable + Send + Sync { /// Format a header to be output into a TcpStream. /// /// This method is not allowed to introduce an Err not produced /// by the passed-in Formatter. fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result; } #[doc(hidden)] pub trait HeaderClone { fn clone_box(&self) -> Box<HeaderFormat + Send + Sync>; } impl<T: HeaderFormat + Clone> HeaderClone for T { #[inline] fn clone_box(&self) -> Box<HeaderFormat + Send + Sync> { Box::new(self.clone()) } } impl HeaderFormat + Send + Sync { #[inline] unsafe fn downcast_ref_unchecked<T:'static>(&self) -> &T { mem::transmute(traitobject::data(self)) } #[inline] unsafe fn downcast_mut_unchecked<T:'static>(&mut self) -> &mut T { mem::transmute(traitobject::data_mut(self)) } } impl Clone for Box<HeaderFormat + Send + Sync> { #[inline] fn clone(&self) -> Box<HeaderFormat + Send + Sync> { self.clone_box() } } #[inline] fn header_name<T: Header>() -> &'static str { <T as Header>::header_name() } /// A map of header fields on requests and responses. #[derive(Clone)] pub struct Headers { data: HashMap<HeaderName, Item> } impl Headers { /// Creates a new, empty headers map. pub fn new() -> Headers { Headers { data: HashMap::new() } } #[doc(hidden)] pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> ::Result<Headers> { let mut headers = Headers::new(); for header in raw { trace!("raw header: {:?}={:?}", header.name, &header.value[..]); let name = UniCase(CowStr(Cow::Owned(header.name.to_owned()))); let mut item = match headers.data.entry(name) { Entry::Vacant(entry) => entry.insert(Item::new_raw(vec![])), Entry::Occupied(entry) => entry.into_mut() }; let trim = header.value.iter().rev().take_while(|&&x| x == b' ').count(); let value = &header.value[.. header.value.len() - trim]; item.mut_raw().push(value.to_vec()); } Ok(headers) } /// Set a header field to the corresponding value. /// /// The field is determined by the type of the value being set. pub fn set<H: Header + HeaderFormat>(&mut self, value: H) { self.data.insert(UniCase(CowStr(Cow::Borrowed(header_name::<H>()))), Item::new_typed(Box::new(value))); } /// Access the raw value of a header. /// /// Prefer to use the typed getters instead. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// let raw_content_type = headers.get_raw("content-type"); /// ``` pub fn get_raw(&self, name: &str) -> Option<&[Vec<u8>]> { self.data .get(&UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) })))) .map(Item::raw) } /// Set the raw value of a header, bypassing any typed headers. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// headers.set_raw("content-length", vec![b"5".to_vec()]); /// ``` pub fn set_raw<K: Into<Cow<'static, str>>>(&mut self, name: K, value: Vec<Vec<u8>>) { self.data.insert(UniCase(CowStr(name.into())), Item::new_raw(value)); } /// Remove a header set by set_raw pub fn remove_raw(&mut self, name: &str) { self.data.remove( &UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) ); } /// Get a reference to the header field's value, if it exists. pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> { self.data.get(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed::<H>) } /// Get a mutable reference to the header field's value, if it exists. pub fn get_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> { self.data.get_mut(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed_mut::<H>) } /// Returns a boolean of whether a certain header is in the map. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # use hyper::header::ContentType; /// # let mut headers = Headers::new(); /// let has_type = headers.has::<ContentType>(); /// ``` pub fn has<H: Header + HeaderFormat>(&self) -> bool { self.data.contains_key(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))) } /// Removes a header from the map, if one existed. /// Returns true if a header has been removed. pub fn remove<H: Header + HeaderFormat>(&mut self) -> bool { self.data.remove(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).is_some() } /// Returns an iterator over the header fields. pub fn iter<'a>(&'a self) -> HeadersItems<'a> { HeadersItems { inner: self.data.iter() } } /// Returns the number of headers in the map. pub fn len(&self) -> usize { self.data.len() } /// Remove all headers from the map. pub fn clear(&mut self) { self.data.clear() } } impl fmt::Display for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for header in self.iter() { try!(write!(f, "{}\r\n", header)); } Ok(()) } } impl fmt::Debug for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str("Headers { ")); for header in self.iter() { try!(write!(f, "{:?}, ", header)); } try!(f.write_str("}")); Ok(()) } } /// An `Iterator` over the fields in a `Headers` map. pub struct HeadersItems<'a> { inner: Iter<'a, HeaderName, Item> } impl<'a> Iterator for HeadersItems<'a> { type Item = HeaderView<'a>; fn next(&mut self) -> Option<HeaderView<'a>> { self.inner.next().map(|(k, v)| HeaderView(k, v)) } } /// Returned with the `HeadersItems` iterator. pub struct HeaderView<'a>(&'a HeaderName, &'a Item); impl<'a> HeaderView<'a> { /// Check if a HeaderView is a certain Header. #[inline] pub fn is<H: Header>(&self) -> bool { UniCase(CowStr(Cow::Borrowed(header_name::<H>()))) == *self.0 } /// Get the Header name as a slice. #[inline] pub fn name(&self) -> &'a str { self.0.as_ref() } /// Cast the value to a certain Header type. #[inline] pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> { self.1.typed::<H>() } /// Get just the header value as a String. #[inline] pub fn value_string(&self) -> String { (*self.1).to_string() } } impl<'a> fmt::Display for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {}", self.0, *self.1) } } impl<'a> fmt::Debug for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl<'a> Extend<HeaderView<'a>> for Headers { fn extend<I: IntoIterator<Item=HeaderView<'a>>>(&mut self, iter: I) { for header in iter { self.data.insert((*header.0).clone(), (*header.1).clone()); } } } impl<'a> FromIterator<HeaderView<'a>> for Headers { fn from_iter<I: IntoIterator<Item=HeaderView<'a>>>(iter: I) -> Headers { let mut headers = Headers::new(); headers.extend(iter); headers } } impl<'a> fmt::Display for &'a (HeaderFormat + Send + Sync) { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(f) } } /// A wrapper around any Header with a Display impl that calls fmt_header. /// /// This can be used like so: `format!("{}", HeaderFormatter(&header))` to /// get the representation of a Header which will be written to an /// outgoing TcpStream. pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); impl<'a, H: HeaderFormat> fmt::Display for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } #[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)] struct CowStr(Cow<'static, str>); impl Deref for CowStr { type Target = Cow<'static, str>; fn deref(&self) -> &Cow<'static, str> { &self.0 } } impl fmt::Debug for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl fmt::Display for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl DerefMut for CowStr { fn deref_mut(&mut self) -> &mut Cow<'static, str> { &mut self.0 } } impl AsRef<str> for CowStr { fn as_ref(&self) -> &str { self } } #[cfg(test)] mod tests { use std::fmt; use mime::Mime; use mime::TopLevel::Text; use mime::SubLevel::Plain; use super::{Headers, Header, HeaderFormat, ContentLength, ContentType, Accept, Host, qitem}; use httparse; #[cfg(feature = "nightly")] use test::Bencher; // Slice.position_elem is unstable fn index_of(slice: &[u8], byte: u8) -> Option<usize> { for (index, &b) in slice.iter().enumerate() { if b == byte { return Some(index); } } None } macro_rules! raw { ($($line:expr),*) => ({ [$({ let line = $line; let pos = index_of(line, b':').expect("raw splits on ':', not found"); httparse::Header { name: ::std::str::from_utf8(&line[..pos]).unwrap(), value: &line[pos + 2..] } }),*] }) } #[test] fn test_from_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get(), Some(&ContentLength(10))); } #[test] fn test_content_type() { let content_type = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(content_type.ok(), Some(ContentType(Mime(Text, Plain, vec![])))); } #[test] fn test_accept() { let text_plain = qitem(Mime(Text, Plain, vec![])); let application_vendor = "application/vnd.github.v3.full+json; q=0.5".parse().unwrap(); let accept = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![text_plain.clone()]))); let accept = Header::parse_header([b"application/vnd.github.v3.full+json; q=0.5, text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![application_vendor, text_plain]))); } #[derive(Clone, PartialEq, Debug)] struct CrazyLength(Option<bool>, usize); impl Header for CrazyLength { fn header_name() -> &'static str { "content-length" } fn parse_header(raw: &[Vec<u8>]) -> ::Result<CrazyLength> { use std::str::from_utf8; use std::str::FromStr; if raw.len()!= 1
// we JUST checked that raw.len() == 1, so raw[0] WILL exist. match match from_utf8(unsafe { &raw.get_unchecked(0)[..] }) { Ok(s) => FromStr::from_str(s).ok(), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) { Some(x) => Ok(x), None => Err(::Error::Header), } } } impl HeaderFormat for CrazyLength { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let CrazyLength(ref opt, ref value) = *self; write!(f, "{:?}, {:?}", opt, value) } } #[test] fn test_different_structs_for_same_header() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); assert_eq!(headers.get::<CrazyLength>(), Some(&CrazyLength(Some(false), 10))); } #[test] fn test_trailing_whitespace() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10 ")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); } #[test] fn test_multiple_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let ContentLength(one) = *headers.get::<ContentLength>().unwrap(); let ContentLength(two) = *headers.get::<ContentLength>().unwrap(); assert_eq!(one, two); } #[test] fn test_different_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10", b"Content-Type: text/plain")).unwrap(); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); let ContentType(_) = *headers.get::<ContentType>().unwrap(); } #[test] fn test_get_mutable() { let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); } #[test] fn test_headers_show() { let mut headers = Headers::new(); headers.set(ContentLength(15)); headers.set(Host { hostname: "foo.bar".to_owned(), port: None }); let s = headers.to_string(); // hashmap's iterators have arbitrary order, so we must sort first let mut pieces = s.split("\r\n").collect::<Vec<&str>>(); pieces.sort(); let s = pieces.into_iter().rev().collect::<Vec<&str>>().connect("\r\n"); assert_eq!(s, "Host: foo.bar\r\nContent-Length: 15\r\n"); } #[test] fn test_headers_show_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let s = headers.to_string(); assert_eq!(s, "Content-Length: 10\r\n"); } #[test] fn test_set_raw() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][..]); assert_eq!(headers.get(), Some(&ContentLength(20))); } #[test] fn test_remove_raw() { let mut headers = Headers::new(); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); headers.remove_raw("content-LENGTH"); assert_eq!(headers.get_raw("Content-length"), None); } #[test] fn test_len() { let mut headers = Headers::new(); headers.set(ContentLength(10)); assert_eq!(headers.len(), 1); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); // Redundant, should not increase count. headers.set(ContentLength(20)); assert_eq!(headers.len(), 2); } #[test] fn test_clear() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); headers.clear(); assert_eq!(headers.len(), 0); } #[test] fn test_iter() { let mut headers = Headers::new(); headers.set(ContentLength(11)); for header in headers.iter() { assert!(header.is::<ContentLength>()); assert_eq!(header.name(), <ContentLength as Header>::header_name()); assert_eq!(header.value(), Some(&ContentLength(11))); assert_eq!(header.value_string(), "11".to_owned()); } } #[cfg(feature = "nightly")] #[bench] fn bench_headers_new(b: &mut Bencher) { b.iter(|| { let mut h = Headers::new(); h.set(ContentLength(11)); h }) } #[cfg(feature = "nightly")] #[bench] fn bench_headers_from_raw(b: &mut Bencher) { let raw = raw!(b"Content-Length: 10");
{ return Err(::Error::Header); }
conditional_block
mod.rs
{ //! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //! ## `Header` and `HeaderFormat` //! //! Consider a Do Not Track header. It can be true or false, but it represents //! that via the numerals `1` and `0`. //! //! ``` //! use std::fmt; //! use hyper::header::{Header, HeaderFormat}; //! //! #[derive(Debug, Clone, Copy)] //! struct Dnt(bool); //! //! impl Header for Dnt { //! fn header_name() -> &'static str { //! "DNT" //! } //! //! fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<Dnt> { //! if raw.len() == 1 { //! let line = &raw[0]; //! if line.len() == 1 { //! let byte = line[0]; //! match byte { //! b'0' => return Ok(Dnt(true)), //! b'1' => return Ok(Dnt(false)), //! _ => () //! } //! } //! } //! Err(hyper::Error::Header) //! } //! } //! //! impl HeaderFormat for Dnt { //! fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { //! if self.0 { //! f.write_str("1") //! } else { //! f.write_str("0") //! } //! } //! } //! ``` use std::any::Any; use std::borrow::{Cow, ToOwned}; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; use std::iter::{FromIterator, IntoIterator}; use std::ops::{Deref, DerefMut}; use std::{mem, fmt}; use {httparse, traitobject}; use typeable::Typeable; use unicase::UniCase; use self::internals::Item; pub use self::shared::*; pub use self::common::*; mod common; mod internals; mod shared; pub mod parsing; type HeaderName = UniCase<CowStr>; /// A trait for any object that will represent a header field and value. /// /// This trait represents the construction and identification of headers, /// and contains trait-object unsafe methods. pub trait Header: Clone + Any + Send + Sync { /// Returns the name of the header field this belongs to. /// /// This will become an associated constant once available. fn header_name() -> &'static str; /// Parse a header from a raw stream of bytes. /// /// It's possible that a request can include a header field more than once, /// and in that case, the slice will have a length greater than 1. However, /// it's not necessarily the case that a Header is *allowed* to have more /// than one field value. If that's the case, you **should** return `None` /// if `raw.len() > 1`. fn parse_header(raw: &[Vec<u8>]) -> ::Result<Self>; } /// A trait for any object that will represent a header field and value. /// /// This trait represents the formatting of a Header for output to a TcpStream. pub trait HeaderFormat: fmt::Debug + HeaderClone + Any + Typeable + Send + Sync { /// Format a header to be output into a TcpStream. /// /// This method is not allowed to introduce an Err not produced /// by the passed-in Formatter. fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result; } #[doc(hidden)] pub trait HeaderClone { fn clone_box(&self) -> Box<HeaderFormat + Send + Sync>; } impl<T: HeaderFormat + Clone> HeaderClone for T { #[inline] fn clone_box(&self) -> Box<HeaderFormat + Send + Sync> { Box::new(self.clone()) } } impl HeaderFormat + Send + Sync { #[inline] unsafe fn downcast_ref_unchecked<T:'static>(&self) -> &T { mem::transmute(traitobject::data(self)) } #[inline] unsafe fn downcast_mut_unchecked<T:'static>(&mut self) -> &mut T { mem::transmute(traitobject::data_mut(self)) } } impl Clone for Box<HeaderFormat + Send + Sync> { #[inline] fn clone(&self) -> Box<HeaderFormat + Send + Sync> { self.clone_box() } } #[inline] fn header_name<T: Header>() -> &'static str { <T as Header>::header_name() } /// A map of header fields on requests and responses. #[derive(Clone)] pub struct Headers { data: HashMap<HeaderName, Item> } impl Headers { /// Creates a new, empty headers map. pub fn new() -> Headers { Headers { data: HashMap::new() } } #[doc(hidden)] pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> ::Result<Headers> { let mut headers = Headers::new(); for header in raw { trace!("raw header: {:?}={:?}", header.name, &header.value[..]); let name = UniCase(CowStr(Cow::Owned(header.name.to_owned()))); let mut item = match headers.data.entry(name) { Entry::Vacant(entry) => entry.insert(Item::new_raw(vec![])), Entry::Occupied(entry) => entry.into_mut() }; let trim = header.value.iter().rev().take_while(|&&x| x == b' ').count(); let value = &header.value[.. header.value.len() - trim]; item.mut_raw().push(value.to_vec()); } Ok(headers) } /// Set a header field to the corresponding value. /// /// The field is determined by the type of the value being set. pub fn set<H: Header + HeaderFormat>(&mut self, value: H) { self.data.insert(UniCase(CowStr(Cow::Borrowed(header_name::<H>()))), Item::new_typed(Box::new(value))); } /// Access the raw value of a header. /// /// Prefer to use the typed getters instead. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// let raw_content_type = headers.get_raw("content-type"); /// ``` pub fn get_raw(&self, name: &str) -> Option<&[Vec<u8>]> { self.data .get(&UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) })))) .map(Item::raw) } /// Set the raw value of a header, bypassing any typed headers. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// headers.set_raw("content-length", vec![b"5".to_vec()]); /// ``` pub fn set_raw<K: Into<Cow<'static, str>>>(&mut self, name: K, value: Vec<Vec<u8>>) { self.data.insert(UniCase(CowStr(name.into())), Item::new_raw(value)); } /// Remove a header set by set_raw pub fn remove_raw(&mut self, name: &str) { self.data.remove( &UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) ); } /// Get a reference to the header field's value, if it exists. pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> { self.data.get(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed::<H>) } /// Get a mutable reference to the header field's value, if it exists. pub fn get_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> { self.data.get_mut(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed_mut::<H>) } /// Returns a boolean of whether a certain header is in the map. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # use hyper::header::ContentType; /// # let mut headers = Headers::new(); /// let has_type = headers.has::<ContentType>(); /// ``` pub fn has<H: Header + HeaderFormat>(&self) -> bool { self.data.contains_key(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))) } /// Removes a header from the map, if one existed. /// Returns true if a header has been removed. pub fn remove<H: Header + HeaderFormat>(&mut self) -> bool { self.data.remove(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).is_some() } /// Returns an iterator over the header fields. pub fn iter<'a>(&'a self) -> HeadersItems<'a> { HeadersItems { inner: self.data.iter() } } /// Returns the number of headers in the map. pub fn len(&self) -> usize { self.data.len() } /// Remove all headers from the map. pub fn clear(&mut self) { self.data.clear() } } impl fmt::Display for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for header in self.iter() { try!(write!(f, "{}\r\n", header)); } Ok(()) } } impl fmt::Debug for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str("Headers { ")); for header in self.iter() { try!(write!(f, "{:?}, ", header)); } try!(f.write_str("}")); Ok(()) } } /// An `Iterator` over the fields in a `Headers` map. pub struct HeadersItems<'a> { inner: Iter<'a, HeaderName, Item> } impl<'a> Iterator for HeadersItems<'a> { type Item = HeaderView<'a>; fn next(&mut self) -> Option<HeaderView<'a>> { self.inner.next().map(|(k, v)| HeaderView(k, v)) } } /// Returned with the `HeadersItems` iterator. pub struct HeaderView<'a>(&'a HeaderName, &'a Item); impl<'a> HeaderView<'a> { /// Check if a HeaderView is a certain Header. #[inline] pub fn is<H: Header>(&self) -> bool { UniCase(CowStr(Cow::Borrowed(header_name::<H>()))) == *self.0 } /// Get the Header name as a slice. #[inline] pub fn name(&self) -> &'a str { self.0.as_ref() }
#[inline] pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> { self.1.typed::<H>() } /// Get just the header value as a String. #[inline] pub fn value_string(&self) -> String { (*self.1).to_string() } } impl<'a> fmt::Display for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {}", self.0, *self.1) } } impl<'a> fmt::Debug for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl<'a> Extend<HeaderView<'a>> for Headers { fn extend<I: IntoIterator<Item=HeaderView<'a>>>(&mut self, iter: I) { for header in iter { self.data.insert((*header.0).clone(), (*header.1).clone()); } } } impl<'a> FromIterator<HeaderView<'a>> for Headers { fn from_iter<I: IntoIterator<Item=HeaderView<'a>>>(iter: I) -> Headers { let mut headers = Headers::new(); headers.extend(iter); headers } } impl<'a> fmt::Display for &'a (HeaderFormat + Send + Sync) { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(f) } } /// A wrapper around any Header with a Display impl that calls fmt_header. /// /// This can be used like so: `format!("{}", HeaderFormatter(&header))` to /// get the representation of a Header which will be written to an /// outgoing TcpStream. pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); impl<'a, H: HeaderFormat> fmt::Display for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } #[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)] struct CowStr(Cow<'static, str>); impl Deref for CowStr { type Target = Cow<'static, str>; fn deref(&self) -> &Cow<'static, str> { &self.0 } } impl fmt::Debug for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl fmt::Display for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl DerefMut for CowStr { fn deref_mut(&mut self) -> &mut Cow<'static, str> { &mut self.0 } } impl AsRef<str> for CowStr { fn as_ref(&self) -> &str { self } } #[cfg(test)] mod tests { use std::fmt; use mime::Mime; use mime::TopLevel::Text; use mime::SubLevel::Plain; use super::{Headers, Header, HeaderFormat, ContentLength, ContentType, Accept, Host, qitem}; use httparse; #[cfg(feature = "nightly")] use test::Bencher; // Slice.position_elem is unstable fn index_of(slice: &[u8], byte: u8) -> Option<usize> { for (index, &b) in slice.iter().enumerate() { if b == byte { return Some(index); } } None } macro_rules! raw { ($($line:expr),*) => ({ [$({ let line = $line; let pos = index_of(line, b':').expect("raw splits on ':', not found"); httparse::Header { name: ::std::str::from_utf8(&line[..pos]).unwrap(), value: &line[pos + 2..] } }),*] }) } #[test] fn test_from_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get(), Some(&ContentLength(10))); } #[test] fn test_content_type() { let content_type = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(content_type.ok(), Some(ContentType(Mime(Text, Plain, vec![])))); } #[test] fn test_accept() { let text_plain = qitem(Mime(Text, Plain, vec![])); let application_vendor = "application/vnd.github.v3.full+json; q=0.5".parse().unwrap(); let accept = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![text_plain.clone()]))); let accept = Header::parse_header([b"application/vnd.github.v3.full+json; q=0.5, text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![application_vendor, text_plain]))); } #[derive(Clone, PartialEq, Debug)] struct CrazyLength(Option<bool>, usize); impl Header for CrazyLength { fn header_name() -> &'static str { "content-length" } fn parse_header(raw: &[Vec<u8>]) -> ::Result<CrazyLength> { use std::str::from_utf8; use std::str::FromStr; if raw.len()!= 1 { return Err(::Error::Header); } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. match match from_utf8(unsafe { &raw.get_unchecked(0)[..] }) { Ok(s) => FromStr::from_str(s).ok(), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) { Some(x) => Ok(x), None => Err(::Error::Header), } } } impl HeaderFormat for CrazyLength { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let CrazyLength(ref opt, ref value) = *self; write!(f, "{:?}, {:?}", opt, value) } } #[test] fn test_different_structs_for_same_header() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); assert_eq!(headers.get::<CrazyLength>(), Some(&CrazyLength(Some(false), 10))); } #[test] fn test_trailing_whitespace() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10 ")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); } #[test] fn test_multiple_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let ContentLength(one) = *headers.get::<ContentLength>().unwrap(); let ContentLength(two) = *headers.get::<ContentLength>().unwrap(); assert_eq!(one, two); } #[test] fn test_different_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10", b"Content-Type: text/plain")).unwrap(); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); let ContentType(_) = *headers.get::<ContentType>().unwrap(); } #[test] fn test_get_mutable() { let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); } #[test] fn test_headers_show() { let mut headers = Headers::new(); headers.set(ContentLength(15)); headers.set(Host { hostname: "foo.bar".to_owned(), port: None }); let s = headers.to_string(); // hashmap's iterators have arbitrary order, so we must sort first let mut pieces = s.split("\r\n").collect::<Vec<&str>>(); pieces.sort(); let s = pieces.into_iter().rev().collect::<Vec<&str>>().connect("\r\n"); assert_eq!(s, "Host: foo.bar\r\nContent-Length: 15\r\n"); } #[test] fn test_headers_show_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let s = headers.to_string(); assert_eq!(s, "Content-Length: 10\r\n"); } #[test] fn test_set_raw() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][..]); assert_eq!(headers.get(), Some(&ContentLength(20))); } #[test] fn test_remove_raw() { let mut headers = Headers::new(); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); headers.remove_raw("content-LENGTH"); assert_eq!(headers.get_raw("Content-length"), None); } #[test] fn test_len() { let mut headers = Headers::new(); headers.set(ContentLength(10)); assert_eq!(headers.len(), 1); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); // Redundant, should not increase count. headers.set(ContentLength(20)); assert_eq!(headers.len(), 2); } #[test] fn test_clear() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); headers.clear(); assert_eq!(headers.len(), 0); } #[test] fn test_iter() { let mut headers = Headers::new(); headers.set(ContentLength(11)); for header in headers.iter() { assert!(header.is::<ContentLength>()); assert_eq!(header.name(), <ContentLength as Header>::header_name()); assert_eq!(header.value(), Some(&ContentLength(11))); assert_eq!(header.value_string(), "11".to_owned()); } } #[cfg(feature = "nightly")] #[bench] fn bench_headers_new(b: &mut Bencher) { b.iter(|| { let mut h = Headers::new(); h.set(ContentLength(11)); h }) } #[cfg(feature = "nightly")] #[bench] fn bench_headers_from_raw(b: &mut Bencher) { let raw = raw!(b"Content-Length: 10");
/// Cast the value to a certain Header type.
random_line_split
mod.rs
//! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //! ## `Header` and `HeaderFormat` //! //! Consider a Do Not Track header. It can be true or false, but it represents //! that via the numerals `1` and `0`. //! //! ``` //! use std::fmt; //! use hyper::header::{Header, HeaderFormat}; //! //! #[derive(Debug, Clone, Copy)] //! struct Dnt(bool); //! //! impl Header for Dnt { //! fn header_name() -> &'static str { //! "DNT" //! } //! //! fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<Dnt> { //! if raw.len() == 1 { //! let line = &raw[0]; //! if line.len() == 1 { //! let byte = line[0]; //! match byte { //! b'0' => return Ok(Dnt(true)), //! b'1' => return Ok(Dnt(false)), //! _ => () //! } //! } //! } //! Err(hyper::Error::Header) //! } //! } //! //! impl HeaderFormat for Dnt { //! fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { //! if self.0 { //! f.write_str("1") //! } else { //! f.write_str("0") //! } //! } //! } //! ``` use std::any::Any; use std::borrow::{Cow, ToOwned}; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; use std::iter::{FromIterator, IntoIterator}; use std::ops::{Deref, DerefMut}; use std::{mem, fmt}; use {httparse, traitobject}; use typeable::Typeable; use unicase::UniCase; use self::internals::Item; pub use self::shared::*; pub use self::common::*; mod common; mod internals; mod shared; pub mod parsing; type HeaderName = UniCase<CowStr>; /// A trait for any object that will represent a header field and value. /// /// This trait represents the construction and identification of headers, /// and contains trait-object unsafe methods. pub trait Header: Clone + Any + Send + Sync { /// Returns the name of the header field this belongs to. /// /// This will become an associated constant once available. fn header_name() -> &'static str; /// Parse a header from a raw stream of bytes. /// /// It's possible that a request can include a header field more than once, /// and in that case, the slice will have a length greater than 1. However, /// it's not necessarily the case that a Header is *allowed* to have more /// than one field value. If that's the case, you **should** return `None` /// if `raw.len() > 1`. fn parse_header(raw: &[Vec<u8>]) -> ::Result<Self>; } /// A trait for any object that will represent a header field and value. /// /// This trait represents the formatting of a Header for output to a TcpStream. pub trait HeaderFormat: fmt::Debug + HeaderClone + Any + Typeable + Send + Sync { /// Format a header to be output into a TcpStream. /// /// This method is not allowed to introduce an Err not produced /// by the passed-in Formatter. fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result; } #[doc(hidden)] pub trait HeaderClone { fn clone_box(&self) -> Box<HeaderFormat + Send + Sync>; } impl<T: HeaderFormat + Clone> HeaderClone for T { #[inline] fn clone_box(&self) -> Box<HeaderFormat + Send + Sync> { Box::new(self.clone()) } } impl HeaderFormat + Send + Sync { #[inline] unsafe fn downcast_ref_unchecked<T:'static>(&self) -> &T { mem::transmute(traitobject::data(self)) } #[inline] unsafe fn downcast_mut_unchecked<T:'static>(&mut self) -> &mut T { mem::transmute(traitobject::data_mut(self)) } } impl Clone for Box<HeaderFormat + Send + Sync> { #[inline] fn clone(&self) -> Box<HeaderFormat + Send + Sync> { self.clone_box() } } #[inline] fn header_name<T: Header>() -> &'static str { <T as Header>::header_name() } /// A map of header fields on requests and responses. #[derive(Clone)] pub struct Headers { data: HashMap<HeaderName, Item> } impl Headers { /// Creates a new, empty headers map. pub fn new() -> Headers { Headers { data: HashMap::new() } } #[doc(hidden)] pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> ::Result<Headers> { let mut headers = Headers::new(); for header in raw { trace!("raw header: {:?}={:?}", header.name, &header.value[..]); let name = UniCase(CowStr(Cow::Owned(header.name.to_owned()))); let mut item = match headers.data.entry(name) { Entry::Vacant(entry) => entry.insert(Item::new_raw(vec![])), Entry::Occupied(entry) => entry.into_mut() }; let trim = header.value.iter().rev().take_while(|&&x| x == b' ').count(); let value = &header.value[.. header.value.len() - trim]; item.mut_raw().push(value.to_vec()); } Ok(headers) } /// Set a header field to the corresponding value. /// /// The field is determined by the type of the value being set. pub fn set<H: Header + HeaderFormat>(&mut self, value: H) { self.data.insert(UniCase(CowStr(Cow::Borrowed(header_name::<H>()))), Item::new_typed(Box::new(value))); } /// Access the raw value of a header. /// /// Prefer to use the typed getters instead. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// let raw_content_type = headers.get_raw("content-type"); /// ``` pub fn get_raw(&self, name: &str) -> Option<&[Vec<u8>]> { self.data .get(&UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) })))) .map(Item::raw) } /// Set the raw value of a header, bypassing any typed headers. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// headers.set_raw("content-length", vec![b"5".to_vec()]); /// ``` pub fn set_raw<K: Into<Cow<'static, str>>>(&mut self, name: K, value: Vec<Vec<u8>>) { self.data.insert(UniCase(CowStr(name.into())), Item::new_raw(value)); } /// Remove a header set by set_raw pub fn remove_raw(&mut self, name: &str) { self.data.remove( &UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) ); } /// Get a reference to the header field's value, if it exists. pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> { self.data.get(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed::<H>) } /// Get a mutable reference to the header field's value, if it exists. pub fn get_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> { self.data.get_mut(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed_mut::<H>) } /// Returns a boolean of whether a certain header is in the map. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # use hyper::header::ContentType; /// # let mut headers = Headers::new(); /// let has_type = headers.has::<ContentType>(); /// ``` pub fn has<H: Header + HeaderFormat>(&self) -> bool { self.data.contains_key(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))) } /// Removes a header from the map, if one existed. /// Returns true if a header has been removed. pub fn remove<H: Header + HeaderFormat>(&mut self) -> bool { self.data.remove(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).is_some() } /// Returns an iterator over the header fields. pub fn iter<'a>(&'a self) -> HeadersItems<'a> { HeadersItems { inner: self.data.iter() } } /// Returns the number of headers in the map. pub fn len(&self) -> usize { self.data.len() } /// Remove all headers from the map. pub fn clear(&mut self) { self.data.clear() } } impl fmt::Display for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for header in self.iter() { try!(write!(f, "{}\r\n", header)); } Ok(()) } } impl fmt::Debug for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str("Headers { ")); for header in self.iter() { try!(write!(f, "{:?}, ", header)); } try!(f.write_str("}")); Ok(()) } } /// An `Iterator` over the fields in a `Headers` map. pub struct HeadersItems<'a> { inner: Iter<'a, HeaderName, Item> } impl<'a> Iterator for HeadersItems<'a> { type Item = HeaderView<'a>; fn next(&mut self) -> Option<HeaderView<'a>> { self.inner.next().map(|(k, v)| HeaderView(k, v)) } } /// Returned with the `HeadersItems` iterator. pub struct HeaderView<'a>(&'a HeaderName, &'a Item); impl<'a> HeaderView<'a> { /// Check if a HeaderView is a certain Header. #[inline] pub fn is<H: Header>(&self) -> bool { UniCase(CowStr(Cow::Borrowed(header_name::<H>()))) == *self.0 } /// Get the Header name as a slice. #[inline] pub fn name(&self) -> &'a str { self.0.as_ref() } /// Cast the value to a certain Header type. #[inline] pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> { self.1.typed::<H>() } /// Get just the header value as a String. #[inline] pub fn value_string(&self) -> String { (*self.1).to_string() } } impl<'a> fmt::Display for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {}", self.0, *self.1) } } impl<'a> fmt::Debug for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl<'a> Extend<HeaderView<'a>> for Headers { fn extend<I: IntoIterator<Item=HeaderView<'a>>>(&mut self, iter: I) { for header in iter { self.data.insert((*header.0).clone(), (*header.1).clone()); } } } impl<'a> FromIterator<HeaderView<'a>> for Headers { fn from_iter<I: IntoIterator<Item=HeaderView<'a>>>(iter: I) -> Headers { let mut headers = Headers::new(); headers.extend(iter); headers } } impl<'a> fmt::Display for &'a (HeaderFormat + Send + Sync) { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(f) } } /// A wrapper around any Header with a Display impl that calls fmt_header. /// /// This can be used like so: `format!("{}", HeaderFormatter(&header))` to /// get the representation of a Header which will be written to an /// outgoing TcpStream. pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); impl<'a, H: HeaderFormat> fmt::Display for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } #[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)] struct CowStr(Cow<'static, str>); impl Deref for CowStr { type Target = Cow<'static, str>; fn deref(&self) -> &Cow<'static, str> { &self.0 } } impl fmt::Debug for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl fmt::Display for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl DerefMut for CowStr { fn deref_mut(&mut self) -> &mut Cow<'static, str> { &mut self.0 } } impl AsRef<str> for CowStr { fn as_ref(&self) -> &str { self } } #[cfg(test)] mod tests { use std::fmt; use mime::Mime; use mime::TopLevel::Text; use mime::SubLevel::Plain; use super::{Headers, Header, HeaderFormat, ContentLength, ContentType, Accept, Host, qitem}; use httparse; #[cfg(feature = "nightly")] use test::Bencher; // Slice.position_elem is unstable fn index_of(slice: &[u8], byte: u8) -> Option<usize> { for (index, &b) in slice.iter().enumerate() { if b == byte { return Some(index); } } None } macro_rules! raw { ($($line:expr),*) => ({ [$({ let line = $line; let pos = index_of(line, b':').expect("raw splits on ':', not found"); httparse::Header { name: ::std::str::from_utf8(&line[..pos]).unwrap(), value: &line[pos + 2..] } }),*] }) } #[test] fn test_from_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get(), Some(&ContentLength(10))); } #[test] fn test_content_type() { let content_type = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(content_type.ok(), Some(ContentType(Mime(Text, Plain, vec![])))); } #[test] fn test_accept() { let text_plain = qitem(Mime(Text, Plain, vec![])); let application_vendor = "application/vnd.github.v3.full+json; q=0.5".parse().unwrap(); let accept = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![text_plain.clone()]))); let accept = Header::parse_header([b"application/vnd.github.v3.full+json; q=0.5, text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![application_vendor, text_plain]))); } #[derive(Clone, PartialEq, Debug)] struct CrazyLength(Option<bool>, usize); impl Header for CrazyLength { fn header_name() -> &'static str { "content-length" } fn parse_header(raw: &[Vec<u8>]) -> ::Result<CrazyLength> { use std::str::from_utf8; use std::str::FromStr; if raw.len()!= 1 { return Err(::Error::Header); } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. match match from_utf8(unsafe { &raw.get_unchecked(0)[..] }) { Ok(s) => FromStr::from_str(s).ok(), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) { Some(x) => Ok(x), None => Err(::Error::Header), } } } impl HeaderFormat for CrazyLength { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let CrazyLength(ref opt, ref value) = *self; write!(f, "{:?}, {:?}", opt, value) } } #[test] fn test_different_structs_for_same_header() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); assert_eq!(headers.get::<CrazyLength>(), Some(&CrazyLength(Some(false), 10))); } #[test] fn test_trailing_whitespace() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10 ")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); } #[test] fn test_multiple_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let ContentLength(one) = *headers.get::<ContentLength>().unwrap(); let ContentLength(two) = *headers.get::<ContentLength>().unwrap(); assert_eq!(one, two); } #[test] fn test_different_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10", b"Content-Type: text/plain")).unwrap(); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); let ContentType(_) = *headers.get::<ContentType>().unwrap(); } #[test] fn test_get_mutable()
#[test] fn test_headers_show() { let mut headers = Headers::new(); headers.set(ContentLength(15)); headers.set(Host { hostname: "foo.bar".to_owned(), port: None }); let s = headers.to_string(); // hashmap's iterators have arbitrary order, so we must sort first let mut pieces = s.split("\r\n").collect::<Vec<&str>>(); pieces.sort(); let s = pieces.into_iter().rev().collect::<Vec<&str>>().connect("\r\n"); assert_eq!(s, "Host: foo.bar\r\nContent-Length: 15\r\n"); } #[test] fn test_headers_show_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let s = headers.to_string(); assert_eq!(s, "Content-Length: 10\r\n"); } #[test] fn test_set_raw() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][..]); assert_eq!(headers.get(), Some(&ContentLength(20))); } #[test] fn test_remove_raw() { let mut headers = Headers::new(); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); headers.remove_raw("content-LENGTH"); assert_eq!(headers.get_raw("Content-length"), None); } #[test] fn test_len() { let mut headers = Headers::new(); headers.set(ContentLength(10)); assert_eq!(headers.len(), 1); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); // Redundant, should not increase count. headers.set(ContentLength(20)); assert_eq!(headers.len(), 2); } #[test] fn test_clear() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); headers.clear(); assert_eq!(headers.len(), 0); } #[test] fn test_iter() { let mut headers = Headers::new(); headers.set(ContentLength(11)); for header in headers.iter() { assert!(header.is::<ContentLength>()); assert_eq!(header.name(), <ContentLength as Header>::header_name()); assert_eq!(header.value(), Some(&ContentLength(11))); assert_eq!(header.value_string(), "11".to_owned()); } } #[cfg(feature = "nightly")] #[bench] fn bench_headers_new(b: &mut Bencher) { b.iter(|| { let mut h = Headers::new(); h.set(ContentLength(11)); h }) } #[cfg(feature = "nightly")] #[bench] fn bench_headers_from_raw(b: &mut Bencher) { let raw = raw!(b"Content-Length: 10");
{ let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); }
identifier_body
mod.rs
{ //! let mut headers = Headers::new(); //! //! headers.set(XRequestGuid("a proper guid".to_owned())) //! } //! ``` //! //! This works well for simple "string" headers. But the header system //! actually involves 2 parts: parsing, and formatting. If you need to //! customize either part, you can do so. //! //! ## `Header` and `HeaderFormat` //! //! Consider a Do Not Track header. It can be true or false, but it represents //! that via the numerals `1` and `0`. //! //! ``` //! use std::fmt; //! use hyper::header::{Header, HeaderFormat}; //! //! #[derive(Debug, Clone, Copy)] //! struct Dnt(bool); //! //! impl Header for Dnt { //! fn header_name() -> &'static str { //! "DNT" //! } //! //! fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<Dnt> { //! if raw.len() == 1 { //! let line = &raw[0]; //! if line.len() == 1 { //! let byte = line[0]; //! match byte { //! b'0' => return Ok(Dnt(true)), //! b'1' => return Ok(Dnt(false)), //! _ => () //! } //! } //! } //! Err(hyper::Error::Header) //! } //! } //! //! impl HeaderFormat for Dnt { //! fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { //! if self.0 { //! f.write_str("1") //! } else { //! f.write_str("0") //! } //! } //! } //! ``` use std::any::Any; use std::borrow::{Cow, ToOwned}; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; use std::iter::{FromIterator, IntoIterator}; use std::ops::{Deref, DerefMut}; use std::{mem, fmt}; use {httparse, traitobject}; use typeable::Typeable; use unicase::UniCase; use self::internals::Item; pub use self::shared::*; pub use self::common::*; mod common; mod internals; mod shared; pub mod parsing; type HeaderName = UniCase<CowStr>; /// A trait for any object that will represent a header field and value. /// /// This trait represents the construction and identification of headers, /// and contains trait-object unsafe methods. pub trait Header: Clone + Any + Send + Sync { /// Returns the name of the header field this belongs to. /// /// This will become an associated constant once available. fn header_name() -> &'static str; /// Parse a header from a raw stream of bytes. /// /// It's possible that a request can include a header field more than once, /// and in that case, the slice will have a length greater than 1. However, /// it's not necessarily the case that a Header is *allowed* to have more /// than one field value. If that's the case, you **should** return `None` /// if `raw.len() > 1`. fn parse_header(raw: &[Vec<u8>]) -> ::Result<Self>; } /// A trait for any object that will represent a header field and value. /// /// This trait represents the formatting of a Header for output to a TcpStream. pub trait HeaderFormat: fmt::Debug + HeaderClone + Any + Typeable + Send + Sync { /// Format a header to be output into a TcpStream. /// /// This method is not allowed to introduce an Err not produced /// by the passed-in Formatter. fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result; } #[doc(hidden)] pub trait HeaderClone { fn clone_box(&self) -> Box<HeaderFormat + Send + Sync>; } impl<T: HeaderFormat + Clone> HeaderClone for T { #[inline] fn clone_box(&self) -> Box<HeaderFormat + Send + Sync> { Box::new(self.clone()) } } impl HeaderFormat + Send + Sync { #[inline] unsafe fn downcast_ref_unchecked<T:'static>(&self) -> &T { mem::transmute(traitobject::data(self)) } #[inline] unsafe fn downcast_mut_unchecked<T:'static>(&mut self) -> &mut T { mem::transmute(traitobject::data_mut(self)) } } impl Clone for Box<HeaderFormat + Send + Sync> { #[inline] fn clone(&self) -> Box<HeaderFormat + Send + Sync> { self.clone_box() } } #[inline] fn header_name<T: Header>() -> &'static str { <T as Header>::header_name() } /// A map of header fields on requests and responses. #[derive(Clone)] pub struct Headers { data: HashMap<HeaderName, Item> } impl Headers { /// Creates a new, empty headers map. pub fn new() -> Headers { Headers { data: HashMap::new() } } #[doc(hidden)] pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> ::Result<Headers> { let mut headers = Headers::new(); for header in raw { trace!("raw header: {:?}={:?}", header.name, &header.value[..]); let name = UniCase(CowStr(Cow::Owned(header.name.to_owned()))); let mut item = match headers.data.entry(name) { Entry::Vacant(entry) => entry.insert(Item::new_raw(vec![])), Entry::Occupied(entry) => entry.into_mut() }; let trim = header.value.iter().rev().take_while(|&&x| x == b' ').count(); let value = &header.value[.. header.value.len() - trim]; item.mut_raw().push(value.to_vec()); } Ok(headers) } /// Set a header field to the corresponding value. /// /// The field is determined by the type of the value being set. pub fn set<H: Header + HeaderFormat>(&mut self, value: H) { self.data.insert(UniCase(CowStr(Cow::Borrowed(header_name::<H>()))), Item::new_typed(Box::new(value))); } /// Access the raw value of a header. /// /// Prefer to use the typed getters instead. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// let raw_content_type = headers.get_raw("content-type"); /// ``` pub fn get_raw(&self, name: &str) -> Option<&[Vec<u8>]> { self.data .get(&UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) })))) .map(Item::raw) } /// Set the raw value of a header, bypassing any typed headers. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// headers.set_raw("content-length", vec![b"5".to_vec()]); /// ``` pub fn set_raw<K: Into<Cow<'static, str>>>(&mut self, name: K, value: Vec<Vec<u8>>) { self.data.insert(UniCase(CowStr(name.into())), Item::new_raw(value)); } /// Remove a header set by set_raw pub fn remove_raw(&mut self, name: &str) { self.data.remove( &UniCase(CowStr(Cow::Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) ); } /// Get a reference to the header field's value, if it exists. pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> { self.data.get(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed::<H>) } /// Get a mutable reference to the header field's value, if it exists. pub fn get_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> { self.data.get_mut(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).and_then(Item::typed_mut::<H>) } /// Returns a boolean of whether a certain header is in the map. /// /// Example: /// /// ``` /// # use hyper::header::Headers; /// # use hyper::header::ContentType; /// # let mut headers = Headers::new(); /// let has_type = headers.has::<ContentType>(); /// ``` pub fn has<H: Header + HeaderFormat>(&self) -> bool { self.data.contains_key(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))) } /// Removes a header from the map, if one existed. /// Returns true if a header has been removed. pub fn remove<H: Header + HeaderFormat>(&mut self) -> bool { self.data.remove(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).is_some() } /// Returns an iterator over the header fields. pub fn iter<'a>(&'a self) -> HeadersItems<'a> { HeadersItems { inner: self.data.iter() } } /// Returns the number of headers in the map. pub fn len(&self) -> usize { self.data.len() } /// Remove all headers from the map. pub fn clear(&mut self) { self.data.clear() } } impl fmt::Display for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for header in self.iter() { try!(write!(f, "{}\r\n", header)); } Ok(()) } } impl fmt::Debug for Headers { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str("Headers { ")); for header in self.iter() { try!(write!(f, "{:?}, ", header)); } try!(f.write_str("}")); Ok(()) } } /// An `Iterator` over the fields in a `Headers` map. pub struct HeadersItems<'a> { inner: Iter<'a, HeaderName, Item> } impl<'a> Iterator for HeadersItems<'a> { type Item = HeaderView<'a>; fn next(&mut self) -> Option<HeaderView<'a>> { self.inner.next().map(|(k, v)| HeaderView(k, v)) } } /// Returned with the `HeadersItems` iterator. pub struct HeaderView<'a>(&'a HeaderName, &'a Item); impl<'a> HeaderView<'a> { /// Check if a HeaderView is a certain Header. #[inline] pub fn is<H: Header>(&self) -> bool { UniCase(CowStr(Cow::Borrowed(header_name::<H>()))) == *self.0 } /// Get the Header name as a slice. #[inline] pub fn name(&self) -> &'a str { self.0.as_ref() } /// Cast the value to a certain Header type. #[inline] pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> { self.1.typed::<H>() } /// Get just the header value as a String. #[inline] pub fn value_string(&self) -> String { (*self.1).to_string() } } impl<'a> fmt::Display for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {}", self.0, *self.1) } } impl<'a> fmt::Debug for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl<'a> Extend<HeaderView<'a>> for Headers { fn extend<I: IntoIterator<Item=HeaderView<'a>>>(&mut self, iter: I) { for header in iter { self.data.insert((*header.0).clone(), (*header.1).clone()); } } } impl<'a> FromIterator<HeaderView<'a>> for Headers { fn from_iter<I: IntoIterator<Item=HeaderView<'a>>>(iter: I) -> Headers { let mut headers = Headers::new(); headers.extend(iter); headers } } impl<'a> fmt::Display for &'a (HeaderFormat + Send + Sync) { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(f) } } /// A wrapper around any Header with a Display impl that calls fmt_header. /// /// This can be used like so: `format!("{}", HeaderFormatter(&header))` to /// get the representation of a Header which will be written to an /// outgoing TcpStream. pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); impl<'a, H: HeaderFormat> fmt::Display for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } #[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)] struct CowStr(Cow<'static, str>); impl Deref for CowStr { type Target = Cow<'static, str>; fn deref(&self) -> &Cow<'static, str> { &self.0 } } impl fmt::Debug for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl fmt::Display for CowStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl DerefMut for CowStr { fn deref_mut(&mut self) -> &mut Cow<'static, str> { &mut self.0 } } impl AsRef<str> for CowStr { fn as_ref(&self) -> &str { self } } #[cfg(test)] mod tests { use std::fmt; use mime::Mime; use mime::TopLevel::Text; use mime::SubLevel::Plain; use super::{Headers, Header, HeaderFormat, ContentLength, ContentType, Accept, Host, qitem}; use httparse; #[cfg(feature = "nightly")] use test::Bencher; // Slice.position_elem is unstable fn index_of(slice: &[u8], byte: u8) -> Option<usize> { for (index, &b) in slice.iter().enumerate() { if b == byte { return Some(index); } } None } macro_rules! raw { ($($line:expr),*) => ({ [$({ let line = $line; let pos = index_of(line, b':').expect("raw splits on ':', not found"); httparse::Header { name: ::std::str::from_utf8(&line[..pos]).unwrap(), value: &line[pos + 2..] } }),*] }) } #[test] fn test_from_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get(), Some(&ContentLength(10))); } #[test] fn test_content_type() { let content_type = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(content_type.ok(), Some(ContentType(Mime(Text, Plain, vec![])))); } #[test] fn test_accept() { let text_plain = qitem(Mime(Text, Plain, vec![])); let application_vendor = "application/vnd.github.v3.full+json; q=0.5".parse().unwrap(); let accept = Header::parse_header([b"text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![text_plain.clone()]))); let accept = Header::parse_header([b"application/vnd.github.v3.full+json; q=0.5, text/plain".to_vec()].as_ref()); assert_eq!(accept.ok(), Some(Accept(vec![application_vendor, text_plain]))); } #[derive(Clone, PartialEq, Debug)] struct CrazyLength(Option<bool>, usize); impl Header for CrazyLength { fn header_name() -> &'static str { "content-length" } fn parse_header(raw: &[Vec<u8>]) -> ::Result<CrazyLength> { use std::str::from_utf8; use std::str::FromStr; if raw.len()!= 1 { return Err(::Error::Header); } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. match match from_utf8(unsafe { &raw.get_unchecked(0)[..] }) { Ok(s) => FromStr::from_str(s).ok(), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) { Some(x) => Ok(x), None => Err(::Error::Header), } } } impl HeaderFormat for CrazyLength { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let CrazyLength(ref opt, ref value) = *self; write!(f, "{:?}, {:?}", opt, value) } } #[test] fn test_different_structs_for_same_header() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); assert_eq!(headers.get::<CrazyLength>(), Some(&CrazyLength(Some(false), 10))); } #[test] fn test_trailing_whitespace() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10 ")).unwrap(); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); } #[test] fn test_multiple_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let ContentLength(one) = *headers.get::<ContentLength>().unwrap(); let ContentLength(two) = *headers.get::<ContentLength>().unwrap(); assert_eq!(one, two); } #[test] fn test_different_reads() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10", b"Content-Type: text/plain")).unwrap(); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); let ContentType(_) = *headers.get::<ContentType>().unwrap(); } #[test] fn
() { let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); } #[test] fn test_headers_show() { let mut headers = Headers::new(); headers.set(ContentLength(15)); headers.set(Host { hostname: "foo.bar".to_owned(), port: None }); let s = headers.to_string(); // hashmap's iterators have arbitrary order, so we must sort first let mut pieces = s.split("\r\n").collect::<Vec<&str>>(); pieces.sort(); let s = pieces.into_iter().rev().collect::<Vec<&str>>().connect("\r\n"); assert_eq!(s, "Host: foo.bar\r\nContent-Length: 15\r\n"); } #[test] fn test_headers_show_raw() { let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); let s = headers.to_string(); assert_eq!(s, "Content-Length: 10\r\n"); } #[test] fn test_set_raw() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][..]); assert_eq!(headers.get(), Some(&ContentLength(20))); } #[test] fn test_remove_raw() { let mut headers = Headers::new(); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); headers.remove_raw("content-LENGTH"); assert_eq!(headers.get_raw("Content-length"), None); } #[test] fn test_len() { let mut headers = Headers::new(); headers.set(ContentLength(10)); assert_eq!(headers.len(), 1); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); // Redundant, should not increase count. headers.set(ContentLength(20)); assert_eq!(headers.len(), 2); } #[test] fn test_clear() { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set(ContentType(Mime(Text, Plain, vec![]))); assert_eq!(headers.len(), 2); headers.clear(); assert_eq!(headers.len(), 0); } #[test] fn test_iter() { let mut headers = Headers::new(); headers.set(ContentLength(11)); for header in headers.iter() { assert!(header.is::<ContentLength>()); assert_eq!(header.name(), <ContentLength as Header>::header_name()); assert_eq!(header.value(), Some(&ContentLength(11))); assert_eq!(header.value_string(), "11".to_owned()); } } #[cfg(feature = "nightly")] #[bench] fn bench_headers_new(b: &mut Bencher) { b.iter(|| { let mut h = Headers::new(); h.set(ContentLength(11)); h }) } #[cfg(feature = "nightly")] #[bench] fn bench_headers_from_raw(b: &mut Bencher) { let raw = raw!(b"Content-Length: 10");
test_get_mutable
identifier_name
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * A type representing values that may be computed concurrently and * operations for working with them. * * # Example * * ```rust * use std::sync::Future; * # fn fib(n: uint) -> uint {42}; * # fn make_a_sandwich() {}; * let mut delayed_fib = Future::spawn(proc() { fib(5000) }); * make_a_sandwich(); * println!("fib(5000) = {}", delayed_fib.get()) * ``` */ #![allow(missing_docs)] use core::prelude::*; use core::mem::replace; use comm::{Receiver, channel}; use task::spawn; /// A type encapsulating the result of a computation which may not be complete pub struct Future<A> { state: FutureState<A>, } enum FutureState<A> { Pending(proc():Send -> A), Evaluating, Forced(A) } /// Methods on the `future` type impl<A:Clone> Future<A> { pub fn get(&mut self) -> A { //! Get the value of the future. (*(self.get_ref())).clone() } } impl<A> Future<A> { /// Gets the value from this future, forcing evaluation. pub fn unwrap(mut self) -> A { self.get_ref(); let state = replace(&mut self.state, Evaluating); match state { Forced(v) => v, _ => panic!( "Logic error." ), } } pub fn get_ref<'a>(&'a mut self) -> &'a A { /*! * Executes the future's closure and then returns a reference * to the result. The reference lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => panic!("Recursive forcing of future!"), Pending(_) => { match replace(&mut self.state, Evaluating) { Forced(_) | Evaluating => panic!("Logic error."), Pending(f) => { self.state = Forced(f()); self.get_ref() } } } } } pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: proc():Send -> A) -> Future<A> { /*! * Create a future from a function. * * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ Future {state: Pending(f)} } } impl<A:Send> Future<A> { pub fn from_receiver(rx: Receiver<A>) -> Future<A> { /*! * Create a future from a port * * The first time that the value is requested the task will block * waiting for the result to be received on the port. */ Future::from_fn(proc() { rx.recv() }) } pub fn spawn(blk: proc():Send -> A) -> Future<A> { /*! * Create a future from a unique closure. * * The closure will be run in a new task and its result used as the * value of the future. */ let (tx, rx) = channel(); spawn(proc() { // Don't panic if the other end has hung up let _ = tx.send_opt(blk()); }); Future::from_receiver(rx) } } #[cfg(test)] mod test { use prelude::*; use sync::Future; use task; use comm::{channel, Sender}; #[test] fn test_from_value() { let mut f = Future::from_value("snail".to_string()); assert_eq!(f.get(), "snail".to_string()); } #[test] fn test_from_receiver() { let (tx, rx) = channel(); tx.send("whale".to_string()); let mut f = Future::from_receiver(rx); assert_eq!(f.get(), "whale".to_string()); } #[test] fn test_from_fn() { let mut f = Future::from_fn(proc() "brail".to_string()); assert_eq!(f.get(), "brail".to_string()); } #[test] fn test_interface_get() { let mut f = Future::from_value("fail".to_string()); assert_eq!(f.get(), "fail".to_string()); } #[test] fn test_interface_unwrap() { let f = Future::from_value("fail".to_string()); assert_eq!(f.unwrap(), "fail".to_string()); } #[test] fn test_get_ref_method() { let mut f = Future::from_value(22i); assert_eq!(*f.get_ref(), 22); } #[test] fn
() { let mut f = Future::spawn(proc() "bale".to_string()); assert_eq!(f.get(), "bale".to_string()); } #[test] #[should_fail] fn test_future_panic() { let mut f = Future::spawn(proc() panic!()); let _x: String = f.get(); } #[test] fn test_sendable_future() { let expected = "schlorf"; let (tx, rx) = channel(); let f = Future::spawn(proc() { expected }); task::spawn(proc() { let mut f = f; tx.send(f.get()); }); assert_eq!(rx.recv(), expected); } #[test] fn test_dropped_future_doesnt_panic() { struct Bomb(Sender<bool>); local_data_key!(LOCAL: Bomb) impl Drop for Bomb { fn drop(&mut self) { let Bomb(ref tx) = *self; tx.send(task::failing()); } } // Spawn a future, but drop it immediately. When we receive the result // later on, we should never view the task as having panicked. let (tx, rx) = channel(); drop(Future::spawn(proc() { LOCAL.replace(Some(Bomb(tx))); })); // Make sure the future didn't panic the task. assert!(!rx.recv()); } }
test_spawn
identifier_name
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * A type representing values that may be computed concurrently and * operations for working with them. * * # Example * * ```rust * use std::sync::Future; * # fn fib(n: uint) -> uint {42}; * # fn make_a_sandwich() {}; * let mut delayed_fib = Future::spawn(proc() { fib(5000) }); * make_a_sandwich(); * println!("fib(5000) = {}", delayed_fib.get()) * ``` */ #![allow(missing_docs)] use core::prelude::*; use core::mem::replace; use comm::{Receiver, channel}; use task::spawn; /// A type encapsulating the result of a computation which may not be complete pub struct Future<A> { state: FutureState<A>, } enum FutureState<A> { Pending(proc():Send -> A), Evaluating, Forced(A) } /// Methods on the `future` type impl<A:Clone> Future<A> { pub fn get(&mut self) -> A { //! Get the value of the future. (*(self.get_ref())).clone() } } impl<A> Future<A> { /// Gets the value from this future, forcing evaluation. pub fn unwrap(mut self) -> A { self.get_ref(); let state = replace(&mut self.state, Evaluating); match state { Forced(v) => v, _ => panic!( "Logic error." ), } } pub fn get_ref<'a>(&'a mut self) -> &'a A { /*! * Executes the future's closure and then returns a reference * to the result. The reference lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => panic!("Recursive forcing of future!"), Pending(_) => { match replace(&mut self.state, Evaluating) { Forced(_) | Evaluating => panic!("Logic error."), Pending(f) => { self.state = Forced(f()); self.get_ref() } } } } } pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: proc():Send -> A) -> Future<A> { /*!
* * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ Future {state: Pending(f)} } } impl<A:Send> Future<A> { pub fn from_receiver(rx: Receiver<A>) -> Future<A> { /*! * Create a future from a port * * The first time that the value is requested the task will block * waiting for the result to be received on the port. */ Future::from_fn(proc() { rx.recv() }) } pub fn spawn(blk: proc():Send -> A) -> Future<A> { /*! * Create a future from a unique closure. * * The closure will be run in a new task and its result used as the * value of the future. */ let (tx, rx) = channel(); spawn(proc() { // Don't panic if the other end has hung up let _ = tx.send_opt(blk()); }); Future::from_receiver(rx) } } #[cfg(test)] mod test { use prelude::*; use sync::Future; use task; use comm::{channel, Sender}; #[test] fn test_from_value() { let mut f = Future::from_value("snail".to_string()); assert_eq!(f.get(), "snail".to_string()); } #[test] fn test_from_receiver() { let (tx, rx) = channel(); tx.send("whale".to_string()); let mut f = Future::from_receiver(rx); assert_eq!(f.get(), "whale".to_string()); } #[test] fn test_from_fn() { let mut f = Future::from_fn(proc() "brail".to_string()); assert_eq!(f.get(), "brail".to_string()); } #[test] fn test_interface_get() { let mut f = Future::from_value("fail".to_string()); assert_eq!(f.get(), "fail".to_string()); } #[test] fn test_interface_unwrap() { let f = Future::from_value("fail".to_string()); assert_eq!(f.unwrap(), "fail".to_string()); } #[test] fn test_get_ref_method() { let mut f = Future::from_value(22i); assert_eq!(*f.get_ref(), 22); } #[test] fn test_spawn() { let mut f = Future::spawn(proc() "bale".to_string()); assert_eq!(f.get(), "bale".to_string()); } #[test] #[should_fail] fn test_future_panic() { let mut f = Future::spawn(proc() panic!()); let _x: String = f.get(); } #[test] fn test_sendable_future() { let expected = "schlorf"; let (tx, rx) = channel(); let f = Future::spawn(proc() { expected }); task::spawn(proc() { let mut f = f; tx.send(f.get()); }); assert_eq!(rx.recv(), expected); } #[test] fn test_dropped_future_doesnt_panic() { struct Bomb(Sender<bool>); local_data_key!(LOCAL: Bomb) impl Drop for Bomb { fn drop(&mut self) { let Bomb(ref tx) = *self; tx.send(task::failing()); } } // Spawn a future, but drop it immediately. When we receive the result // later on, we should never view the task as having panicked. let (tx, rx) = channel(); drop(Future::spawn(proc() { LOCAL.replace(Some(Bomb(tx))); })); // Make sure the future didn't panic the task. assert!(!rx.recv()); } }
* Create a future from a function.
random_line_split
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * A type representing values that may be computed concurrently and * operations for working with them. * * # Example * * ```rust * use std::sync::Future; * # fn fib(n: uint) -> uint {42}; * # fn make_a_sandwich() {}; * let mut delayed_fib = Future::spawn(proc() { fib(5000) }); * make_a_sandwich(); * println!("fib(5000) = {}", delayed_fib.get()) * ``` */ #![allow(missing_docs)] use core::prelude::*; use core::mem::replace; use comm::{Receiver, channel}; use task::spawn; /// A type encapsulating the result of a computation which may not be complete pub struct Future<A> { state: FutureState<A>, } enum FutureState<A> { Pending(proc():Send -> A), Evaluating, Forced(A) } /// Methods on the `future` type impl<A:Clone> Future<A> { pub fn get(&mut self) -> A { //! Get the value of the future. (*(self.get_ref())).clone() } } impl<A> Future<A> { /// Gets the value from this future, forcing evaluation. pub fn unwrap(mut self) -> A { self.get_ref(); let state = replace(&mut self.state, Evaluating); match state { Forced(v) => v, _ => panic!( "Logic error." ), } } pub fn get_ref<'a>(&'a mut self) -> &'a A { /*! * Executes the future's closure and then returns a reference * to the result. The reference lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => panic!("Recursive forcing of future!"), Pending(_) => { match replace(&mut self.state, Evaluating) { Forced(_) | Evaluating => panic!("Logic error."), Pending(f) => { self.state = Forced(f()); self.get_ref() } } } } } pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: proc():Send -> A) -> Future<A> { /*! * Create a future from a function. * * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ Future {state: Pending(f)} } } impl<A:Send> Future<A> { pub fn from_receiver(rx: Receiver<A>) -> Future<A> { /*! * Create a future from a port * * The first time that the value is requested the task will block * waiting for the result to be received on the port. */ Future::from_fn(proc() { rx.recv() }) } pub fn spawn(blk: proc():Send -> A) -> Future<A>
} #[cfg(test)] mod test { use prelude::*; use sync::Future; use task; use comm::{channel, Sender}; #[test] fn test_from_value() { let mut f = Future::from_value("snail".to_string()); assert_eq!(f.get(), "snail".to_string()); } #[test] fn test_from_receiver() { let (tx, rx) = channel(); tx.send("whale".to_string()); let mut f = Future::from_receiver(rx); assert_eq!(f.get(), "whale".to_string()); } #[test] fn test_from_fn() { let mut f = Future::from_fn(proc() "brail".to_string()); assert_eq!(f.get(), "brail".to_string()); } #[test] fn test_interface_get() { let mut f = Future::from_value("fail".to_string()); assert_eq!(f.get(), "fail".to_string()); } #[test] fn test_interface_unwrap() { let f = Future::from_value("fail".to_string()); assert_eq!(f.unwrap(), "fail".to_string()); } #[test] fn test_get_ref_method() { let mut f = Future::from_value(22i); assert_eq!(*f.get_ref(), 22); } #[test] fn test_spawn() { let mut f = Future::spawn(proc() "bale".to_string()); assert_eq!(f.get(), "bale".to_string()); } #[test] #[should_fail] fn test_future_panic() { let mut f = Future::spawn(proc() panic!()); let _x: String = f.get(); } #[test] fn test_sendable_future() { let expected = "schlorf"; let (tx, rx) = channel(); let f = Future::spawn(proc() { expected }); task::spawn(proc() { let mut f = f; tx.send(f.get()); }); assert_eq!(rx.recv(), expected); } #[test] fn test_dropped_future_doesnt_panic() { struct Bomb(Sender<bool>); local_data_key!(LOCAL: Bomb) impl Drop for Bomb { fn drop(&mut self) { let Bomb(ref tx) = *self; tx.send(task::failing()); } } // Spawn a future, but drop it immediately. When we receive the result // later on, we should never view the task as having panicked. let (tx, rx) = channel(); drop(Future::spawn(proc() { LOCAL.replace(Some(Bomb(tx))); })); // Make sure the future didn't panic the task. assert!(!rx.recv()); } }
{ /*! * Create a future from a unique closure. * * The closure will be run in a new task and its result used as the * value of the future. */ let (tx, rx) = channel(); spawn(proc() { // Don't panic if the other end has hung up let _ = tx.send_opt(blk()); }); Future::from_receiver(rx) }
identifier_body
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable 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 // // 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. use std::env; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::PathBuf; use std::str::FromStr; use hcore::fs::find_command; use hcore::package::{PackageIdent, PackageInstall}; use error::{Error, Result}; static LOGKEY: &'static str = "PT"; /// The package identifier for the OS specific interpreter which the Supervisor is built with, /// or which may be independently installed #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_IDENT: &'static str = "core/busybox-static"; #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_COMMAND: &'static str = "busybox"; #[cfg(target_os = "windows")] const INTERPRETER_IDENT: &'static str = "core/powershell"; #[cfg(target_os = "windows")] const INTERPRETER_COMMAND: &'static str = "powershell"; /// Returns a list of path entries, one of which should contain the interpreter binary. /// /// The Supervisor provides a minimal userland of commands to the supervised process. This includes /// binaries such as `chpst` which can be used by a package's `run` hook. /// /// There is a series of fallback strategies used here in order to find a usable interpreter /// installation. The general strategy is the following: /// /// * Are we (the Supervisor) running inside a package? /// * Yes: use the interpreter release describes in our `DEPS` metafile & return its `PATH` /// entries /// * No /// * Can we find any installed interpreter package? /// * Yes: use the latest installed interpreter release & return its `PATH` entries /// * No /// * Is the interpreter binary present on `$PATH`? /// * Yes: return the parent directory which holds the interpreter binary /// * No: out of ideas, so return an error after warning the user we're done /// /// # Errors /// /// * If an installed package should exist, but cannot be loaded /// * If a installed package's path metadata cannot be read or returned /// * If a known-working package identifier string cannot be parsed /// * If the parent directory of a located interpreter binary cannot be computed /// * If the Supervisor is not executing inside a package, and if no interpreter package is /// installed, and if no interpreter binary can be found on the `PATH` pub fn interpreter_paths() -> Result<Vec<PathBuf>> { // First, we'll check if we're running inside a package. If we are, then we should be able to // access the `../DEPS` metadata file and read it to get the specific version of the // interpreter. let my_interpreter_dep_ident = match env::current_exe() { Ok(p) => match p.parent() { Some(p) => {
None } } None => None, }, Err(_) => None, }; let interpreter_paths: Vec<PathBuf> = match my_interpreter_dep_ident { // We've found the specific release that our Supervisor was built with. Get its path // metadata. Some(ident) => { let pkg_install = PackageInstall::load(&ident, None)?; pkg_install.paths()? } // If we're not running out of a package, then see if any package of the interpreter is // installed. None => { let ident = PackageIdent::from_str(INTERPRETER_IDENT)?; match PackageInstall::load(&ident, None) { // We found a version of the interpreter. Get its path metadata. Ok(pkg_install) => pkg_install.paths()?, // Nope, no packages of the interpreter installed. Now we're going to see if the // interpreter command is present on `PATH`. Err(_) => { match find_command(INTERPRETER_COMMAND) { // We found the interpreter on `PATH`, so that its `dirname` and return // that. Some(bin) => match bin.parent() { Some(dir) => vec![dir.to_path_buf()], None => { let path = bin.to_string_lossy().into_owned(); outputln!( "An unexpected error has occurred. {} was \ found at {}, yet the parent directory could not \ be computed. Aborting...", INTERPRETER_COMMAND, &path ); return Err(sup_error!(Error::FileNotFound(path))); } }, // Well, we're not running out of a package, there is no interpreter package // installed, it's not on `PATH`, what more can we do. Time to give up the // chase. Too bad, we were really trying to be helpful here. None => { outputln!( "A interpreter installation is required but could not be \ found. Please install '{}' or put the \ interpreter's command on your $PATH. Aborting...", INTERPRETER_IDENT ); return Err(sup_error!(Error::PackageNotFound(ident))); } } } } } }; Ok(interpreter_paths) } pub fn append_interpreter_and_path(path_entries: &mut Vec<PathBuf>) -> Result<String> { let mut paths = interpreter_paths()?; path_entries.append(&mut paths); if let Some(val) = env::var_os("PATH") { let mut os_paths = env::split_paths(&val).collect(); path_entries.append(&mut os_paths); } let joined = env::join_paths(path_entries)?; let path_str = joined .into_string() .expect("Unable to convert OsStr path to string!"); Ok(path_str) } /// Returns a `PackageIdent` for a interpreter package, assuming it exists in the provided metafile. fn interpreter_dep_from_metafile(metafile: PathBuf) -> Option<PackageIdent> { let f = match File::open(metafile) { Ok(f) => f, Err(_) => return None, }; let reader = BufReader::new(f); for line in reader.lines() { let line = match line { Ok(l) => l, Err(_) => return None, }; if line.contains(INTERPRETER_IDENT) { match PackageIdent::from_str(&line) { Ok(pi) => return Some(pi), Err(_) => return None, } } } None }
let metafile = p.join("DEPS"); if metafile.is_file() { interpreter_dep_from_metafile(metafile) } else {
random_line_split
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable 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 // // 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. use std::env; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::PathBuf; use std::str::FromStr; use hcore::fs::find_command; use hcore::package::{PackageIdent, PackageInstall}; use error::{Error, Result}; static LOGKEY: &'static str = "PT"; /// The package identifier for the OS specific interpreter which the Supervisor is built with, /// or which may be independently installed #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_IDENT: &'static str = "core/busybox-static"; #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_COMMAND: &'static str = "busybox"; #[cfg(target_os = "windows")] const INTERPRETER_IDENT: &'static str = "core/powershell"; #[cfg(target_os = "windows")] const INTERPRETER_COMMAND: &'static str = "powershell"; /// Returns a list of path entries, one of which should contain the interpreter binary. /// /// The Supervisor provides a minimal userland of commands to the supervised process. This includes /// binaries such as `chpst` which can be used by a package's `run` hook. /// /// There is a series of fallback strategies used here in order to find a usable interpreter /// installation. The general strategy is the following: /// /// * Are we (the Supervisor) running inside a package? /// * Yes: use the interpreter release describes in our `DEPS` metafile & return its `PATH` /// entries /// * No /// * Can we find any installed interpreter package? /// * Yes: use the latest installed interpreter release & return its `PATH` entries /// * No /// * Is the interpreter binary present on `$PATH`? /// * Yes: return the parent directory which holds the interpreter binary /// * No: out of ideas, so return an error after warning the user we're done /// /// # Errors /// /// * If an installed package should exist, but cannot be loaded /// * If a installed package's path metadata cannot be read or returned /// * If a known-working package identifier string cannot be parsed /// * If the parent directory of a located interpreter binary cannot be computed /// * If the Supervisor is not executing inside a package, and if no interpreter package is /// installed, and if no interpreter binary can be found on the `PATH` pub fn interpreter_paths() -> Result<Vec<PathBuf>> { // First, we'll check if we're running inside a package. If we are, then we should be able to // access the `../DEPS` metadata file and read it to get the specific version of the // interpreter. let my_interpreter_dep_ident = match env::current_exe() { Ok(p) => match p.parent() { Some(p) => { let metafile = p.join("DEPS"); if metafile.is_file() { interpreter_dep_from_metafile(metafile) } else { None } } None => None, }, Err(_) => None, }; let interpreter_paths: Vec<PathBuf> = match my_interpreter_dep_ident { // We've found the specific release that our Supervisor was built with. Get its path // metadata. Some(ident) => { let pkg_install = PackageInstall::load(&ident, None)?; pkg_install.paths()? } // If we're not running out of a package, then see if any package of the interpreter is // installed. None => { let ident = PackageIdent::from_str(INTERPRETER_IDENT)?; match PackageInstall::load(&ident, None) { // We found a version of the interpreter. Get its path metadata. Ok(pkg_install) => pkg_install.paths()?, // Nope, no packages of the interpreter installed. Now we're going to see if the // interpreter command is present on `PATH`. Err(_) => { match find_command(INTERPRETER_COMMAND) { // We found the interpreter on `PATH`, so that its `dirname` and return // that. Some(bin) => match bin.parent() { Some(dir) => vec![dir.to_path_buf()], None => { let path = bin.to_string_lossy().into_owned(); outputln!( "An unexpected error has occurred. {} was \ found at {}, yet the parent directory could not \ be computed. Aborting...", INTERPRETER_COMMAND, &path ); return Err(sup_error!(Error::FileNotFound(path))); } }, // Well, we're not running out of a package, there is no interpreter package // installed, it's not on `PATH`, what more can we do. Time to give up the // chase. Too bad, we were really trying to be helpful here. None => { outputln!( "A interpreter installation is required but could not be \ found. Please install '{}' or put the \ interpreter's command on your $PATH. Aborting...", INTERPRETER_IDENT ); return Err(sup_error!(Error::PackageNotFound(ident))); } } } } } }; Ok(interpreter_paths) } pub fn append_interpreter_and_path(path_entries: &mut Vec<PathBuf>) -> Result<String> { let mut paths = interpreter_paths()?; path_entries.append(&mut paths); if let Some(val) = env::var_os("PATH") { let mut os_paths = env::split_paths(&val).collect(); path_entries.append(&mut os_paths); } let joined = env::join_paths(path_entries)?; let path_str = joined .into_string() .expect("Unable to convert OsStr path to string!"); Ok(path_str) } /// Returns a `PackageIdent` for a interpreter package, assuming it exists in the provided metafile. fn
(metafile: PathBuf) -> Option<PackageIdent> { let f = match File::open(metafile) { Ok(f) => f, Err(_) => return None, }; let reader = BufReader::new(f); for line in reader.lines() { let line = match line { Ok(l) => l, Err(_) => return None, }; if line.contains(INTERPRETER_IDENT) { match PackageIdent::from_str(&line) { Ok(pi) => return Some(pi), Err(_) => return None, } } } None }
interpreter_dep_from_metafile
identifier_name
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable 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 // // 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. use std::env; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::PathBuf; use std::str::FromStr; use hcore::fs::find_command; use hcore::package::{PackageIdent, PackageInstall}; use error::{Error, Result}; static LOGKEY: &'static str = "PT"; /// The package identifier for the OS specific interpreter which the Supervisor is built with, /// or which may be independently installed #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_IDENT: &'static str = "core/busybox-static"; #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_COMMAND: &'static str = "busybox"; #[cfg(target_os = "windows")] const INTERPRETER_IDENT: &'static str = "core/powershell"; #[cfg(target_os = "windows")] const INTERPRETER_COMMAND: &'static str = "powershell"; /// Returns a list of path entries, one of which should contain the interpreter binary. /// /// The Supervisor provides a minimal userland of commands to the supervised process. This includes /// binaries such as `chpst` which can be used by a package's `run` hook. /// /// There is a series of fallback strategies used here in order to find a usable interpreter /// installation. The general strategy is the following: /// /// * Are we (the Supervisor) running inside a package? /// * Yes: use the interpreter release describes in our `DEPS` metafile & return its `PATH` /// entries /// * No /// * Can we find any installed interpreter package? /// * Yes: use the latest installed interpreter release & return its `PATH` entries /// * No /// * Is the interpreter binary present on `$PATH`? /// * Yes: return the parent directory which holds the interpreter binary /// * No: out of ideas, so return an error after warning the user we're done /// /// # Errors /// /// * If an installed package should exist, but cannot be loaded /// * If a installed package's path metadata cannot be read or returned /// * If a known-working package identifier string cannot be parsed /// * If the parent directory of a located interpreter binary cannot be computed /// * If the Supervisor is not executing inside a package, and if no interpreter package is /// installed, and if no interpreter binary can be found on the `PATH` pub fn interpreter_paths() -> Result<Vec<PathBuf>> { // First, we'll check if we're running inside a package. If we are, then we should be able to // access the `../DEPS` metadata file and read it to get the specific version of the // interpreter. let my_interpreter_dep_ident = match env::current_exe() { Ok(p) => match p.parent() { Some(p) => { let metafile = p.join("DEPS"); if metafile.is_file() { interpreter_dep_from_metafile(metafile) } else { None } } None => None, }, Err(_) => None, }; let interpreter_paths: Vec<PathBuf> = match my_interpreter_dep_ident { // We've found the specific release that our Supervisor was built with. Get its path // metadata. Some(ident) =>
// If we're not running out of a package, then see if any package of the interpreter is // installed. None => { let ident = PackageIdent::from_str(INTERPRETER_IDENT)?; match PackageInstall::load(&ident, None) { // We found a version of the interpreter. Get its path metadata. Ok(pkg_install) => pkg_install.paths()?, // Nope, no packages of the interpreter installed. Now we're going to see if the // interpreter command is present on `PATH`. Err(_) => { match find_command(INTERPRETER_COMMAND) { // We found the interpreter on `PATH`, so that its `dirname` and return // that. Some(bin) => match bin.parent() { Some(dir) => vec![dir.to_path_buf()], None => { let path = bin.to_string_lossy().into_owned(); outputln!( "An unexpected error has occurred. {} was \ found at {}, yet the parent directory could not \ be computed. Aborting...", INTERPRETER_COMMAND, &path ); return Err(sup_error!(Error::FileNotFound(path))); } }, // Well, we're not running out of a package, there is no interpreter package // installed, it's not on `PATH`, what more can we do. Time to give up the // chase. Too bad, we were really trying to be helpful here. None => { outputln!( "A interpreter installation is required but could not be \ found. Please install '{}' or put the \ interpreter's command on your $PATH. Aborting...", INTERPRETER_IDENT ); return Err(sup_error!(Error::PackageNotFound(ident))); } } } } } }; Ok(interpreter_paths) } pub fn append_interpreter_and_path(path_entries: &mut Vec<PathBuf>) -> Result<String> { let mut paths = interpreter_paths()?; path_entries.append(&mut paths); if let Some(val) = env::var_os("PATH") { let mut os_paths = env::split_paths(&val).collect(); path_entries.append(&mut os_paths); } let joined = env::join_paths(path_entries)?; let path_str = joined .into_string() .expect("Unable to convert OsStr path to string!"); Ok(path_str) } /// Returns a `PackageIdent` for a interpreter package, assuming it exists in the provided metafile. fn interpreter_dep_from_metafile(metafile: PathBuf) -> Option<PackageIdent> { let f = match File::open(metafile) { Ok(f) => f, Err(_) => return None, }; let reader = BufReader::new(f); for line in reader.lines() { let line = match line { Ok(l) => l, Err(_) => return None, }; if line.contains(INTERPRETER_IDENT) { match PackageIdent::from_str(&line) { Ok(pi) => return Some(pi), Err(_) => return None, } } } None }
{ let pkg_install = PackageInstall::load(&ident, None)?; pkg_install.paths()? }
conditional_block
path.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable 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 // // 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. use std::env; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::PathBuf; use std::str::FromStr; use hcore::fs::find_command; use hcore::package::{PackageIdent, PackageInstall}; use error::{Error, Result}; static LOGKEY: &'static str = "PT"; /// The package identifier for the OS specific interpreter which the Supervisor is built with, /// or which may be independently installed #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_IDENT: &'static str = "core/busybox-static"; #[cfg(any(target_os = "linux", target_os = "macos"))] const INTERPRETER_COMMAND: &'static str = "busybox"; #[cfg(target_os = "windows")] const INTERPRETER_IDENT: &'static str = "core/powershell"; #[cfg(target_os = "windows")] const INTERPRETER_COMMAND: &'static str = "powershell"; /// Returns a list of path entries, one of which should contain the interpreter binary. /// /// The Supervisor provides a minimal userland of commands to the supervised process. This includes /// binaries such as `chpst` which can be used by a package's `run` hook. /// /// There is a series of fallback strategies used here in order to find a usable interpreter /// installation. The general strategy is the following: /// /// * Are we (the Supervisor) running inside a package? /// * Yes: use the interpreter release describes in our `DEPS` metafile & return its `PATH` /// entries /// * No /// * Can we find any installed interpreter package? /// * Yes: use the latest installed interpreter release & return its `PATH` entries /// * No /// * Is the interpreter binary present on `$PATH`? /// * Yes: return the parent directory which holds the interpreter binary /// * No: out of ideas, so return an error after warning the user we're done /// /// # Errors /// /// * If an installed package should exist, but cannot be loaded /// * If a installed package's path metadata cannot be read or returned /// * If a known-working package identifier string cannot be parsed /// * If the parent directory of a located interpreter binary cannot be computed /// * If the Supervisor is not executing inside a package, and if no interpreter package is /// installed, and if no interpreter binary can be found on the `PATH` pub fn interpreter_paths() -> Result<Vec<PathBuf>> { // First, we'll check if we're running inside a package. If we are, then we should be able to // access the `../DEPS` metadata file and read it to get the specific version of the // interpreter. let my_interpreter_dep_ident = match env::current_exe() { Ok(p) => match p.parent() { Some(p) => { let metafile = p.join("DEPS"); if metafile.is_file() { interpreter_dep_from_metafile(metafile) } else { None } } None => None, }, Err(_) => None, }; let interpreter_paths: Vec<PathBuf> = match my_interpreter_dep_ident { // We've found the specific release that our Supervisor was built with. Get its path // metadata. Some(ident) => { let pkg_install = PackageInstall::load(&ident, None)?; pkg_install.paths()? } // If we're not running out of a package, then see if any package of the interpreter is // installed. None => { let ident = PackageIdent::from_str(INTERPRETER_IDENT)?; match PackageInstall::load(&ident, None) { // We found a version of the interpreter. Get its path metadata. Ok(pkg_install) => pkg_install.paths()?, // Nope, no packages of the interpreter installed. Now we're going to see if the // interpreter command is present on `PATH`. Err(_) => { match find_command(INTERPRETER_COMMAND) { // We found the interpreter on `PATH`, so that its `dirname` and return // that. Some(bin) => match bin.parent() { Some(dir) => vec![dir.to_path_buf()], None => { let path = bin.to_string_lossy().into_owned(); outputln!( "An unexpected error has occurred. {} was \ found at {}, yet the parent directory could not \ be computed. Aborting...", INTERPRETER_COMMAND, &path ); return Err(sup_error!(Error::FileNotFound(path))); } }, // Well, we're not running out of a package, there is no interpreter package // installed, it's not on `PATH`, what more can we do. Time to give up the // chase. Too bad, we were really trying to be helpful here. None => { outputln!( "A interpreter installation is required but could not be \ found. Please install '{}' or put the \ interpreter's command on your $PATH. Aborting...", INTERPRETER_IDENT ); return Err(sup_error!(Error::PackageNotFound(ident))); } } } } } }; Ok(interpreter_paths) } pub fn append_interpreter_and_path(path_entries: &mut Vec<PathBuf>) -> Result<String>
/// Returns a `PackageIdent` for a interpreter package, assuming it exists in the provided metafile. fn interpreter_dep_from_metafile(metafile: PathBuf) -> Option<PackageIdent> { let f = match File::open(metafile) { Ok(f) => f, Err(_) => return None, }; let reader = BufReader::new(f); for line in reader.lines() { let line = match line { Ok(l) => l, Err(_) => return None, }; if line.contains(INTERPRETER_IDENT) { match PackageIdent::from_str(&line) { Ok(pi) => return Some(pi), Err(_) => return None, } } } None }
{ let mut paths = interpreter_paths()?; path_entries.append(&mut paths); if let Some(val) = env::var_os("PATH") { let mut os_paths = env::split_paths(&val).collect(); path_entries.append(&mut os_paths); } let joined = env::join_paths(path_entries)?; let path_str = joined .into_string() .expect("Unable to convert OsStr path to string!"); Ok(path_str) }
identifier_body
trait_objects.rs
trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("String: {}", *self) } } // Static dispatch (No overhead abstraction,'monomorphization,' i.e., rust optimizer creates seperate functions for u8 and String fn do_something(x: &Foo) { x.method(); } /* fn main() { let x = 2u8; let y = "Bonjour".to_string(); println!("This is static dispatch: {:?}", do_something(x)); println!("And so is this: {:?}", do_something(y)); } */ // And now on to dynamic dispatch // Trait objects, e.g., &Foo or Box<Foo>, store a value of any type that implements a given trait, // allowing the actual type to be used at runtime. // They can be used by casting or coercing, e.g., &x as &Foo or using &x as a function with the // parameter &Foo fn main ()
// One cannot use trait objects for things that use Self or have type parameters, e.g., // let this_will_not_work = &v as &Clone // Because it is not "Object safe."
{ let x = 5u8; println!("This uses dynamic dispatch (type casting): {:?}", do_something(&x as &Foo)); println!("And so does this (coercion): {:?}", do_something(&x)); }
identifier_body
trait_objects.rs
trait Foo { fn method(&self) -> String; }
impl Foo for String { fn method(&self) -> String { format!("String: {}", *self) } } // Static dispatch (No overhead abstraction,'monomorphization,' i.e., rust optimizer creates seperate functions for u8 and String fn do_something(x: &Foo) { x.method(); } /* fn main() { let x = 2u8; let y = "Bonjour".to_string(); println!("This is static dispatch: {:?}", do_something(x)); println!("And so is this: {:?}", do_something(y)); } */ // And now on to dynamic dispatch // Trait objects, e.g., &Foo or Box<Foo>, store a value of any type that implements a given trait, // allowing the actual type to be used at runtime. // They can be used by casting or coercing, e.g., &x as &Foo or using &x as a function with the // parameter &Foo fn main () { let x = 5u8; println!("This uses dynamic dispatch (type casting): {:?}", do_something(&x as &Foo)); println!("And so does this (coercion): {:?}", do_something(&x)); } // One cannot use trait objects for things that use Self or have type parameters, e.g., // let this_will_not_work = &v as &Clone // Because it is not "Object safe."
impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
random_line_split
trait_objects.rs
trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn
(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("String: {}", *self) } } // Static dispatch (No overhead abstraction,'monomorphization,' i.e., rust optimizer creates seperate functions for u8 and String fn do_something(x: &Foo) { x.method(); } /* fn main() { let x = 2u8; let y = "Bonjour".to_string(); println!("This is static dispatch: {:?}", do_something(x)); println!("And so is this: {:?}", do_something(y)); } */ // And now on to dynamic dispatch // Trait objects, e.g., &Foo or Box<Foo>, store a value of any type that implements a given trait, // allowing the actual type to be used at runtime. // They can be used by casting or coercing, e.g., &x as &Foo or using &x as a function with the // parameter &Foo fn main () { let x = 5u8; println!("This uses dynamic dispatch (type casting): {:?}", do_something(&x as &Foo)); println!("And so does this (coercion): {:?}", do_something(&x)); } // One cannot use trait objects for things that use Self or have type parameters, e.g., // let this_will_not_work = &v as &Clone // Because it is not "Object safe."
method
identifier_name
mod.rs
use futures::Future; use hyper::service::service_fn_ok; use hyper::{Body, Request, Response}; use hyper::{Client, Server, Uri}; use std::str; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::runtime::Runtime; // Return the received request in the response body for testing purposes. pub fn echo_request(request: Request<Body>) -> Response<Body> { Response::builder() .body(Body::from(format!("{:?}", request))) .unwrap() } // Starts a dummy server in a separate thread. pub fn start_dummy_server( port: u16, response_function: fn(Request<Body>) -> Response<Body>, ) -> Runtime { let address = "127.0.0.1:".to_owned() + &port.to_string(); let addr = address.parse().unwrap(); let new_svc = move || service_fn_ok(response_function); let server = Server::bind(&addr).serve(new_svc).map_err(|_| ()); let mut runtime = Runtime::new().unwrap(); runtime.spawn(server); runtime } // Since it so complicated to make a client request with a Hyper runtime we have // this helper function. #[allow(dead_code)] pub fn client_get(url: Uri) -> Response<Body> { let client = Client::new(); let work = client.get(url).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } #[allow(dead_code)] pub fn client_post(url: Uri, body: &'static str) -> Response<Body> { let client = Client::new(); let req = Request::builder() .method("POST") .uri(url) .body(Body::from(body)) .unwrap(); let work = client.request(req).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } // Since it so complicated to make a client request with a Tokio runtime we have // this helper function. #[allow(dead_code)] pub fn
(request: Request<Body>) -> Response<Body> { let client = Client::new(); let work = client.request(request).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } // Returns a local port number that has not been used yet in parallel test // threads. pub fn get_free_port() -> u16 { static PORT_NR: AtomicUsize = AtomicUsize::new(0); PORT_NR.fetch_add(1, Ordering::SeqCst) as u16 + 9090 }
client_request
identifier_name
mod.rs
use futures::Future; use hyper::service::service_fn_ok; use hyper::{Body, Request, Response}; use hyper::{Client, Server, Uri}; use std::str; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::runtime::Runtime; // Return the received request in the response body for testing purposes. pub fn echo_request(request: Request<Body>) -> Response<Body> { Response::builder() .body(Body::from(format!("{:?}", request))) .unwrap() } // Starts a dummy server in a separate thread. pub fn start_dummy_server( port: u16, response_function: fn(Request<Body>) -> Response<Body>, ) -> Runtime { let address = "127.0.0.1:".to_owned() + &port.to_string(); let addr = address.parse().unwrap(); let new_svc = move || service_fn_ok(response_function); let server = Server::bind(&addr).serve(new_svc).map_err(|_| ()); let mut runtime = Runtime::new().unwrap(); runtime.spawn(server); runtime }
// this helper function. #[allow(dead_code)] pub fn client_get(url: Uri) -> Response<Body> { let client = Client::new(); let work = client.get(url).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } #[allow(dead_code)] pub fn client_post(url: Uri, body: &'static str) -> Response<Body> { let client = Client::new(); let req = Request::builder() .method("POST") .uri(url) .body(Body::from(body)) .unwrap(); let work = client.request(req).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } // Since it so complicated to make a client request with a Tokio runtime we have // this helper function. #[allow(dead_code)] pub fn client_request(request: Request<Body>) -> Response<Body> { let client = Client::new(); let work = client.request(request).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } // Returns a local port number that has not been used yet in parallel test // threads. pub fn get_free_port() -> u16 { static PORT_NR: AtomicUsize = AtomicUsize::new(0); PORT_NR.fetch_add(1, Ordering::SeqCst) as u16 + 9090 }
// Since it so complicated to make a client request with a Hyper runtime we have
random_line_split
mod.rs
use futures::Future; use hyper::service::service_fn_ok; use hyper::{Body, Request, Response}; use hyper::{Client, Server, Uri}; use std::str; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::runtime::Runtime; // Return the received request in the response body for testing purposes. pub fn echo_request(request: Request<Body>) -> Response<Body> { Response::builder() .body(Body::from(format!("{:?}", request))) .unwrap() } // Starts a dummy server in a separate thread. pub fn start_dummy_server( port: u16, response_function: fn(Request<Body>) -> Response<Body>, ) -> Runtime { let address = "127.0.0.1:".to_owned() + &port.to_string(); let addr = address.parse().unwrap(); let new_svc = move || service_fn_ok(response_function); let server = Server::bind(&addr).serve(new_svc).map_err(|_| ()); let mut runtime = Runtime::new().unwrap(); runtime.spawn(server); runtime } // Since it so complicated to make a client request with a Hyper runtime we have // this helper function. #[allow(dead_code)] pub fn client_get(url: Uri) -> Response<Body>
#[allow(dead_code)] pub fn client_post(url: Uri, body: &'static str) -> Response<Body> { let client = Client::new(); let req = Request::builder() .method("POST") .uri(url) .body(Body::from(body)) .unwrap(); let work = client.request(req).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } // Since it so complicated to make a client request with a Tokio runtime we have // this helper function. #[allow(dead_code)] pub fn client_request(request: Request<Body>) -> Response<Body> { let client = Client::new(); let work = client.request(request).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() } // Returns a local port number that has not been used yet in parallel test // threads. pub fn get_free_port() -> u16 { static PORT_NR: AtomicUsize = AtomicUsize::new(0); PORT_NR.fetch_add(1, Ordering::SeqCst) as u16 + 9090 }
{ let client = Client::new(); let work = client.get(url).and_then(Ok); let mut rt = Runtime::new().unwrap(); rt.block_on(work).unwrap() }
identifier_body
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; use boron::router::HttpMethods; static TEST_INIT: Once = ONCE_INIT; struct TestContext { req_client: Client } impl TestContext { fn new() -> TestContext
res.send(b"I was triggered") }); app.listen("0.0.0.0:4040"); }); loop { if ctx.req_client.get("http://0.0.0.0:4040").send().is_ok() { break; } } }); ctx } fn request(&self, url: &str) -> HyperResponse { self.req_client.get(url).send().unwrap() } fn body_from_response(&self, res: &mut HyperResponse) -> String { let mut body = String::new(); let _ = res.read_to_string(&mut body); body } } #[test] fn test_hello_world() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "Hello World!"); } #[test] fn test_some_path() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/path"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "You are at /some/random/path"); } #[test] fn test_res_methods() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/throw/error"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::InternalServerError); assert_eq!(body, "Boom!"); } #[test] fn test_pattern_match() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/pattern"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "I was triggered"); }
{ let ctx = TestContext { req_client: Client::new() }; TEST_INIT.call_once(|| { let _ = thread::spawn(move || { let mut app = Boron::new(); app.get("/", |req: &Request, res: Response| { res.send(b"Hello World!") }); app.get("/some/random/path", |req: &Request, res: Response| { res.send(b"You are at /some/random/path") }); app.get("/throw/error", |req: &Request, mut res: Response| { *res.status_mut() = StatusCode::InternalServerError; let mut started_res = res.start().unwrap(); started_res.write(b"Boom!"); started_res.end() }); app.get(r"/some/[:alpha:]+/pattern", |req: &Request, res: Response| {
identifier_body
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; use boron::router::HttpMethods; static TEST_INIT: Once = ONCE_INIT; struct TestContext { req_client: Client } impl TestContext { fn new() -> TestContext { let ctx = TestContext { req_client: Client::new() }; TEST_INIT.call_once(|| { let _ = thread::spawn(move || { let mut app = Boron::new(); app.get("/", |req: &Request, res: Response| { res.send(b"Hello World!") }); app.get("/some/random/path", |req: &Request, res: Response| { res.send(b"You are at /some/random/path") }); app.get("/throw/error", |req: &Request, mut res: Response| { *res.status_mut() = StatusCode::InternalServerError; let mut started_res = res.start().unwrap(); started_res.write(b"Boom!"); started_res.end() }); app.get(r"/some/[:alpha:]+/pattern", |req: &Request, res: Response| { res.send(b"I was triggered") }); app.listen("0.0.0.0:4040"); }); loop { if ctx.req_client.get("http://0.0.0.0:4040").send().is_ok()
} }); ctx } fn request(&self, url: &str) -> HyperResponse { self.req_client.get(url).send().unwrap() } fn body_from_response(&self, res: &mut HyperResponse) -> String { let mut body = String::new(); let _ = res.read_to_string(&mut body); body } } #[test] fn test_hello_world() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "Hello World!"); } #[test] fn test_some_path() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/path"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "You are at /some/random/path"); } #[test] fn test_res_methods() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/throw/error"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::InternalServerError); assert_eq!(body, "Boom!"); } #[test] fn test_pattern_match() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/pattern"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "I was triggered"); }
{ break; }
conditional_block
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; use boron::router::HttpMethods; static TEST_INIT: Once = ONCE_INIT; struct TestContext { req_client: Client } impl TestContext { fn new() -> TestContext { let ctx = TestContext { req_client: Client::new() }; TEST_INIT.call_once(|| { let _ = thread::spawn(move || { let mut app = Boron::new(); app.get("/", |req: &Request, res: Response| { res.send(b"Hello World!") }); app.get("/some/random/path", |req: &Request, res: Response| { res.send(b"You are at /some/random/path") }); app.get("/throw/error", |req: &Request, mut res: Response| { *res.status_mut() = StatusCode::InternalServerError; let mut started_res = res.start().unwrap(); started_res.write(b"Boom!"); started_res.end() }); app.get(r"/some/[:alpha:]+/pattern", |req: &Request, res: Response| { res.send(b"I was triggered") }); app.listen("0.0.0.0:4040"); }); loop { if ctx.req_client.get("http://0.0.0.0:4040").send().is_ok() { break; } } }); ctx } fn request(&self, url: &str) -> HyperResponse { self.req_client.get(url).send().unwrap() } fn body_from_response(&self, res: &mut HyperResponse) -> String { let mut body = String::new(); let _ = res.read_to_string(&mut body); body } } #[test] fn test_hello_world() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "Hello World!"); } #[test] fn test_some_path() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/path"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "You are at /some/random/path"); } #[test] fn
() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/throw/error"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::InternalServerError); assert_eq!(body, "Boom!"); } #[test] fn test_pattern_match() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/pattern"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "I was triggered"); }
test_res_methods
identifier_name
boron.rs
extern crate hyper; extern crate boron; use std::thread; use std::sync::{Once, ONCE_INIT}; use std::io::{Read, Write}; use hyper::status::StatusCode; use hyper::client::Client; use hyper::client::response::Response as HyperResponse; use boron::server::Boron; use boron::request::Request; use boron::response::Response; use boron::router::HttpMethods; static TEST_INIT: Once = ONCE_INIT; struct TestContext { req_client: Client } impl TestContext { fn new() -> TestContext { let ctx = TestContext { req_client: Client::new() }; TEST_INIT.call_once(|| { let _ = thread::spawn(move || { let mut app = Boron::new(); app.get("/", |req: &Request, res: Response| { res.send(b"Hello World!") }); app.get("/some/random/path", |req: &Request, res: Response| { res.send(b"You are at /some/random/path") }); app.get("/throw/error", |req: &Request, mut res: Response| { *res.status_mut() = StatusCode::InternalServerError; let mut started_res = res.start().unwrap(); started_res.write(b"Boom!"); started_res.end() }); app.get(r"/some/[:alpha:]+/pattern", |req: &Request, res: Response| { res.send(b"I was triggered") }); app.listen("0.0.0.0:4040"); }); loop { if ctx.req_client.get("http://0.0.0.0:4040").send().is_ok() { break; } } }); ctx } fn request(&self, url: &str) -> HyperResponse { self.req_client.get(url).send().unwrap() } fn body_from_response(&self, res: &mut HyperResponse) -> String { let mut body = String::new(); let _ = res.read_to_string(&mut body);
} #[test] fn test_hello_world() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "Hello World!"); } #[test] fn test_some_path() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/path"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "You are at /some/random/path"); } #[test] fn test_res_methods() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/throw/error"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::InternalServerError); assert_eq!(body, "Boom!"); } #[test] fn test_pattern_match() { let ctx = TestContext::new(); let mut res = ctx.request("http://0.0.0.0:4040/some/random/pattern"); let body = ctx.body_from_response(&mut res); assert_eq!(res.status, StatusCode::Ok); assert_eq!(body, "I was triggered"); }
body }
random_line_split
context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use animation::Animation; use app_units::Au; use dom::OpaqueNode; use error_reporting::ParseErrorReporter; use euclid::Size2D; use matching::{ApplicableDeclarationsCache, StyleSharingCandidateCache};
use selector_impl::SelectorImplExt; use selector_matching::Stylist; use std::cell::RefCell; use std::collections::HashMap; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex, RwLock}; pub struct SharedStyleContext<Impl: SelectorImplExt> { /// The current viewport size. pub viewport_size: Size2D<Au>, /// Screen sized changed? pub screen_size_changed: bool, /// The CSS selector stylist. pub stylist: Arc<Stylist<Impl>>, /// Starts at zero, and increased by one every time a layout completes. /// This can be used to easily check for invalid stale data. pub generation: u32, /// A channel on which new animations that have been triggered by style recalculation can be /// sent. pub new_animations_sender: Mutex<Sender<Animation>>, /// Why is this reflow occurring pub goal: ReflowGoal, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter + Sync>, } pub struct LocalStyleContext<C: ComputedValues> { pub applicable_declarations_cache: RefCell<ApplicableDeclarationsCache<C>>, pub style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache<C>>, } pub trait StyleContext<'a, Impl: SelectorImplExt> { fn shared_context(&self) -> &'a SharedStyleContext<Impl>; fn local_context(&self) -> &LocalStyleContext<Impl::ComputedValues>; } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
use properties::ComputedValues;
random_line_split
context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use animation::Animation; use app_units::Au; use dom::OpaqueNode; use error_reporting::ParseErrorReporter; use euclid::Size2D; use matching::{ApplicableDeclarationsCache, StyleSharingCandidateCache}; use properties::ComputedValues; use selector_impl::SelectorImplExt; use selector_matching::Stylist; use std::cell::RefCell; use std::collections::HashMap; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex, RwLock}; pub struct SharedStyleContext<Impl: SelectorImplExt> { /// The current viewport size. pub viewport_size: Size2D<Au>, /// Screen sized changed? pub screen_size_changed: bool, /// The CSS selector stylist. pub stylist: Arc<Stylist<Impl>>, /// Starts at zero, and increased by one every time a layout completes. /// This can be used to easily check for invalid stale data. pub generation: u32, /// A channel on which new animations that have been triggered by style recalculation can be /// sent. pub new_animations_sender: Mutex<Sender<Animation>>, /// Why is this reflow occurring pub goal: ReflowGoal, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter + Sync>, } pub struct
<C: ComputedValues> { pub applicable_declarations_cache: RefCell<ApplicableDeclarationsCache<C>>, pub style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache<C>>, } pub trait StyleContext<'a, Impl: SelectorImplExt> { fn shared_context(&self) -> &'a SharedStyleContext<Impl>; fn local_context(&self) -> &LocalStyleContext<Impl::ComputedValues>; } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
LocalStyleContext
identifier_name
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use super::transform::TryFixedXor; use std::f64; /// Bytewise XOR `ciphertext` with `test_byte`, and then measure the chi-square goodness of fit /// of the resulting output with `language`. pub fn score_byte_decode( test_byte: u8, ciphertext: &[u8], language: &Histogram<char>, ) -> Result<f64, HistogramError> { let bytes = ciphertext .try_fixed_xor(vec![test_byte; ciphertext.len()].as_slice()) .unwrap(); let b_len = bytes.len(); match String::from_utf8(bytes) { Ok(s) => { if s.len()!= b_len { return Err(HistogramError::HistogramMismatch); } // if the resulting string contains a null byte, it's not printable and can be // discarded immediately. if s.contains(|c| c == '\0') { return Ok(f64::MAX); } let s = s .to_lowercase() .chars() .filter(|&c| c.is_alphabetic()) .collect::<String>(); if s.len() == 0 { return Err(HistogramError::HistogramMismatch); } let mut byte_distr: Histogram<char> = s.chars().into(); byte_distr.normalize(); match byte_distr.chisq(language) { Ok(raw_score) =>
Err(e) => Err(e), } } Err(_) => Err(HistogramError::HistogramMismatch), } } }
{ let pct_non_alpha = (b_len - s.len()) as f64 / b_len as f64; Ok(raw_score * pct_non_alpha) }
conditional_block
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use super::transform::TryFixedXor; use std::f64; /// Bytewise XOR `ciphertext` with `test_byte`, and then measure the chi-square goodness of fit /// of the resulting output with `language`. pub fn score_byte_decode( test_byte: u8, ciphertext: &[u8], language: &Histogram<char>, ) -> Result<f64, HistogramError> { let bytes = ciphertext .try_fixed_xor(vec![test_byte; ciphertext.len()].as_slice()) .unwrap(); let b_len = bytes.len(); match String::from_utf8(bytes) { Ok(s) => { if s.len()!= b_len { return Err(HistogramError::HistogramMismatch); } // if the resulting string contains a null byte, it's not printable and can be // discarded immediately. if s.contains(|c| c == '\0') { return Ok(f64::MAX); } let s = s .to_lowercase()
if s.len() == 0 { return Err(HistogramError::HistogramMismatch); } let mut byte_distr: Histogram<char> = s.chars().into(); byte_distr.normalize(); match byte_distr.chisq(language) { Ok(raw_score) => { let pct_non_alpha = (b_len - s.len()) as f64 / b_len as f64; Ok(raw_score * pct_non_alpha) } Err(e) => Err(e), } } Err(_) => Err(HistogramError::HistogramMismatch), } } }
.chars() .filter(|&c| c.is_alphabetic()) .collect::<String>();
random_line_split
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use super::transform::TryFixedXor; use std::f64; /// Bytewise XOR `ciphertext` with `test_byte`, and then measure the chi-square goodness of fit /// of the resulting output with `language`. pub fn score_byte_decode( test_byte: u8, ciphertext: &[u8], language: &Histogram<char>, ) -> Result<f64, HistogramError>
.chars() .filter(|&c| c.is_alphabetic()) .collect::<String>(); if s.len() == 0 { return Err(HistogramError::HistogramMismatch); } let mut byte_distr: Histogram<char> = s.chars().into(); byte_distr.normalize(); match byte_distr.chisq(language) { Ok(raw_score) => { let pct_non_alpha = (b_len - s.len()) as f64 / b_len as f64; Ok(raw_score * pct_non_alpha) } Err(e) => Err(e), } } Err(_) => Err(HistogramError::HistogramMismatch), } } }
{ let bytes = ciphertext .try_fixed_xor(vec![test_byte; ciphertext.len()].as_slice()) .unwrap(); let b_len = bytes.len(); match String::from_utf8(bytes) { Ok(s) => { if s.len() != b_len { return Err(HistogramError::HistogramMismatch); } // if the resulting string contains a null byte, it's not printable and can be // discarded immediately. if s.contains(|c| c == '\0') { return Ok(f64::MAX); } let s = s .to_lowercase()
identifier_body
lib.rs
/// Solutions to the [Cryptopals Challenges](https://cryptopals.com) /// /// Written whilst leading the *A*spiring *R*ustacean *S*ocial *E*ducation group within LinkedIn pub mod encode; pub mod encrypt; pub mod stat; pub mod transform; pub mod xor_cipher { use super::stat::{Histogram, HistogramError}; use super::transform::TryFixedXor; use std::f64; /// Bytewise XOR `ciphertext` with `test_byte`, and then measure the chi-square goodness of fit /// of the resulting output with `language`. pub fn
( test_byte: u8, ciphertext: &[u8], language: &Histogram<char>, ) -> Result<f64, HistogramError> { let bytes = ciphertext .try_fixed_xor(vec![test_byte; ciphertext.len()].as_slice()) .unwrap(); let b_len = bytes.len(); match String::from_utf8(bytes) { Ok(s) => { if s.len()!= b_len { return Err(HistogramError::HistogramMismatch); } // if the resulting string contains a null byte, it's not printable and can be // discarded immediately. if s.contains(|c| c == '\0') { return Ok(f64::MAX); } let s = s .to_lowercase() .chars() .filter(|&c| c.is_alphabetic()) .collect::<String>(); if s.len() == 0 { return Err(HistogramError::HistogramMismatch); } let mut byte_distr: Histogram<char> = s.chars().into(); byte_distr.normalize(); match byte_distr.chisq(language) { Ok(raw_score) => { let pct_non_alpha = (b_len - s.len()) as f64 / b_len as f64; Ok(raw_score * pct_non_alpha) } Err(e) => Err(e), } } Err(_) => Err(HistogramError::HistogramMismatch), } } }
score_byte_decode
identifier_name
mod.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Spec deserialization. pub mod account; pub mod builtin; pub mod genesis;
pub mod params; pub mod spec; pub mod seal; pub mod engine; pub mod state; pub mod ethash; pub mod validator_set; pub mod basic_authority; pub mod authority_round; pub mod tendermint; pub mod null_engine; pub use self::account::Account; pub use self::builtin::{Builtin, Pricing, Linear}; pub use self::genesis::Genesis; pub use self::params::Params; pub use self::spec::Spec; pub use self::seal::{Seal, Ethereum, AuthorityRoundSeal, TendermintSeal}; pub use self::engine::Engine; pub use self::state::State; pub use self::ethash::{Ethash, EthashParams}; pub use self::validator_set::ValidatorSet; pub use self::basic_authority::{BasicAuthority, BasicAuthorityParams}; pub use self::authority_round::{AuthorityRound, AuthorityRoundParams}; pub use self::tendermint::{Tendermint, TendermintParams}; pub use self::null_engine::{NullEngine, NullEngineParams};
random_line_split
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Dictionaries of key-value pairs. use base::{Boolean, CFAllocatorRef, CFIndex, CFIndexConvertible, CFRelease, CFType, CFTypeID}; use base::{CFTypeRef, TCFType, kCFAllocatorDefault}; use std::cast; use std::libc::c_void; use std::ptr; use std::vec; pub type CFDictionaryApplierFunction = *u8; pub type CFDictionaryCopyDescriptionCallBack = *u8; pub type CFDictionaryEqualCallBack = *u8; pub type CFDictionaryHashCallBack = *u8; pub type CFDictionaryReleaseCallBack = *u8; pub type CFDictionaryRetainCallBack = *u8; pub struct CFDictionaryKeyCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack, hash: CFDictionaryHashCallBack } pub struct CFDictionaryValueCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack } struct __CFDictionary; pub type CFDictionaryRef = *__CFDictionary; /// An immutable dictionary of key-value pairs. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFDictionary { priv obj: CFDictionaryRef, } impl Drop for CFDictionary { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) } } } impl TCFType<CFDictionaryRef> for CFDictionary { fn as_concrete_TypeRef(&self) -> CFDictionaryRef { self.obj } unsafe fn
(obj: CFDictionaryRef) -> CFDictionary { CFDictionary { obj: obj, } } #[inline] fn type_id(_: Option<CFDictionary>) -> CFTypeID { unsafe { CFDictionaryGetTypeID() } } } impl CFDictionary { pub fn from_CFType_pairs(pairs: &[(CFType, CFType)]) -> CFDictionary { let (keys, values) = vec::unzip(pairs.iter() .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef()))); unsafe { let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, cast::transmute(keys.as_ptr()), cast::transmute(values.as_ptr()), keys.len().to_CFIndex(), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); TCFType::wrap_under_create_rule(dictionary_ref) } } #[inline] pub fn len(&self) -> uint { unsafe { CFDictionaryGetCount(self.obj) as uint } } #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline] pub fn contains_key(&self, key: *c_void) -> bool { unsafe { CFDictionaryContainsKey(self.obj, key)!= 0 } } #[inline] pub fn find(&self, key: *c_void) -> Option<*c_void> { unsafe { let mut value: *c_void = ptr::null(); if CFDictionaryGetValueIfPresent(self.obj, key, &mut value)!= 0 { Some(value) } else { None } } } #[inline] pub fn get(&self, key: *c_void) -> *c_void { let value = self.find(key); if value.is_none() { fail!("No entry found for key: {:?}", key); } value.unwrap() } /// A convenience function to retrieve `CFType` instances. #[inline] pub unsafe fn get_CFType(&self, key: *c_void) -> CFType { let value: CFTypeRef = cast::transmute(self.get(key)); TCFType::wrap_under_get_rule(value) } } #[link(name = "CoreFoundation", kind = "framework")] extern { /* * CFDictionary.h */ static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks; static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *c_void) -> Boolean; fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: **c_void, values: **c_void, numValues: CFIndex, keyCallBacks: *CFDictionaryKeyCallBacks, valueCallBacks: *CFDictionaryValueCallBacks) -> CFDictionaryRef; fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; fn CFDictionaryGetTypeID() -> CFTypeID; fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *c_void, value: *mut *c_void) -> Boolean; }
wrap_under_create_rule
identifier_name
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Dictionaries of key-value pairs. use base::{Boolean, CFAllocatorRef, CFIndex, CFIndexConvertible, CFRelease, CFType, CFTypeID}; use base::{CFTypeRef, TCFType, kCFAllocatorDefault}; use std::cast; use std::libc::c_void; use std::ptr; use std::vec; pub type CFDictionaryApplierFunction = *u8; pub type CFDictionaryCopyDescriptionCallBack = *u8; pub type CFDictionaryEqualCallBack = *u8; pub type CFDictionaryHashCallBack = *u8; pub type CFDictionaryReleaseCallBack = *u8; pub type CFDictionaryRetainCallBack = *u8; pub struct CFDictionaryKeyCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack, hash: CFDictionaryHashCallBack } pub struct CFDictionaryValueCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack }
/// An immutable dictionary of key-value pairs. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFDictionary { priv obj: CFDictionaryRef, } impl Drop for CFDictionary { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) } } } impl TCFType<CFDictionaryRef> for CFDictionary { fn as_concrete_TypeRef(&self) -> CFDictionaryRef { self.obj } unsafe fn wrap_under_create_rule(obj: CFDictionaryRef) -> CFDictionary { CFDictionary { obj: obj, } } #[inline] fn type_id(_: Option<CFDictionary>) -> CFTypeID { unsafe { CFDictionaryGetTypeID() } } } impl CFDictionary { pub fn from_CFType_pairs(pairs: &[(CFType, CFType)]) -> CFDictionary { let (keys, values) = vec::unzip(pairs.iter() .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef()))); unsafe { let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, cast::transmute(keys.as_ptr()), cast::transmute(values.as_ptr()), keys.len().to_CFIndex(), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); TCFType::wrap_under_create_rule(dictionary_ref) } } #[inline] pub fn len(&self) -> uint { unsafe { CFDictionaryGetCount(self.obj) as uint } } #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline] pub fn contains_key(&self, key: *c_void) -> bool { unsafe { CFDictionaryContainsKey(self.obj, key)!= 0 } } #[inline] pub fn find(&self, key: *c_void) -> Option<*c_void> { unsafe { let mut value: *c_void = ptr::null(); if CFDictionaryGetValueIfPresent(self.obj, key, &mut value)!= 0 { Some(value) } else { None } } } #[inline] pub fn get(&self, key: *c_void) -> *c_void { let value = self.find(key); if value.is_none() { fail!("No entry found for key: {:?}", key); } value.unwrap() } /// A convenience function to retrieve `CFType` instances. #[inline] pub unsafe fn get_CFType(&self, key: *c_void) -> CFType { let value: CFTypeRef = cast::transmute(self.get(key)); TCFType::wrap_under_get_rule(value) } } #[link(name = "CoreFoundation", kind = "framework")] extern { /* * CFDictionary.h */ static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks; static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *c_void) -> Boolean; fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: **c_void, values: **c_void, numValues: CFIndex, keyCallBacks: *CFDictionaryKeyCallBacks, valueCallBacks: *CFDictionaryValueCallBacks) -> CFDictionaryRef; fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; fn CFDictionaryGetTypeID() -> CFTypeID; fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *c_void, value: *mut *c_void) -> Boolean; }
struct __CFDictionary; pub type CFDictionaryRef = *__CFDictionary;
random_line_split
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Dictionaries of key-value pairs. use base::{Boolean, CFAllocatorRef, CFIndex, CFIndexConvertible, CFRelease, CFType, CFTypeID}; use base::{CFTypeRef, TCFType, kCFAllocatorDefault}; use std::cast; use std::libc::c_void; use std::ptr; use std::vec; pub type CFDictionaryApplierFunction = *u8; pub type CFDictionaryCopyDescriptionCallBack = *u8; pub type CFDictionaryEqualCallBack = *u8; pub type CFDictionaryHashCallBack = *u8; pub type CFDictionaryReleaseCallBack = *u8; pub type CFDictionaryRetainCallBack = *u8; pub struct CFDictionaryKeyCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack, hash: CFDictionaryHashCallBack } pub struct CFDictionaryValueCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack } struct __CFDictionary; pub type CFDictionaryRef = *__CFDictionary; /// An immutable dictionary of key-value pairs. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFDictionary { priv obj: CFDictionaryRef, } impl Drop for CFDictionary { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) } } } impl TCFType<CFDictionaryRef> for CFDictionary { fn as_concrete_TypeRef(&self) -> CFDictionaryRef { self.obj } unsafe fn wrap_under_create_rule(obj: CFDictionaryRef) -> CFDictionary { CFDictionary { obj: obj, } } #[inline] fn type_id(_: Option<CFDictionary>) -> CFTypeID { unsafe { CFDictionaryGetTypeID() } } } impl CFDictionary { pub fn from_CFType_pairs(pairs: &[(CFType, CFType)]) -> CFDictionary { let (keys, values) = vec::unzip(pairs.iter() .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef()))); unsafe { let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, cast::transmute(keys.as_ptr()), cast::transmute(values.as_ptr()), keys.len().to_CFIndex(), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); TCFType::wrap_under_create_rule(dictionary_ref) } } #[inline] pub fn len(&self) -> uint { unsafe { CFDictionaryGetCount(self.obj) as uint } } #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline] pub fn contains_key(&self, key: *c_void) -> bool { unsafe { CFDictionaryContainsKey(self.obj, key)!= 0 } } #[inline] pub fn find(&self, key: *c_void) -> Option<*c_void> { unsafe { let mut value: *c_void = ptr::null(); if CFDictionaryGetValueIfPresent(self.obj, key, &mut value)!= 0
else { None } } } #[inline] pub fn get(&self, key: *c_void) -> *c_void { let value = self.find(key); if value.is_none() { fail!("No entry found for key: {:?}", key); } value.unwrap() } /// A convenience function to retrieve `CFType` instances. #[inline] pub unsafe fn get_CFType(&self, key: *c_void) -> CFType { let value: CFTypeRef = cast::transmute(self.get(key)); TCFType::wrap_under_get_rule(value) } } #[link(name = "CoreFoundation", kind = "framework")] extern { /* * CFDictionary.h */ static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks; static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *c_void) -> Boolean; fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: **c_void, values: **c_void, numValues: CFIndex, keyCallBacks: *CFDictionaryKeyCallBacks, valueCallBacks: *CFDictionaryValueCallBacks) -> CFDictionaryRef; fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; fn CFDictionaryGetTypeID() -> CFTypeID; fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *c_void, value: *mut *c_void) -> Boolean; }
{ Some(value) }
conditional_block
dictionary.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Dictionaries of key-value pairs. use base::{Boolean, CFAllocatorRef, CFIndex, CFIndexConvertible, CFRelease, CFType, CFTypeID}; use base::{CFTypeRef, TCFType, kCFAllocatorDefault}; use std::cast; use std::libc::c_void; use std::ptr; use std::vec; pub type CFDictionaryApplierFunction = *u8; pub type CFDictionaryCopyDescriptionCallBack = *u8; pub type CFDictionaryEqualCallBack = *u8; pub type CFDictionaryHashCallBack = *u8; pub type CFDictionaryReleaseCallBack = *u8; pub type CFDictionaryRetainCallBack = *u8; pub struct CFDictionaryKeyCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack, hash: CFDictionaryHashCallBack } pub struct CFDictionaryValueCallBacks { version: CFIndex, retain: CFDictionaryRetainCallBack, release: CFDictionaryReleaseCallBack, copyDescription: CFDictionaryCopyDescriptionCallBack, equal: CFDictionaryEqualCallBack } struct __CFDictionary; pub type CFDictionaryRef = *__CFDictionary; /// An immutable dictionary of key-value pairs. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. pub struct CFDictionary { priv obj: CFDictionaryRef, } impl Drop for CFDictionary { fn drop(&mut self)
} impl TCFType<CFDictionaryRef> for CFDictionary { fn as_concrete_TypeRef(&self) -> CFDictionaryRef { self.obj } unsafe fn wrap_under_create_rule(obj: CFDictionaryRef) -> CFDictionary { CFDictionary { obj: obj, } } #[inline] fn type_id(_: Option<CFDictionary>) -> CFTypeID { unsafe { CFDictionaryGetTypeID() } } } impl CFDictionary { pub fn from_CFType_pairs(pairs: &[(CFType, CFType)]) -> CFDictionary { let (keys, values) = vec::unzip(pairs.iter() .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef()))); unsafe { let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, cast::transmute(keys.as_ptr()), cast::transmute(values.as_ptr()), keys.len().to_CFIndex(), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); TCFType::wrap_under_create_rule(dictionary_ref) } } #[inline] pub fn len(&self) -> uint { unsafe { CFDictionaryGetCount(self.obj) as uint } } #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline] pub fn contains_key(&self, key: *c_void) -> bool { unsafe { CFDictionaryContainsKey(self.obj, key)!= 0 } } #[inline] pub fn find(&self, key: *c_void) -> Option<*c_void> { unsafe { let mut value: *c_void = ptr::null(); if CFDictionaryGetValueIfPresent(self.obj, key, &mut value)!= 0 { Some(value) } else { None } } } #[inline] pub fn get(&self, key: *c_void) -> *c_void { let value = self.find(key); if value.is_none() { fail!("No entry found for key: {:?}", key); } value.unwrap() } /// A convenience function to retrieve `CFType` instances. #[inline] pub unsafe fn get_CFType(&self, key: *c_void) -> CFType { let value: CFTypeRef = cast::transmute(self.get(key)); TCFType::wrap_under_get_rule(value) } } #[link(name = "CoreFoundation", kind = "framework")] extern { /* * CFDictionary.h */ static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks; static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *c_void) -> Boolean; fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: **c_void, values: **c_void, numValues: CFIndex, keyCallBacks: *CFDictionaryKeyCallBacks, valueCallBacks: *CFDictionaryValueCallBacks) -> CFDictionaryRef; fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; fn CFDictionaryGetTypeID() -> CFTypeID; fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *c_void, value: *mut *c_void) -> Boolean; }
{ unsafe { CFRelease(self.as_CFTypeRef()) } }
identifier_body
associated-types-sugar-path.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 paths to associated types using the type-parameter-only sugar. // pretty-expanded FIXME #23616 pub trait Foo { type A; fn boo(&self) -> Self::A; } impl Foo for isize { type A = usize; fn boo(&self) -> usize { 5 } } // Using a type via a function. pub fn bar<T: Foo>(a: T, x: T::A) -> T::A { let _: T::A = a.boo(); x } // Using a type via an impl. trait C { fn f(); fn g(&self) { } } struct B<X>(X); impl<T: Foo> C for B<T> { fn f() { let x: T::A = panic!(); } } pub fn
() { let z: usize = bar(2, 4); }
main
identifier_name
associated-types-sugar-path.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 paths to associated types using the type-parameter-only sugar. // pretty-expanded FIXME #23616 pub trait Foo { type A; fn boo(&self) -> Self::A; } impl Foo for isize { type A = usize; fn boo(&self) -> usize { 5 } } // Using a type via a function. pub fn bar<T: Foo>(a: T, x: T::A) -> T::A { let _: T::A = a.boo(); x } // Using a type via an impl. trait C { fn f(); fn g(&self) { } } struct B<X>(X); impl<T: Foo> C for B<T> { fn f() {
} pub fn main() { let z: usize = bar(2, 4); }
let x: T::A = panic!(); }
random_line_split
associated-types-sugar-path.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 paths to associated types using the type-parameter-only sugar. // pretty-expanded FIXME #23616 pub trait Foo { type A; fn boo(&self) -> Self::A; } impl Foo for isize { type A = usize; fn boo(&self) -> usize
} // Using a type via a function. pub fn bar<T: Foo>(a: T, x: T::A) -> T::A { let _: T::A = a.boo(); x } // Using a type via an impl. trait C { fn f(); fn g(&self) { } } struct B<X>(X); impl<T: Foo> C for B<T> { fn f() { let x: T::A = panic!(); } } pub fn main() { let z: usize = bar(2, 4); }
{ 5 }
identifier_body
coord_transform.rs
use crate::coordinates::{ConversionTo, CoordinateSystem, Point}; use crate::tensors::Vector; use crate::typenum::consts::U3; use generic_array::arr; struct Cartesian; struct Spherical; impl CoordinateSystem for Cartesian { type Dimension = U3; } impl CoordinateSystem for Spherical { type Dimension = U3; } impl ConversionTo<Spherical> for Cartesian { fn convert_point(p: &Point<Cartesian>) -> Point<Spherical> { let r = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt(); let theta = (p[2] / r).acos(); let phi = p[1].atan2(p[0]); Point::new(arr![f64; r, theta, phi]) } } #[test] fn test_vector_to_spherical() { let p = Point::new(arr![f64; 0.0, 1.0, 1.0]);
assert!((v2[1] + 0.5).abs() < 0.00001); assert_eq!(v2[2], 0.0); }
let v = Vector::<Cartesian>::new(p, arr![f64; 0.0, 0.0, 1.0]); let v2: Vector<Spherical> = v.convert(); assert!((v2[0] - 0.5_f64.sqrt()).abs() < 0.00001);
random_line_split
coord_transform.rs
use crate::coordinates::{ConversionTo, CoordinateSystem, Point}; use crate::tensors::Vector; use crate::typenum::consts::U3; use generic_array::arr; struct Cartesian; struct
; impl CoordinateSystem for Cartesian { type Dimension = U3; } impl CoordinateSystem for Spherical { type Dimension = U3; } impl ConversionTo<Spherical> for Cartesian { fn convert_point(p: &Point<Cartesian>) -> Point<Spherical> { let r = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt(); let theta = (p[2] / r).acos(); let phi = p[1].atan2(p[0]); Point::new(arr![f64; r, theta, phi]) } } #[test] fn test_vector_to_spherical() { let p = Point::new(arr![f64; 0.0, 1.0, 1.0]); let v = Vector::<Cartesian>::new(p, arr![f64; 0.0, 0.0, 1.0]); let v2: Vector<Spherical> = v.convert(); assert!((v2[0] - 0.5_f64.sqrt()).abs() < 0.00001); assert!((v2[1] + 0.5).abs() < 0.00001); assert_eq!(v2[2], 0.0); }
Spherical
identifier_name
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. use rust; use rust::Token as rtok; use rust::{TokenAndSpan, Span, token_to_string}; use compiler::*; use std::collections::hash_map::HashMap; pub struct Quasiquote<'a, 'b:'a, 'c, C> where C: 'c { cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>, current_idx: usize, unquoted_tokens: Vec<TokenAndSpan> } impl<'a, 'b, 'c, C> Quasiquote<'a, 'b, 'c, C> where C: 'c + Compiler { pub fn compile(cx: &'a rust::ExtCtxt<'b>, tokens: Vec<TokenAndSpan>, compiler: &'c mut C) -> Vec<TokenAndSpan> { let mut quasiquote = Quasiquote::new(cx, compiler, tokens); quasiquote.unquote_all(); quasiquote.unquoted_tokens } fn new(cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>) -> Quasiquote<'a, 'b, 'c, C> { Quasiquote { cx: cx, compiler: compiler, tokens: tokens, current_idx: 0, unquoted_tokens: vec![] } } fn unquote_all(&mut self) { while!self.at_end() { match self.peek_unquote() { None => { let tok = self.token(); self.unquoted_tokens.push(tok); } Some(d) => { self.unquote(d); } } self.bump(1); } } fn bump(&mut self, n: usize) { self.current_idx = self.current_idx + n; } fn at_end(&self) -> bool { self.current_idx >= self.tokens.len() } fn token(&self) -> TokenAndSpan { self.tokens[self.current_idx].clone() } fn peek_unquote(&self) -> Option<rust::DelimToken> { if self.current_idx + 1 < self.tokens.len() && self.tokens[self.current_idx].tok == rtok::Pound
else { None } } fn unquote(&mut self, delim: rust::DelimToken) { let pound_idx = self.current_idx; let mut opened_delims = 1isize; self.bump(2); while!self.at_end() && self.still_in_quote(delim, opened_delims) { opened_delims = opened_delims + self.count_delim(delim); self.bump(1); } if self.at_end() || opened_delims!= 1 { self.cx.span_fatal(self.tokens[pound_idx + 1].sp, "unclosed delimiter of anynomous macro."); } let unquote = self.make_unquote(pound_idx); self.compile_unquote(delim, unquote); } fn still_in_quote(&self, delim: rust::DelimToken, opened_delims: isize) -> bool { opened_delims!= 1 || self.token().tok!= rtok::CloseDelim(delim) } fn count_delim(&self, delim: rust::DelimToken) -> isize { match self.token().tok { rtok::CloseDelim(d) if d == delim => -1, rtok::OpenDelim(d) if d == delim => 1, _ => 0 } } fn compile_unquote(&mut self, delim: rust::DelimToken, unquote: Unquote) { let span = unquote.span; let non_terminal = match delim { rust::DelimToken::Paren => { rust::Nonterminal::NtExpr(self.compiler.compile_expr(unquote)) } rust::DelimToken::Brace => { rust::Nonterminal::NtBlock(self.compiler.compile_block(unquote)) } d => panic!("compile_unquote: unrecognized delimiter {:?}", d) }; let interpolated_tok = rtok::Interpolated(non_terminal); let unquoted_tok = TokenAndSpan { tok: interpolated_tok, sp: span }; self.unquoted_tokens.push(unquoted_tok); } fn make_unquote(&self, start_idx: usize) -> Unquote { let mut code = String::new(); let mut text_to_ident = HashMap::new(); for idx in (start_idx+2)..self.current_idx { if let rtok::Ident(id) = self.tokens[idx].tok { text_to_ident.insert(format!("{}", id), id); } code.extend(token_to_string(&self.tokens[idx].tok).chars()); code.push(' '); } Unquote { text_to_ident: text_to_ident, code: code, span: self.span_from(start_idx) } } fn span_from(&self, start_idx: usize) -> Span { let mut span = self.tokens[start_idx].sp; span.hi = self.token().sp.hi; span } }
{ match self.tokens[self.current_idx + 1].tok { rtok::OpenDelim(d@rust::DelimToken::Paren) | rtok::OpenDelim(d@rust::DelimToken::Brace) => Some(d), _ => None } }
conditional_block
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. use rust; use rust::Token as rtok; use rust::{TokenAndSpan, Span, token_to_string}; use compiler::*; use std::collections::hash_map::HashMap; pub struct Quasiquote<'a, 'b:'a, 'c, C> where C: 'c { cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>, current_idx: usize, unquoted_tokens: Vec<TokenAndSpan> } impl<'a, 'b, 'c, C> Quasiquote<'a, 'b, 'c, C> where C: 'c + Compiler { pub fn compile(cx: &'a rust::ExtCtxt<'b>, tokens: Vec<TokenAndSpan>, compiler: &'c mut C) -> Vec<TokenAndSpan> { let mut quasiquote = Quasiquote::new(cx, compiler, tokens); quasiquote.unquote_all(); quasiquote.unquoted_tokens } fn new(cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>) -> Quasiquote<'a, 'b, 'c, C> { Quasiquote { cx: cx, compiler: compiler, tokens: tokens, current_idx: 0, unquoted_tokens: vec![] } } fn unquote_all(&mut self) { while!self.at_end() { match self.peek_unquote() { None => { let tok = self.token(); self.unquoted_tokens.push(tok); } Some(d) => { self.unquote(d); } } self.bump(1); } } fn bump(&mut self, n: usize) { self.current_idx = self.current_idx + n; } fn at_end(&self) -> bool { self.current_idx >= self.tokens.len() } fn token(&self) -> TokenAndSpan { self.tokens[self.current_idx].clone() } fn
(&self) -> Option<rust::DelimToken> { if self.current_idx + 1 < self.tokens.len() && self.tokens[self.current_idx].tok == rtok::Pound { match self.tokens[self.current_idx + 1].tok { rtok::OpenDelim(d@rust::DelimToken::Paren) | rtok::OpenDelim(d@rust::DelimToken::Brace) => Some(d), _ => None } } else { None } } fn unquote(&mut self, delim: rust::DelimToken) { let pound_idx = self.current_idx; let mut opened_delims = 1isize; self.bump(2); while!self.at_end() && self.still_in_quote(delim, opened_delims) { opened_delims = opened_delims + self.count_delim(delim); self.bump(1); } if self.at_end() || opened_delims!= 1 { self.cx.span_fatal(self.tokens[pound_idx + 1].sp, "unclosed delimiter of anynomous macro."); } let unquote = self.make_unquote(pound_idx); self.compile_unquote(delim, unquote); } fn still_in_quote(&self, delim: rust::DelimToken, opened_delims: isize) -> bool { opened_delims!= 1 || self.token().tok!= rtok::CloseDelim(delim) } fn count_delim(&self, delim: rust::DelimToken) -> isize { match self.token().tok { rtok::CloseDelim(d) if d == delim => -1, rtok::OpenDelim(d) if d == delim => 1, _ => 0 } } fn compile_unquote(&mut self, delim: rust::DelimToken, unquote: Unquote) { let span = unquote.span; let non_terminal = match delim { rust::DelimToken::Paren => { rust::Nonterminal::NtExpr(self.compiler.compile_expr(unquote)) } rust::DelimToken::Brace => { rust::Nonterminal::NtBlock(self.compiler.compile_block(unquote)) } d => panic!("compile_unquote: unrecognized delimiter {:?}", d) }; let interpolated_tok = rtok::Interpolated(non_terminal); let unquoted_tok = TokenAndSpan { tok: interpolated_tok, sp: span }; self.unquoted_tokens.push(unquoted_tok); } fn make_unquote(&self, start_idx: usize) -> Unquote { let mut code = String::new(); let mut text_to_ident = HashMap::new(); for idx in (start_idx+2)..self.current_idx { if let rtok::Ident(id) = self.tokens[idx].tok { text_to_ident.insert(format!("{}", id), id); } code.extend(token_to_string(&self.tokens[idx].tok).chars()); code.push(' '); } Unquote { text_to_ident: text_to_ident, code: code, span: self.span_from(start_idx) } } fn span_from(&self, start_idx: usize) -> Span { let mut span = self.tokens[start_idx].sp; span.hi = self.token().sp.hi; span } }
peek_unquote
identifier_name
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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. use rust; use rust::Token as rtok; use rust::{TokenAndSpan, Span, token_to_string}; use compiler::*; use std::collections::hash_map::HashMap; pub struct Quasiquote<'a, 'b:'a, 'c, C> where C: 'c { cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>, current_idx: usize, unquoted_tokens: Vec<TokenAndSpan> } impl<'a, 'b, 'c, C> Quasiquote<'a, 'b, 'c, C> where C: 'c + Compiler { pub fn compile(cx: &'a rust::ExtCtxt<'b>, tokens: Vec<TokenAndSpan>, compiler: &'c mut C) -> Vec<TokenAndSpan> { let mut quasiquote = Quasiquote::new(cx, compiler, tokens); quasiquote.unquote_all(); quasiquote.unquoted_tokens } fn new(cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>) -> Quasiquote<'a, 'b, 'c, C> { Quasiquote { cx: cx, compiler: compiler, tokens: tokens, current_idx: 0, unquoted_tokens: vec![] } } fn unquote_all(&mut self) { while!self.at_end() { match self.peek_unquote() { None => { let tok = self.token(); self.unquoted_tokens.push(tok); } Some(d) => { self.unquote(d); } } self.bump(1); } } fn bump(&mut self, n: usize) { self.current_idx = self.current_idx + n; } fn at_end(&self) -> bool { self.current_idx >= self.tokens.len() } fn token(&self) -> TokenAndSpan { self.tokens[self.current_idx].clone() } fn peek_unquote(&self) -> Option<rust::DelimToken> { if self.current_idx + 1 < self.tokens.len() && self.tokens[self.current_idx].tok == rtok::Pound { match self.tokens[self.current_idx + 1].tok { rtok::OpenDelim(d@rust::DelimToken::Paren) | rtok::OpenDelim(d@rust::DelimToken::Brace) => Some(d), _ => None } } else { None } } fn unquote(&mut self, delim: rust::DelimToken)
fn still_in_quote(&self, delim: rust::DelimToken, opened_delims: isize) -> bool { opened_delims!= 1 || self.token().tok!= rtok::CloseDelim(delim) } fn count_delim(&self, delim: rust::DelimToken) -> isize { match self.token().tok { rtok::CloseDelim(d) if d == delim => -1, rtok::OpenDelim(d) if d == delim => 1, _ => 0 } } fn compile_unquote(&mut self, delim: rust::DelimToken, unquote: Unquote) { let span = unquote.span; let non_terminal = match delim { rust::DelimToken::Paren => { rust::Nonterminal::NtExpr(self.compiler.compile_expr(unquote)) } rust::DelimToken::Brace => { rust::Nonterminal::NtBlock(self.compiler.compile_block(unquote)) } d => panic!("compile_unquote: unrecognized delimiter {:?}", d) }; let interpolated_tok = rtok::Interpolated(non_terminal); let unquoted_tok = TokenAndSpan { tok: interpolated_tok, sp: span }; self.unquoted_tokens.push(unquoted_tok); } fn make_unquote(&self, start_idx: usize) -> Unquote { let mut code = String::new(); let mut text_to_ident = HashMap::new(); for idx in (start_idx+2)..self.current_idx { if let rtok::Ident(id) = self.tokens[idx].tok { text_to_ident.insert(format!("{}", id), id); } code.extend(token_to_string(&self.tokens[idx].tok).chars()); code.push(' '); } Unquote { text_to_ident: text_to_ident, code: code, span: self.span_from(start_idx) } } fn span_from(&self, start_idx: usize) -> Span { let mut span = self.tokens[start_idx].sp; span.hi = self.token().sp.hi; span } }
{ let pound_idx = self.current_idx; let mut opened_delims = 1isize; self.bump(2); while !self.at_end() && self.still_in_quote(delim, opened_delims) { opened_delims = opened_delims + self.count_delim(delim); self.bump(1); } if self.at_end() || opened_delims != 1 { self.cx.span_fatal(self.tokens[pound_idx + 1].sp, "unclosed delimiter of anynomous macro."); } let unquote = self.make_unquote(pound_idx); self.compile_unquote(delim, unquote); }
identifier_body
quasiquote.rs
// Copyright 2015 Pierre Talbot (IRCAM) // 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
// 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. use rust; use rust::Token as rtok; use rust::{TokenAndSpan, Span, token_to_string}; use compiler::*; use std::collections::hash_map::HashMap; pub struct Quasiquote<'a, 'b:'a, 'c, C> where C: 'c { cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>, current_idx: usize, unquoted_tokens: Vec<TokenAndSpan> } impl<'a, 'b, 'c, C> Quasiquote<'a, 'b, 'c, C> where C: 'c + Compiler { pub fn compile(cx: &'a rust::ExtCtxt<'b>, tokens: Vec<TokenAndSpan>, compiler: &'c mut C) -> Vec<TokenAndSpan> { let mut quasiquote = Quasiquote::new(cx, compiler, tokens); quasiquote.unquote_all(); quasiquote.unquoted_tokens } fn new(cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>) -> Quasiquote<'a, 'b, 'c, C> { Quasiquote { cx: cx, compiler: compiler, tokens: tokens, current_idx: 0, unquoted_tokens: vec![] } } fn unquote_all(&mut self) { while!self.at_end() { match self.peek_unquote() { None => { let tok = self.token(); self.unquoted_tokens.push(tok); } Some(d) => { self.unquote(d); } } self.bump(1); } } fn bump(&mut self, n: usize) { self.current_idx = self.current_idx + n; } fn at_end(&self) -> bool { self.current_idx >= self.tokens.len() } fn token(&self) -> TokenAndSpan { self.tokens[self.current_idx].clone() } fn peek_unquote(&self) -> Option<rust::DelimToken> { if self.current_idx + 1 < self.tokens.len() && self.tokens[self.current_idx].tok == rtok::Pound { match self.tokens[self.current_idx + 1].tok { rtok::OpenDelim(d@rust::DelimToken::Paren) | rtok::OpenDelim(d@rust::DelimToken::Brace) => Some(d), _ => None } } else { None } } fn unquote(&mut self, delim: rust::DelimToken) { let pound_idx = self.current_idx; let mut opened_delims = 1isize; self.bump(2); while!self.at_end() && self.still_in_quote(delim, opened_delims) { opened_delims = opened_delims + self.count_delim(delim); self.bump(1); } if self.at_end() || opened_delims!= 1 { self.cx.span_fatal(self.tokens[pound_idx + 1].sp, "unclosed delimiter of anynomous macro."); } let unquote = self.make_unquote(pound_idx); self.compile_unquote(delim, unquote); } fn still_in_quote(&self, delim: rust::DelimToken, opened_delims: isize) -> bool { opened_delims!= 1 || self.token().tok!= rtok::CloseDelim(delim) } fn count_delim(&self, delim: rust::DelimToken) -> isize { match self.token().tok { rtok::CloseDelim(d) if d == delim => -1, rtok::OpenDelim(d) if d == delim => 1, _ => 0 } } fn compile_unquote(&mut self, delim: rust::DelimToken, unquote: Unquote) { let span = unquote.span; let non_terminal = match delim { rust::DelimToken::Paren => { rust::Nonterminal::NtExpr(self.compiler.compile_expr(unquote)) } rust::DelimToken::Brace => { rust::Nonterminal::NtBlock(self.compiler.compile_block(unquote)) } d => panic!("compile_unquote: unrecognized delimiter {:?}", d) }; let interpolated_tok = rtok::Interpolated(non_terminal); let unquoted_tok = TokenAndSpan { tok: interpolated_tok, sp: span }; self.unquoted_tokens.push(unquoted_tok); } fn make_unquote(&self, start_idx: usize) -> Unquote { let mut code = String::new(); let mut text_to_ident = HashMap::new(); for idx in (start_idx+2)..self.current_idx { if let rtok::Ident(id) = self.tokens[idx].tok { text_to_ident.insert(format!("{}", id), id); } code.extend(token_to_string(&self.tokens[idx].tok).chars()); code.push(' '); } Unquote { text_to_ident: text_to_ident, code: code, span: self.span_from(start_idx) } } fn span_from(&self, start_idx: usize) -> Span { let mut span = self.tokens[start_idx].sp; span.hi = self.token().sp.hi; span } }
// http://www.apache.org/licenses/LICENSE-2.0
random_line_split
box.rs
use std::mem; #[allow(dead_code)] struct Point { x: f64, y: f64, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn boxed_origin() -> Box<Point>
fn main() { // (all the type annotations are superfluous) // Stack allocated variables let point: Point = origin(); let rectangle: Rectangle = Rectangle { p1: origin(), p2: Point { x: 3.0, y: 4.0 } }; // Heap allocated rectangle let boxed_rectangle: Box<Rectangle> = box Rectangle { p1: origin(), p2: origin() }; // The output of functions can be boxed let boxed_point: Box<Point> = box origin(); // Double indirection let box_in_a_box: Box<Box<Point>> = box boxed_origin(); println!("Point occupies {} bytes in the stack", mem::size_of_val(&point)); println!("Rectangle occupies {} bytes in the stack", mem::size_of_val(&rectangle)); // box size = pointer size println!("Boxed point occupies {} bytes in the stack", mem::size_of_val(&boxed_point)); println!("Boxed rectangle occupies {} bytes in the stack", mem::size_of_val(&boxed_rectangle)); println!("Boxed box occupies {} bytes in the stack", mem::size_of_val(&box_in_a_box)); // Copy the data contained in `boxed_point` into `unboxed_point` let unboxed_point: Point = *boxed_point; println!("Unboxed point occupies {} bytes in the stack", mem::size_of_val(&unboxed_point)); // Unboxing via a destructuring pattern let box another_unboxed_point = boxed_point; println!("Another unboxed point occupies {} bytes in the stack", mem::size_of_val(&another_unboxed_point)); }
{ // Allocate this point in the heap, and return a pointer to it box Point { x: 0.0, y: 0.0 } }
identifier_body
box.rs
use std::mem; #[allow(dead_code)] struct Point { x: f64, y: f64, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn
() -> Box<Point> { // Allocate this point in the heap, and return a pointer to it box Point { x: 0.0, y: 0.0 } } fn main() { // (all the type annotations are superfluous) // Stack allocated variables let point: Point = origin(); let rectangle: Rectangle = Rectangle { p1: origin(), p2: Point { x: 3.0, y: 4.0 } }; // Heap allocated rectangle let boxed_rectangle: Box<Rectangle> = box Rectangle { p1: origin(), p2: origin() }; // The output of functions can be boxed let boxed_point: Box<Point> = box origin(); // Double indirection let box_in_a_box: Box<Box<Point>> = box boxed_origin(); println!("Point occupies {} bytes in the stack", mem::size_of_val(&point)); println!("Rectangle occupies {} bytes in the stack", mem::size_of_val(&rectangle)); // box size = pointer size println!("Boxed point occupies {} bytes in the stack", mem::size_of_val(&boxed_point)); println!("Boxed rectangle occupies {} bytes in the stack", mem::size_of_val(&boxed_rectangle)); println!("Boxed box occupies {} bytes in the stack", mem::size_of_val(&box_in_a_box)); // Copy the data contained in `boxed_point` into `unboxed_point` let unboxed_point: Point = *boxed_point; println!("Unboxed point occupies {} bytes in the stack", mem::size_of_val(&unboxed_point)); // Unboxing via a destructuring pattern let box another_unboxed_point = boxed_point; println!("Another unboxed point occupies {} bytes in the stack", mem::size_of_val(&another_unboxed_point)); }
boxed_origin
identifier_name
box.rs
use std::mem; #[allow(dead_code)] struct Point { x: f64, y: f64, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn boxed_origin() -> Box<Point> { // Allocate this point in the heap, and return a pointer to it box Point { x: 0.0, y: 0.0 } } fn main() { // (all the type annotations are superfluous) // Stack allocated variables let point: Point = origin(); let rectangle: Rectangle = Rectangle {
p2: Point { x: 3.0, y: 4.0 } }; // Heap allocated rectangle let boxed_rectangle: Box<Rectangle> = box Rectangle { p1: origin(), p2: origin() }; // The output of functions can be boxed let boxed_point: Box<Point> = box origin(); // Double indirection let box_in_a_box: Box<Box<Point>> = box boxed_origin(); println!("Point occupies {} bytes in the stack", mem::size_of_val(&point)); println!("Rectangle occupies {} bytes in the stack", mem::size_of_val(&rectangle)); // box size = pointer size println!("Boxed point occupies {} bytes in the stack", mem::size_of_val(&boxed_point)); println!("Boxed rectangle occupies {} bytes in the stack", mem::size_of_val(&boxed_rectangle)); println!("Boxed box occupies {} bytes in the stack", mem::size_of_val(&box_in_a_box)); // Copy the data contained in `boxed_point` into `unboxed_point` let unboxed_point: Point = *boxed_point; println!("Unboxed point occupies {} bytes in the stack", mem::size_of_val(&unboxed_point)); // Unboxing via a destructuring pattern let box another_unboxed_point = boxed_point; println!("Another unboxed point occupies {} bytes in the stack", mem::size_of_val(&another_unboxed_point)); }
p1: origin(),
random_line_split
issue-16098.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. macro_rules! prob1 { (0) => { 0 }; ($n:expr) => { if ($n % 3 == 0) || ($n % 5 == 0) { $n + prob1!($n - 1); //~ ERROR recursion limit reached while expanding the macro `prob1` } else { prob1!($n - 1); } }; } fn
() { println!("Problem 1: {}", prob1!(1000)); }
main
identifier_name
issue-16098.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. macro_rules! prob1 { (0) => { 0 }; ($n:expr) => { if ($n % 3 == 0) || ($n % 5 == 0) { $n + prob1!($n - 1); //~ ERROR recursion limit reached while expanding the macro `prob1` } else { prob1!($n - 1); } }; } fn main()
{ println!("Problem 1: {}", prob1!(1000)); }
identifier_body
issue-16098.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
0 }; ($n:expr) => { if ($n % 3 == 0) || ($n % 5 == 0) { $n + prob1!($n - 1); //~ ERROR recursion limit reached while expanding the macro `prob1` } else { prob1!($n - 1); } }; } fn main() { println!("Problem 1: {}", prob1!(1000)); }
// except according to those terms. macro_rules! prob1 { (0) => {
random_line_split
rpcndr.rs
// Copyright © 2016 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. use ctypes::{ __int64, __uint64, c_char, c_uchar, c_ulong }; pub const NDR_CHAR_REP_MASK: c_ulong = 0x0000000F; pub const NDR_INT_REP_MASK: c_ulong = 0x000000F0; pub const NDR_FLOAT_REP_MASK: c_ulong = 0x0000FF00; pub const NDR_LITTLE_ENDIAN: c_ulong = 0x00000010; pub const NDR_BIG_ENDIAN: c_ulong = 0x00000000; pub const NDR_IEEE_FLOAT: c_ulong = 0x00000000; pub const NDR_VAX_FLOAT: c_ulong = 0x00000100; pub const NDR_IBM_FLOAT: c_ulong = 0x00000300; pub const NDR_ASCII_CHAR: c_ulong = 0x00000000; pub const NDR_EBCDIC_CHAR: c_ulong = 0x00000001; pub const NDR_LOCAL_DATA_REPRESENTATION: c_ulong = 0x00000010; pub const NDR_LOCAL_ENDIAN: c_ulong = NDR_LITTLE_ENDIAN; pub type small = c_char;
pub type boolean = c_uchar; pub type hyper = __int64; pub type MIDL_uhyper = __uint64; // TODO Finish the rest
pub type byte = c_uchar; pub type cs_byte = byte;
random_line_split
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory of `size` bytes with optional alignment. pub fn new(size: usize, align: Option<usize>) -> Result<Self> { let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES); let layout = Layout::from_size_align(size, alignment)?; let ptr = unsafe { alloc::alloc(layout.clone()) }; if ptr.is_null() { alloc::handle_alloc_error(layout); } Ok(Self { ptr: ptr, layout: layout, }) } pub fn as_mut_ptr(&self) -> *mut u8 { self.ptr } /// Returns the size of the Allocation in bytes. pub fn
(&self) -> usize { self.layout.size() } /// Returns the byte alignment of the Allocation. pub fn align(&self) -> usize { self.layout.align() } } impl Drop for Allocation { fn drop(&mut self) { unsafe { alloc::dealloc(self.ptr, self.layout.clone()); } } }
size
identifier_name
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory of `size` bytes with optional alignment. pub fn new(size: usize, align: Option<usize>) -> Result<Self> {
if ptr.is_null() { alloc::handle_alloc_error(layout); } Ok(Self { ptr: ptr, layout: layout, }) } pub fn as_mut_ptr(&self) -> *mut u8 { self.ptr } /// Returns the size of the Allocation in bytes. pub fn size(&self) -> usize { self.layout.size() } /// Returns the byte alignment of the Allocation. pub fn align(&self) -> usize { self.layout.align() } } impl Drop for Allocation { fn drop(&mut self) { unsafe { alloc::dealloc(self.ptr, self.layout.clone()); } } }
let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES); let layout = Layout::from_size_align(size, alignment)?; let ptr = unsafe { alloc::alloc(layout.clone()) };
random_line_split
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory of `size` bytes with optional alignment. pub fn new(size: usize, align: Option<usize>) -> Result<Self> { let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES); let layout = Layout::from_size_align(size, alignment)?; let ptr = unsafe { alloc::alloc(layout.clone()) }; if ptr.is_null() { alloc::handle_alloc_error(layout); } Ok(Self { ptr: ptr, layout: layout, }) } pub fn as_mut_ptr(&self) -> *mut u8 { self.ptr } /// Returns the size of the Allocation in bytes. pub fn size(&self) -> usize
/// Returns the byte alignment of the Allocation. pub fn align(&self) -> usize { self.layout.align() } } impl Drop for Allocation { fn drop(&mut self) { unsafe { alloc::dealloc(self.ptr, self.layout.clone()); } } }
{ self.layout.size() }
identifier_body
allocator.rs
#[cfg(target_env = "sgx")] use alloc::alloc::{self, Layout}; #[cfg(not(target_env = "sgx"))] use std::alloc::{self, Layout}; use errors::*; const DEFAULT_ALIGN_BYTES: usize = 4; #[derive(PartialEq, Eq)] pub struct Allocation { layout: Layout, ptr: *mut u8, } impl Allocation { /// Allocates a chunk of memory of `size` bytes with optional alignment. pub fn new(size: usize, align: Option<usize>) -> Result<Self> { let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES); let layout = Layout::from_size_align(size, alignment)?; let ptr = unsafe { alloc::alloc(layout.clone()) }; if ptr.is_null()
Ok(Self { ptr: ptr, layout: layout, }) } pub fn as_mut_ptr(&self) -> *mut u8 { self.ptr } /// Returns the size of the Allocation in bytes. pub fn size(&self) -> usize { self.layout.size() } /// Returns the byte alignment of the Allocation. pub fn align(&self) -> usize { self.layout.align() } } impl Drop for Allocation { fn drop(&mut self) { unsafe { alloc::dealloc(self.ptr, self.layout.clone()); } } }
{ alloc::handle_alloc_error(layout); }
conditional_block
graphic.rs
use cursive::theme::{BaseColor, Color, ColorStyle}; use cursive::traits::*; use cursive::vec::Vec2; use cursive::Printer; use tutor::{Label, LabeledChord, PrevCharStatus}; pub struct Graphic { switches: Vec<Switch>, } #[derive(Clone, Copy)] pub enum ChordType { Next, Error, Backspace, Persistent, } struct Switch { position: (usize, usize), next: Option<Label>, error: Option<Label>, persistent: Vec<Label>, backspace: Option<Label>, } //////////////////////////////////////////////////////////////////////////////// impl Graphic { pub fn new(persistent: Vec<LabeledChord>) -> Self { let switches: Vec<_> = get_switch_positions() .into_iter() .map(Switch::new) .collect(); let mut graphic = Self { switches }; for labeled_chord in persistent { graphic.apply_chord(labeled_chord, ChordType::Persistent); } graphic } pub fn update( &mut self, next: Option<LabeledChord>, prev: &PrevCharStatus, ) { for switch in &mut self.switches { switch.clear() } if let Some(c) = next { self.apply_chord(c, ChordType::Next) } if let Some(c) = prev.backspace() { self.apply_chord(c, ChordType::Backspace) } if let Some(c) = prev.error() { self.apply_chord(c, ChordType::Error) } } fn apply_chord(&mut self, lc: LabeledChord, chord_type: ChordType) { let (label, chord) = (lc.label, lc.chord); for (bit, switch) in chord.iter().zip(self.switches.iter_mut()) { if bit { switch.set_label(chord_type, label.clone()); } } } pub fn size(&self) -> Vec2 { Vec2::new(78, 12) } } impl View for Graphic { fn required_size(&mut self, _constraint: Vec2) -> Vec2 { self.size() } fn draw(&self, printer: &Printer) { for switch in &self.switches { switch.draw(printer); } } } impl Switch { fn new(position: (usize, usize)) -> Self { Self { next: None, error: None, backspace: None, persistent: Vec::new(), position, } } fn set_label(&mut self, chord_type: ChordType, label: Label) { match chord_type { ChordType::Next => self.next = Some(label), ChordType::Error => self.error = Some(label), ChordType::Backspace => self.backspace = Some(label), ChordType::Persistent => self.persistent.push(label), } } /// Clear all labels except the `persistent` label, since that one stays for /// the whole lesson fn clear(&mut self) { self.next = None; self.error = None; self.backspace = None; } /// Pick 1 label to show, according to their priority order fn label(&self) -> Label { self.next .as_ref() .or_else(|| self.error.as_ref()) .or_else(|| self.backspace.as_ref()) .cloned() .or_else(|| Label::join(&self.persistent)) .unwrap_or_else(Label::default) } /// Pick a style for the switch, based on which labeled chords include it fn styles(&self) -> (ColorStyle, ColorStyle) { let next = Self::next_style(); let error = Self::error_style(); let backspace = Self::backspace_style(); let default = Self::default_style(); match ( self.next.is_some(), self.error.is_some(), self.backspace.is_some(), ) { (true, false, false) => (next, next), (false, true, false) => (error, error), (false, false, true) => (backspace, backspace), (true, true, false) => (next, error), (true, false, true) => (next, backspace), _ => (default, default), } } fn next_style() -> ColorStyle { ColorStyle::tertiary() } fn backspace_style() -> ColorStyle
fn error_style() -> ColorStyle { ColorStyle::secondary() } fn default_style() -> ColorStyle { ColorStyle::title_secondary() } fn draw(&self, printer: &Printer) { let (x, y) = self.position; let row2_left = format!("│{}", self.label()); let (left, right) = self.styles(); printer.with_color(left, |printer| { printer.print((x, y), "╭───"); printer.print((x, y + 1), &row2_left); printer.print((x, y + 2), "╰"); }); printer.with_color(right, |printer| { printer.print((x + 4, y), "╮"); printer.print((x + 4, y + 1), "│"); printer.print((x + 1, y + 2), "───╯"); }); } } fn get_switch_positions() -> Vec<(usize, usize)> { vec![ (0, 2), (6, 1), (12, 1), (18, 1), (54, 1), (60, 1), (66, 1), (72, 2), (0, 5), (6, 4), (12, 4), (18, 4), (54, 4), (60, 4), (66, 4), (72, 5), (60, 7), (12, 7), (20, 8), (26, 8), (32, 9), (40, 9), (46, 8), (52, 8), ] }
{ // TODO the background color is hardcoded, instead of inheriting from // the theme! ColorStyle::new( Color::Dark(BaseColor::Yellow), Color::Dark(BaseColor::Black), ) }
identifier_body
graphic.rs
use cursive::theme::{BaseColor, Color, ColorStyle}; use cursive::traits::*; use cursive::vec::Vec2; use cursive::Printer; use tutor::{Label, LabeledChord, PrevCharStatus}; pub struct Graphic { switches: Vec<Switch>, } #[derive(Clone, Copy)] pub enum ChordType { Next, Error, Backspace, Persistent, } struct Switch { position: (usize, usize), next: Option<Label>, error: Option<Label>, persistent: Vec<Label>, backspace: Option<Label>, } //////////////////////////////////////////////////////////////////////////////// impl Graphic { pub fn new(persistent: Vec<LabeledChord>) -> Self { let switches: Vec<_> = get_switch_positions() .into_iter() .map(Switch::new) .collect(); let mut graphic = Self { switches }; for labeled_chord in persistent { graphic.apply_chord(labeled_chord, ChordType::Persistent); } graphic } pub fn update( &mut self, next: Option<LabeledChord>, prev: &PrevCharStatus, ) { for switch in &mut self.switches { switch.clear() } if let Some(c) = next { self.apply_chord(c, ChordType::Next) } if let Some(c) = prev.backspace() { self.apply_chord(c, ChordType::Backspace) } if let Some(c) = prev.error() { self.apply_chord(c, ChordType::Error) } } fn apply_chord(&mut self, lc: LabeledChord, chord_type: ChordType) { let (label, chord) = (lc.label, lc.chord); for (bit, switch) in chord.iter().zip(self.switches.iter_mut()) { if bit { switch.set_label(chord_type, label.clone()); } } } pub fn size(&self) -> Vec2 { Vec2::new(78, 12) } } impl View for Graphic { fn required_size(&mut self, _constraint: Vec2) -> Vec2 { self.size() } fn draw(&self, printer: &Printer) { for switch in &self.switches { switch.draw(printer); } } } impl Switch { fn new(position: (usize, usize)) -> Self { Self { next: None, error: None, backspace: None, persistent: Vec::new(), position, } } fn set_label(&mut self, chord_type: ChordType, label: Label) { match chord_type { ChordType::Next => self.next = Some(label), ChordType::Error => self.error = Some(label), ChordType::Backspace => self.backspace = Some(label), ChordType::Persistent => self.persistent.push(label), } } /// Clear all labels except the `persistent` label, since that one stays for /// the whole lesson fn clear(&mut self) { self.next = None; self.error = None; self.backspace = None; } /// Pick 1 label to show, according to their priority order fn label(&self) -> Label { self.next .as_ref() .or_else(|| self.error.as_ref()) .or_else(|| self.backspace.as_ref()) .cloned() .or_else(|| Label::join(&self.persistent)) .unwrap_or_else(Label::default) } /// Pick a style for the switch, based on which labeled chords include it fn styles(&self) -> (ColorStyle, ColorStyle) { let next = Self::next_style(); let error = Self::error_style(); let backspace = Self::backspace_style(); let default = Self::default_style(); match ( self.next.is_some(), self.error.is_some(), self.backspace.is_some(), ) { (true, false, false) => (next, next), (false, true, false) => (error, error), (false, false, true) => (backspace, backspace), (true, true, false) => (next, error), (true, false, true) => (next, backspace), _ => (default, default), } } fn next_style() -> ColorStyle { ColorStyle::tertiary() } fn backspace_style() -> ColorStyle { // TODO the background color is hardcoded, instead of inheriting from // the theme! ColorStyle::new( Color::Dark(BaseColor::Yellow), Color::Dark(BaseColor::Black), ) } fn error_style() -> ColorStyle { ColorStyle::secondary() } fn default_style() -> ColorStyle { ColorStyle::title_secondary() } fn draw(&self, printer: &Printer) { let (x, y) = self.position; let row2_left = format!("│{}", self.label()); let (left, right) = self.styles(); printer.with_color(left, |printer| { printer.print((x, y), "╭───"); printer.print((x, y + 1), &row2_left); printer.print((x, y + 2), "╰"); }); printer.with_color(right, |printer| { printer.print((x + 4, y), "╮"); printer.print((x + 4, y + 1), "│"); printer.print((x + 1, y + 2), "───╯"); }); } } fn get_switch_positions() -
> { vec![ (0, 2), (6, 1), (12, 1), (18, 1), (54, 1), (60, 1), (66, 1), (72, 2), (0, 5), (6, 4), (12, 4), (18, 4), (54, 4), (60, 4), (66, 4), (72, 5), (60, 7), (12, 7), (20, 8), (26, 8), (32, 9), (40, 9), (46, 8), (52, 8), ] }
> Vec<(usize, usize)
identifier_name