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
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Logger for parity executables extern crate ethcore_util as util; #[macro_use] extern crate log as rlog; extern crate isatty; extern crate regex; extern crate env_logger; extern crate time; #[macro_use] extern crate lazy_static; use std::{env, thread}; use std::sync::Arc; use std::fs::File; use std::io::Write; use isatty::{stderr_isatty, stdout_isatty}; use env_logger::LogBuilder; use regex::Regex; use util::RotatingLogger; use util::log::Colour; #[derive(Debug, PartialEq)] pub struct Config { pub mode: Option<String>, pub color: bool, pub file: Option<String>, } impl Default for Config { fn default() -> Self { Config { mode: None, color:!cfg!(windows), file: None, } } } /// Sets up the logger pub fn setup_log(config: &Config) -> Result<Arc<RotatingLogger>, String> { use rlog::*; let mut levels = String::new(); let mut builder = LogBuilder::new(); // Disable ws info logging by default. builder.filter(Some("ws"), LogLevelFilter::Warn); // Disable rustls info logging by default. builder.filter(Some("rustls"), LogLevelFilter::Warn); builder.filter(None, LogLevelFilter::Info); if let Ok(lvl) = env::var("RUST_LOG") { levels.push_str(&lvl); levels.push_str(","); builder.parse(&lvl); } if let Some(ref s) = config.mode { levels.push_str(s); builder.parse(s); } let isatty = stderr_isatty(); let enable_color = config.color && isatty; let logs = Arc::new(RotatingLogger::new(levels)); let logger = logs.clone(); let maybe_file = match config.file.as_ref() { Some(f) => Some(try!(File::create(f).map_err(|_| format!("Cannot write to log file given: {}", f)))), None => None, }; let format = move |record: &LogRecord| { let timestamp = time::strftime("%Y-%m-%d %H:%M:%S %Z", &time::now()).unwrap(); let with_color = if max_log_level() <= LogLevelFilter::Info { format!("{} {}", Colour::Black.bold().paint(timestamp), record.args()) } else { let name = thread::current().name().map_or_else(Default::default, |x| format!("{}", Colour::Blue.bold().paint(x))); format!("{} {} {} {} {}", Colour::Black.bold().paint(timestamp), name, record.level(), record.target(), record.args()) }; let removed_color = kill_color(with_color.as_ref()); let ret = match enable_color { true => with_color, false => removed_color.clone(), }; if let Some(mut file) = maybe_file.as_ref() { // ignore errors - there's nothing we can do let _ = file.write_all(removed_color.as_bytes()); let _ = file.write_all(b"\n"); } logger.append(removed_color); if!isatty && record.level() <= LogLevel::Info && stdout_isatty() { // duplicate INFO/WARN output to console println!("{}", ret); } ret }; builder.format(format); builder.init().expect("Logger initialized only once."); Ok(logs)
lazy_static! { static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap(); } RE.replace_all(s, "") } #[test] fn should_remove_colour() { let before = "test"; let after = kill_color(&Colour::Red.bold().paint(before)); assert_eq!(after, "test"); } #[test] fn should_remove_multiple_colour() { let t = format!("{} {}", Colour::Red.bold().paint("test"), Colour::White.normal().paint("again")); let after = kill_color(&t); assert_eq!(after, "test again"); }
} fn kill_color(s: &str) -> String {
random_line_split
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Logger for parity executables extern crate ethcore_util as util; #[macro_use] extern crate log as rlog; extern crate isatty; extern crate regex; extern crate env_logger; extern crate time; #[macro_use] extern crate lazy_static; use std::{env, thread}; use std::sync::Arc; use std::fs::File; use std::io::Write; use isatty::{stderr_isatty, stdout_isatty}; use env_logger::LogBuilder; use regex::Regex; use util::RotatingLogger; use util::log::Colour; #[derive(Debug, PartialEq)] pub struct Config { pub mode: Option<String>, pub color: bool, pub file: Option<String>, } impl Default for Config { fn default() -> Self { Config { mode: None, color:!cfg!(windows), file: None, } } } /// Sets up the logger pub fn setup_log(config: &Config) -> Result<Arc<RotatingLogger>, String> { use rlog::*; let mut levels = String::new(); let mut builder = LogBuilder::new(); // Disable ws info logging by default. builder.filter(Some("ws"), LogLevelFilter::Warn); // Disable rustls info logging by default. builder.filter(Some("rustls"), LogLevelFilter::Warn); builder.filter(None, LogLevelFilter::Info); if let Ok(lvl) = env::var("RUST_LOG") { levels.push_str(&lvl); levels.push_str(","); builder.parse(&lvl); } if let Some(ref s) = config.mode { levels.push_str(s); builder.parse(s); } let isatty = stderr_isatty(); let enable_color = config.color && isatty; let logs = Arc::new(RotatingLogger::new(levels)); let logger = logs.clone(); let maybe_file = match config.file.as_ref() { Some(f) => Some(try!(File::create(f).map_err(|_| format!("Cannot write to log file given: {}", f)))), None => None, }; let format = move |record: &LogRecord| { let timestamp = time::strftime("%Y-%m-%d %H:%M:%S %Z", &time::now()).unwrap(); let with_color = if max_log_level() <= LogLevelFilter::Info { format!("{} {}", Colour::Black.bold().paint(timestamp), record.args()) } else { let name = thread::current().name().map_or_else(Default::default, |x| format!("{}", Colour::Blue.bold().paint(x))); format!("{} {} {} {} {}", Colour::Black.bold().paint(timestamp), name, record.level(), record.target(), record.args()) }; let removed_color = kill_color(with_color.as_ref()); let ret = match enable_color { true => with_color, false => removed_color.clone(), }; if let Some(mut file) = maybe_file.as_ref() { // ignore errors - there's nothing we can do let _ = file.write_all(removed_color.as_bytes()); let _ = file.write_all(b"\n"); } logger.append(removed_color); if!isatty && record.level() <= LogLevel::Info && stdout_isatty()
ret }; builder.format(format); builder.init().expect("Logger initialized only once."); Ok(logs) } fn kill_color(s: &str) -> String { lazy_static! { static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap(); } RE.replace_all(s, "") } #[test] fn should_remove_colour() { let before = "test"; let after = kill_color(&Colour::Red.bold().paint(before)); assert_eq!(after, "test"); } #[test] fn should_remove_multiple_colour() { let t = format!("{} {}", Colour::Red.bold().paint("test"), Colour::White.normal().paint("again")); let after = kill_color(&t); assert_eq!(after, "test again"); }
{ // duplicate INFO/WARN output to console println!("{}", ret); }
conditional_block
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Logger for parity executables extern crate ethcore_util as util; #[macro_use] extern crate log as rlog; extern crate isatty; extern crate regex; extern crate env_logger; extern crate time; #[macro_use] extern crate lazy_static; use std::{env, thread}; use std::sync::Arc; use std::fs::File; use std::io::Write; use isatty::{stderr_isatty, stdout_isatty}; use env_logger::LogBuilder; use regex::Regex; use util::RotatingLogger; use util::log::Colour; #[derive(Debug, PartialEq)] pub struct Config { pub mode: Option<String>, pub color: bool, pub file: Option<String>, } impl Default for Config { fn default() -> Self { Config { mode: None, color:!cfg!(windows), file: None, } } } /// Sets up the logger pub fn
(config: &Config) -> Result<Arc<RotatingLogger>, String> { use rlog::*; let mut levels = String::new(); let mut builder = LogBuilder::new(); // Disable ws info logging by default. builder.filter(Some("ws"), LogLevelFilter::Warn); // Disable rustls info logging by default. builder.filter(Some("rustls"), LogLevelFilter::Warn); builder.filter(None, LogLevelFilter::Info); if let Ok(lvl) = env::var("RUST_LOG") { levels.push_str(&lvl); levels.push_str(","); builder.parse(&lvl); } if let Some(ref s) = config.mode { levels.push_str(s); builder.parse(s); } let isatty = stderr_isatty(); let enable_color = config.color && isatty; let logs = Arc::new(RotatingLogger::new(levels)); let logger = logs.clone(); let maybe_file = match config.file.as_ref() { Some(f) => Some(try!(File::create(f).map_err(|_| format!("Cannot write to log file given: {}", f)))), None => None, }; let format = move |record: &LogRecord| { let timestamp = time::strftime("%Y-%m-%d %H:%M:%S %Z", &time::now()).unwrap(); let with_color = if max_log_level() <= LogLevelFilter::Info { format!("{} {}", Colour::Black.bold().paint(timestamp), record.args()) } else { let name = thread::current().name().map_or_else(Default::default, |x| format!("{}", Colour::Blue.bold().paint(x))); format!("{} {} {} {} {}", Colour::Black.bold().paint(timestamp), name, record.level(), record.target(), record.args()) }; let removed_color = kill_color(with_color.as_ref()); let ret = match enable_color { true => with_color, false => removed_color.clone(), }; if let Some(mut file) = maybe_file.as_ref() { // ignore errors - there's nothing we can do let _ = file.write_all(removed_color.as_bytes()); let _ = file.write_all(b"\n"); } logger.append(removed_color); if!isatty && record.level() <= LogLevel::Info && stdout_isatty() { // duplicate INFO/WARN output to console println!("{}", ret); } ret }; builder.format(format); builder.init().expect("Logger initialized only once."); Ok(logs) } fn kill_color(s: &str) -> String { lazy_static! { static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap(); } RE.replace_all(s, "") } #[test] fn should_remove_colour() { let before = "test"; let after = kill_color(&Colour::Red.bold().paint(before)); assert_eq!(after, "test"); } #[test] fn should_remove_multiple_colour() { let t = format!("{} {}", Colour::Red.bold().paint("test"), Colour::White.normal().paint("again")); let after = kill_color(&t); assert_eq!(after, "test again"); }
setup_log
identifier_name
key_generator.rs
// Copyright 2020 The Exonum Team // // 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 exonum_keys::generate_keys_from_seed; use serde_json::json; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt( name = "key-generator", about = "An utility for keys generation from a seed." )] struct Arguments { /// Seed for deriving keys. #[structopt(short = "s", long)] seed: String, /// Passphrase for encrypting the seed. #[structopt(short = "p", long)] passphrase: String, } fn
() { let args = Arguments::from_args(); let result = generate_json(&args.passphrase, &args.seed).unwrap(); println!( "{}", serde_json::to_string_pretty(&result).expect("Couldn't convert json object to string") ); } fn generate_json(passphrase: &str, seed: &str) -> anyhow::Result<serde_json::Value> { let seed = hex::decode(seed)?; let (keys, encrypted_key) = generate_keys_from_seed(passphrase.as_bytes(), &seed)?; let file_content = toml::to_string_pretty(&encrypted_key)?; Ok(json!({ "consensus_pub_key": keys.consensus.public_key().to_hex(), "service_pub_key": keys.service.public_key().to_hex(), "master_key_file": file_content, })) } #[test] fn test_key_generator() { use exonum_keys::read_keys_from_file; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; use std::{fs::OpenOptions, io::Write}; use tempfile::TempDir; let tempdir = TempDir::new().unwrap(); let master_key_path = tempdir.path().join("master_key.toml"); let seed = "a7839ea524f38d0e91a5ec96a723092719dc8a5b8a75f9131d9eb38f45e76344"; let passphrase = "passphrase"; let json = generate_json(passphrase, seed).unwrap(); let mut open_options = OpenOptions::new(); open_options.create(true).write(true); // By agreement we use the same permissions as for SSH private keys. #[cfg(unix)] open_options.mode(0o_600); let mut file = open_options.open(&master_key_path).unwrap(); file.write_all( json.get("master_key_file") .unwrap() .as_str() .unwrap() .as_bytes(), ) .unwrap(); let r_keys = read_keys_from_file(&master_key_path, passphrase).unwrap(); assert_eq!( json["service_pub_key"].as_str().unwrap(), r_keys.service.public_key().to_hex() ); assert_eq!( json["consensus_pub_key"].as_str().unwrap(), r_keys.consensus.public_key().to_hex() ); }
main
identifier_name
key_generator.rs
// Copyright 2020 The Exonum Team // // 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 exonum_keys::generate_keys_from_seed; use serde_json::json; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt( name = "key-generator", about = "An utility for keys generation from a seed." )] struct Arguments { /// Seed for deriving keys. #[structopt(short = "s", long)] seed: String, /// Passphrase for encrypting the seed. #[structopt(short = "p", long)] passphrase: String, } fn main() { let args = Arguments::from_args(); let result = generate_json(&args.passphrase, &args.seed).unwrap(); println!( "{}", serde_json::to_string_pretty(&result).expect("Couldn't convert json object to string") ); } fn generate_json(passphrase: &str, seed: &str) -> anyhow::Result<serde_json::Value> { let seed = hex::decode(seed)?; let (keys, encrypted_key) = generate_keys_from_seed(passphrase.as_bytes(), &seed)?; let file_content = toml::to_string_pretty(&encrypted_key)?; Ok(json!({ "consensus_pub_key": keys.consensus.public_key().to_hex(), "service_pub_key": keys.service.public_key().to_hex(), "master_key_file": file_content, })) } #[test] fn test_key_generator() { use exonum_keys::read_keys_from_file; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; use std::{fs::OpenOptions, io::Write}; use tempfile::TempDir; let tempdir = TempDir::new().unwrap(); let master_key_path = tempdir.path().join("master_key.toml"); let seed = "a7839ea524f38d0e91a5ec96a723092719dc8a5b8a75f9131d9eb38f45e76344"; let passphrase = "passphrase"; let json = generate_json(passphrase, seed).unwrap(); let mut open_options = OpenOptions::new(); open_options.create(true).write(true); // By agreement we use the same permissions as for SSH private keys. #[cfg(unix)] open_options.mode(0o_600); let mut file = open_options.open(&master_key_path).unwrap(); file.write_all( json.get("master_key_file") .unwrap() .as_str() .unwrap() .as_bytes(), ) .unwrap(); let r_keys = read_keys_from_file(&master_key_path, passphrase).unwrap(); assert_eq!(
); assert_eq!( json["consensus_pub_key"].as_str().unwrap(), r_keys.consensus.public_key().to_hex() ); }
json["service_pub_key"].as_str().unwrap(), r_keys.service.public_key().to_hex()
random_line_split
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Tox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Tox. If not, see <http://www.gnu.org/licenses/>. */ extern crate tox; extern crate futures; extern crate tokio_core; extern crate tokio_io; #[macro_use] extern crate log; extern crate env_logger; extern crate rustc_serialize; use rustc_serialize::hex::FromHex; use tox::toxcore::crypto_core::*; use tox::toxcore::tcp::packet::*; use tox::toxcore::tcp::make_client_handshake; use tox::toxcore::tcp::codec; use futures::prelude::*; use futures::future; use futures::sync::mpsc; use tokio_io::{AsyncRead, IoFuture}; use tokio_core::reactor::{Core, Handle}; use tokio_core::net::TcpStream; use std::{thread, time}; use std::io::{Error, ErrorKind}; // Notice that create_client create a future of client processing. // The future will live untill all copies of tx is dropped or there is a IO error // Since we pass a copy of tx as arg (to send PongResponses), the client will live untill IO error // Comment out pong responser and client will be destroyed when there will be no messages to send fn create_client(rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>, handle: &Handle) -> IoFuture<()> { // Use `gen_keypair` to generate random keys // Client constant keypair for examples/tests let client_pk = PublicKey([252, 72, 40, 127, 213, 13, 0, 95, 13, 230, 176, 49, 69, 252, 220, 132, 48, 73, 227, 58, 218, 154, 215, 245, 23, 189, 223, 216, 153, 237, 130, 88]); let client_sk = SecretKey([157, 128, 29, 197, 1, 72, 47, 56, 65, 81, 191, 67, 220, 225, 108, 193, 46, 163, 145, 242, 139, 125, 159, 137, 174, 14, 225, 7, 138, 120, 185, 153]); let (addr, server_pk) = match 1 { 1 => { // local tcp relay server from example let addr = "0.0.0.0:12345".parse().unwrap(); // Server constant PK for examples/tests let server_pk = PublicKey([177, 185, 54, 250, 10, 168, 174, 148, 0, 93, 99, 13, 131, 131, 239, 193, 129, 141, 80, 158, 50, 133, 100, 182, 179, 183, 234, 116, 142, 102, 53, 38]); (addr, server_pk) }, 2 => { // remote tcp relay server let server_pk_bytes = FromHex::from_hex("461FA3776EF0FA655F1A05477DF1B3B614F7D6B124F7DB1DD4FE3C08B03B640F").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "130.133.110.14:33445".parse().unwrap(); (addr, server_pk) }, 3 => { // local C DHT node, TODO remove this case let server_pk_bytes = FromHex::from_hex("C4B8D288C391704E3C8840A8A7C19B21D0B76CAF3B55341D37C5A9732887F879").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "0.0.0.0:33445".parse().unwrap(); (addr, server_pk) } _ => { unreachable!() } }; let client = TcpStream::connect(&addr, &handle) .and_then(move |socket| { make_client_handshake(socket, client_pk, client_sk, server_pk) }) .and_then(|(socket, channel)| { debug!("Handshake complited"); let secure_socket = socket.framed(codec::Codec::new(channel)); let (to_server, from_server) = secure_socket.split(); let reader = from_server.for_each(move |packet| -> IoFuture<()> { debug!("Got packet {:?}", packet); // Simple pong responser if let Packet::PingRequest(ping) = packet { Box::new( tx.clone().send(Packet::PongResponse( PongResponse { ping_id: ping.ping_id } )) .map(|_| () ) .map_err(|_| Error::new(ErrorKind::Other, "Could not send pong") ) ) } else { Box::new( future::ok(()) ) } }) .then(|res| { debug!("Reader ended with {:?}", res); res }); let writer = rx .map_err(|()| unreachable!("rx can't fail")) .fold(to_server, move |to_server, packet| { debug!("Send packet {:?}", packet); to_server.send(packet) }) // drop to_client when rx stream is exhausted .map(|_to_client| { debug!("Stream rx is exhausted"); () }) .map_err(|err| { error!("Writer err: {}", err); err });; reader.select(writer).map(|_| ()).map_err(|(err, _select_next)| err) }) .then(|res| { debug!("client ended with {:?}", res); Ok(()) }); Box::new(client) } #[allow(dead_code)] fn send_packets(tx: mpsc::Sender<Packet>) { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157, 192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]); let mut i = 0u64; loop { let sleep_duration = time::Duration::from_millis(1); match tx.clone().send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; if i % 10000 == 0 { thread::sleep(sleep_duration); println!("i = {}", i); } i = i + 1; } /* let packets = vec![ Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ) ]; let sleep_duration = time::Duration::from_millis(1500); for packet in packets { match tx.clone().send(packet).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; thread::sleep(sleep_duration); } thread::sleep(sleep_duration); */ } fn main() {
let client = client.select(packet_sender).map_err(|_| ()); // variant 2. send packets in a separate thread //thread::spawn(move || send_packets(tx)); core.run( client ).unwrap(); }
env_logger::init().unwrap(); let (tx, rx) = mpsc::channel(1); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = create_client(rx, tx.clone(), &handle); // variant 1. send packets in the same thread, combine with select(...) let packet_sender = future::loop_fn(tx.clone(), move |tx| { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157, 192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]); tx.send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )) .and_then(|tx| Ok(future::Loop::Continue(tx)) ) .or_else(|e| Ok(future::Loop::Break(e)) ) }).map(|_| ());
identifier_body
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Tox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Tox. If not, see <http://www.gnu.org/licenses/>. */ extern crate tox; extern crate futures; extern crate tokio_core; extern crate tokio_io; #[macro_use] extern crate log; extern crate env_logger; extern crate rustc_serialize; use rustc_serialize::hex::FromHex; use tox::toxcore::crypto_core::*; use tox::toxcore::tcp::packet::*; use tox::toxcore::tcp::make_client_handshake; use tox::toxcore::tcp::codec; use futures::prelude::*; use futures::future; use futures::sync::mpsc; use tokio_io::{AsyncRead, IoFuture}; use tokio_core::reactor::{Core, Handle}; use tokio_core::net::TcpStream; use std::{thread, time}; use std::io::{Error, ErrorKind}; // Notice that create_client create a future of client processing. // The future will live untill all copies of tx is dropped or there is a IO error // Since we pass a copy of tx as arg (to send PongResponses), the client will live untill IO error // Comment out pong responser and client will be destroyed when there will be no messages to send fn create_client(rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>, handle: &Handle) -> IoFuture<()> { // Use `gen_keypair` to generate random keys // Client constant keypair for examples/tests let client_pk = PublicKey([252, 72, 40, 127, 213, 13, 0, 95, 13, 230, 176, 49, 69, 252, 220, 132, 48, 73, 227, 58, 218, 154, 215, 245, 23, 189, 223, 216, 153, 237, 130, 88]); let client_sk = SecretKey([157, 128, 29, 197, 1, 72, 47, 56, 65, 81, 191, 67, 220, 225, 108, 193, 46, 163, 145, 242, 139, 125, 159, 137, 174, 14, 225, 7, 138, 120, 185, 153]); let (addr, server_pk) = match 1 { 1 => {
2 => { // remote tcp relay server let server_pk_bytes = FromHex::from_hex("461FA3776EF0FA655F1A05477DF1B3B614F7D6B124F7DB1DD4FE3C08B03B640F").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "130.133.110.14:33445".parse().unwrap(); (addr, server_pk) }, 3 => { // local C DHT node, TODO remove this case let server_pk_bytes = FromHex::from_hex("C4B8D288C391704E3C8840A8A7C19B21D0B76CAF3B55341D37C5A9732887F879").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "0.0.0.0:33445".parse().unwrap(); (addr, server_pk) } _ => { unreachable!() } }; let client = TcpStream::connect(&addr, &handle) .and_then(move |socket| { make_client_handshake(socket, client_pk, client_sk, server_pk) }) .and_then(|(socket, channel)| { debug!("Handshake complited"); let secure_socket = socket.framed(codec::Codec::new(channel)); let (to_server, from_server) = secure_socket.split(); let reader = from_server.for_each(move |packet| -> IoFuture<()> { debug!("Got packet {:?}", packet); // Simple pong responser if let Packet::PingRequest(ping) = packet { Box::new( tx.clone().send(Packet::PongResponse( PongResponse { ping_id: ping.ping_id } )) .map(|_| () ) .map_err(|_| Error::new(ErrorKind::Other, "Could not send pong") ) ) } else { Box::new( future::ok(()) ) } }) .then(|res| { debug!("Reader ended with {:?}", res); res }); let writer = rx .map_err(|()| unreachable!("rx can't fail")) .fold(to_server, move |to_server, packet| { debug!("Send packet {:?}", packet); to_server.send(packet) }) // drop to_client when rx stream is exhausted .map(|_to_client| { debug!("Stream rx is exhausted"); () }) .map_err(|err| { error!("Writer err: {}", err); err });; reader.select(writer).map(|_| ()).map_err(|(err, _select_next)| err) }) .then(|res| { debug!("client ended with {:?}", res); Ok(()) }); Box::new(client) } #[allow(dead_code)] fn send_packets(tx: mpsc::Sender<Packet>) { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157, 192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]); let mut i = 0u64; loop { let sleep_duration = time::Duration::from_millis(1); match tx.clone().send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; if i % 10000 == 0 { thread::sleep(sleep_duration); println!("i = {}", i); } i = i + 1; } /* let packets = vec![ Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ) ]; let sleep_duration = time::Duration::from_millis(1500); for packet in packets { match tx.clone().send(packet).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; thread::sleep(sleep_duration); } thread::sleep(sleep_duration); */ } fn main() { env_logger::init().unwrap(); let (tx, rx) = mpsc::channel(1); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = create_client(rx, tx.clone(), &handle); // variant 1. send packets in the same thread, combine with select(...) let packet_sender = future::loop_fn(tx.clone(), move |tx| { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157, 192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]); tx.send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )) .and_then(|tx| Ok(future::Loop::Continue(tx)) ) .or_else(|e| Ok(future::Loop::Break(e)) ) }).map(|_| ()); let client = client.select(packet_sender).map_err(|_| ()); // variant 2. send packets in a separate thread //thread::spawn(move || send_packets(tx)); core.run( client ).unwrap(); }
// local tcp relay server from example let addr = "0.0.0.0:12345".parse().unwrap(); // Server constant PK for examples/tests let server_pk = PublicKey([177, 185, 54, 250, 10, 168, 174, 148, 0, 93, 99, 13, 131, 131, 239, 193, 129, 141, 80, 158, 50, 133, 100, 182, 179, 183, 234, 116, 142, 102, 53, 38]); (addr, server_pk) },
conditional_block
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Tox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Tox. If not, see <http://www.gnu.org/licenses/>. */ extern crate tox; extern crate futures; extern crate tokio_core; extern crate tokio_io; #[macro_use] extern crate log; extern crate env_logger; extern crate rustc_serialize; use rustc_serialize::hex::FromHex; use tox::toxcore::crypto_core::*; use tox::toxcore::tcp::packet::*; use tox::toxcore::tcp::make_client_handshake; use tox::toxcore::tcp::codec; use futures::prelude::*; use futures::future; use futures::sync::mpsc; use tokio_io::{AsyncRead, IoFuture}; use tokio_core::reactor::{Core, Handle}; use tokio_core::net::TcpStream; use std::{thread, time}; use std::io::{Error, ErrorKind}; // Notice that create_client create a future of client processing. // The future will live untill all copies of tx is dropped or there is a IO error // Since we pass a copy of tx as arg (to send PongResponses), the client will live untill IO error // Comment out pong responser and client will be destroyed when there will be no messages to send fn create_client(rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>, handle: &Handle) -> IoFuture<()> { // Use `gen_keypair` to generate random keys // Client constant keypair for examples/tests let client_pk = PublicKey([252, 72, 40, 127, 213, 13, 0, 95, 13, 230, 176, 49, 69, 252, 220, 132, 48, 73, 227, 58, 218, 154, 215, 245, 23, 189, 223, 216, 153, 237, 130, 88]); let client_sk = SecretKey([157, 128, 29, 197, 1, 72, 47, 56, 65, 81, 191, 67, 220, 225, 108, 193, 46, 163, 145, 242, 139, 125, 159, 137, 174, 14, 225, 7, 138, 120, 185, 153]); let (addr, server_pk) = match 1 { 1 => { // local tcp relay server from example let addr = "0.0.0.0:12345".parse().unwrap(); // Server constant PK for examples/tests let server_pk = PublicKey([177, 185, 54, 250, 10, 168, 174, 148, 0, 93, 99, 13, 131, 131, 239, 193, 129, 141, 80, 158, 50, 133, 100, 182, 179, 183, 234, 116, 142, 102, 53, 38]); (addr, server_pk) }, 2 => { // remote tcp relay server let server_pk_bytes = FromHex::from_hex("461FA3776EF0FA655F1A05477DF1B3B614F7D6B124F7DB1DD4FE3C08B03B640F").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "130.133.110.14:33445".parse().unwrap(); (addr, server_pk) }, 3 => { // local C DHT node, TODO remove this case let server_pk_bytes = FromHex::from_hex("C4B8D288C391704E3C8840A8A7C19B21D0B76CAF3B55341D37C5A9732887F879").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "0.0.0.0:33445".parse().unwrap(); (addr, server_pk) } _ => { unreachable!() } }; let client = TcpStream::connect(&addr, &handle) .and_then(move |socket| { make_client_handshake(socket, client_pk, client_sk, server_pk) }) .and_then(|(socket, channel)| { debug!("Handshake complited"); let secure_socket = socket.framed(codec::Codec::new(channel)); let (to_server, from_server) = secure_socket.split(); let reader = from_server.for_each(move |packet| -> IoFuture<()> { debug!("Got packet {:?}", packet); // Simple pong responser if let Packet::PingRequest(ping) = packet { Box::new( tx.clone().send(Packet::PongResponse( PongResponse { ping_id: ping.ping_id } )) .map(|_| () ) .map_err(|_| Error::new(ErrorKind::Other, "Could not send pong") ) ) } else { Box::new( future::ok(()) ) } }) .then(|res| { debug!("Reader ended with {:?}", res); res }); let writer = rx .map_err(|()| unreachable!("rx can't fail")) .fold(to_server, move |to_server, packet| { debug!("Send packet {:?}", packet); to_server.send(packet) }) // drop to_client when rx stream is exhausted .map(|_to_client| { debug!("Stream rx is exhausted"); () }) .map_err(|err| { error!("Writer err: {}", err); err });; reader.select(writer).map(|_| ()).map_err(|(err, _select_next)| err) }) .then(|res| { debug!("client ended with {:?}", res); Ok(()) }); Box::new(client) } #[allow(dead_code)] fn send_packets(tx: mpsc::Sender<Packet>) { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157, 192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]); let mut i = 0u64; loop { let sleep_duration = time::Duration::from_millis(1); match tx.clone().send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; if i % 10000 == 0 { thread::sleep(sleep_duration); println!("i = {}", i); } i = i + 1; } /* let packets = vec![ Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ) ]; let sleep_duration = time::Duration::from_millis(1500); for packet in packets { match tx.clone().send(packet).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; thread::sleep(sleep_duration); } thread::sleep(sleep_duration); */ } fn ma
{ env_logger::init().unwrap(); let (tx, rx) = mpsc::channel(1); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = create_client(rx, tx.clone(), &handle); // variant 1. send packets in the same thread, combine with select(...) let packet_sender = future::loop_fn(tx.clone(), move |tx| { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157, 192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]); tx.send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )) .and_then(|tx| Ok(future::Loop::Continue(tx)) ) .or_else(|e| Ok(future::Loop::Break(e)) ) }).map(|_| ()); let client = client.select(packet_sender).map_err(|_| ()); // variant 2. send packets in a separate thread //thread::spawn(move || send_packets(tx)); core.run( client ).unwrap(); }
in()
identifier_name
tcp_client.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Tox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Tox. If not, see <http://www.gnu.org/licenses/>. */ extern crate tox; extern crate futures; extern crate tokio_core; extern crate tokio_io; #[macro_use] extern crate log; extern crate env_logger; extern crate rustc_serialize; use rustc_serialize::hex::FromHex; use tox::toxcore::crypto_core::*; use tox::toxcore::tcp::packet::*; use tox::toxcore::tcp::make_client_handshake; use tox::toxcore::tcp::codec; use futures::prelude::*; use futures::future; use futures::sync::mpsc; use tokio_io::{AsyncRead, IoFuture}; use tokio_core::reactor::{Core, Handle}; use tokio_core::net::TcpStream; use std::{thread, time}; use std::io::{Error, ErrorKind}; // Notice that create_client create a future of client processing. // The future will live untill all copies of tx is dropped or there is a IO error // Since we pass a copy of tx as arg (to send PongResponses), the client will live untill IO error // Comment out pong responser and client will be destroyed when there will be no messages to send fn create_client(rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>, handle: &Handle) -> IoFuture<()> { // Use `gen_keypair` to generate random keys // Client constant keypair for examples/tests let client_pk = PublicKey([252, 72, 40, 127, 213, 13, 0, 95, 13, 230, 176, 49, 69, 252, 220, 132, 48, 73, 227, 58, 218, 154, 215, 245, 23, 189, 223, 216, 153, 237, 130, 88]); let client_sk = SecretKey([157, 128, 29, 197, 1, 72, 47, 56, 65, 81, 191, 67, 220, 225, 108, 193, 46, 163, 145, 242, 139, 125, 159, 137, 174, 14, 225, 7, 138, 120, 185, 153]); let (addr, server_pk) = match 1 { 1 => { // local tcp relay server from example let addr = "0.0.0.0:12345".parse().unwrap(); // Server constant PK for examples/tests let server_pk = PublicKey([177, 185, 54, 250, 10, 168, 174, 148, 0, 93, 99, 13, 131, 131, 239, 193, 129, 141, 80, 158, 50, 133, 100, 182, 179, 183, 234, 116, 142, 102, 53, 38]); (addr, server_pk) }, 2 => { // remote tcp relay server let server_pk_bytes = FromHex::from_hex("461FA3776EF0FA655F1A05477DF1B3B614F7D6B124F7DB1DD4FE3C08B03B640F").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "130.133.110.14:33445".parse().unwrap(); (addr, server_pk) }, 3 => { // local C DHT node, TODO remove this case let server_pk_bytes = FromHex::from_hex("C4B8D288C391704E3C8840A8A7C19B21D0B76CAF3B55341D37C5A9732887F879").unwrap(); let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap(); let addr = "0.0.0.0:33445".parse().unwrap(); (addr, server_pk) } _ => { unreachable!() } }; let client = TcpStream::connect(&addr, &handle) .and_then(move |socket| { make_client_handshake(socket, client_pk, client_sk, server_pk) }) .and_then(|(socket, channel)| { debug!("Handshake complited"); let secure_socket = socket.framed(codec::Codec::new(channel)); let (to_server, from_server) = secure_socket.split(); let reader = from_server.for_each(move |packet| -> IoFuture<()> { debug!("Got packet {:?}", packet); // Simple pong responser if let Packet::PingRequest(ping) = packet { Box::new( tx.clone().send(Packet::PongResponse( PongResponse { ping_id: ping.ping_id } )) .map(|_| () ) .map_err(|_| Error::new(ErrorKind::Other, "Could not send pong") ) ) } else { Box::new( future::ok(()) ) } }) .then(|res| { debug!("Reader ended with {:?}", res); res }); let writer = rx .map_err(|()| unreachable!("rx can't fail")) .fold(to_server, move |to_server, packet| { debug!("Send packet {:?}", packet); to_server.send(packet) }) // drop to_client when rx stream is exhausted .map(|_to_client| { debug!("Stream rx is exhausted"); () }) .map_err(|err| { error!("Writer err: {}", err); err });; reader.select(writer).map(|_| ()).map_err(|(err, _select_next)| err) }) .then(|res| { debug!("client ended with {:?}", res); Ok(()) }); Box::new(client) } #[allow(dead_code)] fn send_packets(tx: mpsc::Sender<Packet>) { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157, 192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]); let mut i = 0u64; loop { let sleep_duration = time::Duration::from_millis(1); match tx.clone().send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; if i % 10000 == 0 { thread::sleep(sleep_duration); println!("i = {}", i); } i = i + 1; } /* let packets = vec![ Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ), Packet::RouteRequest(RouteRequest {pk: friend_pk } ) ]; let sleep_duration = time::Duration::from_millis(1500); for packet in packets { match tx.clone().send(packet).wait() { Ok(_tx) => (), Err(e) => { error!("send_packets: {:?}", e); break }, }; thread::sleep(sleep_duration); } thread::sleep(sleep_duration); */ } fn main() { env_logger::init().unwrap(); let (tx, rx) = mpsc::channel(1); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = create_client(rx, tx.clone(), &handle); // variant 1. send packets in the same thread, combine with select(...) let packet_sender = future::loop_fn(tx.clone(), move |tx| { // Client friend constant PK for examples/tests let friend_pk = PublicKey([15, 107, 126, 130, 81, 55, 154, 157,
tx.send(Packet::RouteRequest(RouteRequest {pk: friend_pk } )) .and_then(|tx| Ok(future::Loop::Continue(tx)) ) .or_else(|e| Ok(future::Loop::Break(e)) ) }).map(|_| ()); let client = client.select(packet_sender).map_err(|_| ()); // variant 2. send packets in a separate thread //thread::spawn(move || send_packets(tx)); core.run( client ).unwrap(); }
192, 117, 0, 225, 119, 43, 48, 117, 84, 109, 112, 57, 243, 216, 4, 171, 185, 111, 33, 146, 221, 31, 77, 118]);
random_line_split
errors.rs
//! Representations of various client errors use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { SerdeJsonError(SerdeError), Hyper(hyper::Error), Http(hyper::http::Error), #[allow(clippy::upper_case_acronyms)] IO(IoError), Encoding(FromUtf8Error), InvalidResponse(String), Fault { code: StatusCode, message: String, }, ConnectionNotUpgraded, } impl From<SerdeError> for Error { fn from(error: SerdeError) -> Error { Error::SerdeJsonError(error) } } impl From<hyper::Error> for Error { fn from(error: hyper::Error) -> Error { Error::Hyper(error) } } impl From<hyper::http::Error> for Error { fn from(error: hyper::http::Error) -> Error { Error::Http(error) } } impl From<http::uri::InvalidUri> for Error { fn from(error: http::uri::InvalidUri) -> Self { let http_error: http::Error = error.into(); http_error.into() } } impl From<IoError> for Error { fn from(error: IoError) -> Error
} impl From<FromUtf8Error> for Error { fn from(error: FromUtf8Error) -> Error { Error::Encoding(error) } } impl fmt::Display for Error { fn fmt( &self, f: &mut fmt::Formatter, ) -> fmt::Result { write!(f, "Docker Error: ")?; match self { Error::SerdeJsonError(ref err) => err.fmt(f), Error::Http(ref err) => err.fmt(f), Error::Hyper(ref err) => err.fmt(f), Error::IO(ref err) => err.fmt(f), Error::Encoding(ref err) => err.fmt(f), Error::InvalidResponse(ref cause) => { write!(f, "Response doesn't have the expected format: {}", cause) } Error::Fault { code, message } => write!(f, "{}: {}", code, message), Error::ConnectionNotUpgraded => write!( f, "expected the docker host to upgrade the HTTP connection but it did not" ), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError +'static)> { match self { Error::SerdeJsonError(ref err) => Some(err), Error::Http(ref err) => Some(err), Error::IO(ref err) => Some(err), Error::Encoding(e) => Some(e), _ => None, } } }
{ Error::IO(error) }
identifier_body
errors.rs
//! Representations of various client errors use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { SerdeJsonError(SerdeError), Hyper(hyper::Error), Http(hyper::http::Error), #[allow(clippy::upper_case_acronyms)] IO(IoError), Encoding(FromUtf8Error), InvalidResponse(String), Fault { code: StatusCode, message: String, }, ConnectionNotUpgraded, } impl From<SerdeError> for Error { fn from(error: SerdeError) -> Error { Error::SerdeJsonError(error) } } impl From<hyper::Error> for Error { fn from(error: hyper::Error) -> Error { Error::Hyper(error) } } impl From<hyper::http::Error> for Error { fn from(error: hyper::http::Error) -> Error { Error::Http(error) } } impl From<http::uri::InvalidUri> for Error { fn
(error: http::uri::InvalidUri) -> Self { let http_error: http::Error = error.into(); http_error.into() } } impl From<IoError> for Error { fn from(error: IoError) -> Error { Error::IO(error) } } impl From<FromUtf8Error> for Error { fn from(error: FromUtf8Error) -> Error { Error::Encoding(error) } } impl fmt::Display for Error { fn fmt( &self, f: &mut fmt::Formatter, ) -> fmt::Result { write!(f, "Docker Error: ")?; match self { Error::SerdeJsonError(ref err) => err.fmt(f), Error::Http(ref err) => err.fmt(f), Error::Hyper(ref err) => err.fmt(f), Error::IO(ref err) => err.fmt(f), Error::Encoding(ref err) => err.fmt(f), Error::InvalidResponse(ref cause) => { write!(f, "Response doesn't have the expected format: {}", cause) } Error::Fault { code, message } => write!(f, "{}: {}", code, message), Error::ConnectionNotUpgraded => write!( f, "expected the docker host to upgrade the HTTP connection but it did not" ), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError +'static)> { match self { Error::SerdeJsonError(ref err) => Some(err), Error::Http(ref err) => Some(err), Error::IO(ref err) => Some(err), Error::Encoding(e) => Some(e), _ => None, } } }
from
identifier_name
errors.rs
use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { SerdeJsonError(SerdeError), Hyper(hyper::Error), Http(hyper::http::Error), #[allow(clippy::upper_case_acronyms)] IO(IoError), Encoding(FromUtf8Error), InvalidResponse(String), Fault { code: StatusCode, message: String, }, ConnectionNotUpgraded, } impl From<SerdeError> for Error { fn from(error: SerdeError) -> Error { Error::SerdeJsonError(error) } } impl From<hyper::Error> for Error { fn from(error: hyper::Error) -> Error { Error::Hyper(error) } } impl From<hyper::http::Error> for Error { fn from(error: hyper::http::Error) -> Error { Error::Http(error) } } impl From<http::uri::InvalidUri> for Error { fn from(error: http::uri::InvalidUri) -> Self { let http_error: http::Error = error.into(); http_error.into() } } impl From<IoError> for Error { fn from(error: IoError) -> Error { Error::IO(error) } } impl From<FromUtf8Error> for Error { fn from(error: FromUtf8Error) -> Error { Error::Encoding(error) } } impl fmt::Display for Error { fn fmt( &self, f: &mut fmt::Formatter, ) -> fmt::Result { write!(f, "Docker Error: ")?; match self { Error::SerdeJsonError(ref err) => err.fmt(f), Error::Http(ref err) => err.fmt(f), Error::Hyper(ref err) => err.fmt(f), Error::IO(ref err) => err.fmt(f), Error::Encoding(ref err) => err.fmt(f), Error::InvalidResponse(ref cause) => { write!(f, "Response doesn't have the expected format: {}", cause) } Error::Fault { code, message } => write!(f, "{}: {}", code, message), Error::ConnectionNotUpgraded => write!( f, "expected the docker host to upgrade the HTTP connection but it did not" ), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError +'static)> { match self { Error::SerdeJsonError(ref err) => Some(err), Error::Http(ref err) => Some(err), Error::IO(ref err) => Some(err), Error::Encoding(e) => Some(e), _ => None, } } }
//! Representations of various client errors
random_line_split
errors.rs
//! Representations of various client errors use hyper::{self, http, StatusCode}; use serde_json::Error as SerdeError; use std::{error::Error as StdError, fmt, string::FromUtf8Error}; use futures_util::io::Error as IoError; /// Represents the result of all docker operations pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { SerdeJsonError(SerdeError), Hyper(hyper::Error), Http(hyper::http::Error), #[allow(clippy::upper_case_acronyms)] IO(IoError), Encoding(FromUtf8Error), InvalidResponse(String), Fault { code: StatusCode, message: String, }, ConnectionNotUpgraded, } impl From<SerdeError> for Error { fn from(error: SerdeError) -> Error { Error::SerdeJsonError(error) } } impl From<hyper::Error> for Error { fn from(error: hyper::Error) -> Error { Error::Hyper(error) } } impl From<hyper::http::Error> for Error { fn from(error: hyper::http::Error) -> Error { Error::Http(error) } } impl From<http::uri::InvalidUri> for Error { fn from(error: http::uri::InvalidUri) -> Self { let http_error: http::Error = error.into(); http_error.into() } } impl From<IoError> for Error { fn from(error: IoError) -> Error { Error::IO(error) } } impl From<FromUtf8Error> for Error { fn from(error: FromUtf8Error) -> Error { Error::Encoding(error) } } impl fmt::Display for Error { fn fmt( &self, f: &mut fmt::Formatter, ) -> fmt::Result { write!(f, "Docker Error: ")?; match self { Error::SerdeJsonError(ref err) => err.fmt(f), Error::Http(ref err) => err.fmt(f), Error::Hyper(ref err) => err.fmt(f), Error::IO(ref err) => err.fmt(f), Error::Encoding(ref err) => err.fmt(f), Error::InvalidResponse(ref cause) =>
Error::Fault { code, message } => write!(f, "{}: {}", code, message), Error::ConnectionNotUpgraded => write!( f, "expected the docker host to upgrade the HTTP connection but it did not" ), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError +'static)> { match self { Error::SerdeJsonError(ref err) => Some(err), Error::Http(ref err) => Some(err), Error::IO(ref err) => Some(err), Error::Encoding(e) => Some(e), _ => None, } } }
{ write!(f, "Response doesn't have the expected format: {}", cause) }
conditional_block
group.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::database::Database; use crate::image::Image; use crate::stats::ScopedDuration; use crate::vec::*; use crate::view::View; use crate::Stopwatch; use crate::TileRef; use crate::R; use crate::{Metadata, MetadataState}; use piston_window::{ color, rectangle, DrawState, G2d, G2dTexture, G2dTextureContext, Texture, TextureSettings, Transformed, }; use std::cmp::Ordering; use std::collections::{BTreeMap, VecDeque}; #[derive(Debug)] pub struct Group { pub extents: [Vector2<u32>; 2], pub tiles: BTreeMap<TileRef, G2dTexture>, pub images: BTreeMap<Vector2<u32>, Image>, pub cache_todo: [VecDeque<Vector2<u32>>; 2], pub thumb_todo: [VecDeque<Vector2<u32>>; 2], } impl Group { pub fn new(extents: [Vector2<u32>; 2]) -> Self { Self { extents, tiles: BTreeMap::new(), images: BTreeMap::new(), cache_todo: [VecDeque::new(), VecDeque::new()], thumb_todo: [VecDeque::new(), VecDeque::new()], } } pub fn insert(&mut self, coords: Vector2<u32>, image: Image) { self.images.insert(coords, image); } pub fn reset(&mut self) { for image in self.images.values_mut() { image.reset(); } self.tiles.clear(); for queue in &mut self.cache_todo { queue.clear(); } for queue in &mut self.thumb_todo { queue.clear(); } } pub fn recheck(&mut self, view: &View) { for queue in &mut self.thumb_todo { queue.clear(); } for queue in &mut self.cache_todo { queue.clear(); } let mut mouse_dist: Vec<(&Vector2<u32>, &Image)> = Vec::with_capacity(self.images.len()); mouse_dist.extend(self.images.iter()); mouse_dist.sort_by_key(|(&coords, _)| vec2_square_len(view.mouse_dist(coords)) as isize); for (&coords, image) in &mouse_dist { let p =!view.is_visible(view.trans(coords)) as usize; match image.metadata { MetadataState::Some(_) => { self.cache_todo[p].push_back(coords); } MetadataState::Missing => { self.thumb_todo[p].push_back(coords); } MetadataState::Errored => continue, } } } pub fn load_cache( &mut self, p: usize, view: &View, db: &Database, texture_context: &mut G2dTextureContext, stopwatch: &Stopwatch, ) -> bool { let _s3 = ScopedDuration::new("Group::load_cache"); let target_size = view.target_size(); let texture_settings = TextureSettings::new(); while let Some(coords) = self.cache_todo[p].pop_front() { let image = self.images.get_mut(&coords).unwrap(); let metadata = image.get_metadata().expect("Image::get_metadata"); let view_coords = view.trans(coords); let shift = if p == 0 { 0 } else { let ratio = view.visible_ratio(view_coords); f64::max(0.0, ratio - 1.0).floor() as usize }; let new_size = metadata.nearest(target_size >> shift); let current_size = image.size.unwrap_or(0); // Progressive resizing. let new_size = match new_size.cmp(&current_size) { Ordering::Less => current_size - 1, Ordering::Equal => { // Already loaded target size. continue; } Ordering::Greater => current_size + 1, }; // Load new tiles. for tile_ref in &metadata.thumbs[new_size].tile_refs { // Already loaded. if self.tiles.contains_key(tile_ref) { continue; } if stopwatch.done() { self.cache_todo[p].push_front(coords); return false; } let data = db.get(*tile_ref).expect("db get").expect("missing tile"); let image = ::image::load_from_memory(&data).expect("load image"); // TODO: Would be great to move off thread. let image = Texture::from_image(texture_context, &image.to_rgba(), &texture_settings) .expect("texture"); self.tiles.insert(*tile_ref, image); } // Unload old tiles. for (j, thumb) in metadata.thumbs.iter().enumerate() { if j == new_size { continue; } for tile_ref in &thumb.tile_refs { self.tiles.remove(tile_ref); } } image.size = Some(new_size); self.cache_todo[p].push_back(coords); } true } pub fn make_thumbs(&mut self, p: usize, thumbnailer: &mut crate::Thumbnailer) -> bool { loop { if thumbnailer.is_full() { return false; } if let Some(coords) = self.thumb_todo[p].pop_front() { let image = self.images.get(&coords).unwrap(); if!thumbnailer.make_thumbs(image) { return false; } } else { break true; } } } pub fn update_metadata(&mut self, coords: Vector2<u32>, metadata_res: R<Metadata>) { let image = self.images.get_mut(&coords).unwrap(); image.metadata = match metadata_res { Ok(metadata) => { self.cache_todo[0].push_front(coords); MetadataState::Some(metadata) } Err(e) => { error!("make_thumb: {}", e); MetadataState::Errored } }; } pub fn draw(&self, trans: [[f64; 3]; 2], view: &View, draw_state: &DrawState, g: &mut G2d) { //{ // let [min, max] = self.extents; // let op_color = color::hex("FF0000"); // let [x, y] = view.trans(min); // let [w, h] = vec2_scale(vec2_f64(vec2_sub(max, min)), view.zoom); // let trans = trans.trans(x, y); // rectangle(op_color, [0.0, 0.0, w, 1.0], trans, g); // rectangle(op_color, [0.0, 0.0, 1.0, h], trans, g); // rectangle(op_color, [w, 0.0, 1.0, h], trans, g); // rectangle(op_color, [0.0, h, w, 1.0], trans, g); //} let dot_color = color::hex("444444"); let mid_zoom = view.zoom * 0.5; for (&coords, image) in &self.images { let coords = view.trans(coords); if!view.is_visible(coords) { continue; } let trans = trans.trans(coords[0], coords[1]); if image.draw(trans, view, &self.tiles, &draw_state, g) { continue; } else { rectangle(dot_color, [mid_zoom, mid_zoom, 1.0, 1.0], trans, g); } } } pub fn
(&self, view: &View) -> usize { let midpoint = vec2_div(vec2_add(self.extents[0], self.extents[1]), [2, 2]); let mouse_dist = view.mouse_dist(midpoint); vec2_square_len(mouse_dist) as usize } }
mouse_dist
identifier_name
group.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::database::Database; use crate::image::Image; use crate::stats::ScopedDuration; use crate::vec::*; use crate::view::View; use crate::Stopwatch; use crate::TileRef; use crate::R; use crate::{Metadata, MetadataState}; use piston_window::{ color, rectangle, DrawState, G2d, G2dTexture, G2dTextureContext, Texture, TextureSettings, Transformed, }; use std::cmp::Ordering; use std::collections::{BTreeMap, VecDeque}; #[derive(Debug)] pub struct Group { pub extents: [Vector2<u32>; 2], pub tiles: BTreeMap<TileRef, G2dTexture>, pub images: BTreeMap<Vector2<u32>, Image>, pub cache_todo: [VecDeque<Vector2<u32>>; 2], pub thumb_todo: [VecDeque<Vector2<u32>>; 2], } impl Group { pub fn new(extents: [Vector2<u32>; 2]) -> Self { Self { extents, tiles: BTreeMap::new(), images: BTreeMap::new(), cache_todo: [VecDeque::new(), VecDeque::new()], thumb_todo: [VecDeque::new(), VecDeque::new()], } } pub fn insert(&mut self, coords: Vector2<u32>, image: Image) { self.images.insert(coords, image); } pub fn reset(&mut self) { for image in self.images.values_mut() { image.reset(); } self.tiles.clear(); for queue in &mut self.cache_todo { queue.clear(); } for queue in &mut self.thumb_todo { queue.clear(); } } pub fn recheck(&mut self, view: &View) { for queue in &mut self.thumb_todo { queue.clear(); } for queue in &mut self.cache_todo { queue.clear(); } let mut mouse_dist: Vec<(&Vector2<u32>, &Image)> = Vec::with_capacity(self.images.len()); mouse_dist.extend(self.images.iter()); mouse_dist.sort_by_key(|(&coords, _)| vec2_square_len(view.mouse_dist(coords)) as isize); for (&coords, image) in &mouse_dist { let p =!view.is_visible(view.trans(coords)) as usize; match image.metadata { MetadataState::Some(_) => { self.cache_todo[p].push_back(coords); } MetadataState::Missing => { self.thumb_todo[p].push_back(coords); } MetadataState::Errored => continue, } } } pub fn load_cache( &mut self, p: usize, view: &View, db: &Database, texture_context: &mut G2dTextureContext, stopwatch: &Stopwatch, ) -> bool { let _s3 = ScopedDuration::new("Group::load_cache"); let target_size = view.target_size(); let texture_settings = TextureSettings::new(); while let Some(coords) = self.cache_todo[p].pop_front() { let image = self.images.get_mut(&coords).unwrap(); let metadata = image.get_metadata().expect("Image::get_metadata"); let view_coords = view.trans(coords); let shift = if p == 0 { 0 } else { let ratio = view.visible_ratio(view_coords); f64::max(0.0, ratio - 1.0).floor() as usize }; let new_size = metadata.nearest(target_size >> shift); let current_size = image.size.unwrap_or(0); // Progressive resizing. let new_size = match new_size.cmp(&current_size) { Ordering::Less => current_size - 1, Ordering::Equal => { // Already loaded target size. continue; } Ordering::Greater => current_size + 1, }; // Load new tiles. for tile_ref in &metadata.thumbs[new_size].tile_refs { // Already loaded. if self.tiles.contains_key(tile_ref) { continue; } if stopwatch.done() { self.cache_todo[p].push_front(coords); return false; } let data = db.get(*tile_ref).expect("db get").expect("missing tile");
let image = ::image::load_from_memory(&data).expect("load image"); // TODO: Would be great to move off thread. let image = Texture::from_image(texture_context, &image.to_rgba(), &texture_settings) .expect("texture"); self.tiles.insert(*tile_ref, image); } // Unload old tiles. for (j, thumb) in metadata.thumbs.iter().enumerate() { if j == new_size { continue; } for tile_ref in &thumb.tile_refs { self.tiles.remove(tile_ref); } } image.size = Some(new_size); self.cache_todo[p].push_back(coords); } true } pub fn make_thumbs(&mut self, p: usize, thumbnailer: &mut crate::Thumbnailer) -> bool { loop { if thumbnailer.is_full() { return false; } if let Some(coords) = self.thumb_todo[p].pop_front() { let image = self.images.get(&coords).unwrap(); if!thumbnailer.make_thumbs(image) { return false; } } else { break true; } } } pub fn update_metadata(&mut self, coords: Vector2<u32>, metadata_res: R<Metadata>) { let image = self.images.get_mut(&coords).unwrap(); image.metadata = match metadata_res { Ok(metadata) => { self.cache_todo[0].push_front(coords); MetadataState::Some(metadata) } Err(e) => { error!("make_thumb: {}", e); MetadataState::Errored } }; } pub fn draw(&self, trans: [[f64; 3]; 2], view: &View, draw_state: &DrawState, g: &mut G2d) { //{ // let [min, max] = self.extents; // let op_color = color::hex("FF0000"); // let [x, y] = view.trans(min); // let [w, h] = vec2_scale(vec2_f64(vec2_sub(max, min)), view.zoom); // let trans = trans.trans(x, y); // rectangle(op_color, [0.0, 0.0, w, 1.0], trans, g); // rectangle(op_color, [0.0, 0.0, 1.0, h], trans, g); // rectangle(op_color, [w, 0.0, 1.0, h], trans, g); // rectangle(op_color, [0.0, h, w, 1.0], trans, g); //} let dot_color = color::hex("444444"); let mid_zoom = view.zoom * 0.5; for (&coords, image) in &self.images { let coords = view.trans(coords); if!view.is_visible(coords) { continue; } let trans = trans.trans(coords[0], coords[1]); if image.draw(trans, view, &self.tiles, &draw_state, g) { continue; } else { rectangle(dot_color, [mid_zoom, mid_zoom, 1.0, 1.0], trans, g); } } } pub fn mouse_dist(&self, view: &View) -> usize { let midpoint = vec2_div(vec2_add(self.extents[0], self.extents[1]), [2, 2]); let mouse_dist = view.mouse_dist(midpoint); vec2_square_len(mouse_dist) as usize } }
random_line_split
keys.rs
use crypto; use crypto::mac::Mac; use gmp::Mpz; use num::FromPrimitive; use rand; use std::io::Write; use util; lazy_static! { static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap(); static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ]); } pub struct PrivateKeys { private_key: Mpz, public_key: Mpz, } pub struct SharedKeys { //private: PrivateKeys, challenge: Vec<u8>, send_key: Vec<u8>, recv_key: Vec<u8> } impl PrivateKeys { pub fn new() -> PrivateKeys { let key_data = util::rand_vec(&mut rand::thread_rng(), 95); Self::new_with_key(&key_data) } pub fn new_with_key(key_data: &[u8]) -> PrivateKeys { let private_key = Mpz::from_bytes_be(key_data); let public_key = DH_GENERATOR.powm(&private_key, &DH_PRIME); PrivateKeys { private_key: private_key, public_key: public_key, } } /* pub fn private_key(&self) -> Vec<u8> { return self.private_key.to_bytes_be(); } */ pub fn public_key(&self) -> Vec<u8> { return self.public_key.to_bytes_be(); } pub fn add_remote_key(self, remote_key: &[u8], client_packet: &[u8], server_packet: &[u8]) -> SharedKeys { let shared_key = Mpz::from_bytes_be(remote_key).powm(&self.private_key, &DH_PRIME); let mut data = Vec::with_capacity(0x64); let mut mac = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &shared_key.to_bytes_be()); for i in 1..6 { mac.input(client_packet); mac.input(server_packet); mac.input(&[i]); data.write(&mac.result().code()).unwrap(); mac.reset(); } mac = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &data[..0x14]); mac.input(client_packet); mac.input(server_packet); SharedKeys { //private: self, challenge: mac.result().code().to_vec(), send_key: data[0x14..0x34].to_vec(), recv_key: data[0x34..0x54].to_vec(), } } } impl SharedKeys { pub fn challenge(&self) -> &[u8] { &self.challenge } pub fn send_key(&self) -> &[u8] { &self.send_key }
}
pub fn recv_key(&self) -> &[u8] { &self.recv_key }
random_line_split
keys.rs
use crypto; use crypto::mac::Mac; use gmp::Mpz; use num::FromPrimitive; use rand; use std::io::Write; use util; lazy_static! { static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap(); static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ]); } pub struct PrivateKeys { private_key: Mpz, public_key: Mpz, } pub struct SharedKeys { //private: PrivateKeys, challenge: Vec<u8>, send_key: Vec<u8>, recv_key: Vec<u8> } impl PrivateKeys { pub fn
() -> PrivateKeys { let key_data = util::rand_vec(&mut rand::thread_rng(), 95); Self::new_with_key(&key_data) } pub fn new_with_key(key_data: &[u8]) -> PrivateKeys { let private_key = Mpz::from_bytes_be(key_data); let public_key = DH_GENERATOR.powm(&private_key, &DH_PRIME); PrivateKeys { private_key: private_key, public_key: public_key, } } /* pub fn private_key(&self) -> Vec<u8> { return self.private_key.to_bytes_be(); } */ pub fn public_key(&self) -> Vec<u8> { return self.public_key.to_bytes_be(); } pub fn add_remote_key(self, remote_key: &[u8], client_packet: &[u8], server_packet: &[u8]) -> SharedKeys { let shared_key = Mpz::from_bytes_be(remote_key).powm(&self.private_key, &DH_PRIME); let mut data = Vec::with_capacity(0x64); let mut mac = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &shared_key.to_bytes_be()); for i in 1..6 { mac.input(client_packet); mac.input(server_packet); mac.input(&[i]); data.write(&mac.result().code()).unwrap(); mac.reset(); } mac = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &data[..0x14]); mac.input(client_packet); mac.input(server_packet); SharedKeys { //private: self, challenge: mac.result().code().to_vec(), send_key: data[0x14..0x34].to_vec(), recv_key: data[0x34..0x54].to_vec(), } } } impl SharedKeys { pub fn challenge(&self) -> &[u8] { &self.challenge } pub fn send_key(&self) -> &[u8] { &self.send_key } pub fn recv_key(&self) -> &[u8] { &self.recv_key } }
new
identifier_name
keys.rs
use crypto; use crypto::mac::Mac; use gmp::Mpz; use num::FromPrimitive; use rand; use std::io::Write; use util; lazy_static! { static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap(); static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ]); } pub struct PrivateKeys { private_key: Mpz, public_key: Mpz, } pub struct SharedKeys { //private: PrivateKeys, challenge: Vec<u8>, send_key: Vec<u8>, recv_key: Vec<u8> } impl PrivateKeys { pub fn new() -> PrivateKeys { let key_data = util::rand_vec(&mut rand::thread_rng(), 95); Self::new_with_key(&key_data) } pub fn new_with_key(key_data: &[u8]) -> PrivateKeys { let private_key = Mpz::from_bytes_be(key_data); let public_key = DH_GENERATOR.powm(&private_key, &DH_PRIME); PrivateKeys { private_key: private_key, public_key: public_key, } } /* pub fn private_key(&self) -> Vec<u8> { return self.private_key.to_bytes_be(); } */ pub fn public_key(&self) -> Vec<u8> { return self.public_key.to_bytes_be(); } pub fn add_remote_key(self, remote_key: &[u8], client_packet: &[u8], server_packet: &[u8]) -> SharedKeys { let shared_key = Mpz::from_bytes_be(remote_key).powm(&self.private_key, &DH_PRIME); let mut data = Vec::with_capacity(0x64); let mut mac = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &shared_key.to_bytes_be()); for i in 1..6 { mac.input(client_packet); mac.input(server_packet); mac.input(&[i]); data.write(&mac.result().code()).unwrap(); mac.reset(); } mac = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &data[..0x14]); mac.input(client_packet); mac.input(server_packet); SharedKeys { //private: self, challenge: mac.result().code().to_vec(), send_key: data[0x14..0x34].to_vec(), recv_key: data[0x34..0x54].to_vec(), } } } impl SharedKeys { pub fn challenge(&self) -> &[u8] { &self.challenge } pub fn send_key(&self) -> &[u8] { &self.send_key } pub fn recv_key(&self) -> &[u8]
}
{ &self.recv_key }
identifier_body
metadata.rs
extern crate env_logger; extern crate gluon_base as base; extern crate gluon_parser as parser; extern crate gluon_check as check; use base::metadata::{Metadata, MetadataEnv}; use base::symbol::Symbol; use check::metadata::metadata; mod support; struct MockEnv; impl MetadataEnv for MockEnv { fn get_metadata(&self, _id: &Symbol) -> Option<&Metadata> { None } } #[test] fn propagate_metadata_let_in() { let _ = env_logger::init(); let text = r#" /// The identity function let id x = x id "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata, Metadata { comment: Some("The identity function".into()), module: Default::default(), }); } #[test] fn propagate_metadata_let_record()
#[test] fn propagate_metadata_type_record() { let _ = env_logger::init(); let text = r#" /// A test type type Test = Int { Test } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata.module.get("Test"), Some(&Metadata { comment: Some("A test type".into()), module: Default::default(), })); }
{ let _ = env_logger::init(); let text = r#" /// The identity function let id x = x { id } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata.module.get("id"), Some(&Metadata { comment: Some("The identity function".into()), module: Default::default(), })); }
identifier_body
metadata.rs
extern crate env_logger; extern crate gluon_base as base; extern crate gluon_parser as parser; extern crate gluon_check as check; use base::metadata::{Metadata, MetadataEnv}; use base::symbol::Symbol; use check::metadata::metadata; mod support; struct
; impl MetadataEnv for MockEnv { fn get_metadata(&self, _id: &Symbol) -> Option<&Metadata> { None } } #[test] fn propagate_metadata_let_in() { let _ = env_logger::init(); let text = r#" /// The identity function let id x = x id "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata, Metadata { comment: Some("The identity function".into()), module: Default::default(), }); } #[test] fn propagate_metadata_let_record() { let _ = env_logger::init(); let text = r#" /// The identity function let id x = x { id } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata.module.get("id"), Some(&Metadata { comment: Some("The identity function".into()), module: Default::default(), })); } #[test] fn propagate_metadata_type_record() { let _ = env_logger::init(); let text = r#" /// A test type type Test = Int { Test } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata.module.get("Test"), Some(&Metadata { comment: Some("A test type".into()), module: Default::default(), })); }
MockEnv
identifier_name
metadata.rs
extern crate env_logger; extern crate gluon_base as base; extern crate gluon_parser as parser; extern crate gluon_check as check; use base::metadata::{Metadata, MetadataEnv}; use base::symbol::Symbol; use check::metadata::metadata; mod support; struct MockEnv; impl MetadataEnv for MockEnv { fn get_metadata(&self, _id: &Symbol) -> Option<&Metadata> { None
let _ = env_logger::init(); let text = r#" /// The identity function let id x = x id "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata, Metadata { comment: Some("The identity function".into()), module: Default::default(), }); } #[test] fn propagate_metadata_let_record() { let _ = env_logger::init(); let text = r#" /// The identity function let id x = x { id } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata.module.get("id"), Some(&Metadata { comment: Some("The identity function".into()), module: Default::default(), })); } #[test] fn propagate_metadata_type_record() { let _ = env_logger::init(); let text = r#" /// A test type type Test = Int { Test } "#; let (mut expr, result) = support::typecheck_expr(text); assert!(result.is_ok(), "{}", result.unwrap_err()); let metadata = metadata(&MockEnv, &mut expr); assert_eq!(metadata.module.get("Test"), Some(&Metadata { comment: Some("A test type".into()), module: Default::default(), })); }
} } #[test] fn propagate_metadata_let_in() {
random_line_split
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, CrateVariancesMap, TyCtxt}; /// Defines the `TermsContext` basically houses an arena where we can /// allocate terms. mod terms; /// Code to gather up constraints. mod constraints; /// Code to solve constraints and write out the results. mod solve; /// Code to write unit tests of variance. pub mod test; /// Code for transforming variances. mod xform; pub fn provide(providers: &mut Providers)
fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> { let arena = DroplessArena::default(); let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena); let constraints_cx = constraints::add_constraints_from_crate(terms_cx); solve::solve_constraints(constraints_cx) } fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] { let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local()); let unsupported = || { // Variance not relevant. span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item") }; match tcx.hir().get(id) { Node::Item(item) => match item.kind { hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Fn(..) => {} _ => unsupported(), }, Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Fn(..) => {} _ => unsupported(), }, Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Fn(..) => {} _ => unsupported(), }, Node::ForeignItem(item) => match item.kind { hir::ForeignItemKind::Fn(..) => {} _ => unsupported(), }, Node::Variant(_) | Node::Ctor(..) => {} _ => unsupported(), } // Everything else must be inferred. let crate_map = tcx.crate_variances(()); crate_map.variances.get(&item_def_id).copied().unwrap_or(&[]) }
{ *providers = Providers { variances_of, crate_variances, ..*providers }; }
identifier_body
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, CrateVariancesMap, TyCtxt}; /// Defines the `TermsContext` basically houses an arena where we can /// allocate terms. mod terms; /// Code to gather up constraints. mod constraints; /// Code to solve constraints and write out the results. mod solve; /// Code to write unit tests of variance. pub mod test; /// Code for transforming variances. mod xform; pub fn provide(providers: &mut Providers) { *providers = Providers { variances_of, crate_variances,..*providers }; } fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> { let arena = DroplessArena::default(); let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena); let constraints_cx = constraints::add_constraints_from_crate(terms_cx); solve::solve_constraints(constraints_cx) } fn
(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] { let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local()); let unsupported = || { // Variance not relevant. span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item") }; match tcx.hir().get(id) { Node::Item(item) => match item.kind { hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Fn(..) => {} _ => unsupported(), }, Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Fn(..) => {} _ => unsupported(), }, Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Fn(..) => {} _ => unsupported(), }, Node::ForeignItem(item) => match item.kind { hir::ForeignItemKind::Fn(..) => {} _ => unsupported(), }, Node::Variant(_) | Node::Ctor(..) => {} _ => unsupported(), } // Everything else must be inferred. let crate_map = tcx.crate_variances(()); crate_map.variances.get(&item_def_id).copied().unwrap_or(&[]) }
variances_of
identifier_name
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, CrateVariancesMap, TyCtxt}; /// Defines the `TermsContext` basically houses an arena where we can /// allocate terms. mod terms; /// Code to gather up constraints. mod constraints; /// Code to solve constraints and write out the results. mod solve; /// Code to write unit tests of variance. pub mod test; /// Code for transforming variances. mod xform; pub fn provide(providers: &mut Providers) { *providers = Providers { variances_of, crate_variances,..*providers }; } fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> { let arena = DroplessArena::default(); let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena); let constraints_cx = constraints::add_constraints_from_crate(terms_cx); solve::solve_constraints(constraints_cx) } fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] { let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local()); let unsupported = || { // Variance not relevant. span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item") }; match tcx.hir().get(id) { Node::Item(item) => match item.kind { hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Fn(..) => {} _ => unsupported(), }, Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Fn(..) =>
_ => unsupported(), }, Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Fn(..) => {} _ => unsupported(), }, Node::ForeignItem(item) => match item.kind { hir::ForeignItemKind::Fn(..) => {} _ => unsupported(), }, Node::Variant(_) | Node::Ctor(..) => {} _ => unsupported(), } // Everything else must be inferred. let crate_map = tcx.crate_variances(()); crate_map.variances.get(&item_def_id).copied().unwrap_or(&[]) }
{}
conditional_block
mod.rs
//! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide] //! chapter for more info. //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html use hir::Node; use rustc_arena::DroplessArena; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, CrateVariancesMap, TyCtxt}; /// Defines the `TermsContext` basically houses an arena where we can /// allocate terms. mod terms; /// Code to gather up constraints. mod constraints; /// Code to solve constraints and write out the results. mod solve; /// Code to write unit tests of variance. pub mod test; /// Code for transforming variances. mod xform; pub fn provide(providers: &mut Providers) { *providers = Providers { variances_of, crate_variances,..*providers }; } fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> { let arena = DroplessArena::default(); let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena); let constraints_cx = constraints::add_constraints_from_crate(terms_cx); solve::solve_constraints(constraints_cx) } fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] { let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local()); let unsupported = || { // Variance not relevant. span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item") }; match tcx.hir().get(id) { Node::Item(item) => match item.kind { hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Fn(..) => {} _ => unsupported(), }, Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Fn(..) => {} _ => unsupported(), }, Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Fn(..) => {} _ => unsupported(), }, Node::ForeignItem(item) => match item.kind { hir::ForeignItemKind::Fn(..) => {} _ => unsupported(), }, Node::Variant(_) | Node::Ctor(..) => {}
_ => unsupported(), } // Everything else must be inferred. let crate_map = tcx.crate_variances(()); crate_map.variances.get(&item_def_id).copied().unwrap_or(&[]) }
random_line_split
prf.rs
// Copyright 2020 The Tink-Rust 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. // //////////////////////////////////////////////////////////////////////////////// //! Pseudo-random function. /// The `Prf` trait is an abstraction for an element of a pseudo random /// function family, selected by a key. It has the following property: /// * It is deterministic. `compute_prf(input, length)` will always return the same output if the /// same key is used. `compute_prf(input, length1)` will be a prefix of `compute_prf(input, /// length2)` if `length1` < `length2` and the same key is used. /// * It is indistinguishable from a random function: Given the evaluation of n different inputs, /// an attacker cannot distinguish between the PRF and random bytes on an input different from /// the n that are known. /// Use cases for PRF are deterministic redaction of PII, keyed hash functions, /// creating sub IDs that do not allow joining with the original dataset without /// knowing the key. /// While PRFs can be used in order to prove authenticity of a message, using the /// [`Mac`](crate::Mac) interface is recommended for that use case, as it has support for /// verification, avoiding the security problems that often happen during /// verification, and having automatic support for key rotation. It also allows /// for non-deterministic MAC algorithms. pub trait Prf: PrfBoxClone { /// Compute the PRF selected by the underlying key on input and /// returns the first `output_length` bytes. /// When choosing this parameter keep the birthday paradox in mind. /// If you have 2^n different inputs that your system has to handle /// set the output length (in bytes) to at least /// ceil(n/4 + 4) /// This corresponds to 2*n + 32 bits, meaning a collision will occur with /// a probability less than 1:2^32. When in doubt, request a security review. /// Returns a non ok status if the algorithm fails or if the output of /// algorithm is less than outputLength. fn compute_prf(&self, input: &[u8], output_length: usize) -> Result<Vec<u8>, crate::TinkError>; } /// Trait bound to indicate that primitive trait objects should support cloning /// themselves as trait objects. pub trait PrfBoxClone { fn box_clone(&self) -> Box<dyn Prf>; } /// Default implementation of the box-clone trait bound for any underlying /// concrete type that implements [`Clone`]. impl<T> PrfBoxClone for T where T:'static + Prf + Clone, { fn box_clone(&self) -> Box<dyn Prf>
}
{ Box::new(self.clone()) }
identifier_body
prf.rs
// Copyright 2020 The Tink-Rust 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. // //////////////////////////////////////////////////////////////////////////////// //! Pseudo-random function. /// The `Prf` trait is an abstraction for an element of a pseudo random /// function family, selected by a key. It has the following property: /// * It is deterministic. `compute_prf(input, length)` will always return the same output if the /// same key is used. `compute_prf(input, length1)` will be a prefix of `compute_prf(input, /// length2)` if `length1` < `length2` and the same key is used. /// * It is indistinguishable from a random function: Given the evaluation of n different inputs, /// an attacker cannot distinguish between the PRF and random bytes on an input different from /// the n that are known. /// Use cases for PRF are deterministic redaction of PII, keyed hash functions, /// creating sub IDs that do not allow joining with the original dataset without /// knowing the key. /// While PRFs can be used in order to prove authenticity of a message, using the /// [`Mac`](crate::Mac) interface is recommended for that use case, as it has support for /// verification, avoiding the security problems that often happen during /// verification, and having automatic support for key rotation. It also allows /// for non-deterministic MAC algorithms. pub trait Prf: PrfBoxClone { /// Compute the PRF selected by the underlying key on input and /// returns the first `output_length` bytes. /// When choosing this parameter keep the birthday paradox in mind. /// If you have 2^n different inputs that your system has to handle /// set the output length (in bytes) to at least /// ceil(n/4 + 4) /// This corresponds to 2*n + 32 bits, meaning a collision will occur with /// a probability less than 1:2^32. When in doubt, request a security review. /// Returns a non ok status if the algorithm fails or if the output of /// algorithm is less than outputLength. fn compute_prf(&self, input: &[u8], output_length: usize) -> Result<Vec<u8>, crate::TinkError>; } /// Trait bound to indicate that primitive trait objects should support cloning /// themselves as trait objects. pub trait PrfBoxClone { fn box_clone(&self) -> Box<dyn Prf>; } /// Default implementation of the box-clone trait bound for any underlying /// concrete type that implements [`Clone`]. impl<T> PrfBoxClone for T where T:'static + Prf + Clone, { fn
(&self) -> Box<dyn Prf> { Box::new(self.clone()) } }
box_clone
identifier_name
prf.rs
// Copyright 2020 The Tink-Rust 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. // //////////////////////////////////////////////////////////////////////////////// //! Pseudo-random function.
/// same key is used. `compute_prf(input, length1)` will be a prefix of `compute_prf(input, /// length2)` if `length1` < `length2` and the same key is used. /// * It is indistinguishable from a random function: Given the evaluation of n different inputs, /// an attacker cannot distinguish between the PRF and random bytes on an input different from /// the n that are known. /// Use cases for PRF are deterministic redaction of PII, keyed hash functions, /// creating sub IDs that do not allow joining with the original dataset without /// knowing the key. /// While PRFs can be used in order to prove authenticity of a message, using the /// [`Mac`](crate::Mac) interface is recommended for that use case, as it has support for /// verification, avoiding the security problems that often happen during /// verification, and having automatic support for key rotation. It also allows /// for non-deterministic MAC algorithms. pub trait Prf: PrfBoxClone { /// Compute the PRF selected by the underlying key on input and /// returns the first `output_length` bytes. /// When choosing this parameter keep the birthday paradox in mind. /// If you have 2^n different inputs that your system has to handle /// set the output length (in bytes) to at least /// ceil(n/4 + 4) /// This corresponds to 2*n + 32 bits, meaning a collision will occur with /// a probability less than 1:2^32. When in doubt, request a security review. /// Returns a non ok status if the algorithm fails or if the output of /// algorithm is less than outputLength. fn compute_prf(&self, input: &[u8], output_length: usize) -> Result<Vec<u8>, crate::TinkError>; } /// Trait bound to indicate that primitive trait objects should support cloning /// themselves as trait objects. pub trait PrfBoxClone { fn box_clone(&self) -> Box<dyn Prf>; } /// Default implementation of the box-clone trait bound for any underlying /// concrete type that implements [`Clone`]. impl<T> PrfBoxClone for T where T:'static + Prf + Clone, { fn box_clone(&self) -> Box<dyn Prf> { Box::new(self.clone()) } }
/// The `Prf` trait is an abstraction for an element of a pseudo random /// function family, selected by a key. It has the following property: /// * It is deterministic. `compute_prf(input, length)` will always return the same output if the
random_line_split
infinite-loops.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 simple way to make sure threading works. This should use all the CPU cycles an any machines that we're likely to see for a while. */ // ignore-test fn loopy(n: isize) { if n > 0
loop { } } pub fn main() { // Commenting this out, as this will hang forever otherwise. // Even after seeing the comment above, I'm not sure what the // intention of this test is. // spawn(move|| { loopy(5) }); }
{ spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); }
conditional_block
infinite-loops.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// // 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 simple way to make sure threading works. This should use all the CPU cycles an any machines that we're likely to see for a while. */ // ignore-test fn loopy(n: isize) { if n > 0 { spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); } loop { } } pub fn main() { // Commenting this out, as this will hang forever otherwise. // Even after seeing the comment above, I'm not sure what the // intention of this test is. // spawn(move|| { loopy(5) }); }
// http://rust-lang.org/COPYRIGHT.
random_line_split
infinite-loops.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 simple way to make sure threading works. This should use all the CPU cycles an any machines that we're likely to see for a while. */ // ignore-test fn loopy(n: isize) { if n > 0 { spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); } loop { } } pub fn main()
{ // Commenting this out, as this will hang forever otherwise. // Even after seeing the comment above, I'm not sure what the // intention of this test is. // spawn(move|| { loopy(5) }); }
identifier_body
infinite-loops.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 simple way to make sure threading works. This should use all the CPU cycles an any machines that we're likely to see for a while. */ // ignore-test fn
(n: isize) { if n > 0 { spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); } loop { } } pub fn main() { // Commenting this out, as this will hang forever otherwise. // Even after seeing the comment above, I'm not sure what the // intention of this test is. // spawn(move|| { loopy(5) }); }
loopy
identifier_name
lib.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![doc( html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png" )] //! <p>Amazon Lex provides both build and runtime endpoints. Each endpoint provides a set of operations (API). Your conversational bot uses the runtime API to understand user utterances (user input text or voice). For example, suppose a user says "I want pizza", your bot sends this input to Amazon Lex using the runtime API. Amazon Lex recognizes that the user request is for the OrderPizza intent (one of the intents defined in the bot). Then Amazon Lex engages in user conversation on behalf of the bot to elicit required information (slot values, such as pizza size and crust type), and then performs fulfillment activity (that you configured when you created the bot). You use the build-time API to create and manage your Amazon Lex bot. For a list of build-time operations, see the build-time API,. </p> //! //! If you're using the service, you're probably looking for [LexRuntimeClient](struct.LexRuntimeClient.html) and [LexRuntime](trait.LexRuntime.html). mod custom; mod generated;
pub use custom::*; pub use generated::*;
random_line_split
deriving-via-extension-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(PartialEq, Show)] struct Foo {
pub fn main() { let a = Foo { x: 1, y: 2, z: 3 }; let b = Foo { x: 1, y: 2, z: 3 }; assert_eq!(a, b); assert!(!(a!= b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); }
x: int, y: int, z: int, }
random_line_split
deriving-via-extension-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(PartialEq, Show)] struct Foo { x: int, y: int, z: int, } pub fn
() { let a = Foo { x: 1, y: 2, z: 3 }; let b = Foo { x: 1, y: 2, z: 3 }; assert_eq!(a, b); assert!(!(a!= b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); }
main
identifier_name
buffer_map.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 std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; use layers::platform::surface::NativePaintingGraphicsContext; use layers::layers::LayerBuffer; use std::hash::{Hash, Hasher}; use std::mem; /// This is a struct used to store buffers when they are not in use. /// The paint task can quickly query for a particular size of buffer when it /// needs it.
mem: usize, /// The maximum allowed memory. Unused buffers will be deleted /// when this threshold is exceeded. max_mem: usize, /// A monotonically increasing counter to track how recently tile sizes were used. counter: usize, } /// A key with which to store buffers. It is based on the size of the buffer. #[derive(Eq, Copy, Clone)] struct BufferKey([usize; 2]); impl Hash for BufferKey { fn hash<H: Hasher>(&self, state: &mut H) { let BufferKey(ref bytes) = *self; bytes.hash(state); } } impl PartialEq for BufferKey { fn eq(&self, other: &BufferKey) -> bool { let BufferKey(s) = *self; let BufferKey(o) = *other; s[0] == o[0] && s[1] == o[1] } } /// Create a key from a given size impl BufferKey { fn get(input: Size2D<usize>) -> BufferKey { BufferKey([input.width, input.height]) } } /// A helper struct to keep track of buffers in the HashMap struct BufferValue { /// An array of buffers, all the same size buffers: Vec<Box<LayerBuffer>>, /// The counter when this size was last requested last_action: usize, } impl BufferMap { // Creates a new BufferMap with a given buffer limit. pub fn new(max_mem: usize) -> BufferMap { BufferMap { map: HashMap::new(), mem: 0, max_mem: max_mem, counter: 0, } } /// Insert a new buffer into the map. pub fn insert(&mut self, graphics_context: &NativePaintingGraphicsContext, new_buffer: Box<LayerBuffer>) { let new_key = BufferKey::get(new_buffer.get_size_2d()); // If all our buffers are the same size and we're already at our // memory limit, no need to store this new buffer; just let it drop. if self.mem + new_buffer.get_mem() > self.max_mem && self.map.len() == 1 && self.map.contains_key(&new_key) { new_buffer.destroy(graphics_context); return; } self.mem += new_buffer.get_mem(); // use lazy insertion function to prevent unnecessary allocation let counter = &self.counter; match self.map.entry(new_key) { Occupied(entry) => { entry.into_mut().buffers.push(new_buffer); } Vacant(entry) => { entry.insert(BufferValue { buffers: vec!(new_buffer), last_action: *counter, }); } } let mut opt_key: Option<BufferKey> = None; while self.mem > self.max_mem { let old_key = match opt_key { Some(key) => key, None => { match self.map.iter().min_by(|&(_, x)| x.last_action) { Some((k, _)) => *k, None => panic!("BufferMap: tried to delete with no elements in map"), } } }; if { let list = &mut self.map.get_mut(&old_key).unwrap().buffers; let condemned_buffer = list.pop().take().unwrap(); self.mem -= condemned_buffer.get_mem(); condemned_buffer.destroy(graphics_context); list.is_empty() } { // then self.map.remove(&old_key); // Don't store empty vectors! opt_key = None; } else { opt_key = Some(old_key); } } } // Try to find a buffer for the given size. pub fn find(&mut self, size: Size2D<usize>) -> Option<Box<LayerBuffer>> { let mut flag = false; // True if key needs to be popped after retrieval. let key = BufferKey::get(size); let ret = match self.map.get_mut(&key) { Some(ref mut buffer_val) => { buffer_val.last_action = self.counter; self.counter += 1; let buffer = buffer_val.buffers.pop().take().unwrap(); self.mem -= buffer.get_mem(); if buffer_val.buffers.is_empty() { flag = true; } Some(buffer) } None => None, }; if flag { self.map.remove(&key); // Don't store empty vectors! } ret } /// Destroys all buffers. pub fn clear(&mut self, graphics_context: &NativePaintingGraphicsContext) { let map = mem::replace(&mut self.map, HashMap::new()); for (_, value) in map.into_iter() { for tile in value.buffers.into_iter() { tile.destroy(graphics_context) } } self.mem = 0 } }
pub struct BufferMap { /// A HashMap that stores the Buffers. map: HashMap<BufferKey, BufferValue>, /// The current amount of memory stored by the BufferMap's buffers.
random_line_split
buffer_map.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 std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; use layers::platform::surface::NativePaintingGraphicsContext; use layers::layers::LayerBuffer; use std::hash::{Hash, Hasher}; use std::mem; /// This is a struct used to store buffers when they are not in use. /// The paint task can quickly query for a particular size of buffer when it /// needs it. pub struct BufferMap { /// A HashMap that stores the Buffers. map: HashMap<BufferKey, BufferValue>, /// The current amount of memory stored by the BufferMap's buffers. mem: usize, /// The maximum allowed memory. Unused buffers will be deleted /// when this threshold is exceeded. max_mem: usize, /// A monotonically increasing counter to track how recently tile sizes were used. counter: usize, } /// A key with which to store buffers. It is based on the size of the buffer. #[derive(Eq, Copy, Clone)] struct BufferKey([usize; 2]); impl Hash for BufferKey { fn hash<H: Hasher>(&self, state: &mut H) { let BufferKey(ref bytes) = *self; bytes.hash(state); } } impl PartialEq for BufferKey { fn eq(&self, other: &BufferKey) -> bool { let BufferKey(s) = *self; let BufferKey(o) = *other; s[0] == o[0] && s[1] == o[1] } } /// Create a key from a given size impl BufferKey { fn get(input: Size2D<usize>) -> BufferKey { BufferKey([input.width, input.height]) } } /// A helper struct to keep track of buffers in the HashMap struct BufferValue { /// An array of buffers, all the same size buffers: Vec<Box<LayerBuffer>>, /// The counter when this size was last requested last_action: usize, } impl BufferMap { // Creates a new BufferMap with a given buffer limit. pub fn new(max_mem: usize) -> BufferMap { BufferMap { map: HashMap::new(), mem: 0, max_mem: max_mem, counter: 0, } } /// Insert a new buffer into the map. pub fn insert(&mut self, graphics_context: &NativePaintingGraphicsContext, new_buffer: Box<LayerBuffer>) { let new_key = BufferKey::get(new_buffer.get_size_2d()); // If all our buffers are the same size and we're already at our // memory limit, no need to store this new buffer; just let it drop. if self.mem + new_buffer.get_mem() > self.max_mem && self.map.len() == 1 && self.map.contains_key(&new_key) { new_buffer.destroy(graphics_context); return; } self.mem += new_buffer.get_mem(); // use lazy insertion function to prevent unnecessary allocation let counter = &self.counter; match self.map.entry(new_key) { Occupied(entry) => { entry.into_mut().buffers.push(new_buffer); } Vacant(entry) => { entry.insert(BufferValue { buffers: vec!(new_buffer), last_action: *counter, }); } } let mut opt_key: Option<BufferKey> = None; while self.mem > self.max_mem { let old_key = match opt_key { Some(key) => key, None =>
}; if { let list = &mut self.map.get_mut(&old_key).unwrap().buffers; let condemned_buffer = list.pop().take().unwrap(); self.mem -= condemned_buffer.get_mem(); condemned_buffer.destroy(graphics_context); list.is_empty() } { // then self.map.remove(&old_key); // Don't store empty vectors! opt_key = None; } else { opt_key = Some(old_key); } } } // Try to find a buffer for the given size. pub fn find(&mut self, size: Size2D<usize>) -> Option<Box<LayerBuffer>> { let mut flag = false; // True if key needs to be popped after retrieval. let key = BufferKey::get(size); let ret = match self.map.get_mut(&key) { Some(ref mut buffer_val) => { buffer_val.last_action = self.counter; self.counter += 1; let buffer = buffer_val.buffers.pop().take().unwrap(); self.mem -= buffer.get_mem(); if buffer_val.buffers.is_empty() { flag = true; } Some(buffer) } None => None, }; if flag { self.map.remove(&key); // Don't store empty vectors! } ret } /// Destroys all buffers. pub fn clear(&mut self, graphics_context: &NativePaintingGraphicsContext) { let map = mem::replace(&mut self.map, HashMap::new()); for (_, value) in map.into_iter() { for tile in value.buffers.into_iter() { tile.destroy(graphics_context) } } self.mem = 0 } }
{ match self.map.iter().min_by(|&(_, x)| x.last_action) { Some((k, _)) => *k, None => panic!("BufferMap: tried to delete with no elements in map"), } }
conditional_block
buffer_map.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 std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; use layers::platform::surface::NativePaintingGraphicsContext; use layers::layers::LayerBuffer; use std::hash::{Hash, Hasher}; use std::mem; /// This is a struct used to store buffers when they are not in use. /// The paint task can quickly query for a particular size of buffer when it /// needs it. pub struct BufferMap { /// A HashMap that stores the Buffers. map: HashMap<BufferKey, BufferValue>, /// The current amount of memory stored by the BufferMap's buffers. mem: usize, /// The maximum allowed memory. Unused buffers will be deleted /// when this threshold is exceeded. max_mem: usize, /// A monotonically increasing counter to track how recently tile sizes were used. counter: usize, } /// A key with which to store buffers. It is based on the size of the buffer. #[derive(Eq, Copy, Clone)] struct BufferKey([usize; 2]); impl Hash for BufferKey { fn hash<H: Hasher>(&self, state: &mut H) { let BufferKey(ref bytes) = *self; bytes.hash(state); } } impl PartialEq for BufferKey { fn eq(&self, other: &BufferKey) -> bool { let BufferKey(s) = *self; let BufferKey(o) = *other; s[0] == o[0] && s[1] == o[1] } } /// Create a key from a given size impl BufferKey { fn get(input: Size2D<usize>) -> BufferKey { BufferKey([input.width, input.height]) } } /// A helper struct to keep track of buffers in the HashMap struct
{ /// An array of buffers, all the same size buffers: Vec<Box<LayerBuffer>>, /// The counter when this size was last requested last_action: usize, } impl BufferMap { // Creates a new BufferMap with a given buffer limit. pub fn new(max_mem: usize) -> BufferMap { BufferMap { map: HashMap::new(), mem: 0, max_mem: max_mem, counter: 0, } } /// Insert a new buffer into the map. pub fn insert(&mut self, graphics_context: &NativePaintingGraphicsContext, new_buffer: Box<LayerBuffer>) { let new_key = BufferKey::get(new_buffer.get_size_2d()); // If all our buffers are the same size and we're already at our // memory limit, no need to store this new buffer; just let it drop. if self.mem + new_buffer.get_mem() > self.max_mem && self.map.len() == 1 && self.map.contains_key(&new_key) { new_buffer.destroy(graphics_context); return; } self.mem += new_buffer.get_mem(); // use lazy insertion function to prevent unnecessary allocation let counter = &self.counter; match self.map.entry(new_key) { Occupied(entry) => { entry.into_mut().buffers.push(new_buffer); } Vacant(entry) => { entry.insert(BufferValue { buffers: vec!(new_buffer), last_action: *counter, }); } } let mut opt_key: Option<BufferKey> = None; while self.mem > self.max_mem { let old_key = match opt_key { Some(key) => key, None => { match self.map.iter().min_by(|&(_, x)| x.last_action) { Some((k, _)) => *k, None => panic!("BufferMap: tried to delete with no elements in map"), } } }; if { let list = &mut self.map.get_mut(&old_key).unwrap().buffers; let condemned_buffer = list.pop().take().unwrap(); self.mem -= condemned_buffer.get_mem(); condemned_buffer.destroy(graphics_context); list.is_empty() } { // then self.map.remove(&old_key); // Don't store empty vectors! opt_key = None; } else { opt_key = Some(old_key); } } } // Try to find a buffer for the given size. pub fn find(&mut self, size: Size2D<usize>) -> Option<Box<LayerBuffer>> { let mut flag = false; // True if key needs to be popped after retrieval. let key = BufferKey::get(size); let ret = match self.map.get_mut(&key) { Some(ref mut buffer_val) => { buffer_val.last_action = self.counter; self.counter += 1; let buffer = buffer_val.buffers.pop().take().unwrap(); self.mem -= buffer.get_mem(); if buffer_val.buffers.is_empty() { flag = true; } Some(buffer) } None => None, }; if flag { self.map.remove(&key); // Don't store empty vectors! } ret } /// Destroys all buffers. pub fn clear(&mut self, graphics_context: &NativePaintingGraphicsContext) { let map = mem::replace(&mut self.map, HashMap::new()); for (_, value) in map.into_iter() { for tile in value.buffers.into_iter() { tile.destroy(graphics_context) } } self.mem = 0 } }
BufferValue
identifier_name
engine_aware.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use crate::core::Value; use crate::externs; use crate::nodes::{lift_directory_digest, lift_file_digest}; use crate::Failure; use crate::Types; use cpython::{PyDict, PyString, Python}; use workunit_store::{ArtifactOutput, Level}; // TODO all `retrieve` implementations should add a check that the `Value` actually subclasses // `EngineAware` pub trait EngineAwareInformation { type MaybeOutput; fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput>; } pub struct EngineAwareLevel {} impl EngineAwareInformation for EngineAwareLevel { type MaybeOutput = Level; fn retrieve(_types: &Types, value: &Value) -> Option<Level> { let new_level_val = externs::call_method(value.as_ref(), "level", &[]).ok()?; let new_level_val = externs::check_for_python_none(new_level_val)?; externs::val_to_log_level(&new_level_val).ok() } } pub struct Message {} impl EngineAwareInformation for Message { type MaybeOutput = String; fn retrieve(_types: &Types, value: &Value) -> Option<String> { let msg_val = externs::call_method(&value, "message", &[]).ok()?; let msg_val = externs::check_for_python_none(msg_val)?; Some(externs::val_to_str(&msg_val)) } } pub struct Metadata; impl EngineAwareInformation for Metadata { type MaybeOutput = Vec<(String, Value)>; fn retrieve(_types: &Types, value: &Value) -> Option<Self::MaybeOutput> { let metadata_val = match externs::call_method(&value, "metadata", &[]) { Ok(value) => value, Err(py_err) => { let failure = Failure::from_py_err(py_err); log::error!("Error calling `metadata` method: {}", failure); return None; } }; let metadata_val = externs::check_for_python_none(metadata_val)?; let gil = Python::acquire_gil(); let py = gil.python(); let mut output = Vec::new(); let metadata_dict: &PyDict = metadata_val.cast_as::<PyDict>(py).ok()?; for (key, value) in metadata_dict.items(py).into_iter() { let key_name: String = match key.extract(py) { Ok(s) => s, Err(e) => { log::error!( "Error in EngineAware.metadata() implementation - non-string key: {:?}", e ); return None; } }; output.push((key_name, Value::from(value))); } Some(output) } } pub struct Artifacts {} impl EngineAwareInformation for Artifacts { type MaybeOutput = Vec<(String, ArtifactOutput)>; fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput> { let artifacts_val = match externs::call_method(&value, "artifacts", &[]) { Ok(value) => value, Err(py_err) => { let failure = Failure::from_py_err(py_err); log::error!("Error calling `artifacts` method: {}", failure); return None; } }; let artifacts_val = externs::check_for_python_none(artifacts_val)?; let gil = Python::acquire_gil(); let py = gil.python(); let artifacts_dict: &PyDict = artifacts_val.cast_as::<PyDict>(py).ok()?; let mut output = Vec::new(); for (key, value) in artifacts_dict.items(py).into_iter() { let key_name: String = match key.cast_as::<PyString>(py) { Ok(s) => s.to_string_lossy(py).into(), Err(e) => { log::error!( "Error in EngineAware.artifacts() implementation - non-string key: {:?}", e ); return None; } }; let artifact_output = if externs::get_type_for(&value) == types.file_digest { match lift_file_digest(&types, &value) { Ok(digest) => ArtifactOutput::FileDigest(digest), Err(e) => { log::error!("Error in EngineAware.artifacts() implementation: {}", e); return None; } } } else { let digest_value = externs::getattr(&value, "digest") .map_err(|e| { log::error!("Error in EngineAware.artifacts() - no `digest` attr: {}", e); }) .ok()?; match lift_directory_digest(&Value::new(digest_value)) { Ok(digest) => ArtifactOutput::Snapshot(digest), Err(e) => { log::error!("Error in EngineAware.artifacts() implementation: {}", e);
}; output.push((key_name, artifact_output)); } Some(output) } } pub struct DebugHint {} impl EngineAwareInformation for DebugHint { type MaybeOutput = String; fn retrieve(_types: &Types, value: &Value) -> Option<String> { externs::call_method(&value, "debug_hint", &[]) .ok() .and_then(externs::check_for_python_none) .map(|val| externs::val_to_str(&val)) } }
return None; } }
random_line_split
engine_aware.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use crate::core::Value; use crate::externs; use crate::nodes::{lift_directory_digest, lift_file_digest}; use crate::Failure; use crate::Types; use cpython::{PyDict, PyString, Python}; use workunit_store::{ArtifactOutput, Level}; // TODO all `retrieve` implementations should add a check that the `Value` actually subclasses // `EngineAware` pub trait EngineAwareInformation { type MaybeOutput; fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput>; } pub struct EngineAwareLevel {} impl EngineAwareInformation for EngineAwareLevel { type MaybeOutput = Level; fn
(_types: &Types, value: &Value) -> Option<Level> { let new_level_val = externs::call_method(value.as_ref(), "level", &[]).ok()?; let new_level_val = externs::check_for_python_none(new_level_val)?; externs::val_to_log_level(&new_level_val).ok() } } pub struct Message {} impl EngineAwareInformation for Message { type MaybeOutput = String; fn retrieve(_types: &Types, value: &Value) -> Option<String> { let msg_val = externs::call_method(&value, "message", &[]).ok()?; let msg_val = externs::check_for_python_none(msg_val)?; Some(externs::val_to_str(&msg_val)) } } pub struct Metadata; impl EngineAwareInformation for Metadata { type MaybeOutput = Vec<(String, Value)>; fn retrieve(_types: &Types, value: &Value) -> Option<Self::MaybeOutput> { let metadata_val = match externs::call_method(&value, "metadata", &[]) { Ok(value) => value, Err(py_err) => { let failure = Failure::from_py_err(py_err); log::error!("Error calling `metadata` method: {}", failure); return None; } }; let metadata_val = externs::check_for_python_none(metadata_val)?; let gil = Python::acquire_gil(); let py = gil.python(); let mut output = Vec::new(); let metadata_dict: &PyDict = metadata_val.cast_as::<PyDict>(py).ok()?; for (key, value) in metadata_dict.items(py).into_iter() { let key_name: String = match key.extract(py) { Ok(s) => s, Err(e) => { log::error!( "Error in EngineAware.metadata() implementation - non-string key: {:?}", e ); return None; } }; output.push((key_name, Value::from(value))); } Some(output) } } pub struct Artifacts {} impl EngineAwareInformation for Artifacts { type MaybeOutput = Vec<(String, ArtifactOutput)>; fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput> { let artifacts_val = match externs::call_method(&value, "artifacts", &[]) { Ok(value) => value, Err(py_err) => { let failure = Failure::from_py_err(py_err); log::error!("Error calling `artifacts` method: {}", failure); return None; } }; let artifacts_val = externs::check_for_python_none(artifacts_val)?; let gil = Python::acquire_gil(); let py = gil.python(); let artifacts_dict: &PyDict = artifacts_val.cast_as::<PyDict>(py).ok()?; let mut output = Vec::new(); for (key, value) in artifacts_dict.items(py).into_iter() { let key_name: String = match key.cast_as::<PyString>(py) { Ok(s) => s.to_string_lossy(py).into(), Err(e) => { log::error!( "Error in EngineAware.artifacts() implementation - non-string key: {:?}", e ); return None; } }; let artifact_output = if externs::get_type_for(&value) == types.file_digest { match lift_file_digest(&types, &value) { Ok(digest) => ArtifactOutput::FileDigest(digest), Err(e) => { log::error!("Error in EngineAware.artifacts() implementation: {}", e); return None; } } } else { let digest_value = externs::getattr(&value, "digest") .map_err(|e| { log::error!("Error in EngineAware.artifacts() - no `digest` attr: {}", e); }) .ok()?; match lift_directory_digest(&Value::new(digest_value)) { Ok(digest) => ArtifactOutput::Snapshot(digest), Err(e) => { log::error!("Error in EngineAware.artifacts() implementation: {}", e); return None; } } }; output.push((key_name, artifact_output)); } Some(output) } } pub struct DebugHint {} impl EngineAwareInformation for DebugHint { type MaybeOutput = String; fn retrieve(_types: &Types, value: &Value) -> Option<String> { externs::call_method(&value, "debug_hint", &[]) .ok() .and_then(externs::check_for_python_none) .map(|val| externs::val_to_str(&val)) } }
retrieve
identifier_name
engine_aware.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use crate::core::Value; use crate::externs; use crate::nodes::{lift_directory_digest, lift_file_digest}; use crate::Failure; use crate::Types; use cpython::{PyDict, PyString, Python}; use workunit_store::{ArtifactOutput, Level}; // TODO all `retrieve` implementations should add a check that the `Value` actually subclasses // `EngineAware` pub trait EngineAwareInformation { type MaybeOutput; fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput>; } pub struct EngineAwareLevel {} impl EngineAwareInformation for EngineAwareLevel { type MaybeOutput = Level; fn retrieve(_types: &Types, value: &Value) -> Option<Level> { let new_level_val = externs::call_method(value.as_ref(), "level", &[]).ok()?; let new_level_val = externs::check_for_python_none(new_level_val)?; externs::val_to_log_level(&new_level_val).ok() } } pub struct Message {} impl EngineAwareInformation for Message { type MaybeOutput = String; fn retrieve(_types: &Types, value: &Value) -> Option<String> { let msg_val = externs::call_method(&value, "message", &[]).ok()?; let msg_val = externs::check_for_python_none(msg_val)?; Some(externs::val_to_str(&msg_val)) } } pub struct Metadata; impl EngineAwareInformation for Metadata { type MaybeOutput = Vec<(String, Value)>; fn retrieve(_types: &Types, value: &Value) -> Option<Self::MaybeOutput> { let metadata_val = match externs::call_method(&value, "metadata", &[]) { Ok(value) => value, Err(py_err) => { let failure = Failure::from_py_err(py_err); log::error!("Error calling `metadata` method: {}", failure); return None; } }; let metadata_val = externs::check_for_python_none(metadata_val)?; let gil = Python::acquire_gil(); let py = gil.python(); let mut output = Vec::new(); let metadata_dict: &PyDict = metadata_val.cast_as::<PyDict>(py).ok()?; for (key, value) in metadata_dict.items(py).into_iter() { let key_name: String = match key.extract(py) { Ok(s) => s, Err(e) =>
}; output.push((key_name, Value::from(value))); } Some(output) } } pub struct Artifacts {} impl EngineAwareInformation for Artifacts { type MaybeOutput = Vec<(String, ArtifactOutput)>; fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput> { let artifacts_val = match externs::call_method(&value, "artifacts", &[]) { Ok(value) => value, Err(py_err) => { let failure = Failure::from_py_err(py_err); log::error!("Error calling `artifacts` method: {}", failure); return None; } }; let artifacts_val = externs::check_for_python_none(artifacts_val)?; let gil = Python::acquire_gil(); let py = gil.python(); let artifacts_dict: &PyDict = artifacts_val.cast_as::<PyDict>(py).ok()?; let mut output = Vec::new(); for (key, value) in artifacts_dict.items(py).into_iter() { let key_name: String = match key.cast_as::<PyString>(py) { Ok(s) => s.to_string_lossy(py).into(), Err(e) => { log::error!( "Error in EngineAware.artifacts() implementation - non-string key: {:?}", e ); return None; } }; let artifact_output = if externs::get_type_for(&value) == types.file_digest { match lift_file_digest(&types, &value) { Ok(digest) => ArtifactOutput::FileDigest(digest), Err(e) => { log::error!("Error in EngineAware.artifacts() implementation: {}", e); return None; } } } else { let digest_value = externs::getattr(&value, "digest") .map_err(|e| { log::error!("Error in EngineAware.artifacts() - no `digest` attr: {}", e); }) .ok()?; match lift_directory_digest(&Value::new(digest_value)) { Ok(digest) => ArtifactOutput::Snapshot(digest), Err(e) => { log::error!("Error in EngineAware.artifacts() implementation: {}", e); return None; } } }; output.push((key_name, artifact_output)); } Some(output) } } pub struct DebugHint {} impl EngineAwareInformation for DebugHint { type MaybeOutput = String; fn retrieve(_types: &Types, value: &Value) -> Option<String> { externs::call_method(&value, "debug_hint", &[]) .ok() .and_then(externs::check_for_python_none) .map(|val| externs::val_to_str(&val)) } }
{ log::error!( "Error in EngineAware.metadata() implementation - non-string key: {:?}", e ); return None; }
conditional_block
generator-yielding-or-returning-itself.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. #![feature(generator_trait)] #![feature(generators)] // Test that we cannot create a generator that returns a value of its // own type. use std::ops::Generator; pub fn want_cyclic_generator_return<T>(_: T) where T: Generator<Yield = (), Return = T> { } fn supply_cyclic_generator_return()
pub fn want_cyclic_generator_yield<T>(_: T) where T: Generator<Yield = T, Return = ()> { } fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() { }
{ want_cyclic_generator_return(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) }
identifier_body
generator-yielding-or-returning-itself.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. #![feature(generator_trait)] #![feature(generators)] // Test that we cannot create a generator that returns a value of its // own type. use std::ops::Generator; pub fn want_cyclic_generator_return<T>(_: T) where T: Generator<Yield = (), Return = T> { } fn supply_cyclic_generator_return() { want_cyclic_generator_return(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } pub fn
<T>(_: T) where T: Generator<Yield = T, Return = ()> { } fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() { }
want_cyclic_generator_yield
identifier_name
generator-yielding-or-returning-itself.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. #![feature(generator_trait)] #![feature(generators)] // Test that we cannot create a generator that returns a value of its // own type. use std::ops::Generator; pub fn want_cyclic_generator_return<T>(_: T) where T: Generator<Yield = (), Return = T> { } fn supply_cyclic_generator_return() { want_cyclic_generator_return(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } pub fn want_cyclic_generator_yield<T>(_: T)
fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() { }
where T: Generator<Yield = T, Return = ()> { }
random_line_split
generator-yielding-or-returning-itself.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. #![feature(generator_trait)] #![feature(generators)] // Test that we cannot create a generator that returns a value of its // own type. use std::ops::Generator; pub fn want_cyclic_generator_return<T>(_: T) where T: Generator<Yield = (), Return = T> { } fn supply_cyclic_generator_return() { want_cyclic_generator_return(|| { //~^ ERROR type mismatch if false
None.unwrap() }) } pub fn want_cyclic_generator_yield<T>(_: T) where T: Generator<Yield = T, Return = ()> { } fn supply_cyclic_generator_yield() { want_cyclic_generator_yield(|| { //~^ ERROR type mismatch if false { yield None.unwrap(); } None.unwrap() }) } fn main() { }
{ yield None.unwrap(); }
conditional_block
errors.rs
use next_swc::{ disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic, }; use std::path::PathBuf; use swc_common::FileName; use swc_ecma_transforms_testing::test_fixture_allowing_error; use swc_ecmascript::parser::{EsConfig, Syntax}; use testing::fixture; fn syntax() -> Syntax { Syntax::Es(EsConfig { jsx: true,
}) } #[fixture("tests/errors/re-export-all-in-page/**/input.js")] fn re_export_all_in_page(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| disallow_re_export_all_in_page(true), &input, &output, ); } #[fixture("tests/errors/next-dynamic/**/input.js")] fn next_dynamic_errors(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| { next_dynamic( FileName::Real(PathBuf::from("/some-project/src/some-file.js")), Some("/some-project/src".into()), ) }, &input, &output, ); }
..Default::default()
random_line_split
errors.rs
use next_swc::{ disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic, }; use std::path::PathBuf; use swc_common::FileName; use swc_ecma_transforms_testing::test_fixture_allowing_error; use swc_ecmascript::parser::{EsConfig, Syntax}; use testing::fixture; fn syntax() -> Syntax
#[fixture("tests/errors/re-export-all-in-page/**/input.js")] fn re_export_all_in_page(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| disallow_re_export_all_in_page(true), &input, &output, ); } #[fixture("tests/errors/next-dynamic/**/input.js")] fn next_dynamic_errors(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| { next_dynamic( FileName::Real(PathBuf::from("/some-project/src/some-file.js")), Some("/some-project/src".into()), ) }, &input, &output, ); }
{ Syntax::Es(EsConfig { jsx: true, ..Default::default() }) }
identifier_body
errors.rs
use next_swc::{ disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic, }; use std::path::PathBuf; use swc_common::FileName; use swc_ecma_transforms_testing::test_fixture_allowing_error; use swc_ecmascript::parser::{EsConfig, Syntax}; use testing::fixture; fn
() -> Syntax { Syntax::Es(EsConfig { jsx: true, ..Default::default() }) } #[fixture("tests/errors/re-export-all-in-page/**/input.js")] fn re_export_all_in_page(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| disallow_re_export_all_in_page(true), &input, &output, ); } #[fixture("tests/errors/next-dynamic/**/input.js")] fn next_dynamic_errors(input: PathBuf) { let output = input.parent().unwrap().join("output.js"); test_fixture_allowing_error( syntax(), &|_tr| { next_dynamic( FileName::Real(PathBuf::from("/some-project/src/some-file.js")), Some("/some-project/src".into()), ) }, &input, &output, ); }
syntax
identifier_name
wheelevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::codegen::Bindings::WheelEventBinding; use crate::dom::bindings::codegen::Bindings::WheelEventBinding::WheelEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::mouseevent::MouseEvent; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; #[dom_struct] pub struct WheelEvent { mouseevent: MouseEvent, delta_x: Cell<Finite<f64>>, delta_y: Cell<Finite<f64>>, delta_z: Cell<Finite<f64>>, delta_mode: Cell<u32>, } impl WheelEvent { fn new_inherited() -> WheelEvent { WheelEvent { mouseevent: MouseEvent::new_inherited(), delta_x: Cell::new(Finite::wrap(0.0)), delta_y: Cell::new(Finite::wrap(0.0)), delta_z: Cell::new(Finite::wrap(0.0)), delta_mode: Cell::new(0), } } pub fn new_unintialized(window: &Window) -> DomRoot<WheelEvent> { reflect_dom_object( Box::new(WheelEvent::new_inherited()), window, WheelEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32, delta_x: Finite<f64>, delta_y: Finite<f64>, delta_z: Finite<f64>, delta_mode: u32, ) -> DomRoot<WheelEvent> { let ev = WheelEvent::new_unintialized(window); ev.InitWheelEvent( type_, bool::from(can_bubble), bool::from(cancelable), view, detail, delta_x, delta_y, delta_z, delta_mode, ); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &WheelEventBinding::WheelEventInit, ) -> Fallible<DomRoot<WheelEvent>> { let event = WheelEvent::new( window, type_, EventBubbles::from(init.parent.parent.parent.parent.bubbles), EventCancelable::from(init.parent.parent.parent.parent.cancelable), init.parent.parent.parent.view.as_deref(), init.parent.parent.parent.detail, init.deltaX, init.deltaY, init.deltaZ, init.deltaMode, ); Ok(event) } } impl WheelEventMethods for WheelEvent { // https://w3c.github.io/uievents/#widl-WheelEvent-deltaX fn DeltaX(&self) -> Finite<f64> { self.delta_x.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaY fn DeltaY(&self) -> Finite<f64>
// https://w3c.github.io/uievents/#widl-WheelEvent-deltaZ fn DeltaZ(&self) -> Finite<f64> { self.delta_z.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaMode fn DeltaMode(&self) -> u32 { self.delta_mode.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-initWheelEvent fn InitWheelEvent( &self, type_arg: DOMString, can_bubble_arg: bool, cancelable_arg: bool, view_arg: Option<&Window>, detail_arg: i32, delta_x_arg: Finite<f64>, delta_y_arg: Finite<f64>, delta_z_arg: Finite<f64>, delta_mode_arg: u32, ) { if self.upcast::<Event>().dispatching() { return; } self.upcast::<MouseEvent>().InitMouseEvent( type_arg, can_bubble_arg, cancelable_arg, view_arg, detail_arg, self.mouseevent.ScreenX(), self.mouseevent.ScreenY(), self.mouseevent.ClientX(), self.mouseevent.ClientY(), self.mouseevent.CtrlKey(), self.mouseevent.AltKey(), self.mouseevent.ShiftKey(), self.mouseevent.MetaKey(), self.mouseevent.Button(), self.mouseevent.GetRelatedTarget().as_deref(), ); self.delta_x.set(delta_x_arg); self.delta_y.set(delta_y_arg); self.delta_z.set(delta_z_arg); self.delta_mode.set(delta_mode_arg); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.mouseevent.IsTrusted() } }
{ self.delta_y.get() }
identifier_body
wheelevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::codegen::Bindings::WheelEventBinding; use crate::dom::bindings::codegen::Bindings::WheelEventBinding::WheelEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::mouseevent::MouseEvent; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; #[dom_struct] pub struct WheelEvent { mouseevent: MouseEvent, delta_x: Cell<Finite<f64>>, delta_y: Cell<Finite<f64>>, delta_z: Cell<Finite<f64>>, delta_mode: Cell<u32>, } impl WheelEvent { fn new_inherited() -> WheelEvent { WheelEvent { mouseevent: MouseEvent::new_inherited(), delta_x: Cell::new(Finite::wrap(0.0)), delta_y: Cell::new(Finite::wrap(0.0)), delta_z: Cell::new(Finite::wrap(0.0)), delta_mode: Cell::new(0), } } pub fn new_unintialized(window: &Window) -> DomRoot<WheelEvent> { reflect_dom_object( Box::new(WheelEvent::new_inherited()), window, WheelEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32, delta_x: Finite<f64>, delta_y: Finite<f64>, delta_z: Finite<f64>, delta_mode: u32, ) -> DomRoot<WheelEvent> { let ev = WheelEvent::new_unintialized(window); ev.InitWheelEvent( type_, bool::from(can_bubble), bool::from(cancelable), view, detail, delta_x, delta_y, delta_z, delta_mode, ); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &WheelEventBinding::WheelEventInit, ) -> Fallible<DomRoot<WheelEvent>> { let event = WheelEvent::new( window, type_, EventBubbles::from(init.parent.parent.parent.parent.bubbles), EventCancelable::from(init.parent.parent.parent.parent.cancelable), init.parent.parent.parent.view.as_deref(), init.parent.parent.parent.detail, init.deltaX, init.deltaY, init.deltaZ, init.deltaMode, ); Ok(event) } } impl WheelEventMethods for WheelEvent { // https://w3c.github.io/uievents/#widl-WheelEvent-deltaX fn DeltaX(&self) -> Finite<f64> { self.delta_x.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaY fn DeltaY(&self) -> Finite<f64> { self.delta_y.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaZ fn DeltaZ(&self) -> Finite<f64> { self.delta_z.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaMode fn DeltaMode(&self) -> u32 { self.delta_mode.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-initWheelEvent fn InitWheelEvent( &self, type_arg: DOMString, can_bubble_arg: bool, cancelable_arg: bool, view_arg: Option<&Window>, detail_arg: i32, delta_x_arg: Finite<f64>, delta_y_arg: Finite<f64>, delta_z_arg: Finite<f64>, delta_mode_arg: u32, ) { if self.upcast::<Event>().dispatching()
self.upcast::<MouseEvent>().InitMouseEvent( type_arg, can_bubble_arg, cancelable_arg, view_arg, detail_arg, self.mouseevent.ScreenX(), self.mouseevent.ScreenY(), self.mouseevent.ClientX(), self.mouseevent.ClientY(), self.mouseevent.CtrlKey(), self.mouseevent.AltKey(), self.mouseevent.ShiftKey(), self.mouseevent.MetaKey(), self.mouseevent.Button(), self.mouseevent.GetRelatedTarget().as_deref(), ); self.delta_x.set(delta_x_arg); self.delta_y.set(delta_y_arg); self.delta_z.set(delta_z_arg); self.delta_mode.set(delta_mode_arg); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.mouseevent.IsTrusted() } }
{ return; }
conditional_block
wheelevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::codegen::Bindings::WheelEventBinding; use crate::dom::bindings::codegen::Bindings::WheelEventBinding::WheelEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::mouseevent::MouseEvent; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; #[dom_struct] pub struct WheelEvent { mouseevent: MouseEvent, delta_x: Cell<Finite<f64>>, delta_y: Cell<Finite<f64>>, delta_z: Cell<Finite<f64>>, delta_mode: Cell<u32>, } impl WheelEvent { fn new_inherited() -> WheelEvent { WheelEvent { mouseevent: MouseEvent::new_inherited(), delta_x: Cell::new(Finite::wrap(0.0)), delta_y: Cell::new(Finite::wrap(0.0)), delta_z: Cell::new(Finite::wrap(0.0)), delta_mode: Cell::new(0), } } pub fn new_unintialized(window: &Window) -> DomRoot<WheelEvent> { reflect_dom_object( Box::new(WheelEvent::new_inherited()), window, WheelEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32, delta_x: Finite<f64>, delta_y: Finite<f64>, delta_z: Finite<f64>, delta_mode: u32, ) -> DomRoot<WheelEvent> { let ev = WheelEvent::new_unintialized(window); ev.InitWheelEvent( type_, bool::from(can_bubble), bool::from(cancelable), view, detail, delta_x, delta_y, delta_z, delta_mode, ); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &WheelEventBinding::WheelEventInit, ) -> Fallible<DomRoot<WheelEvent>> { let event = WheelEvent::new( window, type_, EventBubbles::from(init.parent.parent.parent.parent.bubbles), EventCancelable::from(init.parent.parent.parent.parent.cancelable), init.parent.parent.parent.view.as_deref(), init.parent.parent.parent.detail, init.deltaX, init.deltaY, init.deltaZ, init.deltaMode, ); Ok(event) } } impl WheelEventMethods for WheelEvent { // https://w3c.github.io/uievents/#widl-WheelEvent-deltaX fn DeltaX(&self) -> Finite<f64> { self.delta_x.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaY fn DeltaY(&self) -> Finite<f64> { self.delta_y.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaZ fn DeltaZ(&self) -> Finite<f64> { self.delta_z.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaMode fn DeltaMode(&self) -> u32 { self.delta_mode.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-initWheelEvent fn InitWheelEvent( &self, type_arg: DOMString, can_bubble_arg: bool, cancelable_arg: bool, view_arg: Option<&Window>, detail_arg: i32, delta_x_arg: Finite<f64>, delta_y_arg: Finite<f64>, delta_z_arg: Finite<f64>, delta_mode_arg: u32, ) { if self.upcast::<Event>().dispatching() { return; } self.upcast::<MouseEvent>().InitMouseEvent( type_arg, can_bubble_arg, cancelable_arg, view_arg, detail_arg, self.mouseevent.ScreenX(), self.mouseevent.ScreenY(), self.mouseevent.ClientX(), self.mouseevent.ClientY(), self.mouseevent.CtrlKey(), self.mouseevent.AltKey(), self.mouseevent.ShiftKey(), self.mouseevent.MetaKey(), self.mouseevent.Button(), self.mouseevent.GetRelatedTarget().as_deref(), );
self.delta_y.set(delta_y_arg); self.delta_z.set(delta_z_arg); self.delta_mode.set(delta_mode_arg); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.mouseevent.IsTrusted() } }
self.delta_x.set(delta_x_arg);
random_line_split
wheelevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use crate::dom::bindings::codegen::Bindings::WheelEventBinding; use crate::dom::bindings::codegen::Bindings::WheelEventBinding::WheelEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::mouseevent::MouseEvent; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; #[dom_struct] pub struct WheelEvent { mouseevent: MouseEvent, delta_x: Cell<Finite<f64>>, delta_y: Cell<Finite<f64>>, delta_z: Cell<Finite<f64>>, delta_mode: Cell<u32>, } impl WheelEvent { fn new_inherited() -> WheelEvent { WheelEvent { mouseevent: MouseEvent::new_inherited(), delta_x: Cell::new(Finite::wrap(0.0)), delta_y: Cell::new(Finite::wrap(0.0)), delta_z: Cell::new(Finite::wrap(0.0)), delta_mode: Cell::new(0), } } pub fn new_unintialized(window: &Window) -> DomRoot<WheelEvent> { reflect_dom_object( Box::new(WheelEvent::new_inherited()), window, WheelEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32, delta_x: Finite<f64>, delta_y: Finite<f64>, delta_z: Finite<f64>, delta_mode: u32, ) -> DomRoot<WheelEvent> { let ev = WheelEvent::new_unintialized(window); ev.InitWheelEvent( type_, bool::from(can_bubble), bool::from(cancelable), view, detail, delta_x, delta_y, delta_z, delta_mode, ); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &WheelEventBinding::WheelEventInit, ) -> Fallible<DomRoot<WheelEvent>> { let event = WheelEvent::new( window, type_, EventBubbles::from(init.parent.parent.parent.parent.bubbles), EventCancelable::from(init.parent.parent.parent.parent.cancelable), init.parent.parent.parent.view.as_deref(), init.parent.parent.parent.detail, init.deltaX, init.deltaY, init.deltaZ, init.deltaMode, ); Ok(event) } } impl WheelEventMethods for WheelEvent { // https://w3c.github.io/uievents/#widl-WheelEvent-deltaX fn DeltaX(&self) -> Finite<f64> { self.delta_x.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaY fn DeltaY(&self) -> Finite<f64> { self.delta_y.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaZ fn DeltaZ(&self) -> Finite<f64> { self.delta_z.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-deltaMode fn
(&self) -> u32 { self.delta_mode.get() } // https://w3c.github.io/uievents/#widl-WheelEvent-initWheelEvent fn InitWheelEvent( &self, type_arg: DOMString, can_bubble_arg: bool, cancelable_arg: bool, view_arg: Option<&Window>, detail_arg: i32, delta_x_arg: Finite<f64>, delta_y_arg: Finite<f64>, delta_z_arg: Finite<f64>, delta_mode_arg: u32, ) { if self.upcast::<Event>().dispatching() { return; } self.upcast::<MouseEvent>().InitMouseEvent( type_arg, can_bubble_arg, cancelable_arg, view_arg, detail_arg, self.mouseevent.ScreenX(), self.mouseevent.ScreenY(), self.mouseevent.ClientX(), self.mouseevent.ClientY(), self.mouseevent.CtrlKey(), self.mouseevent.AltKey(), self.mouseevent.ShiftKey(), self.mouseevent.MetaKey(), self.mouseevent.Button(), self.mouseevent.GetRelatedTarget().as_deref(), ); self.delta_x.set(delta_x_arg); self.delta_y.set(delta_y_arg); self.delta_z.set(delta_z_arg); self.delta_mode.set(delta_mode_arg); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.mouseevent.IsTrusted() } }
DeltaMode
identifier_name
unboxed-closure-sugar-region.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test interaction between unboxed closure sugar and region // parameters (should be exactly as if angle brackets were used // and regions omitted). #![feature(unboxed_closures)] #![allow(dead_code)] use std::marker; trait Foo<'a,T,U> { fn dummy(&'a self) -> &'a (T,U); } trait Eq<X:?Sized> { } impl<X:?Sized> Eq<X> for X { } fn eq<A:?Sized,B:?Sized +Eq<A>>() { } fn same_type<A,B:Eq<A>>(a: A, b: B)
fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),()>, Foo(isize) >(); } fn test2(x: &Foo<(isize,),()>, y: &Foo(isize)) { // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) //~ ERROR cannot infer } fn main() { }
{ }
identifier_body
unboxed-closure-sugar-region.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test interaction between unboxed closure sugar and region // parameters (should be exactly as if angle brackets were used // and regions omitted). #![feature(unboxed_closures)] #![allow(dead_code)] use std::marker; trait Foo<'a,T,U> { fn dummy(&'a self) -> &'a (T,U); } trait Eq<X:?Sized> { } impl<X:?Sized> Eq<X> for X { } fn eq<A:?Sized,B:?Sized +Eq<A>>() { } fn same_type<A,B:Eq<A>>(a: A, b: B) { } fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),()>, Foo(isize) >(); } fn test2(x: &Foo<(isize,),()>, y: &Foo(isize)) { // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) //~ ERROR cannot infer } fn
() { }
main
identifier_name
unboxed-closure-sugar-region.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test interaction between unboxed closure sugar and region // parameters (should be exactly as if angle brackets were used // and regions omitted). #![feature(unboxed_closures)] #![allow(dead_code)] use std::marker; trait Foo<'a,T,U> { fn dummy(&'a self) -> &'a (T,U); } trait Eq<X:?Sized> { } impl<X:?Sized> Eq<X> for X { } fn eq<A:?Sized,B:?Sized +Eq<A>>() { }
fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),()>, Foo(isize) >(); } fn test2(x: &Foo<(isize,),()>, y: &Foo(isize)) { // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) //~ ERROR cannot infer } fn main() { }
fn same_type<A,B:Eq<A>>(a: A, b: B) { }
random_line_split
group_by.rs
/* Copyright ⓒ 2015 grabbag contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ use std::cell::RefCell; use std::cmp::min; use std::mem::replace; use std::rc::Rc; /** Sequence of iterators containing successive elements of the subject which have the same group according to a group function. */ pub trait GroupByIterator<E>: Iterator<Item=E> + Sized { /** Creates an iterator that yields a succession of `(group, sub_iterator)` pairs. Each `sub_iterator` yields successive elements of the input iterator that have the same `group`. An element's `group` is computed using the `f` closure. For example: ``` # extern crate grabbag; # use grabbag::iter::GroupByIterator; # fn main () { let v = vec![7usize, 5, 6, 2, 4, 7, 6, 1, 6, 4, 4, 6, 0, 0, 8, 8, 6, 1, 8, 7]; let is_even = |n: &usize| if *n & 1 == 0 { true } else { false }; for (even, mut ns) in v.into_iter().group_by(is_even) { println!("{}...", if even { "Evens" } else { "Odds" }); for n in ns { println!(" - {}", n); } } # } ``` */ fn group_by<GroupFn: FnMut(&E) -> G, G>(self, group: GroupFn) -> GroupBy<Self, GroupFn, E, G> { GroupBy { state: Rc::new(RefCell::new(GroupByShared { iter: self, group: group, last_group: None, push_back: None, })), } } } impl<E, It> GroupByIterator<E> for It where It: Iterator<Item=E> {} // **NOTE**: Although `Clone` *can* be implemented for this, you *should not* do so, since you cannot clone the underlying `GroupByItemsShared` value. pub struct GroupBy<It, GroupFn, E, G> { state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>, } pub struct GroupByShared<It, GroupFn, E, G> { iter: It, group: GroupFn, last_group: Option<G>, push_back: Option<(G, E)>, } impl<It, GroupFn, E, G> Iterator for GroupBy<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It: Iterator<Item=E>, G: Clone + Eq { type Item = (G, Group<It, GroupFn, E, G>); fn next(&mut self) -> Option<(G, Group<It, GroupFn, E, G>)> { // First, get a mutable borrow to the underlying state. let mut state = self.state.borrow_mut(); let state = &mut *state; // If we have a push-back element, immediately construct a sub iterator. if let Some((g, e)) = replace(&mut state.push_back, None) { return Some(( g.clone(), Group { state: self.state.clone(), group_value: g, first_value: Some(e), } )); } // Otherwise, try to pull the next element from the input iterator. // Complication: a sub iterator *might* stop *before* the group is exhausted. We need to account for this (so that users can easily skip groups). let (e, g) = match replace(&mut state.last_group, None) { None => { // We don't *have* a previous group, just grab the next element. let e = match state.iter.next() { Some(e) => e, None => return None }; let g = (state.group)(&e); (e, g) }, Some(last_g) => { // We have to keep pulling elements until the group changes. let mut e; let mut g; loop { e = match state.iter.next() { Some(e) => e, None => return None }; g = (state.group)(&e); if g!= last_g { break; } } (e, g) } };
state.last_group = Some(g.clone()); // Construct the sub-iterator and yield it. Some(( g.clone(), Group { state: self.state.clone(), group_value: g, first_value: Some(e), } )) } fn size_hint(&self) -> (usize, Option<usize>) { let (lb, mub) = self.state.borrow().iter.size_hint(); let lb = min(lb, 1); (lb, mub) } } // **NOTE**: Although `Clone` *can* be implemented for this, you *should not* do so, since you cannot clone the underlying `GroupByShared` value. pub struct Group<It, GroupFn, E, G> { state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>, group_value: G, first_value: Option<E>, } impl<It, GroupFn, E, G> Iterator for Group<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It: Iterator<Item=E>, G: Eq { type Item = E; fn next(&mut self) -> Option<E> { // If we have a first_value, consume and yield that. if let Some(e) = replace(&mut self.first_value, None) { return Some(e) } // Get a mutable borrow to the shared state. let mut state = self.state.borrow_mut(); let state = &mut *state; let e = match state.iter.next() { Some(e) => e, None => return None }; let g = (state.group)(&e); match g == self.group_value { true => { // Still in the same group. Some(e) }, false => { // Different group! We need to push (g, e) back into the master iterator. state.push_back = Some((g, e)); None } } } fn size_hint(&self) -> (usize, Option<usize>) { let state = self.state.borrow(); let lb = if self.first_value.is_some() { 1 } else { 0 }; let (_, mub) = state.iter.size_hint(); (lb, mub) } } #[test] fn test_group_by() { { let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7]; let mut oi = v.into_iter().group_by(|&e| e & 1); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(0)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(1)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(2)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(3)); assert_eq!(ii.next(), Some(5)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(4)); assert_eq!(ii.next(), Some(6)); assert_eq!(ii.next(), Some(8)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(7)); assert_eq!(ii.next(), None); assert!(oi.next().is_none()); } { let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7]; let mut oi = v.into_iter().group_by(|&e| e & 1); let (g, _) = oi.next().unwrap(); assert_eq!(g, 0); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); let (g, _) = oi.next().unwrap(); assert_eq!(g, 0); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(4)); assert_eq!(ii.next(), Some(6)); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); assert!(oi.next().is_none()); } }
// Remember this group.
random_line_split
group_by.rs
/* Copyright ⓒ 2015 grabbag contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ use std::cell::RefCell; use std::cmp::min; use std::mem::replace; use std::rc::Rc; /** Sequence of iterators containing successive elements of the subject which have the same group according to a group function. */ pub trait GroupByIterator<E>: Iterator<Item=E> + Sized { /** Creates an iterator that yields a succession of `(group, sub_iterator)` pairs. Each `sub_iterator` yields successive elements of the input iterator that have the same `group`. An element's `group` is computed using the `f` closure. For example: ``` # extern crate grabbag; # use grabbag::iter::GroupByIterator; # fn main () { let v = vec![7usize, 5, 6, 2, 4, 7, 6, 1, 6, 4, 4, 6, 0, 0, 8, 8, 6, 1, 8, 7]; let is_even = |n: &usize| if *n & 1 == 0 { true } else { false }; for (even, mut ns) in v.into_iter().group_by(is_even) { println!("{}...", if even { "Evens" } else { "Odds" }); for n in ns { println!(" - {}", n); } } # } ``` */ fn group_by<GroupFn: FnMut(&E) -> G, G>(self, group: GroupFn) -> GroupBy<Self, GroupFn, E, G> { GroupBy { state: Rc::new(RefCell::new(GroupByShared { iter: self, group: group, last_group: None, push_back: None, })), } } } impl<E, It> GroupByIterator<E> for It where It: Iterator<Item=E> {} // **NOTE**: Although `Clone` *can* be implemented for this, you *should not* do so, since you cannot clone the underlying `GroupByItemsShared` value. pub struct GroupBy<It, GroupFn, E, G> { state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>, } pub struct GroupByShared<It, GroupFn, E, G> { iter: It, group: GroupFn, last_group: Option<G>, push_back: Option<(G, E)>, } impl<It, GroupFn, E, G> Iterator for GroupBy<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It: Iterator<Item=E>, G: Clone + Eq { type Item = (G, Group<It, GroupFn, E, G>); fn next(&mut self) -> Option<(G, Group<It, GroupFn, E, G>)> { // First, get a mutable borrow to the underlying state. let mut state = self.state.borrow_mut(); let state = &mut *state; // If we have a push-back element, immediately construct a sub iterator. if let Some((g, e)) = replace(&mut state.push_back, None) { return Some(( g.clone(), Group { state: self.state.clone(), group_value: g, first_value: Some(e), } )); } // Otherwise, try to pull the next element from the input iterator. // Complication: a sub iterator *might* stop *before* the group is exhausted. We need to account for this (so that users can easily skip groups). let (e, g) = match replace(&mut state.last_group, None) { None => { // We don't *have* a previous group, just grab the next element. let e = match state.iter.next() { Some(e) => e, None => return None }; let g = (state.group)(&e); (e, g) }, Some(last_g) => { // We have to keep pulling elements until the group changes. let mut e; let mut g; loop { e = match state.iter.next() { Some(e) => e, None => return None }; g = (state.group)(&e); if g!= last_g { break; } } (e, g) } }; // Remember this group. state.last_group = Some(g.clone()); // Construct the sub-iterator and yield it. Some(( g.clone(), Group { state: self.state.clone(), group_value: g, first_value: Some(e), } )) } fn size_hint(&self) -> (usize, Option<usize>) { let (lb, mub) = self.state.borrow().iter.size_hint(); let lb = min(lb, 1); (lb, mub) } } // **NOTE**: Although `Clone` *can* be implemented for this, you *should not* do so, since you cannot clone the underlying `GroupByShared` value. pub struct Group<It, GroupFn, E, G> { state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>, group_value: G, first_value: Option<E>, } impl<It, GroupFn, E, G> Iterator for Group<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It: Iterator<Item=E>, G: Eq { type Item = E; fn next(&mut self) -> Option<E> { // If we have a first_value, consume and yield that. if let Some(e) = replace(&mut self.first_value, None) { return Some(e) } // Get a mutable borrow to the shared state. let mut state = self.state.borrow_mut(); let state = &mut *state; let e = match state.iter.next() { Some(e) => e, None => return None }; let g = (state.group)(&e); match g == self.group_value { true => { // Still in the same group. Some(e) }, false => { // Different group! We need to push (g, e) back into the master iterator. state.push_back = Some((g, e)); None } } } fn size_hint(&self) -> (usize, Option<usize>) { let state = self.state.borrow(); let lb = if self.first_value.is_some() { 1 } else { 0 }; let (_, mub) = state.iter.size_hint(); (lb, mub) } } #[test] fn test_group_by() {
assert_eq!(g, 1); assert_eq!(ii.next(), Some(3)); assert_eq!(ii.next(), Some(5)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(4)); assert_eq!(ii.next(), Some(6)); assert_eq!(ii.next(), Some(8)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(7)); assert_eq!(ii.next(), None); assert!(oi.next().is_none()); } { let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7]; let mut oi = v.into_iter().group_by(|&e| e & 1); let (g, _) = oi.next().unwrap(); assert_eq!(g, 0); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); let (g, _) = oi.next().unwrap(); assert_eq!(g, 0); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(4)); assert_eq!(ii.next(), Some(6)); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); assert!(oi.next().is_none()); } }
{ let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7]; let mut oi = v.into_iter().group_by(|&e| e & 1); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(0)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(1)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(2)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap();
identifier_body
group_by.rs
/* Copyright ⓒ 2015 grabbag contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ use std::cell::RefCell; use std::cmp::min; use std::mem::replace; use std::rc::Rc; /** Sequence of iterators containing successive elements of the subject which have the same group according to a group function. */ pub trait GroupByIterator<E>: Iterator<Item=E> + Sized { /** Creates an iterator that yields a succession of `(group, sub_iterator)` pairs. Each `sub_iterator` yields successive elements of the input iterator that have the same `group`. An element's `group` is computed using the `f` closure. For example: ``` # extern crate grabbag; # use grabbag::iter::GroupByIterator; # fn main () { let v = vec![7usize, 5, 6, 2, 4, 7, 6, 1, 6, 4, 4, 6, 0, 0, 8, 8, 6, 1, 8, 7]; let is_even = |n: &usize| if *n & 1 == 0 { true } else { false }; for (even, mut ns) in v.into_iter().group_by(is_even) { println!("{}...", if even { "Evens" } else { "Odds" }); for n in ns { println!(" - {}", n); } } # } ``` */ fn group_by<GroupFn: FnMut(&E) -> G, G>(self, group: GroupFn) -> GroupBy<Self, GroupFn, E, G> { GroupBy { state: Rc::new(RefCell::new(GroupByShared { iter: self, group: group, last_group: None, push_back: None, })), } } } impl<E, It> GroupByIterator<E> for It where It: Iterator<Item=E> {} // **NOTE**: Although `Clone` *can* be implemented for this, you *should not* do so, since you cannot clone the underlying `GroupByItemsShared` value. pub struct Gr
t, GroupFn, E, G> { state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>, } pub struct GroupByShared<It, GroupFn, E, G> { iter: It, group: GroupFn, last_group: Option<G>, push_back: Option<(G, E)>, } impl<It, GroupFn, E, G> Iterator for GroupBy<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It: Iterator<Item=E>, G: Clone + Eq { type Item = (G, Group<It, GroupFn, E, G>); fn next(&mut self) -> Option<(G, Group<It, GroupFn, E, G>)> { // First, get a mutable borrow to the underlying state. let mut state = self.state.borrow_mut(); let state = &mut *state; // If we have a push-back element, immediately construct a sub iterator. if let Some((g, e)) = replace(&mut state.push_back, None) { return Some(( g.clone(), Group { state: self.state.clone(), group_value: g, first_value: Some(e), } )); } // Otherwise, try to pull the next element from the input iterator. // Complication: a sub iterator *might* stop *before* the group is exhausted. We need to account for this (so that users can easily skip groups). let (e, g) = match replace(&mut state.last_group, None) { None => { // We don't *have* a previous group, just grab the next element. let e = match state.iter.next() { Some(e) => e, None => return None }; let g = (state.group)(&e); (e, g) }, Some(last_g) => { // We have to keep pulling elements until the group changes. let mut e; let mut g; loop { e = match state.iter.next() { Some(e) => e, None => return None }; g = (state.group)(&e); if g!= last_g { break; } } (e, g) } }; // Remember this group. state.last_group = Some(g.clone()); // Construct the sub-iterator and yield it. Some(( g.clone(), Group { state: self.state.clone(), group_value: g, first_value: Some(e), } )) } fn size_hint(&self) -> (usize, Option<usize>) { let (lb, mub) = self.state.borrow().iter.size_hint(); let lb = min(lb, 1); (lb, mub) } } // **NOTE**: Although `Clone` *can* be implemented for this, you *should not* do so, since you cannot clone the underlying `GroupByShared` value. pub struct Group<It, GroupFn, E, G> { state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>, group_value: G, first_value: Option<E>, } impl<It, GroupFn, E, G> Iterator for Group<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It: Iterator<Item=E>, G: Eq { type Item = E; fn next(&mut self) -> Option<E> { // If we have a first_value, consume and yield that. if let Some(e) = replace(&mut self.first_value, None) { return Some(e) } // Get a mutable borrow to the shared state. let mut state = self.state.borrow_mut(); let state = &mut *state; let e = match state.iter.next() { Some(e) => e, None => return None }; let g = (state.group)(&e); match g == self.group_value { true => { // Still in the same group. Some(e) }, false => { // Different group! We need to push (g, e) back into the master iterator. state.push_back = Some((g, e)); None } } } fn size_hint(&self) -> (usize, Option<usize>) { let state = self.state.borrow(); let lb = if self.first_value.is_some() { 1 } else { 0 }; let (_, mub) = state.iter.size_hint(); (lb, mub) } } #[test] fn test_group_by() { { let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7]; let mut oi = v.into_iter().group_by(|&e| e & 1); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(0)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(1)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(2)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(3)); assert_eq!(ii.next(), Some(5)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(4)); assert_eq!(ii.next(), Some(6)); assert_eq!(ii.next(), Some(8)); assert_eq!(ii.next(), None); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 1); assert_eq!(ii.next(), Some(7)); assert_eq!(ii.next(), None); assert!(oi.next().is_none()); } { let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7]; let mut oi = v.into_iter().group_by(|&e| e & 1); let (g, _) = oi.next().unwrap(); assert_eq!(g, 0); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); let (g, _) = oi.next().unwrap(); assert_eq!(g, 0); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); let (g, mut ii) = oi.next().unwrap(); assert_eq!(g, 0); assert_eq!(ii.next(), Some(4)); assert_eq!(ii.next(), Some(6)); let (g, _) = oi.next().unwrap(); assert_eq!(g, 1); assert!(oi.next().is_none()); } }
oupBy<I
identifier_name
condvar.rs
use crate::sys::condvar as imp; use crate::sys::mutex as mutex_imp; use crate::sys_common::mutex::MovableMutex; use crate::time::Duration; mod check; type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check; /// An OS-based condition variable. pub struct Condvar { inner: imp::MovableCondvar, check: CondvarCheck, } impl Condvar { /// Creates a new condition variable for use. pub fn new() -> Self { let mut c = imp::MovableCondvar::from(imp::Condvar::new()); unsafe { c.init() }; Self { inner: c, check: CondvarCheck::new() } } /// Signals one waiter on this condition variable to wake up. #[inline] pub fn
(&self) { unsafe { self.inner.notify_one() }; } /// Awakens all current waiters on this condition variable. #[inline] pub fn notify_all(&self) { unsafe { self.inner.notify_all() }; } /// Waits for a signal on the specified mutex. /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wait(&self, mutex: &MovableMutex) { self.check.verify(mutex); self.inner.wait(mutex.raw()) } /// Waits for a signal on the specified mutex with a timeout duration /// specified by `dur` (a relative time into the future). /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wait_timeout(&self, mutex: &MovableMutex, dur: Duration) -> bool { self.check.verify(mutex); self.inner.wait_timeout(mutex.raw(), dur) } } impl Drop for Condvar { fn drop(&mut self) { unsafe { self.inner.destroy() }; } }
notify_one
identifier_name
condvar.rs
use crate::sys::condvar as imp; use crate::sys::mutex as mutex_imp; use crate::sys_common::mutex::MovableMutex; use crate::time::Duration; mod check; type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check; /// An OS-based condition variable. pub struct Condvar { inner: imp::MovableCondvar, check: CondvarCheck, } impl Condvar { /// Creates a new condition variable for use. pub fn new() -> Self { let mut c = imp::MovableCondvar::from(imp::Condvar::new()); unsafe { c.init() }; Self { inner: c, check: CondvarCheck::new() } } /// Signals one waiter on this condition variable to wake up. #[inline] pub fn notify_one(&self) { unsafe { self.inner.notify_one() }; } /// Awakens all current waiters on this condition variable.
pub fn notify_all(&self) { unsafe { self.inner.notify_all() }; } /// Waits for a signal on the specified mutex. /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wait(&self, mutex: &MovableMutex) { self.check.verify(mutex); self.inner.wait(mutex.raw()) } /// Waits for a signal on the specified mutex with a timeout duration /// specified by `dur` (a relative time into the future). /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wait_timeout(&self, mutex: &MovableMutex, dur: Duration) -> bool { self.check.verify(mutex); self.inner.wait_timeout(mutex.raw(), dur) } } impl Drop for Condvar { fn drop(&mut self) { unsafe { self.inner.destroy() }; } }
#[inline]
random_line_split
condvar.rs
use crate::sys::condvar as imp; use crate::sys::mutex as mutex_imp; use crate::sys_common::mutex::MovableMutex; use crate::time::Duration; mod check; type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check; /// An OS-based condition variable. pub struct Condvar { inner: imp::MovableCondvar, check: CondvarCheck, } impl Condvar { /// Creates a new condition variable for use. pub fn new() -> Self { let mut c = imp::MovableCondvar::from(imp::Condvar::new()); unsafe { c.init() }; Self { inner: c, check: CondvarCheck::new() } } /// Signals one waiter on this condition variable to wake up. #[inline] pub fn notify_one(&self) { unsafe { self.inner.notify_one() }; } /// Awakens all current waiters on this condition variable. #[inline] pub fn notify_all(&self) { unsafe { self.inner.notify_all() }; } /// Waits for a signal on the specified mutex. /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wait(&self, mutex: &MovableMutex)
/// Waits for a signal on the specified mutex with a timeout duration /// specified by `dur` (a relative time into the future). /// /// Behavior is undefined if the mutex is not locked by the current thread. /// /// May panic if used with more than one mutex. #[inline] pub unsafe fn wait_timeout(&self, mutex: &MovableMutex, dur: Duration) -> bool { self.check.verify(mutex); self.inner.wait_timeout(mutex.raw(), dur) } } impl Drop for Condvar { fn drop(&mut self) { unsafe { self.inner.destroy() }; } }
{ self.check.verify(mutex); self.inner.wait(mutex.raw()) }
identifier_body
split_check.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::sync::mpsc::{self, sync_channel}; use std::sync::Arc; use std::time::Duration; use engine_rocks::raw::DB; use engine_rocks::Compat; use raftstore::coprocessor::{ config::{Config, SplitCheckConfigManager}, CoprocessorHost, }; use raftstore::store::{SplitCheckRunner as Runner, SplitCheckTask as Task}; use tikv::config::{ConfigController, Module, TiKvConfig}; use tikv_util::worker::{LazyWorker, Scheduler, Worker}; fn tmp_engine<P: AsRef<Path>>(path: P) -> Arc<DB> { Arc::new( engine_rocks::raw_util::new_engine( path.as_ref().to_str().unwrap(), None, &["split-check-config"], None, ) .unwrap(), ) } fn
(cfg: TiKvConfig, engine: Arc<DB>) -> (ConfigController, LazyWorker<Task>) { let (router, _) = sync_channel(1); let runner = Runner::new( engine.c().clone(), router.clone(), CoprocessorHost::new(router), cfg.coprocessor.clone(), ); let share_worker = Worker::new("split-check-config"); let mut worker = share_worker.lazy_build("split-check-config"); worker.start(runner); let cfg_controller = ConfigController::new(cfg); cfg_controller.register( Module::Coprocessor, Box::new(SplitCheckConfigManager(worker.scheduler())), ); (cfg_controller, worker) } fn validate<F>(scheduler: &Scheduler<Task>, f: F) where F: FnOnce(&Config) + Send +'static, { let (tx, rx) = mpsc::channel(); scheduler .schedule(Task::Validate(Box::new(move |cfg: &Config| { f(cfg); tx.send(()).unwrap(); }))) .unwrap(); rx.recv_timeout(Duration::from_secs(1)).unwrap(); } #[test] fn test_update_split_check_config() { let (mut cfg, _dir) = TiKvConfig::with_tmp().unwrap(); cfg.validate().unwrap(); let engine = tmp_engine(&cfg.storage.data_dir); let (cfg_controller, mut worker) = setup(cfg.clone(), engine); let scheduler = worker.scheduler(); let cop_config = cfg.coprocessor.clone(); // update of other module's config should not effect split check config cfg_controller .update_config("raftstore.raft-log-gc-threshold", "2000") .unwrap(); validate(&scheduler, move |cfg: &Config| { assert_eq!(cfg, &cop_config); }); let change = { let mut m = std::collections::HashMap::new(); m.insert( "coprocessor.split_region_on_table".to_owned(), "true".to_owned(), ); m.insert("coprocessor.batch_split_limit".to_owned(), "123".to_owned()); m.insert( "coprocessor.region_split_keys".to_owned(), "12345".to_owned(), ); m }; cfg_controller.update(change).unwrap(); // config should be updated let cop_config = { let mut cop_config = cfg.coprocessor; cop_config.split_region_on_table = true; cop_config.batch_split_limit = 123; cop_config.region_split_keys = 12345; cop_config }; validate(&scheduler, move |cfg: &Config| { assert_eq!(cfg, &cop_config); }); worker.stop(); }
setup
identifier_name
split_check.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::sync::mpsc::{self, sync_channel}; use std::sync::Arc; use std::time::Duration; use engine_rocks::raw::DB; use engine_rocks::Compat; use raftstore::coprocessor::{ config::{Config, SplitCheckConfigManager}, CoprocessorHost, }; use raftstore::store::{SplitCheckRunner as Runner, SplitCheckTask as Task}; use tikv::config::{ConfigController, Module, TiKvConfig}; use tikv_util::worker::{LazyWorker, Scheduler, Worker}; fn tmp_engine<P: AsRef<Path>>(path: P) -> Arc<DB> { Arc::new( engine_rocks::raw_util::new_engine( path.as_ref().to_str().unwrap(), None, &["split-check-config"], None, ) .unwrap(), ) } fn setup(cfg: TiKvConfig, engine: Arc<DB>) -> (ConfigController, LazyWorker<Task>) { let (router, _) = sync_channel(1); let runner = Runner::new( engine.c().clone(), router.clone(), CoprocessorHost::new(router), cfg.coprocessor.clone(), ); let share_worker = Worker::new("split-check-config"); let mut worker = share_worker.lazy_build("split-check-config"); worker.start(runner); let cfg_controller = ConfigController::new(cfg); cfg_controller.register( Module::Coprocessor, Box::new(SplitCheckConfigManager(worker.scheduler())), ); (cfg_controller, worker) } fn validate<F>(scheduler: &Scheduler<Task>, f: F) where F: FnOnce(&Config) + Send +'static, { let (tx, rx) = mpsc::channel(); scheduler .schedule(Task::Validate(Box::new(move |cfg: &Config| { f(cfg); tx.send(()).unwrap(); }))) .unwrap(); rx.recv_timeout(Duration::from_secs(1)).unwrap(); } #[test] fn test_update_split_check_config()
"true".to_owned(), ); m.insert("coprocessor.batch_split_limit".to_owned(), "123".to_owned()); m.insert( "coprocessor.region_split_keys".to_owned(), "12345".to_owned(), ); m }; cfg_controller.update(change).unwrap(); // config should be updated let cop_config = { let mut cop_config = cfg.coprocessor; cop_config.split_region_on_table = true; cop_config.batch_split_limit = 123; cop_config.region_split_keys = 12345; cop_config }; validate(&scheduler, move |cfg: &Config| { assert_eq!(cfg, &cop_config); }); worker.stop(); }
{ let (mut cfg, _dir) = TiKvConfig::with_tmp().unwrap(); cfg.validate().unwrap(); let engine = tmp_engine(&cfg.storage.data_dir); let (cfg_controller, mut worker) = setup(cfg.clone(), engine); let scheduler = worker.scheduler(); let cop_config = cfg.coprocessor.clone(); // update of other module's config should not effect split check config cfg_controller .update_config("raftstore.raft-log-gc-threshold", "2000") .unwrap(); validate(&scheduler, move |cfg: &Config| { assert_eq!(cfg, &cop_config); }); let change = { let mut m = std::collections::HashMap::new(); m.insert( "coprocessor.split_region_on_table".to_owned(),
identifier_body
split_check.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::sync::mpsc::{self, sync_channel}; use std::sync::Arc; use std::time::Duration; use engine_rocks::raw::DB; use engine_rocks::Compat; use raftstore::coprocessor::{ config::{Config, SplitCheckConfigManager}, CoprocessorHost, }; use raftstore::store::{SplitCheckRunner as Runner, SplitCheckTask as Task}; use tikv::config::{ConfigController, Module, TiKvConfig}; use tikv_util::worker::{LazyWorker, Scheduler, Worker}; fn tmp_engine<P: AsRef<Path>>(path: P) -> Arc<DB> { Arc::new( engine_rocks::raw_util::new_engine( path.as_ref().to_str().unwrap(), None, &["split-check-config"], None, ) .unwrap(), ) } fn setup(cfg: TiKvConfig, engine: Arc<DB>) -> (ConfigController, LazyWorker<Task>) { let (router, _) = sync_channel(1); let runner = Runner::new( engine.c().clone(), router.clone(), CoprocessorHost::new(router), cfg.coprocessor.clone(), ); let share_worker = Worker::new("split-check-config"); let mut worker = share_worker.lazy_build("split-check-config"); worker.start(runner); let cfg_controller = ConfigController::new(cfg); cfg_controller.register( Module::Coprocessor, Box::new(SplitCheckConfigManager(worker.scheduler())), ); (cfg_controller, worker) } fn validate<F>(scheduler: &Scheduler<Task>, f: F) where F: FnOnce(&Config) + Send +'static, { let (tx, rx) = mpsc::channel(); scheduler .schedule(Task::Validate(Box::new(move |cfg: &Config| { f(cfg); tx.send(()).unwrap(); }))) .unwrap(); rx.recv_timeout(Duration::from_secs(1)).unwrap(); } #[test] fn test_update_split_check_config() { let (mut cfg, _dir) = TiKvConfig::with_tmp().unwrap(); cfg.validate().unwrap(); let engine = tmp_engine(&cfg.storage.data_dir); let (cfg_controller, mut worker) = setup(cfg.clone(), engine); let scheduler = worker.scheduler(); let cop_config = cfg.coprocessor.clone(); // update of other module's config should not effect split check config cfg_controller .update_config("raftstore.raft-log-gc-threshold", "2000") .unwrap(); validate(&scheduler, move |cfg: &Config| { assert_eq!(cfg, &cop_config); }); let change = { let mut m = std::collections::HashMap::new(); m.insert( "coprocessor.split_region_on_table".to_owned(), "true".to_owned(), ); m.insert("coprocessor.batch_split_limit".to_owned(), "123".to_owned()); m.insert( "coprocessor.region_split_keys".to_owned(), "12345".to_owned(), ); m }; cfg_controller.update(change).unwrap(); // config should be updated let cop_config = { let mut cop_config = cfg.coprocessor; cop_config.split_region_on_table = true; cop_config.batch_split_limit = 123; cop_config.region_split_keys = 12345; cop_config
validate(&scheduler, move |cfg: &Config| { assert_eq!(cfg, &cop_config); }); worker.stop(); }
};
random_line_split
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, UnprotectedStorage}; use {Index, Generation, Entity}; /// Abstract component type. Doesn't have to be Copy or even Clone. pub trait Component: Any + Sized { /// Associated storage type for this component. type Storage: UnprotectedStorage<Self> + Any + Send + Sync; } /// A custom entity guard used to hide the the fact that Generations /// is lazily created and updated. For this to be useful it _must_ /// be joined with a component. This is because the Generation table /// includes every possible Generation of Entities even if they /// have never been pub struct Entities<'a> { guard: RwLockReadGuard<'a, Allocator>, } impl<'a> Join for &'a Entities<'a> { type Type = Entity; type Value = Self; type Mask = BitSetOr<&'a BitSet, &'a AtomicBitSet>; fn open(self) -> (Self::Mask, Self) { (BitSetOr(&self.guard.alive, &self.guard.raised), self) } unsafe fn get(v: &mut Self, idx: Index) -> Entity { let gen = v.guard.generations.get(idx as usize) .map(|&gen| if gen.is_alive() { gen } else { gen.raised() }) .unwrap_or(Generation(1)); Entity(idx, gen) } } /// Helper builder for entities. pub struct EntityBuilder<'a, C = ()>(Entity, &'a World<C>) where C: 'a + PartialEq + Eq + Hash; impl<'a, C> EntityBuilder<'a, C> where C: 'a + PartialEq + Eq + Hash { /// Adds a `Component` value to the new `Entity`. pub fn with_w_comp_id<T: Component>(self, comp_id: C, value: T) -> EntityBuilder<'a, C> { self.1.write_w_comp_id::<T>(comp_id).insert(self.0, value); self } /// Finishes entity construction. pub fn build(self) -> Entity { self.0 } } impl <'a> EntityBuilder<'a, ()> { /// Adds a `Component` value to the new `Entity`. pub fn with<T: Component>(self, value: T) -> EntityBuilder<'a> { self.1.write::<T>().insert(self.0, value); self } } /// Internally used structure for `Entity` allocation. pub struct Allocator { #[doc(hidden)] pub generations: Vec<Generation>, alive: BitSet, raised: AtomicBitSet, killed: AtomicBitSet, start_from: AtomicUsize } impl Allocator { #[doc(hidden)] pub fn new() -> Allocator { Allocator { generations: vec![], alive: BitSet::new(), raised: AtomicBitSet::new(), killed: AtomicBitSet::new(), start_from: AtomicUsize::new(0) } } fn kill(&self, e: Entity) { self.killed.add_atomic(e.get_id()); } /// Return `true` if the entity is alive. pub fn is_alive(&self, e: Entity) -> bool { e.get_gen() == match self.generations.get(e.get_id() as usize) { Some(g) if!g.is_alive() && self.raised.contains(e.get_id()) => g.raised(), Some(g) => *g, None => Generation(1), } } /// Attempt to move the `start_from` value fn update_start_from(&self, start_from: usize) { loop { let current = self.start_from.load(Ordering::Relaxed); // if the current value is bigger then ours, we bail if current >= start_from { return; } if start_from == self.start_from.compare_and_swap(current, start_from, Ordering::Relaxed) { return; } } } /// Allocate a new entity fn allocate_atomic(&self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.alive.contains(i as Index) &&!self.raised.add_atomic(i as Index) { self.update_start_from(i+1); let gen = self.generations.get(i as usize) .map(|&gen| if gen.is_alive() { gen } else { gen.raised() }) .unwrap_or(Generation(1)); return Entity(i as Index, gen); } } panic!("No entities left to allocate") } /// Allocate a new entity fn allocate(&mut self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.raised.contains(i as Index) &&!self.alive.add(i as Index) { // this is safe since we have mutable access to everything! self.start_from.store(i+1, Ordering::Relaxed); while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); return Entity(i as Index, self.generations[i as usize]); } } panic!("No entities left to allocate") } fn merge(&mut self) -> Vec<Entity> { let mut deleted = vec![]; for i in (&self.raised).iter() { while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); self.alive.add(i); } self.raised.clear(); if let Some(lowest) = (&self.killed).iter().next() { if lowest < self.start_from.load(Ordering::Relaxed) as Index { self.start_from.store(lowest as usize, Ordering::Relaxed); } } for i in (&self.killed).iter() { self.alive.remove(i); self.generations[i as usize].die(); deleted.push(Entity(i, self.generations[i as usize])) } self.killed.clear(); deleted } } /// Entity creation iterator. Will yield new empty entities infinitely. /// Useful for bulk entity construction, since the locks are only happening once. pub struct CreateEntities<'a> { allocate: RwLockWriteGuard<'a, Allocator>, } impl<'a> Iterator for CreateEntities<'a> { type Item = Entity; fn next(&mut self) -> Option<Entity> { Some(self.allocate.allocate()) } } trait StorageLock: Any + Send + Sync { fn del_slice(&self, &[Entity]); } mopafy!(StorageLock); impl<T: Component> StorageLock for RwLock<MaskedStorage<T>> { fn del_slice(&self, entities: &[Entity]) { let mut guard = self.write().unwrap(); for &e in entities.iter() { guard.remove(e.get_id()); } } } trait ResourceLock: Any + Send + Sync {} mopafy!(ResourceLock); impl<T:Any+Send+Sync> ResourceLock for RwLock<T> {} /// The `World` struct contains all the data, which is entities and their components. /// All methods are supposed to be valid for any context they are available in. /// The type parameter C is for component identification in addition of their types. pub struct World<C = ()> where C: PartialEq + Eq + Hash { allocator: RwLock<Allocator>, components: HashMap<(C, TypeId), Box<StorageLock>>, resources: HashMap<TypeId, Box<ResourceLock>>, } impl<C> World<C> where C: PartialEq + Eq + Hash { /// Creates a new empty `World` with the associated component id. pub fn new_w_comp_id() -> World<C> { World { components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type and id pair. pub fn register_w_comp_id<T: Component>(&mut self, comp_id: C) { let any = RwLock::new(MaskedStorage::<T>::new()); self.components.insert((comp_id, TypeId::of::<T>()), Box::new(any)); } /// Unregisters a component type and id pair. pub fn unregister_w_comp_id<T: Component>(&mut self, comp_id: C) -> Option<MaskedStorage<T>> { self.components.remove(&(comp_id, TypeId::of::<T>())).map(|boxed| match boxed.downcast::<RwLock<MaskedStorage<T>>>() { Ok(b) => (*b).into_inner().unwrap(), Err(_) => panic!("Unable to downcast the storage type"), } ) } fn lock_w_comp_id<T: Component>(&self, comp_id: C) -> &RwLock<MaskedStorage<T>> { let boxed = self.components.get(&(comp_id, TypeId::of::<T>())) .expect("Tried to perform an operation on component type that was not registered"); boxed.downcast_ref().unwrap() } /// Locks a component's storage for reading. pub fn read_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).read().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Locks a component's storage for writing. pub fn write_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).write().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Returns the entity iterator. pub fn entities(&self) -> Entities { Entities { guard: self.allocator.read().unwrap(), } } /// Returns the entity creation iterator. Can be used to create many /// empty entities at once without paying the locking overhead. pub fn create_iter(&mut self) -> CreateEntities { CreateEntities { allocate: self.allocator.write().unwrap(), } } /// Creates a new entity instantly, locking the generations data. pub fn create_now(&mut self) -> EntityBuilder<C> { let id = self.allocator.write().unwrap().allocate(); EntityBuilder(id, self) } /// Deletes a new entity instantly, locking the generations data. pub fn delete_now(&mut self, entity: Entity) { for comp in self.components.values() { comp.del_slice(&[entity]); } let mut gens = self.allocator.write().unwrap(); gens.alive.remove(entity.get_id()); gens.raised.remove(entity.get_id()); let id = entity.get_id() as usize; gens.generations[id].die(); if id < gens.start_from.load(Ordering::Relaxed) { gens.start_from.store(id, Ordering::Relaxed); } } /// Creates a new entity dynamically. pub fn create_later(&self) -> Entity { let allocator = self.allocator.read().unwrap(); allocator.allocate_atomic() } /// Deletes an entity dynamically. pub fn delete_later(&self, entity: Entity) { let allocator = self.allocator.read().unwrap(); allocator.kill(entity); } /// Returns `true` if the given `Entity` is alive. pub fn is_alive(&self, entity: Entity) -> bool { debug_assert!(entity.get_gen().is_alive()); let gens = self.allocator.read().unwrap(); gens.generations.get(entity.get_id() as usize).map(|&x| x == entity.get_gen()).unwrap_or(false) } /// Merges in the appendix, recording all the dynamically created /// and deleted entities into the persistent generations vector. /// Also removes all the abandoned components. pub fn maintain(&mut self) { let mut allocator = self.allocator.write().unwrap(); let temp_list = allocator.merge(); for comp in self.components.values() { comp.del_slice(&temp_list); } } /// add a new resource to the world pub fn add_resource<T: Any+Send+Sync>(&mut self, resource: T) { let resource = Box::new(RwLock::new(resource)); self.resources.insert(TypeId::of::<T>(), resource); } /// check to see if a resource is present pub fn has_resource<T: Any+Send+Sync>(&self) -> bool { self.resources.get(&TypeId::of::<T>()).is_some() } /// get read-only access to an resource pub fn read_resource<T: Any+Send+Sync>(&self) -> RwLockReadGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .read() .unwrap() } /// get read-write access to a resource pub fn
<T: Any+Send+Sync>(&self) -> RwLockWriteGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .write() .unwrap() } } impl World<()> { /// Creates a new empty `World`. pub fn new() -> World<()> { World { components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type. pub fn register<T: Component>(&mut self) { self.register_w_comp_id::<T>(()) } /// Unregisters a component type. pub fn unregister<T: Component>(&mut self) -> Option<MaskedStorage<T>> { self.unregister_w_comp_id::<T>(()) } /*fn lock<T: Component>(&self) -> &RwLock<MaskedStorage<T>> { self.lock_w_comp_id::<T>(()) }*/ /// Locks a component's storage for reading. pub fn read<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { self.read_w_comp_id::<T>(()) } /// Locks a component's storage for writing. pub fn write<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { self.write_w_comp_id::<T>(()) } }
write_resource
identifier_name
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, UnprotectedStorage}; use {Index, Generation, Entity}; /// Abstract component type. Doesn't have to be Copy or even Clone. pub trait Component: Any + Sized { /// Associated storage type for this component. type Storage: UnprotectedStorage<Self> + Any + Send + Sync; } /// A custom entity guard used to hide the the fact that Generations /// is lazily created and updated. For this to be useful it _must_ /// be joined with a component. This is because the Generation table /// includes every possible Generation of Entities even if they /// have never been pub struct Entities<'a> { guard: RwLockReadGuard<'a, Allocator>, } impl<'a> Join for &'a Entities<'a> { type Type = Entity; type Value = Self; type Mask = BitSetOr<&'a BitSet, &'a AtomicBitSet>; fn open(self) -> (Self::Mask, Self) { (BitSetOr(&self.guard.alive, &self.guard.raised), self) } unsafe fn get(v: &mut Self, idx: Index) -> Entity { let gen = v.guard.generations.get(idx as usize) .map(|&gen| if gen.is_alive() { gen } else { gen.raised() }) .unwrap_or(Generation(1)); Entity(idx, gen) } } /// Helper builder for entities. pub struct EntityBuilder<'a, C = ()>(Entity, &'a World<C>) where C: 'a + PartialEq + Eq + Hash; impl<'a, C> EntityBuilder<'a, C> where C: 'a + PartialEq + Eq + Hash { /// Adds a `Component` value to the new `Entity`. pub fn with_w_comp_id<T: Component>(self, comp_id: C, value: T) -> EntityBuilder<'a, C> { self.1.write_w_comp_id::<T>(comp_id).insert(self.0, value); self } /// Finishes entity construction. pub fn build(self) -> Entity { self.0 } } impl <'a> EntityBuilder<'a, ()> { /// Adds a `Component` value to the new `Entity`. pub fn with<T: Component>(self, value: T) -> EntityBuilder<'a> { self.1.write::<T>().insert(self.0, value); self } } /// Internally used structure for `Entity` allocation. pub struct Allocator { #[doc(hidden)] pub generations: Vec<Generation>, alive: BitSet, raised: AtomicBitSet, killed: AtomicBitSet, start_from: AtomicUsize } impl Allocator { #[doc(hidden)] pub fn new() -> Allocator { Allocator { generations: vec![], alive: BitSet::new(), raised: AtomicBitSet::new(), killed: AtomicBitSet::new(), start_from: AtomicUsize::new(0) } } fn kill(&self, e: Entity) { self.killed.add_atomic(e.get_id()); } /// Return `true` if the entity is alive. pub fn is_alive(&self, e: Entity) -> bool { e.get_gen() == match self.generations.get(e.get_id() as usize) { Some(g) if!g.is_alive() && self.raised.contains(e.get_id()) => g.raised(), Some(g) => *g, None => Generation(1), } } /// Attempt to move the `start_from` value fn update_start_from(&self, start_from: usize) { loop { let current = self.start_from.load(Ordering::Relaxed); // if the current value is bigger then ours, we bail if current >= start_from { return; } if start_from == self.start_from.compare_and_swap(current, start_from, Ordering::Relaxed) { return; } } } /// Allocate a new entity fn allocate_atomic(&self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.alive.contains(i as Index) &&!self.raised.add_atomic(i as Index) { self.update_start_from(i+1); let gen = self.generations.get(i as usize) .map(|&gen| if gen.is_alive() { gen } else { gen.raised() }) .unwrap_or(Generation(1)); return Entity(i as Index, gen); } } panic!("No entities left to allocate") } /// Allocate a new entity fn allocate(&mut self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.raised.contains(i as Index) &&!self.alive.add(i as Index) { // this is safe since we have mutable access to everything! self.start_from.store(i+1, Ordering::Relaxed); while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); return Entity(i as Index, self.generations[i as usize]); } } panic!("No entities left to allocate") } fn merge(&mut self) -> Vec<Entity> { let mut deleted = vec![]; for i in (&self.raised).iter() { while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); self.alive.add(i); } self.raised.clear(); if let Some(lowest) = (&self.killed).iter().next() { if lowest < self.start_from.load(Ordering::Relaxed) as Index { self.start_from.store(lowest as usize, Ordering::Relaxed); } } for i in (&self.killed).iter() { self.alive.remove(i); self.generations[i as usize].die(); deleted.push(Entity(i, self.generations[i as usize])) } self.killed.clear(); deleted } } /// Entity creation iterator. Will yield new empty entities infinitely. /// Useful for bulk entity construction, since the locks are only happening once. pub struct CreateEntities<'a> { allocate: RwLockWriteGuard<'a, Allocator>, } impl<'a> Iterator for CreateEntities<'a> { type Item = Entity; fn next(&mut self) -> Option<Entity> { Some(self.allocate.allocate()) } } trait StorageLock: Any + Send + Sync { fn del_slice(&self, &[Entity]); } mopafy!(StorageLock); impl<T: Component> StorageLock for RwLock<MaskedStorage<T>> { fn del_slice(&self, entities: &[Entity]) { let mut guard = self.write().unwrap(); for &e in entities.iter() { guard.remove(e.get_id()); } } } trait ResourceLock: Any + Send + Sync {} mopafy!(ResourceLock); impl<T:Any+Send+Sync> ResourceLock for RwLock<T> {} /// The `World` struct contains all the data, which is entities and their components. /// All methods are supposed to be valid for any context they are available in. /// The type parameter C is for component identification in addition of their types. pub struct World<C = ()> where C: PartialEq + Eq + Hash { allocator: RwLock<Allocator>, components: HashMap<(C, TypeId), Box<StorageLock>>, resources: HashMap<TypeId, Box<ResourceLock>>, } impl<C> World<C> where C: PartialEq + Eq + Hash {
components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type and id pair. pub fn register_w_comp_id<T: Component>(&mut self, comp_id: C) { let any = RwLock::new(MaskedStorage::<T>::new()); self.components.insert((comp_id, TypeId::of::<T>()), Box::new(any)); } /// Unregisters a component type and id pair. pub fn unregister_w_comp_id<T: Component>(&mut self, comp_id: C) -> Option<MaskedStorage<T>> { self.components.remove(&(comp_id, TypeId::of::<T>())).map(|boxed| match boxed.downcast::<RwLock<MaskedStorage<T>>>() { Ok(b) => (*b).into_inner().unwrap(), Err(_) => panic!("Unable to downcast the storage type"), } ) } fn lock_w_comp_id<T: Component>(&self, comp_id: C) -> &RwLock<MaskedStorage<T>> { let boxed = self.components.get(&(comp_id, TypeId::of::<T>())) .expect("Tried to perform an operation on component type that was not registered"); boxed.downcast_ref().unwrap() } /// Locks a component's storage for reading. pub fn read_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).read().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Locks a component's storage for writing. pub fn write_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).write().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Returns the entity iterator. pub fn entities(&self) -> Entities { Entities { guard: self.allocator.read().unwrap(), } } /// Returns the entity creation iterator. Can be used to create many /// empty entities at once without paying the locking overhead. pub fn create_iter(&mut self) -> CreateEntities { CreateEntities { allocate: self.allocator.write().unwrap(), } } /// Creates a new entity instantly, locking the generations data. pub fn create_now(&mut self) -> EntityBuilder<C> { let id = self.allocator.write().unwrap().allocate(); EntityBuilder(id, self) } /// Deletes a new entity instantly, locking the generations data. pub fn delete_now(&mut self, entity: Entity) { for comp in self.components.values() { comp.del_slice(&[entity]); } let mut gens = self.allocator.write().unwrap(); gens.alive.remove(entity.get_id()); gens.raised.remove(entity.get_id()); let id = entity.get_id() as usize; gens.generations[id].die(); if id < gens.start_from.load(Ordering::Relaxed) { gens.start_from.store(id, Ordering::Relaxed); } } /// Creates a new entity dynamically. pub fn create_later(&self) -> Entity { let allocator = self.allocator.read().unwrap(); allocator.allocate_atomic() } /// Deletes an entity dynamically. pub fn delete_later(&self, entity: Entity) { let allocator = self.allocator.read().unwrap(); allocator.kill(entity); } /// Returns `true` if the given `Entity` is alive. pub fn is_alive(&self, entity: Entity) -> bool { debug_assert!(entity.get_gen().is_alive()); let gens = self.allocator.read().unwrap(); gens.generations.get(entity.get_id() as usize).map(|&x| x == entity.get_gen()).unwrap_or(false) } /// Merges in the appendix, recording all the dynamically created /// and deleted entities into the persistent generations vector. /// Also removes all the abandoned components. pub fn maintain(&mut self) { let mut allocator = self.allocator.write().unwrap(); let temp_list = allocator.merge(); for comp in self.components.values() { comp.del_slice(&temp_list); } } /// add a new resource to the world pub fn add_resource<T: Any+Send+Sync>(&mut self, resource: T) { let resource = Box::new(RwLock::new(resource)); self.resources.insert(TypeId::of::<T>(), resource); } /// check to see if a resource is present pub fn has_resource<T: Any+Send+Sync>(&self) -> bool { self.resources.get(&TypeId::of::<T>()).is_some() } /// get read-only access to an resource pub fn read_resource<T: Any+Send+Sync>(&self) -> RwLockReadGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .read() .unwrap() } /// get read-write access to a resource pub fn write_resource<T: Any+Send+Sync>(&self) -> RwLockWriteGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .write() .unwrap() } } impl World<()> { /// Creates a new empty `World`. pub fn new() -> World<()> { World { components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type. pub fn register<T: Component>(&mut self) { self.register_w_comp_id::<T>(()) } /// Unregisters a component type. pub fn unregister<T: Component>(&mut self) -> Option<MaskedStorage<T>> { self.unregister_w_comp_id::<T>(()) } /*fn lock<T: Component>(&self) -> &RwLock<MaskedStorage<T>> { self.lock_w_comp_id::<T>(()) }*/ /// Locks a component's storage for reading. pub fn read<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { self.read_w_comp_id::<T>(()) } /// Locks a component's storage for writing. pub fn write<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { self.write_w_comp_id::<T>(()) } }
/// Creates a new empty `World` with the associated component id. pub fn new_w_comp_id() -> World<C> { World {
random_line_split
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, UnprotectedStorage}; use {Index, Generation, Entity}; /// Abstract component type. Doesn't have to be Copy or even Clone. pub trait Component: Any + Sized { /// Associated storage type for this component. type Storage: UnprotectedStorage<Self> + Any + Send + Sync; } /// A custom entity guard used to hide the the fact that Generations /// is lazily created and updated. For this to be useful it _must_ /// be joined with a component. This is because the Generation table /// includes every possible Generation of Entities even if they /// have never been pub struct Entities<'a> { guard: RwLockReadGuard<'a, Allocator>, } impl<'a> Join for &'a Entities<'a> { type Type = Entity; type Value = Self; type Mask = BitSetOr<&'a BitSet, &'a AtomicBitSet>; fn open(self) -> (Self::Mask, Self) { (BitSetOr(&self.guard.alive, &self.guard.raised), self) } unsafe fn get(v: &mut Self, idx: Index) -> Entity { let gen = v.guard.generations.get(idx as usize) .map(|&gen| if gen.is_alive() { gen } else { gen.raised() }) .unwrap_or(Generation(1)); Entity(idx, gen) } } /// Helper builder for entities. pub struct EntityBuilder<'a, C = ()>(Entity, &'a World<C>) where C: 'a + PartialEq + Eq + Hash; impl<'a, C> EntityBuilder<'a, C> where C: 'a + PartialEq + Eq + Hash { /// Adds a `Component` value to the new `Entity`. pub fn with_w_comp_id<T: Component>(self, comp_id: C, value: T) -> EntityBuilder<'a, C> { self.1.write_w_comp_id::<T>(comp_id).insert(self.0, value); self } /// Finishes entity construction. pub fn build(self) -> Entity { self.0 } } impl <'a> EntityBuilder<'a, ()> { /// Adds a `Component` value to the new `Entity`. pub fn with<T: Component>(self, value: T) -> EntityBuilder<'a> { self.1.write::<T>().insert(self.0, value); self } } /// Internally used structure for `Entity` allocation. pub struct Allocator { #[doc(hidden)] pub generations: Vec<Generation>, alive: BitSet, raised: AtomicBitSet, killed: AtomicBitSet, start_from: AtomicUsize } impl Allocator { #[doc(hidden)] pub fn new() -> Allocator { Allocator { generations: vec![], alive: BitSet::new(), raised: AtomicBitSet::new(), killed: AtomicBitSet::new(), start_from: AtomicUsize::new(0) } } fn kill(&self, e: Entity) { self.killed.add_atomic(e.get_id()); } /// Return `true` if the entity is alive. pub fn is_alive(&self, e: Entity) -> bool { e.get_gen() == match self.generations.get(e.get_id() as usize) { Some(g) if!g.is_alive() && self.raised.contains(e.get_id()) => g.raised(), Some(g) => *g, None => Generation(1), } } /// Attempt to move the `start_from` value fn update_start_from(&self, start_from: usize) { loop { let current = self.start_from.load(Ordering::Relaxed); // if the current value is bigger then ours, we bail if current >= start_from { return; } if start_from == self.start_from.compare_and_swap(current, start_from, Ordering::Relaxed) { return; } } } /// Allocate a new entity fn allocate_atomic(&self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.alive.contains(i as Index) &&!self.raised.add_atomic(i as Index) { self.update_start_from(i+1); let gen = self.generations.get(i as usize) .map(|&gen| if gen.is_alive() { gen } else { gen.raised() }) .unwrap_or(Generation(1)); return Entity(i as Index, gen); } } panic!("No entities left to allocate") } /// Allocate a new entity fn allocate(&mut self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.raised.contains(i as Index) &&!self.alive.add(i as Index) { // this is safe since we have mutable access to everything! self.start_from.store(i+1, Ordering::Relaxed); while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); return Entity(i as Index, self.generations[i as usize]); } } panic!("No entities left to allocate") } fn merge(&mut self) -> Vec<Entity> { let mut deleted = vec![]; for i in (&self.raised).iter() { while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); self.alive.add(i); } self.raised.clear(); if let Some(lowest) = (&self.killed).iter().next() { if lowest < self.start_from.load(Ordering::Relaxed) as Index { self.start_from.store(lowest as usize, Ordering::Relaxed); } } for i in (&self.killed).iter() { self.alive.remove(i); self.generations[i as usize].die(); deleted.push(Entity(i, self.generations[i as usize])) } self.killed.clear(); deleted } } /// Entity creation iterator. Will yield new empty entities infinitely. /// Useful for bulk entity construction, since the locks are only happening once. pub struct CreateEntities<'a> { allocate: RwLockWriteGuard<'a, Allocator>, } impl<'a> Iterator for CreateEntities<'a> { type Item = Entity; fn next(&mut self) -> Option<Entity> { Some(self.allocate.allocate()) } } trait StorageLock: Any + Send + Sync { fn del_slice(&self, &[Entity]); } mopafy!(StorageLock); impl<T: Component> StorageLock for RwLock<MaskedStorage<T>> { fn del_slice(&self, entities: &[Entity]) { let mut guard = self.write().unwrap(); for &e in entities.iter() { guard.remove(e.get_id()); } } } trait ResourceLock: Any + Send + Sync {} mopafy!(ResourceLock); impl<T:Any+Send+Sync> ResourceLock for RwLock<T> {} /// The `World` struct contains all the data, which is entities and their components. /// All methods are supposed to be valid for any context they are available in. /// The type parameter C is for component identification in addition of their types. pub struct World<C = ()> where C: PartialEq + Eq + Hash { allocator: RwLock<Allocator>, components: HashMap<(C, TypeId), Box<StorageLock>>, resources: HashMap<TypeId, Box<ResourceLock>>, } impl<C> World<C> where C: PartialEq + Eq + Hash { /// Creates a new empty `World` with the associated component id. pub fn new_w_comp_id() -> World<C> { World { components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type and id pair. pub fn register_w_comp_id<T: Component>(&mut self, comp_id: C) { let any = RwLock::new(MaskedStorage::<T>::new()); self.components.insert((comp_id, TypeId::of::<T>()), Box::new(any)); } /// Unregisters a component type and id pair. pub fn unregister_w_comp_id<T: Component>(&mut self, comp_id: C) -> Option<MaskedStorage<T>> { self.components.remove(&(comp_id, TypeId::of::<T>())).map(|boxed| match boxed.downcast::<RwLock<MaskedStorage<T>>>() { Ok(b) => (*b).into_inner().unwrap(), Err(_) => panic!("Unable to downcast the storage type"), } ) } fn lock_w_comp_id<T: Component>(&self, comp_id: C) -> &RwLock<MaskedStorage<T>> { let boxed = self.components.get(&(comp_id, TypeId::of::<T>())) .expect("Tried to perform an operation on component type that was not registered"); boxed.downcast_ref().unwrap() } /// Locks a component's storage for reading. pub fn read_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).read().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Locks a component's storage for writing. pub fn write_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).write().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Returns the entity iterator. pub fn entities(&self) -> Entities { Entities { guard: self.allocator.read().unwrap(), } } /// Returns the entity creation iterator. Can be used to create many /// empty entities at once without paying the locking overhead. pub fn create_iter(&mut self) -> CreateEntities { CreateEntities { allocate: self.allocator.write().unwrap(), } } /// Creates a new entity instantly, locking the generations data. pub fn create_now(&mut self) -> EntityBuilder<C> { let id = self.allocator.write().unwrap().allocate(); EntityBuilder(id, self) } /// Deletes a new entity instantly, locking the generations data. pub fn delete_now(&mut self, entity: Entity) { for comp in self.components.values() { comp.del_slice(&[entity]); } let mut gens = self.allocator.write().unwrap(); gens.alive.remove(entity.get_id()); gens.raised.remove(entity.get_id()); let id = entity.get_id() as usize; gens.generations[id].die(); if id < gens.start_from.load(Ordering::Relaxed) { gens.start_from.store(id, Ordering::Relaxed); } } /// Creates a new entity dynamically. pub fn create_later(&self) -> Entity { let allocator = self.allocator.read().unwrap(); allocator.allocate_atomic() } /// Deletes an entity dynamically. pub fn delete_later(&self, entity: Entity) { let allocator = self.allocator.read().unwrap(); allocator.kill(entity); } /// Returns `true` if the given `Entity` is alive. pub fn is_alive(&self, entity: Entity) -> bool { debug_assert!(entity.get_gen().is_alive()); let gens = self.allocator.read().unwrap(); gens.generations.get(entity.get_id() as usize).map(|&x| x == entity.get_gen()).unwrap_or(false) } /// Merges in the appendix, recording all the dynamically created /// and deleted entities into the persistent generations vector. /// Also removes all the abandoned components. pub fn maintain(&mut self)
/// add a new resource to the world pub fn add_resource<T: Any+Send+Sync>(&mut self, resource: T) { let resource = Box::new(RwLock::new(resource)); self.resources.insert(TypeId::of::<T>(), resource); } /// check to see if a resource is present pub fn has_resource<T: Any+Send+Sync>(&self) -> bool { self.resources.get(&TypeId::of::<T>()).is_some() } /// get read-only access to an resource pub fn read_resource<T: Any+Send+Sync>(&self) -> RwLockReadGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .read() .unwrap() } /// get read-write access to a resource pub fn write_resource<T: Any+Send+Sync>(&self) -> RwLockWriteGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .write() .unwrap() } } impl World<()> { /// Creates a new empty `World`. pub fn new() -> World<()> { World { components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type. pub fn register<T: Component>(&mut self) { self.register_w_comp_id::<T>(()) } /// Unregisters a component type. pub fn unregister<T: Component>(&mut self) -> Option<MaskedStorage<T>> { self.unregister_w_comp_id::<T>(()) } /*fn lock<T: Component>(&self) -> &RwLock<MaskedStorage<T>> { self.lock_w_comp_id::<T>(()) }*/ /// Locks a component's storage for reading. pub fn read<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { self.read_w_comp_id::<T>(()) } /// Locks a component's storage for writing. pub fn write<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { self.write_w_comp_id::<T>(()) } }
{ let mut allocator = self.allocator.write().unwrap(); let temp_list = allocator.merge(); for comp in self.components.values() { comp.del_slice(&temp_list); } }
identifier_body
world.rs
use std::any::TypeId; use std::collections::HashMap; use std::hash::Hash; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use mopa::Any; use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr}; use join::Join; use storage::{Storage, MaskedStorage, UnprotectedStorage}; use {Index, Generation, Entity}; /// Abstract component type. Doesn't have to be Copy or even Clone. pub trait Component: Any + Sized { /// Associated storage type for this component. type Storage: UnprotectedStorage<Self> + Any + Send + Sync; } /// A custom entity guard used to hide the the fact that Generations /// is lazily created and updated. For this to be useful it _must_ /// be joined with a component. This is because the Generation table /// includes every possible Generation of Entities even if they /// have never been pub struct Entities<'a> { guard: RwLockReadGuard<'a, Allocator>, } impl<'a> Join for &'a Entities<'a> { type Type = Entity; type Value = Self; type Mask = BitSetOr<&'a BitSet, &'a AtomicBitSet>; fn open(self) -> (Self::Mask, Self) { (BitSetOr(&self.guard.alive, &self.guard.raised), self) } unsafe fn get(v: &mut Self, idx: Index) -> Entity { let gen = v.guard.generations.get(idx as usize) .map(|&gen| if gen.is_alive() { gen } else { gen.raised() }) .unwrap_or(Generation(1)); Entity(idx, gen) } } /// Helper builder for entities. pub struct EntityBuilder<'a, C = ()>(Entity, &'a World<C>) where C: 'a + PartialEq + Eq + Hash; impl<'a, C> EntityBuilder<'a, C> where C: 'a + PartialEq + Eq + Hash { /// Adds a `Component` value to the new `Entity`. pub fn with_w_comp_id<T: Component>(self, comp_id: C, value: T) -> EntityBuilder<'a, C> { self.1.write_w_comp_id::<T>(comp_id).insert(self.0, value); self } /// Finishes entity construction. pub fn build(self) -> Entity { self.0 } } impl <'a> EntityBuilder<'a, ()> { /// Adds a `Component` value to the new `Entity`. pub fn with<T: Component>(self, value: T) -> EntityBuilder<'a> { self.1.write::<T>().insert(self.0, value); self } } /// Internally used structure for `Entity` allocation. pub struct Allocator { #[doc(hidden)] pub generations: Vec<Generation>, alive: BitSet, raised: AtomicBitSet, killed: AtomicBitSet, start_from: AtomicUsize } impl Allocator { #[doc(hidden)] pub fn new() -> Allocator { Allocator { generations: vec![], alive: BitSet::new(), raised: AtomicBitSet::new(), killed: AtomicBitSet::new(), start_from: AtomicUsize::new(0) } } fn kill(&self, e: Entity) { self.killed.add_atomic(e.get_id()); } /// Return `true` if the entity is alive. pub fn is_alive(&self, e: Entity) -> bool { e.get_gen() == match self.generations.get(e.get_id() as usize) { Some(g) if!g.is_alive() && self.raised.contains(e.get_id()) => g.raised(), Some(g) => *g, None => Generation(1), } } /// Attempt to move the `start_from` value fn update_start_from(&self, start_from: usize) { loop { let current = self.start_from.load(Ordering::Relaxed); // if the current value is bigger then ours, we bail if current >= start_from { return; } if start_from == self.start_from.compare_and_swap(current, start_from, Ordering::Relaxed) { return; } } } /// Allocate a new entity fn allocate_atomic(&self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.alive.contains(i as Index) &&!self.raised.add_atomic(i as Index) { self.update_start_from(i+1); let gen = self.generations.get(i as usize) .map(|&gen| if gen.is_alive()
else { gen.raised() }) .unwrap_or(Generation(1)); return Entity(i as Index, gen); } } panic!("No entities left to allocate") } /// Allocate a new entity fn allocate(&mut self) -> Entity { let idx = self.start_from.load(Ordering::Relaxed); for i in idx.. { if!self.raised.contains(i as Index) &&!self.alive.add(i as Index) { // this is safe since we have mutable access to everything! self.start_from.store(i+1, Ordering::Relaxed); while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); return Entity(i as Index, self.generations[i as usize]); } } panic!("No entities left to allocate") } fn merge(&mut self) -> Vec<Entity> { let mut deleted = vec![]; for i in (&self.raised).iter() { while self.generations.len() <= i as usize { self.generations.push(Generation(0)); } self.generations[i as usize] = self.generations[i as usize].raised(); self.alive.add(i); } self.raised.clear(); if let Some(lowest) = (&self.killed).iter().next() { if lowest < self.start_from.load(Ordering::Relaxed) as Index { self.start_from.store(lowest as usize, Ordering::Relaxed); } } for i in (&self.killed).iter() { self.alive.remove(i); self.generations[i as usize].die(); deleted.push(Entity(i, self.generations[i as usize])) } self.killed.clear(); deleted } } /// Entity creation iterator. Will yield new empty entities infinitely. /// Useful for bulk entity construction, since the locks are only happening once. pub struct CreateEntities<'a> { allocate: RwLockWriteGuard<'a, Allocator>, } impl<'a> Iterator for CreateEntities<'a> { type Item = Entity; fn next(&mut self) -> Option<Entity> { Some(self.allocate.allocate()) } } trait StorageLock: Any + Send + Sync { fn del_slice(&self, &[Entity]); } mopafy!(StorageLock); impl<T: Component> StorageLock for RwLock<MaskedStorage<T>> { fn del_slice(&self, entities: &[Entity]) { let mut guard = self.write().unwrap(); for &e in entities.iter() { guard.remove(e.get_id()); } } } trait ResourceLock: Any + Send + Sync {} mopafy!(ResourceLock); impl<T:Any+Send+Sync> ResourceLock for RwLock<T> {} /// The `World` struct contains all the data, which is entities and their components. /// All methods are supposed to be valid for any context they are available in. /// The type parameter C is for component identification in addition of their types. pub struct World<C = ()> where C: PartialEq + Eq + Hash { allocator: RwLock<Allocator>, components: HashMap<(C, TypeId), Box<StorageLock>>, resources: HashMap<TypeId, Box<ResourceLock>>, } impl<C> World<C> where C: PartialEq + Eq + Hash { /// Creates a new empty `World` with the associated component id. pub fn new_w_comp_id() -> World<C> { World { components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type and id pair. pub fn register_w_comp_id<T: Component>(&mut self, comp_id: C) { let any = RwLock::new(MaskedStorage::<T>::new()); self.components.insert((comp_id, TypeId::of::<T>()), Box::new(any)); } /// Unregisters a component type and id pair. pub fn unregister_w_comp_id<T: Component>(&mut self, comp_id: C) -> Option<MaskedStorage<T>> { self.components.remove(&(comp_id, TypeId::of::<T>())).map(|boxed| match boxed.downcast::<RwLock<MaskedStorage<T>>>() { Ok(b) => (*b).into_inner().unwrap(), Err(_) => panic!("Unable to downcast the storage type"), } ) } fn lock_w_comp_id<T: Component>(&self, comp_id: C) -> &RwLock<MaskedStorage<T>> { let boxed = self.components.get(&(comp_id, TypeId::of::<T>())) .expect("Tried to perform an operation on component type that was not registered"); boxed.downcast_ref().unwrap() } /// Locks a component's storage for reading. pub fn read_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).read().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Locks a component's storage for writing. pub fn write_w_comp_id<T: Component>(&self, comp_id: C) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { let data = self.lock_w_comp_id::<T>(comp_id).write().unwrap(); Storage::new(self.allocator.read().unwrap(), data) } /// Returns the entity iterator. pub fn entities(&self) -> Entities { Entities { guard: self.allocator.read().unwrap(), } } /// Returns the entity creation iterator. Can be used to create many /// empty entities at once without paying the locking overhead. pub fn create_iter(&mut self) -> CreateEntities { CreateEntities { allocate: self.allocator.write().unwrap(), } } /// Creates a new entity instantly, locking the generations data. pub fn create_now(&mut self) -> EntityBuilder<C> { let id = self.allocator.write().unwrap().allocate(); EntityBuilder(id, self) } /// Deletes a new entity instantly, locking the generations data. pub fn delete_now(&mut self, entity: Entity) { for comp in self.components.values() { comp.del_slice(&[entity]); } let mut gens = self.allocator.write().unwrap(); gens.alive.remove(entity.get_id()); gens.raised.remove(entity.get_id()); let id = entity.get_id() as usize; gens.generations[id].die(); if id < gens.start_from.load(Ordering::Relaxed) { gens.start_from.store(id, Ordering::Relaxed); } } /// Creates a new entity dynamically. pub fn create_later(&self) -> Entity { let allocator = self.allocator.read().unwrap(); allocator.allocate_atomic() } /// Deletes an entity dynamically. pub fn delete_later(&self, entity: Entity) { let allocator = self.allocator.read().unwrap(); allocator.kill(entity); } /// Returns `true` if the given `Entity` is alive. pub fn is_alive(&self, entity: Entity) -> bool { debug_assert!(entity.get_gen().is_alive()); let gens = self.allocator.read().unwrap(); gens.generations.get(entity.get_id() as usize).map(|&x| x == entity.get_gen()).unwrap_or(false) } /// Merges in the appendix, recording all the dynamically created /// and deleted entities into the persistent generations vector. /// Also removes all the abandoned components. pub fn maintain(&mut self) { let mut allocator = self.allocator.write().unwrap(); let temp_list = allocator.merge(); for comp in self.components.values() { comp.del_slice(&temp_list); } } /// add a new resource to the world pub fn add_resource<T: Any+Send+Sync>(&mut self, resource: T) { let resource = Box::new(RwLock::new(resource)); self.resources.insert(TypeId::of::<T>(), resource); } /// check to see if a resource is present pub fn has_resource<T: Any+Send+Sync>(&self) -> bool { self.resources.get(&TypeId::of::<T>()).is_some() } /// get read-only access to an resource pub fn read_resource<T: Any+Send+Sync>(&self) -> RwLockReadGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .read() .unwrap() } /// get read-write access to a resource pub fn write_resource<T: Any+Send+Sync>(&self) -> RwLockWriteGuard<T> { self.resources.get(&TypeId::of::<T>()) .expect("Resource was not registered") .downcast_ref::<RwLock<T>>() .unwrap() .write() .unwrap() } } impl World<()> { /// Creates a new empty `World`. pub fn new() -> World<()> { World { components: HashMap::new(), allocator: RwLock::new(Allocator::new()), resources: HashMap::new() } } /// Registers a new component type. pub fn register<T: Component>(&mut self) { self.register_w_comp_id::<T>(()) } /// Unregisters a component type. pub fn unregister<T: Component>(&mut self) -> Option<MaskedStorage<T>> { self.unregister_w_comp_id::<T>(()) } /*fn lock<T: Component>(&self) -> &RwLock<MaskedStorage<T>> { self.lock_w_comp_id::<T>(()) }*/ /// Locks a component's storage for reading. pub fn read<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> { self.read_w_comp_id::<T>(()) } /// Locks a component's storage for writing. pub fn write<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> { self.write_w_comp_id::<T>(()) } }
{ gen }
conditional_block
io_compat.rs
// there's no real io error on a byte slice pub type Error = (); pub type Result<T> = core::result::Result<T, Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; } impl Write for &mut [u8] { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = core::cmp::min(data.len(), self.len()); let (a, b) = core::mem::replace(self, &mut []).split_at_mut(amt); a.copy_from_slice(&data[..amt]); *self = b; Ok(amt) } } pub enum SeekFrom { Start(u64), Current(i64), } pub trait Seek { fn seek(&mut self, pos: SeekFrom) -> Result<u64>; } // Minimal re-implementation of std::io::Cursor so it // also works in non-std environments pub struct Cursor<T>(T, u64); impl<'a> Cursor<&'a mut [u8]> { pub fn new(inner: &'a mut [u8]) -> Self
pub fn into_inner(self) -> &'a mut [u8] { self.0 } pub fn position(&self) -> u64 { self.1 as u64 } pub fn set_position(&mut self, pos: u64) { self.1 = pos; } pub fn get_mut(&mut self) -> &mut [u8] { self.0 } pub fn get_ref(&self) -> &[u8] { self.0 } } impl<'a> Write for Cursor<&'a mut [u8]> { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = (&mut self.0[(self.1 as usize)..]).write(data)?; self.1 += amt as u64; Ok(amt) } } impl<'a> Seek for Cursor<&'a mut [u8]> { fn seek(&mut self, pos: SeekFrom) -> Result<u64> { let (start, offset) = match pos { SeekFrom::Start(n) => { self.1 = n; return Ok(n); } SeekFrom::Current(n) => (self.1 as u64, n), }; let new_pos = if offset >= 0 { start.checked_add(offset as u64) } else { start.checked_sub((offset.wrapping_neg()) as u64) }; match new_pos { Some(n) => { self.1 = n; Ok(n) } None => panic!("invalid seek to a negative or overflowing position"), } } }
{ Self(inner, 0) }
identifier_body
io_compat.rs
// there's no real io error on a byte slice pub type Error = (); pub type Result<T> = core::result::Result<T, Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; } impl Write for &mut [u8] { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = core::cmp::min(data.len(), self.len()); let (a, b) = core::mem::replace(self, &mut []).split_at_mut(amt); a.copy_from_slice(&data[..amt]); *self = b; Ok(amt) } } pub enum SeekFrom { Start(u64), Current(i64), } pub trait Seek { fn seek(&mut self, pos: SeekFrom) -> Result<u64>; } // Minimal re-implementation of std::io::Cursor so it // also works in non-std environments pub struct Cursor<T>(T, u64); impl<'a> Cursor<&'a mut [u8]> { pub fn
(inner: &'a mut [u8]) -> Self { Self(inner, 0) } pub fn into_inner(self) -> &'a mut [u8] { self.0 } pub fn position(&self) -> u64 { self.1 as u64 } pub fn set_position(&mut self, pos: u64) { self.1 = pos; } pub fn get_mut(&mut self) -> &mut [u8] { self.0 } pub fn get_ref(&self) -> &[u8] { self.0 } } impl<'a> Write for Cursor<&'a mut [u8]> { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = (&mut self.0[(self.1 as usize)..]).write(data)?; self.1 += amt as u64; Ok(amt) } } impl<'a> Seek for Cursor<&'a mut [u8]> { fn seek(&mut self, pos: SeekFrom) -> Result<u64> { let (start, offset) = match pos { SeekFrom::Start(n) => { self.1 = n; return Ok(n); } SeekFrom::Current(n) => (self.1 as u64, n), }; let new_pos = if offset >= 0 { start.checked_add(offset as u64) } else { start.checked_sub((offset.wrapping_neg()) as u64) }; match new_pos { Some(n) => { self.1 = n; Ok(n) } None => panic!("invalid seek to a negative or overflowing position"), } } }
new
identifier_name
io_compat.rs
// there's no real io error on a byte slice pub type Error = (); pub type Result<T> = core::result::Result<T, Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; } impl Write for &mut [u8] { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = core::cmp::min(data.len(), self.len()); let (a, b) = core::mem::replace(self, &mut []).split_at_mut(amt); a.copy_from_slice(&data[..amt]); *self = b; Ok(amt) } } pub enum SeekFrom { Start(u64), Current(i64), } pub trait Seek { fn seek(&mut self, pos: SeekFrom) -> Result<u64>; } // Minimal re-implementation of std::io::Cursor so it // also works in non-std environments pub struct Cursor<T>(T, u64); impl<'a> Cursor<&'a mut [u8]> { pub fn new(inner: &'a mut [u8]) -> Self { Self(inner, 0) } pub fn into_inner(self) -> &'a mut [u8] { self.0 } pub fn position(&self) -> u64 { self.1 as u64 } pub fn set_position(&mut self, pos: u64) { self.1 = pos; } pub fn get_mut(&mut self) -> &mut [u8] { self.0 } pub fn get_ref(&self) -> &[u8] { self.0 } } impl<'a> Write for Cursor<&'a mut [u8]> { fn write(&mut self, data: &[u8]) -> Result<usize> { let amt = (&mut self.0[(self.1 as usize)..]).write(data)?; self.1 += amt as u64; Ok(amt)
impl<'a> Seek for Cursor<&'a mut [u8]> { fn seek(&mut self, pos: SeekFrom) -> Result<u64> { let (start, offset) = match pos { SeekFrom::Start(n) => { self.1 = n; return Ok(n); } SeekFrom::Current(n) => (self.1 as u64, n), }; let new_pos = if offset >= 0 { start.checked_add(offset as u64) } else { start.checked_sub((offset.wrapping_neg()) as u64) }; match new_pos { Some(n) => { self.1 = n; Ok(n) } None => panic!("invalid seek to a negative or overflowing position"), } } }
} }
random_line_split
decoder.rs
u8, /// The dc prediction of the component pub dc_pred: i32 } // Markers // Baseline DCT const SOF0: u8 = 0xC0; // Progressive DCT const SOF2: u8 = 0xC2; // Huffman Tables const DHT: u8 = 0xC4; // Restart Interval start and End (standalone) const RST0: u8 = 0xD0; const RST7: u8 = 0xD7; // Start of Image (standalone) const SOI: u8 = 0xD8; // End of image (standalone) const EOI: u8 = 0xD9; // Start of Scan const SOS: u8 = 0xDA; // Quantization Tables const DQT: u8 = 0xDB; // Number of lines const DNL: u8 = 0xDC; // Restart Interval const DRI: u8 = 0xDD; // Application segments start and end const APP0: u8 = 0xE0; const APPF: u8 = 0xEF; // Comment const COM: u8 = 0xFE; // Reserved const TEM: u8 = 0x01; #[derive(PartialEq)] enum JPEGState { Start, HaveSOI, HaveFirstFrame, HaveFirstScan, #[allow(dead_code)] End } /// The representation of a JPEG decoder /// /// Does not support decoding progressive JPEG images pub struct JPEGDecoder<R> { r: R, qtables: [u8; 64 * 4], dctables: [HuffTable; 2], actables: [HuffTable; 2], h: HuffDecoder, height: u16, width: u16, num_components: u8, scan_components: Vec<u8>, components: HashMap<usize, Component>, // TODO: replace by `VecMap` mcu_row: Vec<u8>, mcu: Vec<u8>, hmax: u8, vmax: u8, interval: u16, mcucount: u16, expected_rst: u8, row_count: u8, decoded_rows: u32, padded_width: usize, state: JPEGState, } impl<R: Read>JPEGDecoder<R> { /// Create a new decoder that decodes from the stream ```r``` pub fn new(r: R) -> JPEGDecoder<R> { let h: HuffTable = Default::default(); JPEGDecoder { r: r, qtables: [0u8; 64 * 4], dctables: [h.clone(), h.clone()], actables: [h.clone(), h.clone()], h: HuffDecoder::new(), height: 0, width: 0, num_components: 0, scan_components: Vec::new(), components: HashMap::new(), mcu_row: Vec::new(), mcu: Vec::new(), hmax: 0, vmax: 0, interval: 0, mcucount: 0, expected_rst: RST0, row_count: 0, decoded_rows: 0, state: JPEGState::Start, padded_width: 0 } } fn decode_mcu_row(&mut self) -> ImageResult<()> { let bytesperpixel = self.num_components as usize; for x0 in range_step(0, self.padded_width * bytesperpixel, bytesperpixel * 8 * self.hmax as usize) { let _ = try!(self.decode_mcu()); upsample_mcu ( &mut self.mcu_row, x0, self.padded_width, bytesperpixel, &self.mcu, self.hmax, self.vmax ); } Ok(()) } fn decode_mcu(&mut self) -> ImageResult<()> { let mut i = 0; let tmp = self.scan_components.clone(); for id in tmp.iter() { let mut c = self.components.get(&(*id as usize)).unwrap().clone(); for _ in (0..c.h * c.v) { let pred = try!(self.decode_block(i, c.dc_table, c.dc_pred, c.ac_table, c.tq)); c.dc_pred = pred; i += 1; } self.components.insert(*id as usize, c); } self.mcucount += 1; self.read_restart() } fn decode_block(&mut self, i: usize, dc: u8, pred: i32, ac: u8, q: u8) -> ImageResult<i32> { let zz = &mut self.mcu[i * 64..i * 64 + 64]; let mut tmp = [0i32; 64]; let dctable = &self.dctables[dc as usize]; let actable = &self.actables[ac as usize]; let qtable = &self.qtables[64 * q as usize..64 * q as usize + 64]; let t = try!(self.h.decode_symbol(&mut self.r, dctable)); let diff = if t > 0 { try!(self.h.receive(&mut self.r, t)) } else { 0 }; // Section F.2.1.3.1 let diff = extend(diff, t); let dc = diff + pred; tmp[0] = dc * qtable[0] as i32; let mut k = 0usize; while k < 63 { let rs = try!(self.h.decode_symbol(&mut self.r, actable)); let ssss = rs & 0x0F; let rrrr = rs >> 4; if ssss == 0 { if rrrr!= 15 { break } k += 16; } else { k += rrrr as usize; // Figure F.14 let t = try!(self.h.receive(&mut self.r, ssss)); tmp[UNZIGZAG[k + 1] as usize] = extend(t, ssss) * qtable[k + 1] as i32; k += 1; } } transform::idct(&tmp, zz); Ok(dc) } fn read_metadata(&mut self) -> ImageResult<()> { while self.state!= JPEGState::HaveFirstScan { let byte = try!(self.r.read_u8()); if byte!= 0xFF { continue; } let marker = try!(self.r.read_u8()); match marker { SOI => self.state = JPEGState::HaveSOI, DHT => try!(self.read_huffman_tables()), DQT => try!(self.read_quantization_tables()), SOF0 => { let _ = try!(self.read_frame_header()); self.state = JPEGState::HaveFirstFrame; } SOS => { let _ = try!(self.read_scan_header()); self.state = JPEGState::HaveFirstScan; } DRI => try!(self.read_restart_interval()), APP0... APPF | COM => { let length = try!(self.r.read_u16::<BigEndian>()); let mut buf = Vec::with_capacity((length - 2) as usize); try!(self.r.by_ref().take((length - 2) as u64).read_to_end(&mut buf)); } TEM => continue, SOF2 => return Err(image::ImageError::UnsupportedError("Marker SOF2 ist not supported.".to_string())), DNL => return Err(image::ImageError::UnsupportedError("Marker DNL ist not supported.".to_string())), marker => return Err(image::ImageError::FormatError(format!("Unkown marker {} encountered.", marker))), } } Ok(()) } fn
(&mut self) -> ImageResult<()> { let _frame_length = try!(self.r.read_u16::<BigEndian>()); let sample_precision = try!(self.r.read_u8()); if sample_precision!= 8 { return Err(image::ImageError::UnsupportedError(format!( "A sample precision of {} is not supported", sample_precision ))) } self.height = try!(self.r.read_u16::<BigEndian>()); self.width = try!(self.r.read_u16::<BigEndian>()); self.num_components = try!(self.r.read_u8()); if self.height == 0 || self.width == 0 { return Err(image::ImageError::DimensionError) } if self.num_components!= 1 && self.num_components!= 3 { return Err(image::ImageError::UnsupportedError(format!( "Frames with {} components are not supported", self.num_components ))) } self.padded_width = 8 * ((self.width as usize + 7) / 8); let num_components = self.num_components; self.read_frame_components(num_components) } fn read_frame_components(&mut self, n: u8) -> ImageResult<()> { let mut blocks_per_mcu = 0; for _ in (0..n) { let id = try!(self.r.read_u8()); let hv = try!(self.r.read_u8()); let tq = try!(self.r.read_u8()); let c = Component { id: id, h: hv >> 4, v: hv & 0x0F, tq: tq, dc_table: 0, ac_table: 0, dc_pred: 0 }; blocks_per_mcu += (hv >> 4) * (hv & 0x0F); self.components.insert(id as usize, c); } let (hmax, vmax) = self.components.iter().fold((0, 0), | (h, v), (_, c) | { (cmp::max(h, c.h), cmp::max(v, c.v)) }); self.hmax = hmax; self.vmax = vmax; // only 1 component no interleaving if n == 1 { for (_, c) in self.components.iter_mut() { c.h = 1; c.v = 1; } blocks_per_mcu = 1; self.hmax = 1; self.vmax = 1; } self.mcu = repeat(0u8).take(blocks_per_mcu as usize * 64).collect::<Vec<u8>>(); let mcus_per_row = (self.width as f32 / (8 * hmax) as f32).ceil() as usize; let mcu_row_len = (hmax as usize * vmax as usize) * self.mcu.len() * mcus_per_row; self.mcu_row = repeat(0u8).take(mcu_row_len).collect::<Vec<u8>>(); Ok(()) } fn read_scan_header(&mut self) -> ImageResult<()> { let _scan_length = try!(self.r.read_u16::<BigEndian>()); let num_scan_components = try!(self.r.read_u8()); self.scan_components = Vec::new(); for _ in (0..num_scan_components as usize) { let id = try!(self.r.read_u8()); let tables = try!(self.r.read_u8()); let c = self.components.get_mut(&(id as usize)).unwrap(); c.dc_table = tables >> 4; c.ac_table = tables & 0x0F; self.scan_components.push(id); } let _spectral_end = try!(self.r.read_u8()); let _spectral_start = try!(self.r.read_u8()); let approx = try!(self.r.read_u8()); let _approx_high = approx >> 4; let _approx_low = approx & 0x0F; Ok(()) } fn read_quantization_tables(&mut self) -> ImageResult<()> { let mut table_length = try!(self.r.read_u16::<BigEndian>()) as i32; table_length -= 2; while table_length > 0 { let pqtq = try!(self.r.read_u8()); let pq = pqtq >> 4; let tq = pqtq & 0x0F; if pq!= 0 || tq > 3 { return Err(image::ImageError::FormatError("Quantization table malformed.".to_string())) } let slice = &mut self.qtables[64 * tq as usize..64 * tq as usize + 64]; for i in (0usize..64) { slice[i] = try!(self.r.read_u8()); } table_length -= 1 + 64; } Ok(()) } fn read_huffman_tables(&mut self) -> ImageResult<()> { let mut table_length = try!(self.r.read_u16::<BigEndian>()); table_length -= 2; while table_length > 0 { let tcth = try!(self.r.read_u8()); let tc = tcth >> 4; let th = tcth & 0x0F; if tc!= 0 && tc!= 1 { return Err(image::ImageError::UnsupportedError(format!( "Huffman table class {} is not supported", tc ))) } let mut bits = Vec::with_capacity(16); try!(self.r.by_ref().take(16).read_to_end(&mut bits)); let len = bits.len(); let mt = bits.iter().fold(0, | a, b | a + *b); let mut huffval = Vec::with_capacity(mt as usize); try!(self.r.by_ref().take(mt as u64).read_to_end(&mut huffval)); if tc == 0 { self.dctables[th as usize] = derive_tables(bits, huffval); } else { self.actables[th as usize] = derive_tables(bits, huffval); } table_length -= 1 + len as u16 + mt as u16; } Ok(()) } fn read_restart_interval(&mut self) -> ImageResult<()> { let _length = try!(self.r.read_u16::<BigEndian>()); self.interval = try!(self.r.read_u16::<BigEndian>()); Ok(()) } fn read_restart(&mut self) -> ImageResult<()> { let w = (self.width + 7) / (self.hmax * 8) as u16; let h = (self.height + 7) / (self.vmax * 8) as u16; if self.interval!= 0 && self.mcucount % self.interval == 0 && self.mcucount < w * h { let rst = try!(self.find_restart_marker()); if rst == self.expected_rst { self.reset(); self.expected_rst += 1; if self.expected_rst > RST7 { self.expected_rst = RST0; } } else { return Err(image::ImageError::FormatError(format!( "Unexpected restart maker {} found", rst ))) } } Ok(()) } fn find_restart_marker(&mut self) -> ImageResult<u8> { if self.h.marker!= 0 { let m = self.h.marker; self.h.marker = 0; return Ok(m); } let mut b; loop { b = try!(self.r.read_u8()); if b == 0xFF { b = try!(self.r.read_u8()); match b { RST0... RST7 => break, EOI => return Err(image::ImageError::FormatError("Restart marker not found.".to_string())), _ => continue } } } Ok(b) } fn reset(&mut self) { self.h.bits = 0; self.h.num_bits = 0; self.h.end = false; self.h.marker = 0; for (_, c) in self.components.iter_mut() { c.dc_pred = 0; } } } impl<R: Read> ImageDecoder for JPEGDecoder<R> { fn dimensions(&mut self) -> ImageResult<(u32, u32)> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } Ok((self.width as u32, self.height as u32)) } fn colortype(&mut self) -> ImageResult<color::ColorType> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let ctype = if self.num_components == 1 { color::ColorType::Gray(8) } else { color::ColorType::RGB(8) }; Ok(ctype) } fn row_len(&mut self) -> ImageResult<usize> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let len = self.width as usize * self.num_components as usize; Ok(len) } fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } if self.row_count == 0 { let _ = try!(self.decode_mcu_row()); } let len = self.padded_width * self.num_components as usize; let slice = &self.mcu_row[self.row_count as usize * len.. self.row_count as usize * len + buf.len()]; ::copy_memory(slice, buf); self.row_count = (self.row_count + 1) % (self.vmax * 8); self.decoded_rows += 1; Ok(self.decoded_rows) } fn read_image(&mut self) -> ImageResult<image::DecodingResult> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let row = try!(self.row_len()); let mut buf = repeat(0u8).take(row * self.height as usize).collect::<Vec<u8>>(); for chunk in buf.chunks_mut(row) { let _len = try!(self.read_scanline(chunk)); } Ok(image::DecodingResult::U8(buf)) } } fn upsample_mcu(out: &mut [u8], xoffset: usize, width: usize, bpp: usize, mcu: &[u8], h: u8, v: u8) { if mcu.len() == 64 { for y in (0usize..8) { for x in (
read_frame_header
identifier_name
decoder.rs
hmax: 0, vmax: 0, interval: 0, mcucount: 0, expected_rst: RST0, row_count: 0, decoded_rows: 0, state: JPEGState::Start, padded_width: 0 } } fn decode_mcu_row(&mut self) -> ImageResult<()> { let bytesperpixel = self.num_components as usize; for x0 in range_step(0, self.padded_width * bytesperpixel, bytesperpixel * 8 * self.hmax as usize) { let _ = try!(self.decode_mcu()); upsample_mcu ( &mut self.mcu_row, x0, self.padded_width, bytesperpixel, &self.mcu, self.hmax, self.vmax ); } Ok(()) } fn decode_mcu(&mut self) -> ImageResult<()> { let mut i = 0; let tmp = self.scan_components.clone(); for id in tmp.iter() { let mut c = self.components.get(&(*id as usize)).unwrap().clone(); for _ in (0..c.h * c.v) { let pred = try!(self.decode_block(i, c.dc_table, c.dc_pred, c.ac_table, c.tq)); c.dc_pred = pred; i += 1; } self.components.insert(*id as usize, c); } self.mcucount += 1; self.read_restart() } fn decode_block(&mut self, i: usize, dc: u8, pred: i32, ac: u8, q: u8) -> ImageResult<i32> { let zz = &mut self.mcu[i * 64..i * 64 + 64]; let mut tmp = [0i32; 64]; let dctable = &self.dctables[dc as usize]; let actable = &self.actables[ac as usize]; let qtable = &self.qtables[64 * q as usize..64 * q as usize + 64]; let t = try!(self.h.decode_symbol(&mut self.r, dctable)); let diff = if t > 0 { try!(self.h.receive(&mut self.r, t)) } else { 0 }; // Section F.2.1.3.1 let diff = extend(diff, t); let dc = diff + pred; tmp[0] = dc * qtable[0] as i32; let mut k = 0usize; while k < 63 { let rs = try!(self.h.decode_symbol(&mut self.r, actable)); let ssss = rs & 0x0F; let rrrr = rs >> 4; if ssss == 0 { if rrrr!= 15 { break } k += 16; } else { k += rrrr as usize; // Figure F.14 let t = try!(self.h.receive(&mut self.r, ssss)); tmp[UNZIGZAG[k + 1] as usize] = extend(t, ssss) * qtable[k + 1] as i32; k += 1; } } transform::idct(&tmp, zz); Ok(dc) } fn read_metadata(&mut self) -> ImageResult<()> { while self.state!= JPEGState::HaveFirstScan { let byte = try!(self.r.read_u8()); if byte!= 0xFF { continue; } let marker = try!(self.r.read_u8()); match marker { SOI => self.state = JPEGState::HaveSOI, DHT => try!(self.read_huffman_tables()), DQT => try!(self.read_quantization_tables()), SOF0 => { let _ = try!(self.read_frame_header()); self.state = JPEGState::HaveFirstFrame; } SOS => { let _ = try!(self.read_scan_header()); self.state = JPEGState::HaveFirstScan; } DRI => try!(self.read_restart_interval()), APP0... APPF | COM => { let length = try!(self.r.read_u16::<BigEndian>()); let mut buf = Vec::with_capacity((length - 2) as usize); try!(self.r.by_ref().take((length - 2) as u64).read_to_end(&mut buf)); } TEM => continue, SOF2 => return Err(image::ImageError::UnsupportedError("Marker SOF2 ist not supported.".to_string())), DNL => return Err(image::ImageError::UnsupportedError("Marker DNL ist not supported.".to_string())), marker => return Err(image::ImageError::FormatError(format!("Unkown marker {} encountered.", marker))), } } Ok(()) } fn read_frame_header(&mut self) -> ImageResult<()> { let _frame_length = try!(self.r.read_u16::<BigEndian>()); let sample_precision = try!(self.r.read_u8()); if sample_precision!= 8 { return Err(image::ImageError::UnsupportedError(format!( "A sample precision of {} is not supported", sample_precision ))) } self.height = try!(self.r.read_u16::<BigEndian>()); self.width = try!(self.r.read_u16::<BigEndian>()); self.num_components = try!(self.r.read_u8()); if self.height == 0 || self.width == 0 { return Err(image::ImageError::DimensionError) } if self.num_components!= 1 && self.num_components!= 3 { return Err(image::ImageError::UnsupportedError(format!( "Frames with {} components are not supported", self.num_components ))) } self.padded_width = 8 * ((self.width as usize + 7) / 8); let num_components = self.num_components; self.read_frame_components(num_components) } fn read_frame_components(&mut self, n: u8) -> ImageResult<()> { let mut blocks_per_mcu = 0; for _ in (0..n) { let id = try!(self.r.read_u8()); let hv = try!(self.r.read_u8()); let tq = try!(self.r.read_u8()); let c = Component { id: id, h: hv >> 4, v: hv & 0x0F, tq: tq, dc_table: 0, ac_table: 0, dc_pred: 0 }; blocks_per_mcu += (hv >> 4) * (hv & 0x0F); self.components.insert(id as usize, c); } let (hmax, vmax) = self.components.iter().fold((0, 0), | (h, v), (_, c) | { (cmp::max(h, c.h), cmp::max(v, c.v)) }); self.hmax = hmax; self.vmax = vmax; // only 1 component no interleaving if n == 1 { for (_, c) in self.components.iter_mut() { c.h = 1; c.v = 1; } blocks_per_mcu = 1; self.hmax = 1; self.vmax = 1; } self.mcu = repeat(0u8).take(blocks_per_mcu as usize * 64).collect::<Vec<u8>>(); let mcus_per_row = (self.width as f32 / (8 * hmax) as f32).ceil() as usize; let mcu_row_len = (hmax as usize * vmax as usize) * self.mcu.len() * mcus_per_row; self.mcu_row = repeat(0u8).take(mcu_row_len).collect::<Vec<u8>>(); Ok(()) } fn read_scan_header(&mut self) -> ImageResult<()> { let _scan_length = try!(self.r.read_u16::<BigEndian>()); let num_scan_components = try!(self.r.read_u8()); self.scan_components = Vec::new(); for _ in (0..num_scan_components as usize) { let id = try!(self.r.read_u8()); let tables = try!(self.r.read_u8()); let c = self.components.get_mut(&(id as usize)).unwrap(); c.dc_table = tables >> 4; c.ac_table = tables & 0x0F; self.scan_components.push(id); } let _spectral_end = try!(self.r.read_u8()); let _spectral_start = try!(self.r.read_u8()); let approx = try!(self.r.read_u8()); let _approx_high = approx >> 4; let _approx_low = approx & 0x0F; Ok(()) } fn read_quantization_tables(&mut self) -> ImageResult<()> { let mut table_length = try!(self.r.read_u16::<BigEndian>()) as i32; table_length -= 2; while table_length > 0 { let pqtq = try!(self.r.read_u8()); let pq = pqtq >> 4; let tq = pqtq & 0x0F; if pq!= 0 || tq > 3 { return Err(image::ImageError::FormatError("Quantization table malformed.".to_string())) } let slice = &mut self.qtables[64 * tq as usize..64 * tq as usize + 64]; for i in (0usize..64) { slice[i] = try!(self.r.read_u8()); } table_length -= 1 + 64; } Ok(()) } fn read_huffman_tables(&mut self) -> ImageResult<()> { let mut table_length = try!(self.r.read_u16::<BigEndian>()); table_length -= 2; while table_length > 0 { let tcth = try!(self.r.read_u8()); let tc = tcth >> 4; let th = tcth & 0x0F; if tc!= 0 && tc!= 1 { return Err(image::ImageError::UnsupportedError(format!( "Huffman table class {} is not supported", tc ))) } let mut bits = Vec::with_capacity(16); try!(self.r.by_ref().take(16).read_to_end(&mut bits)); let len = bits.len(); let mt = bits.iter().fold(0, | a, b | a + *b); let mut huffval = Vec::with_capacity(mt as usize); try!(self.r.by_ref().take(mt as u64).read_to_end(&mut huffval)); if tc == 0 { self.dctables[th as usize] = derive_tables(bits, huffval); } else { self.actables[th as usize] = derive_tables(bits, huffval); } table_length -= 1 + len as u16 + mt as u16; } Ok(()) } fn read_restart_interval(&mut self) -> ImageResult<()> { let _length = try!(self.r.read_u16::<BigEndian>()); self.interval = try!(self.r.read_u16::<BigEndian>()); Ok(()) } fn read_restart(&mut self) -> ImageResult<()> { let w = (self.width + 7) / (self.hmax * 8) as u16; let h = (self.height + 7) / (self.vmax * 8) as u16; if self.interval!= 0 && self.mcucount % self.interval == 0 && self.mcucount < w * h { let rst = try!(self.find_restart_marker()); if rst == self.expected_rst { self.reset(); self.expected_rst += 1; if self.expected_rst > RST7 { self.expected_rst = RST0; } } else { return Err(image::ImageError::FormatError(format!( "Unexpected restart maker {} found", rst ))) } } Ok(()) } fn find_restart_marker(&mut self) -> ImageResult<u8> { if self.h.marker!= 0 { let m = self.h.marker; self.h.marker = 0; return Ok(m); } let mut b; loop { b = try!(self.r.read_u8()); if b == 0xFF { b = try!(self.r.read_u8()); match b { RST0... RST7 => break, EOI => return Err(image::ImageError::FormatError("Restart marker not found.".to_string())), _ => continue } } } Ok(b) } fn reset(&mut self) { self.h.bits = 0; self.h.num_bits = 0; self.h.end = false; self.h.marker = 0; for (_, c) in self.components.iter_mut() { c.dc_pred = 0; } } } impl<R: Read> ImageDecoder for JPEGDecoder<R> { fn dimensions(&mut self) -> ImageResult<(u32, u32)> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } Ok((self.width as u32, self.height as u32)) } fn colortype(&mut self) -> ImageResult<color::ColorType> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let ctype = if self.num_components == 1 { color::ColorType::Gray(8) } else { color::ColorType::RGB(8) }; Ok(ctype) } fn row_len(&mut self) -> ImageResult<usize> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let len = self.width as usize * self.num_components as usize; Ok(len) } fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } if self.row_count == 0 { let _ = try!(self.decode_mcu_row()); } let len = self.padded_width * self.num_components as usize; let slice = &self.mcu_row[self.row_count as usize * len.. self.row_count as usize * len + buf.len()]; ::copy_memory(slice, buf); self.row_count = (self.row_count + 1) % (self.vmax * 8); self.decoded_rows += 1; Ok(self.decoded_rows) } fn read_image(&mut self) -> ImageResult<image::DecodingResult> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let row = try!(self.row_len()); let mut buf = repeat(0u8).take(row * self.height as usize).collect::<Vec<u8>>(); for chunk in buf.chunks_mut(row) { let _len = try!(self.read_scanline(chunk)); } Ok(image::DecodingResult::U8(buf)) } } fn upsample_mcu(out: &mut [u8], xoffset: usize, width: usize, bpp: usize, mcu: &[u8], h: u8, v: u8) { if mcu.len() == 64 { for y in (0usize..8) { for x in (0usize..8) { out[xoffset + x + (y * width)] = mcu[x + y * 8] } } } else { let y_blocks = h * v; let y_blocks = &mcu[..y_blocks as usize * 64]; let cb = &mcu[y_blocks.len()..y_blocks.len() + 64]; let cr = &mcu[y_blocks.len() + cb.len()..]; let mut k = 0; for by in (0..v as usize) { let y0 = by * 8; for bx in (0..h as usize) { let x0 = xoffset + bx * 8 * bpp; for y in (0usize..8) { for x in (0usize..8) { let (a, b, c) = (y_blocks[k * 64 + x + y * 8], cb[x + y * 8], cr[x + y * 8]); let (r, g, b) = ycbcr_to_rgb(a, b, c ); let offset = (y0 + y) * (width * bpp) + x0 + x * bpp; out[offset + 0] = r; out[offset + 1] = g; out[offset + 2] = b; } } k += 1; } } } } fn ycbcr_to_rgb(y: u8, cb: u8, cr: u8) -> (u8, u8, u8) { let y = y as f32; let cr = cr as f32; let cb = cb as f32; let r1 = y + 1.402f32 * (cr - 128f32) ; let g1 = y - 0.34414f32 * (cb - 128f32) - 0.71414f32 * (cr - 128f32); let b1 = y + 1.772f32 * (cb - 128f32); let r = clamp(r1 as i32, 0, 255) as u8; let g = clamp(g1 as i32, 0, 255) as u8; let b = clamp(b1 as i32, 0, 255) as u8;
(r, g, b) } // Section F.2.2.1
random_line_split
decoder.rs
u8, /// The dc prediction of the component pub dc_pred: i32 } // Markers // Baseline DCT const SOF0: u8 = 0xC0; // Progressive DCT const SOF2: u8 = 0xC2; // Huffman Tables const DHT: u8 = 0xC4; // Restart Interval start and End (standalone) const RST0: u8 = 0xD0; const RST7: u8 = 0xD7; // Start of Image (standalone) const SOI: u8 = 0xD8; // End of image (standalone) const EOI: u8 = 0xD9; // Start of Scan const SOS: u8 = 0xDA; // Quantization Tables const DQT: u8 = 0xDB; // Number of lines const DNL: u8 = 0xDC; // Restart Interval const DRI: u8 = 0xDD; // Application segments start and end const APP0: u8 = 0xE0; const APPF: u8 = 0xEF; // Comment const COM: u8 = 0xFE; // Reserved const TEM: u8 = 0x01; #[derive(PartialEq)] enum JPEGState { Start, HaveSOI, HaveFirstFrame, HaveFirstScan, #[allow(dead_code)] End } /// The representation of a JPEG decoder /// /// Does not support decoding progressive JPEG images pub struct JPEGDecoder<R> { r: R, qtables: [u8; 64 * 4], dctables: [HuffTable; 2], actables: [HuffTable; 2], h: HuffDecoder, height: u16, width: u16, num_components: u8, scan_components: Vec<u8>, components: HashMap<usize, Component>, // TODO: replace by `VecMap` mcu_row: Vec<u8>, mcu: Vec<u8>, hmax: u8, vmax: u8, interval: u16, mcucount: u16, expected_rst: u8, row_count: u8, decoded_rows: u32, padded_width: usize, state: JPEGState, } impl<R: Read>JPEGDecoder<R> { /// Create a new decoder that decodes from the stream ```r``` pub fn new(r: R) -> JPEGDecoder<R> { let h: HuffTable = Default::default(); JPEGDecoder { r: r, qtables: [0u8; 64 * 4], dctables: [h.clone(), h.clone()], actables: [h.clone(), h.clone()], h: HuffDecoder::new(), height: 0, width: 0, num_components: 0, scan_components: Vec::new(), components: HashMap::new(), mcu_row: Vec::new(), mcu: Vec::new(), hmax: 0, vmax: 0, interval: 0, mcucount: 0, expected_rst: RST0, row_count: 0, decoded_rows: 0, state: JPEGState::Start, padded_width: 0 } } fn decode_mcu_row(&mut self) -> ImageResult<()> { let bytesperpixel = self.num_components as usize; for x0 in range_step(0, self.padded_width * bytesperpixel, bytesperpixel * 8 * self.hmax as usize) { let _ = try!(self.decode_mcu()); upsample_mcu ( &mut self.mcu_row, x0, self.padded_width, bytesperpixel, &self.mcu, self.hmax, self.vmax ); } Ok(()) } fn decode_mcu(&mut self) -> ImageResult<()> { let mut i = 0; let tmp = self.scan_components.clone(); for id in tmp.iter() { let mut c = self.components.get(&(*id as usize)).unwrap().clone(); for _ in (0..c.h * c.v) { let pred = try!(self.decode_block(i, c.dc_table, c.dc_pred, c.ac_table, c.tq)); c.dc_pred = pred; i += 1; } self.components.insert(*id as usize, c); } self.mcucount += 1; self.read_restart() } fn decode_block(&mut self, i: usize, dc: u8, pred: i32, ac: u8, q: u8) -> ImageResult<i32> { let zz = &mut self.mcu[i * 64..i * 64 + 64]; let mut tmp = [0i32; 64]; let dctable = &self.dctables[dc as usize]; let actable = &self.actables[ac as usize]; let qtable = &self.qtables[64 * q as usize..64 * q as usize + 64]; let t = try!(self.h.decode_symbol(&mut self.r, dctable)); let diff = if t > 0 { try!(self.h.receive(&mut self.r, t)) } else { 0 }; // Section F.2.1.3.1 let diff = extend(diff, t); let dc = diff + pred; tmp[0] = dc * qtable[0] as i32; let mut k = 0usize; while k < 63 { let rs = try!(self.h.decode_symbol(&mut self.r, actable)); let ssss = rs & 0x0F; let rrrr = rs >> 4; if ssss == 0 { if rrrr!= 15 { break } k += 16; } else { k += rrrr as usize; // Figure F.14 let t = try!(self.h.receive(&mut self.r, ssss)); tmp[UNZIGZAG[k + 1] as usize] = extend(t, ssss) * qtable[k + 1] as i32; k += 1; } } transform::idct(&tmp, zz); Ok(dc) } fn read_metadata(&mut self) -> ImageResult<()> { while self.state!= JPEGState::HaveFirstScan { let byte = try!(self.r.read_u8()); if byte!= 0xFF { continue; } let marker = try!(self.r.read_u8()); match marker { SOI => self.state = JPEGState::HaveSOI, DHT => try!(self.read_huffman_tables()), DQT => try!(self.read_quantization_tables()), SOF0 => { let _ = try!(self.read_frame_header()); self.state = JPEGState::HaveFirstFrame; } SOS => { let _ = try!(self.read_scan_header()); self.state = JPEGState::HaveFirstScan; } DRI => try!(self.read_restart_interval()), APP0... APPF | COM => { let length = try!(self.r.read_u16::<BigEndian>()); let mut buf = Vec::with_capacity((length - 2) as usize); try!(self.r.by_ref().take((length - 2) as u64).read_to_end(&mut buf)); } TEM => continue, SOF2 => return Err(image::ImageError::UnsupportedError("Marker SOF2 ist not supported.".to_string())), DNL => return Err(image::ImageError::UnsupportedError("Marker DNL ist not supported.".to_string())), marker => return Err(image::ImageError::FormatError(format!("Unkown marker {} encountered.", marker))), } } Ok(()) } fn read_frame_header(&mut self) -> ImageResult<()>
return Err(image::ImageError::UnsupportedError(format!( "Frames with {} components are not supported", self.num_components ))) } self.padded_width = 8 * ((self.width as usize + 7) / 8); let num_components = self.num_components; self.read_frame_components(num_components) } fn read_frame_components(&mut self, n: u8) -> ImageResult<()> { let mut blocks_per_mcu = 0; for _ in (0..n) { let id = try!(self.r.read_u8()); let hv = try!(self.r.read_u8()); let tq = try!(self.r.read_u8()); let c = Component { id: id, h: hv >> 4, v: hv & 0x0F, tq: tq, dc_table: 0, ac_table: 0, dc_pred: 0 }; blocks_per_mcu += (hv >> 4) * (hv & 0x0F); self.components.insert(id as usize, c); } let (hmax, vmax) = self.components.iter().fold((0, 0), | (h, v), (_, c) | { (cmp::max(h, c.h), cmp::max(v, c.v)) }); self.hmax = hmax; self.vmax = vmax; // only 1 component no interleaving if n == 1 { for (_, c) in self.components.iter_mut() { c.h = 1; c.v = 1; } blocks_per_mcu = 1; self.hmax = 1; self.vmax = 1; } self.mcu = repeat(0u8).take(blocks_per_mcu as usize * 64).collect::<Vec<u8>>(); let mcus_per_row = (self.width as f32 / (8 * hmax) as f32).ceil() as usize; let mcu_row_len = (hmax as usize * vmax as usize) * self.mcu.len() * mcus_per_row; self.mcu_row = repeat(0u8).take(mcu_row_len).collect::<Vec<u8>>(); Ok(()) } fn read_scan_header(&mut self) -> ImageResult<()> { let _scan_length = try!(self.r.read_u16::<BigEndian>()); let num_scan_components = try!(self.r.read_u8()); self.scan_components = Vec::new(); for _ in (0..num_scan_components as usize) { let id = try!(self.r.read_u8()); let tables = try!(self.r.read_u8()); let c = self.components.get_mut(&(id as usize)).unwrap(); c.dc_table = tables >> 4; c.ac_table = tables & 0x0F; self.scan_components.push(id); } let _spectral_end = try!(self.r.read_u8()); let _spectral_start = try!(self.r.read_u8()); let approx = try!(self.r.read_u8()); let _approx_high = approx >> 4; let _approx_low = approx & 0x0F; Ok(()) } fn read_quantization_tables(&mut self) -> ImageResult<()> { let mut table_length = try!(self.r.read_u16::<BigEndian>()) as i32; table_length -= 2; while table_length > 0 { let pqtq = try!(self.r.read_u8()); let pq = pqtq >> 4; let tq = pqtq & 0x0F; if pq!= 0 || tq > 3 { return Err(image::ImageError::FormatError("Quantization table malformed.".to_string())) } let slice = &mut self.qtables[64 * tq as usize..64 * tq as usize + 64]; for i in (0usize..64) { slice[i] = try!(self.r.read_u8()); } table_length -= 1 + 64; } Ok(()) } fn read_huffman_tables(&mut self) -> ImageResult<()> { let mut table_length = try!(self.r.read_u16::<BigEndian>()); table_length -= 2; while table_length > 0 { let tcth = try!(self.r.read_u8()); let tc = tcth >> 4; let th = tcth & 0x0F; if tc!= 0 && tc!= 1 { return Err(image::ImageError::UnsupportedError(format!( "Huffman table class {} is not supported", tc ))) } let mut bits = Vec::with_capacity(16); try!(self.r.by_ref().take(16).read_to_end(&mut bits)); let len = bits.len(); let mt = bits.iter().fold(0, | a, b | a + *b); let mut huffval = Vec::with_capacity(mt as usize); try!(self.r.by_ref().take(mt as u64).read_to_end(&mut huffval)); if tc == 0 { self.dctables[th as usize] = derive_tables(bits, huffval); } else { self.actables[th as usize] = derive_tables(bits, huffval); } table_length -= 1 + len as u16 + mt as u16; } Ok(()) } fn read_restart_interval(&mut self) -> ImageResult<()> { let _length = try!(self.r.read_u16::<BigEndian>()); self.interval = try!(self.r.read_u16::<BigEndian>()); Ok(()) } fn read_restart(&mut self) -> ImageResult<()> { let w = (self.width + 7) / (self.hmax * 8) as u16; let h = (self.height + 7) / (self.vmax * 8) as u16; if self.interval!= 0 && self.mcucount % self.interval == 0 && self.mcucount < w * h { let rst = try!(self.find_restart_marker()); if rst == self.expected_rst { self.reset(); self.expected_rst += 1; if self.expected_rst > RST7 { self.expected_rst = RST0; } } else { return Err(image::ImageError::FormatError(format!( "Unexpected restart maker {} found", rst ))) } } Ok(()) } fn find_restart_marker(&mut self) -> ImageResult<u8> { if self.h.marker!= 0 { let m = self.h.marker; self.h.marker = 0; return Ok(m); } let mut b; loop { b = try!(self.r.read_u8()); if b == 0xFF { b = try!(self.r.read_u8()); match b { RST0... RST7 => break, EOI => return Err(image::ImageError::FormatError("Restart marker not found.".to_string())), _ => continue } } } Ok(b) } fn reset(&mut self) { self.h.bits = 0; self.h.num_bits = 0; self.h.end = false; self.h.marker = 0; for (_, c) in self.components.iter_mut() { c.dc_pred = 0; } } } impl<R: Read> ImageDecoder for JPEGDecoder<R> { fn dimensions(&mut self) -> ImageResult<(u32, u32)> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } Ok((self.width as u32, self.height as u32)) } fn colortype(&mut self) -> ImageResult<color::ColorType> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let ctype = if self.num_components == 1 { color::ColorType::Gray(8) } else { color::ColorType::RGB(8) }; Ok(ctype) } fn row_len(&mut self) -> ImageResult<usize> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let len = self.width as usize * self.num_components as usize; Ok(len) } fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } if self.row_count == 0 { let _ = try!(self.decode_mcu_row()); } let len = self.padded_width * self.num_components as usize; let slice = &self.mcu_row[self.row_count as usize * len.. self.row_count as usize * len + buf.len()]; ::copy_memory(slice, buf); self.row_count = (self.row_count + 1) % (self.vmax * 8); self.decoded_rows += 1; Ok(self.decoded_rows) } fn read_image(&mut self) -> ImageResult<image::DecodingResult> { if self.state == JPEGState::Start { let _ = try!(self.read_metadata()); } let row = try!(self.row_len()); let mut buf = repeat(0u8).take(row * self.height as usize).collect::<Vec<u8>>(); for chunk in buf.chunks_mut(row) { let _len = try!(self.read_scanline(chunk)); } Ok(image::DecodingResult::U8(buf)) } } fn upsample_mcu(out: &mut [u8], xoffset: usize, width: usize, bpp: usize, mcu: &[u8], h: u8, v: u8) { if mcu.len() == 64 { for y in (0usize..8) { for x in (
{ let _frame_length = try!(self.r.read_u16::<BigEndian>()); let sample_precision = try!(self.r.read_u8()); if sample_precision != 8 { return Err(image::ImageError::UnsupportedError(format!( "A sample precision of {} is not supported", sample_precision ))) } self.height = try!(self.r.read_u16::<BigEndian>()); self.width = try!(self.r.read_u16::<BigEndian>()); self.num_components = try!(self.r.read_u8()); if self.height == 0 || self.width == 0 { return Err(image::ImageError::DimensionError) } if self.num_components != 1 && self.num_components != 3 {
identifier_body
nist-spce.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff
use lumol::consts::K_BOLTZMANN; use lumol::energy::{CoulombicPotential, Ewald, PairRestriction, SharedEwald}; use lumol::energy::{LennardJones, NullPotential, PairInteraction}; use lumol::sys::{System, UnitCell}; use lumol::sys::TrajectoryBuilder; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn get_system(path: &str, cutoff: f64) -> System { let path = Path::new(file!()).parent().unwrap().join("data").join("nist-spce").join(path); let mut system = TrajectoryBuilder::new().open(&path).and_then(|mut traj| traj.read()).unwrap(); let mut file = File::open(path).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); let line = buffer.lines().nth(1).unwrap(); let mut splited = line.split_whitespace(); assert_eq!(splited.next(), Some("cell:")); let a: f64 = splited.next() .expect("Missing 'a' cell parameter") .parse() .expect("'a' cell parameter is not a float"); let b: f64 = splited.next() .expect("Missing 'b' cell parameter") .parse() .expect("'b' cell parameter is not a float"); let c: f64 = splited.next() .expect("Missing 'c' cell parameter") .parse() .expect("'c' cell parameter is not a float"); system.cell = UnitCell::ortho(a, b, c); for i in 0..system.size() { if i % 3 == 0 { system.add_bond(i, i + 1); system.add_bond(i, i + 2); } } for particle in system.particles_mut() { match particle.name.as_ref() { "H" => *particle.charge = 0.42380, "O" => *particle.charge = -2.0 * 0.42380, other => panic!("Unknown particle name: {}", other), } } let mut lj = PairInteraction::new( Box::new(LennardJones { epsilon: 78.19743111 * K_BOLTZMANN, sigma: 3.16555789, }), cutoff, ); lj.enable_tail_corrections(); system.add_pair_potential(("O", "O"), lj); system.add_pair_potential(("O", "H"), PairInteraction::new(Box::new(NullPotential), cutoff)); system.add_pair_potential(("H", "H"), PairInteraction::new(Box::new(NullPotential), cutoff)); let mut ewald = Ewald::new(cutoff, 5); ewald.set_alpha(5.6 / f64::min(f64::min(a, b), c)); let mut ewald = SharedEwald::new(ewald); ewald.set_restriction(PairRestriction::InterMolecular); system.set_coulomb_potential(Box::new(ewald)); return system; } mod cutoff_9 { use super::*; use lumol::consts::K_BOLTZMANN; #[test] fn nist1() { let system = get_system("spce-1.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -4.88608e5; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist2() { let system = get_system("spce-2.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06602e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist3() { let system = get_system("spce-3.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.71488e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist4() { let system = get_system("spce-4.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -3.08010e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } } mod cutoff_10 { use super::*; use lumol::consts::K_BOLTZMANN; #[test] fn nist1() { let system = get_system("spce-1.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -4.88604e5; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist2() { let system = get_system("spce-2.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06590e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist3() { let system = get_system("spce-3.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.71488e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist4() { let system = get_system("spce-4.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -3.20501e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } }
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff extern crate lumol;
random_line_split
nist-spce.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff extern crate lumol; use lumol::consts::K_BOLTZMANN; use lumol::energy::{CoulombicPotential, Ewald, PairRestriction, SharedEwald}; use lumol::energy::{LennardJones, NullPotential, PairInteraction}; use lumol::sys::{System, UnitCell}; use lumol::sys::TrajectoryBuilder; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn get_system(path: &str, cutoff: f64) -> System {
.expect("'c' cell parameter is not a float"); system.cell = UnitCell::ortho(a, b, c); for i in 0..system.size() { if i % 3 == 0 { system.add_bond(i, i + 1); system.add_bond(i, i + 2); } } for particle in system.particles_mut() { match particle.name.as_ref() { "H" => *particle.charge = 0.42380, "O" => *particle.charge = -2.0 * 0.42380, other => panic!("Unknown particle name: {}", other), } } let mut lj = PairInteraction::new( Box::new(LennardJones { epsilon: 78.19743111 * K_BOLTZMANN, sigma: 3.16555789, }), cutoff, ); lj.enable_tail_corrections(); system.add_pair_potential(("O", "O"), lj); system.add_pair_potential(("O", "H"), PairInteraction::new(Box::new(NullPotential), cutoff)); system.add_pair_potential(("H", "H"), PairInteraction::new(Box::new(NullPotential), cutoff)); let mut ewald = Ewald::new(cutoff, 5); ewald.set_alpha(5.6 / f64::min(f64::min(a, b), c)); let mut ewald = SharedEwald::new(ewald); ewald.set_restriction(PairRestriction::InterMolecular); system.set_coulomb_potential(Box::new(ewald)); return system; } m od cutoff_9 { use super::*; use lumol::consts::K_BOLTZMANN; #[test] fn nist1() { let system = get_system("spce-1.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -4.88608e5; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist2() { let system = get_system("spce-2.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06602e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist3() { let system = get_system("spce-3.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.71488e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist4() { let system = get_system("spce-4.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -3.08010e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } } mod cutoff_10 { use super::*; use lumol::consts::K_BOLTZMANN; #[test] fn nist1() { let system = get_system("spce-1.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -4.88604e5; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist2() { let system = get_system("spce-2.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06590e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist3() { let system = get_system("spce-3.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.71488e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist4() { let system = get_system("spce-4.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -3.20501e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } }
let path = Path::new(file!()).parent().unwrap().join("data").join("nist-spce").join(path); let mut system = TrajectoryBuilder::new().open(&path).and_then(|mut traj| traj.read()).unwrap(); let mut file = File::open(path).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); let line = buffer.lines().nth(1).unwrap(); let mut splited = line.split_whitespace(); assert_eq!(splited.next(), Some("cell:")); let a: f64 = splited.next() .expect("Missing 'a' cell parameter") .parse() .expect("'a' cell parameter is not a float"); let b: f64 = splited.next() .expect("Missing 'b' cell parameter") .parse() .expect("'b' cell parameter is not a float"); let c: f64 = splited.next() .expect("Missing 'c' cell parameter") .parse()
identifier_body
nist-spce.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff extern crate lumol; use lumol::consts::K_BOLTZMANN; use lumol::energy::{CoulombicPotential, Ewald, PairRestriction, SharedEwald}; use lumol::energy::{LennardJones, NullPotential, PairInteraction}; use lumol::sys::{System, UnitCell}; use lumol::sys::TrajectoryBuilder; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn get_system(path: &str, cutoff: f64) -> System { let path = Path::new(file!()).parent().unwrap().join("data").join("nist-spce").join(path); let mut system = TrajectoryBuilder::new().open(&path).and_then(|mut traj| traj.read()).unwrap(); let mut file = File::open(path).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); let line = buffer.lines().nth(1).unwrap(); let mut splited = line.split_whitespace(); assert_eq!(splited.next(), Some("cell:")); let a: f64 = splited.next() .expect("Missing 'a' cell parameter") .parse() .expect("'a' cell parameter is not a float"); let b: f64 = splited.next() .expect("Missing 'b' cell parameter") .parse() .expect("'b' cell parameter is not a float"); let c: f64 = splited.next() .expect("Missing 'c' cell parameter") .parse() .expect("'c' cell parameter is not a float"); system.cell = UnitCell::ortho(a, b, c); for i in 0..system.size() { if i % 3 == 0 { system.add_bond(i, i + 1); system.add_bond(i, i + 2); } } for particle in system.particles_mut() { match particle.name.as_ref() { "H" => *particle.charge = 0.42380, "O" => *particle.charge = -2.0 * 0.42380, other => panic!("Unknown particle name: {}", other), } } let mut lj = PairInteraction::new( Box::new(LennardJones { epsilon: 78.19743111 * K_BOLTZMANN, sigma: 3.16555789, }), cutoff, ); lj.enable_tail_corrections(); system.add_pair_potential(("O", "O"), lj); system.add_pair_potential(("O", "H"), PairInteraction::new(Box::new(NullPotential), cutoff)); system.add_pair_potential(("H", "H"), PairInteraction::new(Box::new(NullPotential), cutoff)); let mut ewald = Ewald::new(cutoff, 5); ewald.set_alpha(5.6 / f64::min(f64::min(a, b), c)); let mut ewald = SharedEwald::new(ewald); ewald.set_restriction(PairRestriction::InterMolecular); system.set_coulomb_potential(Box::new(ewald)); return system; } mod cutoff_9 { use super::*; use lumol::consts::K_BOLTZMANN; #[test] fn nist1() { let system = get_system("spce-1.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -4.88608e5; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist2() { let system = get_system("spce-2.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06602e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist3() { let system = get_system("spce-3.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.71488e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist4() { let system = get_system("spce-4.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -3.08010e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } } mod cutoff_10 { use super::*; use lumol::consts::K_BOLTZMANN; #[test] fn nist1() { let system = get_system("spce-1.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -4.88604e5; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nis
{ let system = get_system("spce-2.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06590e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist3() { let system = get_system("spce-3.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.71488e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } #[test] fn nist4() { let system = get_system("spce-4.xyz", 10.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -3.20501e6; assert!(f64::abs((energy - expected) / expected) < 1e-3); } }
t2()
identifier_name
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.conf` //! automatically implement the `WeakReferenceable` trait in codegen. //! The instance object is responsible for setting `None` in its own //! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT` //! slot. When all associated `WeakRef` values are dropped, the //! `WeakBox` itself is dropped too. use core::nonzero::NonZero; use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::trace::JSTraceable; use heapsize::HeapSizeOf; use js::jsapi::{JSTracer, JS_GetReservedSlot, JS_SetReservedSlot}; use js::jsval::PrivateValue; use libc::c_void; use std::cell::{Cell, UnsafeCell}; use std::mem; use std::ops::{Deref, DerefMut, Drop}; /// The index of the slot wherein a pointer to the weak holder cell is /// stored for weak-referenceable bindings. We use slot 1 for holding it, /// this is unsafe for globals, we disallow weak-referenceable globals /// directly in codegen. pub const DOM_WEAK_SLOT: u32 = 1; /// A weak reference to a JS-managed DOM object. #[allow_unrooted_interior] pub struct WeakRef<T: WeakReferenceable> { ptr: NonZero<*mut WeakBox<T>>, } /// The inner box of weak references, public for the finalization in codegen. #[must_root] pub struct WeakBox<T: WeakReferenceable> { /// The reference count. When it reaches zero, the `value` field should /// have already been set to `None`. The pointee contributes one to the count. pub count: Cell<usize>, /// The pointer to the JS-managed object, set to None when it is collected. pub value: Cell<Option<NonZero<*const T>>>, } /// Trait implemented by weak-referenceable interfaces. pub trait WeakReferenceable: DomObject + Sized { /// Downgrade a DOM object reference to a weak one. fn downgrade(&self) -> WeakRef<Self> { unsafe { let object = self.reflector().get_jsobject().get(); let mut ptr = JS_GetReservedSlot(object, DOM_WEAK_SLOT) .to_private() as *mut WeakBox<Self>; if ptr.is_null() { trace!("Creating new WeakBox holder for {:p}.", self); ptr = Box::into_raw(box WeakBox { count: Cell::new(1), value: Cell::new(Some(NonZero::new(self))), }); JS_SetReservedSlot(object, DOM_WEAK_SLOT, PrivateValue(ptr as *const c_void)); } let box_ = &*ptr; assert!(box_.value.get().is_some()); let new_count = box_.count.get() + 1; trace!("Incrementing WeakBox refcount for {:p} to {}.", self, new_count); box_.count.set(new_count); WeakRef { ptr: NonZero::new(ptr), } } } } impl<T: WeakReferenceable> WeakRef<T> { /// Create a new weak reference from a `WeakReferenceable` interface instance. /// This is just a convenience wrapper around `<T as WeakReferenceable>::downgrade` /// to not have to import `WeakReferenceable`. pub fn new(value: &T) -> Self { value.downgrade() } /// Root a weak reference. Returns `None` if the object was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.ptr.get() }.value.get().map(Root::new) } /// Return whether the weakly-referenced object is still alive. pub fn is_alive(&self) -> bool { unsafe { &*self.ptr.get() }.value.get().is_some() } } impl<T: WeakReferenceable> Clone for WeakRef<T> { fn clone(&self) -> WeakRef<T> { unsafe { let box_ = &*self.ptr.get(); let new_count = box_.count.get() + 1; box_.count.set(new_count); WeakRef { ptr: self.ptr, } } } } impl<T: WeakReferenceable> HeapSizeOf for WeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } impl<T: WeakReferenceable> PartialEq for WeakRef<T> { fn eq(&self, other: &Self) -> bool { unsafe { (*self.ptr.get()).value.get() == (*other.ptr.get()).value.get() } } } impl<T: WeakReferenceable> PartialEq<T> for WeakRef<T> { fn eq(&self, other: &T) -> bool { unsafe { match (*self.ptr.get()).value.get() { Some(ptr) => ptr.get() == other, None => false, } } } } unsafe impl<T: WeakReferenceable> JSTraceable for WeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing. } } impl<T: WeakReferenceable> Drop for WeakRef<T> { fn drop(&mut self) { unsafe { let (count, value) = { let weak_box = &*self.ptr.get(); assert!(weak_box.count.get() > 0); let count = weak_box.count.get() - 1; weak_box.count.set(count); (count, weak_box.value.get()) }; if count == 0 { assert!(value.is_none()); mem::drop(Box::from_raw(self.ptr.get())); } } } } /// A mutable weak reference to a JS-managed DOM object. On tracing, /// the contained weak reference is dropped if the pointee was already /// collected. pub struct MutableWeakRef<T: WeakReferenceable> { cell: UnsafeCell<Option<WeakRef<T>>>, } impl<T: WeakReferenceable> MutableWeakRef<T> { /// Create a new mutable weak reference. pub fn new(value: Option<&T>) -> MutableWeakRef<T> { MutableWeakRef { cell: UnsafeCell::new(value.map(WeakRef::new)), } } /// Set the pointee of a mutable weak reference. pub fn set(&self, value: Option<&T>) { unsafe { *self.cell.get() = value.map(WeakRef::new); } } /// Root a mutable weak reference. Returns `None` if the object /// was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.cell.get() }.as_ref().and_then(WeakRef::root) } } impl<T: WeakReferenceable> HeapSizeOf for MutableWeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } unsafe impl<T: WeakReferenceable> JSTraceable for MutableWeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer) { let ptr = self.cell.get(); let should_drop = match *ptr { Some(ref value) =>!value.is_alive(), None => false, }; if should_drop { mem::drop((*ptr).take().unwrap()); } } } /// A vector of weak references. On tracing, the vector retains /// only references which still point to live objects. #[allow_unrooted_interior] #[derive(HeapSizeOf)] pub struct WeakRefVec<T: WeakReferenceable> { vec: Vec<WeakRef<T>>, } impl<T: WeakReferenceable> WeakRefVec<T> { /// Create a new vector of weak references. pub fn new() -> Self { WeakRefVec { vec: vec![] } } /// Calls a function on each reference which still points to a /// live object. The order of the references isn't preserved. pub fn update<F: FnMut(WeakRefEntry<T>)>(&mut self, mut f: F) { let mut i = 0; while i < self.vec.len() { if self.vec[i].is_alive() { f(WeakRefEntry { vec: self, index: &mut i }); } else { self.vec.swap_remove(i); } } } /// Clears the vector of its dead references. pub fn retain_alive(&mut self) { self.update(|_| ()); } } impl<T: WeakReferenceable> Deref for WeakRefVec<T> { type Target = Vec<WeakRef<T>>; fn deref(&self) -> &Vec<WeakRef<T>> { &self.vec } } impl<T: WeakReferenceable> DerefMut for WeakRefVec<T> { fn deref_mut(&mut self) -> &mut Vec<WeakRef<T>> { &mut self.vec } } /// An entry of a vector of weak references. Passed to the closure /// given to `WeakRefVec::update`. #[allow_unrooted_interior] pub struct WeakRefEntry<'a, T: WeakReferenceable + 'a> { vec: &'a mut WeakRefVec<T>, index: &'a mut usize, } impl<'a, T: WeakReferenceable + 'a> WeakRefEntry<'a, T> {
mem::forget(self); ref_ } } impl<'a, T: WeakReferenceable + 'a> Deref for WeakRefEntry<'a, T> { type Target = WeakRef<T>; fn deref(&self) -> &WeakRef<T> { &self.vec[*self.index] } } impl<'a, T: WeakReferenceable + 'a> Drop for WeakRefEntry<'a, T> { fn drop(&mut self) { *self.index += 1; } }
/// Remove the entry from the underlying vector of weak references. pub fn remove(self) -> WeakRef<T> { let ref_ = self.vec.swap_remove(*self.index);
random_line_split
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.conf` //! automatically implement the `WeakReferenceable` trait in codegen. //! The instance object is responsible for setting `None` in its own //! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT` //! slot. When all associated `WeakRef` values are dropped, the //! `WeakBox` itself is dropped too. use core::nonzero::NonZero; use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::trace::JSTraceable; use heapsize::HeapSizeOf; use js::jsapi::{JSTracer, JS_GetReservedSlot, JS_SetReservedSlot}; use js::jsval::PrivateValue; use libc::c_void; use std::cell::{Cell, UnsafeCell}; use std::mem; use std::ops::{Deref, DerefMut, Drop}; /// The index of the slot wherein a pointer to the weak holder cell is /// stored for weak-referenceable bindings. We use slot 1 for holding it, /// this is unsafe for globals, we disallow weak-referenceable globals /// directly in codegen. pub const DOM_WEAK_SLOT: u32 = 1; /// A weak reference to a JS-managed DOM object. #[allow_unrooted_interior] pub struct WeakRef<T: WeakReferenceable> { ptr: NonZero<*mut WeakBox<T>>, } /// The inner box of weak references, public for the finalization in codegen. #[must_root] pub struct WeakBox<T: WeakReferenceable> { /// The reference count. When it reaches zero, the `value` field should /// have already been set to `None`. The pointee contributes one to the count. pub count: Cell<usize>, /// The pointer to the JS-managed object, set to None when it is collected. pub value: Cell<Option<NonZero<*const T>>>, } /// Trait implemented by weak-referenceable interfaces. pub trait WeakReferenceable: DomObject + Sized { /// Downgrade a DOM object reference to a weak one. fn downgrade(&self) -> WeakRef<Self> { unsafe { let object = self.reflector().get_jsobject().get(); let mut ptr = JS_GetReservedSlot(object, DOM_WEAK_SLOT) .to_private() as *mut WeakBox<Self>; if ptr.is_null() { trace!("Creating new WeakBox holder for {:p}.", self); ptr = Box::into_raw(box WeakBox { count: Cell::new(1), value: Cell::new(Some(NonZero::new(self))), }); JS_SetReservedSlot(object, DOM_WEAK_SLOT, PrivateValue(ptr as *const c_void)); } let box_ = &*ptr; assert!(box_.value.get().is_some()); let new_count = box_.count.get() + 1; trace!("Incrementing WeakBox refcount for {:p} to {}.", self, new_count); box_.count.set(new_count); WeakRef { ptr: NonZero::new(ptr), } } } } impl<T: WeakReferenceable> WeakRef<T> { /// Create a new weak reference from a `WeakReferenceable` interface instance. /// This is just a convenience wrapper around `<T as WeakReferenceable>::downgrade` /// to not have to import `WeakReferenceable`. pub fn new(value: &T) -> Self { value.downgrade() } /// Root a weak reference. Returns `None` if the object was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.ptr.get() }.value.get().map(Root::new) } /// Return whether the weakly-referenced object is still alive. pub fn is_alive(&self) -> bool { unsafe { &*self.ptr.get() }.value.get().is_some() } } impl<T: WeakReferenceable> Clone for WeakRef<T> { fn clone(&self) -> WeakRef<T> { unsafe { let box_ = &*self.ptr.get(); let new_count = box_.count.get() + 1; box_.count.set(new_count); WeakRef { ptr: self.ptr, } } } } impl<T: WeakReferenceable> HeapSizeOf for WeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } impl<T: WeakReferenceable> PartialEq for WeakRef<T> { fn eq(&self, other: &Self) -> bool { unsafe { (*self.ptr.get()).value.get() == (*other.ptr.get()).value.get() } } } impl<T: WeakReferenceable> PartialEq<T> for WeakRef<T> { fn eq(&self, other: &T) -> bool { unsafe { match (*self.ptr.get()).value.get() { Some(ptr) => ptr.get() == other, None => false, } } } } unsafe impl<T: WeakReferenceable> JSTraceable for WeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing. } } impl<T: WeakReferenceable> Drop for WeakRef<T> { fn drop(&mut self) { unsafe { let (count, value) = { let weak_box = &*self.ptr.get(); assert!(weak_box.count.get() > 0); let count = weak_box.count.get() - 1; weak_box.count.set(count); (count, weak_box.value.get()) }; if count == 0 { assert!(value.is_none()); mem::drop(Box::from_raw(self.ptr.get())); } } } } /// A mutable weak reference to a JS-managed DOM object. On tracing, /// the contained weak reference is dropped if the pointee was already /// collected. pub struct MutableWeakRef<T: WeakReferenceable> { cell: UnsafeCell<Option<WeakRef<T>>>, } impl<T: WeakReferenceable> MutableWeakRef<T> { /// Create a new mutable weak reference. pub fn new(value: Option<&T>) -> MutableWeakRef<T> { MutableWeakRef { cell: UnsafeCell::new(value.map(WeakRef::new)), } } /// Set the pointee of a mutable weak reference. pub fn set(&self, value: Option<&T>) { unsafe { *self.cell.get() = value.map(WeakRef::new); } } /// Root a mutable weak reference. Returns `None` if the object /// was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.cell.get() }.as_ref().and_then(WeakRef::root) } } impl<T: WeakReferenceable> HeapSizeOf for MutableWeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } unsafe impl<T: WeakReferenceable> JSTraceable for MutableWeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer) { let ptr = self.cell.get(); let should_drop = match *ptr { Some(ref value) =>!value.is_alive(), None => false, }; if should_drop { mem::drop((*ptr).take().unwrap()); } } } /// A vector of weak references. On tracing, the vector retains /// only references which still point to live objects. #[allow_unrooted_interior] #[derive(HeapSizeOf)] pub struct WeakRefVec<T: WeakReferenceable> { vec: Vec<WeakRef<T>>, } impl<T: WeakReferenceable> WeakRefVec<T> { /// Create a new vector of weak references. pub fn new() -> Self { WeakRefVec { vec: vec![] } } /// Calls a function on each reference which still points to a /// live object. The order of the references isn't preserved. pub fn update<F: FnMut(WeakRefEntry<T>)>(&mut self, mut f: F) { let mut i = 0; while i < self.vec.len() { if self.vec[i].is_alive()
else { self.vec.swap_remove(i); } } } /// Clears the vector of its dead references. pub fn retain_alive(&mut self) { self.update(|_| ()); } } impl<T: WeakReferenceable> Deref for WeakRefVec<T> { type Target = Vec<WeakRef<T>>; fn deref(&self) -> &Vec<WeakRef<T>> { &self.vec } } impl<T: WeakReferenceable> DerefMut for WeakRefVec<T> { fn deref_mut(&mut self) -> &mut Vec<WeakRef<T>> { &mut self.vec } } /// An entry of a vector of weak references. Passed to the closure /// given to `WeakRefVec::update`. #[allow_unrooted_interior] pub struct WeakRefEntry<'a, T: WeakReferenceable + 'a> { vec: &'a mut WeakRefVec<T>, index: &'a mut usize, } impl<'a, T: WeakReferenceable + 'a> WeakRefEntry<'a, T> { /// Remove the entry from the underlying vector of weak references. pub fn remove(self) -> WeakRef<T> { let ref_ = self.vec.swap_remove(*self.index); mem::forget(self); ref_ } } impl<'a, T: WeakReferenceable + 'a> Deref for WeakRefEntry<'a, T> { type Target = WeakRef<T>; fn deref(&self) -> &WeakRef<T> { &self.vec[*self.index] } } impl<'a, T: WeakReferenceable + 'a> Drop for WeakRefEntry<'a, T> { fn drop(&mut self) { *self.index += 1; } }
{ f(WeakRefEntry { vec: self, index: &mut i }); }
conditional_block
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.conf` //! automatically implement the `WeakReferenceable` trait in codegen. //! The instance object is responsible for setting `None` in its own //! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT` //! slot. When all associated `WeakRef` values are dropped, the //! `WeakBox` itself is dropped too. use core::nonzero::NonZero; use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::trace::JSTraceable; use heapsize::HeapSizeOf; use js::jsapi::{JSTracer, JS_GetReservedSlot, JS_SetReservedSlot}; use js::jsval::PrivateValue; use libc::c_void; use std::cell::{Cell, UnsafeCell}; use std::mem; use std::ops::{Deref, DerefMut, Drop}; /// The index of the slot wherein a pointer to the weak holder cell is /// stored for weak-referenceable bindings. We use slot 1 for holding it, /// this is unsafe for globals, we disallow weak-referenceable globals /// directly in codegen. pub const DOM_WEAK_SLOT: u32 = 1; /// A weak reference to a JS-managed DOM object. #[allow_unrooted_interior] pub struct WeakRef<T: WeakReferenceable> { ptr: NonZero<*mut WeakBox<T>>, } /// The inner box of weak references, public for the finalization in codegen. #[must_root] pub struct WeakBox<T: WeakReferenceable> { /// The reference count. When it reaches zero, the `value` field should /// have already been set to `None`. The pointee contributes one to the count. pub count: Cell<usize>, /// The pointer to the JS-managed object, set to None when it is collected. pub value: Cell<Option<NonZero<*const T>>>, } /// Trait implemented by weak-referenceable interfaces. pub trait WeakReferenceable: DomObject + Sized { /// Downgrade a DOM object reference to a weak one. fn downgrade(&self) -> WeakRef<Self> { unsafe { let object = self.reflector().get_jsobject().get(); let mut ptr = JS_GetReservedSlot(object, DOM_WEAK_SLOT) .to_private() as *mut WeakBox<Self>; if ptr.is_null() { trace!("Creating new WeakBox holder for {:p}.", self); ptr = Box::into_raw(box WeakBox { count: Cell::new(1), value: Cell::new(Some(NonZero::new(self))), }); JS_SetReservedSlot(object, DOM_WEAK_SLOT, PrivateValue(ptr as *const c_void)); } let box_ = &*ptr; assert!(box_.value.get().is_some()); let new_count = box_.count.get() + 1; trace!("Incrementing WeakBox refcount for {:p} to {}.", self, new_count); box_.count.set(new_count); WeakRef { ptr: NonZero::new(ptr), } } } } impl<T: WeakReferenceable> WeakRef<T> { /// Create a new weak reference from a `WeakReferenceable` interface instance. /// This is just a convenience wrapper around `<T as WeakReferenceable>::downgrade` /// to not have to import `WeakReferenceable`. pub fn new(value: &T) -> Self { value.downgrade() } /// Root a weak reference. Returns `None` if the object was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.ptr.get() }.value.get().map(Root::new) } /// Return whether the weakly-referenced object is still alive. pub fn is_alive(&self) -> bool { unsafe { &*self.ptr.get() }.value.get().is_some() } } impl<T: WeakReferenceable> Clone for WeakRef<T> { fn clone(&self) -> WeakRef<T> { unsafe { let box_ = &*self.ptr.get(); let new_count = box_.count.get() + 1; box_.count.set(new_count); WeakRef { ptr: self.ptr, } } } } impl<T: WeakReferenceable> HeapSizeOf for WeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } impl<T: WeakReferenceable> PartialEq for WeakRef<T> { fn eq(&self, other: &Self) -> bool { unsafe { (*self.ptr.get()).value.get() == (*other.ptr.get()).value.get() } } } impl<T: WeakReferenceable> PartialEq<T> for WeakRef<T> { fn eq(&self, other: &T) -> bool { unsafe { match (*self.ptr.get()).value.get() { Some(ptr) => ptr.get() == other, None => false, } } } } unsafe impl<T: WeakReferenceable> JSTraceable for WeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer)
} impl<T: WeakReferenceable> Drop for WeakRef<T> { fn drop(&mut self) { unsafe { let (count, value) = { let weak_box = &*self.ptr.get(); assert!(weak_box.count.get() > 0); let count = weak_box.count.get() - 1; weak_box.count.set(count); (count, weak_box.value.get()) }; if count == 0 { assert!(value.is_none()); mem::drop(Box::from_raw(self.ptr.get())); } } } } /// A mutable weak reference to a JS-managed DOM object. On tracing, /// the contained weak reference is dropped if the pointee was already /// collected. pub struct MutableWeakRef<T: WeakReferenceable> { cell: UnsafeCell<Option<WeakRef<T>>>, } impl<T: WeakReferenceable> MutableWeakRef<T> { /// Create a new mutable weak reference. pub fn new(value: Option<&T>) -> MutableWeakRef<T> { MutableWeakRef { cell: UnsafeCell::new(value.map(WeakRef::new)), } } /// Set the pointee of a mutable weak reference. pub fn set(&self, value: Option<&T>) { unsafe { *self.cell.get() = value.map(WeakRef::new); } } /// Root a mutable weak reference. Returns `None` if the object /// was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.cell.get() }.as_ref().and_then(WeakRef::root) } } impl<T: WeakReferenceable> HeapSizeOf for MutableWeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } unsafe impl<T: WeakReferenceable> JSTraceable for MutableWeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer) { let ptr = self.cell.get(); let should_drop = match *ptr { Some(ref value) =>!value.is_alive(), None => false, }; if should_drop { mem::drop((*ptr).take().unwrap()); } } } /// A vector of weak references. On tracing, the vector retains /// only references which still point to live objects. #[allow_unrooted_interior] #[derive(HeapSizeOf)] pub struct WeakRefVec<T: WeakReferenceable> { vec: Vec<WeakRef<T>>, } impl<T: WeakReferenceable> WeakRefVec<T> { /// Create a new vector of weak references. pub fn new() -> Self { WeakRefVec { vec: vec![] } } /// Calls a function on each reference which still points to a /// live object. The order of the references isn't preserved. pub fn update<F: FnMut(WeakRefEntry<T>)>(&mut self, mut f: F) { let mut i = 0; while i < self.vec.len() { if self.vec[i].is_alive() { f(WeakRefEntry { vec: self, index: &mut i }); } else { self.vec.swap_remove(i); } } } /// Clears the vector of its dead references. pub fn retain_alive(&mut self) { self.update(|_| ()); } } impl<T: WeakReferenceable> Deref for WeakRefVec<T> { type Target = Vec<WeakRef<T>>; fn deref(&self) -> &Vec<WeakRef<T>> { &self.vec } } impl<T: WeakReferenceable> DerefMut for WeakRefVec<T> { fn deref_mut(&mut self) -> &mut Vec<WeakRef<T>> { &mut self.vec } } /// An entry of a vector of weak references. Passed to the closure /// given to `WeakRefVec::update`. #[allow_unrooted_interior] pub struct WeakRefEntry<'a, T: WeakReferenceable + 'a> { vec: &'a mut WeakRefVec<T>, index: &'a mut usize, } impl<'a, T: WeakReferenceable + 'a> WeakRefEntry<'a, T> { /// Remove the entry from the underlying vector of weak references. pub fn remove(self) -> WeakRef<T> { let ref_ = self.vec.swap_remove(*self.index); mem::forget(self); ref_ } } impl<'a, T: WeakReferenceable + 'a> Deref for WeakRefEntry<'a, T> { type Target = WeakRef<T>; fn deref(&self) -> &WeakRef<T> { &self.vec[*self.index] } } impl<'a, T: WeakReferenceable + 'a> Drop for WeakRefEntry<'a, T> { fn drop(&mut self) { *self.index += 1; } }
{ // Do nothing. }
identifier_body
weakref.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/. */ //! Weak-referenceable JS-managed DOM objects. //! //! IDL interfaces marked as `weakReferenceable` in `Bindings.conf` //! automatically implement the `WeakReferenceable` trait in codegen. //! The instance object is responsible for setting `None` in its own //! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT` //! slot. When all associated `WeakRef` values are dropped, the //! `WeakBox` itself is dropped too. use core::nonzero::NonZero; use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::trace::JSTraceable; use heapsize::HeapSizeOf; use js::jsapi::{JSTracer, JS_GetReservedSlot, JS_SetReservedSlot}; use js::jsval::PrivateValue; use libc::c_void; use std::cell::{Cell, UnsafeCell}; use std::mem; use std::ops::{Deref, DerefMut, Drop}; /// The index of the slot wherein a pointer to the weak holder cell is /// stored for weak-referenceable bindings. We use slot 1 for holding it, /// this is unsafe for globals, we disallow weak-referenceable globals /// directly in codegen. pub const DOM_WEAK_SLOT: u32 = 1; /// A weak reference to a JS-managed DOM object. #[allow_unrooted_interior] pub struct WeakRef<T: WeakReferenceable> { ptr: NonZero<*mut WeakBox<T>>, } /// The inner box of weak references, public for the finalization in codegen. #[must_root] pub struct WeakBox<T: WeakReferenceable> { /// The reference count. When it reaches zero, the `value` field should /// have already been set to `None`. The pointee contributes one to the count. pub count: Cell<usize>, /// The pointer to the JS-managed object, set to None when it is collected. pub value: Cell<Option<NonZero<*const T>>>, } /// Trait implemented by weak-referenceable interfaces. pub trait WeakReferenceable: DomObject + Sized { /// Downgrade a DOM object reference to a weak one. fn downgrade(&self) -> WeakRef<Self> { unsafe { let object = self.reflector().get_jsobject().get(); let mut ptr = JS_GetReservedSlot(object, DOM_WEAK_SLOT) .to_private() as *mut WeakBox<Self>; if ptr.is_null() { trace!("Creating new WeakBox holder for {:p}.", self); ptr = Box::into_raw(box WeakBox { count: Cell::new(1), value: Cell::new(Some(NonZero::new(self))), }); JS_SetReservedSlot(object, DOM_WEAK_SLOT, PrivateValue(ptr as *const c_void)); } let box_ = &*ptr; assert!(box_.value.get().is_some()); let new_count = box_.count.get() + 1; trace!("Incrementing WeakBox refcount for {:p} to {}.", self, new_count); box_.count.set(new_count); WeakRef { ptr: NonZero::new(ptr), } } } } impl<T: WeakReferenceable> WeakRef<T> { /// Create a new weak reference from a `WeakReferenceable` interface instance. /// This is just a convenience wrapper around `<T as WeakReferenceable>::downgrade` /// to not have to import `WeakReferenceable`. pub fn new(value: &T) -> Self { value.downgrade() } /// Root a weak reference. Returns `None` if the object was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.ptr.get() }.value.get().map(Root::new) } /// Return whether the weakly-referenced object is still alive. pub fn is_alive(&self) -> bool { unsafe { &*self.ptr.get() }.value.get().is_some() } } impl<T: WeakReferenceable> Clone for WeakRef<T> { fn clone(&self) -> WeakRef<T> { unsafe { let box_ = &*self.ptr.get(); let new_count = box_.count.get() + 1; box_.count.set(new_count); WeakRef { ptr: self.ptr, } } } } impl<T: WeakReferenceable> HeapSizeOf for WeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } impl<T: WeakReferenceable> PartialEq for WeakRef<T> { fn eq(&self, other: &Self) -> bool { unsafe { (*self.ptr.get()).value.get() == (*other.ptr.get()).value.get() } } } impl<T: WeakReferenceable> PartialEq<T> for WeakRef<T> { fn eq(&self, other: &T) -> bool { unsafe { match (*self.ptr.get()).value.get() { Some(ptr) => ptr.get() == other, None => false, } } } } unsafe impl<T: WeakReferenceable> JSTraceable for WeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing. } } impl<T: WeakReferenceable> Drop for WeakRef<T> { fn drop(&mut self) { unsafe { let (count, value) = { let weak_box = &*self.ptr.get(); assert!(weak_box.count.get() > 0); let count = weak_box.count.get() - 1; weak_box.count.set(count); (count, weak_box.value.get()) }; if count == 0 { assert!(value.is_none()); mem::drop(Box::from_raw(self.ptr.get())); } } } } /// A mutable weak reference to a JS-managed DOM object. On tracing, /// the contained weak reference is dropped if the pointee was already /// collected. pub struct MutableWeakRef<T: WeakReferenceable> { cell: UnsafeCell<Option<WeakRef<T>>>, } impl<T: WeakReferenceable> MutableWeakRef<T> { /// Create a new mutable weak reference. pub fn new(value: Option<&T>) -> MutableWeakRef<T> { MutableWeakRef { cell: UnsafeCell::new(value.map(WeakRef::new)), } } /// Set the pointee of a mutable weak reference. pub fn set(&self, value: Option<&T>) { unsafe { *self.cell.get() = value.map(WeakRef::new); } } /// Root a mutable weak reference. Returns `None` if the object /// was already collected. pub fn root(&self) -> Option<Root<T>> { unsafe { &*self.cell.get() }.as_ref().and_then(WeakRef::root) } } impl<T: WeakReferenceable> HeapSizeOf for MutableWeakRef<T> { fn heap_size_of_children(&self) -> usize { 0 } } unsafe impl<T: WeakReferenceable> JSTraceable for MutableWeakRef<T> { unsafe fn trace(&self, _: *mut JSTracer) { let ptr = self.cell.get(); let should_drop = match *ptr { Some(ref value) =>!value.is_alive(), None => false, }; if should_drop { mem::drop((*ptr).take().unwrap()); } } } /// A vector of weak references. On tracing, the vector retains /// only references which still point to live objects. #[allow_unrooted_interior] #[derive(HeapSizeOf)] pub struct
<T: WeakReferenceable> { vec: Vec<WeakRef<T>>, } impl<T: WeakReferenceable> WeakRefVec<T> { /// Create a new vector of weak references. pub fn new() -> Self { WeakRefVec { vec: vec![] } } /// Calls a function on each reference which still points to a /// live object. The order of the references isn't preserved. pub fn update<F: FnMut(WeakRefEntry<T>)>(&mut self, mut f: F) { let mut i = 0; while i < self.vec.len() { if self.vec[i].is_alive() { f(WeakRefEntry { vec: self, index: &mut i }); } else { self.vec.swap_remove(i); } } } /// Clears the vector of its dead references. pub fn retain_alive(&mut self) { self.update(|_| ()); } } impl<T: WeakReferenceable> Deref for WeakRefVec<T> { type Target = Vec<WeakRef<T>>; fn deref(&self) -> &Vec<WeakRef<T>> { &self.vec } } impl<T: WeakReferenceable> DerefMut for WeakRefVec<T> { fn deref_mut(&mut self) -> &mut Vec<WeakRef<T>> { &mut self.vec } } /// An entry of a vector of weak references. Passed to the closure /// given to `WeakRefVec::update`. #[allow_unrooted_interior] pub struct WeakRefEntry<'a, T: WeakReferenceable + 'a> { vec: &'a mut WeakRefVec<T>, index: &'a mut usize, } impl<'a, T: WeakReferenceable + 'a> WeakRefEntry<'a, T> { /// Remove the entry from the underlying vector of weak references. pub fn remove(self) -> WeakRef<T> { let ref_ = self.vec.swap_remove(*self.index); mem::forget(self); ref_ } } impl<'a, T: WeakReferenceable + 'a> Deref for WeakRefEntry<'a, T> { type Target = WeakRef<T>; fn deref(&self) -> &WeakRef<T> { &self.vec[*self.index] } } impl<'a, T: WeakReferenceable + 'a> Drop for WeakRefEntry<'a, T> { fn drop(&mut self) { *self.index += 1; } }
WeakRefVec
identifier_name
refcounted.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 generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task for asynchronous events). Akin to Gecko's //! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures //! that the actual SpiderMonkey GC integration occurs on the script task via //! message passing. Ownership of a `Trusted<T>` object means the DOM object of //! type T to which it points remains alive. Any other behaviour is undefined. //! To guarantee the lifetime of a DOM object when performing asynchronous operations, //! obtain a `Trusted<T>` from that object and pass it along with each operation. //! A usable pointer to the original DOM object can be obtained on the script task //! from a `Trusted<T>` via the `to_temporary` method. //! //! The implementation of Trusted<T> is as follows: //! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object. //! The values in this hashtable are atomic reference counts. When a Trusted<T> object is //! created or cloned, this count is increased. When a Trusted<T> is dropped, the count //! decreases. If the count hits zero, a message is dispatched to the script task to remove //! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object //! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry //! is removed. use dom::bindings::js::{Temporary, JSRef, Unrooted}; use dom::bindings::utils::{Reflector, Reflectable}; use script_task::{ScriptMsg, ScriptChan}; use js::jsapi::{JS_AddObjectRoot, JS_RemoveObjectRoot, JSContext}; use libc; use std::cell::RefCell; use std::collections::hash_map::HashMap; use std::collections::hash_map::Entry::{Vacant, Occupied}; use std::marker::PhantomData; use std::rc::Rc; use std::sync::{Arc, Mutex}; thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None))); /// A pointer to a Rust DOM object that needs to be destroyed. pub struct TrustedReference(*const libc::c_void); unsafe impl Send for TrustedReference {} /// A safe wrapper around a raw pointer to a DOM object that can be /// shared among tasks for use in asynchronous operations. The underlying /// DOM object is guaranteed to live at least as long as the last outstanding /// `Trusted<T>` instance. pub struct Trusted<T: Reflectable> { /// A pointer to the Rust DOM object of type T, but void to allow /// sending `Trusted<T>` between tasks, regardless of T's sendability. ptr: *const libc::c_void, refcount: Arc<Mutex<usize>>, script_chan: Box<ScriptChan + Send>, owner_thread: *const libc::c_void, phantom: PhantomData<T>, } unsafe impl<T: Reflectable> Send for Trusted<T> {} impl<T: Reflectable> Trusted<T> { /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's /// lifetime. pub fn new(cx: *mut JSContext, ptr: JSRef<T>, script_chan: Box<ScriptChan + Send>) -> Trusted<T> { LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let refcount = live_references.addref(cx, &*ptr as *const T); Trusted { ptr: &*ptr as *const T as *const libc::c_void, refcount: refcount, script_chan: script_chan.clone(), owner_thread: (&*live_references) as *const _ as *const libc::c_void, phantom: PhantomData, } }) } /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on /// a different thread than the original value from which this `Trusted<T>` was /// obtained. pub fn
(&self) -> Temporary<T> { assert!(LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); unsafe { Temporary::from_unrooted(Unrooted::from_raw(self.ptr as *const T)) } } } impl<T: Reflectable> Clone for Trusted<T> { fn clone(&self) -> Trusted<T> { { let mut refcount = self.refcount.lock().unwrap(); *refcount += 1; } Trusted { ptr: self.ptr, refcount: self.refcount.clone(), script_chan: self.script_chan.clone(), owner_thread: self.owner_thread, phantom: PhantomData, } } } #[unsafe_destructor] impl<T: Reflectable> Drop for Trusted<T> { fn drop(&mut self) { let mut refcount = self.refcount.lock().unwrap(); assert!(*refcount > 0); *refcount -= 1; if *refcount == 0 { // It's possible this send will fail if the script task // has already exited. There's not much we can do at this // point though. let msg = ScriptMsg::RefcountCleanup(TrustedReference(self.ptr)); let _ = self.script_chan.send(msg); } } } /// The set of live, pinned DOM objects that are currently prevented /// from being garbage collected due to outstanding references. pub struct LiveDOMReferences { // keyed on pointer to Rust DOM object table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>> } impl LiveDOMReferences { /// Set up the task-local data required for storing the outstanding DOM references. pub fn initialize() { LIVE_REFERENCES.with(|ref r| { *r.borrow_mut() = Some(LiveDOMReferences { table: RefCell::new(HashMap::new()), }) }); } fn addref<T: Reflectable>(&self, cx: *mut JSContext, ptr: *const T) -> Arc<Mutex<usize>> { let mut table = self.table.borrow_mut(); match table.entry(ptr as *const libc::c_void) { Occupied(mut entry) => { let refcount = entry.get_mut(); *refcount.lock().unwrap() += 1; refcount.clone() } Vacant(entry) => { unsafe { let rootable = (*ptr).reflector().rootable(); JS_AddObjectRoot(cx, rootable); } let refcount = Arc::new(Mutex::new(1)); entry.insert(refcount.clone()); refcount } } } /// Unpin the given DOM object if its refcount is 0. pub fn cleanup(cx: *mut JSContext, raw_reflectable: TrustedReference) { let TrustedReference(raw_reflectable) = raw_reflectable; LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let reflectable = raw_reflectable as *const Reflector; let mut table = live_references.table.borrow_mut(); match table.entry(raw_reflectable) { Occupied(entry) => { if *entry.get().lock().unwrap()!= 0 { // there could have been a new reference taken since // this message was dispatched. return; } unsafe { JS_RemoveObjectRoot(cx, (*reflectable).rootable()); } let _ = entry.remove(); } Vacant(_) => { // there could be a cleanup message dispatched, then a new // pinned reference obtained and released before the message // is processed, at which point there would be no matching // hashtable entry. info!("attempt to cleanup an unrecognized reflector"); } } }) } }
to_temporary
identifier_name
refcounted.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 generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task for asynchronous events). Akin to Gecko's //! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures //! that the actual SpiderMonkey GC integration occurs on the script task via //! message passing. Ownership of a `Trusted<T>` object means the DOM object of //! type T to which it points remains alive. Any other behaviour is undefined. //! To guarantee the lifetime of a DOM object when performing asynchronous operations, //! obtain a `Trusted<T>` from that object and pass it along with each operation. //! A usable pointer to the original DOM object can be obtained on the script task //! from a `Trusted<T>` via the `to_temporary` method. //! //! The implementation of Trusted<T> is as follows: //! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object. //! The values in this hashtable are atomic reference counts. When a Trusted<T> object is //! created or cloned, this count is increased. When a Trusted<T> is dropped, the count //! decreases. If the count hits zero, a message is dispatched to the script task to remove //! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object //! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry //! is removed. use dom::bindings::js::{Temporary, JSRef, Unrooted}; use dom::bindings::utils::{Reflector, Reflectable}; use script_task::{ScriptMsg, ScriptChan}; use js::jsapi::{JS_AddObjectRoot, JS_RemoveObjectRoot, JSContext}; use libc; use std::cell::RefCell; use std::collections::hash_map::HashMap; use std::collections::hash_map::Entry::{Vacant, Occupied}; use std::marker::PhantomData; use std::rc::Rc; use std::sync::{Arc, Mutex}; thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None))); /// A pointer to a Rust DOM object that needs to be destroyed. pub struct TrustedReference(*const libc::c_void); unsafe impl Send for TrustedReference {}
pub struct Trusted<T: Reflectable> { /// A pointer to the Rust DOM object of type T, but void to allow /// sending `Trusted<T>` between tasks, regardless of T's sendability. ptr: *const libc::c_void, refcount: Arc<Mutex<usize>>, script_chan: Box<ScriptChan + Send>, owner_thread: *const libc::c_void, phantom: PhantomData<T>, } unsafe impl<T: Reflectable> Send for Trusted<T> {} impl<T: Reflectable> Trusted<T> { /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's /// lifetime. pub fn new(cx: *mut JSContext, ptr: JSRef<T>, script_chan: Box<ScriptChan + Send>) -> Trusted<T> { LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let refcount = live_references.addref(cx, &*ptr as *const T); Trusted { ptr: &*ptr as *const T as *const libc::c_void, refcount: refcount, script_chan: script_chan.clone(), owner_thread: (&*live_references) as *const _ as *const libc::c_void, phantom: PhantomData, } }) } /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on /// a different thread than the original value from which this `Trusted<T>` was /// obtained. pub fn to_temporary(&self) -> Temporary<T> { assert!(LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); unsafe { Temporary::from_unrooted(Unrooted::from_raw(self.ptr as *const T)) } } } impl<T: Reflectable> Clone for Trusted<T> { fn clone(&self) -> Trusted<T> { { let mut refcount = self.refcount.lock().unwrap(); *refcount += 1; } Trusted { ptr: self.ptr, refcount: self.refcount.clone(), script_chan: self.script_chan.clone(), owner_thread: self.owner_thread, phantom: PhantomData, } } } #[unsafe_destructor] impl<T: Reflectable> Drop for Trusted<T> { fn drop(&mut self) { let mut refcount = self.refcount.lock().unwrap(); assert!(*refcount > 0); *refcount -= 1; if *refcount == 0 { // It's possible this send will fail if the script task // has already exited. There's not much we can do at this // point though. let msg = ScriptMsg::RefcountCleanup(TrustedReference(self.ptr)); let _ = self.script_chan.send(msg); } } } /// The set of live, pinned DOM objects that are currently prevented /// from being garbage collected due to outstanding references. pub struct LiveDOMReferences { // keyed on pointer to Rust DOM object table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>> } impl LiveDOMReferences { /// Set up the task-local data required for storing the outstanding DOM references. pub fn initialize() { LIVE_REFERENCES.with(|ref r| { *r.borrow_mut() = Some(LiveDOMReferences { table: RefCell::new(HashMap::new()), }) }); } fn addref<T: Reflectable>(&self, cx: *mut JSContext, ptr: *const T) -> Arc<Mutex<usize>> { let mut table = self.table.borrow_mut(); match table.entry(ptr as *const libc::c_void) { Occupied(mut entry) => { let refcount = entry.get_mut(); *refcount.lock().unwrap() += 1; refcount.clone() } Vacant(entry) => { unsafe { let rootable = (*ptr).reflector().rootable(); JS_AddObjectRoot(cx, rootable); } let refcount = Arc::new(Mutex::new(1)); entry.insert(refcount.clone()); refcount } } } /// Unpin the given DOM object if its refcount is 0. pub fn cleanup(cx: *mut JSContext, raw_reflectable: TrustedReference) { let TrustedReference(raw_reflectable) = raw_reflectable; LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let reflectable = raw_reflectable as *const Reflector; let mut table = live_references.table.borrow_mut(); match table.entry(raw_reflectable) { Occupied(entry) => { if *entry.get().lock().unwrap()!= 0 { // there could have been a new reference taken since // this message was dispatched. return; } unsafe { JS_RemoveObjectRoot(cx, (*reflectable).rootable()); } let _ = entry.remove(); } Vacant(_) => { // there could be a cleanup message dispatched, then a new // pinned reference obtained and released before the message // is processed, at which point there would be no matching // hashtable entry. info!("attempt to cleanup an unrecognized reflector"); } } }) } }
/// A safe wrapper around a raw pointer to a DOM object that can be /// shared among tasks for use in asynchronous operations. The underlying /// DOM object is guaranteed to live at least as long as the last outstanding /// `Trusted<T>` instance.
random_line_split
refcounted.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 generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task for asynchronous events). Akin to Gecko's //! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures //! that the actual SpiderMonkey GC integration occurs on the script task via //! message passing. Ownership of a `Trusted<T>` object means the DOM object of //! type T to which it points remains alive. Any other behaviour is undefined. //! To guarantee the lifetime of a DOM object when performing asynchronous operations, //! obtain a `Trusted<T>` from that object and pass it along with each operation. //! A usable pointer to the original DOM object can be obtained on the script task //! from a `Trusted<T>` via the `to_temporary` method. //! //! The implementation of Trusted<T> is as follows: //! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object. //! The values in this hashtable are atomic reference counts. When a Trusted<T> object is //! created or cloned, this count is increased. When a Trusted<T> is dropped, the count //! decreases. If the count hits zero, a message is dispatched to the script task to remove //! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object //! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry //! is removed. use dom::bindings::js::{Temporary, JSRef, Unrooted}; use dom::bindings::utils::{Reflector, Reflectable}; use script_task::{ScriptMsg, ScriptChan}; use js::jsapi::{JS_AddObjectRoot, JS_RemoveObjectRoot, JSContext}; use libc; use std::cell::RefCell; use std::collections::hash_map::HashMap; use std::collections::hash_map::Entry::{Vacant, Occupied}; use std::marker::PhantomData; use std::rc::Rc; use std::sync::{Arc, Mutex}; thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None))); /// A pointer to a Rust DOM object that needs to be destroyed. pub struct TrustedReference(*const libc::c_void); unsafe impl Send for TrustedReference {} /// A safe wrapper around a raw pointer to a DOM object that can be /// shared among tasks for use in asynchronous operations. The underlying /// DOM object is guaranteed to live at least as long as the last outstanding /// `Trusted<T>` instance. pub struct Trusted<T: Reflectable> { /// A pointer to the Rust DOM object of type T, but void to allow /// sending `Trusted<T>` between tasks, regardless of T's sendability. ptr: *const libc::c_void, refcount: Arc<Mutex<usize>>, script_chan: Box<ScriptChan + Send>, owner_thread: *const libc::c_void, phantom: PhantomData<T>, } unsafe impl<T: Reflectable> Send for Trusted<T> {} impl<T: Reflectable> Trusted<T> { /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's /// lifetime. pub fn new(cx: *mut JSContext, ptr: JSRef<T>, script_chan: Box<ScriptChan + Send>) -> Trusted<T> { LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let refcount = live_references.addref(cx, &*ptr as *const T); Trusted { ptr: &*ptr as *const T as *const libc::c_void, refcount: refcount, script_chan: script_chan.clone(), owner_thread: (&*live_references) as *const _ as *const libc::c_void, phantom: PhantomData, } }) } /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on /// a different thread than the original value from which this `Trusted<T>` was /// obtained. pub fn to_temporary(&self) -> Temporary<T>
} impl<T: Reflectable> Clone for Trusted<T> { fn clone(&self) -> Trusted<T> { { let mut refcount = self.refcount.lock().unwrap(); *refcount += 1; } Trusted { ptr: self.ptr, refcount: self.refcount.clone(), script_chan: self.script_chan.clone(), owner_thread: self.owner_thread, phantom: PhantomData, } } } #[unsafe_destructor] impl<T: Reflectable> Drop for Trusted<T> { fn drop(&mut self) { let mut refcount = self.refcount.lock().unwrap(); assert!(*refcount > 0); *refcount -= 1; if *refcount == 0 { // It's possible this send will fail if the script task // has already exited. There's not much we can do at this // point though. let msg = ScriptMsg::RefcountCleanup(TrustedReference(self.ptr)); let _ = self.script_chan.send(msg); } } } /// The set of live, pinned DOM objects that are currently prevented /// from being garbage collected due to outstanding references. pub struct LiveDOMReferences { // keyed on pointer to Rust DOM object table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>> } impl LiveDOMReferences { /// Set up the task-local data required for storing the outstanding DOM references. pub fn initialize() { LIVE_REFERENCES.with(|ref r| { *r.borrow_mut() = Some(LiveDOMReferences { table: RefCell::new(HashMap::new()), }) }); } fn addref<T: Reflectable>(&self, cx: *mut JSContext, ptr: *const T) -> Arc<Mutex<usize>> { let mut table = self.table.borrow_mut(); match table.entry(ptr as *const libc::c_void) { Occupied(mut entry) => { let refcount = entry.get_mut(); *refcount.lock().unwrap() += 1; refcount.clone() } Vacant(entry) => { unsafe { let rootable = (*ptr).reflector().rootable(); JS_AddObjectRoot(cx, rootable); } let refcount = Arc::new(Mutex::new(1)); entry.insert(refcount.clone()); refcount } } } /// Unpin the given DOM object if its refcount is 0. pub fn cleanup(cx: *mut JSContext, raw_reflectable: TrustedReference) { let TrustedReference(raw_reflectable) = raw_reflectable; LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let reflectable = raw_reflectable as *const Reflector; let mut table = live_references.table.borrow_mut(); match table.entry(raw_reflectable) { Occupied(entry) => { if *entry.get().lock().unwrap()!= 0 { // there could have been a new reference taken since // this message was dispatched. return; } unsafe { JS_RemoveObjectRoot(cx, (*reflectable).rootable()); } let _ = entry.remove(); } Vacant(_) => { // there could be a cleanup message dispatched, then a new // pinned reference obtained and released before the message // is processed, at which point there would be no matching // hashtable entry. info!("attempt to cleanup an unrecognized reflector"); } } }) } }
{ assert!(LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); unsafe { Temporary::from_unrooted(Unrooted::from_raw(self.ptr as *const T)) } }
identifier_body
refcounted.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 generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task for asynchronous events). Akin to Gecko's //! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures //! that the actual SpiderMonkey GC integration occurs on the script task via //! message passing. Ownership of a `Trusted<T>` object means the DOM object of //! type T to which it points remains alive. Any other behaviour is undefined. //! To guarantee the lifetime of a DOM object when performing asynchronous operations, //! obtain a `Trusted<T>` from that object and pass it along with each operation. //! A usable pointer to the original DOM object can be obtained on the script task //! from a `Trusted<T>` via the `to_temporary` method. //! //! The implementation of Trusted<T> is as follows: //! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object. //! The values in this hashtable are atomic reference counts. When a Trusted<T> object is //! created or cloned, this count is increased. When a Trusted<T> is dropped, the count //! decreases. If the count hits zero, a message is dispatched to the script task to remove //! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object //! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry //! is removed. use dom::bindings::js::{Temporary, JSRef, Unrooted}; use dom::bindings::utils::{Reflector, Reflectable}; use script_task::{ScriptMsg, ScriptChan}; use js::jsapi::{JS_AddObjectRoot, JS_RemoveObjectRoot, JSContext}; use libc; use std::cell::RefCell; use std::collections::hash_map::HashMap; use std::collections::hash_map::Entry::{Vacant, Occupied}; use std::marker::PhantomData; use std::rc::Rc; use std::sync::{Arc, Mutex}; thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None))); /// A pointer to a Rust DOM object that needs to be destroyed. pub struct TrustedReference(*const libc::c_void); unsafe impl Send for TrustedReference {} /// A safe wrapper around a raw pointer to a DOM object that can be /// shared among tasks for use in asynchronous operations. The underlying /// DOM object is guaranteed to live at least as long as the last outstanding /// `Trusted<T>` instance. pub struct Trusted<T: Reflectable> { /// A pointer to the Rust DOM object of type T, but void to allow /// sending `Trusted<T>` between tasks, regardless of T's sendability. ptr: *const libc::c_void, refcount: Arc<Mutex<usize>>, script_chan: Box<ScriptChan + Send>, owner_thread: *const libc::c_void, phantom: PhantomData<T>, } unsafe impl<T: Reflectable> Send for Trusted<T> {} impl<T: Reflectable> Trusted<T> { /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's /// lifetime. pub fn new(cx: *mut JSContext, ptr: JSRef<T>, script_chan: Box<ScriptChan + Send>) -> Trusted<T> { LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let refcount = live_references.addref(cx, &*ptr as *const T); Trusted { ptr: &*ptr as *const T as *const libc::c_void, refcount: refcount, script_chan: script_chan.clone(), owner_thread: (&*live_references) as *const _ as *const libc::c_void, phantom: PhantomData, } }) } /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on /// a different thread than the original value from which this `Trusted<T>` was /// obtained. pub fn to_temporary(&self) -> Temporary<T> { assert!(LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); unsafe { Temporary::from_unrooted(Unrooted::from_raw(self.ptr as *const T)) } } } impl<T: Reflectable> Clone for Trusted<T> { fn clone(&self) -> Trusted<T> { { let mut refcount = self.refcount.lock().unwrap(); *refcount += 1; } Trusted { ptr: self.ptr, refcount: self.refcount.clone(), script_chan: self.script_chan.clone(), owner_thread: self.owner_thread, phantom: PhantomData, } } } #[unsafe_destructor] impl<T: Reflectable> Drop for Trusted<T> { fn drop(&mut self) { let mut refcount = self.refcount.lock().unwrap(); assert!(*refcount > 0); *refcount -= 1; if *refcount == 0 { // It's possible this send will fail if the script task // has already exited. There's not much we can do at this // point though. let msg = ScriptMsg::RefcountCleanup(TrustedReference(self.ptr)); let _ = self.script_chan.send(msg); } } } /// The set of live, pinned DOM objects that are currently prevented /// from being garbage collected due to outstanding references. pub struct LiveDOMReferences { // keyed on pointer to Rust DOM object table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>> } impl LiveDOMReferences { /// Set up the task-local data required for storing the outstanding DOM references. pub fn initialize() { LIVE_REFERENCES.with(|ref r| { *r.borrow_mut() = Some(LiveDOMReferences { table: RefCell::new(HashMap::new()), }) }); } fn addref<T: Reflectable>(&self, cx: *mut JSContext, ptr: *const T) -> Arc<Mutex<usize>> { let mut table = self.table.borrow_mut(); match table.entry(ptr as *const libc::c_void) { Occupied(mut entry) => { let refcount = entry.get_mut(); *refcount.lock().unwrap() += 1; refcount.clone() } Vacant(entry) =>
} } /// Unpin the given DOM object if its refcount is 0. pub fn cleanup(cx: *mut JSContext, raw_reflectable: TrustedReference) { let TrustedReference(raw_reflectable) = raw_reflectable; LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let reflectable = raw_reflectable as *const Reflector; let mut table = live_references.table.borrow_mut(); match table.entry(raw_reflectable) { Occupied(entry) => { if *entry.get().lock().unwrap()!= 0 { // there could have been a new reference taken since // this message was dispatched. return; } unsafe { JS_RemoveObjectRoot(cx, (*reflectable).rootable()); } let _ = entry.remove(); } Vacant(_) => { // there could be a cleanup message dispatched, then a new // pinned reference obtained and released before the message // is processed, at which point there would be no matching // hashtable entry. info!("attempt to cleanup an unrecognized reflector"); } } }) } }
{ unsafe { let rootable = (*ptr).reflector().rootable(); JS_AddObjectRoot(cx, rootable); } let refcount = Arc::new(Mutex::new(1)); entry.insert(refcount.clone()); refcount }
conditional_block
mod.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Builds MIR from expressions. As a caller into this module, you //! have many options, but the first thing you have to decide is //! whether you are evaluating this expression for its *value*, its //! *location*, or as a *constant*. //! //! Typically, you want the value: e.g., if you are doing `expr_a + //! expr_b`, you want the values of those expressions. In that case, //! you want one of the following functions. Note that if the expr has //! a type that is not `Copy`, then using any of these functions will //! "move" the value out of its current home (if any). //! //! - `into` -- writes the value into a specific location, which //! should be uninitialized //! - `as_operand` -- evaluates the value and yields an `Operand`, //! suitable for use as an argument to an `Rvalue` //! - `as_temp` -- evaluates into a temporary; this is similar to `as_operand` //! except it always returns a fresh place, even for constants //! - `as_rvalue` -- yields an `Rvalue`, suitable for use in an assignment; //! as of this writing, never needed outside of the `expr` module itself //! //! Sometimes though want the expression's *location*. An example //! would be during a match statement, or the operand of the `&` //! operator. In that case, you want `as_place`. This will create a //! temporary if necessary. //! //! Finally, if it's a constant you seek, then call //! `as_constant`. This creates a `Constant<H>`, but naturally it can //! only be used on constant expressions and hence is needed only in //! very limited contexts. //! //! ### Implementation notes //! //! For any given kind of expression, there is generally one way that //! can be lowered most naturally. This is specified by the //! `Category::of` function in the `category` module. For example, a //! struct expression (or other expression that creates a new value) //! is typically easiest to write in terms of `as_rvalue` or `into`, //! whereas a reference to a field is easiest to write in terms of //! `as_place`. (The exception to this is scope and paren //! expressions, which have no category.) //! //! Therefore, the various functions above make use of one another in //! a descending fashion. For any given expression, you should pick //! the most suitable spot to implement it, and then just let the
//! other fns cycle around. The handoff works like this: //! //! - `into(place)` -> fallback is to create a rvalue with `as_rvalue` and assign it to `place` //! - `as_rvalue` -> fallback is to create an Operand with `as_operand` and use `Rvalue::use` //! - `as_operand` -> either invokes `as_constant` or `as_temp` //! - `as_constant` -> (no fallback) //! - `as_temp` -> creates a temporary and either calls `as_place` or `into` //! - `as_place` -> for rvalues, falls back to `as_temp` and returns that //! //! As you can see, there is a cycle where `into` can (in theory) fallback to `as_temp` //! which can fallback to `into`. So if one of the `ExprKind` variants is not, in fact, //! implemented in the category where it is supposed to be, there will be a problem. //! //! Of those fallbacks, the most interesting one is `into`, because //! it discriminates based on the category of the expression. This is //! basically the point where the "by value" operations are bridged //! over to the "by reference" mode (`as_place`). mod as_constant; mod as_operand; mod as_place; mod as_rvalue; mod as_temp; mod category; mod into; mod stmt;
random_line_split
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of (u8, u8, u8, u8). // This is used to take data from PixelBuffer and move it to another thread // with minimum conversions done on main thread. pub struct RGBAImageData { pub data: Vec<(u8, u8, u8, u8)>, pub width: u32, pub height: u32, } impl glium::texture::Texture2dDataSink<(u8, u8, u8, u8)> for RGBAImageData { fn from_raw(data: Cow<'_, [(u8, u8, u8, u8)]>, width: u32, height: u32) -> Self { RGBAImageData { data: data.into_owned(), width, height, } } } struct AsyncScreenshotTask { pub target_frame: u64, pub pixel_buffer: glium::texture::pixel_buffer::PixelBuffer<(u8, u8, u8, u8)>, } impl AsyncScreenshotTask { fn new(facade: &dyn glium::backend::Facade, target_frame: u64) -> Self { // Get information about current framebuffer let dimensions = facade.get_context().get_framebuffer_dimensions(); let rect = glium::Rect { left: 0, bottom: 0, width: dimensions.0, height: dimensions.1, }; let blit_target = glium::BlitTarget { left: 0, bottom: 0, width: dimensions.0 as i32, height: dimensions.1 as i32, }; // Create temporary texture and blit the front buffer to it let texture = glium::texture::Texture2d::empty(facade, dimensions.0, dimensions.1) .unwrap(); let framebuffer = glium::framebuffer::SimpleFrameBuffer::new(facade, &texture).unwrap(); framebuffer.blit_from_frame(&rect, &blit_target, glium::uniforms::MagnifySamplerFilter::Nearest); // Read the texture into new pixel buffer let pixel_buffer = texture.read_to_pixel_buffer(); AsyncScreenshotTask { target_frame, pixel_buffer, } } fn read_image_data(self) -> RGBAImageData { self.pixel_buffer.read_as_texture_2d().unwrap() } } pub struct ScreenshotIterator<'a>(&'a mut AsyncScreenshotTaker); impl<'a> Iterator for ScreenshotIterator<'a> { type Item = RGBAImageData; fn next(&mut self) -> Option<RGBAImageData> { if self.0.screenshot_tasks.front().map(|task| task.target_frame) == Some(self.0.frame)
else { None } } } pub struct AsyncScreenshotTaker { screenshot_delay: u64, frame: u64, screenshot_tasks: VecDeque<AsyncScreenshotTask>, } impl AsyncScreenshotTaker { pub fn new(screenshot_delay: u64) -> Self { AsyncScreenshotTaker { screenshot_delay, frame: 0, screenshot_tasks: VecDeque::new(), } } pub fn next_frame(&mut self) { self.frame += 1; } pub fn pickup_screenshots(&mut self) -> ScreenshotIterator<'_> { ScreenshotIterator(self) } pub fn take_screenshot(&mut self, facade: &dyn glium::backend::Facade) { self.screenshot_tasks .push_back(AsyncScreenshotTask::new(facade, self.frame + self.screenshot_delay)); } } } fn main() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new().with_title("Press S to take screenshot"); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], color: [f32; 3], } implement_vertex!(Vertex, position, color); glium::VertexBuffer::new(&display, &[Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0], }, Vertex { position: [0.0, 0.5], color: [0.0, 0.0, 1.0], }, Vertex { position: [0.5, -0.5], color: [1.0, 0.0, 0.0], }]) .unwrap() }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList, &[0u16, 1, 2]).unwrap(); // compiling shaders and linking them together let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 matrix; in vec2 position; in vec3 color; out vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, ) .unwrap(); // drawing once // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ] }; // The parameter sets the amount of frames between requesting the image // transfer and picking it up. If the value is too small, the main thread // will block waiting for the image to finish transferring. Tune it based on // your requirements. let mut screenshot_taker = screenshot::AsyncScreenshotTaker::new(5); event_loop.run(move |event, _, control_flow| { // React to events use glium::glutin::event::{Event, WindowEvent, ElementState, VirtualKeyCode}; let mut take_screenshot = false; let next_frame_time = std::time::Instant::now() + std::time::Duration::from_nanos(16_666_667); *control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time); match event { Event::WindowEvent { event,.. } => match event { WindowEvent::CloseRequested => { *control_flow = glutin::event_loop::ControlFlow::Exit; return; }, WindowEvent::KeyboardInput { input,.. } => { if let ElementState::Pressed = input.state { if let Some(VirtualKeyCode::S) = input.virtual_keycode { take_screenshot = true; } } }, _ => return, }, Event::NewEvents(cause) => match cause { glutin::event::StartCause::ResumeTimeReached {.. } => (), glutin::event::StartCause::Init => (), _ => return, }, _ => return, } // Tell Screenshot Taker to count next frame screenshot_taker.next_frame(); // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()) .unwrap(); target.finish().unwrap(); if take_screenshot { // Take screenshot and queue it's delivery screenshot_taker.take_screenshot(&display); } // Pick up screenshots that are ready this frame for image_data in screenshot_taker.pickup_screenshots() { // Process and write the image in separate thread to not block the rendering thread. thread::spawn(move || { // Convert (u8, u8, u8, u8) given by glium's PixelBuffer to flat u8 required by // image's ImageBuffer. let pixels = { let mut v = Vec::with_capacity(image_data.data.len() * 4); for (a, b, c, d) in image_data.data { v.push(a); v.push(b); v.push(c); v.push(d); } v }; // Create ImageBuffer let image_buffer = image::ImageBuffer::from_raw(image_data.width, image_data.height, pixels) .unwrap(); // Save the screenshot to file let image = image::DynamicImage::ImageRgba8(image_buffer).flipv(); image.save("glium-example-screenshot.png").unwrap(); }); } }); }
{ let task = self.0.screenshot_tasks.pop_front().unwrap(); Some(task.read_image_data()) }
conditional_block
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of (u8, u8, u8, u8). // This is used to take data from PixelBuffer and move it to another thread // with minimum conversions done on main thread. pub struct RGBAImageData { pub data: Vec<(u8, u8, u8, u8)>, pub width: u32, pub height: u32, } impl glium::texture::Texture2dDataSink<(u8, u8, u8, u8)> for RGBAImageData { fn from_raw(data: Cow<'_, [(u8, u8, u8, u8)]>, width: u32, height: u32) -> Self { RGBAImageData { data: data.into_owned(), width, height, } } } struct AsyncScreenshotTask { pub target_frame: u64, pub pixel_buffer: glium::texture::pixel_buffer::PixelBuffer<(u8, u8, u8, u8)>, } impl AsyncScreenshotTask { fn new(facade: &dyn glium::backend::Facade, target_frame: u64) -> Self { // Get information about current framebuffer let dimensions = facade.get_context().get_framebuffer_dimensions(); let rect = glium::Rect { left: 0, bottom: 0, width: dimensions.0, height: dimensions.1, }; let blit_target = glium::BlitTarget { left: 0, bottom: 0, width: dimensions.0 as i32, height: dimensions.1 as i32, }; // Create temporary texture and blit the front buffer to it let texture = glium::texture::Texture2d::empty(facade, dimensions.0, dimensions.1) .unwrap(); let framebuffer = glium::framebuffer::SimpleFrameBuffer::new(facade, &texture).unwrap(); framebuffer.blit_from_frame(&rect, &blit_target, glium::uniforms::MagnifySamplerFilter::Nearest); // Read the texture into new pixel buffer let pixel_buffer = texture.read_to_pixel_buffer(); AsyncScreenshotTask { target_frame, pixel_buffer, } } fn read_image_data(self) -> RGBAImageData { self.pixel_buffer.read_as_texture_2d().unwrap() } } pub struct ScreenshotIterator<'a>(&'a mut AsyncScreenshotTaker); impl<'a> Iterator for ScreenshotIterator<'a> { type Item = RGBAImageData; fn next(&mut self) -> Option<RGBAImageData> { if self.0.screenshot_tasks.front().map(|task| task.target_frame) == Some(self.0.frame) { let task = self.0.screenshot_tasks.pop_front().unwrap(); Some(task.read_image_data()) } else { None } } } pub struct AsyncScreenshotTaker { screenshot_delay: u64, frame: u64, screenshot_tasks: VecDeque<AsyncScreenshotTask>, } impl AsyncScreenshotTaker { pub fn new(screenshot_delay: u64) -> Self { AsyncScreenshotTaker { screenshot_delay, frame: 0, screenshot_tasks: VecDeque::new(), } } pub fn next_frame(&mut self) { self.frame += 1; } pub fn pickup_screenshots(&mut self) -> ScreenshotIterator<'_> { ScreenshotIterator(self) } pub fn take_screenshot(&mut self, facade: &dyn glium::backend::Facade) { self.screenshot_tasks .push_back(AsyncScreenshotTask::new(facade, self.frame + self.screenshot_delay)); } } } fn main() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new().with_title("Press S to take screenshot"); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], color: [f32; 3], } implement_vertex!(Vertex, position, color); glium::VertexBuffer::new(&display, &[Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0], }, Vertex { position: [0.0, 0.5], color: [0.0, 0.0, 1.0], }, Vertex { position: [0.5, -0.5], color: [1.0, 0.0, 0.0], }]) .unwrap() }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList, &[0u16, 1, 2]).unwrap(); // compiling shaders and linking them together let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 matrix; in vec2 position; in vec3 color; out vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, ) .unwrap(); // drawing once // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ] }; // The parameter sets the amount of frames between requesting the image // transfer and picking it up. If the value is too small, the main thread // will block waiting for the image to finish transferring. Tune it based on // your requirements. let mut screenshot_taker = screenshot::AsyncScreenshotTaker::new(5); event_loop.run(move |event, _, control_flow| { // React to events use glium::glutin::event::{Event, WindowEvent, ElementState, VirtualKeyCode}; let mut take_screenshot = false; let next_frame_time = std::time::Instant::now() + std::time::Duration::from_nanos(16_666_667); *control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time); match event { Event::WindowEvent { event,.. } => match event { WindowEvent::CloseRequested => { *control_flow = glutin::event_loop::ControlFlow::Exit; return; }, WindowEvent::KeyboardInput { input,.. } => { if let ElementState::Pressed = input.state { if let Some(VirtualKeyCode::S) = input.virtual_keycode { take_screenshot = true; } } }, _ => return, }, Event::NewEvents(cause) => match cause { glutin::event::StartCause::ResumeTimeReached {.. } => (), glutin::event::StartCause::Init => (), _ => return, }, _ => return, } // Tell Screenshot Taker to count next frame screenshot_taker.next_frame(); // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()) .unwrap(); target.finish().unwrap(); if take_screenshot { // Take screenshot and queue it's delivery screenshot_taker.take_screenshot(&display); } // Pick up screenshots that are ready this frame for image_data in screenshot_taker.pickup_screenshots() { // Process and write the image in separate thread to not block the rendering thread. thread::spawn(move || {
let pixels = { let mut v = Vec::with_capacity(image_data.data.len() * 4); for (a, b, c, d) in image_data.data { v.push(a); v.push(b); v.push(c); v.push(d); } v }; // Create ImageBuffer let image_buffer = image::ImageBuffer::from_raw(image_data.width, image_data.height, pixels) .unwrap(); // Save the screenshot to file let image = image::DynamicImage::ImageRgba8(image_buffer).flipv(); image.save("glium-example-screenshot.png").unwrap(); }); } }); }
// Convert (u8, u8, u8, u8) given by glium's PixelBuffer to flat u8 required by // image's ImageBuffer.
random_line_split
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of (u8, u8, u8, u8). // This is used to take data from PixelBuffer and move it to another thread // with minimum conversions done on main thread. pub struct RGBAImageData { pub data: Vec<(u8, u8, u8, u8)>, pub width: u32, pub height: u32, } impl glium::texture::Texture2dDataSink<(u8, u8, u8, u8)> for RGBAImageData { fn from_raw(data: Cow<'_, [(u8, u8, u8, u8)]>, width: u32, height: u32) -> Self { RGBAImageData { data: data.into_owned(), width, height, } } } struct AsyncScreenshotTask { pub target_frame: u64, pub pixel_buffer: glium::texture::pixel_buffer::PixelBuffer<(u8, u8, u8, u8)>, } impl AsyncScreenshotTask { fn new(facade: &dyn glium::backend::Facade, target_frame: u64) -> Self
framebuffer.blit_from_frame(&rect, &blit_target, glium::uniforms::MagnifySamplerFilter::Nearest); // Read the texture into new pixel buffer let pixel_buffer = texture.read_to_pixel_buffer(); AsyncScreenshotTask { target_frame, pixel_buffer, } } fn read_image_data(self) -> RGBAImageData { self.pixel_buffer.read_as_texture_2d().unwrap() } } pub struct ScreenshotIterator<'a>(&'a mut AsyncScreenshotTaker); impl<'a> Iterator for ScreenshotIterator<'a> { type Item = RGBAImageData; fn next(&mut self) -> Option<RGBAImageData> { if self.0.screenshot_tasks.front().map(|task| task.target_frame) == Some(self.0.frame) { let task = self.0.screenshot_tasks.pop_front().unwrap(); Some(task.read_image_data()) } else { None } } } pub struct AsyncScreenshotTaker { screenshot_delay: u64, frame: u64, screenshot_tasks: VecDeque<AsyncScreenshotTask>, } impl AsyncScreenshotTaker { pub fn new(screenshot_delay: u64) -> Self { AsyncScreenshotTaker { screenshot_delay, frame: 0, screenshot_tasks: VecDeque::new(), } } pub fn next_frame(&mut self) { self.frame += 1; } pub fn pickup_screenshots(&mut self) -> ScreenshotIterator<'_> { ScreenshotIterator(self) } pub fn take_screenshot(&mut self, facade: &dyn glium::backend::Facade) { self.screenshot_tasks .push_back(AsyncScreenshotTask::new(facade, self.frame + self.screenshot_delay)); } } } fn main() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new().with_title("Press S to take screenshot"); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], color: [f32; 3], } implement_vertex!(Vertex, position, color); glium::VertexBuffer::new(&display, &[Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0], }, Vertex { position: [0.0, 0.5], color: [0.0, 0.0, 1.0], }, Vertex { position: [0.5, -0.5], color: [1.0, 0.0, 0.0], }]) .unwrap() }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList, &[0u16, 1, 2]).unwrap(); // compiling shaders and linking them together let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 matrix; in vec2 position; in vec3 color; out vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, ) .unwrap(); // drawing once // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ] }; // The parameter sets the amount of frames between requesting the image // transfer and picking it up. If the value is too small, the main thread // will block waiting for the image to finish transferring. Tune it based on // your requirements. let mut screenshot_taker = screenshot::AsyncScreenshotTaker::new(5); event_loop.run(move |event, _, control_flow| { // React to events use glium::glutin::event::{Event, WindowEvent, ElementState, VirtualKeyCode}; let mut take_screenshot = false; let next_frame_time = std::time::Instant::now() + std::time::Duration::from_nanos(16_666_667); *control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time); match event { Event::WindowEvent { event,.. } => match event { WindowEvent::CloseRequested => { *control_flow = glutin::event_loop::ControlFlow::Exit; return; }, WindowEvent::KeyboardInput { input,.. } => { if let ElementState::Pressed = input.state { if let Some(VirtualKeyCode::S) = input.virtual_keycode { take_screenshot = true; } } }, _ => return, }, Event::NewEvents(cause) => match cause { glutin::event::StartCause::ResumeTimeReached {.. } => (), glutin::event::StartCause::Init => (), _ => return, }, _ => return, } // Tell Screenshot Taker to count next frame screenshot_taker.next_frame(); // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()) .unwrap(); target.finish().unwrap(); if take_screenshot { // Take screenshot and queue it's delivery screenshot_taker.take_screenshot(&display); } // Pick up screenshots that are ready this frame for image_data in screenshot_taker.pickup_screenshots() { // Process and write the image in separate thread to not block the rendering thread. thread::spawn(move || { // Convert (u8, u8, u8, u8) given by glium's PixelBuffer to flat u8 required by // image's ImageBuffer. let pixels = { let mut v = Vec::with_capacity(image_data.data.len() * 4); for (a, b, c, d) in image_data.data { v.push(a); v.push(b); v.push(c); v.push(d); } v }; // Create ImageBuffer let image_buffer = image::ImageBuffer::from_raw(image_data.width, image_data.height, pixels) .unwrap(); // Save the screenshot to file let image = image::DynamicImage::ImageRgba8(image_buffer).flipv(); image.save("glium-example-screenshot.png").unwrap(); }); } }); }
{ // Get information about current framebuffer let dimensions = facade.get_context().get_framebuffer_dimensions(); let rect = glium::Rect { left: 0, bottom: 0, width: dimensions.0, height: dimensions.1, }; let blit_target = glium::BlitTarget { left: 0, bottom: 0, width: dimensions.0 as i32, height: dimensions.1 as i32, }; // Create temporary texture and blit the front buffer to it let texture = glium::texture::Texture2d::empty(facade, dimensions.0, dimensions.1) .unwrap(); let framebuffer = glium::framebuffer::SimpleFrameBuffer::new(facade, &texture).unwrap();
identifier_body
screenshot-asynchronous.rs
#[macro_use] extern crate glium; use std::thread; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod screenshot { use glium::Surface; use std::collections::VecDeque; use std::vec::Vec; use std::borrow::Cow; // Container that holds image data as vector of (u8, u8, u8, u8). // This is used to take data from PixelBuffer and move it to another thread // with minimum conversions done on main thread. pub struct
{ pub data: Vec<(u8, u8, u8, u8)>, pub width: u32, pub height: u32, } impl glium::texture::Texture2dDataSink<(u8, u8, u8, u8)> for RGBAImageData { fn from_raw(data: Cow<'_, [(u8, u8, u8, u8)]>, width: u32, height: u32) -> Self { RGBAImageData { data: data.into_owned(), width, height, } } } struct AsyncScreenshotTask { pub target_frame: u64, pub pixel_buffer: glium::texture::pixel_buffer::PixelBuffer<(u8, u8, u8, u8)>, } impl AsyncScreenshotTask { fn new(facade: &dyn glium::backend::Facade, target_frame: u64) -> Self { // Get information about current framebuffer let dimensions = facade.get_context().get_framebuffer_dimensions(); let rect = glium::Rect { left: 0, bottom: 0, width: dimensions.0, height: dimensions.1, }; let blit_target = glium::BlitTarget { left: 0, bottom: 0, width: dimensions.0 as i32, height: dimensions.1 as i32, }; // Create temporary texture and blit the front buffer to it let texture = glium::texture::Texture2d::empty(facade, dimensions.0, dimensions.1) .unwrap(); let framebuffer = glium::framebuffer::SimpleFrameBuffer::new(facade, &texture).unwrap(); framebuffer.blit_from_frame(&rect, &blit_target, glium::uniforms::MagnifySamplerFilter::Nearest); // Read the texture into new pixel buffer let pixel_buffer = texture.read_to_pixel_buffer(); AsyncScreenshotTask { target_frame, pixel_buffer, } } fn read_image_data(self) -> RGBAImageData { self.pixel_buffer.read_as_texture_2d().unwrap() } } pub struct ScreenshotIterator<'a>(&'a mut AsyncScreenshotTaker); impl<'a> Iterator for ScreenshotIterator<'a> { type Item = RGBAImageData; fn next(&mut self) -> Option<RGBAImageData> { if self.0.screenshot_tasks.front().map(|task| task.target_frame) == Some(self.0.frame) { let task = self.0.screenshot_tasks.pop_front().unwrap(); Some(task.read_image_data()) } else { None } } } pub struct AsyncScreenshotTaker { screenshot_delay: u64, frame: u64, screenshot_tasks: VecDeque<AsyncScreenshotTask>, } impl AsyncScreenshotTaker { pub fn new(screenshot_delay: u64) -> Self { AsyncScreenshotTaker { screenshot_delay, frame: 0, screenshot_tasks: VecDeque::new(), } } pub fn next_frame(&mut self) { self.frame += 1; } pub fn pickup_screenshots(&mut self) -> ScreenshotIterator<'_> { ScreenshotIterator(self) } pub fn take_screenshot(&mut self, facade: &dyn glium::backend::Facade) { self.screenshot_tasks .push_back(AsyncScreenshotTask::new(facade, self.frame + self.screenshot_delay)); } } } fn main() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new().with_title("Press S to take screenshot"); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], color: [f32; 3], } implement_vertex!(Vertex, position, color); glium::VertexBuffer::new(&display, &[Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0], }, Vertex { position: [0.0, 0.5], color: [0.0, 0.0, 1.0], }, Vertex { position: [0.5, -0.5], color: [1.0, 0.0, 0.0], }]) .unwrap() }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList, &[0u16, 1, 2]).unwrap(); // compiling shaders and linking them together let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 matrix; in vec2 position; in vec3 color; out vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, ) .unwrap(); // drawing once // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ] }; // The parameter sets the amount of frames between requesting the image // transfer and picking it up. If the value is too small, the main thread // will block waiting for the image to finish transferring. Tune it based on // your requirements. let mut screenshot_taker = screenshot::AsyncScreenshotTaker::new(5); event_loop.run(move |event, _, control_flow| { // React to events use glium::glutin::event::{Event, WindowEvent, ElementState, VirtualKeyCode}; let mut take_screenshot = false; let next_frame_time = std::time::Instant::now() + std::time::Duration::from_nanos(16_666_667); *control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time); match event { Event::WindowEvent { event,.. } => match event { WindowEvent::CloseRequested => { *control_flow = glutin::event_loop::ControlFlow::Exit; return; }, WindowEvent::KeyboardInput { input,.. } => { if let ElementState::Pressed = input.state { if let Some(VirtualKeyCode::S) = input.virtual_keycode { take_screenshot = true; } } }, _ => return, }, Event::NewEvents(cause) => match cause { glutin::event::StartCause::ResumeTimeReached {.. } => (), glutin::event::StartCause::Init => (), _ => return, }, _ => return, } // Tell Screenshot Taker to count next frame screenshot_taker.next_frame(); // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()) .unwrap(); target.finish().unwrap(); if take_screenshot { // Take screenshot and queue it's delivery screenshot_taker.take_screenshot(&display); } // Pick up screenshots that are ready this frame for image_data in screenshot_taker.pickup_screenshots() { // Process and write the image in separate thread to not block the rendering thread. thread::spawn(move || { // Convert (u8, u8, u8, u8) given by glium's PixelBuffer to flat u8 required by // image's ImageBuffer. let pixels = { let mut v = Vec::with_capacity(image_data.data.len() * 4); for (a, b, c, d) in image_data.data { v.push(a); v.push(b); v.push(c); v.push(d); } v }; // Create ImageBuffer let image_buffer = image::ImageBuffer::from_raw(image_data.width, image_data.height, pixels) .unwrap(); // Save the screenshot to file let image = image::DynamicImage::ImageRgba8(image_buffer).flipv(); image.save("glium-example-screenshot.png").unwrap(); }); } }); }
RGBAImageData
identifier_name
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use cell::UnsafeCell; use libc::{self, DWORD}; use os; use sys::mutex::{self, Mutex}; use sys::sync as ffi; use time::Duration; pub struct Condvar { inner: UnsafeCell<ffi::CONDITION_VARIABLE> } unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} pub const CONDVAR_INIT: Condvar = Condvar { inner: UnsafeCell { value: ffi::CONDITION_VARIABLE_INIT } }; impl Condvar { #[inline] pub unsafe fn new() -> Condvar { CONDVAR_INIT } #[inline] pub unsafe fn wait(&self, mutex: &Mutex) { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), libc::INFINITE, 0); debug_assert!(r!= 0); } pub unsafe fn
(&self, mutex: &Mutex, dur: Duration) -> bool { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), dur.num_milliseconds() as DWORD, 0); if r == 0 { const ERROR_TIMEOUT: DWORD = 0x5B4; debug_assert_eq!(os::errno() as uint, ERROR_TIMEOUT as uint); false } else { true } } #[inline] pub unsafe fn notify_one(&self) { ffi::WakeConditionVariable(self.inner.get()) } #[inline] pub unsafe fn notify_all(&self) { ffi::WakeAllConditionVariable(self.inner.get()) } pub unsafe fn destroy(&self) { //... } }
wait_timeout
identifier_name
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use cell::UnsafeCell; use libc::{self, DWORD}; use os; use sys::mutex::{self, Mutex}; use sys::sync as ffi; use time::Duration; pub struct Condvar { inner: UnsafeCell<ffi::CONDITION_VARIABLE> } unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} pub const CONDVAR_INIT: Condvar = Condvar { inner: UnsafeCell { value: ffi::CONDITION_VARIABLE_INIT } }; impl Condvar { #[inline] pub unsafe fn new() -> Condvar { CONDVAR_INIT } #[inline] pub unsafe fn wait(&self, mutex: &Mutex) { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), libc::INFINITE, 0); debug_assert!(r!= 0); } pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool
#[inline] pub unsafe fn notify_one(&self) { ffi::WakeConditionVariable(self.inner.get()) } #[inline] pub unsafe fn notify_all(&self) { ffi::WakeAllConditionVariable(self.inner.get()) } pub unsafe fn destroy(&self) { //... } }
{ let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), dur.num_milliseconds() as DWORD, 0); if r == 0 { const ERROR_TIMEOUT: DWORD = 0x5B4; debug_assert_eq!(os::errno() as uint, ERROR_TIMEOUT as uint); false } else { true } }
identifier_body
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use cell::UnsafeCell; use libc::{self, DWORD}; use os; use sys::mutex::{self, Mutex}; use sys::sync as ffi; use time::Duration; pub struct Condvar { inner: UnsafeCell<ffi::CONDITION_VARIABLE> }
inner: UnsafeCell { value: ffi::CONDITION_VARIABLE_INIT } }; impl Condvar { #[inline] pub unsafe fn new() -> Condvar { CONDVAR_INIT } #[inline] pub unsafe fn wait(&self, mutex: &Mutex) { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), libc::INFINITE, 0); debug_assert!(r!= 0); } pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), dur.num_milliseconds() as DWORD, 0); if r == 0 { const ERROR_TIMEOUT: DWORD = 0x5B4; debug_assert_eq!(os::errno() as uint, ERROR_TIMEOUT as uint); false } else { true } } #[inline] pub unsafe fn notify_one(&self) { ffi::WakeConditionVariable(self.inner.get()) } #[inline] pub unsafe fn notify_all(&self) { ffi::WakeAllConditionVariable(self.inner.get()) } pub unsafe fn destroy(&self) { //... } }
unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} pub const CONDVAR_INIT: Condvar = Condvar {
random_line_split
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use cell::UnsafeCell; use libc::{self, DWORD}; use os; use sys::mutex::{self, Mutex}; use sys::sync as ffi; use time::Duration; pub struct Condvar { inner: UnsafeCell<ffi::CONDITION_VARIABLE> } unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} pub const CONDVAR_INIT: Condvar = Condvar { inner: UnsafeCell { value: ffi::CONDITION_VARIABLE_INIT } }; impl Condvar { #[inline] pub unsafe fn new() -> Condvar { CONDVAR_INIT } #[inline] pub unsafe fn wait(&self, mutex: &Mutex) { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), libc::INFINITE, 0); debug_assert!(r!= 0); } pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool { let r = ffi::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), dur.num_milliseconds() as DWORD, 0); if r == 0 { const ERROR_TIMEOUT: DWORD = 0x5B4; debug_assert_eq!(os::errno() as uint, ERROR_TIMEOUT as uint); false } else
} #[inline] pub unsafe fn notify_one(&self) { ffi::WakeConditionVariable(self.inner.get()) } #[inline] pub unsafe fn notify_all(&self) { ffi::WakeAllConditionVariable(self.inner.get()) } pub unsafe fn destroy(&self) { //... } }
{ true }
conditional_block
step_by.rs
// 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. /// This module just implements a simple verison of step_by() since /// the function from the standard library is currently unstable. /// This should be removed once that function becomes stable. use std::ops::{Add, Range}; #[derive(Clone)] pub struct StepUp<T> { next: T, end: T, ammount: T } impl <T> Iterator for StepUp<T> where T: Add<T, Output = T> + PartialOrd + Copy { type Item = T; #[inline] fn next(&mut self) -> Option<T> { if self.next < self.end { let n = self.next; self.next = self.next + self.ammount; Some(n) } else { None } } } pub trait RangeExt<T> { fn step_up(self, ammount: T) -> StepUp<T>; } impl <T> RangeExt<T> for Range<T> where T: Add<T, Output = T> + PartialOrd + Copy { fn step_up(self, ammount: T) -> StepUp<T>
}
{ StepUp { next: self.start, end: self.end, ammount: ammount } }
identifier_body
step_by.rs
// 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. /// This module just implements a simple verison of step_by() since /// the function from the standard library is currently unstable. /// This should be removed once that function becomes stable. use std::ops::{Add, Range}; #[derive(Clone)] pub struct StepUp<T> { next: T, end: T, ammount: T } impl <T> Iterator for StepUp<T> where T: Add<T, Output = T> + PartialOrd + Copy { type Item = T; #[inline] fn next(&mut self) -> Option<T> { if self.next < self.end
else { None } } } pub trait RangeExt<T> { fn step_up(self, ammount: T) -> StepUp<T>; } impl <T> RangeExt<T> for Range<T> where T: Add<T, Output = T> + PartialOrd + Copy { fn step_up(self, ammount: T) -> StepUp<T> { StepUp { next: self.start, end: self.end, ammount: ammount } } }
{ let n = self.next; self.next = self.next + self.ammount; Some(n) }
conditional_block
step_by.rs
// 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. /// This module just implements a simple verison of step_by() since /// the function from the standard library is currently unstable. /// This should be removed once that function becomes stable. use std::ops::{Add, Range}; #[derive(Clone)] pub struct StepUp<T> { next: T,
T: Add<T, Output = T> + PartialOrd + Copy { type Item = T; #[inline] fn next(&mut self) -> Option<T> { if self.next < self.end { let n = self.next; self.next = self.next + self.ammount; Some(n) } else { None } } } pub trait RangeExt<T> { fn step_up(self, ammount: T) -> StepUp<T>; } impl <T> RangeExt<T> for Range<T> where T: Add<T, Output = T> + PartialOrd + Copy { fn step_up(self, ammount: T) -> StepUp<T> { StepUp { next: self.start, end: self.end, ammount: ammount } } }
end: T, ammount: T } impl <T> Iterator for StepUp<T> where
random_line_split
step_by.rs
// 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. /// This module just implements a simple verison of step_by() since /// the function from the standard library is currently unstable. /// This should be removed once that function becomes stable. use std::ops::{Add, Range}; #[derive(Clone)] pub struct
<T> { next: T, end: T, ammount: T } impl <T> Iterator for StepUp<T> where T: Add<T, Output = T> + PartialOrd + Copy { type Item = T; #[inline] fn next(&mut self) -> Option<T> { if self.next < self.end { let n = self.next; self.next = self.next + self.ammount; Some(n) } else { None } } } pub trait RangeExt<T> { fn step_up(self, ammount: T) -> StepUp<T>; } impl <T> RangeExt<T> for Range<T> where T: Add<T, Output = T> + PartialOrd + Copy { fn step_up(self, ammount: T) -> StepUp<T> { StepUp { next: self.start, end: self.end, ammount: ammount } } }
StepUp
identifier_name
kqueue.rs
use std::{cmp, fmt, ptr}; #[cfg(not(target_os = "netbsd"))] use std::os::raw::{c_int, c_short}; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::time::Duration; use libc::{self, time_t}; use {io, Ready, PollOpt, Token}; use event_imp::{self as event, Event}; use sys::unix::{cvt, UnixReady}; use sys::unix::io::set_cloexec; /// Each Selector has a globally unique(ish) ID associated with it. This ID /// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first /// registered with the `Selector`. If a type that is previously associated with /// a `Selector` attempts to register itself with a different `Selector`, the /// operation will return with an error. This matches windows behavior. static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT; #[cfg(not(target_os = "netbsd"))] type Filter = c_short; #[cfg(not(target_os = "netbsd"))] type UData = *mut ::libc::c_void; #[cfg(not(target_os = "netbsd"))] type Count = c_int; #[cfg(target_os = "netbsd")] type Filter = u32; #[cfg(target_os = "netbsd")] type UData = ::libc::intptr_t; #[cfg(target_os = "netbsd")] type Count = usize; macro_rules! kevent { ($id: expr, $filter: expr, $flags: expr, $data: expr) => { libc::kevent { ident: $id as ::libc::uintptr_t, filter: $filter as Filter, flags: $flags, fflags: 0, data: 0, udata: $data as UData, } } } pub struct Selector { id: usize, kq: RawFd, } impl Selector { pub fn new() -> io::Result<Selector> { // offset by 1 to avoid choosing 0 as the id of a selector let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; let kq = unsafe { cvt(libc::kqueue())? }; drop(set_cloexec(kq)); Ok(Selector { id: id, kq: kq, }) } pub fn id(&self) -> usize { self.id } pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> { let timeout = timeout.map(|to| { libc::timespec { tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t, tv_nsec: to.subsec_nanos() as libc::c_long, } }); let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut()); unsafe { let cnt = cvt(libc::kevent(self.kq, ptr::null(), 0, evts.sys_events.0.as_mut_ptr(), evts.sys_events.0.capacity() as Count, timeout))?; evts.sys_events.0.set_len(cnt as usize); Ok(evts.coalesce(awakener)) } } pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { trace!("registering; token={:?}; interests={:?}", token, interests); let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } | if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } | libc::EV_RECEIPT; unsafe { let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE }; let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE }; let mut changes = [ kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)), kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)), ]; cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as Count, changes.as_mut_ptr(), changes.len() as Count, ::std::ptr::null()))?; for change in changes.iter() { debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR); // Test to see if an error happened if change.data == 0 { continue } // Older versions of OSX (10.11 and 10.10 have been witnessed) // can return EPIPE when registering a pipe file descriptor // where the other end has already disappeared. For example code // that creates a pipe, closes a file descriptor, and then // registers the other end will see an EPIPE returned from // `register`. // // It also turns out that kevent will still report events on the // file descriptor, telling us that it's readable/hup at least // after we've done this registration. As a result we just // ignore `EPIPE` here instead of propagating it. // // More info can be found at carllerche/mio#582 if change.data as i32 == libc::EPIPE && change.filter == libc::EVFILT_WRITE as Filter { continue } // ignore ENOENT error for EV_DELETE let orig_flags = if change.filter == libc::EVFILT_READ as Filter { r } else { w }; if change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE!= 0 { continue } return Err(::std::io::Error::from_raw_os_error(change.data as i32)); } Ok(()) } } pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { // Just need to call register here since EV_ADD is a mod if already // registered self.register(fd, token, interests, opts) } pub fn deregister(&self, fd: RawFd) -> io::Result<()> { unsafe { // EV_RECEIPT is a nice way to apply changes and get back per-event results while not // draining the actual changes. let filter = libc::EV_DELETE | libc::EV_RECEIPT; #[cfg(not(target_os = "netbsd"))] let mut changes = [ kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()), kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()), ]; #[cfg(target_os = "netbsd")] let mut changes = [ kevent!(fd, libc::EVFILT_READ, filter, 0), kevent!(fd, libc::EVFILT_WRITE, filter, 0), ]; cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as Count, changes.as_mut_ptr(), changes.len() as Count, ::std::ptr::null())).map(|_| ())?; if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT { return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); } for change in changes.iter() { debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR); if change.data!= 0 && change.data as i32!= libc::ENOENT { return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); } } Ok(()) } } } impl fmt::Debug for Selector { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Selector") .field("id", &self.id) .field("kq", &self.kq) .finish() } } impl AsRawFd for Selector { fn as_raw_fd(&self) -> RawFd { self.kq } } impl Drop for Selector { fn drop(&mut self) { unsafe { let _ = libc::close(self.kq); } } } pub struct Events { sys_events: KeventList, events: Vec<Event>, event_map: HashMap<Token, usize>, } struct KeventList(Vec<libc::kevent>); unsafe impl Send for KeventList {} unsafe impl Sync for KeventList {} impl Events { pub fn with_capacity(cap: usize) -> Events { Events { sys_events: KeventList(Vec::with_capacity(cap)), events: Vec::with_capacity(cap), event_map: HashMap::with_capacity(cap) } } #[inline] pub fn len(&self) -> usize { self.events.len() } #[inline] pub fn capacity(&self) -> usize
#[inline] pub fn is_empty(&self) -> bool { self.events.is_empty() } pub fn get(&self, idx: usize) -> Option<Event> { self.events.get(idx).map(|e| *e) } fn coalesce(&mut self, awakener: Token) -> bool { let mut ret = false; self.events.clear(); self.event_map.clear(); for e in self.sys_events.0.iter() { let token = Token(e.udata as usize); let len = self.events.len(); if token == awakener { // TODO: Should this return an error if event is an error. It // is not critical as spurious wakeups are permitted. ret = true; continue; } let idx = *self.event_map.entry(token) .or_insert(len); if idx == len { // New entry, insert the default self.events.push(Event::new(Ready::empty(), token)); } if e.flags & libc::EV_ERROR!= 0 { event::kind_mut(&mut self.events[idx]).insert(*UnixReady::error()); } if e.filter == libc::EVFILT_READ as Filter { event::kind_mut(&mut self.events[idx]).insert(Ready::readable()); } else if e.filter == libc::EVFILT_WRITE as Filter { event::kind_mut(&mut self.events[idx]).insert(Ready::writable()); } #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos"))] { if e.filter == libc::EVFILT_AIO { event::kind_mut(&mut self.events[idx]).insert(UnixReady::aio()); } } if e.flags & libc::EV_EOF!= 0 { event::kind_mut(&mut self.events[idx]).insert(UnixReady::hup()); // When the read end of the socket is closed, EV_EOF is set on // flags, and fflags contains the error if there is one. if e.fflags!= 0 { event::kind_mut(&mut self.events[idx]).insert(UnixReady::error()); } } } ret } pub fn push_event(&mut self, event: Event) { self.events.push(event); } } impl fmt::Debug for Events { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Events") .field("len", &self.sys_events.0.len()) .finish() } } #[test] fn does_not_register_rw() { use {Poll, Ready, PollOpt, Token}; use unix::EventedFd; let kq = unsafe { libc::kqueue() }; let kqf = EventedFd(&kq); let poll = Poll::new().unwrap(); // registering kqueue fd will fail if write is requested (On anything but some versions of OS // X) poll.register(&kqf, Token(1234), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); } #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos"))] #[test] fn test_coalesce_aio() { let mut events = Events::with_capacity(1); events.sys_events.0.push(kevent!(0x1234, libc::EVFILT_AIO, 0, 42)); events.coalesce(Token(0)); assert!(events.events[0].readiness() == UnixReady::aio().into()); assert!(events.events[0].token() == Token(42)); }
{ self.events.capacity() }
identifier_body
kqueue.rs
use std::{cmp, fmt, ptr}; #[cfg(not(target_os = "netbsd"))] use std::os::raw::{c_int, c_short}; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::time::Duration; use libc::{self, time_t}; use {io, Ready, PollOpt, Token}; use event_imp::{self as event, Event}; use sys::unix::{cvt, UnixReady}; use sys::unix::io::set_cloexec; /// Each Selector has a globally unique(ish) ID associated with it. This ID /// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first /// registered with the `Selector`. If a type that is previously associated with /// a `Selector` attempts to register itself with a different `Selector`, the /// operation will return with an error. This matches windows behavior. static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT; #[cfg(not(target_os = "netbsd"))] type Filter = c_short; #[cfg(not(target_os = "netbsd"))] type UData = *mut ::libc::c_void; #[cfg(not(target_os = "netbsd"))] type Count = c_int; #[cfg(target_os = "netbsd")] type Filter = u32; #[cfg(target_os = "netbsd")] type UData = ::libc::intptr_t; #[cfg(target_os = "netbsd")] type Count = usize; macro_rules! kevent { ($id: expr, $filter: expr, $flags: expr, $data: expr) => { libc::kevent { ident: $id as ::libc::uintptr_t, filter: $filter as Filter, flags: $flags, fflags: 0, data: 0, udata: $data as UData, } } } pub struct Selector { id: usize, kq: RawFd, } impl Selector { pub fn new() -> io::Result<Selector> { // offset by 1 to avoid choosing 0 as the id of a selector let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; let kq = unsafe { cvt(libc::kqueue())? }; drop(set_cloexec(kq)); Ok(Selector { id: id, kq: kq, }) } pub fn id(&self) -> usize { self.id } pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> { let timeout = timeout.map(|to| { libc::timespec { tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t, tv_nsec: to.subsec_nanos() as libc::c_long, } }); let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut()); unsafe { let cnt = cvt(libc::kevent(self.kq, ptr::null(), 0, evts.sys_events.0.as_mut_ptr(), evts.sys_events.0.capacity() as Count, timeout))?; evts.sys_events.0.set_len(cnt as usize); Ok(evts.coalesce(awakener)) } } pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { trace!("registering; token={:?}; interests={:?}", token, interests); let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } | if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } | libc::EV_RECEIPT; unsafe { let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE }; let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE }; let mut changes = [ kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)), kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)), ]; cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as Count, changes.as_mut_ptr(), changes.len() as Count, ::std::ptr::null()))?; for change in changes.iter() { debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR); // Test to see if an error happened if change.data == 0 { continue } // Older versions of OSX (10.11 and 10.10 have been witnessed) // can return EPIPE when registering a pipe file descriptor // where the other end has already disappeared. For example code // that creates a pipe, closes a file descriptor, and then // registers the other end will see an EPIPE returned from // `register`. // // It also turns out that kevent will still report events on the // file descriptor, telling us that it's readable/hup at least // after we've done this registration. As a result we just // ignore `EPIPE` here instead of propagating it. // // More info can be found at carllerche/mio#582 if change.data as i32 == libc::EPIPE && change.filter == libc::EVFILT_WRITE as Filter { continue } // ignore ENOENT error for EV_DELETE let orig_flags = if change.filter == libc::EVFILT_READ as Filter { r } else { w }; if change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE!= 0 { continue } return Err(::std::io::Error::from_raw_os_error(change.data as i32)); } Ok(()) } } pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { // Just need to call register here since EV_ADD is a mod if already // registered self.register(fd, token, interests, opts) } pub fn deregister(&self, fd: RawFd) -> io::Result<()> { unsafe { // EV_RECEIPT is a nice way to apply changes and get back per-event results while not // draining the actual changes. let filter = libc::EV_DELETE | libc::EV_RECEIPT; #[cfg(not(target_os = "netbsd"))] let mut changes = [ kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()), kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()), ]; #[cfg(target_os = "netbsd")] let mut changes = [ kevent!(fd, libc::EVFILT_READ, filter, 0), kevent!(fd, libc::EVFILT_WRITE, filter, 0), ]; cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as Count, changes.as_mut_ptr(), changes.len() as Count, ::std::ptr::null())).map(|_| ())?; if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT
for change in changes.iter() { debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR); if change.data!= 0 && change.data as i32!= libc::ENOENT { return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); } } Ok(()) } } } impl fmt::Debug for Selector { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Selector") .field("id", &self.id) .field("kq", &self.kq) .finish() } } impl AsRawFd for Selector { fn as_raw_fd(&self) -> RawFd { self.kq } } impl Drop for Selector { fn drop(&mut self) { unsafe { let _ = libc::close(self.kq); } } } pub struct Events { sys_events: KeventList, events: Vec<Event>, event_map: HashMap<Token, usize>, } struct KeventList(Vec<libc::kevent>); unsafe impl Send for KeventList {} unsafe impl Sync for KeventList {} impl Events { pub fn with_capacity(cap: usize) -> Events { Events { sys_events: KeventList(Vec::with_capacity(cap)), events: Vec::with_capacity(cap), event_map: HashMap::with_capacity(cap) } } #[inline] pub fn len(&self) -> usize { self.events.len() } #[inline] pub fn capacity(&self) -> usize { self.events.capacity() } #[inline] pub fn is_empty(&self) -> bool { self.events.is_empty() } pub fn get(&self, idx: usize) -> Option<Event> { self.events.get(idx).map(|e| *e) } fn coalesce(&mut self, awakener: Token) -> bool { let mut ret = false; self.events.clear(); self.event_map.clear(); for e in self.sys_events.0.iter() { let token = Token(e.udata as usize); let len = self.events.len(); if token == awakener { // TODO: Should this return an error if event is an error. It // is not critical as spurious wakeups are permitted. ret = true; continue; } let idx = *self.event_map.entry(token) .or_insert(len); if idx == len { // New entry, insert the default self.events.push(Event::new(Ready::empty(), token)); } if e.flags & libc::EV_ERROR!= 0 { event::kind_mut(&mut self.events[idx]).insert(*UnixReady::error()); } if e.filter == libc::EVFILT_READ as Filter { event::kind_mut(&mut self.events[idx]).insert(Ready::readable()); } else if e.filter == libc::EVFILT_WRITE as Filter { event::kind_mut(&mut self.events[idx]).insert(Ready::writable()); } #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos"))] { if e.filter == libc::EVFILT_AIO { event::kind_mut(&mut self.events[idx]).insert(UnixReady::aio()); } } if e.flags & libc::EV_EOF!= 0 { event::kind_mut(&mut self.events[idx]).insert(UnixReady::hup()); // When the read end of the socket is closed, EV_EOF is set on // flags, and fflags contains the error if there is one. if e.fflags!= 0 { event::kind_mut(&mut self.events[idx]).insert(UnixReady::error()); } } } ret } pub fn push_event(&mut self, event: Event) { self.events.push(event); } } impl fmt::Debug for Events { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Events") .field("len", &self.sys_events.0.len()) .finish() } } #[test] fn does_not_register_rw() { use {Poll, Ready, PollOpt, Token}; use unix::EventedFd; let kq = unsafe { libc::kqueue() }; let kqf = EventedFd(&kq); let poll = Poll::new().unwrap(); // registering kqueue fd will fail if write is requested (On anything but some versions of OS // X) poll.register(&kqf, Token(1234), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); } #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos"))] #[test] fn test_coalesce_aio() { let mut events = Events::with_capacity(1); events.sys_events.0.push(kevent!(0x1234, libc::EVFILT_AIO, 0, 42)); events.coalesce(Token(0)); assert!(events.events[0].readiness() == UnixReady::aio().into()); assert!(events.events[0].token() == Token(42)); }
{ return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); }
conditional_block