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
base64.rs
/// Entry point for encoding input strings into base64-encoded output strings. pub fn encode(inp: &str) -> String { let base64_index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .chars() .collect::<Vec<char>>(); let mut result = String::new(); let mut it = inp.encode_utf16().map(|e| e as u32); loop { let triplet = vec![it.next(), it.next(), it.next()]; match triplet[0] { None => break, Some(_) => {} } let loop_end = triplet.iter().any(|e| match *e { None => true, _ => false, }); // look if any of the elements is None and if so flip the bool switch so the loop will be broken out of after some final tasks. let mut bit_string = 0u32; for (i, item) in triplet.iter().map(|e| e.unwrap_or(0u32)).enumerate() { // unwrap_or(some_value) unwraps the Option/Result and returns the value of Some(_) or the default some_value. bit_string |= item; if i!= 2 { bit_string <<= 8; } } let sextet3 = (bit_string & 0x3F) as usize; bit_string >>= 6; let sextet2 = (bit_string & 0x3F) as usize; bit_string >>= 6; let sextet1 = (bit_string & 0x3F) as usize; bit_string >>= 6; let sextet0 = (bit_string & 0x3F) as usize; let lsb1 = match triplet[1] { None => '=', _ => base64_index[sextet2], }; let lsb0 = match triplet[2] { None => '=', _ => base64_index[sextet3], }; result = format!("{}{}{}{}{}", result, base64_index[sextet0], base64_index[sextet1], lsb1, lsb0); if loop_end { break; } } result } /// Entry point for reversing base64-encoded input strings back to pub fn decode(inp: &str) -> String { let base64_index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .chars() .collect::<Vec<char>>(); let inp = match inp.len() % 4 { 2 => format!("{}==", inp), 3 => format!("{}=", inp), _ => inp.to_owned(), }; let mut it = inp.as_str().chars().map(|e| e as u8); let mut result = String::new(); loop { let mut quartet_: Vec<Option<u8>> = vec![]; for _ in 0..4 { quartet_.push(it.next()); } if quartet_.iter().any(|e| match *e { None => true, _ => false, }) { break; } let quartet = quartet_.iter().map(|e| (*e).unwrap_or(0u8)).collect::<Vec<u8>>(); let mut bit_string = 0u32; for (i, item) in quartet.iter().enumerate() { bit_string |= base64_index.iter() .position(|&x| x == (*item as char)) .unwrap_or(0usize) as u32; if i!= 3 { bit_string <<= 6; } } let octet2 = match quartet[3] { 0x3D => 0x0, _ => (bit_string & 0xFF) as u8, }; bit_string >>= 8; let octet1 = match quartet[2] { 0x3D => 0x0, _ => (bit_string & 0xFF) as u8, }; bit_string >>= 8; let octet0 = (bit_string & 0xFF) as u8; let (octet0, octet1, octet2) = (octet0 as char, octet1 as char, octet2 as char); result = match (octet1, octet2) { ('\0', '\0') => format!("{}{}", result, octet0), (_, '\0') => format!("{}{}{}", result, octet0, octet1), _ => format!("{}{}{}{}", result, octet0, octet1, octet2), } } result } #[cfg(test)] mod tests { use super::{encode, decode}; fn leviathan() -> &'static str { "Man is distinguished, not only by his reason, but by this singular passion from other \ animals, which is a lust of the mind, that by a perseverance of delight in the continued \ and indefatigable generation of knowledge, exceeds the short vehemence of any carnal \ pleasure." } fn leviathan_b64() -> &'static str { "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" } #[test] fn encode_man() { assert_eq!("TWFu".to_owned(), encode("Man")); } #[test] fn encode_leviathan()
#[test] fn decode_man() { assert_eq!("Man".to_owned(), decode("TWFu")); } #[test] fn decode_leviathan() { assert_eq!(leviathan(), decode(leviathan_b64())); } }
{ assert_eq!(leviathan_b64(), encode(leviathan())); }
identifier_body
request.rs
//! AWS API requests. //! //! Wraps the Hyper library to send PUT, POST, DELETE and GET requests. extern crate lazy_static; use std::env; use std::io::Read; use std::io::Error as IoError; use std::error::Error; use std::fmt; use std::collections::HashMap; use hyper::Client; use hyper::Error as HyperError; use hyper::header::Headers; use hyper::header::UserAgent; use hyper::method::Method; use log::LogLevel::Debug; use signature::SignedRequest; // Pulls in the statically generated rustc version. include!(concat!(env!("OUT_DIR"), "/user_agent_vars.rs")); // Use a lazy static to cache the default User-Agent header // because it never changes once it's been computed. lazy_static! { static ref DEFAULT_USER_AGENT: Vec<Vec<u8>> = vec![format!("rusoto/{} rust/{} {}", env!("CARGO_PKG_VERSION"), RUST_VERSION, env::consts::OS).as_bytes().to_vec()]; } #[derive(Clone, Default)] pub struct HttpResponse { pub status: u16, pub body: String, pub headers: HashMap<String, String> } #[derive(Debug, PartialEq)] pub struct HttpDispatchError { message: String } impl Error for HttpDispatchError { fn description(&self) -> &str { &self.message
} impl fmt::Display for HttpDispatchError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.message) } } impl From<HyperError> for HttpDispatchError { fn from(err: HyperError) -> HttpDispatchError { HttpDispatchError { message: err.description().to_string() } } } impl From<IoError> for HttpDispatchError { fn from(err: IoError) -> HttpDispatchError { HttpDispatchError { message: err.description().to_string() } } } pub trait DispatchSignedRequest { fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError>; } impl DispatchSignedRequest for Client { fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError> { let hyper_method = match request.method().as_ref() { "POST" => Method::Post, "PUT" => Method::Put, "DELETE" => Method::Delete, "GET" => Method::Get, "HEAD" => Method::Head, v => return Err(HttpDispatchError { message: format!("Unsupported HTTP verb {}", v) }) }; // translate the headers map to a format Hyper likes let mut hyper_headers = Headers::new(); for h in request.headers().iter() { hyper_headers.set_raw(h.0.to_owned(), h.1.to_owned()); } // Add a default user-agent header if one is not already present. if!hyper_headers.has::<UserAgent>() { hyper_headers.set_raw("user-agent".to_owned(), DEFAULT_USER_AGENT.clone()); } let mut final_uri = format!("https://{}{}", request.hostname(), request.canonical_path()); if!request.canonical_query_string().is_empty() { final_uri = final_uri + &format!("?{}", request.canonical_query_string()); } if log_enabled!(Debug) { let payload = request.payload().map(|mut payload_bytes| { let mut payload_string = String::new(); payload_bytes.read_to_string(&mut payload_string) .map(|_| payload_string) .unwrap_or_else(|_| String::from("<non-UTF-8 data>")) }); debug!("Full request: \n method: {}\n final_uri: {}\n payload: {}\nHeaders:\n", hyper_method, final_uri, payload.unwrap_or("".to_owned())); for h in hyper_headers.iter() { debug!("{}:{}", h.name(), h.value_string()); } } let mut hyper_response = match request.payload() { None => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body("").send()), Some(payload_contents) => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body(payload_contents).send()), }; let mut body = String::new(); try!(hyper_response.read_to_string(&mut body)); if log_enabled!(Debug) { debug!("Response body:\n{}", body); } let mut headers: HashMap<String, String> = HashMap::new(); for header in hyper_response.headers.iter() { headers.insert(header.name().to_string(), header.value_string()); } Ok(HttpResponse { status: hyper_response.status.to_u16(), body: body, headers: headers }) } }
}
random_line_split
request.rs
//! AWS API requests. //! //! Wraps the Hyper library to send PUT, POST, DELETE and GET requests. extern crate lazy_static; use std::env; use std::io::Read; use std::io::Error as IoError; use std::error::Error; use std::fmt; use std::collections::HashMap; use hyper::Client; use hyper::Error as HyperError; use hyper::header::Headers; use hyper::header::UserAgent; use hyper::method::Method; use log::LogLevel::Debug; use signature::SignedRequest; // Pulls in the statically generated rustc version. include!(concat!(env!("OUT_DIR"), "/user_agent_vars.rs")); // Use a lazy static to cache the default User-Agent header // because it never changes once it's been computed. lazy_static! { static ref DEFAULT_USER_AGENT: Vec<Vec<u8>> = vec![format!("rusoto/{} rust/{} {}", env!("CARGO_PKG_VERSION"), RUST_VERSION, env::consts::OS).as_bytes().to_vec()]; } #[derive(Clone, Default)] pub struct HttpResponse { pub status: u16, pub body: String, pub headers: HashMap<String, String> } #[derive(Debug, PartialEq)] pub struct HttpDispatchError { message: String } impl Error for HttpDispatchError { fn description(&self) -> &str { &self.message } } impl fmt::Display for HttpDispatchError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.message) } } impl From<HyperError> for HttpDispatchError { fn from(err: HyperError) -> HttpDispatchError { HttpDispatchError { message: err.description().to_string() } } } impl From<IoError> for HttpDispatchError { fn from(err: IoError) -> HttpDispatchError { HttpDispatchError { message: err.description().to_string() } } } pub trait DispatchSignedRequest { fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError>; } impl DispatchSignedRequest for Client { fn
(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError> { let hyper_method = match request.method().as_ref() { "POST" => Method::Post, "PUT" => Method::Put, "DELETE" => Method::Delete, "GET" => Method::Get, "HEAD" => Method::Head, v => return Err(HttpDispatchError { message: format!("Unsupported HTTP verb {}", v) }) }; // translate the headers map to a format Hyper likes let mut hyper_headers = Headers::new(); for h in request.headers().iter() { hyper_headers.set_raw(h.0.to_owned(), h.1.to_owned()); } // Add a default user-agent header if one is not already present. if!hyper_headers.has::<UserAgent>() { hyper_headers.set_raw("user-agent".to_owned(), DEFAULT_USER_AGENT.clone()); } let mut final_uri = format!("https://{}{}", request.hostname(), request.canonical_path()); if!request.canonical_query_string().is_empty() { final_uri = final_uri + &format!("?{}", request.canonical_query_string()); } if log_enabled!(Debug) { let payload = request.payload().map(|mut payload_bytes| { let mut payload_string = String::new(); payload_bytes.read_to_string(&mut payload_string) .map(|_| payload_string) .unwrap_or_else(|_| String::from("<non-UTF-8 data>")) }); debug!("Full request: \n method: {}\n final_uri: {}\n payload: {}\nHeaders:\n", hyper_method, final_uri, payload.unwrap_or("".to_owned())); for h in hyper_headers.iter() { debug!("{}:{}", h.name(), h.value_string()); } } let mut hyper_response = match request.payload() { None => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body("").send()), Some(payload_contents) => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body(payload_contents).send()), }; let mut body = String::new(); try!(hyper_response.read_to_string(&mut body)); if log_enabled!(Debug) { debug!("Response body:\n{}", body); } let mut headers: HashMap<String, String> = HashMap::new(); for header in hyper_response.headers.iter() { headers.insert(header.name().to_string(), header.value_string()); } Ok(HttpResponse { status: hyper_response.status.to_u16(), body: body, headers: headers }) } }
dispatch
identifier_name
request.rs
//! AWS API requests. //! //! Wraps the Hyper library to send PUT, POST, DELETE and GET requests. extern crate lazy_static; use std::env; use std::io::Read; use std::io::Error as IoError; use std::error::Error; use std::fmt; use std::collections::HashMap; use hyper::Client; use hyper::Error as HyperError; use hyper::header::Headers; use hyper::header::UserAgent; use hyper::method::Method; use log::LogLevel::Debug; use signature::SignedRequest; // Pulls in the statically generated rustc version. include!(concat!(env!("OUT_DIR"), "/user_agent_vars.rs")); // Use a lazy static to cache the default User-Agent header // because it never changes once it's been computed. lazy_static! { static ref DEFAULT_USER_AGENT: Vec<Vec<u8>> = vec![format!("rusoto/{} rust/{} {}", env!("CARGO_PKG_VERSION"), RUST_VERSION, env::consts::OS).as_bytes().to_vec()]; } #[derive(Clone, Default)] pub struct HttpResponse { pub status: u16, pub body: String, pub headers: HashMap<String, String> } #[derive(Debug, PartialEq)] pub struct HttpDispatchError { message: String } impl Error for HttpDispatchError { fn description(&self) -> &str { &self.message } } impl fmt::Display for HttpDispatchError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.message) } } impl From<HyperError> for HttpDispatchError { fn from(err: HyperError) -> HttpDispatchError { HttpDispatchError { message: err.description().to_string() } } } impl From<IoError> for HttpDispatchError { fn from(err: IoError) -> HttpDispatchError { HttpDispatchError { message: err.description().to_string() } } } pub trait DispatchSignedRequest { fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError>; } impl DispatchSignedRequest for Client { fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError> { let hyper_method = match request.method().as_ref() { "POST" => Method::Post, "PUT" => Method::Put, "DELETE" => Method::Delete, "GET" => Method::Get, "HEAD" => Method::Head, v => return Err(HttpDispatchError { message: format!("Unsupported HTTP verb {}", v) }) }; // translate the headers map to a format Hyper likes let mut hyper_headers = Headers::new(); for h in request.headers().iter() { hyper_headers.set_raw(h.0.to_owned(), h.1.to_owned()); } // Add a default user-agent header if one is not already present. if!hyper_headers.has::<UserAgent>() { hyper_headers.set_raw("user-agent".to_owned(), DEFAULT_USER_AGENT.clone()); } let mut final_uri = format!("https://{}{}", request.hostname(), request.canonical_path()); if!request.canonical_query_string().is_empty()
if log_enabled!(Debug) { let payload = request.payload().map(|mut payload_bytes| { let mut payload_string = String::new(); payload_bytes.read_to_string(&mut payload_string) .map(|_| payload_string) .unwrap_or_else(|_| String::from("<non-UTF-8 data>")) }); debug!("Full request: \n method: {}\n final_uri: {}\n payload: {}\nHeaders:\n", hyper_method, final_uri, payload.unwrap_or("".to_owned())); for h in hyper_headers.iter() { debug!("{}:{}", h.name(), h.value_string()); } } let mut hyper_response = match request.payload() { None => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body("").send()), Some(payload_contents) => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body(payload_contents).send()), }; let mut body = String::new(); try!(hyper_response.read_to_string(&mut body)); if log_enabled!(Debug) { debug!("Response body:\n{}", body); } let mut headers: HashMap<String, String> = HashMap::new(); for header in hyper_response.headers.iter() { headers.insert(header.name().to_string(), header.value_string()); } Ok(HttpResponse { status: hyper_response.status.to_u16(), body: body, headers: headers }) } }
{ final_uri = final_uri + &format!("?{}", request.canonical_query_string()); }
conditional_block
unify_key.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{self, IntVarValue, Ty}; use rustc_data_structures::unify::UnifyKey; use syntax::ast; pub trait ToType<'tcx> { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx>; } impl UnifyKey for ty::IntVid { type Value = Option<IntVarValue>; fn index(&self) -> u32 { self.index } fn from_index(i: u32) -> ty::IntVid { ty::IntVid { index: i } } fn tag(_: Option<ty::IntVid>) -> &'static str { "IntVid" } } impl<'tcx> ToType<'tcx> for IntVarValue { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> { match *self { ty::IntType(i) => tcx.mk_mach_int(i), ty::UintType(i) => tcx.mk_mach_uint(i), } } } // Floating point type keys impl UnifyKey for ty::FloatVid {
fn tag(_: Option<ty::FloatVid>) -> &'static str { "FloatVid" } } impl<'tcx> ToType<'tcx> for ast::FloatTy { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> { tcx.mk_mach_float(*self) } }
type Value = Option<ast::FloatTy>; fn index(&self) -> u32 { self.index } fn from_index(i: u32) -> ty::FloatVid { ty::FloatVid { index: i } }
random_line_split
unify_key.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{self, IntVarValue, Ty}; use rustc_data_structures::unify::UnifyKey; use syntax::ast; pub trait ToType<'tcx> { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx>; } impl UnifyKey for ty::IntVid { type Value = Option<IntVarValue>; fn index(&self) -> u32 { self.index } fn from_index(i: u32) -> ty::IntVid { ty::IntVid { index: i } } fn tag(_: Option<ty::IntVid>) -> &'static str { "IntVid" } } impl<'tcx> ToType<'tcx> for IntVarValue { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> { match *self { ty::IntType(i) => tcx.mk_mach_int(i), ty::UintType(i) => tcx.mk_mach_uint(i), } } } // Floating point type keys impl UnifyKey for ty::FloatVid { type Value = Option<ast::FloatTy>; fn index(&self) -> u32 { self.index } fn
(i: u32) -> ty::FloatVid { ty::FloatVid { index: i } } fn tag(_: Option<ty::FloatVid>) -> &'static str { "FloatVid" } } impl<'tcx> ToType<'tcx> for ast::FloatTy { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> { tcx.mk_mach_float(*self) } }
from_index
identifier_name
unify_key.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{self, IntVarValue, Ty}; use rustc_data_structures::unify::UnifyKey; use syntax::ast; pub trait ToType<'tcx> { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx>; } impl UnifyKey for ty::IntVid { type Value = Option<IntVarValue>; fn index(&self) -> u32 { self.index } fn from_index(i: u32) -> ty::IntVid { ty::IntVid { index: i } } fn tag(_: Option<ty::IntVid>) -> &'static str { "IntVid" } } impl<'tcx> ToType<'tcx> for IntVarValue { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> { match *self { ty::IntType(i) => tcx.mk_mach_int(i), ty::UintType(i) => tcx.mk_mach_uint(i), } } } // Floating point type keys impl UnifyKey for ty::FloatVid { type Value = Option<ast::FloatTy>; fn index(&self) -> u32 { self.index } fn from_index(i: u32) -> ty::FloatVid
fn tag(_: Option<ty::FloatVid>) -> &'static str { "FloatVid" } } impl<'tcx> ToType<'tcx> for ast::FloatTy { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> { tcx.mk_mach_float(*self) } }
{ ty::FloatVid { index: i } }
identifier_body
rpath.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. use driver::session; use metadata::cstore; use metadata::filesearch; use std::hashmap::HashSet; use std::os; use std::uint; use std::util; use std::vec; fn not_win32(os: session::os) -> bool { os!= session::os_win32 } pub fn get_rpath_flags(sess: session::Session, out_filename: &Path) -> ~[~str] { let os = sess.targ_cfg.os; // No rpath on windows if os == session::os_win32 { return ~[]; } debug!("preparing the RPATH!"); let sysroot = sess.filesearch.sysroot(); let output = out_filename; let libs = cstore::get_used_crate_files(sess.cstore); // We don't currently rpath extern libraries, but we know // where rustrt is and we know every rust program needs it let libs = vec::append_one(libs, get_sysroot_absolute_rt_lib(sess)); let rpaths = get_rpaths(os, sysroot, output, libs, sess.opts.target_triple); rpaths_to_flags(rpaths) } fn get_sysroot_absolute_rt_lib(sess: session::Session) -> Path { let r = filesearch::relative_target_lib_path(sess.opts.target_triple); sess.filesearch.sysroot().push_rel(&r).push(os::dll_filename("rustrt")) } pub fn rpaths_to_flags(rpaths: &[Path]) -> ~[~str] { rpaths.iter().transform(|rpath| fmt!("-Wl,-rpath,%s",rpath.to_str())).collect() } fn get_rpaths(os: session::os, sysroot: &Path, output: &Path, libs: &[Path], target_triple: &str) -> ~[Path] { debug!("sysroot: %s", sysroot.to_str()); debug!("output: %s", output.to_str()); debug!("libs:"); for libs.iter().advance |libpath| { debug!(" %s", libpath.to_str()); } debug!("target_triple: %s", target_triple); // Use relative paths to the libraries. Binaries can be moved // as long as they maintain the relative relationship to the // crates they depend on. let rel_rpaths = get_rpaths_relative_to_output(os, output, libs); // Make backup absolute paths to the libraries. Binaries can // be moved as long as the crates they link against don't move. let abs_rpaths = get_absolute_rpaths(libs); // And a final backup rpath to the global library location. let fallback_rpaths = ~[get_install_prefix_rpath(target_triple)]; fn log_rpaths(desc: &str, rpaths: &[Path]) { debug!("%s rpaths:", desc); for rpaths.iter().advance |rpath| { debug!(" %s", rpath.to_str()); } } log_rpaths("relative", rel_rpaths); log_rpaths("absolute", abs_rpaths); log_rpaths("fallback", fallback_rpaths); let mut rpaths = rel_rpaths; rpaths.push_all(abs_rpaths); rpaths.push_all(fallback_rpaths);
fn get_rpaths_relative_to_output(os: session::os, output: &Path, libs: &[Path]) -> ~[Path] { libs.iter().transform(|a| get_rpath_relative_to_output(os, output, a)).collect() } pub fn get_rpath_relative_to_output(os: session::os, output: &Path, lib: &Path) -> Path { use std::os; assert!(not_win32(os)); // Mac doesn't appear to support $ORIGIN let prefix = match os { session::os_android | session::os_linux | session::os_freebsd => "$ORIGIN", session::os_macos => "@executable_path", session::os_win32 => util::unreachable() }; Path(prefix).push_rel(&get_relative_to(&os::make_absolute(output), &os::make_absolute(lib))) } // Find the relative path from one file to another pub fn get_relative_to(abs1: &Path, abs2: &Path) -> Path { assert!(abs1.is_absolute); assert!(abs2.is_absolute); let abs1 = abs1.normalize(); let abs2 = abs2.normalize(); debug!("finding relative path from %s to %s", abs1.to_str(), abs2.to_str()); let split1: &[~str] = abs1.components; let split2: &[~str] = abs2.components; let len1 = split1.len(); let len2 = split2.len(); assert!(len1 > 0); assert!(len2 > 0); let max_common_path = uint::min(len1, len2) - 1; let mut start_idx = 0; while start_idx < max_common_path && split1[start_idx] == split2[start_idx] { start_idx += 1; } let mut path = ~[]; for uint::range(start_idx, len1 - 1) |_i| { path.push(~".."); }; path.push_all(split2.slice(start_idx, len2 - 1)); return if!path.is_empty() { Path("").push_many(path) } else { Path(".") } } fn get_absolute_rpaths(libs: &[Path]) -> ~[Path] { libs.iter().transform(|a| get_absolute_rpath(a)).collect() } pub fn get_absolute_rpath(lib: &Path) -> Path { os::make_absolute(lib).dir_path() } pub fn get_install_prefix_rpath(target_triple: &str) -> Path { let install_prefix = env!("CFG_PREFIX"); if install_prefix == "" { fail!("rustc compiled without CFG_PREFIX environment variable"); } let tlib = filesearch::relative_target_lib_path(target_triple); os::make_absolute(&Path(install_prefix).push_rel(&tlib)) } pub fn minimize_rpaths(rpaths: &[Path]) -> ~[Path] { let mut set = HashSet::new(); let mut minimized = ~[]; for rpaths.iter().advance |rpath| { if set.insert(rpath.to_str()) { minimized.push(copy *rpath); } } minimized } #[cfg(unix, test)] mod test { use std::os; // FIXME(#2119): the outer attribute should be #[cfg(unix, test)], then // these redundant #[cfg(test)] blocks can be removed #[cfg(test)] #[cfg(test)] use back::rpath::{get_absolute_rpath, get_install_prefix_rpath}; use back::rpath::{get_relative_to, get_rpath_relative_to_output}; use back::rpath::{minimize_rpaths, rpaths_to_flags}; use driver::session; #[test] fn test_rpaths_to_flags() { let flags = rpaths_to_flags([Path("path1"), Path("path2")]); assert_eq!(flags, ~[~"-Wl,-rpath,path1", ~"-Wl,-rpath,path2"]); } #[test] fn test_prefix_rpath() { let res = get_install_prefix_rpath("triple"); let d = Path(env!("CFG_PREFIX")) .push_rel(&Path("lib/rustc/triple/lib")); debug!("test_prefix_path: %s vs. %s", res.to_str(), d.to_str()); assert!(res.to_str().ends_with(d.to_str())); } #[test] fn test_prefix_rpath_abs() { let res = get_install_prefix_rpath("triple"); assert!(res.is_absolute); } #[test] fn test_minimize1() { let res = minimize_rpaths([Path("rpath1"), Path("rpath2"), Path("rpath1")]); assert_eq!(res, ~[Path("rpath1"), Path("rpath2")]); } #[test] fn test_minimize2() { let res = minimize_rpaths([Path("1a"), Path("2"), Path("2"), Path("1a"), Path("4a"),Path("1a"), Path("2"), Path("3"), Path("4a"), Path("3")]); assert_eq!(res, ~[Path("1a"), Path("2"), Path("4a"), Path("3")]); } #[test] fn test_relative_to1() { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/lib/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to2() { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/bin/../lib/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to3() { let p1 = Path("/usr/bin/whatever/rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../../lib/whatever")); } #[test] fn test_relative_to4() { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib/whatever")); } #[test] fn test_relative_to5() { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/../mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to6() { let p1 = Path("/1"); let p2 = Path("/2/3"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("2")); } #[test] fn test_relative_to7() { let p1 = Path("/1/2"); let p2 = Path("/3"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("..")); } #[test] fn test_relative_to8() { let p1 = Path("/home/brian/Dev/rust/build/").push_rel( &Path("stage2/lib/rustc/i686-unknown-linux-gnu/lib/librustc.so")); let p2 = Path("/home/brian/Dev/rust/build/stage2/bin/..").push_rel( &Path("lib/rustc/i686-unknown-linux-gnu/lib/libstd.so")); let res = get_relative_to(&p1, &p2); debug!("test_relative_tu8: %s vs. %s", res.to_str(), Path(".").to_str()); assert_eq!(res, Path(".")); } #[test] #[cfg(target_os = "linux")] #[cfg(target_os = "andorid")] fn test_rpath_relative() { let o = session::os_linux; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] #[cfg(target_os = "freebsd")] fn test_rpath_relative() { let o = session::os_freebsd; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] #[cfg(target_os = "macos")] fn test_rpath_relative() { // this is why refinements would be nice let o = session::os_macos; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"@executable_path/../lib"); } #[test] fn test_get_absolute_rpath() { let res = get_absolute_rpath(&Path("lib/libstd.so")); debug!("test_get_absolute_rpath: %s vs. %s", res.to_str(), os::make_absolute(&Path("lib")).to_str()); assert_eq!(res, os::make_absolute(&Path("lib"))); } }
// Remove duplicates let rpaths = minimize_rpaths(rpaths); return rpaths; }
random_line_split
rpath.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. use driver::session; use metadata::cstore; use metadata::filesearch; use std::hashmap::HashSet; use std::os; use std::uint; use std::util; use std::vec; fn not_win32(os: session::os) -> bool { os!= session::os_win32 } pub fn get_rpath_flags(sess: session::Session, out_filename: &Path) -> ~[~str] { let os = sess.targ_cfg.os; // No rpath on windows if os == session::os_win32 { return ~[]; } debug!("preparing the RPATH!"); let sysroot = sess.filesearch.sysroot(); let output = out_filename; let libs = cstore::get_used_crate_files(sess.cstore); // We don't currently rpath extern libraries, but we know // where rustrt is and we know every rust program needs it let libs = vec::append_one(libs, get_sysroot_absolute_rt_lib(sess)); let rpaths = get_rpaths(os, sysroot, output, libs, sess.opts.target_triple); rpaths_to_flags(rpaths) } fn get_sysroot_absolute_rt_lib(sess: session::Session) -> Path { let r = filesearch::relative_target_lib_path(sess.opts.target_triple); sess.filesearch.sysroot().push_rel(&r).push(os::dll_filename("rustrt")) } pub fn rpaths_to_flags(rpaths: &[Path]) -> ~[~str] { rpaths.iter().transform(|rpath| fmt!("-Wl,-rpath,%s",rpath.to_str())).collect() } fn get_rpaths(os: session::os, sysroot: &Path, output: &Path, libs: &[Path], target_triple: &str) -> ~[Path] { debug!("sysroot: %s", sysroot.to_str()); debug!("output: %s", output.to_str()); debug!("libs:"); for libs.iter().advance |libpath| { debug!(" %s", libpath.to_str()); } debug!("target_triple: %s", target_triple); // Use relative paths to the libraries. Binaries can be moved // as long as they maintain the relative relationship to the // crates they depend on. let rel_rpaths = get_rpaths_relative_to_output(os, output, libs); // Make backup absolute paths to the libraries. Binaries can // be moved as long as the crates they link against don't move. let abs_rpaths = get_absolute_rpaths(libs); // And a final backup rpath to the global library location. let fallback_rpaths = ~[get_install_prefix_rpath(target_triple)]; fn log_rpaths(desc: &str, rpaths: &[Path]) { debug!("%s rpaths:", desc); for rpaths.iter().advance |rpath| { debug!(" %s", rpath.to_str()); } } log_rpaths("relative", rel_rpaths); log_rpaths("absolute", abs_rpaths); log_rpaths("fallback", fallback_rpaths); let mut rpaths = rel_rpaths; rpaths.push_all(abs_rpaths); rpaths.push_all(fallback_rpaths); // Remove duplicates let rpaths = minimize_rpaths(rpaths); return rpaths; } fn get_rpaths_relative_to_output(os: session::os, output: &Path, libs: &[Path]) -> ~[Path] { libs.iter().transform(|a| get_rpath_relative_to_output(os, output, a)).collect() } pub fn get_rpath_relative_to_output(os: session::os, output: &Path, lib: &Path) -> Path { use std::os; assert!(not_win32(os)); // Mac doesn't appear to support $ORIGIN let prefix = match os { session::os_android | session::os_linux | session::os_freebsd => "$ORIGIN", session::os_macos => "@executable_path", session::os_win32 => util::unreachable() }; Path(prefix).push_rel(&get_relative_to(&os::make_absolute(output), &os::make_absolute(lib))) } // Find the relative path from one file to another pub fn get_relative_to(abs1: &Path, abs2: &Path) -> Path { assert!(abs1.is_absolute); assert!(abs2.is_absolute); let abs1 = abs1.normalize(); let abs2 = abs2.normalize(); debug!("finding relative path from %s to %s", abs1.to_str(), abs2.to_str()); let split1: &[~str] = abs1.components; let split2: &[~str] = abs2.components; let len1 = split1.len(); let len2 = split2.len(); assert!(len1 > 0); assert!(len2 > 0); let max_common_path = uint::min(len1, len2) - 1; let mut start_idx = 0; while start_idx < max_common_path && split1[start_idx] == split2[start_idx] { start_idx += 1; } let mut path = ~[]; for uint::range(start_idx, len1 - 1) |_i| { path.push(~".."); }; path.push_all(split2.slice(start_idx, len2 - 1)); return if!path.is_empty() { Path("").push_many(path) } else { Path(".") } } fn get_absolute_rpaths(libs: &[Path]) -> ~[Path] { libs.iter().transform(|a| get_absolute_rpath(a)).collect() } pub fn get_absolute_rpath(lib: &Path) -> Path { os::make_absolute(lib).dir_path() } pub fn get_install_prefix_rpath(target_triple: &str) -> Path { let install_prefix = env!("CFG_PREFIX"); if install_prefix == "" { fail!("rustc compiled without CFG_PREFIX environment variable"); } let tlib = filesearch::relative_target_lib_path(target_triple); os::make_absolute(&Path(install_prefix).push_rel(&tlib)) } pub fn minimize_rpaths(rpaths: &[Path]) -> ~[Path] { let mut set = HashSet::new(); let mut minimized = ~[]; for rpaths.iter().advance |rpath| { if set.insert(rpath.to_str()) { minimized.push(copy *rpath); } } minimized } #[cfg(unix, test)] mod test { use std::os; // FIXME(#2119): the outer attribute should be #[cfg(unix, test)], then // these redundant #[cfg(test)] blocks can be removed #[cfg(test)] #[cfg(test)] use back::rpath::{get_absolute_rpath, get_install_prefix_rpath}; use back::rpath::{get_relative_to, get_rpath_relative_to_output}; use back::rpath::{minimize_rpaths, rpaths_to_flags}; use driver::session; #[test] fn test_rpaths_to_flags() { let flags = rpaths_to_flags([Path("path1"), Path("path2")]); assert_eq!(flags, ~[~"-Wl,-rpath,path1", ~"-Wl,-rpath,path2"]); } #[test] fn test_prefix_rpath() { let res = get_install_prefix_rpath("triple"); let d = Path(env!("CFG_PREFIX")) .push_rel(&Path("lib/rustc/triple/lib")); debug!("test_prefix_path: %s vs. %s", res.to_str(), d.to_str()); assert!(res.to_str().ends_with(d.to_str())); } #[test] fn test_prefix_rpath_abs() { let res = get_install_prefix_rpath("triple"); assert!(res.is_absolute); } #[test] fn test_minimize1() { let res = minimize_rpaths([Path("rpath1"), Path("rpath2"), Path("rpath1")]); assert_eq!(res, ~[Path("rpath1"), Path("rpath2")]); } #[test] fn test_minimize2() { let res = minimize_rpaths([Path("1a"), Path("2"), Path("2"), Path("1a"), Path("4a"),Path("1a"), Path("2"), Path("3"), Path("4a"), Path("3")]); assert_eq!(res, ~[Path("1a"), Path("2"), Path("4a"), Path("3")]); } #[test] fn test_relative_to1() { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/lib/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to2() { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/bin/../lib/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to3() { let p1 = Path("/usr/bin/whatever/rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../../lib/whatever")); } #[test] fn test_relative_to4() { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib/whatever")); } #[test] fn test_relative_to5() { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/../mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to6() { let p1 = Path("/1"); let p2 = Path("/2/3"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("2")); } #[test] fn test_relative_to7() { let p1 = Path("/1/2"); let p2 = Path("/3"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("..")); } #[test] fn test_relative_to8() { let p1 = Path("/home/brian/Dev/rust/build/").push_rel( &Path("stage2/lib/rustc/i686-unknown-linux-gnu/lib/librustc.so")); let p2 = Path("/home/brian/Dev/rust/build/stage2/bin/..").push_rel( &Path("lib/rustc/i686-unknown-linux-gnu/lib/libstd.so")); let res = get_relative_to(&p1, &p2); debug!("test_relative_tu8: %s vs. %s", res.to_str(), Path(".").to_str()); assert_eq!(res, Path(".")); } #[test] #[cfg(target_os = "linux")] #[cfg(target_os = "andorid")] fn test_rpath_relative() { let o = session::os_linux; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] #[cfg(target_os = "freebsd")] fn test_rpath_relative() { let o = session::os_freebsd; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] #[cfg(target_os = "macos")] fn test_rpath_relative()
#[test] fn test_get_absolute_rpath() { let res = get_absolute_rpath(&Path("lib/libstd.so")); debug!("test_get_absolute_rpath: %s vs. %s", res.to_str(), os::make_absolute(&Path("lib")).to_str()); assert_eq!(res, os::make_absolute(&Path("lib"))); } }
{ // this is why refinements would be nice let o = session::os_macos; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"@executable_path/../lib"); }
identifier_body
rpath.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. use driver::session; use metadata::cstore; use metadata::filesearch; use std::hashmap::HashSet; use std::os; use std::uint; use std::util; use std::vec; fn not_win32(os: session::os) -> bool { os!= session::os_win32 } pub fn get_rpath_flags(sess: session::Session, out_filename: &Path) -> ~[~str] { let os = sess.targ_cfg.os; // No rpath on windows if os == session::os_win32 { return ~[]; } debug!("preparing the RPATH!"); let sysroot = sess.filesearch.sysroot(); let output = out_filename; let libs = cstore::get_used_crate_files(sess.cstore); // We don't currently rpath extern libraries, but we know // where rustrt is and we know every rust program needs it let libs = vec::append_one(libs, get_sysroot_absolute_rt_lib(sess)); let rpaths = get_rpaths(os, sysroot, output, libs, sess.opts.target_triple); rpaths_to_flags(rpaths) } fn get_sysroot_absolute_rt_lib(sess: session::Session) -> Path { let r = filesearch::relative_target_lib_path(sess.opts.target_triple); sess.filesearch.sysroot().push_rel(&r).push(os::dll_filename("rustrt")) } pub fn rpaths_to_flags(rpaths: &[Path]) -> ~[~str] { rpaths.iter().transform(|rpath| fmt!("-Wl,-rpath,%s",rpath.to_str())).collect() } fn get_rpaths(os: session::os, sysroot: &Path, output: &Path, libs: &[Path], target_triple: &str) -> ~[Path] { debug!("sysroot: %s", sysroot.to_str()); debug!("output: %s", output.to_str()); debug!("libs:"); for libs.iter().advance |libpath| { debug!(" %s", libpath.to_str()); } debug!("target_triple: %s", target_triple); // Use relative paths to the libraries. Binaries can be moved // as long as they maintain the relative relationship to the // crates they depend on. let rel_rpaths = get_rpaths_relative_to_output(os, output, libs); // Make backup absolute paths to the libraries. Binaries can // be moved as long as the crates they link against don't move. let abs_rpaths = get_absolute_rpaths(libs); // And a final backup rpath to the global library location. let fallback_rpaths = ~[get_install_prefix_rpath(target_triple)]; fn log_rpaths(desc: &str, rpaths: &[Path]) { debug!("%s rpaths:", desc); for rpaths.iter().advance |rpath| { debug!(" %s", rpath.to_str()); } } log_rpaths("relative", rel_rpaths); log_rpaths("absolute", abs_rpaths); log_rpaths("fallback", fallback_rpaths); let mut rpaths = rel_rpaths; rpaths.push_all(abs_rpaths); rpaths.push_all(fallback_rpaths); // Remove duplicates let rpaths = minimize_rpaths(rpaths); return rpaths; } fn get_rpaths_relative_to_output(os: session::os, output: &Path, libs: &[Path]) -> ~[Path] { libs.iter().transform(|a| get_rpath_relative_to_output(os, output, a)).collect() } pub fn get_rpath_relative_to_output(os: session::os, output: &Path, lib: &Path) -> Path { use std::os; assert!(not_win32(os)); // Mac doesn't appear to support $ORIGIN let prefix = match os { session::os_android | session::os_linux | session::os_freebsd => "$ORIGIN", session::os_macos => "@executable_path", session::os_win32 => util::unreachable() }; Path(prefix).push_rel(&get_relative_to(&os::make_absolute(output), &os::make_absolute(lib))) } // Find the relative path from one file to another pub fn get_relative_to(abs1: &Path, abs2: &Path) -> Path { assert!(abs1.is_absolute); assert!(abs2.is_absolute); let abs1 = abs1.normalize(); let abs2 = abs2.normalize(); debug!("finding relative path from %s to %s", abs1.to_str(), abs2.to_str()); let split1: &[~str] = abs1.components; let split2: &[~str] = abs2.components; let len1 = split1.len(); let len2 = split2.len(); assert!(len1 > 0); assert!(len2 > 0); let max_common_path = uint::min(len1, len2) - 1; let mut start_idx = 0; while start_idx < max_common_path && split1[start_idx] == split2[start_idx] { start_idx += 1; } let mut path = ~[]; for uint::range(start_idx, len1 - 1) |_i| { path.push(~".."); }; path.push_all(split2.slice(start_idx, len2 - 1)); return if!path.is_empty() { Path("").push_many(path) } else { Path(".") } } fn get_absolute_rpaths(libs: &[Path]) -> ~[Path] { libs.iter().transform(|a| get_absolute_rpath(a)).collect() } pub fn get_absolute_rpath(lib: &Path) -> Path { os::make_absolute(lib).dir_path() } pub fn get_install_prefix_rpath(target_triple: &str) -> Path { let install_prefix = env!("CFG_PREFIX"); if install_prefix == "" { fail!("rustc compiled without CFG_PREFIX environment variable"); } let tlib = filesearch::relative_target_lib_path(target_triple); os::make_absolute(&Path(install_prefix).push_rel(&tlib)) } pub fn minimize_rpaths(rpaths: &[Path]) -> ~[Path] { let mut set = HashSet::new(); let mut minimized = ~[]; for rpaths.iter().advance |rpath| { if set.insert(rpath.to_str()) { minimized.push(copy *rpath); } } minimized } #[cfg(unix, test)] mod test { use std::os; // FIXME(#2119): the outer attribute should be #[cfg(unix, test)], then // these redundant #[cfg(test)] blocks can be removed #[cfg(test)] #[cfg(test)] use back::rpath::{get_absolute_rpath, get_install_prefix_rpath}; use back::rpath::{get_relative_to, get_rpath_relative_to_output}; use back::rpath::{minimize_rpaths, rpaths_to_flags}; use driver::session; #[test] fn
() { let flags = rpaths_to_flags([Path("path1"), Path("path2")]); assert_eq!(flags, ~[~"-Wl,-rpath,path1", ~"-Wl,-rpath,path2"]); } #[test] fn test_prefix_rpath() { let res = get_install_prefix_rpath("triple"); let d = Path(env!("CFG_PREFIX")) .push_rel(&Path("lib/rustc/triple/lib")); debug!("test_prefix_path: %s vs. %s", res.to_str(), d.to_str()); assert!(res.to_str().ends_with(d.to_str())); } #[test] fn test_prefix_rpath_abs() { let res = get_install_prefix_rpath("triple"); assert!(res.is_absolute); } #[test] fn test_minimize1() { let res = minimize_rpaths([Path("rpath1"), Path("rpath2"), Path("rpath1")]); assert_eq!(res, ~[Path("rpath1"), Path("rpath2")]); } #[test] fn test_minimize2() { let res = minimize_rpaths([Path("1a"), Path("2"), Path("2"), Path("1a"), Path("4a"),Path("1a"), Path("2"), Path("3"), Path("4a"), Path("3")]); assert_eq!(res, ~[Path("1a"), Path("2"), Path("4a"), Path("3")]); } #[test] fn test_relative_to1() { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/lib/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to2() { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/bin/../lib/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to3() { let p1 = Path("/usr/bin/whatever/rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../../lib/whatever")); } #[test] fn test_relative_to4() { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib/whatever")); } #[test] fn test_relative_to5() { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/../mylib"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("../lib")); } #[test] fn test_relative_to6() { let p1 = Path("/1"); let p2 = Path("/2/3"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("2")); } #[test] fn test_relative_to7() { let p1 = Path("/1/2"); let p2 = Path("/3"); let res = get_relative_to(&p1, &p2); assert_eq!(res, Path("..")); } #[test] fn test_relative_to8() { let p1 = Path("/home/brian/Dev/rust/build/").push_rel( &Path("stage2/lib/rustc/i686-unknown-linux-gnu/lib/librustc.so")); let p2 = Path("/home/brian/Dev/rust/build/stage2/bin/..").push_rel( &Path("lib/rustc/i686-unknown-linux-gnu/lib/libstd.so")); let res = get_relative_to(&p1, &p2); debug!("test_relative_tu8: %s vs. %s", res.to_str(), Path(".").to_str()); assert_eq!(res, Path(".")); } #[test] #[cfg(target_os = "linux")] #[cfg(target_os = "andorid")] fn test_rpath_relative() { let o = session::os_linux; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] #[cfg(target_os = "freebsd")] fn test_rpath_relative() { let o = session::os_freebsd; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] #[cfg(target_os = "macos")] fn test_rpath_relative() { // this is why refinements would be nice let o = session::os_macos; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); assert_eq!(res.to_str(), ~"@executable_path/../lib"); } #[test] fn test_get_absolute_rpath() { let res = get_absolute_rpath(&Path("lib/libstd.so")); debug!("test_get_absolute_rpath: %s vs. %s", res.to_str(), os::make_absolute(&Path("lib")).to_str()); assert_eq!(res, os::make_absolute(&Path("lib"))); } }
test_rpaths_to_flags
identifier_name
binary_search.rs
fn main() { let nums = vec![1, 3, 5, 7, 9]; let find_me = 5; let result = binary_search(&nums, find_me, 0, nums.len()); println!("Given Array: {:?}", nums); match result { Some(index) => println!("Searched for {} and found index {}.", find_me, index), None => println!("Searched for {} but found no occurrence.", find_me), } }
fn binary_search(nums: &[i64], search_value: i64, left: usize, right: usize) -> Option<usize> { let mut left: usize = left; let mut right: usize = right; while left <= right { let middle = (left + right) / 2; if middle == nums.len() { break; } if nums[middle] == search_value { return Some(middle); } else if nums[middle] < search_value { left = middle + 1; } else if nums[middle] > search_value && middle!= 0 { right = middle - 1; } else { break; } } None }
random_line_split
binary_search.rs
fn main() { let nums = vec![1, 3, 5, 7, 9]; let find_me = 5; let result = binary_search(&nums, find_me, 0, nums.len()); println!("Given Array: {:?}", nums); match result { Some(index) => println!("Searched for {} and found index {}.", find_me, index), None => println!("Searched for {} but found no occurrence.", find_me), } } fn binary_search(nums: &[i64], search_value: i64, left: usize, right: usize) -> Option<usize> { let mut left: usize = left; let mut right: usize = right; while left <= right { let middle = (left + right) / 2; if middle == nums.len() { break; } if nums[middle] == search_value { return Some(middle); } else if nums[middle] < search_value
else if nums[middle] > search_value && middle!= 0 { right = middle - 1; } else { break; } } None }
{ left = middle + 1; }
conditional_block
binary_search.rs
fn main() { let nums = vec![1, 3, 5, 7, 9]; let find_me = 5; let result = binary_search(&nums, find_me, 0, nums.len()); println!("Given Array: {:?}", nums); match result { Some(index) => println!("Searched for {} and found index {}.", find_me, index), None => println!("Searched for {} but found no occurrence.", find_me), } } fn binary_search(nums: &[i64], search_value: i64, left: usize, right: usize) -> Option<usize>
} None }
{ let mut left: usize = left; let mut right: usize = right; while left <= right { let middle = (left + right) / 2; if middle == nums.len() { break; } if nums[middle] == search_value { return Some(middle); } else if nums[middle] < search_value { left = middle + 1; } else if nums[middle] > search_value && middle != 0 { right = middle - 1; } else { break; }
identifier_body
binary_search.rs
fn main() { let nums = vec![1, 3, 5, 7, 9]; let find_me = 5; let result = binary_search(&nums, find_me, 0, nums.len()); println!("Given Array: {:?}", nums); match result { Some(index) => println!("Searched for {} and found index {}.", find_me, index), None => println!("Searched for {} but found no occurrence.", find_me), } } fn
(nums: &[i64], search_value: i64, left: usize, right: usize) -> Option<usize> { let mut left: usize = left; let mut right: usize = right; while left <= right { let middle = (left + right) / 2; if middle == nums.len() { break; } if nums[middle] == search_value { return Some(middle); } else if nums[middle] < search_value { left = middle + 1; } else if nums[middle] > search_value && middle!= 0 { right = middle - 1; } else { break; } } None }
binary_search
identifier_name
audio.rs
use docopt::ArgvMap; use toml::{Value, ParserError}; use settings::Load; #[derive(Clone, Debug)] pub struct Audio { music: bool, only: bool, } impl Default for Audio { fn default() -> Audio { Audio { music: true, only: false, } } } impl Load for Audio { fn load(&mut self, args: &ArgvMap, toml: &Value) -> Result<(), ParserError>
self.music = false; } Ok(()) } } impl Audio { #[inline(always)] pub fn music(&self) -> bool { self.music } #[inline(always)] pub fn only(&self) -> bool { self.only } }
{ let toml = toml.as_table().unwrap(); if let Some(toml) = toml.get("audio") { let toml = expect!(toml.as_table(), "`audio` must be a table"); if let Some(value) = toml.get("only") { self.only = expect!(value.as_bool(), "`audio.only` must be a boolean"); } if let Some(value) = toml.get("music") { self.music = expect!(value.as_bool(), "`audio.music` must be a boolean"); } } if args.get_bool("--audio-only") { self.only = true; } if args.get_bool("--no-music") {
identifier_body
audio.rs
use docopt::ArgvMap; use toml::{Value, ParserError}; use settings::Load; #[derive(Clone, Debug)] pub struct Audio { music: bool, only: bool, } impl Default for Audio { fn default() -> Audio { Audio { music: true, only: false, } } } impl Load for Audio { fn load(&mut self, args: &ArgvMap, toml: &Value) -> Result<(), ParserError> { let toml = toml.as_table().unwrap(); if let Some(toml) = toml.get("audio") { let toml = expect!(toml.as_table(), "`audio` must be a table"); if let Some(value) = toml.get("only") { self.only = expect!(value.as_bool(), "`audio.only` must be a boolean"); } if let Some(value) = toml.get("music") { self.music = expect!(value.as_bool(), "`audio.music` must be a boolean"); } } if args.get_bool("--audio-only") { self.only = true; } if args.get_bool("--no-music") { self.music = false; } Ok(()) }
impl Audio { #[inline(always)] pub fn music(&self) -> bool { self.music } #[inline(always)] pub fn only(&self) -> bool { self.only } }
}
random_line_split
audio.rs
use docopt::ArgvMap; use toml::{Value, ParserError}; use settings::Load; #[derive(Clone, Debug)] pub struct
{ music: bool, only: bool, } impl Default for Audio { fn default() -> Audio { Audio { music: true, only: false, } } } impl Load for Audio { fn load(&mut self, args: &ArgvMap, toml: &Value) -> Result<(), ParserError> { let toml = toml.as_table().unwrap(); if let Some(toml) = toml.get("audio") { let toml = expect!(toml.as_table(), "`audio` must be a table"); if let Some(value) = toml.get("only") { self.only = expect!(value.as_bool(), "`audio.only` must be a boolean"); } if let Some(value) = toml.get("music") { self.music = expect!(value.as_bool(), "`audio.music` must be a boolean"); } } if args.get_bool("--audio-only") { self.only = true; } if args.get_bool("--no-music") { self.music = false; } Ok(()) } } impl Audio { #[inline(always)] pub fn music(&self) -> bool { self.music } #[inline(always)] pub fn only(&self) -> bool { self.only } }
Audio
identifier_name
audio.rs
use docopt::ArgvMap; use toml::{Value, ParserError}; use settings::Load; #[derive(Clone, Debug)] pub struct Audio { music: bool, only: bool, } impl Default for Audio { fn default() -> Audio { Audio { music: true, only: false, } } } impl Load for Audio { fn load(&mut self, args: &ArgvMap, toml: &Value) -> Result<(), ParserError> { let toml = toml.as_table().unwrap(); if let Some(toml) = toml.get("audio") { let toml = expect!(toml.as_table(), "`audio` must be a table"); if let Some(value) = toml.get("only") { self.only = expect!(value.as_bool(), "`audio.only` must be a boolean"); } if let Some(value) = toml.get("music") { self.music = expect!(value.as_bool(), "`audio.music` must be a boolean"); } } if args.get_bool("--audio-only")
if args.get_bool("--no-music") { self.music = false; } Ok(()) } } impl Audio { #[inline(always)] pub fn music(&self) -> bool { self.music } #[inline(always)] pub fn only(&self) -> bool { self.only } }
{ self.only = true; }
conditional_block
geniza.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::{Path, PathBuf}; use clap::{App, SubCommand}; use std::env::current_dir; use sodiumoxide::crypto::stream::Key; // Helper to find a dat directory somewhere in the parent to the current working directory (or None // if not found) fn find_dat_dir() -> Option<PathBuf>
fn run() -> Result<()> { env_logger::init().unwrap(); let matches = App::new("geniza") .version(env!("CARGO_PKG_VERSION")) .subcommand( SubCommand::with_name("clone") .about("Finds and downloads a dat archive from the network into a given folder") .arg_from_usage("<address> 'dat address (public key) to fetch'") .arg_from_usage("[dir] 'directory to clone into'") .arg_from_usage("--full 'pull and save complete history (not just latest version)'"), ) .subcommand( SubCommand::with_name("init") .about("Creates a data archive in the current directory") .arg_from_usage("[dir] 'init somewhere other than current directory'"), ) .subcommand( SubCommand::with_name("status") .about("Displays current status of archive and checkout") ) .subcommand( SubCommand::with_name("log") .about("Displays version history of the archive") ) .subcommand( SubCommand::with_name("checkout") .about("Copies (or overwrites) files from dat archive") .arg_from_usage("<path>'relative path to checkout'"), ) .subcommand( SubCommand::with_name("add") .about("Adds a path to the current dat archive") .arg_from_usage("<path> 'file to delete from dat archive'"), ) .subcommand( SubCommand::with_name("rm") .about("Removes a path from the current dat archive, and from disk (danger!)") .arg_from_usage("<path> 'file to delete from dat archive'"), ) .subcommand( SubCommand::with_name("ls") .about("Lists contents of the archive") .arg_from_usage("[path] 'path to display'") .arg_from_usage("--recursive'show directory recursively'"), ) .subcommand( SubCommand::with_name("seed") .about("Uploads indefinately to any peer") ) .subcommand( SubCommand::with_name("pull") .about("Pulls highest known version from all possible peers") .arg_from_usage("--forever 'continues to search for updates forever'"), ) .get_matches(); match matches.subcommand() { ("clone", Some(subm)) => { let dat_key = subm.value_of("address").unwrap(); let key_bytes = parse_dat_address(&dat_key)?; let key = Key::from_slice(&key_bytes).unwrap(); let dir = Path::new(subm.value_of("dir").unwrap()); let mut sync = Synchronizer::new_downloader(key, SyncMode::RxMax, dir)?; let peer_count = sync.discover()?; println!("Found {} potential peers", peer_count); sync.run()?; } ("init", Some(subm)) => { let _dir = Path::new(subm.value_of("dir").unwrap()); unimplemented!(); } ("status", Some(_subm)) => { unimplemented!(); } ("log", Some(_subm)) => { let dat_dir = match find_dat_dir() { Some(p) => p, None => { println!("Couldn't find '.dat/' in the current or (any parent) directory."); println!("Are you running from inside a Dat archive?"); ::std::process::exit(-1); } }; println!("{:?}", dat_dir); let mut drive = DatDrive::open(dat_dir, false)?; for entry in drive.history(0) { let entry = entry?; if let Some(stat) = entry.stat { if stat.get_blocks() == 0 { println!("{}\t[chg] {}", entry.index, entry.path.display()); } else { println!("{}\t[put] {}\t{} bytes ({} blocks)", entry.index, entry.path.display(), stat.get_size(), stat.get_blocks()); } } else { println!("{}\t[del] {}", entry.index, entry.path.display()); } } } ("checkout", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("add", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("rm", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("ls", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("seed", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("pull", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } _ => { println!("Missing or unimplemented command!"); println!("{}", matches.usage()); ::std::process::exit(-1); } } Ok(()) } quick_main!(run);
{ let mut here: &Path = &current_dir().unwrap(); loop { let check = here.join(".dat"); if check.is_dir() && check.join("metadata.tree").is_file() { return Some(check); }; here = match here.parent() { None => return None, Some(t) => t, } } }
identifier_body
geniza.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::{Path, PathBuf}; use clap::{App, SubCommand}; use std::env::current_dir; use sodiumoxide::crypto::stream::Key; // Helper to find a dat directory somewhere in the parent to the current working directory (or None // if not found) fn
() -> Option<PathBuf> { let mut here: &Path = &current_dir().unwrap(); loop { let check = here.join(".dat"); if check.is_dir() && check.join("metadata.tree").is_file() { return Some(check); }; here = match here.parent() { None => return None, Some(t) => t, } } } fn run() -> Result<()> { env_logger::init().unwrap(); let matches = App::new("geniza") .version(env!("CARGO_PKG_VERSION")) .subcommand( SubCommand::with_name("clone") .about("Finds and downloads a dat archive from the network into a given folder") .arg_from_usage("<address> 'dat address (public key) to fetch'") .arg_from_usage("[dir] 'directory to clone into'") .arg_from_usage("--full 'pull and save complete history (not just latest version)'"), ) .subcommand( SubCommand::with_name("init") .about("Creates a data archive in the current directory") .arg_from_usage("[dir] 'init somewhere other than current directory'"), ) .subcommand( SubCommand::with_name("status") .about("Displays current status of archive and checkout") ) .subcommand( SubCommand::with_name("log") .about("Displays version history of the archive") ) .subcommand( SubCommand::with_name("checkout") .about("Copies (or overwrites) files from dat archive") .arg_from_usage("<path>'relative path to checkout'"), ) .subcommand( SubCommand::with_name("add") .about("Adds a path to the current dat archive") .arg_from_usage("<path> 'file to delete from dat archive'"), ) .subcommand( SubCommand::with_name("rm") .about("Removes a path from the current dat archive, and from disk (danger!)") .arg_from_usage("<path> 'file to delete from dat archive'"), ) .subcommand( SubCommand::with_name("ls") .about("Lists contents of the archive") .arg_from_usage("[path] 'path to display'") .arg_from_usage("--recursive'show directory recursively'"), ) .subcommand( SubCommand::with_name("seed") .about("Uploads indefinately to any peer") ) .subcommand( SubCommand::with_name("pull") .about("Pulls highest known version from all possible peers") .arg_from_usage("--forever 'continues to search for updates forever'"), ) .get_matches(); match matches.subcommand() { ("clone", Some(subm)) => { let dat_key = subm.value_of("address").unwrap(); let key_bytes = parse_dat_address(&dat_key)?; let key = Key::from_slice(&key_bytes).unwrap(); let dir = Path::new(subm.value_of("dir").unwrap()); let mut sync = Synchronizer::new_downloader(key, SyncMode::RxMax, dir)?; let peer_count = sync.discover()?; println!("Found {} potential peers", peer_count); sync.run()?; } ("init", Some(subm)) => { let _dir = Path::new(subm.value_of("dir").unwrap()); unimplemented!(); } ("status", Some(_subm)) => { unimplemented!(); } ("log", Some(_subm)) => { let dat_dir = match find_dat_dir() { Some(p) => p, None => { println!("Couldn't find '.dat/' in the current or (any parent) directory."); println!("Are you running from inside a Dat archive?"); ::std::process::exit(-1); } }; println!("{:?}", dat_dir); let mut drive = DatDrive::open(dat_dir, false)?; for entry in drive.history(0) { let entry = entry?; if let Some(stat) = entry.stat { if stat.get_blocks() == 0 { println!("{}\t[chg] {}", entry.index, entry.path.display()); } else { println!("{}\t[put] {}\t{} bytes ({} blocks)", entry.index, entry.path.display(), stat.get_size(), stat.get_blocks()); } } else { println!("{}\t[del] {}", entry.index, entry.path.display()); } } } ("checkout", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("add", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("rm", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("ls", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("seed", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("pull", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } _ => { println!("Missing or unimplemented command!"); println!("{}", matches.usage()); ::std::process::exit(-1); } } Ok(()) } quick_main!(run);
find_dat_dir
identifier_name
geniza.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::{Path, PathBuf}; use clap::{App, SubCommand}; use std::env::current_dir; use sodiumoxide::crypto::stream::Key; // Helper to find a dat directory somewhere in the parent to the current working directory (or None // if not found) fn find_dat_dir() -> Option<PathBuf> { let mut here: &Path = &current_dir().unwrap(); loop { let check = here.join(".dat"); if check.is_dir() && check.join("metadata.tree").is_file() { return Some(check); }; here = match here.parent() { None => return None, Some(t) => t, } } } fn run() -> Result<()> { env_logger::init().unwrap(); let matches = App::new("geniza") .version(env!("CARGO_PKG_VERSION")) .subcommand( SubCommand::with_name("clone") .about("Finds and downloads a dat archive from the network into a given folder") .arg_from_usage("<address> 'dat address (public key) to fetch'") .arg_from_usage("[dir] 'directory to clone into'") .arg_from_usage("--full 'pull and save complete history (not just latest version)'"), ) .subcommand( SubCommand::with_name("init") .about("Creates a data archive in the current directory") .arg_from_usage("[dir] 'init somewhere other than current directory'"), ) .subcommand( SubCommand::with_name("status") .about("Displays current status of archive and checkout") ) .subcommand( SubCommand::with_name("log") .about("Displays version history of the archive") ) .subcommand( SubCommand::with_name("checkout") .about("Copies (or overwrites) files from dat archive") .arg_from_usage("<path>'relative path to checkout'"), ) .subcommand( SubCommand::with_name("add") .about("Adds a path to the current dat archive") .arg_from_usage("<path> 'file to delete from dat archive'"), ) .subcommand( SubCommand::with_name("rm") .about("Removes a path from the current dat archive, and from disk (danger!)")
.subcommand( SubCommand::with_name("ls") .about("Lists contents of the archive") .arg_from_usage("[path] 'path to display'") .arg_from_usage("--recursive'show directory recursively'"), ) .subcommand( SubCommand::with_name("seed") .about("Uploads indefinately to any peer") ) .subcommand( SubCommand::with_name("pull") .about("Pulls highest known version from all possible peers") .arg_from_usage("--forever 'continues to search for updates forever'"), ) .get_matches(); match matches.subcommand() { ("clone", Some(subm)) => { let dat_key = subm.value_of("address").unwrap(); let key_bytes = parse_dat_address(&dat_key)?; let key = Key::from_slice(&key_bytes).unwrap(); let dir = Path::new(subm.value_of("dir").unwrap()); let mut sync = Synchronizer::new_downloader(key, SyncMode::RxMax, dir)?; let peer_count = sync.discover()?; println!("Found {} potential peers", peer_count); sync.run()?; } ("init", Some(subm)) => { let _dir = Path::new(subm.value_of("dir").unwrap()); unimplemented!(); } ("status", Some(_subm)) => { unimplemented!(); } ("log", Some(_subm)) => { let dat_dir = match find_dat_dir() { Some(p) => p, None => { println!("Couldn't find '.dat/' in the current or (any parent) directory."); println!("Are you running from inside a Dat archive?"); ::std::process::exit(-1); } }; println!("{:?}", dat_dir); let mut drive = DatDrive::open(dat_dir, false)?; for entry in drive.history(0) { let entry = entry?; if let Some(stat) = entry.stat { if stat.get_blocks() == 0 { println!("{}\t[chg] {}", entry.index, entry.path.display()); } else { println!("{}\t[put] {}\t{} bytes ({} blocks)", entry.index, entry.path.display(), stat.get_size(), stat.get_blocks()); } } else { println!("{}\t[del] {}", entry.index, entry.path.display()); } } } ("checkout", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("add", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("rm", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("ls", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("seed", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("pull", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } _ => { println!("Missing or unimplemented command!"); println!("{}", matches.usage()); ::std::process::exit(-1); } } Ok(()) } quick_main!(run);
.arg_from_usage("<path> 'file to delete from dat archive'"), )
random_line_split
geniza.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::{Path, PathBuf}; use clap::{App, SubCommand}; use std::env::current_dir; use sodiumoxide::crypto::stream::Key; // Helper to find a dat directory somewhere in the parent to the current working directory (or None // if not found) fn find_dat_dir() -> Option<PathBuf> { let mut here: &Path = &current_dir().unwrap(); loop { let check = here.join(".dat"); if check.is_dir() && check.join("metadata.tree").is_file() { return Some(check); }; here = match here.parent() { None => return None, Some(t) => t, } } } fn run() -> Result<()> { env_logger::init().unwrap(); let matches = App::new("geniza") .version(env!("CARGO_PKG_VERSION")) .subcommand( SubCommand::with_name("clone") .about("Finds and downloads a dat archive from the network into a given folder") .arg_from_usage("<address> 'dat address (public key) to fetch'") .arg_from_usage("[dir] 'directory to clone into'") .arg_from_usage("--full 'pull and save complete history (not just latest version)'"), ) .subcommand( SubCommand::with_name("init") .about("Creates a data archive in the current directory") .arg_from_usage("[dir] 'init somewhere other than current directory'"), ) .subcommand( SubCommand::with_name("status") .about("Displays current status of archive and checkout") ) .subcommand( SubCommand::with_name("log") .about("Displays version history of the archive") ) .subcommand( SubCommand::with_name("checkout") .about("Copies (or overwrites) files from dat archive") .arg_from_usage("<path>'relative path to checkout'"), ) .subcommand( SubCommand::with_name("add") .about("Adds a path to the current dat archive") .arg_from_usage("<path> 'file to delete from dat archive'"), ) .subcommand( SubCommand::with_name("rm") .about("Removes a path from the current dat archive, and from disk (danger!)") .arg_from_usage("<path> 'file to delete from dat archive'"), ) .subcommand( SubCommand::with_name("ls") .about("Lists contents of the archive") .arg_from_usage("[path] 'path to display'") .arg_from_usage("--recursive'show directory recursively'"), ) .subcommand( SubCommand::with_name("seed") .about("Uploads indefinately to any peer") ) .subcommand( SubCommand::with_name("pull") .about("Pulls highest known version from all possible peers") .arg_from_usage("--forever 'continues to search for updates forever'"), ) .get_matches(); match matches.subcommand() { ("clone", Some(subm)) => { let dat_key = subm.value_of("address").unwrap(); let key_bytes = parse_dat_address(&dat_key)?; let key = Key::from_slice(&key_bytes).unwrap(); let dir = Path::new(subm.value_of("dir").unwrap()); let mut sync = Synchronizer::new_downloader(key, SyncMode::RxMax, dir)?; let peer_count = sync.discover()?; println!("Found {} potential peers", peer_count); sync.run()?; } ("init", Some(subm)) => { let _dir = Path::new(subm.value_of("dir").unwrap()); unimplemented!(); } ("status", Some(_subm)) => { unimplemented!(); } ("log", Some(_subm)) => { let dat_dir = match find_dat_dir() { Some(p) => p, None => { println!("Couldn't find '.dat/' in the current or (any parent) directory."); println!("Are you running from inside a Dat archive?"); ::std::process::exit(-1); } }; println!("{:?}", dat_dir); let mut drive = DatDrive::open(dat_dir, false)?; for entry in drive.history(0) { let entry = entry?; if let Some(stat) = entry.stat
else { println!("{}\t[del] {}", entry.index, entry.path.display()); } } } ("checkout", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("add", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("rm", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("ls", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("seed", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } ("pull", Some(subm)) => { let _path = Path::new(subm.value_of("path").unwrap()); unimplemented!(); } _ => { println!("Missing or unimplemented command!"); println!("{}", matches.usage()); ::std::process::exit(-1); } } Ok(()) } quick_main!(run);
{ if stat.get_blocks() == 0 { println!("{}\t[chg] {}", entry.index, entry.path.display()); } else { println!("{}\t[put] {}\t{} bytes ({} blocks)", entry.index, entry.path.display(), stat.get_size(), stat.get_blocks()); } }
conditional_block
serviceworkerjob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A Job is an abstraction of async operation in service worker lifecycle propagation. //! Each Job is uniquely identified by its scope_url, and is keyed accordingly under //! the script thread. The script thread contains a JobQueue, which stores all scheduled Jobs //! by multiple service worker clients in a Vec. use dom::bindings::cell::DOMRefCell; use dom::bindings::error::Error; use dom::bindings::js::JS; use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::reflector::DomObject; use dom::client::Client; use dom::promise::Promise; use dom::serviceworkerregistration::ServiceWorkerRegistration; use dom::urlhelper::UrlHelper; use script_thread::ScriptThread; use servo_url::ServoUrl; use std::cmp::PartialEq; use std::collections::HashMap; use std::rc::Rc; use task_source::TaskSource; use task_source::dom_manipulation::DOMManipulationTaskSource; #[derive(Clone, Copy, Debug, JSTraceable, PartialEq)] pub enum JobType { Register, Unregister, Update } #[derive(Clone)] pub enum SettleType { Resolve(Trusted<ServiceWorkerRegistration>), Reject(Error) } #[must_root] #[derive(JSTraceable)] pub struct Job { pub job_type: JobType, pub scope_url: ServoUrl, pub script_url: ServoUrl, pub promise: Rc<Promise>, pub equivalent_jobs: Vec<Job>, // client can be a window client, worker client so `Client` will be an enum in future pub client: JS<Client>, pub referrer: ServoUrl } impl Job { #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#create-job-algorithm pub fn create_job(job_type: JobType, scope_url: ServoUrl, script_url: ServoUrl, promise: Rc<Promise>, client: &Client) -> Job { Job { job_type: job_type, scope_url: scope_url, script_url: script_url, promise: promise, equivalent_jobs: vec![], client: JS::from_ref(client), referrer: client.creation_url() } } #[allow(unrooted_must_root)] pub fn append_equivalent_job(&mut self, job: Job) { self.equivalent_jobs.push(job); } } impl PartialEq for Job { // Equality criteria as described in https://w3c.github.io/ServiceWorker/#dfn-job-equivalent fn eq(&self, other: &Self) -> bool { let same_job = self.job_type == other.job_type; if same_job { match self.job_type { JobType::Register | JobType::Update => { self.scope_url == other.scope_url && self.script_url == other.script_url }, JobType::Unregister => self.scope_url == other.scope_url } } else { false } } } #[must_root] #[derive(JSTraceable)] pub struct JobQueue(pub DOMRefCell<HashMap<ServoUrl, Vec<Job>>>); impl JobQueue { pub fn new() -> JobQueue { JobQueue(DOMRefCell::new(HashMap::new())) } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#schedule-job-algorithm pub fn
(&self, job: Job, script_thread: &ScriptThread) { debug!("scheduling {:?} job", job.job_type); let mut queue_ref = self.0.borrow_mut(); let job_queue = queue_ref.entry(job.scope_url.clone()).or_insert(vec![]); // Step 1 if job_queue.is_empty() { let scope_url = job.scope_url.clone(); job_queue.push(job); let _ = script_thread.schedule_job_queue(scope_url); debug!("queued task to run newly-queued job"); } else { // Step 2 let mut last_job = job_queue.pop().unwrap(); if job == last_job &&!last_job.promise.is_fulfilled() { last_job.append_equivalent_job(job); job_queue.push(last_job); debug!("appended equivalent job"); } else { // restore the popped last_job job_queue.push(last_job); // and push this new job to job queue job_queue.push(job); debug!("pushed onto job queue job"); } } } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#run-job-algorithm pub fn run_job(&self, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("running a job"); let url = { let queue_ref = self.0.borrow(); let front_job = { let job_vec = queue_ref.get(&scope_url); job_vec.unwrap().first().unwrap() }; let front_scope_url = front_job.scope_url.clone(); match front_job.job_type { JobType::Register => self.run_register(front_job, scope_url, script_thread), JobType::Update => self.update(front_job, script_thread), JobType::Unregister => unreachable!(), }; front_scope_url }; self.finish_job(url, script_thread); } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#register-algorithm fn run_register(&self, job: &Job, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("running register job"); // Step 1-3 if!UrlHelper::is_origin_trustworthy(&job.script_url) { // Step 1.1 reject_job_promise(job, Error::Type("Invalid script ServoURL".to_owned()), script_thread.dom_manipulation_task_source()); // Step 1.2 (see run_job) return; } else if job.script_url.origin()!= job.referrer.origin() || job.scope_url.origin()!= job.referrer.origin() { // Step 2.1/3.1 reject_job_promise(job, Error::Security, script_thread.dom_manipulation_task_source()); // Step 2.2/3.2 (see run_job) return; } // Step 4-5 if let Some(reg) = script_thread.handle_get_registration(&job.scope_url) { // Step 5.1 if reg.get_uninstalling() { reg.set_uninstalling(false); } // Step 5.3 if let Some(ref newest_worker) = reg.get_newest_worker() { if (&*newest_worker).get_script_url() == job.script_url { // Step 5.3.1 resolve_job_promise(job, &*reg, script_thread.dom_manipulation_task_source()); // Step 5.3.2 (see run_job) return; } } } else { // Step 6.1 let global = &*job.client.global(); let pipeline = global.pipeline_id(); let new_reg = ServiceWorkerRegistration::new(&*global, &job.script_url, scope_url); script_thread.handle_serviceworker_registration(&job.scope_url, &*new_reg, pipeline); } // Step 7 self.update(job, script_thread) } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#finish-job-algorithm pub fn finish_job(&self, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("finishing previous job"); let run_job = if let Some(job_vec) = (*self.0.borrow_mut()).get_mut(&scope_url) { assert_eq!(job_vec.first().as_ref().unwrap().scope_url, scope_url); let _ = job_vec.remove(0); !job_vec.is_empty() } else { warn!("non-existent job vector for Servourl: {:?}", scope_url); false }; if run_job { debug!("further jobs in queue after finishing"); self.run_job(scope_url, script_thread); } } // https://w3c.github.io/ServiceWorker/#update-algorithm fn update(&self, job: &Job, script_thread: &ScriptThread) { debug!("running update job"); // Step 1 let reg = match script_thread.handle_get_registration(&job.scope_url) { Some(reg) => reg, None => { let err_type = Error::Type("No registration to update".to_owned()); // Step 2.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 2.2 (see run_job) return; } }; // Step 2 if reg.get_uninstalling() { let err_type = Error::Type("Update called on an uninstalling registration".to_owned()); // Step 2.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 2.2 (see run_job) return; } // Step 3 let newest_worker = reg.get_newest_worker(); let newest_worker_url = newest_worker.as_ref().map(|w| w.get_script_url()); // Step 4 if newest_worker_url.as_ref() == Some(&job.script_url) && job.job_type == JobType::Update { let err_type = Error::Type("Invalid script ServoURL".to_owned()); // Step 4.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 4.2 (see run_job) return; } // Step 8 if let Some(newest_worker) = newest_worker { job.client.set_controller(&*newest_worker); // Step 8.1 resolve_job_promise(job, &*reg, script_thread.dom_manipulation_task_source()); // Step 8.2 present in run_job } // TODO Step 9 (create new service worker) } } fn settle_job_promise(promise: &Promise, settle: SettleType) { match settle { SettleType::Resolve(reg) => promise.resolve_native(&*reg.root()), SettleType::Reject(err) => promise.reject_error(err), }; } #[allow(unrooted_must_root)] fn queue_settle_promise_for_job(job: &Job, settle: SettleType, task_source: &DOMManipulationTaskSource) { let global = job.client.global(); let promise = TrustedPromise::new(job.promise.clone()); // FIXME(nox): Why are errors silenced here? let _ = task_source.queue( task!(settle_promise_for_job: move || { let promise = promise.root(); settle_job_promise(&promise, settle) }), &*global, ); } // https://w3c.github.io/ServiceWorker/#reject-job-promise-algorithm // https://w3c.github.io/ServiceWorker/#resolve-job-promise-algorithm fn queue_settle_promise(job: &Job, settle: SettleType, task_source: &DOMManipulationTaskSource) { // Step 1 queue_settle_promise_for_job(job, settle.clone(), task_source); // Step 2 for job in &job.equivalent_jobs { queue_settle_promise_for_job(job, settle.clone(), task_source); } } fn reject_job_promise(job: &Job, err: Error, task_source: &DOMManipulationTaskSource) { queue_settle_promise(job, SettleType::Reject(err), task_source) } fn resolve_job_promise(job: &Job, reg: &ServiceWorkerRegistration, task_source: &DOMManipulationTaskSource) { queue_settle_promise(job, SettleType::Resolve(Trusted::new(reg)), task_source) }
schedule_job
identifier_name
serviceworkerjob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A Job is an abstraction of async operation in service worker lifecycle propagation. //! Each Job is uniquely identified by its scope_url, and is keyed accordingly under //! the script thread. The script thread contains a JobQueue, which stores all scheduled Jobs //! by multiple service worker clients in a Vec. use dom::bindings::cell::DOMRefCell; use dom::bindings::error::Error; use dom::bindings::js::JS; use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::reflector::DomObject; use dom::client::Client; use dom::promise::Promise; use dom::serviceworkerregistration::ServiceWorkerRegistration; use dom::urlhelper::UrlHelper; use script_thread::ScriptThread; use servo_url::ServoUrl; use std::cmp::PartialEq; use std::collections::HashMap; use std::rc::Rc; use task_source::TaskSource; use task_source::dom_manipulation::DOMManipulationTaskSource; #[derive(Clone, Copy, Debug, JSTraceable, PartialEq)] pub enum JobType { Register, Unregister, Update } #[derive(Clone)] pub enum SettleType { Resolve(Trusted<ServiceWorkerRegistration>), Reject(Error) } #[must_root] #[derive(JSTraceable)] pub struct Job { pub job_type: JobType, pub scope_url: ServoUrl, pub script_url: ServoUrl, pub promise: Rc<Promise>, pub equivalent_jobs: Vec<Job>, // client can be a window client, worker client so `Client` will be an enum in future pub client: JS<Client>, pub referrer: ServoUrl } impl Job { #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#create-job-algorithm pub fn create_job(job_type: JobType, scope_url: ServoUrl, script_url: ServoUrl, promise: Rc<Promise>, client: &Client) -> Job { Job { job_type: job_type, scope_url: scope_url, script_url: script_url, promise: promise, equivalent_jobs: vec![], client: JS::from_ref(client), referrer: client.creation_url() } } #[allow(unrooted_must_root)] pub fn append_equivalent_job(&mut self, job: Job) { self.equivalent_jobs.push(job); } } impl PartialEq for Job { // Equality criteria as described in https://w3c.github.io/ServiceWorker/#dfn-job-equivalent fn eq(&self, other: &Self) -> bool { let same_job = self.job_type == other.job_type; if same_job { match self.job_type { JobType::Register | JobType::Update => { self.scope_url == other.scope_url && self.script_url == other.script_url }, JobType::Unregister => self.scope_url == other.scope_url } } else { false } } } #[must_root] #[derive(JSTraceable)] pub struct JobQueue(pub DOMRefCell<HashMap<ServoUrl, Vec<Job>>>); impl JobQueue { pub fn new() -> JobQueue { JobQueue(DOMRefCell::new(HashMap::new())) } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#schedule-job-algorithm pub fn schedule_job(&self, job: Job, script_thread: &ScriptThread) { debug!("scheduling {:?} job", job.job_type); let mut queue_ref = self.0.borrow_mut(); let job_queue = queue_ref.entry(job.scope_url.clone()).or_insert(vec![]); // Step 1 if job_queue.is_empty() { let scope_url = job.scope_url.clone(); job_queue.push(job); let _ = script_thread.schedule_job_queue(scope_url); debug!("queued task to run newly-queued job"); } else { // Step 2 let mut last_job = job_queue.pop().unwrap(); if job == last_job &&!last_job.promise.is_fulfilled() { last_job.append_equivalent_job(job); job_queue.push(last_job); debug!("appended equivalent job"); } else { // restore the popped last_job job_queue.push(last_job); // and push this new job to job queue job_queue.push(job); debug!("pushed onto job queue job"); } } } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#run-job-algorithm pub fn run_job(&self, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("running a job"); let url = { let queue_ref = self.0.borrow(); let front_job = { let job_vec = queue_ref.get(&scope_url); job_vec.unwrap().first().unwrap() }; let front_scope_url = front_job.scope_url.clone(); match front_job.job_type { JobType::Register => self.run_register(front_job, scope_url, script_thread), JobType::Update => self.update(front_job, script_thread), JobType::Unregister => unreachable!(), }; front_scope_url }; self.finish_job(url, script_thread); } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#register-algorithm fn run_register(&self, job: &Job, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("running register job"); // Step 1-3 if!UrlHelper::is_origin_trustworthy(&job.script_url) { // Step 1.1 reject_job_promise(job, Error::Type("Invalid script ServoURL".to_owned()), script_thread.dom_manipulation_task_source()); // Step 1.2 (see run_job) return; } else if job.script_url.origin()!= job.referrer.origin() || job.scope_url.origin()!= job.referrer.origin() { // Step 2.1/3.1 reject_job_promise(job, Error::Security, script_thread.dom_manipulation_task_source()); // Step 2.2/3.2 (see run_job) return; } // Step 4-5 if let Some(reg) = script_thread.handle_get_registration(&job.scope_url)
else { // Step 6.1 let global = &*job.client.global(); let pipeline = global.pipeline_id(); let new_reg = ServiceWorkerRegistration::new(&*global, &job.script_url, scope_url); script_thread.handle_serviceworker_registration(&job.scope_url, &*new_reg, pipeline); } // Step 7 self.update(job, script_thread) } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#finish-job-algorithm pub fn finish_job(&self, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("finishing previous job"); let run_job = if let Some(job_vec) = (*self.0.borrow_mut()).get_mut(&scope_url) { assert_eq!(job_vec.first().as_ref().unwrap().scope_url, scope_url); let _ = job_vec.remove(0); !job_vec.is_empty() } else { warn!("non-existent job vector for Servourl: {:?}", scope_url); false }; if run_job { debug!("further jobs in queue after finishing"); self.run_job(scope_url, script_thread); } } // https://w3c.github.io/ServiceWorker/#update-algorithm fn update(&self, job: &Job, script_thread: &ScriptThread) { debug!("running update job"); // Step 1 let reg = match script_thread.handle_get_registration(&job.scope_url) { Some(reg) => reg, None => { let err_type = Error::Type("No registration to update".to_owned()); // Step 2.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 2.2 (see run_job) return; } }; // Step 2 if reg.get_uninstalling() { let err_type = Error::Type("Update called on an uninstalling registration".to_owned()); // Step 2.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 2.2 (see run_job) return; } // Step 3 let newest_worker = reg.get_newest_worker(); let newest_worker_url = newest_worker.as_ref().map(|w| w.get_script_url()); // Step 4 if newest_worker_url.as_ref() == Some(&job.script_url) && job.job_type == JobType::Update { let err_type = Error::Type("Invalid script ServoURL".to_owned()); // Step 4.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 4.2 (see run_job) return; } // Step 8 if let Some(newest_worker) = newest_worker { job.client.set_controller(&*newest_worker); // Step 8.1 resolve_job_promise(job, &*reg, script_thread.dom_manipulation_task_source()); // Step 8.2 present in run_job } // TODO Step 9 (create new service worker) } } fn settle_job_promise(promise: &Promise, settle: SettleType) { match settle { SettleType::Resolve(reg) => promise.resolve_native(&*reg.root()), SettleType::Reject(err) => promise.reject_error(err), }; } #[allow(unrooted_must_root)] fn queue_settle_promise_for_job(job: &Job, settle: SettleType, task_source: &DOMManipulationTaskSource) { let global = job.client.global(); let promise = TrustedPromise::new(job.promise.clone()); // FIXME(nox): Why are errors silenced here? let _ = task_source.queue( task!(settle_promise_for_job: move || { let promise = promise.root(); settle_job_promise(&promise, settle) }), &*global, ); } // https://w3c.github.io/ServiceWorker/#reject-job-promise-algorithm // https://w3c.github.io/ServiceWorker/#resolve-job-promise-algorithm fn queue_settle_promise(job: &Job, settle: SettleType, task_source: &DOMManipulationTaskSource) { // Step 1 queue_settle_promise_for_job(job, settle.clone(), task_source); // Step 2 for job in &job.equivalent_jobs { queue_settle_promise_for_job(job, settle.clone(), task_source); } } fn reject_job_promise(job: &Job, err: Error, task_source: &DOMManipulationTaskSource) { queue_settle_promise(job, SettleType::Reject(err), task_source) } fn resolve_job_promise(job: &Job, reg: &ServiceWorkerRegistration, task_source: &DOMManipulationTaskSource) { queue_settle_promise(job, SettleType::Resolve(Trusted::new(reg)), task_source) }
{ // Step 5.1 if reg.get_uninstalling() { reg.set_uninstalling(false); } // Step 5.3 if let Some(ref newest_worker) = reg.get_newest_worker() { if (&*newest_worker).get_script_url() == job.script_url { // Step 5.3.1 resolve_job_promise(job, &*reg, script_thread.dom_manipulation_task_source()); // Step 5.3.2 (see run_job) return; } } }
conditional_block
serviceworkerjob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A Job is an abstraction of async operation in service worker lifecycle propagation. //! Each Job is uniquely identified by its scope_url, and is keyed accordingly under //! the script thread. The script thread contains a JobQueue, which stores all scheduled Jobs //! by multiple service worker clients in a Vec. use dom::bindings::cell::DOMRefCell; use dom::bindings::error::Error; use dom::bindings::js::JS; use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::reflector::DomObject; use dom::client::Client; use dom::promise::Promise; use dom::serviceworkerregistration::ServiceWorkerRegistration; use dom::urlhelper::UrlHelper; use script_thread::ScriptThread; use servo_url::ServoUrl; use std::cmp::PartialEq; use std::collections::HashMap; use std::rc::Rc; use task_source::TaskSource; use task_source::dom_manipulation::DOMManipulationTaskSource; #[derive(Clone, Copy, Debug, JSTraceable, PartialEq)] pub enum JobType { Register, Unregister, Update } #[derive(Clone)] pub enum SettleType { Resolve(Trusted<ServiceWorkerRegistration>), Reject(Error) } #[must_root] #[derive(JSTraceable)] pub struct Job { pub job_type: JobType, pub scope_url: ServoUrl, pub script_url: ServoUrl, pub promise: Rc<Promise>, pub equivalent_jobs: Vec<Job>, // client can be a window client, worker client so `Client` will be an enum in future pub client: JS<Client>, pub referrer: ServoUrl } impl Job { #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#create-job-algorithm pub fn create_job(job_type: JobType, scope_url: ServoUrl, script_url: ServoUrl, promise: Rc<Promise>, client: &Client) -> Job { Job { job_type: job_type, scope_url: scope_url, script_url: script_url, promise: promise, equivalent_jobs: vec![], client: JS::from_ref(client), referrer: client.creation_url() } } #[allow(unrooted_must_root)] pub fn append_equivalent_job(&mut self, job: Job) { self.equivalent_jobs.push(job); } } impl PartialEq for Job { // Equality criteria as described in https://w3c.github.io/ServiceWorker/#dfn-job-equivalent fn eq(&self, other: &Self) -> bool { let same_job = self.job_type == other.job_type; if same_job { match self.job_type { JobType::Register | JobType::Update => { self.scope_url == other.scope_url && self.script_url == other.script_url }, JobType::Unregister => self.scope_url == other.scope_url } } else { false } } } #[must_root] #[derive(JSTraceable)] pub struct JobQueue(pub DOMRefCell<HashMap<ServoUrl, Vec<Job>>>); impl JobQueue { pub fn new() -> JobQueue { JobQueue(DOMRefCell::new(HashMap::new())) } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#schedule-job-algorithm pub fn schedule_job(&self, job: Job, script_thread: &ScriptThread) { debug!("scheduling {:?} job", job.job_type); let mut queue_ref = self.0.borrow_mut(); let job_queue = queue_ref.entry(job.scope_url.clone()).or_insert(vec![]); // Step 1 if job_queue.is_empty() { let scope_url = job.scope_url.clone(); job_queue.push(job); let _ = script_thread.schedule_job_queue(scope_url); debug!("queued task to run newly-queued job"); } else { // Step 2 let mut last_job = job_queue.pop().unwrap(); if job == last_job &&!last_job.promise.is_fulfilled() { last_job.append_equivalent_job(job); job_queue.push(last_job); debug!("appended equivalent job"); } else { // restore the popped last_job job_queue.push(last_job); // and push this new job to job queue job_queue.push(job); debug!("pushed onto job queue job"); } } } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#run-job-algorithm pub fn run_job(&self, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("running a job"); let url = { let queue_ref = self.0.borrow(); let front_job = { let job_vec = queue_ref.get(&scope_url); job_vec.unwrap().first().unwrap() }; let front_scope_url = front_job.scope_url.clone(); match front_job.job_type {
front_scope_url }; self.finish_job(url, script_thread); } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#register-algorithm fn run_register(&self, job: &Job, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("running register job"); // Step 1-3 if!UrlHelper::is_origin_trustworthy(&job.script_url) { // Step 1.1 reject_job_promise(job, Error::Type("Invalid script ServoURL".to_owned()), script_thread.dom_manipulation_task_source()); // Step 1.2 (see run_job) return; } else if job.script_url.origin()!= job.referrer.origin() || job.scope_url.origin()!= job.referrer.origin() { // Step 2.1/3.1 reject_job_promise(job, Error::Security, script_thread.dom_manipulation_task_source()); // Step 2.2/3.2 (see run_job) return; } // Step 4-5 if let Some(reg) = script_thread.handle_get_registration(&job.scope_url) { // Step 5.1 if reg.get_uninstalling() { reg.set_uninstalling(false); } // Step 5.3 if let Some(ref newest_worker) = reg.get_newest_worker() { if (&*newest_worker).get_script_url() == job.script_url { // Step 5.3.1 resolve_job_promise(job, &*reg, script_thread.dom_manipulation_task_source()); // Step 5.3.2 (see run_job) return; } } } else { // Step 6.1 let global = &*job.client.global(); let pipeline = global.pipeline_id(); let new_reg = ServiceWorkerRegistration::new(&*global, &job.script_url, scope_url); script_thread.handle_serviceworker_registration(&job.scope_url, &*new_reg, pipeline); } // Step 7 self.update(job, script_thread) } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#finish-job-algorithm pub fn finish_job(&self, scope_url: ServoUrl, script_thread: &ScriptThread) { debug!("finishing previous job"); let run_job = if let Some(job_vec) = (*self.0.borrow_mut()).get_mut(&scope_url) { assert_eq!(job_vec.first().as_ref().unwrap().scope_url, scope_url); let _ = job_vec.remove(0); !job_vec.is_empty() } else { warn!("non-existent job vector for Servourl: {:?}", scope_url); false }; if run_job { debug!("further jobs in queue after finishing"); self.run_job(scope_url, script_thread); } } // https://w3c.github.io/ServiceWorker/#update-algorithm fn update(&self, job: &Job, script_thread: &ScriptThread) { debug!("running update job"); // Step 1 let reg = match script_thread.handle_get_registration(&job.scope_url) { Some(reg) => reg, None => { let err_type = Error::Type("No registration to update".to_owned()); // Step 2.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 2.2 (see run_job) return; } }; // Step 2 if reg.get_uninstalling() { let err_type = Error::Type("Update called on an uninstalling registration".to_owned()); // Step 2.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 2.2 (see run_job) return; } // Step 3 let newest_worker = reg.get_newest_worker(); let newest_worker_url = newest_worker.as_ref().map(|w| w.get_script_url()); // Step 4 if newest_worker_url.as_ref() == Some(&job.script_url) && job.job_type == JobType::Update { let err_type = Error::Type("Invalid script ServoURL".to_owned()); // Step 4.1 reject_job_promise(job, err_type, script_thread.dom_manipulation_task_source()); // Step 4.2 (see run_job) return; } // Step 8 if let Some(newest_worker) = newest_worker { job.client.set_controller(&*newest_worker); // Step 8.1 resolve_job_promise(job, &*reg, script_thread.dom_manipulation_task_source()); // Step 8.2 present in run_job } // TODO Step 9 (create new service worker) } } fn settle_job_promise(promise: &Promise, settle: SettleType) { match settle { SettleType::Resolve(reg) => promise.resolve_native(&*reg.root()), SettleType::Reject(err) => promise.reject_error(err), }; } #[allow(unrooted_must_root)] fn queue_settle_promise_for_job(job: &Job, settle: SettleType, task_source: &DOMManipulationTaskSource) { let global = job.client.global(); let promise = TrustedPromise::new(job.promise.clone()); // FIXME(nox): Why are errors silenced here? let _ = task_source.queue( task!(settle_promise_for_job: move || { let promise = promise.root(); settle_job_promise(&promise, settle) }), &*global, ); } // https://w3c.github.io/ServiceWorker/#reject-job-promise-algorithm // https://w3c.github.io/ServiceWorker/#resolve-job-promise-algorithm fn queue_settle_promise(job: &Job, settle: SettleType, task_source: &DOMManipulationTaskSource) { // Step 1 queue_settle_promise_for_job(job, settle.clone(), task_source); // Step 2 for job in &job.equivalent_jobs { queue_settle_promise_for_job(job, settle.clone(), task_source); } } fn reject_job_promise(job: &Job, err: Error, task_source: &DOMManipulationTaskSource) { queue_settle_promise(job, SettleType::Reject(err), task_source) } fn resolve_job_promise(job: &Job, reg: &ServiceWorkerRegistration, task_source: &DOMManipulationTaskSource) { queue_settle_promise(job, SettleType::Resolve(Trusted::new(reg)), task_source) }
JobType::Register => self.run_register(front_job, scope_url, script_thread), JobType::Update => self.update(front_job, script_thread), JobType::Unregister => unreachable!(), };
random_line_split
pg_specific_expressions_cant_be_used_in_a_sqlite_query.rs
extern crate diesel; use diesel::*; use diesel::sql_types::*; use diesel::dsl::*; use diesel::upsert::on_constraint; table! { users { id -> Integer, name -> VarChar, } } sql_function!(fn lower(x: VarChar) -> VarChar); #[derive(Insertable)] #[table_name="users"] struct
(#[column_name = "name"] &'static str); // NOTE: This test is meant to be comprehensive, but not exhaustive. fn main() { use self::users::dsl::*; let connection = SqliteConnection::establish(":memory:").unwrap(); users.select(id).filter(name.eq(any(Vec::<String>::new()))) .load::<i32>(&connection); users.select(id).filter(name.is_not_distinct_from("Sean")) .load::<i32>(&connection); users.select(id).filter(now.eq(now.at_time_zone("UTC"))) .load::<i32>(&connection); insert_into(users).values(&NewUser("Sean")) .on_conflict(on_constraint("name")) .execute(&connection); }
NewUser
identifier_name
pg_specific_expressions_cant_be_used_in_a_sqlite_query.rs
extern crate diesel; use diesel::*; use diesel::sql_types::*; use diesel::dsl::*; use diesel::upsert::on_constraint;
table! { users { id -> Integer, name -> VarChar, } } sql_function!(fn lower(x: VarChar) -> VarChar); #[derive(Insertable)] #[table_name="users"] struct NewUser(#[column_name = "name"] &'static str); // NOTE: This test is meant to be comprehensive, but not exhaustive. fn main() { use self::users::dsl::*; let connection = SqliteConnection::establish(":memory:").unwrap(); users.select(id).filter(name.eq(any(Vec::<String>::new()))) .load::<i32>(&connection); users.select(id).filter(name.is_not_distinct_from("Sean")) .load::<i32>(&connection); users.select(id).filter(now.eq(now.at_time_zone("UTC"))) .load::<i32>(&connection); insert_into(users).values(&NewUser("Sean")) .on_conflict(on_constraint("name")) .execute(&connection); }
random_line_split
editor.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use libimagstore::store::Entry; use libimagrt::runtime::Runtime; use libimagentryedit::edit::edit_in_tmpfile; use viewer::Viewer; use error::Result; use error::ResultExt; use error::ViewErrorKind as VEK; pub struct
<'a>(&'a Runtime<'a>); impl<'a> EditorView<'a> { pub fn new(rt: &'a Runtime) -> EditorView<'a> { EditorView(rt) } } impl<'a> Viewer for EditorView<'a> { fn view_entry(&self, e: &Entry) -> Result<()> { let mut entry = e.to_str().clone().to_string(); edit_in_tmpfile(self.0, &mut entry).chain_err(|| VEK::ViewError) } }
EditorView
identifier_name
editor.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use libimagstore::store::Entry; use libimagrt::runtime::Runtime; use libimagentryedit::edit::edit_in_tmpfile; use viewer::Viewer; use error::Result; use error::ResultExt; use error::ViewErrorKind as VEK; pub struct EditorView<'a>(&'a Runtime<'a>); impl<'a> EditorView<'a> { pub fn new(rt: &'a Runtime) -> EditorView<'a> { EditorView(rt) } } impl<'a> Viewer for EditorView<'a> { fn view_entry(&self, e: &Entry) -> Result<()>
}
{ let mut entry = e.to_str().clone().to_string(); edit_in_tmpfile(self.0, &mut entry).chain_err(|| VEK::ViewError) }
identifier_body
editor.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use libimagstore::store::Entry; use libimagrt::runtime::Runtime; use libimagentryedit::edit::edit_in_tmpfile; use viewer::Viewer; use error::Result; use error::ResultExt; use error::ViewErrorKind as VEK; pub struct EditorView<'a>(&'a Runtime<'a>); impl<'a> EditorView<'a> { pub fn new(rt: &'a Runtime) -> EditorView<'a> { EditorView(rt) } }
impl<'a> Viewer for EditorView<'a> { fn view_entry(&self, e: &Entry) -> Result<()> { let mut entry = e.to_str().clone().to_string(); edit_in_tmpfile(self.0, &mut entry).chain_err(|| VEK::ViewError) } }
random_line_split
dsp_waveforms.rs
/// DSP waveforms. use std::collections::HashMap; use std; use std::f32; /// Basic struct for holding DSP windows. pub struct DSPWindow { forms_by_bsize : HashMap<u32, Vec<f32>>, } impl DSPWindow { fn new() -> DSPWindow { let v512 = [0.0f32 ; 512]; let v2048 = [0.0f32 ; 512]; let mut m : HashMap<u32, Vec<f32>> = HashMap::new(); //(); DSPWindow { forms_by_bsize : m } } } /// Convert amplitude to dbfs value. /// # Parameters /// /// `amplitude` : An amplitude, usually in the range 0.0 to 1.0. /// /// # Returns /// An f32 which usually spans between 0.0 to -infinity. pub fn ampl2dbfs(amplitude : f32) -> f32 { 10.0 * amplitude.log10() } pub struct DSPWindowCollection { hamming : DSPWindow, } impl DSPWindowCollection { fn new() -> DSPWindowCollection { let mut hamming = DSPWindow::new(); DSPWindowCollection { hamming : hamming } } fn get_hamming(&self, bsize : usize) -> Vec<f32> { // TODO: Cache this // Get a hamming window of bsize matching arg let alpha = 0.53836; let beta = 1.0 - alpha; let mut toreturn : Vec<f32> = vec![0.0f32;bsize]; let pi = f32::consts::PI; let denom = (bsize as f32) - 1.0; for n in 0..bsize { let numer = 2.0 * pi * (n as f32); let frac = numer / denom; let val = alpha - beta * frac.cos(); toreturn[n] = val; } toreturn } } pub struct WaveFormCache { waveforms : HashMap<[u32;2], Vec<f32>>, } impl WaveFormCache { pub fn
() -> WaveFormCache { let m : HashMap<[u32;2], Vec<f32>> = HashMap::new(); //let mut waveforms = DSPWindow::new(); WaveFormCache { waveforms : m } } pub fn get_sine(&self, period : f32, length : usize) -> Vec<f32> { let mut toreturn : Vec<f32> = vec![0.0f32;length]; for n in 0..length { let t = 2.0 * f32::consts::PI * (((n as f32)/(period)) % 1.0); toreturn[n] = t.sin(); } toreturn } } #[test] fn instansiate_waveformbuilders() { DSPWindowCollection::new(); WaveFormCache::new(); } #[test] fn converter_ampl2dbfs() { let n3db = ampl2dbfs(0.5); assert!(-3.1 < n3db && n3db < -2.9); let n6db = ampl2dbfs(0.25); assert!(-6.1 < n6db && n6db < -5.9); let n0db = ampl2dbfs(1.0); assert!(-0.01 < n0db && n0db < 0.01); let n0db2 = ampl2dbfs(0.00); println!("Got {}", n0db2); assert!(n0db2 == f32::NEG_INFINITY); } #[test] fn gen_hamming() { let d = DSPWindowCollection::new(); let h16 = d.get_hamming(16); let h512 = d.get_hamming(512); assert!(h16.len() == 16); assert!(h512.len() == 512); assert!(h16[0] < 0.1); assert!(h16[7] > 0.6); assert!(h512[511] < 0.1); assert!(h512[256] > 0.6); } #[test] fn gen_sine_16() { // Test simple block of 16-periodic sin function. let wfc = WaveFormCache::new(); let sin16_16 = wfc.get_sine(16.0, 16); let sin16_17 = wfc.get_sine(16.0, 17); //for n in 0..sin16_16.len() { // println!("{} {} {}", n, sin16_16[n], sin16_17[n]); //} for n in 0..sin16_16.len() { assert!(sin16_16[n] == sin16_17[n]); } assert!(sin16_17[0] == 0.0); assert!(sin16_17[0] == 0.0); assert!(sin16_17[0] == sin16_17[16]); assert!((sin16_17[1] + sin16_17[9]).abs() < 0.001); }
new
identifier_name
dsp_waveforms.rs
/// DSP waveforms. use std::collections::HashMap; use std; use std::f32; /// Basic struct for holding DSP windows. pub struct DSPWindow { forms_by_bsize : HashMap<u32, Vec<f32>>, } impl DSPWindow { fn new() -> DSPWindow
} /// Convert amplitude to dbfs value. /// # Parameters /// /// `amplitude` : An amplitude, usually in the range 0.0 to 1.0. /// /// # Returns /// An f32 which usually spans between 0.0 to -infinity. pub fn ampl2dbfs(amplitude : f32) -> f32 { 10.0 * amplitude.log10() } pub struct DSPWindowCollection { hamming : DSPWindow, } impl DSPWindowCollection { fn new() -> DSPWindowCollection { let mut hamming = DSPWindow::new(); DSPWindowCollection { hamming : hamming } } fn get_hamming(&self, bsize : usize) -> Vec<f32> { // TODO: Cache this // Get a hamming window of bsize matching arg let alpha = 0.53836; let beta = 1.0 - alpha; let mut toreturn : Vec<f32> = vec![0.0f32;bsize]; let pi = f32::consts::PI; let denom = (bsize as f32) - 1.0; for n in 0..bsize { let numer = 2.0 * pi * (n as f32); let frac = numer / denom; let val = alpha - beta * frac.cos(); toreturn[n] = val; } toreturn } } pub struct WaveFormCache { waveforms : HashMap<[u32;2], Vec<f32>>, } impl WaveFormCache { pub fn new() -> WaveFormCache { let m : HashMap<[u32;2], Vec<f32>> = HashMap::new(); //let mut waveforms = DSPWindow::new(); WaveFormCache { waveforms : m } } pub fn get_sine(&self, period : f32, length : usize) -> Vec<f32> { let mut toreturn : Vec<f32> = vec![0.0f32;length]; for n in 0..length { let t = 2.0 * f32::consts::PI * (((n as f32)/(period)) % 1.0); toreturn[n] = t.sin(); } toreturn } } #[test] fn instansiate_waveformbuilders() { DSPWindowCollection::new(); WaveFormCache::new(); } #[test] fn converter_ampl2dbfs() { let n3db = ampl2dbfs(0.5); assert!(-3.1 < n3db && n3db < -2.9); let n6db = ampl2dbfs(0.25); assert!(-6.1 < n6db && n6db < -5.9); let n0db = ampl2dbfs(1.0); assert!(-0.01 < n0db && n0db < 0.01); let n0db2 = ampl2dbfs(0.00); println!("Got {}", n0db2); assert!(n0db2 == f32::NEG_INFINITY); } #[test] fn gen_hamming() { let d = DSPWindowCollection::new(); let h16 = d.get_hamming(16); let h512 = d.get_hamming(512); assert!(h16.len() == 16); assert!(h512.len() == 512); assert!(h16[0] < 0.1); assert!(h16[7] > 0.6); assert!(h512[511] < 0.1); assert!(h512[256] > 0.6); } #[test] fn gen_sine_16() { // Test simple block of 16-periodic sin function. let wfc = WaveFormCache::new(); let sin16_16 = wfc.get_sine(16.0, 16); let sin16_17 = wfc.get_sine(16.0, 17); //for n in 0..sin16_16.len() { // println!("{} {} {}", n, sin16_16[n], sin16_17[n]); //} for n in 0..sin16_16.len() { assert!(sin16_16[n] == sin16_17[n]); } assert!(sin16_17[0] == 0.0); assert!(sin16_17[0] == 0.0); assert!(sin16_17[0] == sin16_17[16]); assert!((sin16_17[1] + sin16_17[9]).abs() < 0.001); }
{ let v512 = [0.0f32 ; 512]; let v2048 = [0.0f32 ; 512]; let mut m : HashMap<u32, Vec<f32>> = HashMap::new(); //(); DSPWindow { forms_by_bsize : m } }
identifier_body
dsp_waveforms.rs
/// DSP waveforms. use std::collections::HashMap; use std; use std::f32; /// Basic struct for holding DSP windows. pub struct DSPWindow { forms_by_bsize : HashMap<u32, Vec<f32>>, } impl DSPWindow { fn new() -> DSPWindow { let v512 = [0.0f32 ; 512]; let v2048 = [0.0f32 ; 512]; let mut m : HashMap<u32, Vec<f32>> = HashMap::new(); //(); DSPWindow { forms_by_bsize : m } } } /// Convert amplitude to dbfs value. /// # Parameters /// /// `amplitude` : An amplitude, usually in the range 0.0 to 1.0.
/// /// # Returns /// An f32 which usually spans between 0.0 to -infinity. pub fn ampl2dbfs(amplitude : f32) -> f32 { 10.0 * amplitude.log10() } pub struct DSPWindowCollection { hamming : DSPWindow, } impl DSPWindowCollection { fn new() -> DSPWindowCollection { let mut hamming = DSPWindow::new(); DSPWindowCollection { hamming : hamming } } fn get_hamming(&self, bsize : usize) -> Vec<f32> { // TODO: Cache this // Get a hamming window of bsize matching arg let alpha = 0.53836; let beta = 1.0 - alpha; let mut toreturn : Vec<f32> = vec![0.0f32;bsize]; let pi = f32::consts::PI; let denom = (bsize as f32) - 1.0; for n in 0..bsize { let numer = 2.0 * pi * (n as f32); let frac = numer / denom; let val = alpha - beta * frac.cos(); toreturn[n] = val; } toreturn } } pub struct WaveFormCache { waveforms : HashMap<[u32;2], Vec<f32>>, } impl WaveFormCache { pub fn new() -> WaveFormCache { let m : HashMap<[u32;2], Vec<f32>> = HashMap::new(); //let mut waveforms = DSPWindow::new(); WaveFormCache { waveforms : m } } pub fn get_sine(&self, period : f32, length : usize) -> Vec<f32> { let mut toreturn : Vec<f32> = vec![0.0f32;length]; for n in 0..length { let t = 2.0 * f32::consts::PI * (((n as f32)/(period)) % 1.0); toreturn[n] = t.sin(); } toreturn } } #[test] fn instansiate_waveformbuilders() { DSPWindowCollection::new(); WaveFormCache::new(); } #[test] fn converter_ampl2dbfs() { let n3db = ampl2dbfs(0.5); assert!(-3.1 < n3db && n3db < -2.9); let n6db = ampl2dbfs(0.25); assert!(-6.1 < n6db && n6db < -5.9); let n0db = ampl2dbfs(1.0); assert!(-0.01 < n0db && n0db < 0.01); let n0db2 = ampl2dbfs(0.00); println!("Got {}", n0db2); assert!(n0db2 == f32::NEG_INFINITY); } #[test] fn gen_hamming() { let d = DSPWindowCollection::new(); let h16 = d.get_hamming(16); let h512 = d.get_hamming(512); assert!(h16.len() == 16); assert!(h512.len() == 512); assert!(h16[0] < 0.1); assert!(h16[7] > 0.6); assert!(h512[511] < 0.1); assert!(h512[256] > 0.6); } #[test] fn gen_sine_16() { // Test simple block of 16-periodic sin function. let wfc = WaveFormCache::new(); let sin16_16 = wfc.get_sine(16.0, 16); let sin16_17 = wfc.get_sine(16.0, 17); //for n in 0..sin16_16.len() { // println!("{} {} {}", n, sin16_16[n], sin16_17[n]); //} for n in 0..sin16_16.len() { assert!(sin16_16[n] == sin16_17[n]); } assert!(sin16_17[0] == 0.0); assert!(sin16_17[0] == 0.0); assert!(sin16_17[0] == sin16_17[16]); assert!((sin16_17[1] + sin16_17[9]).abs() < 0.001); }
random_line_split
state_cache.rs
// Copyright 2016 The xi-editor Authors. // // 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. //! A more sophisticated cache that manages user state. use rand::{thread_rng, Rng}; use xi_rope::interval::IntervalBounds; use xi_rope::{LinesMetric, RopeDelta}; use xi_trace::trace_block; use super::{Cache, DataSource, Error, View}; use crate::base_cache::ChunkCache; const CACHE_SIZE: usize = 1024; /// Number of probes for eviction logic. const NUM_PROBES: usize = 5; struct CacheEntry<S> { line_num: usize, offset: usize, user_state: Option<S>, } /// The caching state #[derive(Default)] pub struct StateCache<S> { pub(crate) buf_cache: ChunkCache, state_cache: Vec<CacheEntry<S>>, /// The frontier, represented as a sorted list of line numbers. frontier: Vec<usize>, } impl<S: Clone + Default> Cache for StateCache<S> { fn new(buf_size: usize, rev: u64, num_lines: usize) -> Self { StateCache { buf_cache: ChunkCache::new(buf_size, rev, num_lines), state_cache: Vec::new(), frontier: Vec::new(), } } fn get_line<DS: DataSource>(&mut self, source: &DS, line_num: usize) -> Result<&str, Error> { self.buf_cache.get_line(source, line_num) } fn get_region<DS, I>(&mut self, source: &DS, interval: I) -> Result<&str, Error> where DS: DataSource, I: IntervalBounds, { self.buf_cache.get_region(source, interval) } fn get_document<DS: DataSource>(&mut self, source: &DS) -> Result<String, Error> { self.buf_cache.get_document(source) } fn offset_of_line<DS: DataSource>( &mut self, source: &DS, line_num: usize, ) -> Result<usize, Error> { self.buf_cache.offset_of_line(source, line_num) } fn line_of_offset<DS: DataSource>( &mut self, source: &DS, offset: usize, ) -> Result<usize, Error> { self.buf_cache.line_of_offset(source, offset) } /// Updates the cache by applying this delta. fn update(&mut self, delta: Option<&RopeDelta>, buf_size: usize, num_lines: usize, rev: u64) { let _t = trace_block("StateCache::update", &["plugin"]); if let Some(ref delta) = delta { self.update_line_cache(delta); } else { // if there's no delta (very large edit) we blow away everything self.clear_to_start(0); } self.buf_cache.update(delta, buf_size, num_lines, rev); } /// Flushes any state held by this cache. fn clear(&mut self) { self.reset() } } impl<S: Clone + Default> StateCache<S> { /// Find an entry in the cache by line num. On return `Ok(i)` means entry /// at index `i` is an exact match, while `Err(i)` means the entry would be /// inserted at `i`. fn find_line(&self, line_num: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.line_num.cmp(&line_num)) } /// Find an entry in the cache by offset. Similar to `find_line`. pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.offset.cmp(&offset)) } /// Get the state from the nearest cache entry at or before given line number. /// Returns line number, offset, and user state. pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { if line_num > 0 { let mut ix = match self.find_line(line_num) { Ok(ix) => ix, Err(0) => return (0, 0, S::default()), Err(ix) => ix - 1, }; loop { let item = &self.state_cache[ix]; if let Some(ref s) = item.user_state { return (item.line_num, item.offset, s.clone()); } if ix == 0 { break; } ix -= 1; } } (0, 0, S::default()) } /// Get the state at the given line number, if it exists in the cache. pub fn get(&self, line_num: usize) -> Option<&S> { self.find_line(line_num).ok().and_then(|ix| self.state_cache[ix].user_state.as_ref()) } /// Set the state at the given line number. Note: has no effect if line_num /// references the end of the partial line at EOF. pub fn set<DS>(&mut self, source: &DS, line_num: usize, s: S) where DS: DataSource, {
} /// Get the cache entry at the given line number, creating it if necessary. /// Returns None if line_num > number of newlines in doc (ie if it references /// the end of the partial line at EOF). fn get_entry<DS>(&mut self, source: &DS, line_num: usize) -> Option<&mut CacheEntry<S>> where DS: DataSource, { match self.find_line(line_num) { Ok(ix) => Some(&mut self.state_cache[ix]), Err(_ix) => { if line_num == self.buf_cache.num_lines { None } else { let offset = self .buf_cache .offset_of_line(source, line_num) .expect("get_entry should validate inputs"); let new_ix = self.insert_entry(line_num, offset, None); Some(&mut self.state_cache[new_ix]) } } } } /// Insert a new entry into the cache, returning its index. fn insert_entry(&mut self, line_num: usize, offset: usize, user_state: Option<S>) -> usize { if self.state_cache.len() >= CACHE_SIZE { self.evict(); } match self.find_line(line_num) { Ok(_ix) => panic!("entry already exists"), Err(ix) => { self.state_cache.insert(ix, CacheEntry { line_num, offset, user_state }); ix } } } /// Evict one cache entry. fn evict(&mut self) { let ix = self.choose_victim(); self.state_cache.remove(ix); } fn choose_victim(&self) -> usize { let mut best = None; let mut rng = thread_rng(); for _ in 0..NUM_PROBES { let ix = rng.gen_range(0, self.state_cache.len()); let gap = self.compute_gap(ix); if best.map(|(last_gap, _)| gap < last_gap).unwrap_or(true) { best = Some((gap, ix)); } } best.unwrap().1 } /// Compute the gap that would result after deleting the given entry. fn compute_gap(&self, ix: usize) -> usize { let before = if ix == 0 { 0 } else { self.state_cache[ix - 1].offset }; let after = if let Some(item) = self.state_cache.get(ix + 1) { item.offset } else { self.buf_cache.buf_size }; assert!(after >= before, "{} < {} ix: {}", after, before, ix); after - before } /// Release all state _after_ the given offset. fn truncate_cache(&mut self, offset: usize) { let (line_num, ix) = match self.find_offset(offset) { Ok(ix) => (self.state_cache[ix].line_num, ix + 1), Err(ix) => (if ix == 0 { 0 } else { self.state_cache[ix - 1].line_num }, ix), }; self.truncate_frontier(line_num); self.state_cache.truncate(ix); } pub(crate) fn truncate_frontier(&mut self, line_num: usize) { match self.frontier.binary_search(&line_num) { Ok(ix) => self.frontier.truncate(ix + 1), Err(ix) => { self.frontier.truncate(ix); self.frontier.push(line_num); } } } /// Updates the line cache to reflect this delta. fn update_line_cache(&mut self, delta: &RopeDelta) { let (iv, new_len) = delta.summary(); if let Some(n) = delta.as_simple_insert() { assert_eq!(iv.size(), 0); assert_eq!(new_len, n.len()); let newline_count = n.measure::<LinesMetric>(); self.line_cache_simple_insert(iv.start(), new_len, newline_count); } else if delta.is_simple_delete() { assert_eq!(new_len, 0); self.line_cache_simple_delete(iv.start(), iv.end()) } else { self.clear_to_start(iv.start()); } } fn line_cache_simple_insert(&mut self, start: usize, new_len: usize, newline_num: usize) { let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; for entry in &mut self.state_cache[ix..] { entry.line_num += newline_num; entry.offset += new_len; } self.patchup_frontier(ix, newline_num as isize); } fn line_cache_simple_delete(&mut self, start: usize, end: usize) { let off = self.buf_cache.offset; let chunk_end = off + self.buf_cache.contents.len(); if start >= off && end <= chunk_end { let del_newline_num = count_newlines(&self.buf_cache.contents[start - off..end - off]); // delete all entries that overlap the deleted range let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; while ix < self.state_cache.len() && self.state_cache[ix].offset <= end { self.state_cache.remove(ix); } for entry in &mut self.state_cache[ix..] { entry.line_num -= del_newline_num; entry.offset -= end - start; } self.patchup_frontier(ix, -(del_newline_num as isize)); } else { // if this region isn't in our chunk we can't correctly adjust newlines self.clear_to_start(start); } } fn patchup_frontier(&mut self, cache_idx: usize, nl_count_delta: isize) { let line_num = match cache_idx { 0 => 0, ix => self.state_cache[ix - 1].line_num, }; let mut new_frontier = Vec::new(); let mut need_push = true; for old_ln in &self.frontier { if *old_ln < line_num { new_frontier.push(*old_ln); } else if need_push { new_frontier.push(line_num); need_push = false; if let Some(ref entry) = self.state_cache.get(cache_idx) { if *old_ln >= entry.line_num { new_frontier.push(old_ln.wrapping_add(nl_count_delta as usize)); } } } } if need_push { new_frontier.push(line_num); } self.frontier = new_frontier; } /// Clears any cached text and anything in the state cache before `start`. fn clear_to_start(&mut self, start: usize) { self.truncate_cache(start); } /// Clear all state and reset frontier to start. pub fn reset(&mut self) { self.truncate_cache(0); } /// The frontier keeps track of work needing to be done. A typical /// user will call `get_frontier` to get a line number, do the work /// on that line, insert state for the next line, and then call either /// `update_frontier` or `close_frontier` depending on whether there /// is more work to be done at that location. pub fn get_frontier(&self) -> Option<usize> { self.frontier.first().cloned() } /// Updates the frontier. This can go backward, but most typically /// goes forward by 1 line (compared to the `get_frontier` result). pub fn update_frontier(&mut self, new_frontier: usize) { if self.frontier.get(1) == Some(&new_frontier) { self.frontier.remove(0); } else { self.frontier[0] = new_frontier; } } /// Closes the current frontier. This is the correct choice to handle /// EOF. pub fn close_frontier(&mut self) { self.frontier.remove(0); } } /// StateCache specific extensions on `View` impl<S: Default + Clone> View<StateCache<S>> { pub fn get_frontier(&self) -> Option<usize> { self.cache.get_frontier() } pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { self.cache.get_prev(line_num) } pub fn get(&self, line_num: usize) -> Option<&S> { self.cache.get(line_num) } pub fn set(&mut self, line_num: usize, s: S) { let ctx = self.make_ctx(); self.cache.set(&ctx, line_num, s) } pub fn update_frontier(&mut self, new_frontier: usize) { self.cache.update_frontier(new_frontier) } pub fn close_frontier(&mut self) { self.cache.close_frontier() } pub fn reset(&mut self) { self.cache.reset() } pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.cache.find_offset(offset) } } fn count_newlines(s: &str) -> usize { bytecount::count(s.as_bytes(), b'\n') }
if let Some(entry) = self.get_entry(source, line_num) { entry.user_state = Some(s); }
random_line_split
state_cache.rs
// Copyright 2016 The xi-editor Authors. // // 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. //! A more sophisticated cache that manages user state. use rand::{thread_rng, Rng}; use xi_rope::interval::IntervalBounds; use xi_rope::{LinesMetric, RopeDelta}; use xi_trace::trace_block; use super::{Cache, DataSource, Error, View}; use crate::base_cache::ChunkCache; const CACHE_SIZE: usize = 1024; /// Number of probes for eviction logic. const NUM_PROBES: usize = 5; struct CacheEntry<S> { line_num: usize, offset: usize, user_state: Option<S>, } /// The caching state #[derive(Default)] pub struct StateCache<S> { pub(crate) buf_cache: ChunkCache, state_cache: Vec<CacheEntry<S>>, /// The frontier, represented as a sorted list of line numbers. frontier: Vec<usize>, } impl<S: Clone + Default> Cache for StateCache<S> { fn new(buf_size: usize, rev: u64, num_lines: usize) -> Self { StateCache { buf_cache: ChunkCache::new(buf_size, rev, num_lines), state_cache: Vec::new(), frontier: Vec::new(), } } fn get_line<DS: DataSource>(&mut self, source: &DS, line_num: usize) -> Result<&str, Error> { self.buf_cache.get_line(source, line_num) } fn get_region<DS, I>(&mut self, source: &DS, interval: I) -> Result<&str, Error> where DS: DataSource, I: IntervalBounds, { self.buf_cache.get_region(source, interval) } fn get_document<DS: DataSource>(&mut self, source: &DS) -> Result<String, Error> { self.buf_cache.get_document(source) } fn offset_of_line<DS: DataSource>( &mut self, source: &DS, line_num: usize, ) -> Result<usize, Error> { self.buf_cache.offset_of_line(source, line_num) } fn line_of_offset<DS: DataSource>( &mut self, source: &DS, offset: usize, ) -> Result<usize, Error> { self.buf_cache.line_of_offset(source, offset) } /// Updates the cache by applying this delta. fn update(&mut self, delta: Option<&RopeDelta>, buf_size: usize, num_lines: usize, rev: u64) { let _t = trace_block("StateCache::update", &["plugin"]); if let Some(ref delta) = delta { self.update_line_cache(delta); } else { // if there's no delta (very large edit) we blow away everything self.clear_to_start(0); } self.buf_cache.update(delta, buf_size, num_lines, rev); } /// Flushes any state held by this cache. fn clear(&mut self) { self.reset() } } impl<S: Clone + Default> StateCache<S> { /// Find an entry in the cache by line num. On return `Ok(i)` means entry /// at index `i` is an exact match, while `Err(i)` means the entry would be /// inserted at `i`. fn find_line(&self, line_num: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.line_num.cmp(&line_num)) } /// Find an entry in the cache by offset. Similar to `find_line`. pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.offset.cmp(&offset)) } /// Get the state from the nearest cache entry at or before given line number. /// Returns line number, offset, and user state. pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { if line_num > 0 { let mut ix = match self.find_line(line_num) { Ok(ix) => ix, Err(0) => return (0, 0, S::default()), Err(ix) => ix - 1, }; loop { let item = &self.state_cache[ix]; if let Some(ref s) = item.user_state { return (item.line_num, item.offset, s.clone()); } if ix == 0
ix -= 1; } } (0, 0, S::default()) } /// Get the state at the given line number, if it exists in the cache. pub fn get(&self, line_num: usize) -> Option<&S> { self.find_line(line_num).ok().and_then(|ix| self.state_cache[ix].user_state.as_ref()) } /// Set the state at the given line number. Note: has no effect if line_num /// references the end of the partial line at EOF. pub fn set<DS>(&mut self, source: &DS, line_num: usize, s: S) where DS: DataSource, { if let Some(entry) = self.get_entry(source, line_num) { entry.user_state = Some(s); } } /// Get the cache entry at the given line number, creating it if necessary. /// Returns None if line_num > number of newlines in doc (ie if it references /// the end of the partial line at EOF). fn get_entry<DS>(&mut self, source: &DS, line_num: usize) -> Option<&mut CacheEntry<S>> where DS: DataSource, { match self.find_line(line_num) { Ok(ix) => Some(&mut self.state_cache[ix]), Err(_ix) => { if line_num == self.buf_cache.num_lines { None } else { let offset = self .buf_cache .offset_of_line(source, line_num) .expect("get_entry should validate inputs"); let new_ix = self.insert_entry(line_num, offset, None); Some(&mut self.state_cache[new_ix]) } } } } /// Insert a new entry into the cache, returning its index. fn insert_entry(&mut self, line_num: usize, offset: usize, user_state: Option<S>) -> usize { if self.state_cache.len() >= CACHE_SIZE { self.evict(); } match self.find_line(line_num) { Ok(_ix) => panic!("entry already exists"), Err(ix) => { self.state_cache.insert(ix, CacheEntry { line_num, offset, user_state }); ix } } } /// Evict one cache entry. fn evict(&mut self) { let ix = self.choose_victim(); self.state_cache.remove(ix); } fn choose_victim(&self) -> usize { let mut best = None; let mut rng = thread_rng(); for _ in 0..NUM_PROBES { let ix = rng.gen_range(0, self.state_cache.len()); let gap = self.compute_gap(ix); if best.map(|(last_gap, _)| gap < last_gap).unwrap_or(true) { best = Some((gap, ix)); } } best.unwrap().1 } /// Compute the gap that would result after deleting the given entry. fn compute_gap(&self, ix: usize) -> usize { let before = if ix == 0 { 0 } else { self.state_cache[ix - 1].offset }; let after = if let Some(item) = self.state_cache.get(ix + 1) { item.offset } else { self.buf_cache.buf_size }; assert!(after >= before, "{} < {} ix: {}", after, before, ix); after - before } /// Release all state _after_ the given offset. fn truncate_cache(&mut self, offset: usize) { let (line_num, ix) = match self.find_offset(offset) { Ok(ix) => (self.state_cache[ix].line_num, ix + 1), Err(ix) => (if ix == 0 { 0 } else { self.state_cache[ix - 1].line_num }, ix), }; self.truncate_frontier(line_num); self.state_cache.truncate(ix); } pub(crate) fn truncate_frontier(&mut self, line_num: usize) { match self.frontier.binary_search(&line_num) { Ok(ix) => self.frontier.truncate(ix + 1), Err(ix) => { self.frontier.truncate(ix); self.frontier.push(line_num); } } } /// Updates the line cache to reflect this delta. fn update_line_cache(&mut self, delta: &RopeDelta) { let (iv, new_len) = delta.summary(); if let Some(n) = delta.as_simple_insert() { assert_eq!(iv.size(), 0); assert_eq!(new_len, n.len()); let newline_count = n.measure::<LinesMetric>(); self.line_cache_simple_insert(iv.start(), new_len, newline_count); } else if delta.is_simple_delete() { assert_eq!(new_len, 0); self.line_cache_simple_delete(iv.start(), iv.end()) } else { self.clear_to_start(iv.start()); } } fn line_cache_simple_insert(&mut self, start: usize, new_len: usize, newline_num: usize) { let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; for entry in &mut self.state_cache[ix..] { entry.line_num += newline_num; entry.offset += new_len; } self.patchup_frontier(ix, newline_num as isize); } fn line_cache_simple_delete(&mut self, start: usize, end: usize) { let off = self.buf_cache.offset; let chunk_end = off + self.buf_cache.contents.len(); if start >= off && end <= chunk_end { let del_newline_num = count_newlines(&self.buf_cache.contents[start - off..end - off]); // delete all entries that overlap the deleted range let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; while ix < self.state_cache.len() && self.state_cache[ix].offset <= end { self.state_cache.remove(ix); } for entry in &mut self.state_cache[ix..] { entry.line_num -= del_newline_num; entry.offset -= end - start; } self.patchup_frontier(ix, -(del_newline_num as isize)); } else { // if this region isn't in our chunk we can't correctly adjust newlines self.clear_to_start(start); } } fn patchup_frontier(&mut self, cache_idx: usize, nl_count_delta: isize) { let line_num = match cache_idx { 0 => 0, ix => self.state_cache[ix - 1].line_num, }; let mut new_frontier = Vec::new(); let mut need_push = true; for old_ln in &self.frontier { if *old_ln < line_num { new_frontier.push(*old_ln); } else if need_push { new_frontier.push(line_num); need_push = false; if let Some(ref entry) = self.state_cache.get(cache_idx) { if *old_ln >= entry.line_num { new_frontier.push(old_ln.wrapping_add(nl_count_delta as usize)); } } } } if need_push { new_frontier.push(line_num); } self.frontier = new_frontier; } /// Clears any cached text and anything in the state cache before `start`. fn clear_to_start(&mut self, start: usize) { self.truncate_cache(start); } /// Clear all state and reset frontier to start. pub fn reset(&mut self) { self.truncate_cache(0); } /// The frontier keeps track of work needing to be done. A typical /// user will call `get_frontier` to get a line number, do the work /// on that line, insert state for the next line, and then call either /// `update_frontier` or `close_frontier` depending on whether there /// is more work to be done at that location. pub fn get_frontier(&self) -> Option<usize> { self.frontier.first().cloned() } /// Updates the frontier. This can go backward, but most typically /// goes forward by 1 line (compared to the `get_frontier` result). pub fn update_frontier(&mut self, new_frontier: usize) { if self.frontier.get(1) == Some(&new_frontier) { self.frontier.remove(0); } else { self.frontier[0] = new_frontier; } } /// Closes the current frontier. This is the correct choice to handle /// EOF. pub fn close_frontier(&mut self) { self.frontier.remove(0); } } /// StateCache specific extensions on `View` impl<S: Default + Clone> View<StateCache<S>> { pub fn get_frontier(&self) -> Option<usize> { self.cache.get_frontier() } pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { self.cache.get_prev(line_num) } pub fn get(&self, line_num: usize) -> Option<&S> { self.cache.get(line_num) } pub fn set(&mut self, line_num: usize, s: S) { let ctx = self.make_ctx(); self.cache.set(&ctx, line_num, s) } pub fn update_frontier(&mut self, new_frontier: usize) { self.cache.update_frontier(new_frontier) } pub fn close_frontier(&mut self) { self.cache.close_frontier() } pub fn reset(&mut self) { self.cache.reset() } pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.cache.find_offset(offset) } } fn count_newlines(s: &str) -> usize { bytecount::count(s.as_bytes(), b'\n') }
{ break; }
conditional_block
state_cache.rs
// Copyright 2016 The xi-editor Authors. // // 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. //! A more sophisticated cache that manages user state. use rand::{thread_rng, Rng}; use xi_rope::interval::IntervalBounds; use xi_rope::{LinesMetric, RopeDelta}; use xi_trace::trace_block; use super::{Cache, DataSource, Error, View}; use crate::base_cache::ChunkCache; const CACHE_SIZE: usize = 1024; /// Number of probes for eviction logic. const NUM_PROBES: usize = 5; struct CacheEntry<S> { line_num: usize, offset: usize, user_state: Option<S>, } /// The caching state #[derive(Default)] pub struct StateCache<S> { pub(crate) buf_cache: ChunkCache, state_cache: Vec<CacheEntry<S>>, /// The frontier, represented as a sorted list of line numbers. frontier: Vec<usize>, } impl<S: Clone + Default> Cache for StateCache<S> { fn new(buf_size: usize, rev: u64, num_lines: usize) -> Self { StateCache { buf_cache: ChunkCache::new(buf_size, rev, num_lines), state_cache: Vec::new(), frontier: Vec::new(), } } fn get_line<DS: DataSource>(&mut self, source: &DS, line_num: usize) -> Result<&str, Error> { self.buf_cache.get_line(source, line_num) } fn get_region<DS, I>(&mut self, source: &DS, interval: I) -> Result<&str, Error> where DS: DataSource, I: IntervalBounds, { self.buf_cache.get_region(source, interval) } fn get_document<DS: DataSource>(&mut self, source: &DS) -> Result<String, Error> { self.buf_cache.get_document(source) } fn offset_of_line<DS: DataSource>( &mut self, source: &DS, line_num: usize, ) -> Result<usize, Error> { self.buf_cache.offset_of_line(source, line_num) } fn line_of_offset<DS: DataSource>( &mut self, source: &DS, offset: usize, ) -> Result<usize, Error> { self.buf_cache.line_of_offset(source, offset) } /// Updates the cache by applying this delta. fn update(&mut self, delta: Option<&RopeDelta>, buf_size: usize, num_lines: usize, rev: u64) { let _t = trace_block("StateCache::update", &["plugin"]); if let Some(ref delta) = delta { self.update_line_cache(delta); } else { // if there's no delta (very large edit) we blow away everything self.clear_to_start(0); } self.buf_cache.update(delta, buf_size, num_lines, rev); } /// Flushes any state held by this cache. fn clear(&mut self) { self.reset() } } impl<S: Clone + Default> StateCache<S> { /// Find an entry in the cache by line num. On return `Ok(i)` means entry /// at index `i` is an exact match, while `Err(i)` means the entry would be /// inserted at `i`. fn find_line(&self, line_num: usize) -> Result<usize, usize>
/// Find an entry in the cache by offset. Similar to `find_line`. pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.offset.cmp(&offset)) } /// Get the state from the nearest cache entry at or before given line number. /// Returns line number, offset, and user state. pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { if line_num > 0 { let mut ix = match self.find_line(line_num) { Ok(ix) => ix, Err(0) => return (0, 0, S::default()), Err(ix) => ix - 1, }; loop { let item = &self.state_cache[ix]; if let Some(ref s) = item.user_state { return (item.line_num, item.offset, s.clone()); } if ix == 0 { break; } ix -= 1; } } (0, 0, S::default()) } /// Get the state at the given line number, if it exists in the cache. pub fn get(&self, line_num: usize) -> Option<&S> { self.find_line(line_num).ok().and_then(|ix| self.state_cache[ix].user_state.as_ref()) } /// Set the state at the given line number. Note: has no effect if line_num /// references the end of the partial line at EOF. pub fn set<DS>(&mut self, source: &DS, line_num: usize, s: S) where DS: DataSource, { if let Some(entry) = self.get_entry(source, line_num) { entry.user_state = Some(s); } } /// Get the cache entry at the given line number, creating it if necessary. /// Returns None if line_num > number of newlines in doc (ie if it references /// the end of the partial line at EOF). fn get_entry<DS>(&mut self, source: &DS, line_num: usize) -> Option<&mut CacheEntry<S>> where DS: DataSource, { match self.find_line(line_num) { Ok(ix) => Some(&mut self.state_cache[ix]), Err(_ix) => { if line_num == self.buf_cache.num_lines { None } else { let offset = self .buf_cache .offset_of_line(source, line_num) .expect("get_entry should validate inputs"); let new_ix = self.insert_entry(line_num, offset, None); Some(&mut self.state_cache[new_ix]) } } } } /// Insert a new entry into the cache, returning its index. fn insert_entry(&mut self, line_num: usize, offset: usize, user_state: Option<S>) -> usize { if self.state_cache.len() >= CACHE_SIZE { self.evict(); } match self.find_line(line_num) { Ok(_ix) => panic!("entry already exists"), Err(ix) => { self.state_cache.insert(ix, CacheEntry { line_num, offset, user_state }); ix } } } /// Evict one cache entry. fn evict(&mut self) { let ix = self.choose_victim(); self.state_cache.remove(ix); } fn choose_victim(&self) -> usize { let mut best = None; let mut rng = thread_rng(); for _ in 0..NUM_PROBES { let ix = rng.gen_range(0, self.state_cache.len()); let gap = self.compute_gap(ix); if best.map(|(last_gap, _)| gap < last_gap).unwrap_or(true) { best = Some((gap, ix)); } } best.unwrap().1 } /// Compute the gap that would result after deleting the given entry. fn compute_gap(&self, ix: usize) -> usize { let before = if ix == 0 { 0 } else { self.state_cache[ix - 1].offset }; let after = if let Some(item) = self.state_cache.get(ix + 1) { item.offset } else { self.buf_cache.buf_size }; assert!(after >= before, "{} < {} ix: {}", after, before, ix); after - before } /// Release all state _after_ the given offset. fn truncate_cache(&mut self, offset: usize) { let (line_num, ix) = match self.find_offset(offset) { Ok(ix) => (self.state_cache[ix].line_num, ix + 1), Err(ix) => (if ix == 0 { 0 } else { self.state_cache[ix - 1].line_num }, ix), }; self.truncate_frontier(line_num); self.state_cache.truncate(ix); } pub(crate) fn truncate_frontier(&mut self, line_num: usize) { match self.frontier.binary_search(&line_num) { Ok(ix) => self.frontier.truncate(ix + 1), Err(ix) => { self.frontier.truncate(ix); self.frontier.push(line_num); } } } /// Updates the line cache to reflect this delta. fn update_line_cache(&mut self, delta: &RopeDelta) { let (iv, new_len) = delta.summary(); if let Some(n) = delta.as_simple_insert() { assert_eq!(iv.size(), 0); assert_eq!(new_len, n.len()); let newline_count = n.measure::<LinesMetric>(); self.line_cache_simple_insert(iv.start(), new_len, newline_count); } else if delta.is_simple_delete() { assert_eq!(new_len, 0); self.line_cache_simple_delete(iv.start(), iv.end()) } else { self.clear_to_start(iv.start()); } } fn line_cache_simple_insert(&mut self, start: usize, new_len: usize, newline_num: usize) { let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; for entry in &mut self.state_cache[ix..] { entry.line_num += newline_num; entry.offset += new_len; } self.patchup_frontier(ix, newline_num as isize); } fn line_cache_simple_delete(&mut self, start: usize, end: usize) { let off = self.buf_cache.offset; let chunk_end = off + self.buf_cache.contents.len(); if start >= off && end <= chunk_end { let del_newline_num = count_newlines(&self.buf_cache.contents[start - off..end - off]); // delete all entries that overlap the deleted range let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; while ix < self.state_cache.len() && self.state_cache[ix].offset <= end { self.state_cache.remove(ix); } for entry in &mut self.state_cache[ix..] { entry.line_num -= del_newline_num; entry.offset -= end - start; } self.patchup_frontier(ix, -(del_newline_num as isize)); } else { // if this region isn't in our chunk we can't correctly adjust newlines self.clear_to_start(start); } } fn patchup_frontier(&mut self, cache_idx: usize, nl_count_delta: isize) { let line_num = match cache_idx { 0 => 0, ix => self.state_cache[ix - 1].line_num, }; let mut new_frontier = Vec::new(); let mut need_push = true; for old_ln in &self.frontier { if *old_ln < line_num { new_frontier.push(*old_ln); } else if need_push { new_frontier.push(line_num); need_push = false; if let Some(ref entry) = self.state_cache.get(cache_idx) { if *old_ln >= entry.line_num { new_frontier.push(old_ln.wrapping_add(nl_count_delta as usize)); } } } } if need_push { new_frontier.push(line_num); } self.frontier = new_frontier; } /// Clears any cached text and anything in the state cache before `start`. fn clear_to_start(&mut self, start: usize) { self.truncate_cache(start); } /// Clear all state and reset frontier to start. pub fn reset(&mut self) { self.truncate_cache(0); } /// The frontier keeps track of work needing to be done. A typical /// user will call `get_frontier` to get a line number, do the work /// on that line, insert state for the next line, and then call either /// `update_frontier` or `close_frontier` depending on whether there /// is more work to be done at that location. pub fn get_frontier(&self) -> Option<usize> { self.frontier.first().cloned() } /// Updates the frontier. This can go backward, but most typically /// goes forward by 1 line (compared to the `get_frontier` result). pub fn update_frontier(&mut self, new_frontier: usize) { if self.frontier.get(1) == Some(&new_frontier) { self.frontier.remove(0); } else { self.frontier[0] = new_frontier; } } /// Closes the current frontier. This is the correct choice to handle /// EOF. pub fn close_frontier(&mut self) { self.frontier.remove(0); } } /// StateCache specific extensions on `View` impl<S: Default + Clone> View<StateCache<S>> { pub fn get_frontier(&self) -> Option<usize> { self.cache.get_frontier() } pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { self.cache.get_prev(line_num) } pub fn get(&self, line_num: usize) -> Option<&S> { self.cache.get(line_num) } pub fn set(&mut self, line_num: usize, s: S) { let ctx = self.make_ctx(); self.cache.set(&ctx, line_num, s) } pub fn update_frontier(&mut self, new_frontier: usize) { self.cache.update_frontier(new_frontier) } pub fn close_frontier(&mut self) { self.cache.close_frontier() } pub fn reset(&mut self) { self.cache.reset() } pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.cache.find_offset(offset) } } fn count_newlines(s: &str) -> usize { bytecount::count(s.as_bytes(), b'\n') }
{ self.state_cache.binary_search_by(|probe| probe.line_num.cmp(&line_num)) }
identifier_body
state_cache.rs
// Copyright 2016 The xi-editor Authors. // // 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. //! A more sophisticated cache that manages user state. use rand::{thread_rng, Rng}; use xi_rope::interval::IntervalBounds; use xi_rope::{LinesMetric, RopeDelta}; use xi_trace::trace_block; use super::{Cache, DataSource, Error, View}; use crate::base_cache::ChunkCache; const CACHE_SIZE: usize = 1024; /// Number of probes for eviction logic. const NUM_PROBES: usize = 5; struct CacheEntry<S> { line_num: usize, offset: usize, user_state: Option<S>, } /// The caching state #[derive(Default)] pub struct StateCache<S> { pub(crate) buf_cache: ChunkCache, state_cache: Vec<CacheEntry<S>>, /// The frontier, represented as a sorted list of line numbers. frontier: Vec<usize>, } impl<S: Clone + Default> Cache for StateCache<S> { fn new(buf_size: usize, rev: u64, num_lines: usize) -> Self { StateCache { buf_cache: ChunkCache::new(buf_size, rev, num_lines), state_cache: Vec::new(), frontier: Vec::new(), } } fn get_line<DS: DataSource>(&mut self, source: &DS, line_num: usize) -> Result<&str, Error> { self.buf_cache.get_line(source, line_num) } fn get_region<DS, I>(&mut self, source: &DS, interval: I) -> Result<&str, Error> where DS: DataSource, I: IntervalBounds, { self.buf_cache.get_region(source, interval) } fn get_document<DS: DataSource>(&mut self, source: &DS) -> Result<String, Error> { self.buf_cache.get_document(source) } fn offset_of_line<DS: DataSource>( &mut self, source: &DS, line_num: usize, ) -> Result<usize, Error> { self.buf_cache.offset_of_line(source, line_num) } fn line_of_offset<DS: DataSource>( &mut self, source: &DS, offset: usize, ) -> Result<usize, Error> { self.buf_cache.line_of_offset(source, offset) } /// Updates the cache by applying this delta. fn update(&mut self, delta: Option<&RopeDelta>, buf_size: usize, num_lines: usize, rev: u64) { let _t = trace_block("StateCache::update", &["plugin"]); if let Some(ref delta) = delta { self.update_line_cache(delta); } else { // if there's no delta (very large edit) we blow away everything self.clear_to_start(0); } self.buf_cache.update(delta, buf_size, num_lines, rev); } /// Flushes any state held by this cache. fn clear(&mut self) { self.reset() } } impl<S: Clone + Default> StateCache<S> { /// Find an entry in the cache by line num. On return `Ok(i)` means entry /// at index `i` is an exact match, while `Err(i)` means the entry would be /// inserted at `i`. fn find_line(&self, line_num: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.line_num.cmp(&line_num)) } /// Find an entry in the cache by offset. Similar to `find_line`. pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.offset.cmp(&offset)) } /// Get the state from the nearest cache entry at or before given line number. /// Returns line number, offset, and user state. pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { if line_num > 0 { let mut ix = match self.find_line(line_num) { Ok(ix) => ix, Err(0) => return (0, 0, S::default()), Err(ix) => ix - 1, }; loop { let item = &self.state_cache[ix]; if let Some(ref s) = item.user_state { return (item.line_num, item.offset, s.clone()); } if ix == 0 { break; } ix -= 1; } } (0, 0, S::default()) } /// Get the state at the given line number, if it exists in the cache. pub fn get(&self, line_num: usize) -> Option<&S> { self.find_line(line_num).ok().and_then(|ix| self.state_cache[ix].user_state.as_ref()) } /// Set the state at the given line number. Note: has no effect if line_num /// references the end of the partial line at EOF. pub fn set<DS>(&mut self, source: &DS, line_num: usize, s: S) where DS: DataSource, { if let Some(entry) = self.get_entry(source, line_num) { entry.user_state = Some(s); } } /// Get the cache entry at the given line number, creating it if necessary. /// Returns None if line_num > number of newlines in doc (ie if it references /// the end of the partial line at EOF). fn get_entry<DS>(&mut self, source: &DS, line_num: usize) -> Option<&mut CacheEntry<S>> where DS: DataSource, { match self.find_line(line_num) { Ok(ix) => Some(&mut self.state_cache[ix]), Err(_ix) => { if line_num == self.buf_cache.num_lines { None } else { let offset = self .buf_cache .offset_of_line(source, line_num) .expect("get_entry should validate inputs"); let new_ix = self.insert_entry(line_num, offset, None); Some(&mut self.state_cache[new_ix]) } } } } /// Insert a new entry into the cache, returning its index. fn insert_entry(&mut self, line_num: usize, offset: usize, user_state: Option<S>) -> usize { if self.state_cache.len() >= CACHE_SIZE { self.evict(); } match self.find_line(line_num) { Ok(_ix) => panic!("entry already exists"), Err(ix) => { self.state_cache.insert(ix, CacheEntry { line_num, offset, user_state }); ix } } } /// Evict one cache entry. fn evict(&mut self) { let ix = self.choose_victim(); self.state_cache.remove(ix); } fn choose_victim(&self) -> usize { let mut best = None; let mut rng = thread_rng(); for _ in 0..NUM_PROBES { let ix = rng.gen_range(0, self.state_cache.len()); let gap = self.compute_gap(ix); if best.map(|(last_gap, _)| gap < last_gap).unwrap_or(true) { best = Some((gap, ix)); } } best.unwrap().1 } /// Compute the gap that would result after deleting the given entry. fn compute_gap(&self, ix: usize) -> usize { let before = if ix == 0 { 0 } else { self.state_cache[ix - 1].offset }; let after = if let Some(item) = self.state_cache.get(ix + 1) { item.offset } else { self.buf_cache.buf_size }; assert!(after >= before, "{} < {} ix: {}", after, before, ix); after - before } /// Release all state _after_ the given offset. fn truncate_cache(&mut self, offset: usize) { let (line_num, ix) = match self.find_offset(offset) { Ok(ix) => (self.state_cache[ix].line_num, ix + 1), Err(ix) => (if ix == 0 { 0 } else { self.state_cache[ix - 1].line_num }, ix), }; self.truncate_frontier(line_num); self.state_cache.truncate(ix); } pub(crate) fn truncate_frontier(&mut self, line_num: usize) { match self.frontier.binary_search(&line_num) { Ok(ix) => self.frontier.truncate(ix + 1), Err(ix) => { self.frontier.truncate(ix); self.frontier.push(line_num); } } } /// Updates the line cache to reflect this delta. fn update_line_cache(&mut self, delta: &RopeDelta) { let (iv, new_len) = delta.summary(); if let Some(n) = delta.as_simple_insert() { assert_eq!(iv.size(), 0); assert_eq!(new_len, n.len()); let newline_count = n.measure::<LinesMetric>(); self.line_cache_simple_insert(iv.start(), new_len, newline_count); } else if delta.is_simple_delete() { assert_eq!(new_len, 0); self.line_cache_simple_delete(iv.start(), iv.end()) } else { self.clear_to_start(iv.start()); } } fn line_cache_simple_insert(&mut self, start: usize, new_len: usize, newline_num: usize) { let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; for entry in &mut self.state_cache[ix..] { entry.line_num += newline_num; entry.offset += new_len; } self.patchup_frontier(ix, newline_num as isize); } fn line_cache_simple_delete(&mut self, start: usize, end: usize) { let off = self.buf_cache.offset; let chunk_end = off + self.buf_cache.contents.len(); if start >= off && end <= chunk_end { let del_newline_num = count_newlines(&self.buf_cache.contents[start - off..end - off]); // delete all entries that overlap the deleted range let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; while ix < self.state_cache.len() && self.state_cache[ix].offset <= end { self.state_cache.remove(ix); } for entry in &mut self.state_cache[ix..] { entry.line_num -= del_newline_num; entry.offset -= end - start; } self.patchup_frontier(ix, -(del_newline_num as isize)); } else { // if this region isn't in our chunk we can't correctly adjust newlines self.clear_to_start(start); } } fn patchup_frontier(&mut self, cache_idx: usize, nl_count_delta: isize) { let line_num = match cache_idx { 0 => 0, ix => self.state_cache[ix - 1].line_num, }; let mut new_frontier = Vec::new(); let mut need_push = true; for old_ln in &self.frontier { if *old_ln < line_num { new_frontier.push(*old_ln); } else if need_push { new_frontier.push(line_num); need_push = false; if let Some(ref entry) = self.state_cache.get(cache_idx) { if *old_ln >= entry.line_num { new_frontier.push(old_ln.wrapping_add(nl_count_delta as usize)); } } } } if need_push { new_frontier.push(line_num); } self.frontier = new_frontier; } /// Clears any cached text and anything in the state cache before `start`. fn clear_to_start(&mut self, start: usize) { self.truncate_cache(start); } /// Clear all state and reset frontier to start. pub fn reset(&mut self) { self.truncate_cache(0); } /// The frontier keeps track of work needing to be done. A typical /// user will call `get_frontier` to get a line number, do the work /// on that line, insert state for the next line, and then call either /// `update_frontier` or `close_frontier` depending on whether there /// is more work to be done at that location. pub fn get_frontier(&self) -> Option<usize> { self.frontier.first().cloned() } /// Updates the frontier. This can go backward, but most typically /// goes forward by 1 line (compared to the `get_frontier` result). pub fn update_frontier(&mut self, new_frontier: usize) { if self.frontier.get(1) == Some(&new_frontier) { self.frontier.remove(0); } else { self.frontier[0] = new_frontier; } } /// Closes the current frontier. This is the correct choice to handle /// EOF. pub fn close_frontier(&mut self) { self.frontier.remove(0); } } /// StateCache specific extensions on `View` impl<S: Default + Clone> View<StateCache<S>> { pub fn get_frontier(&self) -> Option<usize> { self.cache.get_frontier() } pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { self.cache.get_prev(line_num) } pub fn get(&self, line_num: usize) -> Option<&S> { self.cache.get(line_num) } pub fn set(&mut self, line_num: usize, s: S) { let ctx = self.make_ctx(); self.cache.set(&ctx, line_num, s) } pub fn
(&mut self, new_frontier: usize) { self.cache.update_frontier(new_frontier) } pub fn close_frontier(&mut self) { self.cache.close_frontier() } pub fn reset(&mut self) { self.cache.reset() } pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.cache.find_offset(offset) } } fn count_newlines(s: &str) -> usize { bytecount::count(s.as_bytes(), b'\n') }
update_frontier
identifier_name
boxed.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A unique pointer type. use core::any::{Any, AnyRefExt}; use core::clone::Clone; use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; use core::fmt; use core::kinds::Sized; use core::mem; use core::option::Option; use core::raw::TraitObject; use core::result::{Ok, Err, Result}; /// A value that represents the global exchange heap. This is the default /// place that the `box` keyword allocates into when no place is supplied. /// /// The following two examples are equivalent: /// /// ```rust /// use std::boxed::HEAP; /// /// # struct Bar; /// # impl Bar { fn new(_a: int) { } } /// let foo = box(HEAP) Bar::new(2); /// let foo = box Bar::new(2); /// ``` #[lang = "exchange_heap"] #[experimental = "may be renamed; uncertain about custom allocator design"] pub static HEAP: () = (); /// A type that represents a uniquely-owned value. #[lang = "owned_box"] #[unstable = "custom allocators will add an additional type parameter (with default)"] pub struct Box<T>(*mut T); impl<T: Default> Default for Box<T> { fn default() -> Box<T> { box Default::default() } } impl<T> Default for Box<[T]> { fn default() -> Box<[T]> { box [] } } #[unstable] impl<T: Clone> Clone for Box<T> { /// Returns a copy of the owned box. #[inline] fn clone(&self) -> Box<T> { box {(**self).clone()} } /// Performs copy-assignment from `source` by reusing the existing allocation. #[inline] fn clone_from(&mut self, source: &Box<T>) { (**self).clone_from(&(**source)); } } impl<Sized? T: PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) } }
#[inline] fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) } } impl<Sized? T: Ord> Ord for Box<T> { #[inline] fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } } impl<Sized? T: Eq> Eq for Box<T> {} /// Extension methods for an owning `Any` trait object. #[unstable = "post-DST and coherence changes, this will not be a trait but \ rather a direct `impl` on `Box<Any>`"] pub trait BoxAny { /// Returns the boxed value if it is of type `T`, or /// `Err(Self)` if it isn't. #[unstable = "naming conventions around accessing innards may change"] fn downcast<T:'static>(self) -> Result<Box<T>, Self>; } #[stable] impl BoxAny for Box<Any> { #[inline] fn downcast<T:'static>(self) -> Result<Box<T>, Box<Any>> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = mem::transmute::<Box<Any>, TraitObject>(self); // Extract the data pointer Ok(mem::transmute(to.data)) } } else { Err(self) } } } impl<Sized? T: fmt::Show> fmt::Show for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } } impl fmt::Show for Box<Any+'static> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("Box<Any>") } } #[cfg(test)] mod test { #[test] fn test_owned_clone() { let a = box 5i; let b: Box<int> = a.clone(); assert!(a == b); } #[test] fn any_move() { let a = box 8u as Box<Any>; let b = box Test as Box<Any>; match a.downcast::<uint>() { Ok(a) => { assert!(a == box 8u); } Err(..) => panic!() } match b.downcast::<Test>() { Ok(a) => { assert!(a == box Test); } Err(..) => panic!() } let a = box 8u as Box<Any>; let b = box Test as Box<Any>; assert!(a.downcast::<Box<Test>>().is_err()); assert!(b.downcast::<Box<uint>>().is_err()); } #[test] fn test_show() { let a = box 8u as Box<Any>; let b = box Test as Box<Any>; let a_str = a.to_str(); let b_str = b.to_str(); assert_eq!(a_str.as_slice(), "Box<Any>"); assert_eq!(b_str.as_slice(), "Box<Any>"); let a = &8u as &Any; let b = &Test as &Any; let s = format!("{}", a); assert_eq!(s.as_slice(), "&Any"); let s = format!("{}", b); assert_eq!(s.as_slice(), "&Any"); } }
impl<Sized? T: PartialOrd> PartialOrd for Box<T> {
random_line_split
boxed.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A unique pointer type. use core::any::{Any, AnyRefExt}; use core::clone::Clone; use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; use core::fmt; use core::kinds::Sized; use core::mem; use core::option::Option; use core::raw::TraitObject; use core::result::{Ok, Err, Result}; /// A value that represents the global exchange heap. This is the default /// place that the `box` keyword allocates into when no place is supplied. /// /// The following two examples are equivalent: /// /// ```rust /// use std::boxed::HEAP; /// /// # struct Bar; /// # impl Bar { fn new(_a: int) { } } /// let foo = box(HEAP) Bar::new(2); /// let foo = box Bar::new(2); /// ``` #[lang = "exchange_heap"] #[experimental = "may be renamed; uncertain about custom allocator design"] pub static HEAP: () = (); /// A type that represents a uniquely-owned value. #[lang = "owned_box"] #[unstable = "custom allocators will add an additional type parameter (with default)"] pub struct Box<T>(*mut T); impl<T: Default> Default for Box<T> { fn default() -> Box<T> { box Default::default() } } impl<T> Default for Box<[T]> { fn default() -> Box<[T]> { box [] } } #[unstable] impl<T: Clone> Clone for Box<T> { /// Returns a copy of the owned box. #[inline] fn clone(&self) -> Box<T> { box {(**self).clone()} } /// Performs copy-assignment from `source` by reusing the existing allocation. #[inline] fn clone_from(&mut self, source: &Box<T>)
} impl<Sized? T: PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) } } impl<Sized? T: PartialOrd> PartialOrd for Box<T> { #[inline] fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) } } impl<Sized? T: Ord> Ord for Box<T> { #[inline] fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } } impl<Sized? T: Eq> Eq for Box<T> {} /// Extension methods for an owning `Any` trait object. #[unstable = "post-DST and coherence changes, this will not be a trait but \ rather a direct `impl` on `Box<Any>`"] pub trait BoxAny { /// Returns the boxed value if it is of type `T`, or /// `Err(Self)` if it isn't. #[unstable = "naming conventions around accessing innards may change"] fn downcast<T:'static>(self) -> Result<Box<T>, Self>; } #[stable] impl BoxAny for Box<Any> { #[inline] fn downcast<T:'static>(self) -> Result<Box<T>, Box<Any>> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = mem::transmute::<Box<Any>, TraitObject>(self); // Extract the data pointer Ok(mem::transmute(to.data)) } } else { Err(self) } } } impl<Sized? T: fmt::Show> fmt::Show for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } } impl fmt::Show for Box<Any+'static> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("Box<Any>") } } #[cfg(test)] mod test { #[test] fn test_owned_clone() { let a = box 5i; let b: Box<int> = a.clone(); assert!(a == b); } #[test] fn any_move() { let a = box 8u as Box<Any>; let b = box Test as Box<Any>; match a.downcast::<uint>() { Ok(a) => { assert!(a == box 8u); } Err(..) => panic!() } match b.downcast::<Test>() { Ok(a) => { assert!(a == box Test); } Err(..) => panic!() } let a = box 8u as Box<Any>; let b = box Test as Box<Any>; assert!(a.downcast::<Box<Test>>().is_err()); assert!(b.downcast::<Box<uint>>().is_err()); } #[test] fn test_show() { let a = box 8u as Box<Any>; let b = box Test as Box<Any>; let a_str = a.to_str(); let b_str = b.to_str(); assert_eq!(a_str.as_slice(), "Box<Any>"); assert_eq!(b_str.as_slice(), "Box<Any>"); let a = &8u as &Any; let b = &Test as &Any; let s = format!("{}", a); assert_eq!(s.as_slice(), "&Any"); let s = format!("{}", b); assert_eq!(s.as_slice(), "&Any"); } }
{ (**self).clone_from(&(**source)); }
identifier_body
boxed.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A unique pointer type. use core::any::{Any, AnyRefExt}; use core::clone::Clone; use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; use core::fmt; use core::kinds::Sized; use core::mem; use core::option::Option; use core::raw::TraitObject; use core::result::{Ok, Err, Result}; /// A value that represents the global exchange heap. This is the default /// place that the `box` keyword allocates into when no place is supplied. /// /// The following two examples are equivalent: /// /// ```rust /// use std::boxed::HEAP; /// /// # struct Bar; /// # impl Bar { fn new(_a: int) { } } /// let foo = box(HEAP) Bar::new(2); /// let foo = box Bar::new(2); /// ``` #[lang = "exchange_heap"] #[experimental = "may be renamed; uncertain about custom allocator design"] pub static HEAP: () = (); /// A type that represents a uniquely-owned value. #[lang = "owned_box"] #[unstable = "custom allocators will add an additional type parameter (with default)"] pub struct Box<T>(*mut T); impl<T: Default> Default for Box<T> { fn default() -> Box<T> { box Default::default() } } impl<T> Default for Box<[T]> { fn default() -> Box<[T]> { box [] } } #[unstable] impl<T: Clone> Clone for Box<T> { /// Returns a copy of the owned box. #[inline] fn clone(&self) -> Box<T> { box {(**self).clone()} } /// Performs copy-assignment from `source` by reusing the existing allocation. #[inline] fn clone_from(&mut self, source: &Box<T>) { (**self).clone_from(&(**source)); } } impl<Sized? T: PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) } } impl<Sized? T: PartialOrd> PartialOrd for Box<T> { #[inline] fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) } } impl<Sized? T: Ord> Ord for Box<T> { #[inline] fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } } impl<Sized? T: Eq> Eq for Box<T> {} /// Extension methods for an owning `Any` trait object. #[unstable = "post-DST and coherence changes, this will not be a trait but \ rather a direct `impl` on `Box<Any>`"] pub trait BoxAny { /// Returns the boxed value if it is of type `T`, or /// `Err(Self)` if it isn't. #[unstable = "naming conventions around accessing innards may change"] fn downcast<T:'static>(self) -> Result<Box<T>, Self>; } #[stable] impl BoxAny for Box<Any> { #[inline] fn downcast<T:'static>(self) -> Result<Box<T>, Box<Any>> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = mem::transmute::<Box<Any>, TraitObject>(self); // Extract the data pointer Ok(mem::transmute(to.data)) } } else { Err(self) } } } impl<Sized? T: fmt::Show> fmt::Show for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } } impl fmt::Show for Box<Any+'static> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("Box<Any>") } } #[cfg(test)] mod test { #[test] fn test_owned_clone() { let a = box 5i; let b: Box<int> = a.clone(); assert!(a == b); } #[test] fn
() { let a = box 8u as Box<Any>; let b = box Test as Box<Any>; match a.downcast::<uint>() { Ok(a) => { assert!(a == box 8u); } Err(..) => panic!() } match b.downcast::<Test>() { Ok(a) => { assert!(a == box Test); } Err(..) => panic!() } let a = box 8u as Box<Any>; let b = box Test as Box<Any>; assert!(a.downcast::<Box<Test>>().is_err()); assert!(b.downcast::<Box<uint>>().is_err()); } #[test] fn test_show() { let a = box 8u as Box<Any>; let b = box Test as Box<Any>; let a_str = a.to_str(); let b_str = b.to_str(); assert_eq!(a_str.as_slice(), "Box<Any>"); assert_eq!(b_str.as_slice(), "Box<Any>"); let a = &8u as &Any; let b = &Test as &Any; let s = format!("{}", a); assert_eq!(s.as_slice(), "&Any"); let s = format!("{}", b); assert_eq!(s.as_slice(), "&Any"); } }
any_move
identifier_name
model.rs
use Lattice::events::Events; use Lattice::view::View; use ::view::{GameView, Home, Memorial, NewGame, LoadGame, GameHome}; use ::controller::{GameControl}; use ::time; use ::agent::{Class}; use std::sync::{Mutex}; use std::ops::{DerefMut}; lazy_static! { pub static ref GAME_CONTROL: Mutex<GameControl> = Mutex::new( GameControl::new_null() ); } pub struct GameState { view: GameView, } impl GameState { pub fn
() -> GameState { GameState { view: GameView::new(), } } pub fn cycle(s: f64, u: u64) -> usize { (((time::precise_time_s().abs()/s) as u64) % u) as usize } pub fn next_frame(&mut self, events: &mut Events) -> View { self.view.new_frame(); { let mut gmc = GAME_CONTROL.lock().unwrap(); let mut new_game = None; { let ref mut gm = gmc.deref_mut(); let ref friend = gm.target_friend; let ref mut map = gm.map; for msg in events.messages.iter() { if msg[0].as_str() == "view" { self.view.message(msg); } else if msg[0].as_str() == "control" && msg[1].as_str()=="transition" { if msg[2].as_str()=="home" { self.view = GameView::Home(Home::new()); } else if msg[2].as_str()=="new_game" { self.view = GameView::NewGame(NewGame::new()); } else if msg[2].as_str()=="load_game" { self.view = GameView::LoadGame(LoadGame::new()); } else if msg[2].as_str()=="you_died" { self.view = GameView::Memorial(Memorial::new()); } else if msg[2].as_str()=="game_home" && msg[3].as_str()=="new" { let class = Class::from_string(msg[4].as_str()); new_game = Some(GameControl::new(class)); self.view = GameView::GameHome(GameHome::new()); } else { panic!("Unexpected screen transition: {}", msg[2]); } } else if msg[0].as_str() == "control" && msg[1].as_str()=="plan" { let dst: Vec<&str> = msg[2].split(",").collect(); let dst_x = dst[0].parse::<i64>().expect("i64"); let dst_y = dst[1].parse::<i64>().expect("i64"); map.plan(friend, dst_x, dst_y); } } events.messages.clear(); } if let Some(ng) = new_game { *gmc = ng; } { let ref mut gm = gmc.deref_mut(); gm.step(); } } self.view.render() } }
new
identifier_name
model.rs
use Lattice::events::Events; use Lattice::view::View; use ::view::{GameView, Home, Memorial, NewGame, LoadGame, GameHome}; use ::controller::{GameControl}; use ::time; use ::agent::{Class}; use std::sync::{Mutex}; use std::ops::{DerefMut}; lazy_static! { pub static ref GAME_CONTROL: Mutex<GameControl> = Mutex::new( GameControl::new_null() ); } pub struct GameState { view: GameView, } impl GameState { pub fn new() -> GameState { GameState { view: GameView::new(), } } pub fn cycle(s: f64, u: u64) -> usize
pub fn next_frame(&mut self, events: &mut Events) -> View { self.view.new_frame(); { let mut gmc = GAME_CONTROL.lock().unwrap(); let mut new_game = None; { let ref mut gm = gmc.deref_mut(); let ref friend = gm.target_friend; let ref mut map = gm.map; for msg in events.messages.iter() { if msg[0].as_str() == "view" { self.view.message(msg); } else if msg[0].as_str() == "control" && msg[1].as_str()=="transition" { if msg[2].as_str()=="home" { self.view = GameView::Home(Home::new()); } else if msg[2].as_str()=="new_game" { self.view = GameView::NewGame(NewGame::new()); } else if msg[2].as_str()=="load_game" { self.view = GameView::LoadGame(LoadGame::new()); } else if msg[2].as_str()=="you_died" { self.view = GameView::Memorial(Memorial::new()); } else if msg[2].as_str()=="game_home" && msg[3].as_str()=="new" { let class = Class::from_string(msg[4].as_str()); new_game = Some(GameControl::new(class)); self.view = GameView::GameHome(GameHome::new()); } else { panic!("Unexpected screen transition: {}", msg[2]); } } else if msg[0].as_str() == "control" && msg[1].as_str()=="plan" { let dst: Vec<&str> = msg[2].split(",").collect(); let dst_x = dst[0].parse::<i64>().expect("i64"); let dst_y = dst[1].parse::<i64>().expect("i64"); map.plan(friend, dst_x, dst_y); } } events.messages.clear(); } if let Some(ng) = new_game { *gmc = ng; } { let ref mut gm = gmc.deref_mut(); gm.step(); } } self.view.render() } }
{ (((time::precise_time_s().abs()/s) as u64) % u) as usize }
identifier_body
model.rs
use Lattice::events::Events; use Lattice::view::View; use ::view::{GameView, Home, Memorial, NewGame, LoadGame, GameHome}; use ::controller::{GameControl}; use ::time; use ::agent::{Class}; use std::sync::{Mutex}; use std::ops::{DerefMut}; lazy_static! { pub static ref GAME_CONTROL: Mutex<GameControl> = Mutex::new( GameControl::new_null() ); } pub struct GameState { view: GameView, } impl GameState { pub fn new() -> GameState { GameState { view: GameView::new(), } } pub fn cycle(s: f64, u: u64) -> usize { (((time::precise_time_s().abs()/s) as u64) % u) as usize } pub fn next_frame(&mut self, events: &mut Events) -> View { self.view.new_frame(); { let mut gmc = GAME_CONTROL.lock().unwrap(); let mut new_game = None; { let ref mut gm = gmc.deref_mut(); let ref friend = gm.target_friend; let ref mut map = gm.map; for msg in events.messages.iter() { if msg[0].as_str() == "view"
else if msg[0].as_str() == "control" && msg[1].as_str()=="transition" { if msg[2].as_str()=="home" { self.view = GameView::Home(Home::new()); } else if msg[2].as_str()=="new_game" { self.view = GameView::NewGame(NewGame::new()); } else if msg[2].as_str()=="load_game" { self.view = GameView::LoadGame(LoadGame::new()); } else if msg[2].as_str()=="you_died" { self.view = GameView::Memorial(Memorial::new()); } else if msg[2].as_str()=="game_home" && msg[3].as_str()=="new" { let class = Class::from_string(msg[4].as_str()); new_game = Some(GameControl::new(class)); self.view = GameView::GameHome(GameHome::new()); } else { panic!("Unexpected screen transition: {}", msg[2]); } } else if msg[0].as_str() == "control" && msg[1].as_str()=="plan" { let dst: Vec<&str> = msg[2].split(",").collect(); let dst_x = dst[0].parse::<i64>().expect("i64"); let dst_y = dst[1].parse::<i64>().expect("i64"); map.plan(friend, dst_x, dst_y); } } events.messages.clear(); } if let Some(ng) = new_game { *gmc = ng; } { let ref mut gm = gmc.deref_mut(); gm.step(); } } self.view.render() } }
{ self.view.message(msg); }
conditional_block
model.rs
use Lattice::events::Events; use Lattice::view::View; use ::view::{GameView, Home, Memorial, NewGame, LoadGame, GameHome}; use ::controller::{GameControl}; use ::time; use ::agent::{Class}; use std::sync::{Mutex}; use std::ops::{DerefMut}; lazy_static! { pub static ref GAME_CONTROL: Mutex<GameControl> = Mutex::new( GameControl::new_null() ); } pub struct GameState { view: GameView, } impl GameState { pub fn new() -> GameState { GameState { view: GameView::new(), } } pub fn cycle(s: f64, u: u64) -> usize { (((time::precise_time_s().abs()/s) as u64) % u) as usize } pub fn next_frame(&mut self, events: &mut Events) -> View { self.view.new_frame(); { let mut gmc = GAME_CONTROL.lock().unwrap(); let mut new_game = None; {
for msg in events.messages.iter() { if msg[0].as_str() == "view" { self.view.message(msg); } else if msg[0].as_str() == "control" && msg[1].as_str()=="transition" { if msg[2].as_str()=="home" { self.view = GameView::Home(Home::new()); } else if msg[2].as_str()=="new_game" { self.view = GameView::NewGame(NewGame::new()); } else if msg[2].as_str()=="load_game" { self.view = GameView::LoadGame(LoadGame::new()); } else if msg[2].as_str()=="you_died" { self.view = GameView::Memorial(Memorial::new()); } else if msg[2].as_str()=="game_home" && msg[3].as_str()=="new" { let class = Class::from_string(msg[4].as_str()); new_game = Some(GameControl::new(class)); self.view = GameView::GameHome(GameHome::new()); } else { panic!("Unexpected screen transition: {}", msg[2]); } } else if msg[0].as_str() == "control" && msg[1].as_str()=="plan" { let dst: Vec<&str> = msg[2].split(",").collect(); let dst_x = dst[0].parse::<i64>().expect("i64"); let dst_y = dst[1].parse::<i64>().expect("i64"); map.plan(friend, dst_x, dst_y); } } events.messages.clear(); } if let Some(ng) = new_game { *gmc = ng; } { let ref mut gm = gmc.deref_mut(); gm.step(); } } self.view.render() } }
let ref mut gm = gmc.deref_mut(); let ref friend = gm.target_friend; let ref mut map = gm.map;
random_line_split
with_borders_layout.rs
extern crate wtftw; use self::wtftw::config::GeneralConfig; use self::wtftw::core::stack::Stack; use self::wtftw::layout::Layout; use self::wtftw::layout::LayoutMessage; use self::wtftw::window_system::Rectangle; use self::wtftw::window_system::Window; use self::wtftw::window_system::WindowSystem; pub struct WithBordersLayout { border: u32, layout: Box<Layout> } impl WithBordersLayout { pub fn new(border: u32, layout: Box<Layout>) -> Box<Layout> { Box::new(WithBordersLayout { border: border, layout: layout.copy() }) } } impl Layout for WithBordersLayout { fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &GeneralConfig, stack: &Option<Stack<Window>>) -> Vec<(Window, Rectangle)> { if let &Some(ref s) = stack { for window in s.integrate().into_iter() { window_system.set_window_border_width(window, self.border); } } self.layout.apply_layout(window_system, screen, config, stack) } fn apply_message(&mut self, message: LayoutMessage, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) -> bool { self.layout.apply_message(message, window_system, stack, config) } fn description(&self) -> String { self.layout.description() } fn copy(&self) -> Box<Layout>
fn unhook(&self, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) { if let &Some(ref s) = stack { for window in s.integrate().into_iter() { window_system.set_window_border_width(window, config.border_width); let Rectangle(_, _, w, h) = window_system.get_geometry(window); window_system.resize_window(window, w + 2 * config.border_width, h + 2 * config.border_width); } } } }
{ Box::new(WithBordersLayout { border: self.border, layout: self.layout.copy() }) }
identifier_body
with_borders_layout.rs
extern crate wtftw; use self::wtftw::config::GeneralConfig; use self::wtftw::core::stack::Stack; use self::wtftw::layout::Layout; use self::wtftw::layout::LayoutMessage; use self::wtftw::window_system::Rectangle; use self::wtftw::window_system::Window; use self::wtftw::window_system::WindowSystem; pub struct WithBordersLayout { border: u32, layout: Box<Layout> } impl WithBordersLayout { pub fn new(border: u32, layout: Box<Layout>) -> Box<Layout> { Box::new(WithBordersLayout { border: border, layout: layout.copy() }) } } impl Layout for WithBordersLayout { fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &GeneralConfig, stack: &Option<Stack<Window>>) -> Vec<(Window, Rectangle)> { if let &Some(ref s) = stack { for window in s.integrate().into_iter() { window_system.set_window_border_width(window, self.border); } } self.layout.apply_layout(window_system, screen, config, stack) } fn apply_message(&mut self, message: LayoutMessage, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) -> bool { self.layout.apply_message(message, window_system, stack, config) } fn description(&self) -> String { self.layout.description() } fn copy(&self) -> Box<Layout> { Box::new(WithBordersLayout { border: self.border, layout: self.layout.copy() }) } fn unhook(&self, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) { if let &Some(ref s) = stack
} }
{ for window in s.integrate().into_iter() { window_system.set_window_border_width(window, config.border_width); let Rectangle(_, _, w, h) = window_system.get_geometry(window); window_system.resize_window(window, w + 2 * config.border_width, h + 2 * config.border_width); } }
conditional_block
with_borders_layout.rs
extern crate wtftw; use self::wtftw::config::GeneralConfig; use self::wtftw::core::stack::Stack; use self::wtftw::layout::Layout; use self::wtftw::layout::LayoutMessage; use self::wtftw::window_system::Rectangle; use self::wtftw::window_system::Window; use self::wtftw::window_system::WindowSystem; pub struct WithBordersLayout { border: u32, layout: Box<Layout> } impl WithBordersLayout { pub fn
(border: u32, layout: Box<Layout>) -> Box<Layout> { Box::new(WithBordersLayout { border: border, layout: layout.copy() }) } } impl Layout for WithBordersLayout { fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &GeneralConfig, stack: &Option<Stack<Window>>) -> Vec<(Window, Rectangle)> { if let &Some(ref s) = stack { for window in s.integrate().into_iter() { window_system.set_window_border_width(window, self.border); } } self.layout.apply_layout(window_system, screen, config, stack) } fn apply_message(&mut self, message: LayoutMessage, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) -> bool { self.layout.apply_message(message, window_system, stack, config) } fn description(&self) -> String { self.layout.description() } fn copy(&self) -> Box<Layout> { Box::new(WithBordersLayout { border: self.border, layout: self.layout.copy() }) } fn unhook(&self, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) { if let &Some(ref s) = stack { for window in s.integrate().into_iter() { window_system.set_window_border_width(window, config.border_width); let Rectangle(_, _, w, h) = window_system.get_geometry(window); window_system.resize_window(window, w + 2 * config.border_width, h + 2 * config.border_width); } } } }
new
identifier_name
with_borders_layout.rs
extern crate wtftw; use self::wtftw::config::GeneralConfig; use self::wtftw::core::stack::Stack; use self::wtftw::layout::Layout; use self::wtftw::layout::LayoutMessage; use self::wtftw::window_system::Rectangle; use self::wtftw::window_system::Window; use self::wtftw::window_system::WindowSystem; pub struct WithBordersLayout { border: u32, layout: Box<Layout> } impl WithBordersLayout { pub fn new(border: u32, layout: Box<Layout>) -> Box<Layout> { Box::new(WithBordersLayout { border: border, layout: layout.copy() }) } } impl Layout for WithBordersLayout { fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &GeneralConfig, stack: &Option<Stack<Window>>) -> Vec<(Window, Rectangle)> { if let &Some(ref s) = stack {
} fn apply_message(&mut self, message: LayoutMessage, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) -> bool { self.layout.apply_message(message, window_system, stack, config) } fn description(&self) -> String { self.layout.description() } fn copy(&self) -> Box<Layout> { Box::new(WithBordersLayout { border: self.border, layout: self.layout.copy() }) } fn unhook(&self, window_system: &WindowSystem, stack: &Option<Stack<Window>>, config: &GeneralConfig) { if let &Some(ref s) = stack { for window in s.integrate().into_iter() { window_system.set_window_border_width(window, config.border_width); let Rectangle(_, _, w, h) = window_system.get_geometry(window); window_system.resize_window(window, w + 2 * config.border_width, h + 2 * config.border_width); } } } }
for window in s.integrate().into_iter() { window_system.set_window_border_width(window, self.border); } } self.layout.apply_layout(window_system, screen, config, stack)
random_line_split
namespace.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::hir; use rustc::ty; // Whether an item exists in the type or value namespace. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Namespace { Type, Value, } impl From<ty::AssociatedKind> for Namespace { fn from(a_kind: ty::AssociatedKind) -> Self { match a_kind { ty::AssociatedKind::Existential | ty::AssociatedKind::Type => Namespace::Type, ty::AssociatedKind::Const | ty::AssociatedKind::Method => Namespace::Value, }
fn from(impl_kind: &'a hir::ImplItemKind) -> Self { match *impl_kind { hir::ImplItemKind::Existential(..) | hir::ImplItemKind::Type(..) => Namespace::Type, hir::ImplItemKind::Const(..) | hir::ImplItemKind::Method(..) => Namespace::Value, } } }
} } impl<'a> From <&'a hir::ImplItemKind> for Namespace {
random_line_split
namespace.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::hir; use rustc::ty; // Whether an item exists in the type or value namespace. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Namespace { Type, Value, } impl From<ty::AssociatedKind> for Namespace { fn from(a_kind: ty::AssociatedKind) -> Self { match a_kind { ty::AssociatedKind::Existential | ty::AssociatedKind::Type => Namespace::Type, ty::AssociatedKind::Const | ty::AssociatedKind::Method => Namespace::Value, } } } impl<'a> From <&'a hir::ImplItemKind> for Namespace { fn from(impl_kind: &'a hir::ImplItemKind) -> Self
}
{ match *impl_kind { hir::ImplItemKind::Existential(..) | hir::ImplItemKind::Type(..) => Namespace::Type, hir::ImplItemKind::Const(..) | hir::ImplItemKind::Method(..) => Namespace::Value, } }
identifier_body
namespace.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::hir; use rustc::ty; // Whether an item exists in the type or value namespace. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum
{ Type, Value, } impl From<ty::AssociatedKind> for Namespace { fn from(a_kind: ty::AssociatedKind) -> Self { match a_kind { ty::AssociatedKind::Existential | ty::AssociatedKind::Type => Namespace::Type, ty::AssociatedKind::Const | ty::AssociatedKind::Method => Namespace::Value, } } } impl<'a> From <&'a hir::ImplItemKind> for Namespace { fn from(impl_kind: &'a hir::ImplItemKind) -> Self { match *impl_kind { hir::ImplItemKind::Existential(..) | hir::ImplItemKind::Type(..) => Namespace::Type, hir::ImplItemKind::Const(..) | hir::ImplItemKind::Method(..) => Namespace::Value, } } }
Namespace
identifier_name
main.rs
extern crate rustbox; extern crate vex; extern crate getopts; use getopts::Options; use std::env; use std::path::Path; use self::rustbox::{RustBox}; use vex::editor::{State}; fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = State::new(rustbox.width(), rustbox.height()); for name in matches.free { state.open(Path::new(&name)); } state.edit(&rustbox); } fn print_usage(program: &str, opts: Options)
{ let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); }
identifier_body
main.rs
extern crate rustbox; extern crate vex; extern crate getopts; use getopts::Options; use std::env; use std::path::Path; use self::rustbox::{RustBox}; use vex::editor::{State}; fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h")
let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = State::new(rustbox.width(), rustbox.height()); for name in matches.free { state.open(Path::new(&name)); } state.edit(&rustbox); } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); }
{ print_usage(&program, opts); return; }
conditional_block
main.rs
extern crate rustbox; extern crate vex; extern crate getopts; use getopts::Options; use std::env; use std::path::Path; use self::rustbox::{RustBox}; use vex::editor::{State}; fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m }
print_usage(&program, opts); return; } let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = State::new(rustbox.width(), rustbox.height()); for name in matches.free { state.open(Path::new(&name)); } state.edit(&rustbox); } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); }
Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") {
random_line_split
main.rs
extern crate rustbox; extern crate vex; extern crate getopts; use getopts::Options; use std::env; use std::path::Path; use self::rustbox::{RustBox}; use vex::editor::{State}; fn
() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = State::new(rustbox.width(), rustbox.height()); for name in matches.free { state.open(Path::new(&name)); } state.edit(&rustbox); } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); }
main
identifier_name
bindless.rs
/*! Without bindless textures, using a texture in a shader requires binding the texture to a specific bind point before drawing. This not only slows down rendering, but may also prevent you from grouping multiple draw calls into one because of the limitation to the number of available texture units. Instead, bindless textures allow you to manually manipulate pointers to textures in video memory. You can use thousands of textures if you want. # Initialization Before using a bindless texture, you must turn it into a `ResidentTexture`. This is done by calling `resident` on the texture you want. Bindless textures are a very recent feature that is supported only by recent hardware and drivers. `resident` will return an `Err` if this feature is not supported. ```no_run # let display: glium::Display = unsafe { std::mem::uninitialized() }; # let texture: glium::texture::Texture2d = unsafe { std::mem::uninitialized() }; let texture = texture.resident().unwrap(); ``` In a real application, you will likely manage a `Vec<ResidentTexture>`. # Usage You can then use a `TextureHandle` as if it was a pointer to a texture. A `TextureHandle` can be built from a `&ResidentTexture` and can't outlive it. ```no_run #[macro_use] extern crate glium; # fn main() { #[derive(Copy, Clone)] struct UniformBuffer<'a> { texture: glium::texture::TextureHandle<'a>, some_value: f32, } implement_uniform_block!(UniformBuffer<'a>, texture, some_value); # let display: glium::Display = unsafe { std::mem::uninitialized() }; # let texture: glium::texture::bindless::ResidentTexture = unsafe { std::mem::uninitialized() }; let uniform_buffer = glium::uniforms::UniformBuffer::new(&display, UniformBuffer { texture: glium::texture::TextureHandle::new(&texture, &Default::default()), some_value: 5.0, }); # } ``` Inside your shader, you can refer to the texture with a traditional `sampler*` variable. Glium
*/ use texture::any::TextureAny; use TextureExt; use GlObject; use ContextExt; use gl; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use program::BlockLayout; use uniforms::AsUniformValue; use uniforms::LayoutMismatchError; use uniforms::UniformBlock; use uniforms::UniformValue; use uniforms::UniformType; use uniforms::SamplerBehavior; /// A texture that is resident in video memory. This allows you to use bindless textures in your /// shaders. pub struct ResidentTexture { texture: Option<TextureAny>, handle: gl::types::GLuint64, } impl ResidentTexture { /// Takes ownership of the given texture and makes it resident. // TODO: sampler pub fn new(texture: TextureAny) -> Result<ResidentTexture, BindlessTexturesNotSupportedError> { let handle = { let mut ctxt = texture.get_context().make_current(); if!ctxt.extensions.gl_arb_bindless_texture { return Err(BindlessTexturesNotSupportedError); } let handle = unsafe { ctxt.gl.GetTextureHandleARB(texture.get_id()) }; unsafe { ctxt.gl.MakeTextureHandleResidentARB(handle) }; ctxt.resident_texture_handles.push(handle); handle }; // store the handle in the context Ok(ResidentTexture { texture: Some(texture), handle: handle, }) } /// Unwraps the texture and restores it. #[inline] pub fn into_inner(mut self) -> TextureAny { self.into_inner_impl() } /// Implementation of `into_inner`. Also called by the destructor. fn into_inner_impl(&mut self) -> TextureAny { let texture = self.texture.take().unwrap(); { let mut ctxt = texture.get_context().make_current(); unsafe { ctxt.gl.MakeTextureHandleNonResidentARB(self.handle) }; ctxt.resident_texture_handles.retain(|&t| t!= self.handle); } texture } } impl Deref for ResidentTexture { type Target = TextureAny; #[inline] fn deref(&self) -> &TextureAny { self.texture.as_ref().unwrap() } } impl DerefMut for ResidentTexture { #[inline] fn deref_mut(&mut self) -> &mut TextureAny { self.texture.as_mut().unwrap() } } impl Drop for ResidentTexture { #[inline] fn drop(&mut self) { self.into_inner_impl(); } } /// Represents a handle to a texture. Contains a raw pointer to a texture that is hidden from you. #[derive(Copy, Clone)] pub struct TextureHandle<'a> { value: gl::types::GLuint64, marker: PhantomData<&'a ResidentTexture>, } impl<'a> TextureHandle<'a> { /// Builds a new handle. #[inline] pub fn new(texture: &'a ResidentTexture, _: &SamplerBehavior) -> TextureHandle<'a> { // FIXME: take sampler into account TextureHandle { value: texture.handle, marker: PhantomData, } } /// Sets the value to the given texture. #[inline] pub fn set(&mut self, texture: &'a ResidentTexture, _: &SamplerBehavior) { // FIXME: take sampler into account self.value = texture.handle; } } impl<'a> AsUniformValue for TextureHandle<'a> { #[inline] fn as_uniform_value(&self) -> UniformValue { // TODO: u64 unimplemented!(); } } impl<'a> UniformBlock for TextureHandle<'a> { fn matches(layout: &BlockLayout, base_offset: usize) -> Result<(), LayoutMismatchError> { if let &BlockLayout::BasicType { ty, offset_in_buffer } = layout { // TODO: unfortunately we have no idea what the exact type of this handle is // strong typing should be considered // // however there is no safety problem here ; the worse that can happen in case of // wrong type is zeroes or undefined data being returned when sampling match ty { UniformType::Sampler1d => (), UniformType::ISampler1d => (), UniformType::USampler1d => (), UniformType::Sampler2d => (), UniformType::ISampler2d => (), UniformType::USampler2d => (), UniformType::Sampler3d => (), UniformType::ISampler3d => (), UniformType::USampler3d => (), UniformType::Sampler1dArray => (), UniformType::ISampler1dArray => (), UniformType::USampler1dArray => (), UniformType::Sampler2dArray => (), UniformType::ISampler2dArray => (), UniformType::USampler2dArray => (), UniformType::SamplerCube => (), UniformType::ISamplerCube => (), UniformType::USamplerCube => (), UniformType::Sampler2dRect => (), UniformType::ISampler2dRect => (), UniformType::USampler2dRect => (), UniformType::Sampler2dRectShadow => (), UniformType::SamplerCubeArray => (), UniformType::ISamplerCubeArray => (), UniformType::USamplerCubeArray => (), UniformType::SamplerBuffer => (), UniformType::ISamplerBuffer => (), UniformType::USamplerBuffer => (), UniformType::Sampler2dMultisample => (), UniformType::ISampler2dMultisample => (), UniformType::USampler2dMultisample => (), UniformType::Sampler2dMultisampleArray => (), UniformType::ISampler2dMultisampleArray => (), UniformType::USampler2dMultisampleArray => (), UniformType::Sampler1dShadow => (), UniformType::Sampler2dShadow => (), UniformType::SamplerCubeShadow => (), UniformType::Sampler1dArrayShadow => (), UniformType::Sampler2dArrayShadow => (), UniformType::SamplerCubeArrayShadow => (), _ => return Err(LayoutMismatchError::TypeMismatch { expected: ty, obtained: UniformType::Sampler2d, // TODO: wrong }) } if offset_in_buffer!= base_offset { return Err(LayoutMismatchError::OffsetMismatch { expected: offset_in_buffer, obtained: base_offset, }); } Ok(()) } else if let &BlockLayout::Struct { ref members } = layout { if members.len() == 1 { <TextureHandle as UniformBlock>::matches(&members[0].1, base_offset) } else { Err(LayoutMismatchError::LayoutMismatch { expected: layout.clone(), obtained: BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } }) } } else { Err(LayoutMismatchError::LayoutMismatch { expected: layout.clone(), obtained: BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } }) } } #[inline] fn build_layout(base_offset: usize) -> BlockLayout { BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } } } // TODO: implement `vertex::Attribute` on `TextureHandle` /// Bindless textures are not supported. #[derive(Debug, Copy, Clone)] pub struct BindlessTexturesNotSupportedError; #[cfg(test)] mod test { use std::mem; use super::TextureHandle; #[test] fn texture_handle_size() { assert_eq!(mem::size_of::<TextureHandle>(), 8); } }
currently doesn't check whether the type of your texture matches the expected type (but it may do in the future). Binding the wrong type of texture may lead to undefined values when sampling the texture.
random_line_split
bindless.rs
/*! Without bindless textures, using a texture in a shader requires binding the texture to a specific bind point before drawing. This not only slows down rendering, but may also prevent you from grouping multiple draw calls into one because of the limitation to the number of available texture units. Instead, bindless textures allow you to manually manipulate pointers to textures in video memory. You can use thousands of textures if you want. # Initialization Before using a bindless texture, you must turn it into a `ResidentTexture`. This is done by calling `resident` on the texture you want. Bindless textures are a very recent feature that is supported only by recent hardware and drivers. `resident` will return an `Err` if this feature is not supported. ```no_run # let display: glium::Display = unsafe { std::mem::uninitialized() }; # let texture: glium::texture::Texture2d = unsafe { std::mem::uninitialized() }; let texture = texture.resident().unwrap(); ``` In a real application, you will likely manage a `Vec<ResidentTexture>`. # Usage You can then use a `TextureHandle` as if it was a pointer to a texture. A `TextureHandle` can be built from a `&ResidentTexture` and can't outlive it. ```no_run #[macro_use] extern crate glium; # fn main() { #[derive(Copy, Clone)] struct UniformBuffer<'a> { texture: glium::texture::TextureHandle<'a>, some_value: f32, } implement_uniform_block!(UniformBuffer<'a>, texture, some_value); # let display: glium::Display = unsafe { std::mem::uninitialized() }; # let texture: glium::texture::bindless::ResidentTexture = unsafe { std::mem::uninitialized() }; let uniform_buffer = glium::uniforms::UniformBuffer::new(&display, UniformBuffer { texture: glium::texture::TextureHandle::new(&texture, &Default::default()), some_value: 5.0, }); # } ``` Inside your shader, you can refer to the texture with a traditional `sampler*` variable. Glium currently doesn't check whether the type of your texture matches the expected type (but it may do in the future). Binding the wrong type of texture may lead to undefined values when sampling the texture. */ use texture::any::TextureAny; use TextureExt; use GlObject; use ContextExt; use gl; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use program::BlockLayout; use uniforms::AsUniformValue; use uniforms::LayoutMismatchError; use uniforms::UniformBlock; use uniforms::UniformValue; use uniforms::UniformType; use uniforms::SamplerBehavior; /// A texture that is resident in video memory. This allows you to use bindless textures in your /// shaders. pub struct ResidentTexture { texture: Option<TextureAny>, handle: gl::types::GLuint64, } impl ResidentTexture { /// Takes ownership of the given texture and makes it resident. // TODO: sampler pub fn new(texture: TextureAny) -> Result<ResidentTexture, BindlessTexturesNotSupportedError> { let handle = { let mut ctxt = texture.get_context().make_current(); if!ctxt.extensions.gl_arb_bindless_texture { return Err(BindlessTexturesNotSupportedError); } let handle = unsafe { ctxt.gl.GetTextureHandleARB(texture.get_id()) }; unsafe { ctxt.gl.MakeTextureHandleResidentARB(handle) }; ctxt.resident_texture_handles.push(handle); handle }; // store the handle in the context Ok(ResidentTexture { texture: Some(texture), handle: handle, }) } /// Unwraps the texture and restores it. #[inline] pub fn into_inner(mut self) -> TextureAny { self.into_inner_impl() } /// Implementation of `into_inner`. Also called by the destructor. fn into_inner_impl(&mut self) -> TextureAny { let texture = self.texture.take().unwrap(); { let mut ctxt = texture.get_context().make_current(); unsafe { ctxt.gl.MakeTextureHandleNonResidentARB(self.handle) }; ctxt.resident_texture_handles.retain(|&t| t!= self.handle); } texture } } impl Deref for ResidentTexture { type Target = TextureAny; #[inline] fn deref(&self) -> &TextureAny { self.texture.as_ref().unwrap() } } impl DerefMut for ResidentTexture { #[inline] fn deref_mut(&mut self) -> &mut TextureAny { self.texture.as_mut().unwrap() } } impl Drop for ResidentTexture { #[inline] fn drop(&mut self) { self.into_inner_impl(); } } /// Represents a handle to a texture. Contains a raw pointer to a texture that is hidden from you. #[derive(Copy, Clone)] pub struct TextureHandle<'a> { value: gl::types::GLuint64, marker: PhantomData<&'a ResidentTexture>, } impl<'a> TextureHandle<'a> { /// Builds a new handle. #[inline] pub fn new(texture: &'a ResidentTexture, _: &SamplerBehavior) -> TextureHandle<'a> { // FIXME: take sampler into account TextureHandle { value: texture.handle, marker: PhantomData, } } /// Sets the value to the given texture. #[inline] pub fn set(&mut self, texture: &'a ResidentTexture, _: &SamplerBehavior) { // FIXME: take sampler into account self.value = texture.handle; } } impl<'a> AsUniformValue for TextureHandle<'a> { #[inline] fn as_uniform_value(&self) -> UniformValue { // TODO: u64 unimplemented!(); } } impl<'a> UniformBlock for TextureHandle<'a> { fn matches(layout: &BlockLayout, base_offset: usize) -> Result<(), LayoutMismatchError> { if let &BlockLayout::BasicType { ty, offset_in_buffer } = layout { // TODO: unfortunately we have no idea what the exact type of this handle is // strong typing should be considered // // however there is no safety problem here ; the worse that can happen in case of // wrong type is zeroes or undefined data being returned when sampling match ty { UniformType::Sampler1d => (), UniformType::ISampler1d => (), UniformType::USampler1d => (), UniformType::Sampler2d => (), UniformType::ISampler2d => (), UniformType::USampler2d => (), UniformType::Sampler3d => (), UniformType::ISampler3d => (), UniformType::USampler3d => (), UniformType::Sampler1dArray => (), UniformType::ISampler1dArray => (), UniformType::USampler1dArray => (), UniformType::Sampler2dArray => (), UniformType::ISampler2dArray => (), UniformType::USampler2dArray => (), UniformType::SamplerCube => (), UniformType::ISamplerCube => (), UniformType::USamplerCube => (), UniformType::Sampler2dRect => (), UniformType::ISampler2dRect => (), UniformType::USampler2dRect => (), UniformType::Sampler2dRectShadow => (), UniformType::SamplerCubeArray => (), UniformType::ISamplerCubeArray => (), UniformType::USamplerCubeArray => (), UniformType::SamplerBuffer => (), UniformType::ISamplerBuffer => (), UniformType::USamplerBuffer => (), UniformType::Sampler2dMultisample => (), UniformType::ISampler2dMultisample => (), UniformType::USampler2dMultisample => (), UniformType::Sampler2dMultisampleArray => (), UniformType::ISampler2dMultisampleArray => (), UniformType::USampler2dMultisampleArray => (), UniformType::Sampler1dShadow => (), UniformType::Sampler2dShadow => (), UniformType::SamplerCubeShadow => (), UniformType::Sampler1dArrayShadow => (), UniformType::Sampler2dArrayShadow => (), UniformType::SamplerCubeArrayShadow => (), _ => return Err(LayoutMismatchError::TypeMismatch { expected: ty, obtained: UniformType::Sampler2d, // TODO: wrong }) } if offset_in_buffer!= base_offset { return Err(LayoutMismatchError::OffsetMismatch { expected: offset_in_buffer, obtained: base_offset, }); } Ok(()) } else if let &BlockLayout::Struct { ref members } = layout { if members.len() == 1 { <TextureHandle as UniformBlock>::matches(&members[0].1, base_offset) } else { Err(LayoutMismatchError::LayoutMismatch { expected: layout.clone(), obtained: BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } }) } } else { Err(LayoutMismatchError::LayoutMismatch { expected: layout.clone(), obtained: BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } }) } } #[inline] fn build_layout(base_offset: usize) -> BlockLayout
} // TODO: implement `vertex::Attribute` on `TextureHandle` /// Bindless textures are not supported. #[derive(Debug, Copy, Clone)] pub struct BindlessTexturesNotSupportedError; #[cfg(test)] mod test { use std::mem; use super::TextureHandle; #[test] fn texture_handle_size() { assert_eq!(mem::size_of::<TextureHandle>(), 8); } }
{ BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } }
identifier_body
bindless.rs
/*! Without bindless textures, using a texture in a shader requires binding the texture to a specific bind point before drawing. This not only slows down rendering, but may also prevent you from grouping multiple draw calls into one because of the limitation to the number of available texture units. Instead, bindless textures allow you to manually manipulate pointers to textures in video memory. You can use thousands of textures if you want. # Initialization Before using a bindless texture, you must turn it into a `ResidentTexture`. This is done by calling `resident` on the texture you want. Bindless textures are a very recent feature that is supported only by recent hardware and drivers. `resident` will return an `Err` if this feature is not supported. ```no_run # let display: glium::Display = unsafe { std::mem::uninitialized() }; # let texture: glium::texture::Texture2d = unsafe { std::mem::uninitialized() }; let texture = texture.resident().unwrap(); ``` In a real application, you will likely manage a `Vec<ResidentTexture>`. # Usage You can then use a `TextureHandle` as if it was a pointer to a texture. A `TextureHandle` can be built from a `&ResidentTexture` and can't outlive it. ```no_run #[macro_use] extern crate glium; # fn main() { #[derive(Copy, Clone)] struct UniformBuffer<'a> { texture: glium::texture::TextureHandle<'a>, some_value: f32, } implement_uniform_block!(UniformBuffer<'a>, texture, some_value); # let display: glium::Display = unsafe { std::mem::uninitialized() }; # let texture: glium::texture::bindless::ResidentTexture = unsafe { std::mem::uninitialized() }; let uniform_buffer = glium::uniforms::UniformBuffer::new(&display, UniformBuffer { texture: glium::texture::TextureHandle::new(&texture, &Default::default()), some_value: 5.0, }); # } ``` Inside your shader, you can refer to the texture with a traditional `sampler*` variable. Glium currently doesn't check whether the type of your texture matches the expected type (but it may do in the future). Binding the wrong type of texture may lead to undefined values when sampling the texture. */ use texture::any::TextureAny; use TextureExt; use GlObject; use ContextExt; use gl; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use program::BlockLayout; use uniforms::AsUniformValue; use uniforms::LayoutMismatchError; use uniforms::UniformBlock; use uniforms::UniformValue; use uniforms::UniformType; use uniforms::SamplerBehavior; /// A texture that is resident in video memory. This allows you to use bindless textures in your /// shaders. pub struct ResidentTexture { texture: Option<TextureAny>, handle: gl::types::GLuint64, } impl ResidentTexture { /// Takes ownership of the given texture and makes it resident. // TODO: sampler pub fn new(texture: TextureAny) -> Result<ResidentTexture, BindlessTexturesNotSupportedError> { let handle = { let mut ctxt = texture.get_context().make_current(); if!ctxt.extensions.gl_arb_bindless_texture { return Err(BindlessTexturesNotSupportedError); } let handle = unsafe { ctxt.gl.GetTextureHandleARB(texture.get_id()) }; unsafe { ctxt.gl.MakeTextureHandleResidentARB(handle) }; ctxt.resident_texture_handles.push(handle); handle }; // store the handle in the context Ok(ResidentTexture { texture: Some(texture), handle: handle, }) } /// Unwraps the texture and restores it. #[inline] pub fn into_inner(mut self) -> TextureAny { self.into_inner_impl() } /// Implementation of `into_inner`. Also called by the destructor. fn into_inner_impl(&mut self) -> TextureAny { let texture = self.texture.take().unwrap(); { let mut ctxt = texture.get_context().make_current(); unsafe { ctxt.gl.MakeTextureHandleNonResidentARB(self.handle) }; ctxt.resident_texture_handles.retain(|&t| t!= self.handle); } texture } } impl Deref for ResidentTexture { type Target = TextureAny; #[inline] fn deref(&self) -> &TextureAny { self.texture.as_ref().unwrap() } } impl DerefMut for ResidentTexture { #[inline] fn deref_mut(&mut self) -> &mut TextureAny { self.texture.as_mut().unwrap() } } impl Drop for ResidentTexture { #[inline] fn drop(&mut self) { self.into_inner_impl(); } } /// Represents a handle to a texture. Contains a raw pointer to a texture that is hidden from you. #[derive(Copy, Clone)] pub struct TextureHandle<'a> { value: gl::types::GLuint64, marker: PhantomData<&'a ResidentTexture>, } impl<'a> TextureHandle<'a> { /// Builds a new handle. #[inline] pub fn
(texture: &'a ResidentTexture, _: &SamplerBehavior) -> TextureHandle<'a> { // FIXME: take sampler into account TextureHandle { value: texture.handle, marker: PhantomData, } } /// Sets the value to the given texture. #[inline] pub fn set(&mut self, texture: &'a ResidentTexture, _: &SamplerBehavior) { // FIXME: take sampler into account self.value = texture.handle; } } impl<'a> AsUniformValue for TextureHandle<'a> { #[inline] fn as_uniform_value(&self) -> UniformValue { // TODO: u64 unimplemented!(); } } impl<'a> UniformBlock for TextureHandle<'a> { fn matches(layout: &BlockLayout, base_offset: usize) -> Result<(), LayoutMismatchError> { if let &BlockLayout::BasicType { ty, offset_in_buffer } = layout { // TODO: unfortunately we have no idea what the exact type of this handle is // strong typing should be considered // // however there is no safety problem here ; the worse that can happen in case of // wrong type is zeroes or undefined data being returned when sampling match ty { UniformType::Sampler1d => (), UniformType::ISampler1d => (), UniformType::USampler1d => (), UniformType::Sampler2d => (), UniformType::ISampler2d => (), UniformType::USampler2d => (), UniformType::Sampler3d => (), UniformType::ISampler3d => (), UniformType::USampler3d => (), UniformType::Sampler1dArray => (), UniformType::ISampler1dArray => (), UniformType::USampler1dArray => (), UniformType::Sampler2dArray => (), UniformType::ISampler2dArray => (), UniformType::USampler2dArray => (), UniformType::SamplerCube => (), UniformType::ISamplerCube => (), UniformType::USamplerCube => (), UniformType::Sampler2dRect => (), UniformType::ISampler2dRect => (), UniformType::USampler2dRect => (), UniformType::Sampler2dRectShadow => (), UniformType::SamplerCubeArray => (), UniformType::ISamplerCubeArray => (), UniformType::USamplerCubeArray => (), UniformType::SamplerBuffer => (), UniformType::ISamplerBuffer => (), UniformType::USamplerBuffer => (), UniformType::Sampler2dMultisample => (), UniformType::ISampler2dMultisample => (), UniformType::USampler2dMultisample => (), UniformType::Sampler2dMultisampleArray => (), UniformType::ISampler2dMultisampleArray => (), UniformType::USampler2dMultisampleArray => (), UniformType::Sampler1dShadow => (), UniformType::Sampler2dShadow => (), UniformType::SamplerCubeShadow => (), UniformType::Sampler1dArrayShadow => (), UniformType::Sampler2dArrayShadow => (), UniformType::SamplerCubeArrayShadow => (), _ => return Err(LayoutMismatchError::TypeMismatch { expected: ty, obtained: UniformType::Sampler2d, // TODO: wrong }) } if offset_in_buffer!= base_offset { return Err(LayoutMismatchError::OffsetMismatch { expected: offset_in_buffer, obtained: base_offset, }); } Ok(()) } else if let &BlockLayout::Struct { ref members } = layout { if members.len() == 1 { <TextureHandle as UniformBlock>::matches(&members[0].1, base_offset) } else { Err(LayoutMismatchError::LayoutMismatch { expected: layout.clone(), obtained: BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } }) } } else { Err(LayoutMismatchError::LayoutMismatch { expected: layout.clone(), obtained: BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } }) } } #[inline] fn build_layout(base_offset: usize) -> BlockLayout { BlockLayout::BasicType { ty: UniformType::Sampler2d, // TODO: wrong offset_in_buffer: base_offset, } } } // TODO: implement `vertex::Attribute` on `TextureHandle` /// Bindless textures are not supported. #[derive(Debug, Copy, Clone)] pub struct BindlessTexturesNotSupportedError; #[cfg(test)] mod test { use std::mem; use super::TextureHandle; #[test] fn texture_handle_size() { assert_eq!(mem::size_of::<TextureHandle>(), 8); } }
new
identifier_name
lib.rs
//! //! Core library entry point. //! extern crate rustc_serialize; extern crate byteorder; extern crate bincode; extern crate flate2; extern crate rust_htslib as htslib; use std::fs; use std::io::ErrorKind; use std::process::exit; // generic functions pub fn
<P: AsRef<Path>>(filename: P) -> bool { let ref_filename = filename.as_ref(); match fs::metadata(ref_filename) { Ok(meta) => meta.is_file(), Err(err) => match err.kind() { ErrorKind::NotFound => false, _ => { println!("Failed to open file {}: {:}", ref_filename.to_string_lossy(), err); exit(-1) }, }, } } // private modules mod randfile; // public modules pub mod tallyrun; pub mod tallyread; pub mod seqtable; pub mod fasta; pub mod filter; pub mod counts; pub mod bigwig; pub mod scale; pub mod outputfile; // C API pub mod c_api; pub use c_api::*; use std::path::Path;
file_exists
identifier_name
lib.rs
//! //! Core library entry point. //! extern crate rustc_serialize; extern crate byteorder; extern crate bincode; extern crate flate2; extern crate rust_htslib as htslib; use std::fs; use std::io::ErrorKind; use std::process::exit; // generic functions
pub fn file_exists<P: AsRef<Path>>(filename: P) -> bool { let ref_filename = filename.as_ref(); match fs::metadata(ref_filename) { Ok(meta) => meta.is_file(), Err(err) => match err.kind() { ErrorKind::NotFound => false, _ => { println!("Failed to open file {}: {:}", ref_filename.to_string_lossy(), err); exit(-1) }, }, } } // private modules mod randfile; // public modules pub mod tallyrun; pub mod tallyread; pub mod seqtable; pub mod fasta; pub mod filter; pub mod counts; pub mod bigwig; pub mod scale; pub mod outputfile; // C API pub mod c_api; pub use c_api::*; use std::path::Path;
random_line_split
lib.rs
//! //! Core library entry point. //! extern crate rustc_serialize; extern crate byteorder; extern crate bincode; extern crate flate2; extern crate rust_htslib as htslib; use std::fs; use std::io::ErrorKind; use std::process::exit; // generic functions pub fn file_exists<P: AsRef<Path>>(filename: P) -> bool
// private modules mod randfile; // public modules pub mod tallyrun; pub mod tallyread; pub mod seqtable; pub mod fasta; pub mod filter; pub mod counts; pub mod bigwig; pub mod scale; pub mod outputfile; // C API pub mod c_api; pub use c_api::*; use std::path::Path;
{ let ref_filename = filename.as_ref(); match fs::metadata(ref_filename) { Ok(meta) => meta.is_file(), Err(err) => match err.kind() { ErrorKind::NotFound => false, _ => { println!("Failed to open file {}: {:}", ref_filename.to_string_lossy(), err); exit(-1) }, }, } }
identifier_body
disciplines.rs
use std::collections::HashMap; use crate::common::TeamSize; /// Additional fields for `Discipline` wrap. #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct AdditionalFields(pub HashMap<String, HashMap<String, String>>); /// A game discipline identity. #[derive( Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, )] pub struct DisciplineId(pub String); /// A game discipline object. #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct Discipline { /// An identifier for a discipline, can be used in others APIs. /// Example: "counterstrike_go" pub id: DisciplineId, /// The official name of the discipline. /// Example: "Counter-Strike: GO" pub name: String, /// The short name of the discipline. /// Example: "CS:GO" #[serde(rename = "shortname")] pub short_name: String, /// The complete name of the discipline. /// Example: "Counter-Strike: Global Offensive" #[serde(rename = "fullname")] pub full_name: String, /// The name of the publisher of the discipline or any other right related information about the owner of the discipline. /// Example: "Valve Software" pub copyrights: String, /// (Optional) Sets the minimum and maximum of players in a team. /// Example: (4, 8), where `4` is minimal size of a team in the tournament /// and `8` is maximal size of a team in the tournament. #[serde(skip_serializing_if = "Option::is_none")] pub team_size: Option<TeamSize>, /// (Optional) Additional fields concerning the discipline. /// Note about the special fields in this API: if the field is mentioned, you must use one of the following values. #[serde(skip_serializing_if = "Option::is_none")] pub additional_fields: Option<AdditionalFields>, } impl Discipline { /// Creates new `Discipline` object. pub fn
<S: Into<String>>( id: DisciplineId, name: S, short_name: S, full_name: S, copyrights: S, ) -> Discipline { Discipline { id, name: name.into(), short_name: short_name.into(), full_name: full_name.into(), copyrights: copyrights.into(), team_size: None, additional_fields: None, } } builder!(id, DisciplineId); builder_s!(name); builder_s!(short_name); builder_s!(full_name); builder_s!(copyrights); builder!(team_size, Option<TeamSize>); builder!(additional_fields, Option<AdditionalFields>); } impl Discipline { /// Returns iter for the discipline pub fn iter<'a>(&self, client: &'a crate::Toornament) -> crate::DisciplineIter<'a> { crate::DisciplineIter::new(client, self.id.clone()) } /// Converts discipline into an iter pub fn into_iter(self, client: &crate::Toornament) -> crate::DisciplineIter<'_> { crate::DisciplineIter::new(client, self.id) } } /// A list of `Discipline` objects. #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct Disciplines(pub Vec<Discipline>); #[cfg(test)] mod tests { use super::{Discipline, DisciplineId, Disciplines}; #[test] fn test_discipline_parse() { let string = r#"{ "id": "counterstrike_go", "name": "Counter-Strike: GO", "shortname": "CS:GO", "fullname": "Counter-Strike: Global Offensive", "copyrights": "Valve Software" }"#; let d: Discipline = serde_json::from_str(string).unwrap(); assert_eq!(d.id.0, "counterstrike_go"); assert_eq!(d.name, "Counter-Strike: GO"); assert_eq!(d.short_name, "CS:GO"); assert_eq!(d.full_name, "Counter-Strike: Global Offensive"); assert_eq!(d.copyrights, "Valve Software"); } #[test] fn test_discipline_full_parse() { let string = r#"{ "id": "cod4", "name": "COD4:MW", "shortname": "COD4", "fullname": "Call of Duty 4 : Modern Warfare", "copyrights": "Infinity Ward / Activision", "team_size": { "min": 4, "max": 4 }, "additional_fields": { "field_name": { "value": "label" } } }"#; let d: Discipline = serde_json::from_str(string).unwrap(); assert_eq!(d.id.0, "cod4"); assert_eq!(d.name, "COD4:MW"); assert_eq!(d.short_name, "COD4"); assert_eq!(d.full_name, "Call of Duty 4 : Modern Warfare"); assert_eq!(d.copyrights, r#"Infinity Ward / Activision"#); assert!(d.team_size.is_some()); let ts = d.team_size.unwrap(); // safe assert_eq!(ts.min, 4i64); assert_eq!(ts.max, 4i64); assert!(d.additional_fields.is_some()); let af = d.additional_fields.unwrap(); // safe assert_eq!(af.0.len(), 1); let first = af.0.into_iter().next().unwrap(); // safe assert_eq!(first.0, "field_name"); assert_eq!(first.1.len(), 1); let first_value = first.1.into_iter().next().unwrap(); // safe assert_eq!(first_value.0, "value"); assert_eq!(first_value.1, "label"); } #[test] fn test_disciplines_parse() { let string = r#"[ { "id": "counterstrike_go", "name": "Counter-Strike: GO", "shortname": "CS:GO", "fullname": "Counter-Strike: Global Offensive", "copyrights": "Valve Software" }, { "id": "quakelive", "name": "Quake Live", "shortname": "QL", "fullname": "Quake Live", "copyrights": "id Software" } ]"#; let ds: Disciplines = serde_json::from_str(string).unwrap(); assert_eq!(ds.0.len(), 2); let correct_disciplines = vec![ Discipline::new( DisciplineId("counterstrike_go".to_owned()), "Counter-Strike: GO", "CS:GO", "Counter-Strike: Global Offensive", "Valve Software", ), Discipline::new( DisciplineId("quakelive".to_owned()), "Quake Live", "QL", "Quake Live", "id Software", ), ]; let iter = ds.0.iter().zip(correct_disciplines.iter()); for pair in iter { assert_eq!(pair.0.id, pair.1.id); assert_eq!(pair.0.name, pair.1.name); assert_eq!(pair.0.short_name, pair.1.short_name); assert_eq!(pair.0.full_name, pair.1.full_name); assert_eq!(pair.0.copyrights, pair.1.copyrights); } } }
new
identifier_name
disciplines.rs
use std::collections::HashMap; use crate::common::TeamSize; /// Additional fields for `Discipline` wrap. #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct AdditionalFields(pub HashMap<String, HashMap<String, String>>); /// A game discipline identity. #[derive( Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, )] pub struct DisciplineId(pub String); /// A game discipline object. #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct Discipline { /// An identifier for a discipline, can be used in others APIs. /// Example: "counterstrike_go" pub id: DisciplineId, /// The official name of the discipline. /// Example: "Counter-Strike: GO" pub name: String, /// The short name of the discipline. /// Example: "CS:GO" #[serde(rename = "shortname")] pub short_name: String, /// The complete name of the discipline. /// Example: "Counter-Strike: Global Offensive" #[serde(rename = "fullname")] pub full_name: String, /// The name of the publisher of the discipline or any other right related information about the owner of the discipline. /// Example: "Valve Software" pub copyrights: String, /// (Optional) Sets the minimum and maximum of players in a team. /// Example: (4, 8), where `4` is minimal size of a team in the tournament /// and `8` is maximal size of a team in the tournament. #[serde(skip_serializing_if = "Option::is_none")] pub team_size: Option<TeamSize>, /// (Optional) Additional fields concerning the discipline. /// Note about the special fields in this API: if the field is mentioned, you must use one of the following values. #[serde(skip_serializing_if = "Option::is_none")] pub additional_fields: Option<AdditionalFields>, } impl Discipline { /// Creates new `Discipline` object. pub fn new<S: Into<String>>( id: DisciplineId, name: S, short_name: S, full_name: S, copyrights: S, ) -> Discipline { Discipline { id, name: name.into(), short_name: short_name.into(), full_name: full_name.into(), copyrights: copyrights.into(), team_size: None, additional_fields: None, } } builder!(id, DisciplineId); builder_s!(name); builder_s!(short_name); builder_s!(full_name); builder_s!(copyrights); builder!(team_size, Option<TeamSize>); builder!(additional_fields, Option<AdditionalFields>); } impl Discipline { /// Returns iter for the discipline pub fn iter<'a>(&self, client: &'a crate::Toornament) -> crate::DisciplineIter<'a> { crate::DisciplineIter::new(client, self.id.clone()) } /// Converts discipline into an iter pub fn into_iter(self, client: &crate::Toornament) -> crate::DisciplineIter<'_> { crate::DisciplineIter::new(client, self.id) } } /// A list of `Discipline` objects. #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct Disciplines(pub Vec<Discipline>); #[cfg(test)] mod tests { use super::{Discipline, DisciplineId, Disciplines}; #[test] fn test_discipline_parse() { let string = r#"{ "id": "counterstrike_go", "name": "Counter-Strike: GO", "shortname": "CS:GO", "fullname": "Counter-Strike: Global Offensive", "copyrights": "Valve Software" }"#; let d: Discipline = serde_json::from_str(string).unwrap(); assert_eq!(d.id.0, "counterstrike_go"); assert_eq!(d.name, "Counter-Strike: GO"); assert_eq!(d.short_name, "CS:GO"); assert_eq!(d.full_name, "Counter-Strike: Global Offensive"); assert_eq!(d.copyrights, "Valve Software"); } #[test] fn test_discipline_full_parse()
assert_eq!(d.name, "COD4:MW"); assert_eq!(d.short_name, "COD4"); assert_eq!(d.full_name, "Call of Duty 4 : Modern Warfare"); assert_eq!(d.copyrights, r#"Infinity Ward / Activision"#); assert!(d.team_size.is_some()); let ts = d.team_size.unwrap(); // safe assert_eq!(ts.min, 4i64); assert_eq!(ts.max, 4i64); assert!(d.additional_fields.is_some()); let af = d.additional_fields.unwrap(); // safe assert_eq!(af.0.len(), 1); let first = af.0.into_iter().next().unwrap(); // safe assert_eq!(first.0, "field_name"); assert_eq!(first.1.len(), 1); let first_value = first.1.into_iter().next().unwrap(); // safe assert_eq!(first_value.0, "value"); assert_eq!(first_value.1, "label"); } #[test] fn test_disciplines_parse() { let string = r#"[ { "id": "counterstrike_go", "name": "Counter-Strike: GO", "shortname": "CS:GO", "fullname": "Counter-Strike: Global Offensive", "copyrights": "Valve Software" }, { "id": "quakelive", "name": "Quake Live", "shortname": "QL", "fullname": "Quake Live", "copyrights": "id Software" } ]"#; let ds: Disciplines = serde_json::from_str(string).unwrap(); assert_eq!(ds.0.len(), 2); let correct_disciplines = vec![ Discipline::new( DisciplineId("counterstrike_go".to_owned()), "Counter-Strike: GO", "CS:GO", "Counter-Strike: Global Offensive", "Valve Software", ), Discipline::new( DisciplineId("quakelive".to_owned()), "Quake Live", "QL", "Quake Live", "id Software", ), ]; let iter = ds.0.iter().zip(correct_disciplines.iter()); for pair in iter { assert_eq!(pair.0.id, pair.1.id); assert_eq!(pair.0.name, pair.1.name); assert_eq!(pair.0.short_name, pair.1.short_name); assert_eq!(pair.0.full_name, pair.1.full_name); assert_eq!(pair.0.copyrights, pair.1.copyrights); } } }
{ let string = r#"{ "id": "cod4", "name": "COD4:MW", "shortname": "COD4", "fullname": "Call of Duty 4 : Modern Warfare", "copyrights": "Infinity Ward / Activision", "team_size": { "min": 4, "max": 4 }, "additional_fields": { "field_name": { "value": "label" } } }"#; let d: Discipline = serde_json::from_str(string).unwrap(); assert_eq!(d.id.0, "cod4");
identifier_body
disciplines.rs
use std::collections::HashMap; use crate::common::TeamSize; /// Additional fields for `Discipline` wrap. #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct AdditionalFields(pub HashMap<String, HashMap<String, String>>); /// A game discipline identity. #[derive( Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, )] pub struct DisciplineId(pub String); /// A game discipline object. #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct Discipline { /// An identifier for a discipline, can be used in others APIs. /// Example: "counterstrike_go" pub id: DisciplineId, /// The official name of the discipline. /// Example: "Counter-Strike: GO" pub name: String, /// The short name of the discipline. /// Example: "CS:GO" #[serde(rename = "shortname")] pub short_name: String, /// The complete name of the discipline. /// Example: "Counter-Strike: Global Offensive" #[serde(rename = "fullname")] pub full_name: String, /// The name of the publisher of the discipline or any other right related information about the owner of the discipline. /// Example: "Valve Software" pub copyrights: String, /// (Optional) Sets the minimum and maximum of players in a team. /// Example: (4, 8), where `4` is minimal size of a team in the tournament /// and `8` is maximal size of a team in the tournament. #[serde(skip_serializing_if = "Option::is_none")] pub team_size: Option<TeamSize>, /// (Optional) Additional fields concerning the discipline. /// Note about the special fields in this API: if the field is mentioned, you must use one of the following values. #[serde(skip_serializing_if = "Option::is_none")] pub additional_fields: Option<AdditionalFields>, } impl Discipline { /// Creates new `Discipline` object. pub fn new<S: Into<String>>( id: DisciplineId, name: S, short_name: S, full_name: S, copyrights: S, ) -> Discipline { Discipline { id, name: name.into(), short_name: short_name.into(), full_name: full_name.into(), copyrights: copyrights.into(), team_size: None, additional_fields: None, } } builder!(id, DisciplineId); builder_s!(name); builder_s!(short_name); builder_s!(full_name); builder_s!(copyrights); builder!(team_size, Option<TeamSize>); builder!(additional_fields, Option<AdditionalFields>); } impl Discipline { /// Returns iter for the discipline pub fn iter<'a>(&self, client: &'a crate::Toornament) -> crate::DisciplineIter<'a> { crate::DisciplineIter::new(client, self.id.clone()) } /// Converts discipline into an iter pub fn into_iter(self, client: &crate::Toornament) -> crate::DisciplineIter<'_> { crate::DisciplineIter::new(client, self.id) } } /// A list of `Discipline` objects. #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct Disciplines(pub Vec<Discipline>); #[cfg(test)] mod tests { use super::{Discipline, DisciplineId, Disciplines}; #[test] fn test_discipline_parse() { let string = r#"{ "id": "counterstrike_go", "name": "Counter-Strike: GO", "shortname": "CS:GO", "fullname": "Counter-Strike: Global Offensive", "copyrights": "Valve Software" }"#; let d: Discipline = serde_json::from_str(string).unwrap(); assert_eq!(d.id.0, "counterstrike_go"); assert_eq!(d.name, "Counter-Strike: GO"); assert_eq!(d.short_name, "CS:GO"); assert_eq!(d.full_name, "Counter-Strike: Global Offensive"); assert_eq!(d.copyrights, "Valve Software"); } #[test] fn test_discipline_full_parse() { let string = r#"{ "id": "cod4", "name": "COD4:MW", "shortname": "COD4", "fullname": "Call of Duty 4 : Modern Warfare", "copyrights": "Infinity Ward / Activision", "team_size": { "min": 4,
"additional_fields": { "field_name": { "value": "label" } } }"#; let d: Discipline = serde_json::from_str(string).unwrap(); assert_eq!(d.id.0, "cod4"); assert_eq!(d.name, "COD4:MW"); assert_eq!(d.short_name, "COD4"); assert_eq!(d.full_name, "Call of Duty 4 : Modern Warfare"); assert_eq!(d.copyrights, r#"Infinity Ward / Activision"#); assert!(d.team_size.is_some()); let ts = d.team_size.unwrap(); // safe assert_eq!(ts.min, 4i64); assert_eq!(ts.max, 4i64); assert!(d.additional_fields.is_some()); let af = d.additional_fields.unwrap(); // safe assert_eq!(af.0.len(), 1); let first = af.0.into_iter().next().unwrap(); // safe assert_eq!(first.0, "field_name"); assert_eq!(first.1.len(), 1); let first_value = first.1.into_iter().next().unwrap(); // safe assert_eq!(first_value.0, "value"); assert_eq!(first_value.1, "label"); } #[test] fn test_disciplines_parse() { let string = r#"[ { "id": "counterstrike_go", "name": "Counter-Strike: GO", "shortname": "CS:GO", "fullname": "Counter-Strike: Global Offensive", "copyrights": "Valve Software" }, { "id": "quakelive", "name": "Quake Live", "shortname": "QL", "fullname": "Quake Live", "copyrights": "id Software" } ]"#; let ds: Disciplines = serde_json::from_str(string).unwrap(); assert_eq!(ds.0.len(), 2); let correct_disciplines = vec![ Discipline::new( DisciplineId("counterstrike_go".to_owned()), "Counter-Strike: GO", "CS:GO", "Counter-Strike: Global Offensive", "Valve Software", ), Discipline::new( DisciplineId("quakelive".to_owned()), "Quake Live", "QL", "Quake Live", "id Software", ), ]; let iter = ds.0.iter().zip(correct_disciplines.iter()); for pair in iter { assert_eq!(pair.0.id, pair.1.id); assert_eq!(pair.0.name, pair.1.name); assert_eq!(pair.0.short_name, pair.1.short_name); assert_eq!(pair.0.full_name, pair.1.full_name); assert_eq!(pair.0.copyrights, pair.1.copyrights); } } }
"max": 4 },
random_line_split
combox.rs
use super::*; use crate::attributes::{ComClass, ComInterface, HasInterface}; use crate::raw::RawComPtr; use crate::type_system::TypeSystemName; use std::sync::atomic::{AtomicU32, Ordering}; /// Pointer to a COM-enabled Rust struct. /// /// Intercom requires a specific memory layout for the COM objects so that it /// can implement reference counting and map COM method calls back to the /// target struct instance. /// /// This is done by requiring each COM-enabled Rust object is constructed /// through a `ComBox<T>` type. /// /// Technically the memory layout is specified by the [`ComBoxData`](struct.ComBoxData.html) /// type, however that type shouldn't be needed by the user. For all intents /// the `ComBox` type is _the_ COM-compatible object handle. pub struct ComBox<T: ComClass> { data: *mut ComBoxData<T>, } impl<T: ComClass> ComBox<T> { /// Constructs a new `ComBox` by placing the `value` into reference /// counted memory. /// /// - `value` - The initial state to use for the COM object. pub fn new(value: T) -> ComBox<T> { // Construct a ComBoxData in memory and track the reference on it. let cb = ComBoxData::new(value); unsafe { ComBoxData::add_ref(&*cb) }; // Return the struct. ComBox { data: cb } } /// Acquires a ComItf for this struct. /// /// # Safety /// /// The ComItf must not outlive the current instance without invoking /// `add_ref`. unsafe fn as_comitf<I: ComInterface +?Sized>(&self) -> ComItf<I> where T: HasInterface<I>, { let (automation_ptr, raw_ptr) = { let vtbl = &self.as_ref().vtable_list; let automation_ptr = match I::iid(TypeSystemName::Automation) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; let raw_ptr = match I::iid(TypeSystemName::Raw) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; (automation_ptr, raw_ptr) }; ComItf::maybe_new( raw::InterfacePtr::new(automation_ptr), raw::InterfacePtr::new(raw_ptr), ) .expect("Intercom failed to create interface pointers") } } impl<T: ComClass + std::fmt::Debug> std::fmt::Debug for ComBox<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ComBox(")?; self.as_ref().fmt(f)?; write!(f, ")") } } impl<T: ComClass> Drop for ComBox<T> { /// Decreases the reference count by one. If this is the last reference /// the memory will be deallocated. fn drop(&mut self) { unsafe { ComBoxData::release(self.data) }; } } impl<T: ComClass> AsMut<ComBoxData<T>> for ComBox<T> { fn as_mut(&mut self) -> &mut ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_mut().expect("ComBox had null reference") } } } impl<T: ComClass> AsRef<ComBoxData<T>> for ComBox<T> { fn as_ref(&self) -> &ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_ref().expect("ComBox had null reference") } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<ComBox<T>> for ComRc<I> { fn from(source: ComBox<T>) -> ComRc<I> { // as_comitf does not change the reference count so attach is safe // as long as we forget the source so it won't release it either. unsafe { let rc = ComRc::attach(source.as_comitf()); std::mem::forget(source); rc } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<&ComBox<T>> for ComRc<I> { fn from(combox: &ComBox<T>) -> Self { // The ComItf temporary doesn't outlive self, making this safe. unsafe { ComRc::from(&combox.as_comitf()) } } } /// Type factory for the concrete COM coclass types. /// /// Includes the virtual tables required for COM method invocations, reference /// count required for `IUnknown` implementation and the custom value struct /// required for any user defined interfaces. /// /// While this struct is available for manual handling of raw COM interface /// pointers, it's worth realizing that it's use is inherently unsafe. Most of /// the methods implemented for the type come with conditions that Rust isn't /// able to enforce. /// /// The methods that handle `RawComPtr` types must only be invoked with correct /// pointer values. There's no type checking for the pointers and the `ComBoxData` /// will make serious assumptions on the pointers passed in. /// /// Furthermore the `new_ptr` constructor and the `IUnknown` methods `add_ref` /// and `release` must be used correctly together. Failure to do so will result /// either in memory leaks or access to dangling pointers. #[repr(C)] pub struct ComBoxData<T: ComClass> { vtable_list: T::VTableList, ref_count: AtomicU32, value: T, } impl<T: ComClass> ComBoxData<T> { /// Creates a new ComBoxData and returns a pointer to it. /// /// The box is initialized with a reference count of zero. In most cases /// the ComBoxData creation is followed by query_interface, which increments the /// ref_count. /// /// The value should be cleaned by calling'release'. pub fn new(value: T) -> *mut ComBoxData<T> { // TODO: Fix this to use raw heap allocation at some point. There's // no need to construct and immediately detach a Box. Box::into_raw(Box::new(ComBoxData { vtable_list: T::VTABLE, ref_count: AtomicU32::new(0), value, })) } /// Acquires a specific interface pointer. /// /// Increments the reference count to include the reference through the /// returned interface pointer. /// /// The acquired interface must be released explicitly when not needed /// anymore. /// /// # Safety /// /// The `out` pointer must be valid for writing the interface pointer to. pub unsafe fn query_interface(this: &Self, riid: REFIID, out: *mut RawComPtr) -> raw::HRESULT { match T::query_interface(&this.vtable_list, riid) { Ok(ptr) => { *out = ptr; Self::add_ref(this); raw::S_OK } Err(e) => { *out = std::ptr::null_mut(); e } } } /// Increments the reference count. /// /// Returns the reference count after the increment. /// /// # Safety /// /// The method isn't technically unsafe in regard to Rust unsafety, but /// it's marked as unsafe to discourage it's use due to high risks of /// memory leaks. pub unsafe fn add_ref(this: &Self) -> u32 { let previous_value = this.ref_count.fetch_add(1, Ordering::Relaxed); (previous_value + 1) } /// Gets the reference count of the object. pub fn get_ref_count(&self) -> u32 { self.ref_count.load(Ordering::Relaxed) } /// Decrements the reference count. Destroys the object if the count reaches /// zero. /// /// Returns the reference count after the release. /// /// # Safety /// /// The pointer must be valid and not previously released. After the call /// completes, the struct may have been deallocated and the pointer should /// be considered dangling. pub unsafe fn release(this: *mut Self) -> u32 { // Ensure we're not releasing an interface that has no references. // // Note: If the interface has no references, it has already been // dropped. As a result we can't guarantee that it's ref_count stays // as zero as the memory could have been reallocated for something else. // // However this is still an effective check in the case where the client // attempts to release a com pointer twice and the memory hasn't been // reused. // // It might not be deterministic, but in the cases where it triggers // it's way better than the access violation error we'd otherwise get. if (*this).ref_count.load(Ordering::Relaxed) == 0 { panic!("Attempt to release pointer with no references."); } // Decrease the ref count and store a copy of it. We'll need a local // copy for a return value in case we end up dropping the ComBoxData // instance. after the drop referencing *this would be undeterministic. let previous_value = (*this).ref_count.fetch_sub(1, Ordering::Relaxed); let rc = previous_value - 1; // If that was the last reference we can drop self. Do this by giving // it back to a box and then dropping the box. This should reverse the // allocation we did by boxing the value in the first place. if rc == 0 { drop(Box::from_raw(this)); } rc } /// Converts a RawComPtr to a ComBoxData reference. /// /// # Safety /// /// The method is unsafe in two different ways: /// /// - There is no way for the method to ensure the RawComPtr points to /// a valid ComBoxData<T> instance. It's the caller's responsibility to /// ensure the method is not called with invalid pointers. /// /// - As the pointers have no lifetime tied to them, the borrow checker /// is unable to enforce the lifetime of the ComBoxData reference. If the /// ComBoxData is free'd by calling release on the pointer, the ComBoxData /// reference will still reference the old, now free'd value. The caller /// must ensure that the returned reference won't be used in case the /// ComBoxData is released. pub unsafe fn from_ptr<'a>(ptr: RawComPtr) -> &'a mut ComBoxData<T> { &mut *(ptr as *mut ComBoxData<T>) } /// Returns a reference to the virtual table on the ComBoxData. pub fn vtable(ct: &ComBox<T>) -> &T::VTableList { unsafe { &(*ct.data).vtable_list } } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of(value: &T) -> &ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *const T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of_mut(value: &mut T) -> &mut ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *mut T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Returns a reference to a null-ComBoxData vtable pointer list. /// /// # Safety /// /// **The reference itself is invalid and must not be dereferenced.** /// /// The reference may be used to further get references to the various /// VTableList fields to resolve offset values between the various VTable /// pointers and the actual `ComBoxData` containing these pointers. #[inline] pub unsafe fn null_vtable() -> &'static T::VTableList { let null_combox = std::ptr::null() as *const ComBoxData<T>; &(*null_combox).vtable_list } } impl<T> std::ops::Deref for ComBoxData<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { &self.value } } impl<T> std::ops::DerefMut for ComBoxData<T> where T: ComClass, { fn
(&mut self) -> &mut T { &mut self.value } } impl<T> std::ops::Deref for ComBox<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { unsafe { &(*self.data).value } } } impl<T> std::ops::DerefMut for ComBox<T> where T: ComClass, { fn deref_mut(&mut self) -> &mut T { unsafe { &mut (*self.data).value } } } impl<T: Default + ComClass> Default for ComBox<T> { fn default() -> Self { ComBox::new(T::default()) } }
deref_mut
identifier_name
combox.rs
use super::*; use crate::attributes::{ComClass, ComInterface, HasInterface}; use crate::raw::RawComPtr; use crate::type_system::TypeSystemName; use std::sync::atomic::{AtomicU32, Ordering}; /// Pointer to a COM-enabled Rust struct. /// /// Intercom requires a specific memory layout for the COM objects so that it /// can implement reference counting and map COM method calls back to the /// target struct instance. /// /// This is done by requiring each COM-enabled Rust object is constructed /// through a `ComBox<T>` type. /// /// Technically the memory layout is specified by the [`ComBoxData`](struct.ComBoxData.html) /// type, however that type shouldn't be needed by the user. For all intents /// the `ComBox` type is _the_ COM-compatible object handle. pub struct ComBox<T: ComClass> { data: *mut ComBoxData<T>, } impl<T: ComClass> ComBox<T> { /// Constructs a new `ComBox` by placing the `value` into reference /// counted memory. /// /// - `value` - The initial state to use for the COM object. pub fn new(value: T) -> ComBox<T> { // Construct a ComBoxData in memory and track the reference on it. let cb = ComBoxData::new(value); unsafe { ComBoxData::add_ref(&*cb) }; // Return the struct. ComBox { data: cb } } /// Acquires a ComItf for this struct. /// /// # Safety /// /// The ComItf must not outlive the current instance without invoking /// `add_ref`. unsafe fn as_comitf<I: ComInterface +?Sized>(&self) -> ComItf<I> where T: HasInterface<I>, { let (automation_ptr, raw_ptr) = { let vtbl = &self.as_ref().vtable_list; let automation_ptr = match I::iid(TypeSystemName::Automation) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; let raw_ptr = match I::iid(TypeSystemName::Raw) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; (automation_ptr, raw_ptr) }; ComItf::maybe_new( raw::InterfacePtr::new(automation_ptr), raw::InterfacePtr::new(raw_ptr), ) .expect("Intercom failed to create interface pointers") } } impl<T: ComClass + std::fmt::Debug> std::fmt::Debug for ComBox<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ComBox(")?; self.as_ref().fmt(f)?; write!(f, ")") } } impl<T: ComClass> Drop for ComBox<T> { /// Decreases the reference count by one. If this is the last reference /// the memory will be deallocated. fn drop(&mut self) { unsafe { ComBoxData::release(self.data) }; } } impl<T: ComClass> AsMut<ComBoxData<T>> for ComBox<T> { fn as_mut(&mut self) -> &mut ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_mut().expect("ComBox had null reference") } } } impl<T: ComClass> AsRef<ComBoxData<T>> for ComBox<T> { fn as_ref(&self) -> &ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_ref().expect("ComBox had null reference") } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<ComBox<T>> for ComRc<I> { fn from(source: ComBox<T>) -> ComRc<I> { // as_comitf does not change the reference count so attach is safe // as long as we forget the source so it won't release it either. unsafe { let rc = ComRc::attach(source.as_comitf()); std::mem::forget(source); rc } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<&ComBox<T>> for ComRc<I> { fn from(combox: &ComBox<T>) -> Self { // The ComItf temporary doesn't outlive self, making this safe. unsafe { ComRc::from(&combox.as_comitf()) } } } /// Type factory for the concrete COM coclass types. /// /// Includes the virtual tables required for COM method invocations, reference /// count required for `IUnknown` implementation and the custom value struct /// required for any user defined interfaces. /// /// While this struct is available for manual handling of raw COM interface /// pointers, it's worth realizing that it's use is inherently unsafe. Most of /// the methods implemented for the type come with conditions that Rust isn't /// able to enforce. /// /// The methods that handle `RawComPtr` types must only be invoked with correct /// pointer values. There's no type checking for the pointers and the `ComBoxData` /// will make serious assumptions on the pointers passed in. /// /// Furthermore the `new_ptr` constructor and the `IUnknown` methods `add_ref` /// and `release` must be used correctly together. Failure to do so will result /// either in memory leaks or access to dangling pointers. #[repr(C)] pub struct ComBoxData<T: ComClass> { vtable_list: T::VTableList, ref_count: AtomicU32, value: T, } impl<T: ComClass> ComBoxData<T> { /// Creates a new ComBoxData and returns a pointer to it. /// /// The box is initialized with a reference count of zero. In most cases /// the ComBoxData creation is followed by query_interface, which increments the /// ref_count. /// /// The value should be cleaned by calling'release'. pub fn new(value: T) -> *mut ComBoxData<T> { // TODO: Fix this to use raw heap allocation at some point. There's // no need to construct and immediately detach a Box. Box::into_raw(Box::new(ComBoxData { vtable_list: T::VTABLE, ref_count: AtomicU32::new(0), value, })) } /// Acquires a specific interface pointer. /// /// Increments the reference count to include the reference through the /// returned interface pointer. /// /// The acquired interface must be released explicitly when not needed /// anymore. /// /// # Safety /// /// The `out` pointer must be valid for writing the interface pointer to. pub unsafe fn query_interface(this: &Self, riid: REFIID, out: *mut RawComPtr) -> raw::HRESULT { match T::query_interface(&this.vtable_list, riid) { Ok(ptr) => { *out = ptr; Self::add_ref(this); raw::S_OK } Err(e) =>
} } /// Increments the reference count. /// /// Returns the reference count after the increment. /// /// # Safety /// /// The method isn't technically unsafe in regard to Rust unsafety, but /// it's marked as unsafe to discourage it's use due to high risks of /// memory leaks. pub unsafe fn add_ref(this: &Self) -> u32 { let previous_value = this.ref_count.fetch_add(1, Ordering::Relaxed); (previous_value + 1) } /// Gets the reference count of the object. pub fn get_ref_count(&self) -> u32 { self.ref_count.load(Ordering::Relaxed) } /// Decrements the reference count. Destroys the object if the count reaches /// zero. /// /// Returns the reference count after the release. /// /// # Safety /// /// The pointer must be valid and not previously released. After the call /// completes, the struct may have been deallocated and the pointer should /// be considered dangling. pub unsafe fn release(this: *mut Self) -> u32 { // Ensure we're not releasing an interface that has no references. // // Note: If the interface has no references, it has already been // dropped. As a result we can't guarantee that it's ref_count stays // as zero as the memory could have been reallocated for something else. // // However this is still an effective check in the case where the client // attempts to release a com pointer twice and the memory hasn't been // reused. // // It might not be deterministic, but in the cases where it triggers // it's way better than the access violation error we'd otherwise get. if (*this).ref_count.load(Ordering::Relaxed) == 0 { panic!("Attempt to release pointer with no references."); } // Decrease the ref count and store a copy of it. We'll need a local // copy for a return value in case we end up dropping the ComBoxData // instance. after the drop referencing *this would be undeterministic. let previous_value = (*this).ref_count.fetch_sub(1, Ordering::Relaxed); let rc = previous_value - 1; // If that was the last reference we can drop self. Do this by giving // it back to a box and then dropping the box. This should reverse the // allocation we did by boxing the value in the first place. if rc == 0 { drop(Box::from_raw(this)); } rc } /// Converts a RawComPtr to a ComBoxData reference. /// /// # Safety /// /// The method is unsafe in two different ways: /// /// - There is no way for the method to ensure the RawComPtr points to /// a valid ComBoxData<T> instance. It's the caller's responsibility to /// ensure the method is not called with invalid pointers. /// /// - As the pointers have no lifetime tied to them, the borrow checker /// is unable to enforce the lifetime of the ComBoxData reference. If the /// ComBoxData is free'd by calling release on the pointer, the ComBoxData /// reference will still reference the old, now free'd value. The caller /// must ensure that the returned reference won't be used in case the /// ComBoxData is released. pub unsafe fn from_ptr<'a>(ptr: RawComPtr) -> &'a mut ComBoxData<T> { &mut *(ptr as *mut ComBoxData<T>) } /// Returns a reference to the virtual table on the ComBoxData. pub fn vtable(ct: &ComBox<T>) -> &T::VTableList { unsafe { &(*ct.data).vtable_list } } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of(value: &T) -> &ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *const T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of_mut(value: &mut T) -> &mut ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *mut T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Returns a reference to a null-ComBoxData vtable pointer list. /// /// # Safety /// /// **The reference itself is invalid and must not be dereferenced.** /// /// The reference may be used to further get references to the various /// VTableList fields to resolve offset values between the various VTable /// pointers and the actual `ComBoxData` containing these pointers. #[inline] pub unsafe fn null_vtable() -> &'static T::VTableList { let null_combox = std::ptr::null() as *const ComBoxData<T>; &(*null_combox).vtable_list } } impl<T> std::ops::Deref for ComBoxData<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { &self.value } } impl<T> std::ops::DerefMut for ComBoxData<T> where T: ComClass, { fn deref_mut(&mut self) -> &mut T { &mut self.value } } impl<T> std::ops::Deref for ComBox<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { unsafe { &(*self.data).value } } } impl<T> std::ops::DerefMut for ComBox<T> where T: ComClass, { fn deref_mut(&mut self) -> &mut T { unsafe { &mut (*self.data).value } } } impl<T: Default + ComClass> Default for ComBox<T> { fn default() -> Self { ComBox::new(T::default()) } }
{ *out = std::ptr::null_mut(); e }
conditional_block
combox.rs
use super::*; use crate::attributes::{ComClass, ComInterface, HasInterface}; use crate::raw::RawComPtr; use crate::type_system::TypeSystemName; use std::sync::atomic::{AtomicU32, Ordering}; /// Pointer to a COM-enabled Rust struct. /// /// Intercom requires a specific memory layout for the COM objects so that it /// can implement reference counting and map COM method calls back to the /// target struct instance. /// /// This is done by requiring each COM-enabled Rust object is constructed /// through a `ComBox<T>` type. /// /// Technically the memory layout is specified by the [`ComBoxData`](struct.ComBoxData.html) /// type, however that type shouldn't be needed by the user. For all intents /// the `ComBox` type is _the_ COM-compatible object handle. pub struct ComBox<T: ComClass> { data: *mut ComBoxData<T>, } impl<T: ComClass> ComBox<T> { /// Constructs a new `ComBox` by placing the `value` into reference /// counted memory. /// /// - `value` - The initial state to use for the COM object. pub fn new(value: T) -> ComBox<T> { // Construct a ComBoxData in memory and track the reference on it. let cb = ComBoxData::new(value); unsafe { ComBoxData::add_ref(&*cb) }; // Return the struct. ComBox { data: cb } } /// Acquires a ComItf for this struct. /// /// # Safety /// /// The ComItf must not outlive the current instance without invoking /// `add_ref`. unsafe fn as_comitf<I: ComInterface +?Sized>(&self) -> ComItf<I> where T: HasInterface<I>, { let (automation_ptr, raw_ptr) = { let vtbl = &self.as_ref().vtable_list; let automation_ptr = match I::iid(TypeSystemName::Automation) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; let raw_ptr = match I::iid(TypeSystemName::Raw) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; (automation_ptr, raw_ptr) }; ComItf::maybe_new( raw::InterfacePtr::new(automation_ptr), raw::InterfacePtr::new(raw_ptr), ) .expect("Intercom failed to create interface pointers") } } impl<T: ComClass + std::fmt::Debug> std::fmt::Debug for ComBox<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ComBox(")?; self.as_ref().fmt(f)?; write!(f, ")") } } impl<T: ComClass> Drop for ComBox<T> { /// Decreases the reference count by one. If this is the last reference /// the memory will be deallocated. fn drop(&mut self) { unsafe { ComBoxData::release(self.data) }; } } impl<T: ComClass> AsMut<ComBoxData<T>> for ComBox<T> { fn as_mut(&mut self) -> &mut ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_mut().expect("ComBox had null reference") } } } impl<T: ComClass> AsRef<ComBoxData<T>> for ComBox<T> { fn as_ref(&self) -> &ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_ref().expect("ComBox had null reference") } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<ComBox<T>> for ComRc<I> { fn from(source: ComBox<T>) -> ComRc<I> { // as_comitf does not change the reference count so attach is safe // as long as we forget the source so it won't release it either. unsafe { let rc = ComRc::attach(source.as_comitf()); std::mem::forget(source); rc } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<&ComBox<T>> for ComRc<I> { fn from(combox: &ComBox<T>) -> Self
} /// Type factory for the concrete COM coclass types. /// /// Includes the virtual tables required for COM method invocations, reference /// count required for `IUnknown` implementation and the custom value struct /// required for any user defined interfaces. /// /// While this struct is available for manual handling of raw COM interface /// pointers, it's worth realizing that it's use is inherently unsafe. Most of /// the methods implemented for the type come with conditions that Rust isn't /// able to enforce. /// /// The methods that handle `RawComPtr` types must only be invoked with correct /// pointer values. There's no type checking for the pointers and the `ComBoxData` /// will make serious assumptions on the pointers passed in. /// /// Furthermore the `new_ptr` constructor and the `IUnknown` methods `add_ref` /// and `release` must be used correctly together. Failure to do so will result /// either in memory leaks or access to dangling pointers. #[repr(C)] pub struct ComBoxData<T: ComClass> { vtable_list: T::VTableList, ref_count: AtomicU32, value: T, } impl<T: ComClass> ComBoxData<T> { /// Creates a new ComBoxData and returns a pointer to it. /// /// The box is initialized with a reference count of zero. In most cases /// the ComBoxData creation is followed by query_interface, which increments the /// ref_count. /// /// The value should be cleaned by calling'release'. pub fn new(value: T) -> *mut ComBoxData<T> { // TODO: Fix this to use raw heap allocation at some point. There's // no need to construct and immediately detach a Box. Box::into_raw(Box::new(ComBoxData { vtable_list: T::VTABLE, ref_count: AtomicU32::new(0), value, })) } /// Acquires a specific interface pointer. /// /// Increments the reference count to include the reference through the /// returned interface pointer. /// /// The acquired interface must be released explicitly when not needed /// anymore. /// /// # Safety /// /// The `out` pointer must be valid for writing the interface pointer to. pub unsafe fn query_interface(this: &Self, riid: REFIID, out: *mut RawComPtr) -> raw::HRESULT { match T::query_interface(&this.vtable_list, riid) { Ok(ptr) => { *out = ptr; Self::add_ref(this); raw::S_OK } Err(e) => { *out = std::ptr::null_mut(); e } } } /// Increments the reference count. /// /// Returns the reference count after the increment. /// /// # Safety /// /// The method isn't technically unsafe in regard to Rust unsafety, but /// it's marked as unsafe to discourage it's use due to high risks of /// memory leaks. pub unsafe fn add_ref(this: &Self) -> u32 { let previous_value = this.ref_count.fetch_add(1, Ordering::Relaxed); (previous_value + 1) } /// Gets the reference count of the object. pub fn get_ref_count(&self) -> u32 { self.ref_count.load(Ordering::Relaxed) } /// Decrements the reference count. Destroys the object if the count reaches /// zero. /// /// Returns the reference count after the release. /// /// # Safety /// /// The pointer must be valid and not previously released. After the call /// completes, the struct may have been deallocated and the pointer should /// be considered dangling. pub unsafe fn release(this: *mut Self) -> u32 { // Ensure we're not releasing an interface that has no references. // // Note: If the interface has no references, it has already been // dropped. As a result we can't guarantee that it's ref_count stays // as zero as the memory could have been reallocated for something else. // // However this is still an effective check in the case where the client // attempts to release a com pointer twice and the memory hasn't been // reused. // // It might not be deterministic, but in the cases where it triggers // it's way better than the access violation error we'd otherwise get. if (*this).ref_count.load(Ordering::Relaxed) == 0 { panic!("Attempt to release pointer with no references."); } // Decrease the ref count and store a copy of it. We'll need a local // copy for a return value in case we end up dropping the ComBoxData // instance. after the drop referencing *this would be undeterministic. let previous_value = (*this).ref_count.fetch_sub(1, Ordering::Relaxed); let rc = previous_value - 1; // If that was the last reference we can drop self. Do this by giving // it back to a box and then dropping the box. This should reverse the // allocation we did by boxing the value in the first place. if rc == 0 { drop(Box::from_raw(this)); } rc } /// Converts a RawComPtr to a ComBoxData reference. /// /// # Safety /// /// The method is unsafe in two different ways: /// /// - There is no way for the method to ensure the RawComPtr points to /// a valid ComBoxData<T> instance. It's the caller's responsibility to /// ensure the method is not called with invalid pointers. /// /// - As the pointers have no lifetime tied to them, the borrow checker /// is unable to enforce the lifetime of the ComBoxData reference. If the /// ComBoxData is free'd by calling release on the pointer, the ComBoxData /// reference will still reference the old, now free'd value. The caller /// must ensure that the returned reference won't be used in case the /// ComBoxData is released. pub unsafe fn from_ptr<'a>(ptr: RawComPtr) -> &'a mut ComBoxData<T> { &mut *(ptr as *mut ComBoxData<T>) } /// Returns a reference to the virtual table on the ComBoxData. pub fn vtable(ct: &ComBox<T>) -> &T::VTableList { unsafe { &(*ct.data).vtable_list } } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of(value: &T) -> &ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *const T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of_mut(value: &mut T) -> &mut ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *mut T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Returns a reference to a null-ComBoxData vtable pointer list. /// /// # Safety /// /// **The reference itself is invalid and must not be dereferenced.** /// /// The reference may be used to further get references to the various /// VTableList fields to resolve offset values between the various VTable /// pointers and the actual `ComBoxData` containing these pointers. #[inline] pub unsafe fn null_vtable() -> &'static T::VTableList { let null_combox = std::ptr::null() as *const ComBoxData<T>; &(*null_combox).vtable_list } } impl<T> std::ops::Deref for ComBoxData<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { &self.value } } impl<T> std::ops::DerefMut for ComBoxData<T> where T: ComClass, { fn deref_mut(&mut self) -> &mut T { &mut self.value } } impl<T> std::ops::Deref for ComBox<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { unsafe { &(*self.data).value } } } impl<T> std::ops::DerefMut for ComBox<T> where T: ComClass, { fn deref_mut(&mut self) -> &mut T { unsafe { &mut (*self.data).value } } } impl<T: Default + ComClass> Default for ComBox<T> { fn default() -> Self { ComBox::new(T::default()) } }
{ // The ComItf temporary doesn't outlive self, making this safe. unsafe { ComRc::from(&combox.as_comitf()) } }
identifier_body
combox.rs
use super::*; use crate::attributes::{ComClass, ComInterface, HasInterface}; use crate::raw::RawComPtr; use crate::type_system::TypeSystemName; use std::sync::atomic::{AtomicU32, Ordering}; /// Pointer to a COM-enabled Rust struct. /// /// Intercom requires a specific memory layout for the COM objects so that it /// can implement reference counting and map COM method calls back to the /// target struct instance. /// /// This is done by requiring each COM-enabled Rust object is constructed /// through a `ComBox<T>` type. /// /// Technically the memory layout is specified by the [`ComBoxData`](struct.ComBoxData.html) /// type, however that type shouldn't be needed by the user. For all intents /// the `ComBox` type is _the_ COM-compatible object handle. pub struct ComBox<T: ComClass> { data: *mut ComBoxData<T>, } impl<T: ComClass> ComBox<T> { /// Constructs a new `ComBox` by placing the `value` into reference /// counted memory. /// /// - `value` - The initial state to use for the COM object. pub fn new(value: T) -> ComBox<T> { // Construct a ComBoxData in memory and track the reference on it. let cb = ComBoxData::new(value); unsafe { ComBoxData::add_ref(&*cb) }; // Return the struct. ComBox { data: cb } } /// Acquires a ComItf for this struct. /// /// # Safety /// /// The ComItf must not outlive the current instance without invoking /// `add_ref`. unsafe fn as_comitf<I: ComInterface +?Sized>(&self) -> ComItf<I> where T: HasInterface<I>, { let (automation_ptr, raw_ptr) = { let vtbl = &self.as_ref().vtable_list; let automation_ptr = match I::iid(TypeSystemName::Automation) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; let raw_ptr = match I::iid(TypeSystemName::Raw) { Some(iid) => match <T as ComClass>::query_interface(&vtbl, iid) { Ok(itf) => itf, Err(_) => ::std::ptr::null_mut(), }, None => ::std::ptr::null_mut(), }; (automation_ptr, raw_ptr) }; ComItf::maybe_new( raw::InterfacePtr::new(automation_ptr), raw::InterfacePtr::new(raw_ptr), ) .expect("Intercom failed to create interface pointers") } } impl<T: ComClass + std::fmt::Debug> std::fmt::Debug for ComBox<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ComBox(")?; self.as_ref().fmt(f)?; write!(f, ")") } } impl<T: ComClass> Drop for ComBox<T> { /// Decreases the reference count by one. If this is the last reference /// the memory will be deallocated. fn drop(&mut self) { unsafe { ComBoxData::release(self.data) }; } } impl<T: ComClass> AsMut<ComBoxData<T>> for ComBox<T> { fn as_mut(&mut self) -> &mut ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_mut().expect("ComBox had null reference") }
{ fn as_ref(&self) -> &ComBoxData<T> { // 'data' should always be valid pointer. unsafe { self.data.as_ref().expect("ComBox had null reference") } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<ComBox<T>> for ComRc<I> { fn from(source: ComBox<T>) -> ComRc<I> { // as_comitf does not change the reference count so attach is safe // as long as we forget the source so it won't release it either. unsafe { let rc = ComRc::attach(source.as_comitf()); std::mem::forget(source); rc } } } impl<I: ComInterface +?Sized, T: HasInterface<I>> From<&ComBox<T>> for ComRc<I> { fn from(combox: &ComBox<T>) -> Self { // The ComItf temporary doesn't outlive self, making this safe. unsafe { ComRc::from(&combox.as_comitf()) } } } /// Type factory for the concrete COM coclass types. /// /// Includes the virtual tables required for COM method invocations, reference /// count required for `IUnknown` implementation and the custom value struct /// required for any user defined interfaces. /// /// While this struct is available for manual handling of raw COM interface /// pointers, it's worth realizing that it's use is inherently unsafe. Most of /// the methods implemented for the type come with conditions that Rust isn't /// able to enforce. /// /// The methods that handle `RawComPtr` types must only be invoked with correct /// pointer values. There's no type checking for the pointers and the `ComBoxData` /// will make serious assumptions on the pointers passed in. /// /// Furthermore the `new_ptr` constructor and the `IUnknown` methods `add_ref` /// and `release` must be used correctly together. Failure to do so will result /// either in memory leaks or access to dangling pointers. #[repr(C)] pub struct ComBoxData<T: ComClass> { vtable_list: T::VTableList, ref_count: AtomicU32, value: T, } impl<T: ComClass> ComBoxData<T> { /// Creates a new ComBoxData and returns a pointer to it. /// /// The box is initialized with a reference count of zero. In most cases /// the ComBoxData creation is followed by query_interface, which increments the /// ref_count. /// /// The value should be cleaned by calling'release'. pub fn new(value: T) -> *mut ComBoxData<T> { // TODO: Fix this to use raw heap allocation at some point. There's // no need to construct and immediately detach a Box. Box::into_raw(Box::new(ComBoxData { vtable_list: T::VTABLE, ref_count: AtomicU32::new(0), value, })) } /// Acquires a specific interface pointer. /// /// Increments the reference count to include the reference through the /// returned interface pointer. /// /// The acquired interface must be released explicitly when not needed /// anymore. /// /// # Safety /// /// The `out` pointer must be valid for writing the interface pointer to. pub unsafe fn query_interface(this: &Self, riid: REFIID, out: *mut RawComPtr) -> raw::HRESULT { match T::query_interface(&this.vtable_list, riid) { Ok(ptr) => { *out = ptr; Self::add_ref(this); raw::S_OK } Err(e) => { *out = std::ptr::null_mut(); e } } } /// Increments the reference count. /// /// Returns the reference count after the increment. /// /// # Safety /// /// The method isn't technically unsafe in regard to Rust unsafety, but /// it's marked as unsafe to discourage it's use due to high risks of /// memory leaks. pub unsafe fn add_ref(this: &Self) -> u32 { let previous_value = this.ref_count.fetch_add(1, Ordering::Relaxed); (previous_value + 1) } /// Gets the reference count of the object. pub fn get_ref_count(&self) -> u32 { self.ref_count.load(Ordering::Relaxed) } /// Decrements the reference count. Destroys the object if the count reaches /// zero. /// /// Returns the reference count after the release. /// /// # Safety /// /// The pointer must be valid and not previously released. After the call /// completes, the struct may have been deallocated and the pointer should /// be considered dangling. pub unsafe fn release(this: *mut Self) -> u32 { // Ensure we're not releasing an interface that has no references. // // Note: If the interface has no references, it has already been // dropped. As a result we can't guarantee that it's ref_count stays // as zero as the memory could have been reallocated for something else. // // However this is still an effective check in the case where the client // attempts to release a com pointer twice and the memory hasn't been // reused. // // It might not be deterministic, but in the cases where it triggers // it's way better than the access violation error we'd otherwise get. if (*this).ref_count.load(Ordering::Relaxed) == 0 { panic!("Attempt to release pointer with no references."); } // Decrease the ref count and store a copy of it. We'll need a local // copy for a return value in case we end up dropping the ComBoxData // instance. after the drop referencing *this would be undeterministic. let previous_value = (*this).ref_count.fetch_sub(1, Ordering::Relaxed); let rc = previous_value - 1; // If that was the last reference we can drop self. Do this by giving // it back to a box and then dropping the box. This should reverse the // allocation we did by boxing the value in the first place. if rc == 0 { drop(Box::from_raw(this)); } rc } /// Converts a RawComPtr to a ComBoxData reference. /// /// # Safety /// /// The method is unsafe in two different ways: /// /// - There is no way for the method to ensure the RawComPtr points to /// a valid ComBoxData<T> instance. It's the caller's responsibility to /// ensure the method is not called with invalid pointers. /// /// - As the pointers have no lifetime tied to them, the borrow checker /// is unable to enforce the lifetime of the ComBoxData reference. If the /// ComBoxData is free'd by calling release on the pointer, the ComBoxData /// reference will still reference the old, now free'd value. The caller /// must ensure that the returned reference won't be used in case the /// ComBoxData is released. pub unsafe fn from_ptr<'a>(ptr: RawComPtr) -> &'a mut ComBoxData<T> { &mut *(ptr as *mut ComBoxData<T>) } /// Returns a reference to the virtual table on the ComBoxData. pub fn vtable(ct: &ComBox<T>) -> &T::VTableList { unsafe { &(*ct.data).vtable_list } } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of(value: &T) -> &ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *const T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Gets the ComBoxData holding the value. /// /// # Safety /// /// This is unsafe for two reasons: /// /// - There is no way for the method to check that the value is actually /// contained in a `ComBoxData`. It is up to the caller to ensure this method /// is only called with values that exist within a `ComBoxData`. /// /// - The method returns a mutable reference to the ComBoxData containing the /// value. As demonstrated by the parameter type, the caller already has /// a mutable reference to the value itself. As a result the caller will /// end up with two different mutable references to the value - the direct /// one given as a parameter and an indirect one available through the /// return value. The caller should not attempt to access the value data /// through the returned `ComBoxData` reference. pub unsafe fn of_mut(value: &mut T) -> &mut ComBoxData<T> { // Resolve the offset of the 'value' field. let null_combox = std::ptr::null() as *const ComBoxData<T>; let value_offset = &((*null_combox).value) as *const _ as usize; let combox_loc = value as *mut T as usize - value_offset; &mut *(combox_loc as *mut ComBoxData<T>) } /// Returns a reference to a null-ComBoxData vtable pointer list. /// /// # Safety /// /// **The reference itself is invalid and must not be dereferenced.** /// /// The reference may be used to further get references to the various /// VTableList fields to resolve offset values between the various VTable /// pointers and the actual `ComBoxData` containing these pointers. #[inline] pub unsafe fn null_vtable() -> &'static T::VTableList { let null_combox = std::ptr::null() as *const ComBoxData<T>; &(*null_combox).vtable_list } } impl<T> std::ops::Deref for ComBoxData<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { &self.value } } impl<T> std::ops::DerefMut for ComBoxData<T> where T: ComClass, { fn deref_mut(&mut self) -> &mut T { &mut self.value } } impl<T> std::ops::Deref for ComBox<T> where T: ComClass, { type Target = T; fn deref(&self) -> &T { unsafe { &(*self.data).value } } } impl<T> std::ops::DerefMut for ComBox<T> where T: ComClass, { fn deref_mut(&mut self) -> &mut T { unsafe { &mut (*self.data).value } } } impl<T: Default + ComClass> Default for ComBox<T> { fn default() -> Self { ComBox::new(T::default()) } }
} } impl<T: ComClass> AsRef<ComBoxData<T>> for ComBox<T>
random_line_split
oss.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::Result; use fbinit::FacebookInit; use sql_ext::facebook::MysqlOptions; use crate::{SqlConstruct, SqlShardedConstruct}; macro_rules! fb_unimplemented { () => { unimplemented!("This is implemented only for fbcode_build!") }; } /// Construct a SQL data manager backed by Facebook infrastructure pub trait FbSqlConstruct: SqlConstruct + Sized + Send + Sync +'static { fn with_mysql<'a>(_: FacebookInit, _: String, _: &'a MysqlOptions, _: bool) -> Result<Self> { fb_unimplemented!() } } impl<T: SqlConstruct> FbSqlConstruct for T {} /// Construct a sharded SQL data manager backed by Facebook infrastructure pub trait FbSqlShardedConstruct: SqlShardedConstruct + Sized + Send + Sync +'static { fn with_sharded_mysql( _: FacebookInit, _: String, _: usize, _: &MysqlOptions, _: bool, ) -> Result<Self>
} impl<T: SqlShardedConstruct> FbSqlShardedConstruct for T {}
{ fb_unimplemented!() }
identifier_body
oss.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::Result; use fbinit::FacebookInit; use sql_ext::facebook::MysqlOptions; use crate::{SqlConstruct, SqlShardedConstruct}; macro_rules! fb_unimplemented { () => { unimplemented!("This is implemented only for fbcode_build!") }; } /// Construct a SQL data manager backed by Facebook infrastructure pub trait FbSqlConstruct: SqlConstruct + Sized + Send + Sync +'static { fn with_mysql<'a>(_: FacebookInit, _: String, _: &'a MysqlOptions, _: bool) -> Result<Self> { fb_unimplemented!() } } impl<T: SqlConstruct> FbSqlConstruct for T {} /// Construct a sharded SQL data manager backed by Facebook infrastructure pub trait FbSqlShardedConstruct: SqlShardedConstruct + Sized + Send + Sync +'static { fn with_sharded_mysql( _: FacebookInit, _: String, _: usize,
} } impl<T: SqlShardedConstruct> FbSqlShardedConstruct for T {}
_: &MysqlOptions, _: bool, ) -> Result<Self> { fb_unimplemented!()
random_line_split
oss.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::Result; use fbinit::FacebookInit; use sql_ext::facebook::MysqlOptions; use crate::{SqlConstruct, SqlShardedConstruct}; macro_rules! fb_unimplemented { () => { unimplemented!("This is implemented only for fbcode_build!") }; } /// Construct a SQL data manager backed by Facebook infrastructure pub trait FbSqlConstruct: SqlConstruct + Sized + Send + Sync +'static { fn
<'a>(_: FacebookInit, _: String, _: &'a MysqlOptions, _: bool) -> Result<Self> { fb_unimplemented!() } } impl<T: SqlConstruct> FbSqlConstruct for T {} /// Construct a sharded SQL data manager backed by Facebook infrastructure pub trait FbSqlShardedConstruct: SqlShardedConstruct + Sized + Send + Sync +'static { fn with_sharded_mysql( _: FacebookInit, _: String, _: usize, _: &MysqlOptions, _: bool, ) -> Result<Self> { fb_unimplemented!() } } impl<T: SqlShardedConstruct> FbSqlShardedConstruct for T {}
with_mysql
identifier_name
mfenced.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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::any::Any; use std::cell::RefCell; use super::super::{Element, ElementType, GeneralLayout, InheritedProps, StyleProps, Family, InstanceId, Presentation, PresentationPrivate, SpecifiedPresentationProps, PropertyCalculator, Property, EmptyComputeCtx, Mrow, Mo, Token}; use ::platform::Context; use ::layout::{Layout}; #[allow(const_err)] const PROP_OPEN: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from("("), reader: |i| i.mfenced_open() }; #[allow(const_err)] const PROP_CLOSE: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from(")"), reader: |i| i.mfenced_close(), }; #[allow(const_err)] const PROP_SEPARATORS: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from(","), reader: |i| i.mfenced_separators(), }; pub struct Mfenced { open: Option<String>, close: Option<String>, separators: Option<String>, placeholders: RefCell<Mrow>, presentation_props: SpecifiedPresentationProps, instance_id: InstanceId, } impl Mfenced { pub fn new() -> Mfenced { let mut mrow = Mrow::new(); // Opening fence placeholder mrow.with_child(Box::new(Mo::new(String::new()))); // Content placeholder mrow.with_child(Box::new(Mrow::new())); // Closing fence placeholder mrow.with_child(Box::new(Mo::new(String::new()))); Mfenced { open: None, close: None, separators: None, placeholders: RefCell::new(mrow), presentation_props: SpecifiedPresentationProps::default(), instance_id: InstanceId::new(), } } pub fn with_child<'a>(&'a mut self, child: Box<Element>) -> &'a mut Mfenced { // Scope for mutable borrow of self { let content = &mut self.placeholders.get_mut().children_mut()[1]; let content: &mut Mrow = content.as_any_mut().downcast_mut::<Mrow>().unwrap(); if content.children().len() > 0 { // Separator placeholder content.with_child(Box::new(Mo::new(String::new()))); } content.with_child(child); } self } pub fn with_open<'a>(&'a mut self, fence: Option<String>) -> &'a Mfenced { self.open = fence; self } pub fn open(&self) -> Option<&String> { self.open.as_ref() } pub fn with_close<'a>(&'a mut self, fence: Option<String>) -> &'a Mfenced { self.close = fence; self } pub fn close(&self) -> Option<&String> { self.close.as_ref() } pub fn with_separators<'a>(&'a mut self, separators: Option<String>) -> &'a Mfenced { self.separators = separators; self } pub fn separators(&self) -> Option<&String> { self.separators.as_ref() } } impl Element for Mfenced { fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps, style: &Option<&StyleProps>) -> Box<Layout> { let mut calculator = PropertyCalculator::new( context, self, family, inherited, style.clone()); let presentation_layout = self.layout_presentation(&mut calculator); let open = calculator.calculate(&PROP_OPEN, self.open.as_ref()); let close = calculator.calculate(&PROP_CLOSE, self.close.as_ref()); let separators: Vec<char> = calculator.calculate(&PROP_SEPARATORS, self.separators.as_ref()) .chars() .filter(|c|!c.is_whitespace()) .collect(); let inherited_fork = calculator.make_fork().copy(); let new_family = family.add(self); // Scope for mutating placeholders based on calculated props { let mut placeholders = self.placeholders.borrow_mut(); // Updated math background since it is not inherited placeholders.with_math_background(Some(presentation_layout.math_background)); let placeholders: &mut Mrow = placeholders.as_any_mut().downcast_mut::<Mrow>().unwrap(); let children = placeholders.children_mut(); // Scope for opening fence operator mutable borrow { let open_fence_op: &mut Mo = children[0].as_any_mut().downcast_mut::<Mo>() .expect("Cannot find opening fence placeholder"); open_fence_op.with_text(open); } // Scope for closing fence operator mutable borrow { let close_fence_op: &mut Mo = children[2].as_any_mut().downcast_mut::<Mo>() .expect("Cannot find closing fence placeholder"); close_fence_op.with_text(close); } // Scope for content mutable borrow { let content: &mut Mrow = children[1].as_any_mut().downcast_mut::<Mrow>() .expect("Cannot find contents"); let mut latest_separator = separators[0]; let mut separator_index = 0usize; for (index, child) in content.children_mut().iter_mut().enumerate() { if index % 2!= 0 { let separator: &mut Mo = child.as_any_mut().downcast_mut::<Mo>() .expect(&format!("Expected operator at index {}", index)); latest_separator = *separators.get(separator_index).unwrap_or(&latest_separator); separator.with_text(latest_separator.to_string()); separator_index += 1; } } } } let row = self.placeholders.borrow(); let layout = row.layout(context, &new_family, &inherited_fork, style); return layout; } fn type_info(&self) -> ElementType { ElementType::GeneralLayout(GeneralLayout::Mfenced) } fn as_any(&self) -> &Any { self } fn
(&mut self) -> &mut Any { self } fn instance_id(&self) -> &InstanceId { &self.instance_id } } impl PresentationPrivate<Mfenced> for Mfenced { fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps { &self.presentation_props } fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps { &mut self.presentation_props } } impl Presentation<Mfenced> for Mfenced {} #[cfg(test)] mod test { use ::test::skia::Snapshot; use super::*; use elements::*; use ::props::*; #[test] fn it_works() { let snap = Snapshot::default(); let mut fenced = Mfenced::new(); fenced.with_child(Box::new(Mi::new(String::from("x")))); snap.snap_element(&fenced, "mfenced_one_element"); fenced.with_child(Box::new(Mi::new(String::from("y")))); snap.snap_element(&fenced, "mfenced_two_elements"); fenced.with_open(Some(String::from("{"))); snap.snap_element(&fenced, "mfenced_curly_braces_open"); fenced.with_close(Some(String::from("}"))); snap.snap_element(&fenced, "mfenced_curly_braces_close"); fenced.with_separators(Some(String::from("."))); snap.snap_element(&fenced, "mfenced_dot_separator"); fenced.with_child(Box::new(Mn::new(String::from("3")))); snap.snap_element(&fenced, "mfenced_repeats_separator"); fenced.with_separators(Some(String::from(",."))); snap.snap_element(&fenced, "mfenced_multiple_separator"); fenced.with_child(Box::new(Mn::new(String::from("2")))); snap.snap_element(&fenced, "mfenced_repeats_last_separator"); fenced.with_math_color(Some(Color::RGB(0, 255, 0))); snap.snap_element(&fenced, "mfenced_green_color"); fenced.with_math_background(Some(Color::RGB(0, 0, 0))); snap.snap_element(&fenced, "mfenced_black_background"); } }
as_any_mut
identifier_name
mfenced.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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::any::Any; use std::cell::RefCell; use super::super::{Element, ElementType, GeneralLayout, InheritedProps, StyleProps, Family, InstanceId, Presentation, PresentationPrivate, SpecifiedPresentationProps, PropertyCalculator, Property, EmptyComputeCtx, Mrow, Mo, Token}; use ::platform::Context; use ::layout::{Layout}; #[allow(const_err)] const PROP_OPEN: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from("("), reader: |i| i.mfenced_open() }; #[allow(const_err)] const PROP_CLOSE: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from(")"), reader: |i| i.mfenced_close(), }; #[allow(const_err)] const PROP_SEPARATORS: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from(","), reader: |i| i.mfenced_separators(), }; pub struct Mfenced { open: Option<String>, close: Option<String>, separators: Option<String>, placeholders: RefCell<Mrow>, presentation_props: SpecifiedPresentationProps, instance_id: InstanceId, } impl Mfenced { pub fn new() -> Mfenced { let mut mrow = Mrow::new(); // Opening fence placeholder mrow.with_child(Box::new(Mo::new(String::new()))); // Content placeholder mrow.with_child(Box::new(Mrow::new())); // Closing fence placeholder mrow.with_child(Box::new(Mo::new(String::new()))); Mfenced { open: None, close: None, separators: None, placeholders: RefCell::new(mrow), presentation_props: SpecifiedPresentationProps::default(), instance_id: InstanceId::new(), } } pub fn with_child<'a>(&'a mut self, child: Box<Element>) -> &'a mut Mfenced { // Scope for mutable borrow of self { let content = &mut self.placeholders.get_mut().children_mut()[1]; let content: &mut Mrow = content.as_any_mut().downcast_mut::<Mrow>().unwrap(); if content.children().len() > 0
content.with_child(child); } self } pub fn with_open<'a>(&'a mut self, fence: Option<String>) -> &'a Mfenced { self.open = fence; self } pub fn open(&self) -> Option<&String> { self.open.as_ref() } pub fn with_close<'a>(&'a mut self, fence: Option<String>) -> &'a Mfenced { self.close = fence; self } pub fn close(&self) -> Option<&String> { self.close.as_ref() } pub fn with_separators<'a>(&'a mut self, separators: Option<String>) -> &'a Mfenced { self.separators = separators; self } pub fn separators(&self) -> Option<&String> { self.separators.as_ref() } } impl Element for Mfenced { fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps, style: &Option<&StyleProps>) -> Box<Layout> { let mut calculator = PropertyCalculator::new( context, self, family, inherited, style.clone()); let presentation_layout = self.layout_presentation(&mut calculator); let open = calculator.calculate(&PROP_OPEN, self.open.as_ref()); let close = calculator.calculate(&PROP_CLOSE, self.close.as_ref()); let separators: Vec<char> = calculator.calculate(&PROP_SEPARATORS, self.separators.as_ref()) .chars() .filter(|c|!c.is_whitespace()) .collect(); let inherited_fork = calculator.make_fork().copy(); let new_family = family.add(self); // Scope for mutating placeholders based on calculated props { let mut placeholders = self.placeholders.borrow_mut(); // Updated math background since it is not inherited placeholders.with_math_background(Some(presentation_layout.math_background)); let placeholders: &mut Mrow = placeholders.as_any_mut().downcast_mut::<Mrow>().unwrap(); let children = placeholders.children_mut(); // Scope for opening fence operator mutable borrow { let open_fence_op: &mut Mo = children[0].as_any_mut().downcast_mut::<Mo>() .expect("Cannot find opening fence placeholder"); open_fence_op.with_text(open); } // Scope for closing fence operator mutable borrow { let close_fence_op: &mut Mo = children[2].as_any_mut().downcast_mut::<Mo>() .expect("Cannot find closing fence placeholder"); close_fence_op.with_text(close); } // Scope for content mutable borrow { let content: &mut Mrow = children[1].as_any_mut().downcast_mut::<Mrow>() .expect("Cannot find contents"); let mut latest_separator = separators[0]; let mut separator_index = 0usize; for (index, child) in content.children_mut().iter_mut().enumerate() { if index % 2!= 0 { let separator: &mut Mo = child.as_any_mut().downcast_mut::<Mo>() .expect(&format!("Expected operator at index {}", index)); latest_separator = *separators.get(separator_index).unwrap_or(&latest_separator); separator.with_text(latest_separator.to_string()); separator_index += 1; } } } } let row = self.placeholders.borrow(); let layout = row.layout(context, &new_family, &inherited_fork, style); return layout; } fn type_info(&self) -> ElementType { ElementType::GeneralLayout(GeneralLayout::Mfenced) } fn as_any(&self) -> &Any { self } fn as_any_mut(&mut self) -> &mut Any { self } fn instance_id(&self) -> &InstanceId { &self.instance_id } } impl PresentationPrivate<Mfenced> for Mfenced { fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps { &self.presentation_props } fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps { &mut self.presentation_props } } impl Presentation<Mfenced> for Mfenced {} #[cfg(test)] mod test { use ::test::skia::Snapshot; use super::*; use elements::*; use ::props::*; #[test] fn it_works() { let snap = Snapshot::default(); let mut fenced = Mfenced::new(); fenced.with_child(Box::new(Mi::new(String::from("x")))); snap.snap_element(&fenced, "mfenced_one_element"); fenced.with_child(Box::new(Mi::new(String::from("y")))); snap.snap_element(&fenced, "mfenced_two_elements"); fenced.with_open(Some(String::from("{"))); snap.snap_element(&fenced, "mfenced_curly_braces_open"); fenced.with_close(Some(String::from("}"))); snap.snap_element(&fenced, "mfenced_curly_braces_close"); fenced.with_separators(Some(String::from("."))); snap.snap_element(&fenced, "mfenced_dot_separator"); fenced.with_child(Box::new(Mn::new(String::from("3")))); snap.snap_element(&fenced, "mfenced_repeats_separator"); fenced.with_separators(Some(String::from(",."))); snap.snap_element(&fenced, "mfenced_multiple_separator"); fenced.with_child(Box::new(Mn::new(String::from("2")))); snap.snap_element(&fenced, "mfenced_repeats_last_separator"); fenced.with_math_color(Some(Color::RGB(0, 255, 0))); snap.snap_element(&fenced, "mfenced_green_color"); fenced.with_math_background(Some(Color::RGB(0, 0, 0))); snap.snap_element(&fenced, "mfenced_black_background"); } }
{ // Separator placeholder content.with_child(Box::new(Mo::new(String::new()))); }
conditional_block
mfenced.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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::any::Any; use std::cell::RefCell; use super::super::{Element, ElementType, GeneralLayout, InheritedProps, StyleProps, Family, InstanceId, Presentation, PresentationPrivate, SpecifiedPresentationProps, PropertyCalculator, Property, EmptyComputeCtx, Mrow, Mo, Token}; use ::platform::Context; use ::layout::{Layout}; #[allow(const_err)] const PROP_OPEN: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from("("), reader: |i| i.mfenced_open() }; #[allow(const_err)] const PROP_CLOSE: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from(")"), reader: |i| i.mfenced_close(), }; #[allow(const_err)] const PROP_SEPARATORS: Property<String, Mfenced, EmptyComputeCtx> = Property::Specified { default: || String::from(","), reader: |i| i.mfenced_separators(), }; pub struct Mfenced { open: Option<String>, close: Option<String>, separators: Option<String>, placeholders: RefCell<Mrow>, presentation_props: SpecifiedPresentationProps, instance_id: InstanceId, } impl Mfenced { pub fn new() -> Mfenced { let mut mrow = Mrow::new(); // Opening fence placeholder mrow.with_child(Box::new(Mo::new(String::new()))); // Content placeholder mrow.with_child(Box::new(Mrow::new())); // Closing fence placeholder mrow.with_child(Box::new(Mo::new(String::new()))); Mfenced { open: None, close: None, separators: None, placeholders: RefCell::new(mrow), presentation_props: SpecifiedPresentationProps::default(), instance_id: InstanceId::new(), } } pub fn with_child<'a>(&'a mut self, child: Box<Element>) -> &'a mut Mfenced { // Scope for mutable borrow of self { let content = &mut self.placeholders.get_mut().children_mut()[1]; let content: &mut Mrow = content.as_any_mut().downcast_mut::<Mrow>().unwrap(); if content.children().len() > 0 { // Separator placeholder content.with_child(Box::new(Mo::new(String::new()))); } content.with_child(child); } self } pub fn with_open<'a>(&'a mut self, fence: Option<String>) -> &'a Mfenced { self.open = fence; self } pub fn open(&self) -> Option<&String> { self.open.as_ref() } pub fn with_close<'a>(&'a mut self, fence: Option<String>) -> &'a Mfenced { self.close = fence; self } pub fn close(&self) -> Option<&String> { self.close.as_ref() } pub fn with_separators<'a>(&'a mut self, separators: Option<String>) -> &'a Mfenced { self.separators = separators; self } pub fn separators(&self) -> Option<&String> { self.separators.as_ref() } } impl Element for Mfenced { fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps, style: &Option<&StyleProps>) -> Box<Layout> { let mut calculator = PropertyCalculator::new( context, self, family, inherited, style.clone()); let presentation_layout = self.layout_presentation(&mut calculator); let open = calculator.calculate(&PROP_OPEN, self.open.as_ref()); let close = calculator.calculate(&PROP_CLOSE, self.close.as_ref()); let separators: Vec<char> = calculator.calculate(&PROP_SEPARATORS, self.separators.as_ref()) .chars() .filter(|c|!c.is_whitespace()) .collect(); let inherited_fork = calculator.make_fork().copy(); let new_family = family.add(self); // Scope for mutating placeholders based on calculated props { let mut placeholders = self.placeholders.borrow_mut(); // Updated math background since it is not inherited placeholders.with_math_background(Some(presentation_layout.math_background)); let placeholders: &mut Mrow = placeholders.as_any_mut().downcast_mut::<Mrow>().unwrap(); let children = placeholders.children_mut(); // Scope for opening fence operator mutable borrow { let open_fence_op: &mut Mo = children[0].as_any_mut().downcast_mut::<Mo>() .expect("Cannot find opening fence placeholder"); open_fence_op.with_text(open); } // Scope for closing fence operator mutable borrow { let close_fence_op: &mut Mo = children[2].as_any_mut().downcast_mut::<Mo>() .expect("Cannot find closing fence placeholder"); close_fence_op.with_text(close); } // Scope for content mutable borrow { let content: &mut Mrow = children[1].as_any_mut().downcast_mut::<Mrow>() .expect("Cannot find contents"); let mut latest_separator = separators[0]; let mut separator_index = 0usize; for (index, child) in content.children_mut().iter_mut().enumerate() { if index % 2!= 0 { let separator: &mut Mo = child.as_any_mut().downcast_mut::<Mo>() .expect(&format!("Expected operator at index {}", index)); latest_separator = *separators.get(separator_index).unwrap_or(&latest_separator); separator.with_text(latest_separator.to_string()); separator_index += 1; } } } } let row = self.placeholders.borrow(); let layout = row.layout(context, &new_family, &inherited_fork, style); return layout; } fn type_info(&self) -> ElementType { ElementType::GeneralLayout(GeneralLayout::Mfenced) } fn as_any(&self) -> &Any { self } fn as_any_mut(&mut self) -> &mut Any
fn instance_id(&self) -> &InstanceId { &self.instance_id } } impl PresentationPrivate<Mfenced> for Mfenced { fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps { &self.presentation_props } fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps { &mut self.presentation_props } } impl Presentation<Mfenced> for Mfenced {} #[cfg(test)] mod test { use ::test::skia::Snapshot; use super::*; use elements::*; use ::props::*; #[test] fn it_works() { let snap = Snapshot::default(); let mut fenced = Mfenced::new(); fenced.with_child(Box::new(Mi::new(String::from("x")))); snap.snap_element(&fenced, "mfenced_one_element"); fenced.with_child(Box::new(Mi::new(String::from("y")))); snap.snap_element(&fenced, "mfenced_two_elements"); fenced.with_open(Some(String::from("{"))); snap.snap_element(&fenced, "mfenced_curly_braces_open"); fenced.with_close(Some(String::from("}"))); snap.snap_element(&fenced, "mfenced_curly_braces_close"); fenced.with_separators(Some(String::from("."))); snap.snap_element(&fenced, "mfenced_dot_separator"); fenced.with_child(Box::new(Mn::new(String::from("3")))); snap.snap_element(&fenced, "mfenced_repeats_separator"); fenced.with_separators(Some(String::from(",."))); snap.snap_element(&fenced, "mfenced_multiple_separator"); fenced.with_child(Box::new(Mn::new(String::from("2")))); snap.snap_element(&fenced, "mfenced_repeats_last_separator"); fenced.with_math_color(Some(Color::RGB(0, 255, 0))); snap.snap_element(&fenced, "mfenced_green_color"); fenced.with_math_background(Some(Color::RGB(0, 0, 0))); snap.snap_element(&fenced, "mfenced_black_background"); } }
{ self }
identifier_body
local_data.rs
`local_data_key!` macro. This macro will expand to a `static` item appropriately named and annotated. This name is then passed to the functions in this module to modify/read the slot specified by the key. ```rust use std::local_data; local_data_key!(key_int: int) local_data_key!(key_vector: ~[int]) local_data::set(key_int, 3); local_data::get(key_int, |opt| assert_eq!(opt.map(|x| *x), Some(3))); local_data::set(key_vector, ~[4]); local_data::get(key_vector, |opt| assert_eq!(*opt.unwrap(), ~[4])); ``` */ // Casting 'Arcane Sight' reveals an overwhelming aura of Transmutation // magic. use cast; use libc; use prelude::*; use rt::task::{Task, LocalStorage}; use util; /** * Indexes a task-local data slot. This pointer is used for comparison to * differentiate keys from one another. The actual type `T` is not used anywhere * as a member of this type, except that it is parameterized with it to define * the type of each key's value. * * The value of each Key is of the singleton enum KeyValue. These also have the * same name as `Key` and their purpose is to take up space in the programs data * sections to ensure that each value of the `Key` type points to a unique * location. */ pub type Key<T> = &'static KeyValue<T>; #[allow(missing_doc)] pub enum KeyValue<T> { Key } #[allow(missing_doc)] trait LocalData {} impl<T:'static> LocalData for T {} // The task-local-map stores all TLS information for the currently running task. // It is stored as an owned pointer into the runtime, and it's only allocated // when TLS is used for the first time. This map must be very carefully // constructed because it has many mutable loans unsoundly handed out on it to // the various invocations of TLS requests. // // One of the most important operations is loaning a value via `get` to a // caller. In doing so, the slot that the TLS entry is occupying cannot be // invalidated because upon returning its loan state must be updated. Currently // the TLS map is a vector, but this is possibly dangerous because the vector // can be reallocated/moved when new values are pushed onto it. // // This problem currently isn't solved in a very elegant way. Inside the `get` // function, it internally "invalidates" all references after the loan is // finished and looks up into the vector again. In theory this will prevent // pointers from being moved under our feet so long as LLVM doesn't go too crazy // with the optimizations. // // n.b. If TLS is used heavily in future, this could be made more efficient with // a proper map. #[doc(hidden)] pub type Map = ~[Option<(*libc::c_void, TLSValue, LoanState)>]; type TLSValue = ~LocalData; // Gets the map from the runtime. Lazily initialises if not done so already. unsafe fn get_local_map() -> &mut Map { use rt::local::Local; let task: *mut Task = Local::unsafe_borrow(); match &mut (*task).storage { // If the at_exit function is already set, then we just need to take // a loan out on the TLS map stored inside &LocalStorage(Some(ref mut map_ptr)) => { return map_ptr; } // If this is the first time we've accessed TLS, perform similar // actions to the oldsched way of doing things. &LocalStorage(ref mut slot) => { *slot = Some(~[]); match *slot { Some(ref mut map_ptr) => { return map_ptr } None => abort() } } } } #[deriving(Eq)] enum LoanState { NoLoan, ImmLoan, MutLoan } impl LoanState { fn describe(&self) -> &'static str { match *self { NoLoan => "no loan", ImmLoan => "immutable", MutLoan => "mutable" } } } fn key_to_key_value<T:'static>(key: Key<T>) -> *libc::c_void { unsafe { cast::transmute(key) } } /// Removes a task-local value from task-local storage. This will return /// Some(value) if the key was present in TLS, otherwise it will return None. /// /// A runtime assertion will be triggered it removal of TLS value is attempted /// while the value is still loaned out via `get` or `get_mut`. pub fn pop<T:'static>(key: Key<T>) -> Option<T> { let map = unsafe { get_local_map() }; let key_value = key_to_key_value(key); for entry in map.mut_iter() { match *entry { Some((k, _, loan)) if k == key_value => { if loan!= NoLoan { fail!("TLS value cannot be removed because it is currently \ borrowed as {}", loan.describe()); } // Move the data out of the `entry` slot via util::replace. // This is guaranteed to succeed because we already matched // on `Some` above. let data = match util::replace(entry, None) { Some((_, data, _)) => data, None => abort() }; // Move `data` into transmute to get out the memory that it // owns, we must free it manually later. let (_vtable, alloc): (uint, ~T) = unsafe { cast::transmute(data) }; // Now that we own `alloc`, we can just move out of it as we // would with any other data. return Some(*alloc); } _ => {} } } return None; } /// Retrieves a value from TLS. The closure provided is yielded `Some` of a /// reference to the value located in TLS if one exists, or `None` if the key /// provided is not present in TLS currently. /// /// It is considered a runtime error to attempt to get a value which is already /// on loan via the `get_mut` method provided. pub fn get<T:'static, U>(key: Key<T>, f: |Option<&T>| -> U) -> U { get_with(key, ImmLoan, f) } /// Retrieves a mutable value from TLS. The closure provided is yielded `Some` /// of a reference to the mutable value located in TLS if one exists, or `None` /// if the key provided is not present in TLS currently. /// /// It is considered a runtime error to attempt to get a value which is already /// on loan via this or the `get` methods. This is similar to how it's a runtime /// error to take two mutable loans on an `@mut` box. pub fn get_mut<T:'static, U>(key: Key<T>, f: |Option<&mut T>| -> U) -> U { get_with(key, MutLoan, |x| { match x { None => f(None), // We're violating a lot of compiler guarantees with this // invocation of `transmute_mut`, but we're doing runtime checks to // ensure that it's always valid (only one at a time). // // there is no need to be upset! Some(x) => { f(Some(unsafe { cast::transmute_mut(x) })) } } }) } fn get_with<T:'static, U>( key: Key<T>, state: LoanState, f: |Option<&T>| -> U) -> U { // This function must be extremely careful. Because TLS can store owned // values, and we must have some form of `get` function other than `pop`, // this function has to give a `&` reference back to the caller. // // One option is to return the reference, but this cannot be sound because // the actual lifetime of the object is not known. The slot in TLS could not // be modified until the object goes out of scope, but the TLS code cannot // know when this happens. // // For this reason, the reference is yielded to a specified closure. This // way the TLS code knows exactly what the lifetime of the yielded pointer // is, allowing callers to acquire references to owned data. This is also // sound so long as measures are taken to ensure that while a TLS slot is // loaned out to a caller, it's not modified recursively. let map = unsafe { get_local_map() }; let key_value = key_to_key_value(key); let pos = map.iter().position(|entry| { match *entry { Some((k, _, _)) if k == key_value => true, _ => false } }); match pos { None => { return f(None); } Some(i) => { let ret; let mut return_loan = false; match map[i] { Some((_, ref data, ref mut loan)) => { match (state, *loan) { (_, NoLoan) => { *loan = state; return_loan = true; } (ImmLoan, ImmLoan) => {} (want, cur) => { fail!("TLS slot cannot be borrowed as {} because \ it is already borrowed as {}", want.describe(), cur.describe()); } } // data was created with `~T as ~LocalData`, so we extract // pointer part of the trait, (as ~T), and then use // compiler coercions to achieve a '&' pointer. unsafe { match *cast::transmute::<&TLSValue, &(uint, ~T)>(data){ (_vtable, ref alloc) => { let value: &T = *alloc; ret = f(Some(value)); } } } } _ => abort() } // n.b. 'data' and 'loans' are both invalid pointers at the point // 'f' returned because `f` could have appended more TLS items which // in turn relocated the vector. Hence we do another lookup here to // fixup the loans. if return_loan { match map[i] { Some((_, _, ref mut loan)) => { *loan = NoLoan; } None => abort() } } return ret; } } } fn abort() ->!
/// Inserts a value into task local storage. If the key is already present in /// TLS, then the previous value is removed and replaced with the provided data. /// /// It is considered a runtime error to attempt to set a key which is currently /// on loan via the `get` or `get_mut` methods. pub fn set<T:'static>(key: Key<T>, data: T) { let map = unsafe { get_local_map() }; let keyval = key_to_key_value(key); // When the task-local map is destroyed, all the data needs to be cleaned // up. For this reason we can't do some clever tricks to store '~T' as a // '*c_void' or something like that. To solve the problem, we cast // everything to a trait (LocalData) which is then stored inside the map. // Upon destruction of the map, all the objects will be destroyed and the // traits have enough information about them to destroy themselves. let data = ~data as ~LocalData:; fn insertion_position(map: &mut Map, key: *libc::c_void) -> Option<uint> { // First see if the map contains this key already let curspot = map.iter().position(|entry| { match *entry { Some((ekey, _, loan)) if key == ekey => { if loan!= NoLoan { fail!("TLS value cannot be overwritten because it is already borrowed as {}", loan.describe()) } true } _ => false, } }); // If it doesn't contain the key, just find a slot that's None match curspot { Some(i) => Some(i), None => map.iter().position(|entry| entry.is_none()) } } // The type of the local data map must ascribe to Send, so we do the // transmute here to add the Send bound back on. This doesn't actually // matter because TLS will always own the data (until its moved out) and // we're not actually sending it to other schedulers or anything. let data: ~LocalData = unsafe { cast::transmute(data) }; match insertion_position(map, keyval) { Some(i) => { map[i] = Some((keyval, data, NoLoan)); } None => { map.push(Some((keyval, data, NoLoan))); } } } /// Modifies a task-local value by temporarily removing it from task-local /// storage and then re-inserting if `Some` is returned from the closure. /// /// This function will have the same runtime errors as generated from `pop` and /// `set` (the key must not currently be on loan pub fn modify<T:'static>(key: Key<T>, f: |Option<T>| -> Option<T>) { match f(pop(key)) { Some(next) => { set(key, next); } None => {} } } #[cfg(test)] mod tests { use prelude::*; use super::*; use task; #[test] fn test_tls_multitask() { static my_key: Key<~str> = &Key; set(my_key, ~"parent data"); do task::spawn { // TLS shouldn't carry over. assert!(get(my_key, |k| k.map(|k| (*k).clone())).is_none()); set(my_key, ~"child data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"child data"); // should be cleaned up for us } // Must work multiple times assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); } #[test] fn test_tls_overwrite() { static my_key: Key<~str> = &Key; set(my_key, ~"first data"); set(my_key, ~"next data"); // Shouldn't leak. assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"next data"); } #[test] fn test_tls_pop() { static my_key: Key<~str> = &Key; set(my_key, ~"weasel"); assert!(pop(my_key).unwrap() == ~"weasel"); // Pop must remove the data from the map. assert!(pop(my_key).is_none()); } #[test] fn test_tls_modify() { static my_key: Key<~str> = &Key; modify(my_key, |data| { match data { Some(ref val) => fail!("unwelcome value: {}", *val), None => Some(~"first data") } }); modify(my_key, |data| { match data { Some(~"first data") => Some(~"next data"), Some(ref val) => fail!("wrong value: {}", *val), None => fail!("missing value") } }); assert!(pop(my_key).unwrap() == ~"next data"); } #[test] fn test_tls_crust_automorestack_memorial_bug() { // This might result in a stack-canary clobber if the runtime fails to // set sp_limit to 0 when calling the cleanup extern - it might // automatically jump over to the rust stack, which causes next_c_sp // to get recorded as something within a rust stack segment. Then a // subsequent upcall (esp. for logging, think vsnprintf) would run on // a stack smaller than 1 MB. static my_key: Key<~str> = &Key; do task::spawn { set(my_key, ~"hax"); } } #[test] fn test_tls_multiple_types() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; do task::spawn { set(str_key, ~"string data"); set(box_key, @()); set(int_key, 42); } } #[test] #[allow(dead_code)] fn test_tls_overwrite_multiple_types() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; do task::spawn { set(str_key, ~"string data"); set(str_key, ~"string data 2"); set(box_key, @()); set(box_key, @()); set(int_key, 42); // This could cause a segfault if overwriting-destruction is done // with the crazy polymorphic transmute rather than the provided // finaliser. set(int_key, 31337); } } #[test] #[should_fail] fn test_tls_cleanup_on_failure() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; set(str_key, ~"parent data"); set(box_key, @()); do task::spawn { // spawn_linked set(str_key, ~"string data"); set(box_key, @()); set(int_key, 42); fail!(); } // Not quite nondeterministic. set(int_key, 31337); fail!(); } #[test] fn test_static_pointer() { static key: Key<&'static int> = &Key; static VALUE: int = 0; let v: &'static int = &VALUE; set(key, v); } #[test] fn test_owned() { static key: Key<~int> = &Key; set(key, ~1); get(key, |v| { get(key, |v| { get(key, |v| { assert_eq!(**v.unwrap(), 1); }); assert_eq!(**v.unwrap(), 1); }); assert_eq!(**v.unwrap(), 1); }); set(key, ~2); get(key, |v| { assert_eq!(**v.unwrap(), 2); }) } #[test] fn test_get_mut() { static key: Key<int> = &Key; set(key, 1); get_mut(key, |v| { *v.unwrap() = 2; }); get(key, |v| { assert_eq!(*v.unwrap(), 2); }) } #[test] fn test_same_key_type() { static key1: Key<int> = &Key; static key2: Key<int> = &Key; static key3: Key<int> = &Key; static key4: Key<int> = &Key; static key5: Key<int> = &Key; set(key1, 1); set(key2, 2); set(key3, 3); set(key4, 4); set(key5, 5); get(key1, |x| assert_eq!(*x.unwrap(), 1)); get(key2, |x| assert_eq!(*x.unwrap(), 2)); get(key3, |x| assert_eq!(*x.unwrap(), 3)); get(key4, |x| assert_eq!(*x.unwrap(), 4)); get(key5, |x| assert_eq!(*x.unwrap(), 5));
{ unsafe { libc::abort() } }
identifier_body
local_data.rs
`local_data_key!` macro. This macro will expand to a `static` item appropriately named and annotated. This name is then passed to the functions in this module to modify/read the slot specified by the key. ```rust use std::local_data; local_data_key!(key_int: int) local_data_key!(key_vector: ~[int]) local_data::set(key_int, 3); local_data::get(key_int, |opt| assert_eq!(opt.map(|x| *x), Some(3))); local_data::set(key_vector, ~[4]); local_data::get(key_vector, |opt| assert_eq!(*opt.unwrap(), ~[4])); ``` */ // Casting 'Arcane Sight' reveals an overwhelming aura of Transmutation // magic. use cast; use libc; use prelude::*; use rt::task::{Task, LocalStorage}; use util; /** * Indexes a task-local data slot. This pointer is used for comparison to * differentiate keys from one another. The actual type `T` is not used anywhere * as a member of this type, except that it is parameterized with it to define * the type of each key's value. * * The value of each Key is of the singleton enum KeyValue. These also have the * same name as `Key` and their purpose is to take up space in the programs data * sections to ensure that each value of the `Key` type points to a unique * location. */ pub type Key<T> = &'static KeyValue<T>; #[allow(missing_doc)] pub enum KeyValue<T> { Key } #[allow(missing_doc)] trait LocalData {} impl<T:'static> LocalData for T {} // The task-local-map stores all TLS information for the currently running task. // It is stored as an owned pointer into the runtime, and it's only allocated // when TLS is used for the first time. This map must be very carefully // constructed because it has many mutable loans unsoundly handed out on it to // the various invocations of TLS requests. // // One of the most important operations is loaning a value via `get` to a // caller. In doing so, the slot that the TLS entry is occupying cannot be // invalidated because upon returning its loan state must be updated. Currently // the TLS map is a vector, but this is possibly dangerous because the vector // can be reallocated/moved when new values are pushed onto it. // // This problem currently isn't solved in a very elegant way. Inside the `get` // function, it internally "invalidates" all references after the loan is // finished and looks up into the vector again. In theory this will prevent // pointers from being moved under our feet so long as LLVM doesn't go too crazy // with the optimizations. // // n.b. If TLS is used heavily in future, this could be made more efficient with // a proper map. #[doc(hidden)] pub type Map = ~[Option<(*libc::c_void, TLSValue, LoanState)>]; type TLSValue = ~LocalData; // Gets the map from the runtime. Lazily initialises if not done so already. unsafe fn get_local_map() -> &mut Map { use rt::local::Local; let task: *mut Task = Local::unsafe_borrow(); match &mut (*task).storage { // If the at_exit function is already set, then we just need to take // a loan out on the TLS map stored inside &LocalStorage(Some(ref mut map_ptr)) => { return map_ptr; } // If this is the first time we've accessed TLS, perform similar // actions to the oldsched way of doing things. &LocalStorage(ref mut slot) => { *slot = Some(~[]); match *slot { Some(ref mut map_ptr) => { return map_ptr } None => abort() } } } } #[deriving(Eq)] enum LoanState { NoLoan, ImmLoan, MutLoan } impl LoanState { fn describe(&self) -> &'static str { match *self { NoLoan => "no loan", ImmLoan => "immutable", MutLoan => "mutable" } } } fn key_to_key_value<T:'static>(key: Key<T>) -> *libc::c_void { unsafe { cast::transmute(key) } } /// Removes a task-local value from task-local storage. This will return /// Some(value) if the key was present in TLS, otherwise it will return None. /// /// A runtime assertion will be triggered it removal of TLS value is attempted /// while the value is still loaned out via `get` or `get_mut`. pub fn pop<T:'static>(key: Key<T>) -> Option<T> { let map = unsafe { get_local_map() }; let key_value = key_to_key_value(key); for entry in map.mut_iter() { match *entry { Some((k, _, loan)) if k == key_value => { if loan!= NoLoan { fail!("TLS value cannot be removed because it is currently \ borrowed as {}", loan.describe()); } // Move the data out of the `entry` slot via util::replace. // This is guaranteed to succeed because we already matched // on `Some` above. let data = match util::replace(entry, None) { Some((_, data, _)) => data, None => abort() }; // Move `data` into transmute to get out the memory that it // owns, we must free it manually later. let (_vtable, alloc): (uint, ~T) = unsafe { cast::transmute(data) }; // Now that we own `alloc`, we can just move out of it as we // would with any other data. return Some(*alloc); } _ => {} } } return None; } /// Retrieves a value from TLS. The closure provided is yielded `Some` of a /// reference to the value located in TLS if one exists, or `None` if the key /// provided is not present in TLS currently. /// /// It is considered a runtime error to attempt to get a value which is already /// on loan via the `get_mut` method provided. pub fn get<T:'static, U>(key: Key<T>, f: |Option<&T>| -> U) -> U { get_with(key, ImmLoan, f) } /// Retrieves a mutable value from TLS. The closure provided is yielded `Some` /// of a reference to the mutable value located in TLS if one exists, or `None` /// if the key provided is not present in TLS currently. /// /// It is considered a runtime error to attempt to get a value which is already /// on loan via this or the `get` methods. This is similar to how it's a runtime /// error to take two mutable loans on an `@mut` box. pub fn get_mut<T:'static, U>(key: Key<T>, f: |Option<&mut T>| -> U) -> U { get_with(key, MutLoan, |x| { match x { None => f(None), // We're violating a lot of compiler guarantees with this // invocation of `transmute_mut`, but we're doing runtime checks to // ensure that it's always valid (only one at a time). // // there is no need to be upset! Some(x) => { f(Some(unsafe { cast::transmute_mut(x) })) } } }) } fn get_with<T:'static, U>( key: Key<T>, state: LoanState, f: |Option<&T>| -> U) -> U { // This function must be extremely careful. Because TLS can store owned // values, and we must have some form of `get` function other than `pop`, // this function has to give a `&` reference back to the caller. // // One option is to return the reference, but this cannot be sound because // the actual lifetime of the object is not known. The slot in TLS could not // be modified until the object goes out of scope, but the TLS code cannot // know when this happens. // // For this reason, the reference is yielded to a specified closure. This // way the TLS code knows exactly what the lifetime of the yielded pointer // is, allowing callers to acquire references to owned data. This is also // sound so long as measures are taken to ensure that while a TLS slot is // loaned out to a caller, it's not modified recursively. let map = unsafe { get_local_map() }; let key_value = key_to_key_value(key); let pos = map.iter().position(|entry| { match *entry { Some((k, _, _)) if k == key_value => true, _ => false } }); match pos { None => { return f(None); } Some(i) => { let ret; let mut return_loan = false; match map[i] { Some((_, ref data, ref mut loan)) => { match (state, *loan) { (_, NoLoan) => { *loan = state; return_loan = true; } (ImmLoan, ImmLoan) => {} (want, cur) => { fail!("TLS slot cannot be borrowed as {} because \ it is already borrowed as {}", want.describe(), cur.describe()); } } // data was created with `~T as ~LocalData`, so we extract // pointer part of the trait, (as ~T), and then use // compiler coercions to achieve a '&' pointer. unsafe { match *cast::transmute::<&TLSValue, &(uint, ~T)>(data){ (_vtable, ref alloc) => { let value: &T = *alloc; ret = f(Some(value)); } } } } _ => abort() } // n.b. 'data' and 'loans' are both invalid pointers at the point // 'f' returned because `f` could have appended more TLS items which // in turn relocated the vector. Hence we do another lookup here to // fixup the loans. if return_loan { match map[i] { Some((_, _, ref mut loan)) => { *loan = NoLoan; } None => abort() } } return ret; } } } fn abort() ->! { unsafe { libc::abort() } } /// Inserts a value into task local storage. If the key is already present in /// TLS, then the previous value is removed and replaced with the provided data. /// /// It is considered a runtime error to attempt to set a key which is currently /// on loan via the `get` or `get_mut` methods. pub fn set<T:'static>(key: Key<T>, data: T) { let map = unsafe { get_local_map() }; let keyval = key_to_key_value(key); // When the task-local map is destroyed, all the data needs to be cleaned // up. For this reason we can't do some clever tricks to store '~T' as a // '*c_void' or something like that. To solve the problem, we cast // everything to a trait (LocalData) which is then stored inside the map. // Upon destruction of the map, all the objects will be destroyed and the // traits have enough information about them to destroy themselves. let data = ~data as ~LocalData:; fn
(map: &mut Map, key: *libc::c_void) -> Option<uint> { // First see if the map contains this key already let curspot = map.iter().position(|entry| { match *entry { Some((ekey, _, loan)) if key == ekey => { if loan!= NoLoan { fail!("TLS value cannot be overwritten because it is already borrowed as {}", loan.describe()) } true } _ => false, } }); // If it doesn't contain the key, just find a slot that's None match curspot { Some(i) => Some(i), None => map.iter().position(|entry| entry.is_none()) } } // The type of the local data map must ascribe to Send, so we do the // transmute here to add the Send bound back on. This doesn't actually // matter because TLS will always own the data (until its moved out) and // we're not actually sending it to other schedulers or anything. let data: ~LocalData = unsafe { cast::transmute(data) }; match insertion_position(map, keyval) { Some(i) => { map[i] = Some((keyval, data, NoLoan)); } None => { map.push(Some((keyval, data, NoLoan))); } } } /// Modifies a task-local value by temporarily removing it from task-local /// storage and then re-inserting if `Some` is returned from the closure. /// /// This function will have the same runtime errors as generated from `pop` and /// `set` (the key must not currently be on loan pub fn modify<T:'static>(key: Key<T>, f: |Option<T>| -> Option<T>) { match f(pop(key)) { Some(next) => { set(key, next); } None => {} } } #[cfg(test)] mod tests { use prelude::*; use super::*; use task; #[test] fn test_tls_multitask() { static my_key: Key<~str> = &Key; set(my_key, ~"parent data"); do task::spawn { // TLS shouldn't carry over. assert!(get(my_key, |k| k.map(|k| (*k).clone())).is_none()); set(my_key, ~"child data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"child data"); // should be cleaned up for us } // Must work multiple times assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); } #[test] fn test_tls_overwrite() { static my_key: Key<~str> = &Key; set(my_key, ~"first data"); set(my_key, ~"next data"); // Shouldn't leak. assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"next data"); } #[test] fn test_tls_pop() { static my_key: Key<~str> = &Key; set(my_key, ~"weasel"); assert!(pop(my_key).unwrap() == ~"weasel"); // Pop must remove the data from the map. assert!(pop(my_key).is_none()); } #[test] fn test_tls_modify() { static my_key: Key<~str> = &Key; modify(my_key, |data| { match data { Some(ref val) => fail!("unwelcome value: {}", *val), None => Some(~"first data") } }); modify(my_key, |data| { match data { Some(~"first data") => Some(~"next data"), Some(ref val) => fail!("wrong value: {}", *val), None => fail!("missing value") } }); assert!(pop(my_key).unwrap() == ~"next data"); } #[test] fn test_tls_crust_automorestack_memorial_bug() { // This might result in a stack-canary clobber if the runtime fails to // set sp_limit to 0 when calling the cleanup extern - it might // automatically jump over to the rust stack, which causes next_c_sp // to get recorded as something within a rust stack segment. Then a // subsequent upcall (esp. for logging, think vsnprintf) would run on // a stack smaller than 1 MB. static my_key: Key<~str> = &Key; do task::spawn { set(my_key, ~"hax"); } } #[test] fn test_tls_multiple_types() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; do task::spawn { set(str_key, ~"string data"); set(box_key, @()); set(int_key, 42); } } #[test] #[allow(dead_code)] fn test_tls_overwrite_multiple_types() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; do task::spawn { set(str_key, ~"string data"); set(str_key, ~"string data 2"); set(box_key, @()); set(box_key, @()); set(int_key, 42); // This could cause a segfault if overwriting-destruction is done // with the crazy polymorphic transmute rather than the provided // finaliser. set(int_key, 31337); } } #[test] #[should_fail] fn test_tls_cleanup_on_failure() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; set(str_key, ~"parent data"); set(box_key, @()); do task::spawn { // spawn_linked set(str_key, ~"string data"); set(box_key, @()); set(int_key, 42); fail!(); } // Not quite nondeterministic. set(int_key, 31337); fail!(); } #[test] fn test_static_pointer() { static key: Key<&'static int> = &Key; static VALUE: int = 0; let v: &'static int = &VALUE; set(key, v); } #[test] fn test_owned() { static key: Key<~int> = &Key; set(key, ~1); get(key, |v| { get(key, |v| { get(key, |v| { assert_eq!(**v.unwrap(), 1); }); assert_eq!(**v.unwrap(), 1); }); assert_eq!(**v.unwrap(), 1); }); set(key, ~2); get(key, |v| { assert_eq!(**v.unwrap(), 2); }) } #[test] fn test_get_mut() { static key: Key<int> = &Key; set(key, 1); get_mut(key, |v| { *v.unwrap() = 2; }); get(key, |v| { assert_eq!(*v.unwrap(), 2); }) } #[test] fn test_same_key_type() { static key1: Key<int> = &Key; static key2: Key<int> = &Key; static key3: Key<int> = &Key; static key4: Key<int> = &Key; static key5: Key<int> = &Key; set(key1, 1); set(key2, 2); set(key3, 3); set(key4, 4); set(key5, 5); get(key1, |x| assert_eq!(*x.unwrap(), 1)); get(key2, |x| assert_eq!(*x.unwrap(), 2)); get(key3, |x| assert_eq!(*x.unwrap(), 3)); get(key4, |x| assert_eq!(*x.unwrap(), 4)); get(key5, |x| assert_eq!(*x.unwrap(), 5));
insertion_position
identifier_name
local_data.rs
the `local_data_key!` macro. This macro will expand to a `static` item appropriately named and annotated. This name is then passed to the functions in this module to modify/read the slot specified by the key. ```rust use std::local_data; local_data_key!(key_int: int) local_data_key!(key_vector: ~[int]) local_data::set(key_int, 3); local_data::get(key_int, |opt| assert_eq!(opt.map(|x| *x), Some(3))); local_data::set(key_vector, ~[4]); local_data::get(key_vector, |opt| assert_eq!(*opt.unwrap(), ~[4])); ``` */ // Casting 'Arcane Sight' reveals an overwhelming aura of Transmutation // magic. use cast; use libc; use prelude::*; use rt::task::{Task, LocalStorage}; use util; /** * Indexes a task-local data slot. This pointer is used for comparison to * differentiate keys from one another. The actual type `T` is not used anywhere * as a member of this type, except that it is parameterized with it to define * the type of each key's value. * * The value of each Key is of the singleton enum KeyValue. These also have the * same name as `Key` and their purpose is to take up space in the programs data * sections to ensure that each value of the `Key` type points to a unique * location. */ pub type Key<T> = &'static KeyValue<T>; #[allow(missing_doc)] pub enum KeyValue<T> { Key } #[allow(missing_doc)] trait LocalData {} impl<T:'static> LocalData for T {} // The task-local-map stores all TLS information for the currently running task. // It is stored as an owned pointer into the runtime, and it's only allocated // when TLS is used for the first time. This map must be very carefully // constructed because it has many mutable loans unsoundly handed out on it to // the various invocations of TLS requests. // // One of the most important operations is loaning a value via `get` to a // caller. In doing so, the slot that the TLS entry is occupying cannot be // invalidated because upon returning its loan state must be updated. Currently // the TLS map is a vector, but this is possibly dangerous because the vector // can be reallocated/moved when new values are pushed onto it. // // This problem currently isn't solved in a very elegant way. Inside the `get` // function, it internally "invalidates" all references after the loan is // finished and looks up into the vector again. In theory this will prevent // pointers from being moved under our feet so long as LLVM doesn't go too crazy // with the optimizations. // // n.b. If TLS is used heavily in future, this could be made more efficient with // a proper map. #[doc(hidden)] pub type Map = ~[Option<(*libc::c_void, TLSValue, LoanState)>]; type TLSValue = ~LocalData; // Gets the map from the runtime. Lazily initialises if not done so already. unsafe fn get_local_map() -> &mut Map { use rt::local::Local; let task: *mut Task = Local::unsafe_borrow(); match &mut (*task).storage { // If the at_exit function is already set, then we just need to take // a loan out on the TLS map stored inside &LocalStorage(Some(ref mut map_ptr)) => { return map_ptr; } // If this is the first time we've accessed TLS, perform similar // actions to the oldsched way of doing things. &LocalStorage(ref mut slot) => { *slot = Some(~[]); match *slot { Some(ref mut map_ptr) => { return map_ptr } None => abort() } } } } #[deriving(Eq)] enum LoanState { NoLoan, ImmLoan, MutLoan } impl LoanState { fn describe(&self) -> &'static str { match *self { NoLoan => "no loan", ImmLoan => "immutable", MutLoan => "mutable" } } } fn key_to_key_value<T:'static>(key: Key<T>) -> *libc::c_void { unsafe { cast::transmute(key) } } /// Removes a task-local value from task-local storage. This will return /// Some(value) if the key was present in TLS, otherwise it will return None. /// /// A runtime assertion will be triggered it removal of TLS value is attempted /// while the value is still loaned out via `get` or `get_mut`. pub fn pop<T:'static>(key: Key<T>) -> Option<T> { let map = unsafe { get_local_map() }; let key_value = key_to_key_value(key); for entry in map.mut_iter() { match *entry { Some((k, _, loan)) if k == key_value => { if loan!= NoLoan { fail!("TLS value cannot be removed because it is currently \ borrowed as {}", loan.describe()); } // Move the data out of the `entry` slot via util::replace. // This is guaranteed to succeed because we already matched // on `Some` above. let data = match util::replace(entry, None) { Some((_, data, _)) => data, None => abort() }; // Move `data` into transmute to get out the memory that it // owns, we must free it manually later. let (_vtable, alloc): (uint, ~T) = unsafe { cast::transmute(data) }; // Now that we own `alloc`, we can just move out of it as we // would with any other data. return Some(*alloc); } _ => {} } } return None; } /// Retrieves a value from TLS. The closure provided is yielded `Some` of a /// reference to the value located in TLS if one exists, or `None` if the key /// provided is not present in TLS currently. /// /// It is considered a runtime error to attempt to get a value which is already /// on loan via the `get_mut` method provided. pub fn get<T:'static, U>(key: Key<T>, f: |Option<&T>| -> U) -> U { get_with(key, ImmLoan, f) } /// Retrieves a mutable value from TLS. The closure provided is yielded `Some` /// of a reference to the mutable value located in TLS if one exists, or `None` /// if the key provided is not present in TLS currently. /// /// It is considered a runtime error to attempt to get a value which is already /// on loan via this or the `get` methods. This is similar to how it's a runtime /// error to take two mutable loans on an `@mut` box. pub fn get_mut<T:'static, U>(key: Key<T>, f: |Option<&mut T>| -> U) -> U { get_with(key, MutLoan, |x| { match x { None => f(None), // We're violating a lot of compiler guarantees with this // invocation of `transmute_mut`, but we're doing runtime checks to // ensure that it's always valid (only one at a time). // // there is no need to be upset! Some(x) => { f(Some(unsafe { cast::transmute_mut(x) })) } } }) } fn get_with<T:'static, U>( key: Key<T>, state: LoanState, f: |Option<&T>| -> U) -> U { // This function must be extremely careful. Because TLS can store owned // values, and we must have some form of `get` function other than `pop`, // this function has to give a `&` reference back to the caller. // // One option is to return the reference, but this cannot be sound because // the actual lifetime of the object is not known. The slot in TLS could not // be modified until the object goes out of scope, but the TLS code cannot // know when this happens. // // For this reason, the reference is yielded to a specified closure. This // way the TLS code knows exactly what the lifetime of the yielded pointer // is, allowing callers to acquire references to owned data. This is also // sound so long as measures are taken to ensure that while a TLS slot is // loaned out to a caller, it's not modified recursively. let map = unsafe { get_local_map() }; let key_value = key_to_key_value(key); let pos = map.iter().position(|entry| { match *entry { Some((k, _, _)) if k == key_value => true, _ => false } }); match pos { None => { return f(None); } Some(i) => { let ret; let mut return_loan = false; match map[i] { Some((_, ref data, ref mut loan)) => { match (state, *loan) { (_, NoLoan) => { *loan = state; return_loan = true; } (ImmLoan, ImmLoan) => {} (want, cur) => { fail!("TLS slot cannot be borrowed as {} because \ it is already borrowed as {}", want.describe(), cur.describe()); } } // data was created with `~T as ~LocalData`, so we extract // pointer part of the trait, (as ~T), and then use // compiler coercions to achieve a '&' pointer. unsafe { match *cast::transmute::<&TLSValue, &(uint, ~T)>(data){ (_vtable, ref alloc) => { let value: &T = *alloc; ret = f(Some(value)); } } } } _ => abort() } // n.b. 'data' and 'loans' are both invalid pointers at the point // 'f' returned because `f` could have appended more TLS items which // in turn relocated the vector. Hence we do another lookup here to // fixup the loans. if return_loan { match map[i] { Some((_, _, ref mut loan)) => { *loan = NoLoan; } None => abort() } } return ret; } } } fn abort() ->! { unsafe { libc::abort() } } /// Inserts a value into task local storage. If the key is already present in /// TLS, then the previous value is removed and replaced with the provided data. /// /// It is considered a runtime error to attempt to set a key which is currently /// on loan via the `get` or `get_mut` methods. pub fn set<T:'static>(key: Key<T>, data: T) { let map = unsafe { get_local_map() }; let keyval = key_to_key_value(key); // When the task-local map is destroyed, all the data needs to be cleaned // up. For this reason we can't do some clever tricks to store '~T' as a // '*c_void' or something like that. To solve the problem, we cast // everything to a trait (LocalData) which is then stored inside the map. // Upon destruction of the map, all the objects will be destroyed and the // traits have enough information about them to destroy themselves. let data = ~data as ~LocalData:; fn insertion_position(map: &mut Map, key: *libc::c_void) -> Option<uint> { // First see if the map contains this key already let curspot = map.iter().position(|entry| { match *entry { Some((ekey, _, loan)) if key == ekey => { if loan!= NoLoan { fail!("TLS value cannot be overwritten because it is already borrowed as {}", loan.describe()) } true } _ => false, } }); // If it doesn't contain the key, just find a slot that's None match curspot { Some(i) => Some(i), None => map.iter().position(|entry| entry.is_none()) } } // The type of the local data map must ascribe to Send, so we do the // transmute here to add the Send bound back on. This doesn't actually // matter because TLS will always own the data (until its moved out) and // we're not actually sending it to other schedulers or anything. let data: ~LocalData = unsafe { cast::transmute(data) }; match insertion_position(map, keyval) { Some(i) => { map[i] = Some((keyval, data, NoLoan)); } None => { map.push(Some((keyval, data, NoLoan))); } } } /// Modifies a task-local value by temporarily removing it from task-local /// storage and then re-inserting if `Some` is returned from the closure. /// /// This function will have the same runtime errors as generated from `pop` and /// `set` (the key must not currently be on loan pub fn modify<T:'static>(key: Key<T>, f: |Option<T>| -> Option<T>) { match f(pop(key)) { Some(next) => { set(key, next); } None => {} } } #[cfg(test)] mod tests { use prelude::*; use super::*; use task; #[test] fn test_tls_multitask() { static my_key: Key<~str> = &Key; set(my_key, ~"parent data"); do task::spawn { // TLS shouldn't carry over.
assert!(get(my_key, |k| k.map(|k| (*k).clone())).is_none()); set(my_key, ~"child data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"child data"); // should be cleaned up for us } // Must work multiple times assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data"); } #[test] fn test_tls_overwrite() { static my_key: Key<~str> = &Key; set(my_key, ~"first data"); set(my_key, ~"next data"); // Shouldn't leak. assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"next data"); } #[test] fn test_tls_pop() { static my_key: Key<~str> = &Key; set(my_key, ~"weasel"); assert!(pop(my_key).unwrap() == ~"weasel"); // Pop must remove the data from the map. assert!(pop(my_key).is_none()); } #[test] fn test_tls_modify() { static my_key: Key<~str> = &Key; modify(my_key, |data| { match data { Some(ref val) => fail!("unwelcome value: {}", *val), None => Some(~"first data") } }); modify(my_key, |data| { match data { Some(~"first data") => Some(~"next data"), Some(ref val) => fail!("wrong value: {}", *val), None => fail!("missing value") } }); assert!(pop(my_key).unwrap() == ~"next data"); } #[test] fn test_tls_crust_automorestack_memorial_bug() { // This might result in a stack-canary clobber if the runtime fails to // set sp_limit to 0 when calling the cleanup extern - it might // automatically jump over to the rust stack, which causes next_c_sp // to get recorded as something within a rust stack segment. Then a // subsequent upcall (esp. for logging, think vsnprintf) would run on // a stack smaller than 1 MB. static my_key: Key<~str> = &Key; do task::spawn { set(my_key, ~"hax"); } } #[test] fn test_tls_multiple_types() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; do task::spawn { set(str_key, ~"string data"); set(box_key, @()); set(int_key, 42); } } #[test] #[allow(dead_code)] fn test_tls_overwrite_multiple_types() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; do task::spawn { set(str_key, ~"string data"); set(str_key, ~"string data 2"); set(box_key, @()); set(box_key, @()); set(int_key, 42); // This could cause a segfault if overwriting-destruction is done // with the crazy polymorphic transmute rather than the provided // finaliser. set(int_key, 31337); } } #[test] #[should_fail] fn test_tls_cleanup_on_failure() { static str_key: Key<~str> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; set(str_key, ~"parent data"); set(box_key, @()); do task::spawn { // spawn_linked set(str_key, ~"string data"); set(box_key, @()); set(int_key, 42); fail!(); } // Not quite nondeterministic. set(int_key, 31337); fail!(); } #[test] fn test_static_pointer() { static key: Key<&'static int> = &Key; static VALUE: int = 0; let v: &'static int = &VALUE; set(key, v); } #[test] fn test_owned() { static key: Key<~int> = &Key; set(key, ~1); get(key, |v| { get(key, |v| { get(key, |v| { assert_eq!(**v.unwrap(), 1); }); assert_eq!(**v.unwrap(), 1); }); assert_eq!(**v.unwrap(), 1); }); set(key, ~2); get(key, |v| { assert_eq!(**v.unwrap(), 2); }) } #[test] fn test_get_mut() { static key: Key<int> = &Key; set(key, 1); get_mut(key, |v| { *v.unwrap() = 2; }); get(key, |v| { assert_eq!(*v.unwrap(), 2); }) } #[test] fn test_same_key_type() { static key1: Key<int> = &Key; static key2: Key<int> = &Key; static key3: Key<int> = &Key; static key4: Key<int> = &Key; static key5: Key<int> = &Key; set(key1, 1); set(key2, 2); set(key3, 3); set(key4, 4); set(key5, 5); get(key1, |x| assert_eq!(*x.unwrap(), 1)); get(key2, |x| assert_eq!(*x.unwrap(), 2)); get(key3, |x| assert_eq!(*x.unwrap(), 3)); get(key4, |x| assert_eq!(*x.unwrap(), 4)); get(key5, |x| assert_eq!(*x.unwrap(), 5)); }
random_line_split
config.rs
/* * Copyright (c) 2017 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::collections::HashMap; use std::fs::{File, create_dir_all}; use std::io::{self, BufReader, Write}; use std::path::{Path, PathBuf}; use mg_settings::{Config, EnumFromStr, Parser, ParseResult}; use app::settings::DefaultConfig; use {Mode, file}; use super::{ Modes, ModesHash, COMMAND_MODE, COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, NORMAL_MODE, PASTE, PASTE_SELECTION, }; /// Create the default config directories and files. pub fn create_default_config(default_config: Vec<DefaultConfig>) -> Result<(), io::Error>
/// Create the config file with its default content if it does not exist. pub fn create_default_config_file(path: &Path, content: &'static str) -> Result<(), io::Error> { if!path.exists() { let mut file = File::create(path)?; write!(file, "{}", content)?; } Ok(()) } /// Parse a configuration file. pub fn parse_config<P: AsRef<Path>, COMM: EnumFromStr>(filename: P, user_modes: Modes, include_path: Option<PathBuf>) -> (Parser<COMM>, ParseResult<COMM>, ModesHash) { let mut parse_result = ParseResult::new(); let mut modes = HashMap::new(); for mode in user_modes { modes.insert(mode.prefix, mode.clone()); } assert!(modes.insert("n", Mode { name: NORMAL_MODE, prefix: "n", show_count: true }).is_none(), "Duplicate mode prefix n."); assert!(modes.insert("c", Mode { name: COMMAND_MODE, prefix: "c", show_count: false }).is_none(), "Duplicate mode prefix c."); let config = Config { application_commands: vec![COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, PASTE, PASTE_SELECTION], mapping_modes: modes.keys().cloned().collect(), }; let mut parser = Parser::new_with_config(config); if let Some(include_path) = include_path { parser.set_include_path(include_path); } let file = file::open(&filename); let file = rtry_no_return!(parse_result, file, { return (parser, parse_result, modes); }); let buf_reader = BufReader::new(file); let parse_result = parser.parse(buf_reader, None); (parser, parse_result, modes) }
{ for config_item in default_config { match config_item { DefaultConfig::Dir(directory) => create_dir_all(directory?)?, DefaultConfig::File(name, content) => create_default_config_file(&name?, content)?, } } Ok(()) }
identifier_body
config.rs
/* * Copyright (c) 2017 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::collections::HashMap; use std::fs::{File, create_dir_all}; use std::io::{self, BufReader, Write}; use std::path::{Path, PathBuf}; use mg_settings::{Config, EnumFromStr, Parser, ParseResult}; use app::settings::DefaultConfig; use {Mode, file}; use super::{ Modes, ModesHash, COMMAND_MODE, COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, NORMAL_MODE, PASTE, PASTE_SELECTION, }; /// Create the default config directories and files. pub fn create_default_config(default_config: Vec<DefaultConfig>) -> Result<(), io::Error> { for config_item in default_config { match config_item { DefaultConfig::Dir(directory) => create_dir_all(directory?)?, DefaultConfig::File(name, content) => create_default_config_file(&name?, content)?, } } Ok(()) } /// Create the config file with its default content if it does not exist. pub fn create_default_config_file(path: &Path, content: &'static str) -> Result<(), io::Error> { if!path.exists() { let mut file = File::create(path)?; write!(file, "{}", content)?; } Ok(()) } /// Parse a configuration file. pub fn
<P: AsRef<Path>, COMM: EnumFromStr>(filename: P, user_modes: Modes, include_path: Option<PathBuf>) -> (Parser<COMM>, ParseResult<COMM>, ModesHash) { let mut parse_result = ParseResult::new(); let mut modes = HashMap::new(); for mode in user_modes { modes.insert(mode.prefix, mode.clone()); } assert!(modes.insert("n", Mode { name: NORMAL_MODE, prefix: "n", show_count: true }).is_none(), "Duplicate mode prefix n."); assert!(modes.insert("c", Mode { name: COMMAND_MODE, prefix: "c", show_count: false }).is_none(), "Duplicate mode prefix c."); let config = Config { application_commands: vec![COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, PASTE, PASTE_SELECTION], mapping_modes: modes.keys().cloned().collect(), }; let mut parser = Parser::new_with_config(config); if let Some(include_path) = include_path { parser.set_include_path(include_path); } let file = file::open(&filename); let file = rtry_no_return!(parse_result, file, { return (parser, parse_result, modes); }); let buf_reader = BufReader::new(file); let parse_result = parser.parse(buf_reader, None); (parser, parse_result, modes) }
parse_config
identifier_name
config.rs
/* * Copyright (c) 2017 Boucher, Antoni <[email protected]> *
* this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::collections::HashMap; use std::fs::{File, create_dir_all}; use std::io::{self, BufReader, Write}; use std::path::{Path, PathBuf}; use mg_settings::{Config, EnumFromStr, Parser, ParseResult}; use app::settings::DefaultConfig; use {Mode, file}; use super::{ Modes, ModesHash, COMMAND_MODE, COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, NORMAL_MODE, PASTE, PASTE_SELECTION, }; /// Create the default config directories and files. pub fn create_default_config(default_config: Vec<DefaultConfig>) -> Result<(), io::Error> { for config_item in default_config { match config_item { DefaultConfig::Dir(directory) => create_dir_all(directory?)?, DefaultConfig::File(name, content) => create_default_config_file(&name?, content)?, } } Ok(()) } /// Create the config file with its default content if it does not exist. pub fn create_default_config_file(path: &Path, content: &'static str) -> Result<(), io::Error> { if!path.exists() { let mut file = File::create(path)?; write!(file, "{}", content)?; } Ok(()) } /// Parse a configuration file. pub fn parse_config<P: AsRef<Path>, COMM: EnumFromStr>(filename: P, user_modes: Modes, include_path: Option<PathBuf>) -> (Parser<COMM>, ParseResult<COMM>, ModesHash) { let mut parse_result = ParseResult::new(); let mut modes = HashMap::new(); for mode in user_modes { modes.insert(mode.prefix, mode.clone()); } assert!(modes.insert("n", Mode { name: NORMAL_MODE, prefix: "n", show_count: true }).is_none(), "Duplicate mode prefix n."); assert!(modes.insert("c", Mode { name: COMMAND_MODE, prefix: "c", show_count: false }).is_none(), "Duplicate mode prefix c."); let config = Config { application_commands: vec![COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, PASTE, PASTE_SELECTION], mapping_modes: modes.keys().cloned().collect(), }; let mut parser = Parser::new_with_config(config); if let Some(include_path) = include_path { parser.set_include_path(include_path); } let file = file::open(&filename); let file = rtry_no_return!(parse_result, file, { return (parser, parse_result, modes); }); let buf_reader = BufReader::new(file); let parse_result = parser.parse(buf_reader, None); (parser, parse_result, modes) }
* Permission is hereby granted, free of charge, to any person obtaining a copy of
random_line_split
config.rs
/* * Copyright (c) 2017 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::collections::HashMap; use std::fs::{File, create_dir_all}; use std::io::{self, BufReader, Write}; use std::path::{Path, PathBuf}; use mg_settings::{Config, EnumFromStr, Parser, ParseResult}; use app::settings::DefaultConfig; use {Mode, file}; use super::{ Modes, ModesHash, COMMAND_MODE, COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, NORMAL_MODE, PASTE, PASTE_SELECTION, }; /// Create the default config directories and files. pub fn create_default_config(default_config: Vec<DefaultConfig>) -> Result<(), io::Error> { for config_item in default_config { match config_item { DefaultConfig::Dir(directory) => create_dir_all(directory?)?, DefaultConfig::File(name, content) => create_default_config_file(&name?, content)?, } } Ok(()) } /// Create the config file with its default content if it does not exist. pub fn create_default_config_file(path: &Path, content: &'static str) -> Result<(), io::Error> { if!path.exists() { let mut file = File::create(path)?; write!(file, "{}", content)?; } Ok(()) } /// Parse a configuration file. pub fn parse_config<P: AsRef<Path>, COMM: EnumFromStr>(filename: P, user_modes: Modes, include_path: Option<PathBuf>) -> (Parser<COMM>, ParseResult<COMM>, ModesHash) { let mut parse_result = ParseResult::new(); let mut modes = HashMap::new(); for mode in user_modes { modes.insert(mode.prefix, mode.clone()); } assert!(modes.insert("n", Mode { name: NORMAL_MODE, prefix: "n", show_count: true }).is_none(), "Duplicate mode prefix n."); assert!(modes.insert("c", Mode { name: COMMAND_MODE, prefix: "c", show_count: false }).is_none(), "Duplicate mode prefix c."); let config = Config { application_commands: vec![COMPLETE_NEXT_COMMAND, COMPLETE_PREVIOUS_COMMAND, COPY, CUT, ENTRY_DELETE_NEXT_CHAR, ENTRY_DELETE_NEXT_WORD, ENTRY_DELETE_PREVIOUS_WORD, ENTRY_END, ENTRY_NEXT_CHAR, ENTRY_NEXT_WORD, ENTRY_PREVIOUS_CHAR, ENTRY_PREVIOUS_WORD, ENTRY_SMART_HOME, PASTE, PASTE_SELECTION], mapping_modes: modes.keys().cloned().collect(), }; let mut parser = Parser::new_with_config(config); if let Some(include_path) = include_path
let file = file::open(&filename); let file = rtry_no_return!(parse_result, file, { return (parser, parse_result, modes); }); let buf_reader = BufReader::new(file); let parse_result = parser.parse(buf_reader, None); (parser, parse_result, modes) }
{ parser.set_include_path(include_path); }
conditional_block
type-id-higher-rank-2.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we can't ignore lifetimes by going through Any. use std::any::Any; struct Foo<'a>(&'a str); fn good(s: &String) -> Foo { Foo(s) } fn bad1(s: String) -> Option<&'static str> { let a: Box<Any> = Box::new(good as fn(&String) -> Foo); a.downcast_ref::<fn(&String) -> Foo<'static>>().map(|f| f(&s).0) } trait AsStr<'a, 'b> { fn get(&'a self) -> &'b str; }
fn get(&'a self) -> &'a str { self } } fn bad2(s: String) -> Option<&'static str> { let a: Box<Any> = Box::new(Box::new(s) as Box<for<'a> AsStr<'a, 'a>>); a.downcast_ref::<Box<for<'a> AsStr<'a,'static>>>().map(|x| x.get()) } fn main() { assert_eq!(bad1(String::from("foo")), None); assert_eq!(bad2(String::from("bar")), None); }
impl<'a> AsStr<'a, 'a> for String {
random_line_split
type-id-higher-rank-2.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we can't ignore lifetimes by going through Any. use std::any::Any; struct Foo<'a>(&'a str); fn good(s: &String) -> Foo { Foo(s) } fn
(s: String) -> Option<&'static str> { let a: Box<Any> = Box::new(good as fn(&String) -> Foo); a.downcast_ref::<fn(&String) -> Foo<'static>>().map(|f| f(&s).0) } trait AsStr<'a, 'b> { fn get(&'a self) -> &'b str; } impl<'a> AsStr<'a, 'a> for String { fn get(&'a self) -> &'a str { self } } fn bad2(s: String) -> Option<&'static str> { let a: Box<Any> = Box::new(Box::new(s) as Box<for<'a> AsStr<'a, 'a>>); a.downcast_ref::<Box<for<'a> AsStr<'a,'static>>>().map(|x| x.get()) } fn main() { assert_eq!(bad1(String::from("foo")), None); assert_eq!(bad2(String::from("bar")), None); }
bad1
identifier_name
meg_csar_create.rs
extern crate megam_api; extern crate rand; extern crate rustc_serialize; extern crate term_painter; extern crate yaml_rust; extern crate toml; use std::path::Path; use util::parse_csar::CConfig; use self::term_painter::ToStyle; use self::term_painter::Color::*; use megam_api::api::Api; use self::megam_api::util::csars::Csar; use self::megam_api::util::errors::MegResponse; use util::header_hash as head;
#[derive(PartialEq, Clone, Debug)] pub struct CsarCoptions { pub file: String, } impl CsarCoptions { pub fn create(&self) { let file = from_utf8(self.file.as_bytes()).unwrap(); let path = Path::new(file).to_str().unwrap(); let we = CConfig; let data = we.load(path); let mut opts = Csar::new(); let api_call = head::api_call().unwrap(); opts.desc = data.unwrap_or("Error".to_string()); let out = opts.create(json::encode(&api_call).unwrap()); match out { Ok(v) => { let x = json::decode::<MegResponse>(&v).unwrap(); println!("{}", Green.paint("Successfully created your CSAR")); println!("----\n\nCode: {:?}\nMessage: {:?}\n\n----", x.code, x.msg); } Err(e) => { println!("{}", Red.bold().paint("Error: Not able to create CSAR.")); }}; } } impl CreateCSAR for CsarCoptions { fn new() -> CsarCoptions { CsarCoptions { file: "".to_string() } } } pub trait CreateCSAR { fn new() -> Self; }
use self::rustc_serialize::json; use std::str::from_utf8;
random_line_split
meg_csar_create.rs
extern crate megam_api; extern crate rand; extern crate rustc_serialize; extern crate term_painter; extern crate yaml_rust; extern crate toml; use std::path::Path; use util::parse_csar::CConfig; use self::term_painter::ToStyle; use self::term_painter::Color::*; use megam_api::api::Api; use self::megam_api::util::csars::Csar; use self::megam_api::util::errors::MegResponse; use util::header_hash as head; use self::rustc_serialize::json; use std::str::from_utf8; #[derive(PartialEq, Clone, Debug)] pub struct CsarCoptions { pub file: String, } impl CsarCoptions { pub fn create(&self) { let file = from_utf8(self.file.as_bytes()).unwrap(); let path = Path::new(file).to_str().unwrap(); let we = CConfig; let data = we.load(path); let mut opts = Csar::new(); let api_call = head::api_call().unwrap(); opts.desc = data.unwrap_or("Error".to_string()); let out = opts.create(json::encode(&api_call).unwrap()); match out { Ok(v) => { let x = json::decode::<MegResponse>(&v).unwrap(); println!("{}", Green.paint("Successfully created your CSAR")); println!("----\n\nCode: {:?}\nMessage: {:?}\n\n----", x.code, x.msg); } Err(e) => { println!("{}", Red.bold().paint("Error: Not able to create CSAR.")); }}; } } impl CreateCSAR for CsarCoptions { fn
() -> CsarCoptions { CsarCoptions { file: "".to_string() } } } pub trait CreateCSAR { fn new() -> Self; }
new
identifier_name
get_pushers.rs
//! `GET /_matrix/client/*/pushers` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3pushers use ruma_common::api::ruma_api; use serde::{Deserialize, Serialize}; use crate::push::{PusherData, PusherKind}; ruma_api! { metadata: { description: "Gets all currently active pushers for the authenticated user.", method: GET, name: "get_pushers", r0_path: "/_matrix/client/r0/pushers", stable_path: "/_matrix/client/v3/pushers", rate_limited: false, authentication: AccessToken, added: 1.0, } #[derive(Default)] request: {} response: { /// An array containing the current pushers for the user. pub pushers: Vec<Pusher>, } error: crate::Error } impl Request { /// Creates an empty `Request`. pub fn new() -> Self { Self {} }
} impl Response { /// Creates a new `Response` with the given pushers. pub fn new(pushers: Vec<Pusher>) -> Self { Self { pushers } } } /// Defines a pusher. /// /// To create an instance of this type, first create a `PusherInit` and convert it via /// `Pusher::from` / `.into()`. #[derive(Clone, Debug, Serialize, Deserialize)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct Pusher { /// A unique identifier for this pusher. /// /// The maximum allowed length is 512 bytes. pub pushkey: String, /// The kind of the pusher. pub kind: PusherKind, /// A reverse-DNS style identifier for the application. /// /// The maximum allowed length is 64 bytes. pub app_id: String, /// A string that will allow the user to identify what application owns this pusher. pub app_display_name: String, /// A string that will allow the user to identify what device owns this pusher. pub device_display_name: String, /// Determines which set of device specific rules this pusher executes. #[serde(skip_serializing_if = "Option::is_none")] pub profile_tag: Option<String>, /// The preferred language for receiving notifications (e.g. 'en' or 'en-US') pub lang: String, /// Information for the pusher implementation itself. pub data: PusherData, } /// Initial set of fields of `Pusher`. /// /// This struct will not be updated even if additional fields are added to `Pusher` in a new /// (non-breaking) release of the Matrix specification. #[derive(Debug)] #[allow(clippy::exhaustive_structs)] pub struct PusherInit { /// A unique identifier for this pusher. /// /// The maximum allowed length is 512 bytes. pub pushkey: String, /// The kind of the pusher. pub kind: PusherKind, /// A reverse-DNS style identifier for the application. /// /// The maximum allowed length is 64 bytes. pub app_id: String, /// A string that will allow the user to identify what application owns this pusher. pub app_display_name: String, /// A string that will allow the user to identify what device owns this pusher. pub device_display_name: String, /// Determines which set of device-specific rules this pusher executes. pub profile_tag: Option<String>, /// The preferred language for receiving notifications (e.g. 'en' or 'en-US'). pub lang: String, /// Information for the pusher implementation itself. pub data: PusherData, } impl From<PusherInit> for Pusher { fn from(init: PusherInit) -> Self { let PusherInit { pushkey, kind, app_id, app_display_name, device_display_name, profile_tag, lang, data, } = init; Self { pushkey, kind, app_id, app_display_name, device_display_name, profile_tag, lang, data, } } } }
random_line_split
get_pushers.rs
//! `GET /_matrix/client/*/pushers` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3pushers use ruma_common::api::ruma_api; use serde::{Deserialize, Serialize}; use crate::push::{PusherData, PusherKind}; ruma_api! { metadata: { description: "Gets all currently active pushers for the authenticated user.", method: GET, name: "get_pushers", r0_path: "/_matrix/client/r0/pushers", stable_path: "/_matrix/client/v3/pushers", rate_limited: false, authentication: AccessToken, added: 1.0, } #[derive(Default)] request: {} response: { /// An array containing the current pushers for the user. pub pushers: Vec<Pusher>, } error: crate::Error } impl Request { /// Creates an empty `Request`. pub fn new() -> Self { Self {} } } impl Response { /// Creates a new `Response` with the given pushers. pub fn new(pushers: Vec<Pusher>) -> Self { Self { pushers } } } /// Defines a pusher. /// /// To create an instance of this type, first create a `PusherInit` and convert it via /// `Pusher::from` / `.into()`. #[derive(Clone, Debug, Serialize, Deserialize)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct Pusher { /// A unique identifier for this pusher. /// /// The maximum allowed length is 512 bytes. pub pushkey: String, /// The kind of the pusher. pub kind: PusherKind, /// A reverse-DNS style identifier for the application. /// /// The maximum allowed length is 64 bytes. pub app_id: String, /// A string that will allow the user to identify what application owns this pusher. pub app_display_name: String, /// A string that will allow the user to identify what device owns this pusher. pub device_display_name: String, /// Determines which set of device specific rules this pusher executes. #[serde(skip_serializing_if = "Option::is_none")] pub profile_tag: Option<String>, /// The preferred language for receiving notifications (e.g. 'en' or 'en-US') pub lang: String, /// Information for the pusher implementation itself. pub data: PusherData, } /// Initial set of fields of `Pusher`. /// /// This struct will not be updated even if additional fields are added to `Pusher` in a new /// (non-breaking) release of the Matrix specification. #[derive(Debug)] #[allow(clippy::exhaustive_structs)] pub struct
{ /// A unique identifier for this pusher. /// /// The maximum allowed length is 512 bytes. pub pushkey: String, /// The kind of the pusher. pub kind: PusherKind, /// A reverse-DNS style identifier for the application. /// /// The maximum allowed length is 64 bytes. pub app_id: String, /// A string that will allow the user to identify what application owns this pusher. pub app_display_name: String, /// A string that will allow the user to identify what device owns this pusher. pub device_display_name: String, /// Determines which set of device-specific rules this pusher executes. pub profile_tag: Option<String>, /// The preferred language for receiving notifications (e.g. 'en' or 'en-US'). pub lang: String, /// Information for the pusher implementation itself. pub data: PusherData, } impl From<PusherInit> for Pusher { fn from(init: PusherInit) -> Self { let PusherInit { pushkey, kind, app_id, app_display_name, device_display_name, profile_tag, lang, data, } = init; Self { pushkey, kind, app_id, app_display_name, device_display_name, profile_tag, lang, data, } } } }
PusherInit
identifier_name
xmlhttprequesteventtarget.rs
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::XMLHttpRequestEventTargetBinding::XMLHttpRequestEventTargetMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::XMLHttpRequestEventTargetDerived; use dom::bindings::js::JSRef; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; #[deriving(Copy, PartialEq)] #[jstraceable] pub enum XMLHttpRequestEventTargetTypeId { XMLHttpRequest, XMLHttpRequestUpload, } #[dom_struct] pub struct XMLHttpRequestEventTarget { eventtarget: EventTarget, } impl XMLHttpRequestEventTarget { pub fn new_inherited(type_id: XMLHttpRequestEventTargetTypeId) -> XMLHttpRequestEventTarget { XMLHttpRequestEventTarget { eventtarget: EventTarget::new_inherited(EventTargetTypeId::XMLHttpRequestEventTarget(type_id)) } } #[inline] pub fn eventtarget<'a>(&'a self) -> &'a EventTarget { &self.eventtarget } } impl XMLHttpRequestEventTargetDerived for EventTarget { fn is_xmlhttprequesteventtarget(&self) -> bool { match *self.type_id() { EventTargetTypeId::XMLHttpRequestEventTarget(_) => true, _ => false } } } impl<'a> XMLHttpRequestEventTargetMethods for JSRef<'a, XMLHttpRequestEventTarget> { event_handler!(loadstart,GetOnloadstart, SetOnloadstart) event_handler!(progress, GetOnprogress, SetOnprogress) event_handler!(abort, GetOnabort, SetOnabort) event_handler!(error, GetOnerror, SetOnerror) event_handler!(load, GetOnload, SetOnload) event_handler!(timeout, GetOntimeout, SetOntimeout) event_handler!(loadend, GetOnloadend, SetOnloadend) }
/* 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/. */
random_line_split
xmlhttprequesteventtarget.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::XMLHttpRequestEventTargetBinding::XMLHttpRequestEventTargetMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::XMLHttpRequestEventTargetDerived; use dom::bindings::js::JSRef; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; #[deriving(Copy, PartialEq)] #[jstraceable] pub enum XMLHttpRequestEventTargetTypeId { XMLHttpRequest, XMLHttpRequestUpload, } #[dom_struct] pub struct XMLHttpRequestEventTarget { eventtarget: EventTarget, } impl XMLHttpRequestEventTarget { pub fn
(type_id: XMLHttpRequestEventTargetTypeId) -> XMLHttpRequestEventTarget { XMLHttpRequestEventTarget { eventtarget: EventTarget::new_inherited(EventTargetTypeId::XMLHttpRequestEventTarget(type_id)) } } #[inline] pub fn eventtarget<'a>(&'a self) -> &'a EventTarget { &self.eventtarget } } impl XMLHttpRequestEventTargetDerived for EventTarget { fn is_xmlhttprequesteventtarget(&self) -> bool { match *self.type_id() { EventTargetTypeId::XMLHttpRequestEventTarget(_) => true, _ => false } } } impl<'a> XMLHttpRequestEventTargetMethods for JSRef<'a, XMLHttpRequestEventTarget> { event_handler!(loadstart,GetOnloadstart, SetOnloadstart) event_handler!(progress, GetOnprogress, SetOnprogress) event_handler!(abort, GetOnabort, SetOnabort) event_handler!(error, GetOnerror, SetOnerror) event_handler!(load, GetOnload, SetOnload) event_handler!(timeout, GetOntimeout, SetOntimeout) event_handler!(loadend, GetOnloadend, SetOnloadend) }
new_inherited
identifier_name
xmlhttprequesteventtarget.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::XMLHttpRequestEventTargetBinding::XMLHttpRequestEventTargetMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::XMLHttpRequestEventTargetDerived; use dom::bindings::js::JSRef; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; #[deriving(Copy, PartialEq)] #[jstraceable] pub enum XMLHttpRequestEventTargetTypeId { XMLHttpRequest, XMLHttpRequestUpload, } #[dom_struct] pub struct XMLHttpRequestEventTarget { eventtarget: EventTarget, } impl XMLHttpRequestEventTarget { pub fn new_inherited(type_id: XMLHttpRequestEventTargetTypeId) -> XMLHttpRequestEventTarget { XMLHttpRequestEventTarget { eventtarget: EventTarget::new_inherited(EventTargetTypeId::XMLHttpRequestEventTarget(type_id)) } } #[inline] pub fn eventtarget<'a>(&'a self) -> &'a EventTarget
} impl XMLHttpRequestEventTargetDerived for EventTarget { fn is_xmlhttprequesteventtarget(&self) -> bool { match *self.type_id() { EventTargetTypeId::XMLHttpRequestEventTarget(_) => true, _ => false } } } impl<'a> XMLHttpRequestEventTargetMethods for JSRef<'a, XMLHttpRequestEventTarget> { event_handler!(loadstart,GetOnloadstart, SetOnloadstart) event_handler!(progress, GetOnprogress, SetOnprogress) event_handler!(abort, GetOnabort, SetOnabort) event_handler!(error, GetOnerror, SetOnerror) event_handler!(load, GetOnload, SetOnload) event_handler!(timeout, GetOntimeout, SetOntimeout) event_handler!(loadend, GetOnloadend, SetOnloadend) }
{ &self.eventtarget }
identifier_body
color.rs
//! A color type, with utility methods for modifying colors and parsing colors from hex integers and strings. use std::str::FromStr; use gl; use gl::types::*; use shader::{UniformValue, UniformKind}; use buffer::VertexData; /// A color with red, green, blue and alpha components. All components are expected to be /// between 0 and 1, both inclusinve. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Color { pub r: f32, pub g: f32, pub b: f32, pub a: f32, } impl Color { /// Creates a new, completly opaque (alpha = 1), color. /// /// All parameters are clamped so that they are between 0 and 1, both inclusive. pub fn rgb(r: f32, g: f32, b: f32) -> Color { Color { r: clamp(r, 0.0, 1.0), g: clamp(g, 0.0, 1.0), b: clamp(b, 0.0, 1.0), a: 1.0 } } /// Creates a new color. /// /// All parameters are clamped so that they are between 0 and 1, both inclusive. pub fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color { Color { r: clamp(r, 0.0, 1.0), g: clamp(g, 0.0, 1.0), b: clamp(b, 0.0, 1.0), a: clamp(a, 0.0, 1.0) } } /// Creates a new color, converting the given values to rgb. The returned color will be /// completly opaque. `saturation` and `lightness` given values are clamped to be between /// 0 and 1, both inclusive. pub fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color { let saturation = clamp(saturation, 0.0, 1.0); let lightness = clamp(lightness, 0.0, 1.0); let hue = hue % 1.0; if saturation <= 0.0 { return Color { r: lightness, g: lightness, b: lightness, a: 1.0 }; } let q = if lightness < 0.5 { lightness * (1.0 + saturation) } else { lightness + saturation - lightness*saturation }; let p = 2.0*lightness - q; let hue_to_rgb = |hue| { let hue = hue % 1.0; if hue < 1.0/6.0 { return p + (q - p)*6.0*hue } if hue < 1.0/2.0 { return q } if hue < 2.0/3.0 { return p + (q - p)*(2.0/3.0 - hue)*6.0 } return p; }; Color { r: hue_to_rgb(hue + 1.0/3.0), g: hue_to_rgb(hue), b: hue_to_rgb(hue - 1.0/3.0), a: 1.0, } } /// Creates a color from a hex string. The string should be of the format "#rrggbb" or /// "rrggbb", where each of r, g and b is a hexadecimal digit. Note that this currently does /// not support loading colors with a alpha channel. All colors created will be completly /// opaque. pub fn hex_str(string: &str) -> Option<Color> { let value = { if string.len() == 6 { u32::from_str_radix(string, 16) } else if string.len() == 7 { u32::from_str_radix(&string[1..], 16) } else { return None } }; match value { Ok(value) => Some(Color::hex_int(value)), Err(_) => None, } } /// Creates a color from a hex int. Bit `0..8` (The eight least significant bits) are the /// red channel. Bit `8..16` are the green channel. Bit `16..24` are the blue channel. Note /// that this function currently ignores the alpha channel. /// /// # Example /// ```rust /// # use gondola::Color; /// let color = Color::hex_int(0xff00ff); /// /// assert_eq!(color, Color::rgb(1.0, 0.0, 1.0)); /// ``` pub fn hex_int(value: u32) -> Color { let r = value >> 16 & 0xff; let g = value >> 8 & 0xff; let b = value & 0xff; let r = r as f32 / 255.0; let g = g as f32 / 255.0; let b = b as f32 / 255.0; Color { r: r, g: g, b: b, a: 1.0 } } /// Same as [`hex_int`], but allows specifying the alpha channel. `alpha` should be between 0 /// and 1, both inclusive. /// /// [`hex_int`]: struct.Color.html#method.hex_int pub fn hex_int_alpha(value: u32, alpha: f32) -> Color { let r = value >> 16 & 0xff; let g = value >> 8 & 0xff; let b = value & 0xff; let r = r as f32 / 255.0; let g = g as f32 / 255.0; let b = b as f32 / 255.0; Color { r: r, g: g, b: b, a: alpha } } /// Converts this color to a hex string like "#ffa13b". Note that this function currently /// ignores the alpha channel. pub fn to_hex(&self) -> String { let r = (self.r * 255.0) as u32; let g = (self.g * 255.0) as u32; let b = (self.b * 255.0) as u32; let value = r << 16 | g << 8 | b; format!("#{:06x}", value) } /// Creates a new color based on this color, with the red, green and blue components multiplied /// by the given factor. pub fn with_lightness(&self, factor: f32) -> Color { Color { r: clamp(self.r*factor, 0.0, 1.0), g: clamp(self.g*factor, 0.0, 1.0), b: clamp(self.b*factor, 0.0, 1.0), a: self.a } } /// Linearly interpolates between this color and the given other color. `t` should be between /// 0 and 1. Values outside of this range will lead to extrapolation. pub fn lerp(self, other: Color, t: f32) -> Color { Color { r: self.r*(1.0 - t) + other.r*t, g: self.g*(1.0 - t) + other.g*t, b: self.b*(1.0 - t) + other.b*t, a: self.a*(1.0 - t) + other.a*t, } } } // Does not properly handle NaN, which should not really matter fn clamp(value: f32, min: f32, max: f32) -> f32 { if value < min { return min; } if value > max { return max; } value } impl VertexData for Color { type Primitive = f32; fn primitives() -> usize { 4 } } impl UniformValue for Color { const KIND: UniformKind = UniformKind::VEC4_F32; unsafe fn set_uniform(color: &Color, location: GLint) { gl::Uniform4f(location, color.r, color.g, color.b, color.a); } unsafe fn set_uniform_slice(colors: &[Color], location: GLint) { gl::Uniform4fv(location, colors.len() as GLsizei, colors.as_ptr() as *const GLfloat); } } impl From<u32> for Color { fn from(v: u32) -> Color { Color::hex_int(v) } } impl FromStr for Color { type Err = (); // User can probably see why his color failed to parse on inspection fn from_str(s: &str) -> Result<Color, ()> { match Color::hex_str(s) { Some(c) => Ok(c), None => Err(()), } } } // Custom serialization #[cfg(feature = "serialize")] mod serialize { use super::*; use std::fmt; use serde::{Serialize, Deserialize, Serializer, Deserializer}; use serde::de::{Visitor, Error}; impl Serialize for Color { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&self.to_hex()) } } impl<'de> Deserialize<'de> for Color { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { d.deserialize_str(ColorVisitor) } } struct
; impl<'de> Visitor<'de> for ColorVisitor { type Value = Color; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("A string representing a valid hex color") } fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> { match Color::hex_str(v) { Some(color) => Ok(color), None => Err(E::custom(format!("\"{}\" is not a valid color string", v))), } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_to_hex() { assert_eq!("#ffa3b1", Color::hex("#ffa3b1").unwrap().to_hex()); assert_eq!("#a300f1", Color::hex("#a300f1").unwrap().to_hex()); assert_eq!("#000000", Color::hex("#000000").unwrap().to_hex()); assert_eq!("#000001", Color::hex("#000001").unwrap().to_hex()); assert_eq!("#100000", Color::hex("#100000").unwrap().to_hex()); } }
ColorVisitor
identifier_name
color.rs
//! A color type, with utility methods for modifying colors and parsing colors from hex integers and strings. use std::str::FromStr; use gl; use gl::types::*; use shader::{UniformValue, UniformKind}; use buffer::VertexData; /// A color with red, green, blue and alpha components. All components are expected to be /// between 0 and 1, both inclusinve. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Color { pub r: f32, pub g: f32, pub b: f32, pub a: f32, } impl Color { /// Creates a new, completly opaque (alpha = 1), color. /// /// All parameters are clamped so that they are between 0 and 1, both inclusive. pub fn rgb(r: f32, g: f32, b: f32) -> Color { Color { r: clamp(r, 0.0, 1.0), g: clamp(g, 0.0, 1.0), b: clamp(b, 0.0, 1.0), a: 1.0 } } /// Creates a new color. /// /// All parameters are clamped so that they are between 0 and 1, both inclusive. pub fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color { Color { r: clamp(r, 0.0, 1.0), g: clamp(g, 0.0, 1.0), b: clamp(b, 0.0, 1.0), a: clamp(a, 0.0, 1.0) } } /// Creates a new color, converting the given values to rgb. The returned color will be /// completly opaque. `saturation` and `lightness` given values are clamped to be between /// 0 and 1, both inclusive. pub fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color { let saturation = clamp(saturation, 0.0, 1.0); let lightness = clamp(lightness, 0.0, 1.0); let hue = hue % 1.0; if saturation <= 0.0 { return Color { r: lightness, g: lightness, b: lightness, a: 1.0 }; } let q = if lightness < 0.5 { lightness * (1.0 + saturation) } else { lightness + saturation - lightness*saturation }; let p = 2.0*lightness - q; let hue_to_rgb = |hue| { let hue = hue % 1.0; if hue < 1.0/6.0 { return p + (q - p)*6.0*hue } if hue < 1.0/2.0 { return q } if hue < 2.0/3.0 { return p + (q - p)*(2.0/3.0 - hue)*6.0 } return p; }; Color { r: hue_to_rgb(hue + 1.0/3.0), g: hue_to_rgb(hue), b: hue_to_rgb(hue - 1.0/3.0), a: 1.0, } } /// Creates a color from a hex string. The string should be of the format "#rrggbb" or /// "rrggbb", where each of r, g and b is a hexadecimal digit. Note that this currently does /// not support loading colors with a alpha channel. All colors created will be completly /// opaque. pub fn hex_str(string: &str) -> Option<Color> { let value = { if string.len() == 6 { u32::from_str_radix(string, 16) } else if string.len() == 7 { u32::from_str_radix(&string[1..], 16) } else { return None } }; match value { Ok(value) => Some(Color::hex_int(value)), Err(_) => None, } } /// Creates a color from a hex int. Bit `0..8` (The eight least significant bits) are the /// red channel. Bit `8..16` are the green channel. Bit `16..24` are the blue channel. Note /// that this function currently ignores the alpha channel. /// /// # Example /// ```rust /// # use gondola::Color; /// let color = Color::hex_int(0xff00ff); /// /// assert_eq!(color, Color::rgb(1.0, 0.0, 1.0)); /// ``` pub fn hex_int(value: u32) -> Color { let r = value >> 16 & 0xff; let g = value >> 8 & 0xff; let b = value & 0xff; let r = r as f32 / 255.0; let g = g as f32 / 255.0; let b = b as f32 / 255.0; Color { r: r, g: g, b: b, a: 1.0 } } /// Same as [`hex_int`], but allows specifying the alpha channel. `alpha` should be between 0 /// and 1, both inclusive. /// /// [`hex_int`]: struct.Color.html#method.hex_int pub fn hex_int_alpha(value: u32, alpha: f32) -> Color { let r = value >> 16 & 0xff; let g = value >> 8 & 0xff; let b = value & 0xff; let r = r as f32 / 255.0; let g = g as f32 / 255.0; let b = b as f32 / 255.0; Color { r: r, g: g, b: b, a: alpha } } /// Converts this color to a hex string like "#ffa13b". Note that this function currently /// ignores the alpha channel. pub fn to_hex(&self) -> String { let r = (self.r * 255.0) as u32; let g = (self.g * 255.0) as u32; let b = (self.b * 255.0) as u32; let value = r << 16 | g << 8 | b; format!("#{:06x}", value) } /// Creates a new color based on this color, with the red, green and blue components multiplied /// by the given factor. pub fn with_lightness(&self, factor: f32) -> Color { Color { r: clamp(self.r*factor, 0.0, 1.0), g: clamp(self.g*factor, 0.0, 1.0), b: clamp(self.b*factor, 0.0, 1.0), a: self.a } } /// Linearly interpolates between this color and the given other color. `t` should be between /// 0 and 1. Values outside of this range will lead to extrapolation. pub fn lerp(self, other: Color, t: f32) -> Color { Color { r: self.r*(1.0 - t) + other.r*t, g: self.g*(1.0 - t) + other.g*t, b: self.b*(1.0 - t) + other.b*t, a: self.a*(1.0 - t) + other.a*t, } } } // Does not properly handle NaN, which should not really matter fn clamp(value: f32, min: f32, max: f32) -> f32 { if value < min { return min; } if value > max { return max; } value } impl VertexData for Color { type Primitive = f32; fn primitives() -> usize { 4 } } impl UniformValue for Color { const KIND: UniformKind = UniformKind::VEC4_F32; unsafe fn set_uniform(color: &Color, location: GLint) { gl::Uniform4f(location, color.r, color.g, color.b, color.a); } unsafe fn set_uniform_slice(colors: &[Color], location: GLint) { gl::Uniform4fv(location, colors.len() as GLsizei, colors.as_ptr() as *const GLfloat); } } impl From<u32> for Color { fn from(v: u32) -> Color { Color::hex_int(v) } } impl FromStr for Color { type Err = (); // User can probably see why his color failed to parse on inspection fn from_str(s: &str) -> Result<Color, ()> { match Color::hex_str(s) { Some(c) => Ok(c),
} } } // Custom serialization #[cfg(feature = "serialize")] mod serialize { use super::*; use std::fmt; use serde::{Serialize, Deserialize, Serializer, Deserializer}; use serde::de::{Visitor, Error}; impl Serialize for Color { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&self.to_hex()) } } impl<'de> Deserialize<'de> for Color { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { d.deserialize_str(ColorVisitor) } } struct ColorVisitor; impl<'de> Visitor<'de> for ColorVisitor { type Value = Color; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("A string representing a valid hex color") } fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> { match Color::hex_str(v) { Some(color) => Ok(color), None => Err(E::custom(format!("\"{}\" is not a valid color string", v))), } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_to_hex() { assert_eq!("#ffa3b1", Color::hex("#ffa3b1").unwrap().to_hex()); assert_eq!("#a300f1", Color::hex("#a300f1").unwrap().to_hex()); assert_eq!("#000000", Color::hex("#000000").unwrap().to_hex()); assert_eq!("#000001", Color::hex("#000001").unwrap().to_hex()); assert_eq!("#100000", Color::hex("#100000").unwrap().to_hex()); } }
None => Err(()),
random_line_split
color.rs
//! A color type, with utility methods for modifying colors and parsing colors from hex integers and strings. use std::str::FromStr; use gl; use gl::types::*; use shader::{UniformValue, UniformKind}; use buffer::VertexData; /// A color with red, green, blue and alpha components. All components are expected to be /// between 0 and 1, both inclusinve. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Color { pub r: f32, pub g: f32, pub b: f32, pub a: f32, } impl Color { /// Creates a new, completly opaque (alpha = 1), color. /// /// All parameters are clamped so that they are between 0 and 1, both inclusive. pub fn rgb(r: f32, g: f32, b: f32) -> Color { Color { r: clamp(r, 0.0, 1.0), g: clamp(g, 0.0, 1.0), b: clamp(b, 0.0, 1.0), a: 1.0 } } /// Creates a new color. /// /// All parameters are clamped so that they are between 0 and 1, both inclusive. pub fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color { Color { r: clamp(r, 0.0, 1.0), g: clamp(g, 0.0, 1.0), b: clamp(b, 0.0, 1.0), a: clamp(a, 0.0, 1.0) } } /// Creates a new color, converting the given values to rgb. The returned color will be /// completly opaque. `saturation` and `lightness` given values are clamped to be between /// 0 and 1, both inclusive. pub fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color { let saturation = clamp(saturation, 0.0, 1.0); let lightness = clamp(lightness, 0.0, 1.0); let hue = hue % 1.0; if saturation <= 0.0 { return Color { r: lightness, g: lightness, b: lightness, a: 1.0 }; } let q = if lightness < 0.5 { lightness * (1.0 + saturation) } else { lightness + saturation - lightness*saturation }; let p = 2.0*lightness - q; let hue_to_rgb = |hue| { let hue = hue % 1.0; if hue < 1.0/6.0 { return p + (q - p)*6.0*hue } if hue < 1.0/2.0 { return q } if hue < 2.0/3.0 { return p + (q - p)*(2.0/3.0 - hue)*6.0 } return p; }; Color { r: hue_to_rgb(hue + 1.0/3.0), g: hue_to_rgb(hue), b: hue_to_rgb(hue - 1.0/3.0), a: 1.0, } } /// Creates a color from a hex string. The string should be of the format "#rrggbb" or /// "rrggbb", where each of r, g and b is a hexadecimal digit. Note that this currently does /// not support loading colors with a alpha channel. All colors created will be completly /// opaque. pub fn hex_str(string: &str) -> Option<Color> { let value = { if string.len() == 6 { u32::from_str_radix(string, 16) } else if string.len() == 7 { u32::from_str_radix(&string[1..], 16) } else { return None } }; match value { Ok(value) => Some(Color::hex_int(value)), Err(_) => None, } } /// Creates a color from a hex int. Bit `0..8` (The eight least significant bits) are the /// red channel. Bit `8..16` are the green channel. Bit `16..24` are the blue channel. Note /// that this function currently ignores the alpha channel. /// /// # Example /// ```rust /// # use gondola::Color; /// let color = Color::hex_int(0xff00ff); /// /// assert_eq!(color, Color::rgb(1.0, 0.0, 1.0)); /// ``` pub fn hex_int(value: u32) -> Color { let r = value >> 16 & 0xff; let g = value >> 8 & 0xff; let b = value & 0xff; let r = r as f32 / 255.0; let g = g as f32 / 255.0; let b = b as f32 / 255.0; Color { r: r, g: g, b: b, a: 1.0 } } /// Same as [`hex_int`], but allows specifying the alpha channel. `alpha` should be between 0 /// and 1, both inclusive. /// /// [`hex_int`]: struct.Color.html#method.hex_int pub fn hex_int_alpha(value: u32, alpha: f32) -> Color { let r = value >> 16 & 0xff; let g = value >> 8 & 0xff; let b = value & 0xff; let r = r as f32 / 255.0; let g = g as f32 / 255.0; let b = b as f32 / 255.0; Color { r: r, g: g, b: b, a: alpha } } /// Converts this color to a hex string like "#ffa13b". Note that this function currently /// ignores the alpha channel. pub fn to_hex(&self) -> String { let r = (self.r * 255.0) as u32; let g = (self.g * 255.0) as u32; let b = (self.b * 255.0) as u32; let value = r << 16 | g << 8 | b; format!("#{:06x}", value) } /// Creates a new color based on this color, with the red, green and blue components multiplied /// by the given factor. pub fn with_lightness(&self, factor: f32) -> Color { Color { r: clamp(self.r*factor, 0.0, 1.0), g: clamp(self.g*factor, 0.0, 1.0), b: clamp(self.b*factor, 0.0, 1.0), a: self.a } } /// Linearly interpolates between this color and the given other color. `t` should be between /// 0 and 1. Values outside of this range will lead to extrapolation. pub fn lerp(self, other: Color, t: f32) -> Color { Color { r: self.r*(1.0 - t) + other.r*t, g: self.g*(1.0 - t) + other.g*t, b: self.b*(1.0 - t) + other.b*t, a: self.a*(1.0 - t) + other.a*t, } } } // Does not properly handle NaN, which should not really matter fn clamp(value: f32, min: f32, max: f32) -> f32
impl VertexData for Color { type Primitive = f32; fn primitives() -> usize { 4 } } impl UniformValue for Color { const KIND: UniformKind = UniformKind::VEC4_F32; unsafe fn set_uniform(color: &Color, location: GLint) { gl::Uniform4f(location, color.r, color.g, color.b, color.a); } unsafe fn set_uniform_slice(colors: &[Color], location: GLint) { gl::Uniform4fv(location, colors.len() as GLsizei, colors.as_ptr() as *const GLfloat); } } impl From<u32> for Color { fn from(v: u32) -> Color { Color::hex_int(v) } } impl FromStr for Color { type Err = (); // User can probably see why his color failed to parse on inspection fn from_str(s: &str) -> Result<Color, ()> { match Color::hex_str(s) { Some(c) => Ok(c), None => Err(()), } } } // Custom serialization #[cfg(feature = "serialize")] mod serialize { use super::*; use std::fmt; use serde::{Serialize, Deserialize, Serializer, Deserializer}; use serde::de::{Visitor, Error}; impl Serialize for Color { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&self.to_hex()) } } impl<'de> Deserialize<'de> for Color { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { d.deserialize_str(ColorVisitor) } } struct ColorVisitor; impl<'de> Visitor<'de> for ColorVisitor { type Value = Color; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("A string representing a valid hex color") } fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> { match Color::hex_str(v) { Some(color) => Ok(color), None => Err(E::custom(format!("\"{}\" is not a valid color string", v))), } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_to_hex() { assert_eq!("#ffa3b1", Color::hex("#ffa3b1").unwrap().to_hex()); assert_eq!("#a300f1", Color::hex("#a300f1").unwrap().to_hex()); assert_eq!("#000000", Color::hex("#000000").unwrap().to_hex()); assert_eq!("#000001", Color::hex("#000001").unwrap().to_hex()); assert_eq!("#100000", Color::hex("#100000").unwrap().to_hex()); } }
{ if value < min { return min; } if value > max { return max; } value }
identifier_body
inheritance_integrity.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 rustc::lint::{LateContext, LintPass, LintArray, Level, LateLintPass, LintContext}; use rustc::middle::def; use rustc_front::hir; use syntax::ast; use utils::match_lang_ty; declare_lint!(INHERITANCE_INTEGRITY, Deny, "Ensures that struct fields are properly laid out for inheritance to work"); /// Lint for ensuring proper layout of DOM structs /// /// A DOM struct must have one Reflector field or one field /// which itself is a DOM struct (in which case it must be the first field). pub struct InheritancePass; impl LintPass for InheritancePass { fn get_lints(&self) -> LintArray { lint_array!(INHERITANCE_INTEGRITY) } } impl LateLintPass for InheritancePass { fn check_struct_def(&mut self, cx: &LateContext, def: &hir::VariantData, _n: ast::Name, _gen: &hir::Generics, id: ast::NodeId) { // Lints are run post expansion, so it's fine to use // #[_dom_struct_marker] here without also checking for #[dom_struct] if cx.tcx.has_attr(cx.tcx.map.local_def_id(id), "_dom_struct_marker") { // Find the reflector, if any let reflector_span = def.fields().iter().enumerate() .find(|&(ctr, f)| { if match_lang_ty(cx, &*f.node.ty, "reflector") { if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "The Reflector should be the first field of the DOM \ struct"); } return true; } false }) .map(|(_, f)| f.span); // Find all #[dom_struct] fields let dom_spans: Vec<_> = def.fields().iter().enumerate().filter_map(|(ctr, f)| { if let hir::TyPath(..) = f.node.ty.node { if let Some(&def::PathResolution { base_def: def,.. }) = cx.tcx.def_map.borrow().get(&f.node.ty.id) { if let def::Def::PrimTy(_) = def { return None; } if cx.tcx.has_attr(def.def_id(), "_dom_struct_marker") { // If the field is not the first, it's probably // being misused (a) if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "Bare DOM structs should only be used as the first field of a \ DOM struct. Consider using JS<T> instead."); } return Some(f.span) } } } None }).collect(); // We should not have both a reflector and a dom struct field if let Some(sp) = reflector_span { if dom_spans.len() > 0 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has both Reflector \ and bare DOM struct members"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { db.span_note(sp, "Reflector found here"); for span in &dom_spans { db.span_note(*span, "Bare DOM struct found here"); } } } // Nor should we have more than one dom struct field } else if dom_spans.len() > 1 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has multiple \ DOM struct members, only one is allowed"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { for span in &dom_spans {
} else if dom_spans.is_empty() { cx.span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has no reflector or parent DOM struct"); } } } }
db.span_note(*span, "Bare DOM struct found here"); } }
random_line_split
inheritance_integrity.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 rustc::lint::{LateContext, LintPass, LintArray, Level, LateLintPass, LintContext}; use rustc::middle::def; use rustc_front::hir; use syntax::ast; use utils::match_lang_ty; declare_lint!(INHERITANCE_INTEGRITY, Deny, "Ensures that struct fields are properly laid out for inheritance to work"); /// Lint for ensuring proper layout of DOM structs /// /// A DOM struct must have one Reflector field or one field /// which itself is a DOM struct (in which case it must be the first field). pub struct InheritancePass; impl LintPass for InheritancePass { fn get_lints(&self) -> LintArray { lint_array!(INHERITANCE_INTEGRITY) } } impl LateLintPass for InheritancePass { fn check_struct_def(&mut self, cx: &LateContext, def: &hir::VariantData, _n: ast::Name, _gen: &hir::Generics, id: ast::NodeId) { // Lints are run post expansion, so it's fine to use // #[_dom_struct_marker] here without also checking for #[dom_struct] if cx.tcx.has_attr(cx.tcx.map.local_def_id(id), "_dom_struct_marker") { // Find the reflector, if any let reflector_span = def.fields().iter().enumerate() .find(|&(ctr, f)| { if match_lang_ty(cx, &*f.node.ty, "reflector") { if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "The Reflector should be the first field of the DOM \ struct"); } return true; } false }) .map(|(_, f)| f.span); // Find all #[dom_struct] fields let dom_spans: Vec<_> = def.fields().iter().enumerate().filter_map(|(ctr, f)| { if let hir::TyPath(..) = f.node.ty.node { if let Some(&def::PathResolution { base_def: def,.. }) = cx.tcx.def_map.borrow().get(&f.node.ty.id) { if let def::Def::PrimTy(_) = def
if cx.tcx.has_attr(def.def_id(), "_dom_struct_marker") { // If the field is not the first, it's probably // being misused (a) if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "Bare DOM structs should only be used as the first field of a \ DOM struct. Consider using JS<T> instead."); } return Some(f.span) } } } None }).collect(); // We should not have both a reflector and a dom struct field if let Some(sp) = reflector_span { if dom_spans.len() > 0 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has both Reflector \ and bare DOM struct members"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { db.span_note(sp, "Reflector found here"); for span in &dom_spans { db.span_note(*span, "Bare DOM struct found here"); } } } // Nor should we have more than one dom struct field } else if dom_spans.len() > 1 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has multiple \ DOM struct members, only one is allowed"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { for span in &dom_spans { db.span_note(*span, "Bare DOM struct found here"); } } } else if dom_spans.is_empty() { cx.span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has no reflector or parent DOM struct"); } } } }
{ return None; }
conditional_block
inheritance_integrity.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 rustc::lint::{LateContext, LintPass, LintArray, Level, LateLintPass, LintContext}; use rustc::middle::def; use rustc_front::hir; use syntax::ast; use utils::match_lang_ty; declare_lint!(INHERITANCE_INTEGRITY, Deny, "Ensures that struct fields are properly laid out for inheritance to work"); /// Lint for ensuring proper layout of DOM structs /// /// A DOM struct must have one Reflector field or one field /// which itself is a DOM struct (in which case it must be the first field). pub struct InheritancePass; impl LintPass for InheritancePass { fn get_lints(&self) -> LintArray
} impl LateLintPass for InheritancePass { fn check_struct_def(&mut self, cx: &LateContext, def: &hir::VariantData, _n: ast::Name, _gen: &hir::Generics, id: ast::NodeId) { // Lints are run post expansion, so it's fine to use // #[_dom_struct_marker] here without also checking for #[dom_struct] if cx.tcx.has_attr(cx.tcx.map.local_def_id(id), "_dom_struct_marker") { // Find the reflector, if any let reflector_span = def.fields().iter().enumerate() .find(|&(ctr, f)| { if match_lang_ty(cx, &*f.node.ty, "reflector") { if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "The Reflector should be the first field of the DOM \ struct"); } return true; } false }) .map(|(_, f)| f.span); // Find all #[dom_struct] fields let dom_spans: Vec<_> = def.fields().iter().enumerate().filter_map(|(ctr, f)| { if let hir::TyPath(..) = f.node.ty.node { if let Some(&def::PathResolution { base_def: def,.. }) = cx.tcx.def_map.borrow().get(&f.node.ty.id) { if let def::Def::PrimTy(_) = def { return None; } if cx.tcx.has_attr(def.def_id(), "_dom_struct_marker") { // If the field is not the first, it's probably // being misused (a) if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "Bare DOM structs should only be used as the first field of a \ DOM struct. Consider using JS<T> instead."); } return Some(f.span) } } } None }).collect(); // We should not have both a reflector and a dom struct field if let Some(sp) = reflector_span { if dom_spans.len() > 0 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has both Reflector \ and bare DOM struct members"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { db.span_note(sp, "Reflector found here"); for span in &dom_spans { db.span_note(*span, "Bare DOM struct found here"); } } } // Nor should we have more than one dom struct field } else if dom_spans.len() > 1 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has multiple \ DOM struct members, only one is allowed"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { for span in &dom_spans { db.span_note(*span, "Bare DOM struct found here"); } } } else if dom_spans.is_empty() { cx.span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has no reflector or parent DOM struct"); } } } }
{ lint_array!(INHERITANCE_INTEGRITY) }
identifier_body
inheritance_integrity.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 rustc::lint::{LateContext, LintPass, LintArray, Level, LateLintPass, LintContext}; use rustc::middle::def; use rustc_front::hir; use syntax::ast; use utils::match_lang_ty; declare_lint!(INHERITANCE_INTEGRITY, Deny, "Ensures that struct fields are properly laid out for inheritance to work"); /// Lint for ensuring proper layout of DOM structs /// /// A DOM struct must have one Reflector field or one field /// which itself is a DOM struct (in which case it must be the first field). pub struct
; impl LintPass for InheritancePass { fn get_lints(&self) -> LintArray { lint_array!(INHERITANCE_INTEGRITY) } } impl LateLintPass for InheritancePass { fn check_struct_def(&mut self, cx: &LateContext, def: &hir::VariantData, _n: ast::Name, _gen: &hir::Generics, id: ast::NodeId) { // Lints are run post expansion, so it's fine to use // #[_dom_struct_marker] here without also checking for #[dom_struct] if cx.tcx.has_attr(cx.tcx.map.local_def_id(id), "_dom_struct_marker") { // Find the reflector, if any let reflector_span = def.fields().iter().enumerate() .find(|&(ctr, f)| { if match_lang_ty(cx, &*f.node.ty, "reflector") { if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "The Reflector should be the first field of the DOM \ struct"); } return true; } false }) .map(|(_, f)| f.span); // Find all #[dom_struct] fields let dom_spans: Vec<_> = def.fields().iter().enumerate().filter_map(|(ctr, f)| { if let hir::TyPath(..) = f.node.ty.node { if let Some(&def::PathResolution { base_def: def,.. }) = cx.tcx.def_map.borrow().get(&f.node.ty.id) { if let def::Def::PrimTy(_) = def { return None; } if cx.tcx.has_attr(def.def_id(), "_dom_struct_marker") { // If the field is not the first, it's probably // being misused (a) if ctr > 0 { cx.span_lint(INHERITANCE_INTEGRITY, f.span, "Bare DOM structs should only be used as the first field of a \ DOM struct. Consider using JS<T> instead."); } return Some(f.span) } } } None }).collect(); // We should not have both a reflector and a dom struct field if let Some(sp) = reflector_span { if dom_spans.len() > 0 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has both Reflector \ and bare DOM struct members"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { db.span_note(sp, "Reflector found here"); for span in &dom_spans { db.span_note(*span, "Bare DOM struct found here"); } } } // Nor should we have more than one dom struct field } else if dom_spans.len() > 1 { let mut db = cx.struct_span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has multiple \ DOM struct members, only one is allowed"); if cx.current_level(INHERITANCE_INTEGRITY)!= Level::Allow { for span in &dom_spans { db.span_note(*span, "Bare DOM struct found here"); } } } else if dom_spans.is_empty() { cx.span_lint(INHERITANCE_INTEGRITY, cx.tcx.map.expect_item(id).span, "This DOM struct has no reflector or parent DOM struct"); } } } }
InheritancePass
identifier_name
asm-out-read-uninit.rs
// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast #[feature] doesn't work with check-fast #![feature(asm)] fn foo(x: int) { println!("{}", x); } #[cfg(target_arch = "x86")] #[cfg(target_arch = "x86_64")] #[cfg(target_arch = "arm")] pub fn main() { let x: int; unsafe { asm!("mov $1, $0" : "=r"(x) : "r"(x)); //~ ERROR use of possibly uninitialized variable: `x` } foo(x); } #[cfg(not(target_arch = "x86"), not(target_arch = "x86_64"), not(target_arch = "arm"))] pub fn main() {}
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
asm-out-read-uninit.rs
// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast #[feature] doesn't work with check-fast #![feature(asm)] fn foo(x: int)
#[cfg(target_arch = "x86")] #[cfg(target_arch = "x86_64")] #[cfg(target_arch = "arm")] pub fn main() { let x: int; unsafe { asm!("mov $1, $0" : "=r"(x) : "r"(x)); //~ ERROR use of possibly uninitialized variable: `x` } foo(x); } #[cfg(not(target_arch = "x86"), not(target_arch = "x86_64"), not(target_arch = "arm"))] pub fn main() {}
{ println!("{}", x); }
identifier_body
asm-out-read-uninit.rs
// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast #[feature] doesn't work with check-fast #![feature(asm)] fn
(x: int) { println!("{}", x); } #[cfg(target_arch = "x86")] #[cfg(target_arch = "x86_64")] #[cfg(target_arch = "arm")] pub fn main() { let x: int; unsafe { asm!("mov $1, $0" : "=r"(x) : "r"(x)); //~ ERROR use of possibly uninitialized variable: `x` } foo(x); } #[cfg(not(target_arch = "x86"), not(target_arch = "x86_64"), not(target_arch = "arm"))] pub fn main() {}
foo
identifier_name