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 |
---|---|---|---|---|
socket.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use ffi;
use glib::object::Downcast;
use Widget;
glib_wrapper! {
pub struct Socket(Object<ffi::GtkSocket>): Widget, ::Container;
match fn {
get_type => || ffi::gtk_socket_get_type(),
}
}
impl Socket {
pub fn | () -> Socket {
assert_initialized_main_thread!();
unsafe { Widget::from_glib_none(ffi::gtk_socket_new()).downcast_unchecked() }
}
/*pub fn add_id(&self, window: Window) {
unsafe { ffi::gtk_socket_add_id(self.to_glib_none().0, window) };
}
pub fn get_id(&self) -> Window {
unsafe { ffi::gtk_socket_get_id(self.to_glib_none().0) };
}
pub fn get_plug_window(&self) -> GdkWindow {
let tmp_pointer = unsafe { ffi::gtk_socket_get_plug_window(self.to_glib_none().0) };
// add end of code
}*/
}
| new | identifier_name |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Creates and registers client and network services.
use util::*;
use io::*;
use spec::Spec;
use error::*;
use client::{Client, ClientConfig, ChainNotify};
use miner::Miner;
use snapshot::ManifestData;
use snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams};
use std::sync::atomic::AtomicBool;
#[cfg(feature="ipc")]
use nanoipc;
/// Message type for external and internal events
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ClientIoMessage {
/// Best Block Hash in chain has been changed
NewChainHead,
/// A block is ready
BlockVerified,
/// New transaction RLPs are ready to be imported
NewTransactions(Vec<Bytes>, usize),
/// Begin snapshot restoration
BeginRestoration(ManifestData),
/// Feed a state chunk to the snapshot service
FeedStateChunk(H256, Bytes),
/// Feed a block chunk to the snapshot service
FeedBlockChunk(H256, Bytes),
/// Take a snapshot for the block with given number.
TakeSnapshot(u64),
/// New consensus message received.
NewMessage(Bytes)
}
/// Client service setup. Creates and registers client and network services with the IO subsystem.
pub struct ClientService {
io_service: Arc<IoService<ClientIoMessage>>,
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
panic_handler: Arc<PanicHandler>,
database: Arc<Database>,
_stop_guard: ::devtools::StopGuard,
}
impl ClientService {
/// Start the `ClientService`.
pub fn start(
config: ClientConfig,
spec: &Spec,
client_path: &Path,
snapshot_path: &Path,
ipc_path: &Path,
miner: Arc<Miner>,
) -> Result<ClientService, Error>
| &client_path.to_str().expect("DB path could not be converted to string.")
).map_err(::client::Error::Database)?);
let pruning = config.pruning;
let client = Client::new(config, &spec, db.clone(), miner, io_service.channel())?;
let snapshot_params = SnapServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
db_config: db_config.clone(),
pruning: pruning,
channel: io_service.channel(),
snapshot_root: snapshot_path.into(),
db_restore: client.clone(),
};
let snapshot = Arc::new(SnapshotService::new(snapshot_params)?);
panic_handler.forward_from(&*client);
let client_io = Arc::new(ClientIoHandler {
client: client.clone(),
snapshot: snapshot.clone(),
});
io_service.register_handler(client_io)?;
spec.engine.register_client(Arc::downgrade(&client));
let stop_guard = ::devtools::StopGuard::new();
run_ipc(ipc_path, client.clone(), snapshot.clone(), stop_guard.share());
Ok(ClientService {
io_service: Arc::new(io_service),
client: client,
snapshot: snapshot,
panic_handler: panic_handler,
database: db,
_stop_guard: stop_guard,
})
}
/// Get general IO interface
pub fn register_io_handler(&self, handler: Arc<IoHandler<ClientIoMessage> + Send>) -> Result<(), IoError> {
self.io_service.register_handler(handler)
}
/// Get client interface
pub fn client(&self) -> Arc<Client> {
self.client.clone()
}
/// Get snapshot interface.
pub fn snapshot_service(&self) -> Arc<SnapshotService> {
self.snapshot.clone()
}
/// Get network service component
pub fn io(&self) -> Arc<IoService<ClientIoMessage>> {
self.io_service.clone()
}
/// Set the actor to be notified on certain chain events
pub fn add_notify(&self, notify: Arc<ChainNotify>) {
self.client.add_notify(notify);
}
/// Get a handle to the database.
pub fn db(&self) -> Arc<KeyValueDB> { self.database.clone() }
}
impl MayPanic for ClientService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
/// IO interface for the Client handler
struct ClientIoHandler {
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
}
const CLIENT_TICK_TIMER: TimerToken = 0;
const SNAPSHOT_TICK_TIMER: TimerToken = 1;
const CLIENT_TICK_MS: u64 = 5000;
const SNAPSHOT_TICK_MS: u64 = 10000;
impl IoHandler<ClientIoMessage> for ClientIoHandler {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(CLIENT_TICK_TIMER, CLIENT_TICK_MS).expect("Error registering client timer");
io.register_timer(SNAPSHOT_TICK_TIMER, SNAPSHOT_TICK_MS).expect("Error registering snapshot timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
match timer {
CLIENT_TICK_TIMER => self.client.tick(),
SNAPSHOT_TICK_TIMER => self.snapshot.tick(),
_ => warn!("IO service triggered unregistered timer '{}'", timer),
}
}
#[cfg_attr(feature="dev", allow(single_match))]
fn message(&self, _io: &IoContext<ClientIoMessage>, net_message: &ClientIoMessage) {
use std::thread;
match *net_message {
ClientIoMessage::BlockVerified => { self.client.import_verified_blocks(); }
ClientIoMessage::NewTransactions(ref transactions, peer_id) => {
self.client.import_queued_transactions(transactions, peer_id);
}
ClientIoMessage::BeginRestoration(ref manifest) => {
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
warn!("Failed to initialize snapshot restoration: {}", e);
}
}
ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => self.snapshot.feed_state_chunk(*hash, chunk),
ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => self.snapshot.feed_block_chunk(*hash, chunk),
ClientIoMessage::TakeSnapshot(num) => {
let client = self.client.clone();
let snapshot = self.snapshot.clone();
let res = thread::Builder::new().name("Periodic Snapshot".into()).spawn(move || {
if let Err(e) = snapshot.take_snapshot(&*client, num) {
warn!("Failed to take snapshot at block #{}: {}", num, e);
}
});
if let Err(e) = res {
debug!(target: "snapshot", "Failed to initialize periodic snapshot thread: {:?}", e);
}
},
ClientIoMessage::NewMessage(ref message) => if let Err(e) = self.client.engine().handle_message(message) {
trace!(target: "poa", "Invalid message received: {}", e);
},
_ => {} // ignore other messages
}
}
}
#[cfg(feature="ipc")]
fn run_ipc(base_path: &Path, client: Arc<Client>, snapshot_service: Arc<SnapshotService>, stop: Arc<AtomicBool>) {
let mut path = base_path.to_owned();
path.push("parity-chain.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
let s = stop.clone();
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(client as Arc<BlockChainClient>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!s.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
let mut path = base_path.to_owned();
path.push("parity-snapshot.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(snapshot_service as Arc<::snapshot::SnapshotService>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!stop.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
}
#[cfg(not(feature="ipc"))]
fn run_ipc(_base_path: &Path, _client: Arc<Client>, _snapshot_service: Arc<SnapshotService>, _stop: Arc<AtomicBool>) {
}
#[cfg(test)]
mod tests {
use super::*;
use tests::helpers::*;
use devtools::*;
use client::ClientConfig;
use std::sync::Arc;
use miner::Miner;
#[test]
fn it_can_be_started() {
let temp_path = RandomTempPath::new();
let path = temp_path.as_path().to_owned();
let client_path = {
let mut path = path.to_owned();
path.push("client");
path
};
let snapshot_path = {
let mut path = path.to_owned();
path.push("snapshot");
path
};
let spec = get_test_spec();
let service = ClientService::start(
ClientConfig::default(),
&spec,
&client_path,
&snapshot_path,
&path,
Arc::new(Miner::with_spec(&spec)),
);
assert!(service.is_ok());
drop(service.unwrap());
::std::thread::park_timeout(::std::time::Duration::from_millis(100));
}
}
| {
let panic_handler = PanicHandler::new_in_arc();
let io_service = IoService::<ClientIoMessage>::start()?;
panic_handler.forward_from(&io_service);
info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name()));
let mut db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
// give all rocksdb cache to state column; everything else has its
// own caches.
if let Some(size) = config.db_cache_size {
db_config.set_cache(::db::COL_STATE, size);
}
db_config.compaction = config.db_compaction.compaction_profile(client_path);
db_config.wal = config.db_wal;
let db = Arc::new(Database::open(
&db_config, | identifier_body |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Creates and registers client and network services.
use util::*;
use io::*;
use spec::Spec;
use error::*;
use client::{Client, ClientConfig, ChainNotify};
use miner::Miner;
use snapshot::ManifestData;
use snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams};
use std::sync::atomic::AtomicBool;
#[cfg(feature="ipc")]
use nanoipc;
/// Message type for external and internal events
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ClientIoMessage {
/// Best Block Hash in chain has been changed
NewChainHead,
/// A block is ready
BlockVerified,
/// New transaction RLPs are ready to be imported
NewTransactions(Vec<Bytes>, usize),
/// Begin snapshot restoration
BeginRestoration(ManifestData),
/// Feed a state chunk to the snapshot service
FeedStateChunk(H256, Bytes),
/// Feed a block chunk to the snapshot service
FeedBlockChunk(H256, Bytes),
/// Take a snapshot for the block with given number.
TakeSnapshot(u64),
/// New consensus message received.
NewMessage(Bytes)
}
/// Client service setup. Creates and registers client and network services with the IO subsystem.
pub struct ClientService {
io_service: Arc<IoService<ClientIoMessage>>,
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
panic_handler: Arc<PanicHandler>,
database: Arc<Database>,
_stop_guard: ::devtools::StopGuard,
}
impl ClientService {
/// Start the `ClientService`.
pub fn start(
config: ClientConfig,
spec: &Spec,
client_path: &Path,
snapshot_path: &Path,
ipc_path: &Path,
miner: Arc<Miner>,
) -> Result<ClientService, Error>
{
let panic_handler = PanicHandler::new_in_arc();
let io_service = IoService::<ClientIoMessage>::start()?;
panic_handler.forward_from(&io_service);
info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name()));
let mut db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
// give all rocksdb cache to state column; everything else has its
// own caches.
if let Some(size) = config.db_cache_size {
db_config.set_cache(::db::COL_STATE, size);
}
db_config.compaction = config.db_compaction.compaction_profile(client_path);
db_config.wal = config.db_wal;
let db = Arc::new(Database::open(
&db_config,
&client_path.to_str().expect("DB path could not be converted to string.")
).map_err(::client::Error::Database)?);
let pruning = config.pruning;
let client = Client::new(config, &spec, db.clone(), miner, io_service.channel())?;
let snapshot_params = SnapServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
db_config: db_config.clone(),
pruning: pruning,
channel: io_service.channel(),
snapshot_root: snapshot_path.into(),
db_restore: client.clone(),
};
let snapshot = Arc::new(SnapshotService::new(snapshot_params)?);
panic_handler.forward_from(&*client);
let client_io = Arc::new(ClientIoHandler {
client: client.clone(),
snapshot: snapshot.clone(),
});
io_service.register_handler(client_io)?;
spec.engine.register_client(Arc::downgrade(&client));
let stop_guard = ::devtools::StopGuard::new();
run_ipc(ipc_path, client.clone(), snapshot.clone(), stop_guard.share());
Ok(ClientService {
io_service: Arc::new(io_service),
client: client,
snapshot: snapshot,
panic_handler: panic_handler,
database: db,
_stop_guard: stop_guard,
})
}
/// Get general IO interface
pub fn register_io_handler(&self, handler: Arc<IoHandler<ClientIoMessage> + Send>) -> Result<(), IoError> {
self.io_service.register_handler(handler)
}
/// Get client interface
pub fn | (&self) -> Arc<Client> {
self.client.clone()
}
/// Get snapshot interface.
pub fn snapshot_service(&self) -> Arc<SnapshotService> {
self.snapshot.clone()
}
/// Get network service component
pub fn io(&self) -> Arc<IoService<ClientIoMessage>> {
self.io_service.clone()
}
/// Set the actor to be notified on certain chain events
pub fn add_notify(&self, notify: Arc<ChainNotify>) {
self.client.add_notify(notify);
}
/// Get a handle to the database.
pub fn db(&self) -> Arc<KeyValueDB> { self.database.clone() }
}
impl MayPanic for ClientService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
/// IO interface for the Client handler
struct ClientIoHandler {
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
}
const CLIENT_TICK_TIMER: TimerToken = 0;
const SNAPSHOT_TICK_TIMER: TimerToken = 1;
const CLIENT_TICK_MS: u64 = 5000;
const SNAPSHOT_TICK_MS: u64 = 10000;
impl IoHandler<ClientIoMessage> for ClientIoHandler {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(CLIENT_TICK_TIMER, CLIENT_TICK_MS).expect("Error registering client timer");
io.register_timer(SNAPSHOT_TICK_TIMER, SNAPSHOT_TICK_MS).expect("Error registering snapshot timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
match timer {
CLIENT_TICK_TIMER => self.client.tick(),
SNAPSHOT_TICK_TIMER => self.snapshot.tick(),
_ => warn!("IO service triggered unregistered timer '{}'", timer),
}
}
#[cfg_attr(feature="dev", allow(single_match))]
fn message(&self, _io: &IoContext<ClientIoMessage>, net_message: &ClientIoMessage) {
use std::thread;
match *net_message {
ClientIoMessage::BlockVerified => { self.client.import_verified_blocks(); }
ClientIoMessage::NewTransactions(ref transactions, peer_id) => {
self.client.import_queued_transactions(transactions, peer_id);
}
ClientIoMessage::BeginRestoration(ref manifest) => {
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
warn!("Failed to initialize snapshot restoration: {}", e);
}
}
ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => self.snapshot.feed_state_chunk(*hash, chunk),
ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => self.snapshot.feed_block_chunk(*hash, chunk),
ClientIoMessage::TakeSnapshot(num) => {
let client = self.client.clone();
let snapshot = self.snapshot.clone();
let res = thread::Builder::new().name("Periodic Snapshot".into()).spawn(move || {
if let Err(e) = snapshot.take_snapshot(&*client, num) {
warn!("Failed to take snapshot at block #{}: {}", num, e);
}
});
if let Err(e) = res {
debug!(target: "snapshot", "Failed to initialize periodic snapshot thread: {:?}", e);
}
},
ClientIoMessage::NewMessage(ref message) => if let Err(e) = self.client.engine().handle_message(message) {
trace!(target: "poa", "Invalid message received: {}", e);
},
_ => {} // ignore other messages
}
}
}
#[cfg(feature="ipc")]
fn run_ipc(base_path: &Path, client: Arc<Client>, snapshot_service: Arc<SnapshotService>, stop: Arc<AtomicBool>) {
let mut path = base_path.to_owned();
path.push("parity-chain.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
let s = stop.clone();
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(client as Arc<BlockChainClient>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!s.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
let mut path = base_path.to_owned();
path.push("parity-snapshot.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(snapshot_service as Arc<::snapshot::SnapshotService>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!stop.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
}
#[cfg(not(feature="ipc"))]
fn run_ipc(_base_path: &Path, _client: Arc<Client>, _snapshot_service: Arc<SnapshotService>, _stop: Arc<AtomicBool>) {
}
#[cfg(test)]
mod tests {
use super::*;
use tests::helpers::*;
use devtools::*;
use client::ClientConfig;
use std::sync::Arc;
use miner::Miner;
#[test]
fn it_can_be_started() {
let temp_path = RandomTempPath::new();
let path = temp_path.as_path().to_owned();
let client_path = {
let mut path = path.to_owned();
path.push("client");
path
};
let snapshot_path = {
let mut path = path.to_owned();
path.push("snapshot");
path
};
let spec = get_test_spec();
let service = ClientService::start(
ClientConfig::default(),
&spec,
&client_path,
&snapshot_path,
&path,
Arc::new(Miner::with_spec(&spec)),
);
assert!(service.is_ok());
drop(service.unwrap());
::std::thread::park_timeout(::std::time::Duration::from_millis(100));
}
}
| client | identifier_name |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Creates and registers client and network services.
use util::*;
use io::*;
use spec::Spec;
use error::*;
use client::{Client, ClientConfig, ChainNotify};
use miner::Miner;
use snapshot::ManifestData;
use snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams};
use std::sync::atomic::AtomicBool;
#[cfg(feature="ipc")]
use nanoipc;
/// Message type for external and internal events
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ClientIoMessage {
/// Best Block Hash in chain has been changed
NewChainHead,
/// A block is ready
BlockVerified,
/// New transaction RLPs are ready to be imported
NewTransactions(Vec<Bytes>, usize),
/// Begin snapshot restoration
BeginRestoration(ManifestData),
/// Feed a state chunk to the snapshot service
FeedStateChunk(H256, Bytes),
/// Feed a block chunk to the snapshot service
FeedBlockChunk(H256, Bytes),
/// Take a snapshot for the block with given number.
TakeSnapshot(u64),
/// New consensus message received.
NewMessage(Bytes)
}
/// Client service setup. Creates and registers client and network services with the IO subsystem.
pub struct ClientService {
io_service: Arc<IoService<ClientIoMessage>>,
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
panic_handler: Arc<PanicHandler>,
database: Arc<Database>,
_stop_guard: ::devtools::StopGuard,
}
impl ClientService {
/// Start the `ClientService`.
pub fn start(
config: ClientConfig,
spec: &Spec,
client_path: &Path,
snapshot_path: &Path,
ipc_path: &Path,
miner: Arc<Miner>,
) -> Result<ClientService, Error>
{
let panic_handler = PanicHandler::new_in_arc();
let io_service = IoService::<ClientIoMessage>::start()?;
panic_handler.forward_from(&io_service);
info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name()));
let mut db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
// give all rocksdb cache to state column; everything else has its
// own caches.
if let Some(size) = config.db_cache_size {
db_config.set_cache(::db::COL_STATE, size);
}
db_config.compaction = config.db_compaction.compaction_profile(client_path);
db_config.wal = config.db_wal;
let db = Arc::new(Database::open(
&db_config,
&client_path.to_str().expect("DB path could not be converted to string.")
).map_err(::client::Error::Database)?);
let pruning = config.pruning;
let client = Client::new(config, &spec, db.clone(), miner, io_service.channel())?;
let snapshot_params = SnapServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
db_config: db_config.clone(),
pruning: pruning,
channel: io_service.channel(),
snapshot_root: snapshot_path.into(),
db_restore: client.clone(),
};
let snapshot = Arc::new(SnapshotService::new(snapshot_params)?);
panic_handler.forward_from(&*client);
let client_io = Arc::new(ClientIoHandler {
client: client.clone(),
snapshot: snapshot.clone(),
});
io_service.register_handler(client_io)?;
spec.engine.register_client(Arc::downgrade(&client));
let stop_guard = ::devtools::StopGuard::new();
run_ipc(ipc_path, client.clone(), snapshot.clone(), stop_guard.share());
Ok(ClientService {
io_service: Arc::new(io_service),
client: client,
snapshot: snapshot,
panic_handler: panic_handler,
database: db,
_stop_guard: stop_guard,
})
}
/// Get general IO interface
pub fn register_io_handler(&self, handler: Arc<IoHandler<ClientIoMessage> + Send>) -> Result<(), IoError> {
self.io_service.register_handler(handler)
}
/// Get client interface
pub fn client(&self) -> Arc<Client> {
self.client.clone()
}
/// Get snapshot interface.
pub fn snapshot_service(&self) -> Arc<SnapshotService> {
self.snapshot.clone()
}
/// Get network service component
pub fn io(&self) -> Arc<IoService<ClientIoMessage>> {
self.io_service.clone()
}
/// Set the actor to be notified on certain chain events
pub fn add_notify(&self, notify: Arc<ChainNotify>) {
self.client.add_notify(notify);
}
/// Get a handle to the database.
pub fn db(&self) -> Arc<KeyValueDB> { self.database.clone() }
}
impl MayPanic for ClientService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
/// IO interface for the Client handler
struct ClientIoHandler {
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
}
const CLIENT_TICK_TIMER: TimerToken = 0;
const SNAPSHOT_TICK_TIMER: TimerToken = 1;
const CLIENT_TICK_MS: u64 = 5000;
const SNAPSHOT_TICK_MS: u64 = 10000;
impl IoHandler<ClientIoMessage> for ClientIoHandler {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(CLIENT_TICK_TIMER, CLIENT_TICK_MS).expect("Error registering client timer");
io.register_timer(SNAPSHOT_TICK_TIMER, SNAPSHOT_TICK_MS).expect("Error registering snapshot timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
match timer {
CLIENT_TICK_TIMER => self.client.tick(),
SNAPSHOT_TICK_TIMER => self.snapshot.tick(),
_ => warn!("IO service triggered unregistered timer '{}'", timer),
}
}
#[cfg_attr(feature="dev", allow(single_match))]
fn message(&self, _io: &IoContext<ClientIoMessage>, net_message: &ClientIoMessage) {
use std::thread;
match *net_message {
ClientIoMessage::BlockVerified => { self.client.import_verified_blocks(); }
ClientIoMessage::NewTransactions(ref transactions, peer_id) => {
self.client.import_queued_transactions(transactions, peer_id);
}
ClientIoMessage::BeginRestoration(ref manifest) => |
ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => self.snapshot.feed_state_chunk(*hash, chunk),
ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => self.snapshot.feed_block_chunk(*hash, chunk),
ClientIoMessage::TakeSnapshot(num) => {
let client = self.client.clone();
let snapshot = self.snapshot.clone();
let res = thread::Builder::new().name("Periodic Snapshot".into()).spawn(move || {
if let Err(e) = snapshot.take_snapshot(&*client, num) {
warn!("Failed to take snapshot at block #{}: {}", num, e);
}
});
if let Err(e) = res {
debug!(target: "snapshot", "Failed to initialize periodic snapshot thread: {:?}", e);
}
},
ClientIoMessage::NewMessage(ref message) => if let Err(e) = self.client.engine().handle_message(message) {
trace!(target: "poa", "Invalid message received: {}", e);
},
_ => {} // ignore other messages
}
}
}
#[cfg(feature="ipc")]
fn run_ipc(base_path: &Path, client: Arc<Client>, snapshot_service: Arc<SnapshotService>, stop: Arc<AtomicBool>) {
let mut path = base_path.to_owned();
path.push("parity-chain.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
let s = stop.clone();
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(client as Arc<BlockChainClient>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!s.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
let mut path = base_path.to_owned();
path.push("parity-snapshot.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(snapshot_service as Arc<::snapshot::SnapshotService>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!stop.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
}
#[cfg(not(feature="ipc"))]
fn run_ipc(_base_path: &Path, _client: Arc<Client>, _snapshot_service: Arc<SnapshotService>, _stop: Arc<AtomicBool>) {
}
#[cfg(test)]
mod tests {
use super::*;
use tests::helpers::*;
use devtools::*;
use client::ClientConfig;
use std::sync::Arc;
use miner::Miner;
#[test]
fn it_can_be_started() {
let temp_path = RandomTempPath::new();
let path = temp_path.as_path().to_owned();
let client_path = {
let mut path = path.to_owned();
path.push("client");
path
};
let snapshot_path = {
let mut path = path.to_owned();
path.push("snapshot");
path
};
let spec = get_test_spec();
let service = ClientService::start(
ClientConfig::default(),
&spec,
&client_path,
&snapshot_path,
&path,
Arc::new(Miner::with_spec(&spec)),
);
assert!(service.is_ok());
drop(service.unwrap());
::std::thread::park_timeout(::std::time::Duration::from_millis(100));
}
}
| {
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
warn!("Failed to initialize snapshot restoration: {}", e);
}
} | conditional_block |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Creates and registers client and network services.
use util::*;
use io::*;
use spec::Spec;
use error::*;
use client::{Client, ClientConfig, ChainNotify};
use miner::Miner;
use snapshot::ManifestData;
use snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams};
use std::sync::atomic::AtomicBool;
#[cfg(feature="ipc")]
use nanoipc;
/// Message type for external and internal events
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ClientIoMessage {
/// Best Block Hash in chain has been changed
NewChainHead,
/// A block is ready
BlockVerified,
/// New transaction RLPs are ready to be imported
NewTransactions(Vec<Bytes>, usize),
/// Begin snapshot restoration
BeginRestoration(ManifestData),
/// Feed a state chunk to the snapshot service
FeedStateChunk(H256, Bytes),
/// Feed a block chunk to the snapshot service
FeedBlockChunk(H256, Bytes),
/// Take a snapshot for the block with given number.
TakeSnapshot(u64),
/// New consensus message received.
NewMessage(Bytes)
}
/// Client service setup. Creates and registers client and network services with the IO subsystem.
pub struct ClientService {
io_service: Arc<IoService<ClientIoMessage>>,
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
panic_handler: Arc<PanicHandler>,
database: Arc<Database>,
_stop_guard: ::devtools::StopGuard,
}
impl ClientService {
/// Start the `ClientService`.
pub fn start(
config: ClientConfig,
spec: &Spec,
client_path: &Path,
snapshot_path: &Path,
ipc_path: &Path,
miner: Arc<Miner>,
) -> Result<ClientService, Error>
{
let panic_handler = PanicHandler::new_in_arc();
let io_service = IoService::<ClientIoMessage>::start()?;
panic_handler.forward_from(&io_service);
info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name()));
let mut db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
// give all rocksdb cache to state column; everything else has its
// own caches.
if let Some(size) = config.db_cache_size {
db_config.set_cache(::db::COL_STATE, size);
}
db_config.compaction = config.db_compaction.compaction_profile(client_path);
db_config.wal = config.db_wal;
let db = Arc::new(Database::open(
&db_config,
&client_path.to_str().expect("DB path could not be converted to string.")
).map_err(::client::Error::Database)?);
let pruning = config.pruning;
let client = Client::new(config, &spec, db.clone(), miner, io_service.channel())?;
let snapshot_params = SnapServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
db_config: db_config.clone(),
pruning: pruning,
channel: io_service.channel(),
snapshot_root: snapshot_path.into(),
db_restore: client.clone(),
};
let snapshot = Arc::new(SnapshotService::new(snapshot_params)?);
panic_handler.forward_from(&*client);
let client_io = Arc::new(ClientIoHandler {
client: client.clone(),
snapshot: snapshot.clone(),
});
io_service.register_handler(client_io)?;
spec.engine.register_client(Arc::downgrade(&client)); | run_ipc(ipc_path, client.clone(), snapshot.clone(), stop_guard.share());
Ok(ClientService {
io_service: Arc::new(io_service),
client: client,
snapshot: snapshot,
panic_handler: panic_handler,
database: db,
_stop_guard: stop_guard,
})
}
/// Get general IO interface
pub fn register_io_handler(&self, handler: Arc<IoHandler<ClientIoMessage> + Send>) -> Result<(), IoError> {
self.io_service.register_handler(handler)
}
/// Get client interface
pub fn client(&self) -> Arc<Client> {
self.client.clone()
}
/// Get snapshot interface.
pub fn snapshot_service(&self) -> Arc<SnapshotService> {
self.snapshot.clone()
}
/// Get network service component
pub fn io(&self) -> Arc<IoService<ClientIoMessage>> {
self.io_service.clone()
}
/// Set the actor to be notified on certain chain events
pub fn add_notify(&self, notify: Arc<ChainNotify>) {
self.client.add_notify(notify);
}
/// Get a handle to the database.
pub fn db(&self) -> Arc<KeyValueDB> { self.database.clone() }
}
impl MayPanic for ClientService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
/// IO interface for the Client handler
struct ClientIoHandler {
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
}
const CLIENT_TICK_TIMER: TimerToken = 0;
const SNAPSHOT_TICK_TIMER: TimerToken = 1;
const CLIENT_TICK_MS: u64 = 5000;
const SNAPSHOT_TICK_MS: u64 = 10000;
impl IoHandler<ClientIoMessage> for ClientIoHandler {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(CLIENT_TICK_TIMER, CLIENT_TICK_MS).expect("Error registering client timer");
io.register_timer(SNAPSHOT_TICK_TIMER, SNAPSHOT_TICK_MS).expect("Error registering snapshot timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
match timer {
CLIENT_TICK_TIMER => self.client.tick(),
SNAPSHOT_TICK_TIMER => self.snapshot.tick(),
_ => warn!("IO service triggered unregistered timer '{}'", timer),
}
}
#[cfg_attr(feature="dev", allow(single_match))]
fn message(&self, _io: &IoContext<ClientIoMessage>, net_message: &ClientIoMessage) {
use std::thread;
match *net_message {
ClientIoMessage::BlockVerified => { self.client.import_verified_blocks(); }
ClientIoMessage::NewTransactions(ref transactions, peer_id) => {
self.client.import_queued_transactions(transactions, peer_id);
}
ClientIoMessage::BeginRestoration(ref manifest) => {
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
warn!("Failed to initialize snapshot restoration: {}", e);
}
}
ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => self.snapshot.feed_state_chunk(*hash, chunk),
ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => self.snapshot.feed_block_chunk(*hash, chunk),
ClientIoMessage::TakeSnapshot(num) => {
let client = self.client.clone();
let snapshot = self.snapshot.clone();
let res = thread::Builder::new().name("Periodic Snapshot".into()).spawn(move || {
if let Err(e) = snapshot.take_snapshot(&*client, num) {
warn!("Failed to take snapshot at block #{}: {}", num, e);
}
});
if let Err(e) = res {
debug!(target: "snapshot", "Failed to initialize periodic snapshot thread: {:?}", e);
}
},
ClientIoMessage::NewMessage(ref message) => if let Err(e) = self.client.engine().handle_message(message) {
trace!(target: "poa", "Invalid message received: {}", e);
},
_ => {} // ignore other messages
}
}
}
#[cfg(feature="ipc")]
fn run_ipc(base_path: &Path, client: Arc<Client>, snapshot_service: Arc<SnapshotService>, stop: Arc<AtomicBool>) {
let mut path = base_path.to_owned();
path.push("parity-chain.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
let s = stop.clone();
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(client as Arc<BlockChainClient>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!s.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
let mut path = base_path.to_owned();
path.push("parity-snapshot.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(snapshot_service as Arc<::snapshot::SnapshotService>));
worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while!stop.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll();
}
});
}
#[cfg(not(feature="ipc"))]
fn run_ipc(_base_path: &Path, _client: Arc<Client>, _snapshot_service: Arc<SnapshotService>, _stop: Arc<AtomicBool>) {
}
#[cfg(test)]
mod tests {
use super::*;
use tests::helpers::*;
use devtools::*;
use client::ClientConfig;
use std::sync::Arc;
use miner::Miner;
#[test]
fn it_can_be_started() {
let temp_path = RandomTempPath::new();
let path = temp_path.as_path().to_owned();
let client_path = {
let mut path = path.to_owned();
path.push("client");
path
};
let snapshot_path = {
let mut path = path.to_owned();
path.push("snapshot");
path
};
let spec = get_test_spec();
let service = ClientService::start(
ClientConfig::default(),
&spec,
&client_path,
&snapshot_path,
&path,
Arc::new(Miner::with_spec(&spec)),
);
assert!(service.is_ok());
drop(service.unwrap());
::std::thread::park_timeout(::std::time::Duration::from_millis(100));
}
} |
let stop_guard = ::devtools::StopGuard::new(); | random_line_split |
call.rs | //! Facilities for working with `v8::FunctionCallbackInfo` and getting the current `v8::Isolate`.
use std::os::raw::c_void;
use std::ptr::null_mut;
use raw::{FunctionCallbackInfo, Isolate, Local};
#[repr(C)]
pub struct | {
pub static_callback: *mut c_void,
pub dynamic_callback: *mut c_void
}
impl Default for CCallback {
fn default() -> Self {
CCallback {
static_callback: null_mut(),
dynamic_callback: null_mut()
}
}
}
extern "C" {
/// Sets the return value of the function call.
#[link_name = "Neon_Call_SetReturn"]
pub fn set_return(info: &FunctionCallbackInfo, value: Local);
/// Gets the isolate of the function call.
#[link_name = "Neon_Call_GetIsolate"]
pub fn get_isolate(info: &FunctionCallbackInfo) -> *mut Isolate;
/// Gets the current `v8::Isolate`.
#[link_name = "Neon_Call_CurrentIsolate"]
pub fn current_isolate() -> *mut Isolate;
/// Indicates if the function call was invoked as a constructor.
#[link_name = "Neon_Call_IsConstruct"]
pub fn is_construct(info: &FunctionCallbackInfo) -> bool;
/// Mutates the `out` argument provided to refer to the `v8::Local` handle value of the object
/// the function is bound to.
#[link_name = "Neon_Call_This"]
pub fn this(info: &FunctionCallbackInfo, out: &mut Local);
/// Mutates the `out` argument provided to refer to the `v8::Local` handle value of the
/// `v8::FunctionCallbackInfo` `Data`.
#[link_name = "Neon_Call_Data"]
pub fn data(info: &FunctionCallbackInfo, out: &mut Local);
/// Gets the number of arguments passed to the function.
#[link_name = "Neon_Call_Length"]
pub fn len(info: &FunctionCallbackInfo) -> i32;
/// Mutates the `out` argument provided to refer to the `v8::Local` handle value of the `i`th
/// argument passed to the function.
#[link_name = "Neon_Call_Get"]
pub fn get(info: &FunctionCallbackInfo, i: i32, out: &mut Local);
}
| CCallback | identifier_name |
call.rs | //! Facilities for working with `v8::FunctionCallbackInfo` and getting the current `v8::Isolate`.
use std::os::raw::c_void;
use std::ptr::null_mut;
use raw::{FunctionCallbackInfo, Isolate, Local};
#[repr(C)]
pub struct CCallback {
pub static_callback: *mut c_void,
pub dynamic_callback: *mut c_void
}
impl Default for CCallback {
fn default() -> Self {
CCallback {
static_callback: null_mut(),
dynamic_callback: null_mut()
}
}
} | /// Sets the return value of the function call.
#[link_name = "Neon_Call_SetReturn"]
pub fn set_return(info: &FunctionCallbackInfo, value: Local);
/// Gets the isolate of the function call.
#[link_name = "Neon_Call_GetIsolate"]
pub fn get_isolate(info: &FunctionCallbackInfo) -> *mut Isolate;
/// Gets the current `v8::Isolate`.
#[link_name = "Neon_Call_CurrentIsolate"]
pub fn current_isolate() -> *mut Isolate;
/// Indicates if the function call was invoked as a constructor.
#[link_name = "Neon_Call_IsConstruct"]
pub fn is_construct(info: &FunctionCallbackInfo) -> bool;
/// Mutates the `out` argument provided to refer to the `v8::Local` handle value of the object
/// the function is bound to.
#[link_name = "Neon_Call_This"]
pub fn this(info: &FunctionCallbackInfo, out: &mut Local);
/// Mutates the `out` argument provided to refer to the `v8::Local` handle value of the
/// `v8::FunctionCallbackInfo` `Data`.
#[link_name = "Neon_Call_Data"]
pub fn data(info: &FunctionCallbackInfo, out: &mut Local);
/// Gets the number of arguments passed to the function.
#[link_name = "Neon_Call_Length"]
pub fn len(info: &FunctionCallbackInfo) -> i32;
/// Mutates the `out` argument provided to refer to the `v8::Local` handle value of the `i`th
/// argument passed to the function.
#[link_name = "Neon_Call_Get"]
pub fn get(info: &FunctionCallbackInfo, i: i32, out: &mut Local);
} |
extern "C" {
| random_line_split |
lib.rs | #![deny(missing_docs)]
//! Bootstrapped meta rules for mathematical notation.
extern crate range;
extern crate piston_meta;
use piston_meta::Syntax;
pub mod interpreter;
/// Gets the syntax rules.
pub fn syntax_rules() -> Syntax {
use piston_meta::*;
let meta_rules = bootstrap::rules();
let source = include_str!("../assets/syntax.txt");
let mut res = vec![];
parse(&meta_rules, source, &mut res).unwrap();
bootstrap::convert(&res, &mut vec![]).unwrap()
}
#[cfg(test)]
mod tests {
use piston_meta::*;
#[test]
fn test_syntax() {
let syntax = "assets/syntax.txt";
let _ = load_syntax_data2(syntax, "assets/bool.txt");
let _ = load_syntax_data2(syntax, "assets/nat.txt"); | let _ = load_syntax_data2(syntax, "assets/the-simpsons.txt");
}
} | let _ = load_syntax_data2(syntax, "assets/option.txt");
let _ = load_syntax_data2(syntax, "assets/string.txt"); | random_line_split |
lib.rs | #![deny(missing_docs)]
//! Bootstrapped meta rules for mathematical notation.
extern crate range;
extern crate piston_meta;
use piston_meta::Syntax;
pub mod interpreter;
/// Gets the syntax rules.
pub fn syntax_rules() -> Syntax {
use piston_meta::*;
let meta_rules = bootstrap::rules();
let source = include_str!("../assets/syntax.txt");
let mut res = vec![];
parse(&meta_rules, source, &mut res).unwrap();
bootstrap::convert(&res, &mut vec![]).unwrap()
}
#[cfg(test)]
mod tests {
use piston_meta::*;
#[test]
fn | () {
let syntax = "assets/syntax.txt";
let _ = load_syntax_data2(syntax, "assets/bool.txt");
let _ = load_syntax_data2(syntax, "assets/nat.txt");
let _ = load_syntax_data2(syntax, "assets/option.txt");
let _ = load_syntax_data2(syntax, "assets/string.txt");
let _ = load_syntax_data2(syntax, "assets/the-simpsons.txt");
}
}
| test_syntax | identifier_name |
lib.rs | #![deny(missing_docs)]
//! Bootstrapped meta rules for mathematical notation.
extern crate range;
extern crate piston_meta;
use piston_meta::Syntax;
pub mod interpreter;
/// Gets the syntax rules.
pub fn syntax_rules() -> Syntax {
use piston_meta::*;
let meta_rules = bootstrap::rules();
let source = include_str!("../assets/syntax.txt");
let mut res = vec![];
parse(&meta_rules, source, &mut res).unwrap();
bootstrap::convert(&res, &mut vec![]).unwrap()
}
#[cfg(test)]
mod tests {
use piston_meta::*;
#[test]
fn test_syntax() |
}
| {
let syntax = "assets/syntax.txt";
let _ = load_syntax_data2(syntax, "assets/bool.txt");
let _ = load_syntax_data2(syntax, "assets/nat.txt");
let _ = load_syntax_data2(syntax, "assets/option.txt");
let _ = load_syntax_data2(syntax, "assets/string.txt");
let _ = load_syntax_data2(syntax, "assets/the-simpsons.txt");
} | identifier_body |
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n {
counter += 1;
chars.next();
} else {
break;
}
}
compressed.push_str(counter.to_string().as_str());
compressed.push(c);
}
compressed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compress_empty_string() {
assert_eq!(compress(""), "");
}
#[test]
fn compress_unique_chars_string() |
#[test]
fn compress_doubled_chars_string() {
assert_eq!(compress("aabbcc"), "2a2b2c");
}
}
| {
assert_eq!(compress("abc"), "1a1b1c");
} | identifier_body |
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n {
counter += 1;
chars.next();
} else {
break;
}
}
compressed.push_str(counter.to_string().as_str());
compressed.push(c);
}
compressed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compress_empty_string() {
assert_eq!(compress(""), "");
}
| #[test]
fn compress_unique_chars_string() {
assert_eq!(compress("abc"), "1a1b1c");
}
#[test]
fn compress_doubled_chars_string() {
assert_eq!(compress("aabbcc"), "2a2b2c");
}
} | random_line_split |
|
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n {
counter += 1;
chars.next();
} else {
break;
}
}
compressed.push_str(counter.to_string().as_str());
compressed.push(c);
}
compressed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compress_empty_string() {
assert_eq!(compress(""), "");
}
#[test]
fn compress_unique_chars_string() {
assert_eq!(compress("abc"), "1a1b1c");
}
#[test]
fn | () {
assert_eq!(compress("aabbcc"), "2a2b2c");
}
}
| compress_doubled_chars_string | identifier_name |
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n | else {
break;
}
}
compressed.push_str(counter.to_string().as_str());
compressed.push(c);
}
compressed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compress_empty_string() {
assert_eq!(compress(""), "");
}
#[test]
fn compress_unique_chars_string() {
assert_eq!(compress("abc"), "1a1b1c");
}
#[test]
fn compress_doubled_chars_string() {
assert_eq!(compress("aabbcc"), "2a2b2c");
}
}
| {
counter += 1;
chars.next();
} | conditional_block |
lib.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/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::MallocSizeOf;
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum PixelFormat {
/// Luminance channel only
K8,
/// Luminance + alpha
KA8,
/// RGB, 8 bits per channel
RGB8,
/// RGB + alpha, 8 bits per channel
RGBA8,
/// BGR + alpha, 8 bits per channel
BGRA8,
}
pub fn rgba8_get_rect(pixels: &[u8], size: Size2D<u32>, rect: Rect<u32>) -> Cow<[u8]> {
assert!(!rect.is_empty());
assert!(Rect::from_size(size).contains_rect(&rect));
assert_eq!(pixels.len() % 4, 0);
assert_eq!(size.area() as usize, pixels.len() / 4);
let area = rect.size.area() as usize;
let first_column_start = rect.origin.x as usize * 4;
let row_length = size.width as usize * 4;
let first_row_start = rect.origin.y as usize * row_length;
if rect.origin.x == 0 && rect.size.width == size.width || rect.size.height == 1 {
let start = first_column_start + first_row_start;
return Cow::Borrowed(&pixels[start..start + area * 4]);
}
let mut data = Vec::with_capacity(area * 4);
for row in pixels[first_row_start..]
.chunks(row_length)
.take(rect.size.height as usize)
{
data.extend_from_slice(&row[first_column_start..][..rect.size.width as usize * 4]);
}
data.into()
}
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
pub fn rgba8_byte_swap_colors_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = rgba[2];
rgba[2] = b;
}
}
pub fn rgba8_byte_swap_and_premultiply_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = multiply_u8_color(rgba[2], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(b, rgba[3]);
}
}
/// Returns true if the pixels were found to be completely opaque.
pub fn rgba8_premultiply_inplace(pixels: &mut [u8]) -> bool {
assert!(pixels.len() % 4 == 0);
let mut is_opaque = true;
for rgba in pixels.chunks_mut(4) {
rgba[0] = multiply_u8_color(rgba[0], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(rgba[2], rgba[3]);
is_opaque = is_opaque && rgba[3] == 255;
}
is_opaque
}
pub fn multiply_u8_color(a: u8, b: u8) -> u8 {
return (a as u32 * b as u32 / 255) as u8;
}
pub fn clip(
mut origin: Point2D<i32>,
mut size: Size2D<u32>,
surface: Size2D<u32>,
) -> Option<Rect<u32>> {
if origin.x < 0 |
if origin.y < 0 {
size.height = size.height.saturating_sub(-origin.y as u32);
origin.y = 0;
}
Rect::new(origin.to_u32(), size)
.intersection(&Rect::from_size(surface))
.filter(|rect|!rect.is_empty())
}
| {
size.width = size.width.saturating_sub(-origin.x as u32);
origin.x = 0;
} | conditional_block |
lib.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/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::MallocSizeOf;
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum PixelFormat {
/// Luminance channel only
K8,
/// Luminance + alpha
KA8,
/// RGB, 8 bits per channel
RGB8,
/// RGB + alpha, 8 bits per channel
RGBA8,
/// BGR + alpha, 8 bits per channel
BGRA8,
}
pub fn | (pixels: &[u8], size: Size2D<u32>, rect: Rect<u32>) -> Cow<[u8]> {
assert!(!rect.is_empty());
assert!(Rect::from_size(size).contains_rect(&rect));
assert_eq!(pixels.len() % 4, 0);
assert_eq!(size.area() as usize, pixels.len() / 4);
let area = rect.size.area() as usize;
let first_column_start = rect.origin.x as usize * 4;
let row_length = size.width as usize * 4;
let first_row_start = rect.origin.y as usize * row_length;
if rect.origin.x == 0 && rect.size.width == size.width || rect.size.height == 1 {
let start = first_column_start + first_row_start;
return Cow::Borrowed(&pixels[start..start + area * 4]);
}
let mut data = Vec::with_capacity(area * 4);
for row in pixels[first_row_start..]
.chunks(row_length)
.take(rect.size.height as usize)
{
data.extend_from_slice(&row[first_column_start..][..rect.size.width as usize * 4]);
}
data.into()
}
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
pub fn rgba8_byte_swap_colors_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = rgba[2];
rgba[2] = b;
}
}
pub fn rgba8_byte_swap_and_premultiply_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = multiply_u8_color(rgba[2], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(b, rgba[3]);
}
}
/// Returns true if the pixels were found to be completely opaque.
pub fn rgba8_premultiply_inplace(pixels: &mut [u8]) -> bool {
assert!(pixels.len() % 4 == 0);
let mut is_opaque = true;
for rgba in pixels.chunks_mut(4) {
rgba[0] = multiply_u8_color(rgba[0], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(rgba[2], rgba[3]);
is_opaque = is_opaque && rgba[3] == 255;
}
is_opaque
}
pub fn multiply_u8_color(a: u8, b: u8) -> u8 {
return (a as u32 * b as u32 / 255) as u8;
}
pub fn clip(
mut origin: Point2D<i32>,
mut size: Size2D<u32>,
surface: Size2D<u32>,
) -> Option<Rect<u32>> {
if origin.x < 0 {
size.width = size.width.saturating_sub(-origin.x as u32);
origin.x = 0;
}
if origin.y < 0 {
size.height = size.height.saturating_sub(-origin.y as u32);
origin.y = 0;
}
Rect::new(origin.to_u32(), size)
.intersection(&Rect::from_size(surface))
.filter(|rect|!rect.is_empty())
}
| rgba8_get_rect | identifier_name |
lib.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/. */
#[macro_use] | extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::MallocSizeOf;
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum PixelFormat {
/// Luminance channel only
K8,
/// Luminance + alpha
KA8,
/// RGB, 8 bits per channel
RGB8,
/// RGB + alpha, 8 bits per channel
RGBA8,
/// BGR + alpha, 8 bits per channel
BGRA8,
}
pub fn rgba8_get_rect(pixels: &[u8], size: Size2D<u32>, rect: Rect<u32>) -> Cow<[u8]> {
assert!(!rect.is_empty());
assert!(Rect::from_size(size).contains_rect(&rect));
assert_eq!(pixels.len() % 4, 0);
assert_eq!(size.area() as usize, pixels.len() / 4);
let area = rect.size.area() as usize;
let first_column_start = rect.origin.x as usize * 4;
let row_length = size.width as usize * 4;
let first_row_start = rect.origin.y as usize * row_length;
if rect.origin.x == 0 && rect.size.width == size.width || rect.size.height == 1 {
let start = first_column_start + first_row_start;
return Cow::Borrowed(&pixels[start..start + area * 4]);
}
let mut data = Vec::with_capacity(area * 4);
for row in pixels[first_row_start..]
.chunks(row_length)
.take(rect.size.height as usize)
{
data.extend_from_slice(&row[first_column_start..][..rect.size.width as usize * 4]);
}
data.into()
}
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
pub fn rgba8_byte_swap_colors_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = rgba[2];
rgba[2] = b;
}
}
pub fn rgba8_byte_swap_and_premultiply_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = multiply_u8_color(rgba[2], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(b, rgba[3]);
}
}
/// Returns true if the pixels were found to be completely opaque.
pub fn rgba8_premultiply_inplace(pixels: &mut [u8]) -> bool {
assert!(pixels.len() % 4 == 0);
let mut is_opaque = true;
for rgba in pixels.chunks_mut(4) {
rgba[0] = multiply_u8_color(rgba[0], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(rgba[2], rgba[3]);
is_opaque = is_opaque && rgba[3] == 255;
}
is_opaque
}
pub fn multiply_u8_color(a: u8, b: u8) -> u8 {
return (a as u32 * b as u32 / 255) as u8;
}
pub fn clip(
mut origin: Point2D<i32>,
mut size: Size2D<u32>,
surface: Size2D<u32>,
) -> Option<Rect<u32>> {
if origin.x < 0 {
size.width = size.width.saturating_sub(-origin.x as u32);
origin.x = 0;
}
if origin.y < 0 {
size.height = size.height.saturating_sub(-origin.y as u32);
origin.y = 0;
}
Rect::new(origin.to_u32(), size)
.intersection(&Rect::from_size(surface))
.filter(|rect|!rect.is_empty())
} | random_line_split |
|
lib.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/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::MallocSizeOf;
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum PixelFormat {
/// Luminance channel only
K8,
/// Luminance + alpha
KA8,
/// RGB, 8 bits per channel
RGB8,
/// RGB + alpha, 8 bits per channel
RGBA8,
/// BGR + alpha, 8 bits per channel
BGRA8,
}
pub fn rgba8_get_rect(pixels: &[u8], size: Size2D<u32>, rect: Rect<u32>) -> Cow<[u8]> {
assert!(!rect.is_empty());
assert!(Rect::from_size(size).contains_rect(&rect));
assert_eq!(pixels.len() % 4, 0);
assert_eq!(size.area() as usize, pixels.len() / 4);
let area = rect.size.area() as usize;
let first_column_start = rect.origin.x as usize * 4;
let row_length = size.width as usize * 4;
let first_row_start = rect.origin.y as usize * row_length;
if rect.origin.x == 0 && rect.size.width == size.width || rect.size.height == 1 {
let start = first_column_start + first_row_start;
return Cow::Borrowed(&pixels[start..start + area * 4]);
}
let mut data = Vec::with_capacity(area * 4);
for row in pixels[first_row_start..]
.chunks(row_length)
.take(rect.size.height as usize)
{
data.extend_from_slice(&row[first_column_start..][..rect.size.width as usize * 4]);
}
data.into()
}
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
pub fn rgba8_byte_swap_colors_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = rgba[2];
rgba[2] = b;
}
}
pub fn rgba8_byte_swap_and_premultiply_inplace(pixels: &mut [u8]) {
assert!(pixels.len() % 4 == 0);
for rgba in pixels.chunks_mut(4) {
let b = rgba[0];
rgba[0] = multiply_u8_color(rgba[2], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(b, rgba[3]);
}
}
/// Returns true if the pixels were found to be completely opaque.
pub fn rgba8_premultiply_inplace(pixels: &mut [u8]) -> bool {
assert!(pixels.len() % 4 == 0);
let mut is_opaque = true;
for rgba in pixels.chunks_mut(4) {
rgba[0] = multiply_u8_color(rgba[0], rgba[3]);
rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
rgba[2] = multiply_u8_color(rgba[2], rgba[3]);
is_opaque = is_opaque && rgba[3] == 255;
}
is_opaque
}
pub fn multiply_u8_color(a: u8, b: u8) -> u8 {
return (a as u32 * b as u32 / 255) as u8;
}
pub fn clip(
mut origin: Point2D<i32>,
mut size: Size2D<u32>,
surface: Size2D<u32>,
) -> Option<Rect<u32>> | {
if origin.x < 0 {
size.width = size.width.saturating_sub(-origin.x as u32);
origin.x = 0;
}
if origin.y < 0 {
size.height = size.height.saturating_sub(-origin.y as u32);
origin.y = 0;
}
Rect::new(origin.to_u32(), size)
.intersection(&Rect::from_size(surface))
.filter(|rect| !rect.is_empty())
} | identifier_body |
|
vrstageparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStageParametersBinding;
use dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods;
use dom::bindings::num::Finite;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject};
use js::typedarray::{Float32Array, CreateWith};
use std::ptr;
use webvr_traits::WebVRStageParameters;
#[dom_struct]
pub struct VRStageParameters {
reflector_: Reflector,
#[ignore_heap_size_of = "Defined in rust-webvr"]
parameters: DomRefCell<WebVRStageParameters>,
transform: Heap<*mut JSObject>,
}
unsafe_no_jsmanaged_fields!(WebVRStageParameters);
impl VRStageParameters {
fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters {
VRStageParameters {
reflector_: Reflector::new(),
parameters: DomRefCell::new(parameters),
transform: Heap::default()
}
}
#[allow(unsafe_code)]
pub fn new(parameters: WebVRStageParameters, global: &GlobalScope) -> DomRoot<VRStageParameters> {
let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut());
unsafe {
let _ = Float32Array::create(cx, CreateWith::Slice(¶meters.sitting_to_standing_transform),
array.handle_mut());
}
let stage_parameters = reflect_dom_object(box VRStageParameters::new_inherited(parameters),
global,
VRStageParametersBinding::Wrap);
stage_parameters.transform.set(array.get());
stage_parameters
}
#[allow(unsafe_code)]
pub fn update(&self, parameters: &WebVRStageParameters) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array {
array.update(¶meters.sitting_to_standing_transform);
}
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new_unchecked(self.transform.get())
}
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizex
fn SizeX(&self) -> Finite<f32> |
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizez
fn SizeZ(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_z)
}
}
| {
Finite::wrap(self.parameters.borrow().size_x)
} | identifier_body |
vrstageparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStageParametersBinding;
use dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods;
use dom::bindings::num::Finite;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject};
use js::typedarray::{Float32Array, CreateWith};
use std::ptr;
use webvr_traits::WebVRStageParameters;
#[dom_struct]
pub struct VRStageParameters {
reflector_: Reflector,
#[ignore_heap_size_of = "Defined in rust-webvr"]
parameters: DomRefCell<WebVRStageParameters>,
transform: Heap<*mut JSObject>,
}
unsafe_no_jsmanaged_fields!(WebVRStageParameters);
impl VRStageParameters {
fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters {
VRStageParameters {
reflector_: Reflector::new(),
parameters: DomRefCell::new(parameters),
transform: Heap::default()
}
}
#[allow(unsafe_code)]
pub fn new(parameters: WebVRStageParameters, global: &GlobalScope) -> DomRoot<VRStageParameters> {
let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut());
unsafe {
let _ = Float32Array::create(cx, CreateWith::Slice(¶meters.sitting_to_standing_transform),
array.handle_mut());
}
let stage_parameters = reflect_dom_object(box VRStageParameters::new_inherited(parameters),
global,
VRStageParametersBinding::Wrap);
stage_parameters.transform.set(array.get());
stage_parameters
}
#[allow(unsafe_code)]
pub fn update(&self, parameters: &WebVRStageParameters) {
unsafe { | if let Ok(mut array) = array {
array.update(¶meters.sitting_to_standing_transform);
}
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new_unchecked(self.transform.get())
}
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizex
fn SizeX(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_x)
}
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizez
fn SizeZ(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_z)
}
} | let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get()); | random_line_split |
vrstageparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStageParametersBinding;
use dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods;
use dom::bindings::num::Finite;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject};
use js::typedarray::{Float32Array, CreateWith};
use std::ptr;
use webvr_traits::WebVRStageParameters;
#[dom_struct]
pub struct VRStageParameters {
reflector_: Reflector,
#[ignore_heap_size_of = "Defined in rust-webvr"]
parameters: DomRefCell<WebVRStageParameters>,
transform: Heap<*mut JSObject>,
}
unsafe_no_jsmanaged_fields!(WebVRStageParameters);
impl VRStageParameters {
fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters {
VRStageParameters {
reflector_: Reflector::new(),
parameters: DomRefCell::new(parameters),
transform: Heap::default()
}
}
#[allow(unsafe_code)]
pub fn new(parameters: WebVRStageParameters, global: &GlobalScope) -> DomRoot<VRStageParameters> {
let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut());
unsafe {
let _ = Float32Array::create(cx, CreateWith::Slice(¶meters.sitting_to_standing_transform),
array.handle_mut());
}
let stage_parameters = reflect_dom_object(box VRStageParameters::new_inherited(parameters),
global,
VRStageParametersBinding::Wrap);
stage_parameters.transform.set(array.get());
stage_parameters
}
#[allow(unsafe_code)]
pub fn update(&self, parameters: &WebVRStageParameters) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array |
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new_unchecked(self.transform.get())
}
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizex
fn SizeX(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_x)
}
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizez
fn SizeZ(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_z)
}
}
| {
array.update(¶meters.sitting_to_standing_transform);
} | conditional_block |
vrstageparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStageParametersBinding;
use dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods;
use dom::bindings::num::Finite;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject};
use js::typedarray::{Float32Array, CreateWith};
use std::ptr;
use webvr_traits::WebVRStageParameters;
#[dom_struct]
pub struct | {
reflector_: Reflector,
#[ignore_heap_size_of = "Defined in rust-webvr"]
parameters: DomRefCell<WebVRStageParameters>,
transform: Heap<*mut JSObject>,
}
unsafe_no_jsmanaged_fields!(WebVRStageParameters);
impl VRStageParameters {
fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters {
VRStageParameters {
reflector_: Reflector::new(),
parameters: DomRefCell::new(parameters),
transform: Heap::default()
}
}
#[allow(unsafe_code)]
pub fn new(parameters: WebVRStageParameters, global: &GlobalScope) -> DomRoot<VRStageParameters> {
let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut());
unsafe {
let _ = Float32Array::create(cx, CreateWith::Slice(¶meters.sitting_to_standing_transform),
array.handle_mut());
}
let stage_parameters = reflect_dom_object(box VRStageParameters::new_inherited(parameters),
global,
VRStageParametersBinding::Wrap);
stage_parameters.transform.set(array.get());
stage_parameters
}
#[allow(unsafe_code)]
pub fn update(&self, parameters: &WebVRStageParameters) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array {
array.update(¶meters.sitting_to_standing_transform);
}
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new_unchecked(self.transform.get())
}
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizex
fn SizeX(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_x)
}
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizez
fn SizeZ(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_z)
}
}
| VRStageParameters | identifier_name |
standard.rs |
use super::super::*;
pub const TRANSPARENT: u8 = 0;
pub const PINKISH_TAN: u8 = 1;
pub const ORANGEY_RED: u8 = 2;
pub const ROUGE: u8 = 3;
pub const STRONG_PINK: u8 = 4;
pub const BUBBLEGUM_PINK: u8 = 5;
pub const PINK_PURPLE: u8 = 6;
pub const WARM_PURPLE: u8 = 7;
pub const BURGUNDY: u8 = 8;
pub const NAVY_BLUE: u8 = 9;
pub const BLUE_PURPLE: u8 = 10;
pub const MEDIUM_BLUE: u8 = 11;
pub const AZURE: u8 = 12;
pub const ROBINS_EGG: u8 = 13;
pub const BLUE_GREEN: u8 = 14;
pub const DARK_AQUA: u8 = 15;
pub const DARK_FOREST_GREEN: u8 = 16;
pub const BLACK: u8 = 17;
pub const CHARCOAL_GREY: u8 = 18;
pub const GREYISH_PURPLE: u8 = 19;
pub const LIGHT_PERIWINKLE: u8 = 20;
pub const WHITE: u8 = 21;
pub const GREENISH_GREY: u8 = 22;
pub const MEDIUM_GREY: u8 = 23;
pub const BROWN: u8 = 24;
pub const UMBER: u8 = 25;
pub const YELLOWISH_ORANGE: u8 = 26;
pub const YELLOWISH: u8 = 27;
pub const PEA_SOUP: u8 = 28;
pub const MUD_GREEN: u8 = 29;
pub const KELLEY_GREEN: u8 = 30;
pub const TOXIC_GREEN: u8 = 31;
pub const BRIGHT_TEAL: u8 = 32;
pub fn create_palette() -> Palette {
Palette {
colors: vec![
Color { rgba: 0x00000000 },
Color { rgba: 0xff90a0d6 },
Color { rgba: 0xff1e3bfe },
Color { rgba: 0xff322ca1 },
Color { rgba: 0xff7a2ffa },
Color { rgba: 0xffda9ffb },
Color { rgba: 0xfff71ce6 },
Color { rgba: 0xff7c2f99 },
Color { rgba: 0xff1f0147 },
Color { rgba: 0xff551105 },
Color { rgba: 0xffec024f },
Color { rgba: 0xffcb692d },
Color { rgba: 0xffeea600 },
Color { rgba: 0xffffeb6f },
Color { rgba: 0xff9aa208 },
Color { rgba: 0xff6a662a },
Color { rgba: 0xff193606 },
Color { rgba: 0xff000000 },
Color { rgba: 0xff57494a },
Color { rgba: 0xffa47b8e },
Color { rgba: 0xffffc0b7 },
Color { rgba: 0xffffffff },
Color { rgba: 0xff9cbeac },
Color { rgba: 0xff707c82 },
Color { rgba: 0xff1c3b5a },
Color { rgba: 0xff0765ae },
Color { rgba: 0xff30aaf7 },
Color { rgba: 0xff5ceaf4 },
Color { rgba: 0xff00959b },
Color { rgba: 0xff046256 },
Color { rgba: 0xff3b9611 },
Color { rgba: 0xff13e151 },
Color { rgba: 0xffccfd08 },
],
}
}
pub fn | () -> Vec<String> {
vec![
String::from("Transparent"),
String::from("Pinkish Tan"),
String::from("Orangey Red"),
String::from("Rouge"),
String::from("Strong Pink"),
String::from("Bubblegum Pink"),
String::from("Pink/Purple"),
String::from("Warm Purple"),
String::from("Burgundy"),
String::from("Navy Blue"),
String::from("Blue/Purple"),
String::from("Medium Blue"),
String::from("Azure"),
String::from("Robin’s Egg"),
String::from("Blue/Green"),
String::from("Dark Aqua"),
String::from("Dark Forest Green"),
String::from("Black"),
String::from("Charcoal Grey"),
String::from("Greyish Purple"),
String::from("Light Periwinkle"),
String::from("White"),
String::from("Greenish Grey"),
String::from("Medium Grey"),
String::from("Brown"),
String::from("Umber"),
String::from("Yellowish Orange"),
String::from("Yellowish"),
String::from("Pea Soup"),
String::from("Mud Green"),
String::from("Kelley Green"),
String::from("Toxic Green"),
String::from("Bright Teal"),
]
}
| names | identifier_name |
standard.rs | use super::super::*;
pub const TRANSPARENT: u8 = 0;
pub const PINKISH_TAN: u8 = 1;
pub const ORANGEY_RED: u8 = 2;
pub const ROUGE: u8 = 3;
pub const STRONG_PINK: u8 = 4;
pub const BUBBLEGUM_PINK: u8 = 5;
pub const PINK_PURPLE: u8 = 6;
pub const WARM_PURPLE: u8 = 7;
pub const BURGUNDY: u8 = 8;
pub const NAVY_BLUE: u8 = 9;
pub const BLUE_PURPLE: u8 = 10;
pub const MEDIUM_BLUE: u8 = 11;
pub const AZURE: u8 = 12;
pub const ROBINS_EGG: u8 = 13;
pub const BLUE_GREEN: u8 = 14;
pub const DARK_AQUA: u8 = 15;
pub const DARK_FOREST_GREEN: u8 = 16;
pub const BLACK: u8 = 17;
pub const CHARCOAL_GREY: u8 = 18;
pub const GREYISH_PURPLE: u8 = 19;
pub const LIGHT_PERIWINKLE: u8 = 20;
pub const WHITE: u8 = 21;
pub const GREENISH_GREY: u8 = 22;
pub const MEDIUM_GREY: u8 = 23;
pub const BROWN: u8 = 24;
pub const UMBER: u8 = 25;
pub const YELLOWISH_ORANGE: u8 = 26;
pub const YELLOWISH: u8 = 27;
pub const PEA_SOUP: u8 = 28;
pub const MUD_GREEN: u8 = 29;
pub const KELLEY_GREEN: u8 = 30;
pub const TOXIC_GREEN: u8 = 31;
pub const BRIGHT_TEAL: u8 = 32;
pub fn create_palette() -> Palette {
Palette {
colors: vec![
Color { rgba: 0x00000000 },
Color { rgba: 0xff90a0d6 },
Color { rgba: 0xff1e3bfe },
Color { rgba: 0xff322ca1 },
Color { rgba: 0xff7a2ffa },
Color { rgba: 0xffda9ffb },
Color { rgba: 0xfff71ce6 },
Color { rgba: 0xff7c2f99 },
Color { rgba: 0xff1f0147 },
Color { rgba: 0xff551105 },
Color { rgba: 0xffec024f },
Color { rgba: 0xffcb692d },
Color { rgba: 0xffeea600 },
Color { rgba: 0xffffeb6f },
Color { rgba: 0xff9aa208 },
Color { rgba: 0xff6a662a },
Color { rgba: 0xff193606 },
Color { rgba: 0xff000000 },
Color { rgba: 0xff57494a },
Color { rgba: 0xffa47b8e },
Color { rgba: 0xffffc0b7 },
Color { rgba: 0xffffffff },
Color { rgba: 0xff9cbeac },
Color { rgba: 0xff707c82 },
Color { rgba: 0xff1c3b5a },
Color { rgba: 0xff0765ae },
Color { rgba: 0xff30aaf7 },
Color { rgba: 0xff5ceaf4 },
Color { rgba: 0xff00959b },
Color { rgba: 0xff046256 },
Color { rgba: 0xff3b9611 },
Color { rgba: 0xff13e151 },
Color { rgba: 0xffccfd08 },
],
}
}
pub fn names() -> Vec<String> {
vec![
String::from("Transparent"),
String::from("Pinkish Tan"),
String::from("Orangey Red"),
String::from("Rouge"),
String::from("Strong Pink"),
String::from("Bubblegum Pink"),
String::from("Pink/Purple"), | String::from("Navy Blue"),
String::from("Blue/Purple"),
String::from("Medium Blue"),
String::from("Azure"),
String::from("Robin’s Egg"),
String::from("Blue/Green"),
String::from("Dark Aqua"),
String::from("Dark Forest Green"),
String::from("Black"),
String::from("Charcoal Grey"),
String::from("Greyish Purple"),
String::from("Light Periwinkle"),
String::from("White"),
String::from("Greenish Grey"),
String::from("Medium Grey"),
String::from("Brown"),
String::from("Umber"),
String::from("Yellowish Orange"),
String::from("Yellowish"),
String::from("Pea Soup"),
String::from("Mud Green"),
String::from("Kelley Green"),
String::from("Toxic Green"),
String::from("Bright Teal"),
]
} | String::from("Warm Purple"),
String::from("Burgundy"), | random_line_split |
standard.rs |
use super::super::*;
pub const TRANSPARENT: u8 = 0;
pub const PINKISH_TAN: u8 = 1;
pub const ORANGEY_RED: u8 = 2;
pub const ROUGE: u8 = 3;
pub const STRONG_PINK: u8 = 4;
pub const BUBBLEGUM_PINK: u8 = 5;
pub const PINK_PURPLE: u8 = 6;
pub const WARM_PURPLE: u8 = 7;
pub const BURGUNDY: u8 = 8;
pub const NAVY_BLUE: u8 = 9;
pub const BLUE_PURPLE: u8 = 10;
pub const MEDIUM_BLUE: u8 = 11;
pub const AZURE: u8 = 12;
pub const ROBINS_EGG: u8 = 13;
pub const BLUE_GREEN: u8 = 14;
pub const DARK_AQUA: u8 = 15;
pub const DARK_FOREST_GREEN: u8 = 16;
pub const BLACK: u8 = 17;
pub const CHARCOAL_GREY: u8 = 18;
pub const GREYISH_PURPLE: u8 = 19;
pub const LIGHT_PERIWINKLE: u8 = 20;
pub const WHITE: u8 = 21;
pub const GREENISH_GREY: u8 = 22;
pub const MEDIUM_GREY: u8 = 23;
pub const BROWN: u8 = 24;
pub const UMBER: u8 = 25;
pub const YELLOWISH_ORANGE: u8 = 26;
pub const YELLOWISH: u8 = 27;
pub const PEA_SOUP: u8 = 28;
pub const MUD_GREEN: u8 = 29;
pub const KELLEY_GREEN: u8 = 30;
pub const TOXIC_GREEN: u8 = 31;
pub const BRIGHT_TEAL: u8 = 32;
pub fn create_palette() -> Palette | Color { rgba: 0xff000000 },
Color { rgba: 0xff57494a },
Color { rgba: 0xffa47b8e },
Color { rgba: 0xffffc0b7 },
Color { rgba: 0xffffffff },
Color { rgba: 0xff9cbeac },
Color { rgba: 0xff707c82 },
Color { rgba: 0xff1c3b5a },
Color { rgba: 0xff0765ae },
Color { rgba: 0xff30aaf7 },
Color { rgba: 0xff5ceaf4 },
Color { rgba: 0xff00959b },
Color { rgba: 0xff046256 },
Color { rgba: 0xff3b9611 },
Color { rgba: 0xff13e151 },
Color { rgba: 0xffccfd08 },
],
}
}
pub fn names() -> Vec<String> {
vec![
String::from("Transparent"),
String::from("Pinkish Tan"),
String::from("Orangey Red"),
String::from("Rouge"),
String::from("Strong Pink"),
String::from("Bubblegum Pink"),
String::from("Pink/Purple"),
String::from("Warm Purple"),
String::from("Burgundy"),
String::from("Navy Blue"),
String::from("Blue/Purple"),
String::from("Medium Blue"),
String::from("Azure"),
String::from("Robin’s Egg"),
String::from("Blue/Green"),
String::from("Dark Aqua"),
String::from("Dark Forest Green"),
String::from("Black"),
String::from("Charcoal Grey"),
String::from("Greyish Purple"),
String::from("Light Periwinkle"),
String::from("White"),
String::from("Greenish Grey"),
String::from("Medium Grey"),
String::from("Brown"),
String::from("Umber"),
String::from("Yellowish Orange"),
String::from("Yellowish"),
String::from("Pea Soup"),
String::from("Mud Green"),
String::from("Kelley Green"),
String::from("Toxic Green"),
String::from("Bright Teal"),
]
}
| {
Palette {
colors: vec![
Color { rgba: 0x00000000 },
Color { rgba: 0xff90a0d6 },
Color { rgba: 0xff1e3bfe },
Color { rgba: 0xff322ca1 },
Color { rgba: 0xff7a2ffa },
Color { rgba: 0xffda9ffb },
Color { rgba: 0xfff71ce6 },
Color { rgba: 0xff7c2f99 },
Color { rgba: 0xff1f0147 },
Color { rgba: 0xff551105 },
Color { rgba: 0xffec024f },
Color { rgba: 0xffcb692d },
Color { rgba: 0xffeea600 },
Color { rgba: 0xffffeb6f },
Color { rgba: 0xff9aa208 },
Color { rgba: 0xff6a662a },
Color { rgba: 0xff193606 }, | identifier_body |
classes-simple.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.
struct cat {
priv meows : uint,
how_hungry : int,
}
fn cat(in_x : uint, in_y : int) -> cat {
cat {
meows: in_x,
how_hungry: in_y
}
}
pub fn main() {
let mut nyan : cat = cat(52u, 99);
let mut kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
} | // | random_line_split |
classes-simple.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.
struct cat {
priv meows : uint,
how_hungry : int,
}
fn cat(in_x : uint, in_y : int) -> cat |
pub fn main() {
let mut nyan : cat = cat(52u, 99);
let mut kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
}
| {
cat {
meows: in_x,
how_hungry: in_y
}
} | identifier_body |
classes-simple.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.
struct cat {
priv meows : uint,
how_hungry : int,
}
fn cat(in_x : uint, in_y : int) -> cat {
cat {
meows: in_x,
how_hungry: in_y
}
}
pub fn | () {
let mut nyan : cat = cat(52u, 99);
let mut kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
}
| main | identifier_name |
lib.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/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Servo's components
// together as type `Browser`, along with a generic client
// implementing the `WindowMethods` trait, to create a working web
// browser.
//
// The `Browser` type is responsible for configuring a
// `Constellation`, which does the heavy lifting of coordinating all
// of Servo's internal subsystems, including the `ScriptTask` and the
// `LayoutTask`, as well maintains the navigation context.
//
// The `Browser` is fed events from a generic type that implements the
// `WindowMethods` trait.
extern crate gaol;
#[macro_use]
extern crate util as _util;
mod export {
extern crate canvas;
extern crate canvas_traits;
extern crate compositing;
extern crate devtools;
extern crate devtools_traits;
extern crate euclid;
extern crate gfx;
extern crate gleam;
extern crate ipc_channel;
extern crate layers;
extern crate layout;
extern crate msg;
extern crate net;
extern crate net_traits;
extern crate profile;
extern crate profile_traits;
extern crate script;
extern crate script_traits;
extern crate style;
extern crate url;
}
extern crate libc;
#[cfg(feature = "webdriver")]
extern crate webdriver_server;
#[cfg(feature = "webdriver")]
fn webdriver(port: u16, constellation: Sender<ConstellationMsg>) {
webdriver_server::start_server(port, constellation);
}
#[cfg(not(feature = "webdriver"))]
fn webdriver(_port: u16, _constellation: Sender<ConstellationMsg>) { }
use compositing::CompositorEventListener;
use compositing::compositor_task::InitialCompositorState;
use compositing::constellation::InitialConstellationState;
use compositing::pipeline::UnprivilegedPipelineContent;
use compositing::sandboxing;
use compositing::windowing::WindowEvent;
use compositing::windowing::WindowMethods;
use compositing::{CompositorProxy, CompositorTask, Constellation};
use gaol::sandbox::{ChildSandbox, ChildSandboxMethods};
use gfx::font_cache_task::FontCacheTask;
use ipc_channel::ipc::{self, IpcSender};
use msg::constellation_msg::CompositorMsg as ConstellationMsg;
use net::image_cache_task::new_image_cache_task;
use net::resource_task::new_resource_task;
use net::storage_task::StorageTaskFactory;
use net_traits::storage_task::StorageTask;
use profile::mem as profile_mem;
use profile::time as profile_time;
use profile_traits::mem;
use profile_traits::time;
use std::borrow::Borrow;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use util::opts;
pub use _util as util;
pub use export::canvas;
pub use export::canvas_traits;
pub use export::compositing;
pub use export::devtools;
pub use export::devtools_traits;
pub use export::euclid;
pub use export::gfx;
pub use export::gleam::gl;
pub use export::ipc_channel;
pub use export::layers;
pub use export::layout;
pub use export::msg;
pub use export::net;
pub use export::net_traits;
pub use export::profile;
pub use export::profile_traits;
pub use export::script;
pub use export::script_traits;
pub use export::style;
pub use export::url;
pub struct | {
compositor: Box<CompositorEventListener +'static>,
}
/// The in-process interface to Servo.
///
/// It does everything necessary to render the web, primarily
/// orchestrating the interaction between JavaScript, CSS layout,
/// rendering, and the client window.
///
/// Clients create a `Browser` for a given reference-counted type
/// implementing `WindowMethods`, which is the bridge to whatever
/// application Servo is embedded in. Clients then create an event
/// loop to pump messages between the embedding application and
/// various browser components.
impl Browser {
pub fn new<Window>(window: Option<Rc<Window>>) -> Browser
where Window: WindowMethods +'static {
// Global configuration options, parsed from the command line.
let opts = opts::get();
script::init();
// Get both endpoints of a special channel for communication between
// the client window and the compositor. This channel is unique because
// messages to client may need to pump a platform-specific event loop
// to deliver the message.
let (compositor_proxy, compositor_receiver) =
WindowMethods::create_compositor_channel(&window);
let supports_clipboard = match window {
Some(ref win_rc) => {
let win: &Window = win_rc.borrow();
win.supports_clipboard()
}
None => false
};
let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period);
let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period);
let devtools_chan = opts.devtools_port.map(|port| {
devtools::start_server(port)
});
// Create the constellation, which maintains the engine
// pipelines, including the script and layout threads, as well
// as the navigation context.
let constellation_chan = create_constellation(opts.clone(),
compositor_proxy.clone_compositor_proxy(),
time_profiler_chan.clone(),
mem_profiler_chan.clone(),
devtools_chan,
supports_clipboard);
if cfg!(feature = "webdriver") {
if let Some(port) = opts.webdriver_port {
webdriver(port, constellation_chan.clone());
}
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = CompositorTask::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
constellation_chan: constellation_chan,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
});
Browser {
compositor: compositor,
}
}
pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool {
self.compositor.handle_events(events)
}
pub fn repaint_synchronously(&mut self) {
self.compositor.repaint_synchronously()
}
pub fn pinch_zoom_level(&self) -> f32 {
self.compositor.pinch_zoom_level()
}
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
}
fn create_constellation(opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>,
supports_clipboard: bool) -> Sender<ConstellationMsg> {
let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone());
let image_cache_task = new_image_cache_task(resource_task.clone());
let font_cache_task = FontCacheTask::new(resource_task.clone());
let storage_task: StorageTask = StorageTaskFactory::new();
let initial_state = InitialConstellationState {
compositor_proxy: compositor_proxy,
devtools_chan: devtools_chan,
image_cache_task: image_cache_task,
font_cache_task: font_cache_task,
resource_task: resource_task,
storage_task: storage_task,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
supports_clipboard: supports_clipboard,
};
let constellation_chan =
Constellation::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>::start(initial_state);
// Send the URL command to the constellation.
match opts.url {
Some(url) => {
constellation_chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap();
},
None => ()
};
constellation_chan
}
/// Content process entry point.
pub fn run_content_process(token: String) {
let (unprivileged_content_sender, unprivileged_content_receiver) =
ipc::channel::<UnprivilegedPipelineContent>().unwrap();
let connection_bootstrap: IpcSender<IpcSender<UnprivilegedPipelineContent>> =
IpcSender::connect(token).unwrap();
connection_bootstrap.send(unprivileged_content_sender).unwrap();
let unprivileged_content = unprivileged_content_receiver.recv().unwrap();
opts::set_defaults(unprivileged_content.opts());
// Enter the sandbox if necessary.
if opts::get().sandbox {
ChildSandbox::new(sandboxing::content_process_sandbox_profile()).activate().unwrap();
}
script::init();
unprivileged_content.start_all::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>(true);
}
| Browser | identifier_name |
lib.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/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Servo's components
// together as type `Browser`, along with a generic client
// implementing the `WindowMethods` trait, to create a working web
// browser.
//
// The `Browser` type is responsible for configuring a
// `Constellation`, which does the heavy lifting of coordinating all
// of Servo's internal subsystems, including the `ScriptTask` and the
// `LayoutTask`, as well maintains the navigation context.
//
// The `Browser` is fed events from a generic type that implements the
// `WindowMethods` trait.
extern crate gaol;
#[macro_use]
extern crate util as _util;
mod export {
extern crate canvas;
extern crate canvas_traits;
extern crate compositing;
extern crate devtools;
extern crate devtools_traits;
extern crate euclid;
extern crate gfx;
extern crate gleam;
extern crate ipc_channel;
extern crate layers;
extern crate layout;
extern crate msg;
extern crate net;
extern crate net_traits;
extern crate profile;
extern crate profile_traits;
extern crate script;
extern crate script_traits;
extern crate style;
extern crate url;
}
extern crate libc;
#[cfg(feature = "webdriver")]
extern crate webdriver_server;
#[cfg(feature = "webdriver")]
fn webdriver(port: u16, constellation: Sender<ConstellationMsg>) {
webdriver_server::start_server(port, constellation);
}
#[cfg(not(feature = "webdriver"))]
fn webdriver(_port: u16, _constellation: Sender<ConstellationMsg>) { }
use compositing::CompositorEventListener;
use compositing::compositor_task::InitialCompositorState;
use compositing::constellation::InitialConstellationState;
use compositing::pipeline::UnprivilegedPipelineContent;
use compositing::sandboxing;
use compositing::windowing::WindowEvent;
use compositing::windowing::WindowMethods;
use compositing::{CompositorProxy, CompositorTask, Constellation};
use gaol::sandbox::{ChildSandbox, ChildSandboxMethods};
use gfx::font_cache_task::FontCacheTask;
use ipc_channel::ipc::{self, IpcSender};
use msg::constellation_msg::CompositorMsg as ConstellationMsg;
use net::image_cache_task::new_image_cache_task;
use net::resource_task::new_resource_task;
use net::storage_task::StorageTaskFactory;
use net_traits::storage_task::StorageTask;
use profile::mem as profile_mem;
use profile::time as profile_time;
use profile_traits::mem;
use profile_traits::time;
use std::borrow::Borrow;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use util::opts;
pub use _util as util;
pub use export::canvas;
pub use export::canvas_traits;
pub use export::compositing;
pub use export::devtools;
pub use export::devtools_traits;
pub use export::euclid;
pub use export::gfx;
pub use export::gleam::gl;
pub use export::ipc_channel;
pub use export::layers;
pub use export::layout;
pub use export::msg;
pub use export::net;
pub use export::net_traits;
pub use export::profile;
pub use export::profile_traits;
pub use export::script;
pub use export::script_traits;
pub use export::style;
pub use export::url;
pub struct Browser {
compositor: Box<CompositorEventListener +'static>,
}
/// The in-process interface to Servo.
///
/// It does everything necessary to render the web, primarily
/// orchestrating the interaction between JavaScript, CSS layout,
/// rendering, and the client window.
///
/// Clients create a `Browser` for a given reference-counted type
/// implementing `WindowMethods`, which is the bridge to whatever
/// application Servo is embedded in. Clients then create an event
/// loop to pump messages between the embedding application and
/// various browser components.
impl Browser {
pub fn new<Window>(window: Option<Rc<Window>>) -> Browser
where Window: WindowMethods +'static {
// Global configuration options, parsed from the command line.
let opts = opts::get();
script::init();
// Get both endpoints of a special channel for communication between
// the client window and the compositor. This channel is unique because
// messages to client may need to pump a platform-specific event loop
// to deliver the message.
let (compositor_proxy, compositor_receiver) =
WindowMethods::create_compositor_channel(&window);
let supports_clipboard = match window {
Some(ref win_rc) => {
let win: &Window = win_rc.borrow();
win.supports_clipboard()
}
None => false
};
let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period);
let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period);
let devtools_chan = opts.devtools_port.map(|port| {
devtools::start_server(port)
});
// Create the constellation, which maintains the engine
// pipelines, including the script and layout threads, as well
// as the navigation context.
let constellation_chan = create_constellation(opts.clone(),
compositor_proxy.clone_compositor_proxy(),
time_profiler_chan.clone(),
mem_profiler_chan.clone(),
devtools_chan,
supports_clipboard);
if cfg!(feature = "webdriver") {
if let Some(port) = opts.webdriver_port {
webdriver(port, constellation_chan.clone());
}
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = CompositorTask::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
constellation_chan: constellation_chan,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
});
Browser {
compositor: compositor,
}
}
pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool {
self.compositor.handle_events(events)
}
pub fn repaint_synchronously(&mut self) |
pub fn pinch_zoom_level(&self) -> f32 {
self.compositor.pinch_zoom_level()
}
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
}
fn create_constellation(opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>,
supports_clipboard: bool) -> Sender<ConstellationMsg> {
let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone());
let image_cache_task = new_image_cache_task(resource_task.clone());
let font_cache_task = FontCacheTask::new(resource_task.clone());
let storage_task: StorageTask = StorageTaskFactory::new();
let initial_state = InitialConstellationState {
compositor_proxy: compositor_proxy,
devtools_chan: devtools_chan,
image_cache_task: image_cache_task,
font_cache_task: font_cache_task,
resource_task: resource_task,
storage_task: storage_task,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
supports_clipboard: supports_clipboard,
};
let constellation_chan =
Constellation::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>::start(initial_state);
// Send the URL command to the constellation.
match opts.url {
Some(url) => {
constellation_chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap();
},
None => ()
};
constellation_chan
}
/// Content process entry point.
pub fn run_content_process(token: String) {
let (unprivileged_content_sender, unprivileged_content_receiver) =
ipc::channel::<UnprivilegedPipelineContent>().unwrap();
let connection_bootstrap: IpcSender<IpcSender<UnprivilegedPipelineContent>> =
IpcSender::connect(token).unwrap();
connection_bootstrap.send(unprivileged_content_sender).unwrap();
let unprivileged_content = unprivileged_content_receiver.recv().unwrap();
opts::set_defaults(unprivileged_content.opts());
// Enter the sandbox if necessary.
if opts::get().sandbox {
ChildSandbox::new(sandboxing::content_process_sandbox_profile()).activate().unwrap();
}
script::init();
unprivileged_content.start_all::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>(true);
}
| {
self.compositor.repaint_synchronously()
} | identifier_body |
lib.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/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Servo's components
// together as type `Browser`, along with a generic client
// implementing the `WindowMethods` trait, to create a working web
// browser.
//
// The `Browser` type is responsible for configuring a
// `Constellation`, which does the heavy lifting of coordinating all
// of Servo's internal subsystems, including the `ScriptTask` and the
// `LayoutTask`, as well maintains the navigation context.
//
// The `Browser` is fed events from a generic type that implements the
// `WindowMethods` trait.
extern crate gaol;
#[macro_use]
extern crate util as _util;
mod export {
extern crate canvas;
extern crate canvas_traits;
extern crate compositing;
extern crate devtools;
extern crate devtools_traits;
extern crate euclid;
extern crate gfx;
extern crate gleam;
extern crate ipc_channel;
extern crate layers;
extern crate layout;
extern crate msg;
extern crate net;
extern crate net_traits;
extern crate profile;
extern crate profile_traits;
extern crate script;
extern crate script_traits;
extern crate style;
extern crate url;
}
extern crate libc;
#[cfg(feature = "webdriver")]
extern crate webdriver_server;
#[cfg(feature = "webdriver")]
fn webdriver(port: u16, constellation: Sender<ConstellationMsg>) {
webdriver_server::start_server(port, constellation);
}
#[cfg(not(feature = "webdriver"))]
fn webdriver(_port: u16, _constellation: Sender<ConstellationMsg>) { }
use compositing::CompositorEventListener;
use compositing::compositor_task::InitialCompositorState;
use compositing::constellation::InitialConstellationState;
use compositing::pipeline::UnprivilegedPipelineContent;
use compositing::sandboxing;
use compositing::windowing::WindowEvent;
use compositing::windowing::WindowMethods;
use compositing::{CompositorProxy, CompositorTask, Constellation};
use gaol::sandbox::{ChildSandbox, ChildSandboxMethods};
use gfx::font_cache_task::FontCacheTask;
use ipc_channel::ipc::{self, IpcSender};
use msg::constellation_msg::CompositorMsg as ConstellationMsg;
use net::image_cache_task::new_image_cache_task;
use net::resource_task::new_resource_task;
use net::storage_task::StorageTaskFactory;
use net_traits::storage_task::StorageTask;
use profile::mem as profile_mem;
use profile::time as profile_time;
use profile_traits::mem;
use profile_traits::time;
use std::borrow::Borrow;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use util::opts;
pub use _util as util;
pub use export::canvas;
pub use export::canvas_traits;
pub use export::compositing;
pub use export::devtools;
pub use export::devtools_traits;
pub use export::euclid;
pub use export::gfx;
pub use export::gleam::gl;
pub use export::ipc_channel;
pub use export::layers;
pub use export::layout;
pub use export::msg;
pub use export::net;
pub use export::net_traits;
pub use export::profile;
pub use export::profile_traits;
pub use export::script;
pub use export::script_traits;
pub use export::style;
pub use export::url;
pub struct Browser {
compositor: Box<CompositorEventListener +'static>,
}
/// The in-process interface to Servo.
///
/// It does everything necessary to render the web, primarily
/// orchestrating the interaction between JavaScript, CSS layout,
/// rendering, and the client window.
///
/// Clients create a `Browser` for a given reference-counted type
/// implementing `WindowMethods`, which is the bridge to whatever
/// application Servo is embedded in. Clients then create an event
/// loop to pump messages between the embedding application and
/// various browser components.
impl Browser {
pub fn new<Window>(window: Option<Rc<Window>>) -> Browser
where Window: WindowMethods +'static {
// Global configuration options, parsed from the command line.
let opts = opts::get();
script::init();
// Get both endpoints of a special channel for communication between
// the client window and the compositor. This channel is unique because
// messages to client may need to pump a platform-specific event loop
// to deliver the message.
let (compositor_proxy, compositor_receiver) =
WindowMethods::create_compositor_channel(&window);
let supports_clipboard = match window {
Some(ref win_rc) => {
let win: &Window = win_rc.borrow();
win.supports_clipboard()
}
None => false
};
let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period);
let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period);
let devtools_chan = opts.devtools_port.map(|port| {
devtools::start_server(port)
});
// Create the constellation, which maintains the engine
// pipelines, including the script and layout threads, as well
// as the navigation context.
let constellation_chan = create_constellation(opts.clone(),
compositor_proxy.clone_compositor_proxy(),
time_profiler_chan.clone(),
mem_profiler_chan.clone(),
devtools_chan,
supports_clipboard);
if cfg!(feature = "webdriver") {
if let Some(port) = opts.webdriver_port {
webdriver(port, constellation_chan.clone());
}
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = CompositorTask::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
constellation_chan: constellation_chan,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
});
Browser {
compositor: compositor,
}
}
pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool {
self.compositor.handle_events(events)
}
pub fn repaint_synchronously(&mut self) {
self.compositor.repaint_synchronously()
}
pub fn pinch_zoom_level(&self) -> f32 {
self.compositor.pinch_zoom_level()
}
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
}
fn create_constellation(opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>,
supports_clipboard: bool) -> Sender<ConstellationMsg> {
let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone());
let image_cache_task = new_image_cache_task(resource_task.clone());
let font_cache_task = FontCacheTask::new(resource_task.clone());
let storage_task: StorageTask = StorageTaskFactory::new();
let initial_state = InitialConstellationState {
compositor_proxy: compositor_proxy,
devtools_chan: devtools_chan,
image_cache_task: image_cache_task,
font_cache_task: font_cache_task,
resource_task: resource_task,
storage_task: storage_task,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
supports_clipboard: supports_clipboard,
};
let constellation_chan =
Constellation::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>::start(initial_state);
// Send the URL command to the constellation.
match opts.url {
Some(url) => | ,
None => ()
};
constellation_chan
}
/// Content process entry point.
pub fn run_content_process(token: String) {
let (unprivileged_content_sender, unprivileged_content_receiver) =
ipc::channel::<UnprivilegedPipelineContent>().unwrap();
let connection_bootstrap: IpcSender<IpcSender<UnprivilegedPipelineContent>> =
IpcSender::connect(token).unwrap();
connection_bootstrap.send(unprivileged_content_sender).unwrap();
let unprivileged_content = unprivileged_content_receiver.recv().unwrap();
opts::set_defaults(unprivileged_content.opts());
// Enter the sandbox if necessary.
if opts::get().sandbox {
ChildSandbox::new(sandboxing::content_process_sandbox_profile()).activate().unwrap();
}
script::init();
unprivileged_content.start_all::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>(true);
}
| {
constellation_chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap();
} | conditional_block |
lib.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/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Servo's components
// together as type `Browser`, along with a generic client
// implementing the `WindowMethods` trait, to create a working web
// browser.
//
// The `Browser` type is responsible for configuring a
// `Constellation`, which does the heavy lifting of coordinating all
// of Servo's internal subsystems, including the `ScriptTask` and the
// `LayoutTask`, as well maintains the navigation context.
//
// The `Browser` is fed events from a generic type that implements the
// `WindowMethods` trait.
extern crate gaol;
#[macro_use]
extern crate util as _util;
mod export {
extern crate canvas;
extern crate canvas_traits;
extern crate compositing;
extern crate devtools;
extern crate devtools_traits;
extern crate euclid;
extern crate gfx;
extern crate gleam;
extern crate ipc_channel;
extern crate layers;
extern crate layout;
extern crate msg;
extern crate net;
extern crate net_traits;
extern crate profile;
extern crate profile_traits;
extern crate script;
extern crate script_traits;
extern crate style;
extern crate url;
}
extern crate libc;
#[cfg(feature = "webdriver")]
extern crate webdriver_server;
#[cfg(feature = "webdriver")]
fn webdriver(port: u16, constellation: Sender<ConstellationMsg>) {
webdriver_server::start_server(port, constellation);
}
#[cfg(not(feature = "webdriver"))]
fn webdriver(_port: u16, _constellation: Sender<ConstellationMsg>) { }
use compositing::CompositorEventListener;
use compositing::compositor_task::InitialCompositorState;
use compositing::constellation::InitialConstellationState;
use compositing::pipeline::UnprivilegedPipelineContent;
use compositing::sandboxing;
use compositing::windowing::WindowEvent;
use compositing::windowing::WindowMethods;
use compositing::{CompositorProxy, CompositorTask, Constellation};
use gaol::sandbox::{ChildSandbox, ChildSandboxMethods};
use gfx::font_cache_task::FontCacheTask;
use ipc_channel::ipc::{self, IpcSender};
use msg::constellation_msg::CompositorMsg as ConstellationMsg;
use net::image_cache_task::new_image_cache_task;
use net::resource_task::new_resource_task;
use net::storage_task::StorageTaskFactory;
use net_traits::storage_task::StorageTask;
use profile::mem as profile_mem;
use profile::time as profile_time;
use profile_traits::mem;
use profile_traits::time;
use std::borrow::Borrow;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use util::opts;
pub use _util as util;
pub use export::canvas;
pub use export::canvas_traits;
pub use export::compositing;
pub use export::devtools;
pub use export::devtools_traits;
pub use export::euclid;
pub use export::gfx;
pub use export::gleam::gl;
pub use export::ipc_channel;
pub use export::layers;
pub use export::layout;
pub use export::msg;
pub use export::net;
pub use export::net_traits;
pub use export::profile;
pub use export::profile_traits;
pub use export::script;
pub use export::script_traits;
pub use export::style;
pub use export::url;
pub struct Browser {
compositor: Box<CompositorEventListener +'static>,
}
/// The in-process interface to Servo.
///
/// It does everything necessary to render the web, primarily
/// orchestrating the interaction between JavaScript, CSS layout,
/// rendering, and the client window.
///
/// Clients create a `Browser` for a given reference-counted type
/// implementing `WindowMethods`, which is the bridge to whatever
/// application Servo is embedded in. Clients then create an event
/// loop to pump messages between the embedding application and
/// various browser components.
impl Browser {
pub fn new<Window>(window: Option<Rc<Window>>) -> Browser
where Window: WindowMethods +'static {
// Global configuration options, parsed from the command line.
let opts = opts::get();
script::init();
// Get both endpoints of a special channel for communication between
// the client window and the compositor. This channel is unique because
// messages to client may need to pump a platform-specific event loop
// to deliver the message.
let (compositor_proxy, compositor_receiver) =
WindowMethods::create_compositor_channel(&window);
let supports_clipboard = match window {
Some(ref win_rc) => {
let win: &Window = win_rc.borrow();
win.supports_clipboard()
}
None => false
};
let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period);
let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period);
let devtools_chan = opts.devtools_port.map(|port| {
devtools::start_server(port)
});
// Create the constellation, which maintains the engine
// pipelines, including the script and layout threads, as well | devtools_chan,
supports_clipboard);
if cfg!(feature = "webdriver") {
if let Some(port) = opts.webdriver_port {
webdriver(port, constellation_chan.clone());
}
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = CompositorTask::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
constellation_chan: constellation_chan,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
});
Browser {
compositor: compositor,
}
}
pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool {
self.compositor.handle_events(events)
}
pub fn repaint_synchronously(&mut self) {
self.compositor.repaint_synchronously()
}
pub fn pinch_zoom_level(&self) -> f32 {
self.compositor.pinch_zoom_level()
}
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
}
fn create_constellation(opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>,
supports_clipboard: bool) -> Sender<ConstellationMsg> {
let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone());
let image_cache_task = new_image_cache_task(resource_task.clone());
let font_cache_task = FontCacheTask::new(resource_task.clone());
let storage_task: StorageTask = StorageTaskFactory::new();
let initial_state = InitialConstellationState {
compositor_proxy: compositor_proxy,
devtools_chan: devtools_chan,
image_cache_task: image_cache_task,
font_cache_task: font_cache_task,
resource_task: resource_task,
storage_task: storage_task,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
supports_clipboard: supports_clipboard,
};
let constellation_chan =
Constellation::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>::start(initial_state);
// Send the URL command to the constellation.
match opts.url {
Some(url) => {
constellation_chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap();
},
None => ()
};
constellation_chan
}
/// Content process entry point.
pub fn run_content_process(token: String) {
let (unprivileged_content_sender, unprivileged_content_receiver) =
ipc::channel::<UnprivilegedPipelineContent>().unwrap();
let connection_bootstrap: IpcSender<IpcSender<UnprivilegedPipelineContent>> =
IpcSender::connect(token).unwrap();
connection_bootstrap.send(unprivileged_content_sender).unwrap();
let unprivileged_content = unprivileged_content_receiver.recv().unwrap();
opts::set_defaults(unprivileged_content.opts());
// Enter the sandbox if necessary.
if opts::get().sandbox {
ChildSandbox::new(sandboxing::content_process_sandbox_profile()).activate().unwrap();
}
script::init();
unprivileged_content.start_all::<layout::layout_task::LayoutTask,
script::script_task::ScriptTask>(true);
} | // as the navigation context.
let constellation_chan = create_constellation(opts.clone(),
compositor_proxy.clone_compositor_proxy(),
time_profiler_chan.clone(),
mem_profiler_chan.clone(), | random_line_split |
dist.rs | //! This module implements middleware to serve the compiled emberjs
//! frontend
use std::error::Error;
use conduit::{Request, Response, Handler};
use conduit_static::Static;
use conduit_middleware::AroundMiddleware;
use util::RequestProxy;
// Can't derive debug because of Handler and Static.
#[allow(missing_debug_implementations)]
pub struct Middleware {
handler: Option<Box<Handler>>,
dist: Static,
}
impl Default for Middleware {
fn default() -> Middleware {
Middleware {
handler: None,
dist: Static::new("dist"),
}
}
}
impl AroundMiddleware for Middleware {
fn with_handler(&mut self, handler: Box<Handler>) |
}
impl Handler for Middleware {
fn call(&self, req: &mut Request) -> Result<Response, Box<Error + Send>> {
// First, attempt to serve a static file. If we're missing a static
// file, then keep going.
match self.dist.call(req) {
Ok(ref resp) if resp.status.0 == 404 => {}
ret => return ret,
}
// Second, if we're requesting html, then we've only got one page so
// serve up that page. Otherwise proxy on to the rest of the app.
let wants_html = req.headers()
.find("Accept")
.map(|accept| accept.iter().any(|s| s.contains("html")))
.unwrap_or(false);
// If the route starts with /api, just assume they want the API
// response. Someone is either debugging or trying to download a crate.
let is_api_path = req.path().starts_with("/api");
if wants_html &&!is_api_path {
self.dist.call(&mut RequestProxy {
other: req,
path: Some("/index.html"),
method: None,
})
} else {
self.handler.as_ref().unwrap().call(req)
}
}
}
| {
self.handler = Some(handler);
} | identifier_body |
dist.rs | //! This module implements middleware to serve the compiled emberjs
//! frontend
use std::error::Error;
use conduit::{Request, Response, Handler};
use conduit_static::Static;
use conduit_middleware::AroundMiddleware;
use util::RequestProxy;
// Can't derive debug because of Handler and Static.
#[allow(missing_debug_implementations)]
pub struct Middleware {
handler: Option<Box<Handler>>,
dist: Static,
}
impl Default for Middleware {
fn | () -> Middleware {
Middleware {
handler: None,
dist: Static::new("dist"),
}
}
}
impl AroundMiddleware for Middleware {
fn with_handler(&mut self, handler: Box<Handler>) {
self.handler = Some(handler);
}
}
impl Handler for Middleware {
fn call(&self, req: &mut Request) -> Result<Response, Box<Error + Send>> {
// First, attempt to serve a static file. If we're missing a static
// file, then keep going.
match self.dist.call(req) {
Ok(ref resp) if resp.status.0 == 404 => {}
ret => return ret,
}
// Second, if we're requesting html, then we've only got one page so
// serve up that page. Otherwise proxy on to the rest of the app.
let wants_html = req.headers()
.find("Accept")
.map(|accept| accept.iter().any(|s| s.contains("html")))
.unwrap_or(false);
// If the route starts with /api, just assume they want the API
// response. Someone is either debugging or trying to download a crate.
let is_api_path = req.path().starts_with("/api");
if wants_html &&!is_api_path {
self.dist.call(&mut RequestProxy {
other: req,
path: Some("/index.html"),
method: None,
})
} else {
self.handler.as_ref().unwrap().call(req)
}
}
}
| default | identifier_name |
dist.rs | //! This module implements middleware to serve the compiled emberjs
//! frontend
use std::error::Error;
use conduit::{Request, Response, Handler};
use conduit_static::Static;
use conduit_middleware::AroundMiddleware;
use util::RequestProxy;
// Can't derive debug because of Handler and Static.
#[allow(missing_debug_implementations)]
pub struct Middleware {
handler: Option<Box<Handler>>,
dist: Static,
}
impl Default for Middleware {
fn default() -> Middleware {
Middleware {
handler: None,
dist: Static::new("dist"),
}
}
}
impl AroundMiddleware for Middleware {
fn with_handler(&mut self, handler: Box<Handler>) {
self.handler = Some(handler);
}
}
impl Handler for Middleware {
fn call(&self, req: &mut Request) -> Result<Response, Box<Error + Send>> {
// First, attempt to serve a static file. If we're missing a static
// file, then keep going.
match self.dist.call(req) {
Ok(ref resp) if resp.status.0 == 404 => {}
ret => return ret,
}
// Second, if we're requesting html, then we've only got one page so
// serve up that page. Otherwise proxy on to the rest of the app. | let wants_html = req.headers()
.find("Accept")
.map(|accept| accept.iter().any(|s| s.contains("html")))
.unwrap_or(false);
// If the route starts with /api, just assume they want the API
// response. Someone is either debugging or trying to download a crate.
let is_api_path = req.path().starts_with("/api");
if wants_html &&!is_api_path {
self.dist.call(&mut RequestProxy {
other: req,
path: Some("/index.html"),
method: None,
})
} else {
self.handler.as_ref().unwrap().call(req)
}
}
} | random_line_split |
|
mod.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/. */
//! Tests for parsing and serialization of values/properties
use cssparser::{Parser, ParserInput};
use style::context::QuirksMode;
use style::parser::ParserContext;
use style::stylesheets::{CssRuleType, Origin};
use style_traits::{ParsingMode, ParseError};
fn parse<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
let mut input = ParserInput::new(s);
parse_input(f, &mut input)
}
fn parse_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(
Origin::Author,
&url,
Some(CssRuleType::Style),
ParsingMode::DEFAULT,
QuirksMode::NoQuirks,
None,
None,
);
let mut parser = Parser::new(input);
f(&context, &mut parser)
}
fn parse_entirely<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
let mut input = ParserInput::new(s);
parse_entirely_input(f, &mut input)
}
fn | <'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
parse_input(|context, parser| parser.parse_entirely(|p| f(context, p)), input)
}
// This is a macro so that the file/line information
// is preserved in the panic
macro_rules! assert_roundtrip_with_context {
($fun:expr, $string:expr) => {
assert_roundtrip_with_context!($fun, $string, $string);
};
($fun:expr, $input:expr, $output:expr) => {{
let mut input = ::cssparser::ParserInput::new($input);
let serialized = super::parse_input(|context, i| {
let parsed = $fun(context, i)
.expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
Ok(serialized)
}, &mut input).unwrap();
let mut input = ::cssparser::ParserInput::new(&serialized);
let unwrapped = super::parse_input(|context, i| {
let re_parsed = $fun(context, i)
.expect(&format!("Failed to parse serialization {}", $input));
let re_serialized = ToCss::to_css_string(&re_parsed);
assert_eq!(serialized, re_serialized);
Ok(())
}, &mut input).unwrap();
unwrapped
}}
}
macro_rules! assert_roundtrip {
($fun:expr, $string:expr) => {
assert_roundtrip!($fun, $string, $string);
};
($fun:expr, $input:expr, $output:expr) => {
let mut input = ParserInput::new($input);
let mut parser = Parser::new(&mut input);
let parsed = $fun(&mut parser)
.expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
let mut input = ParserInput::new(&serialized);
let mut parser = Parser::new(&mut input);
let re_parsed = $fun(&mut parser)
.expect(&format!("Failed to parse serialization {}", $input));
let re_serialized = ToCss::to_css_string(&re_parsed);
assert_eq!(serialized, re_serialized)
}
}
macro_rules! assert_parser_exhausted {
($fun:expr, $string:expr, $should_exhausted:expr) => {{
parse(|context, input| {
let parsed = $fun(context, input);
assert_eq!(parsed.is_ok(), true);
assert_eq!(input.is_exhausted(), $should_exhausted);
Ok(())
}, $string).unwrap()
}}
}
macro_rules! parse_longhand {
($name:ident, $s:expr) => {
parse($name::parse, $s).unwrap()
};
}
mod animation;
mod background;
mod border;
mod box_;
mod column;
mod effects;
mod image;
mod inherited_text;
mod outline;
mod position;
mod selectors;
mod supports;
mod text_overflow;
mod transition_duration;
mod transition_timing_function;
| parse_entirely_input | identifier_name |
mod.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/. */
//! Tests for parsing and serialization of values/properties
use cssparser::{Parser, ParserInput};
use style::context::QuirksMode;
use style::parser::ParserContext;
use style::stylesheets::{CssRuleType, Origin};
use style_traits::{ParsingMode, ParseError};
fn parse<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
let mut input = ParserInput::new(s);
parse_input(f, &mut input)
}
fn parse_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(
Origin::Author,
&url,
Some(CssRuleType::Style),
ParsingMode::DEFAULT,
QuirksMode::NoQuirks,
None,
None,
);
let mut parser = Parser::new(input);
f(&context, &mut parser)
}
fn parse_entirely<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
let mut input = ParserInput::new(s);
parse_entirely_input(f, &mut input)
}
fn parse_entirely_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
parse_input(|context, parser| parser.parse_entirely(|p| f(context, p)), input)
}
// This is a macro so that the file/line information
// is preserved in the panic
macro_rules! assert_roundtrip_with_context {
($fun:expr, $string:expr) => {
assert_roundtrip_with_context!($fun, $string, $string);
};
($fun:expr, $input:expr, $output:expr) => {{
let mut input = ::cssparser::ParserInput::new($input);
let serialized = super::parse_input(|context, i| {
let parsed = $fun(context, i)
.expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
Ok(serialized)
}, &mut input).unwrap();
let mut input = ::cssparser::ParserInput::new(&serialized);
let unwrapped = super::parse_input(|context, i| {
let re_parsed = $fun(context, i)
.expect(&format!("Failed to parse serialization {}", $input));
let re_serialized = ToCss::to_css_string(&re_parsed);
assert_eq!(serialized, re_serialized);
Ok(())
}, &mut input).unwrap();
unwrapped
}}
}
macro_rules! assert_roundtrip {
($fun:expr, $string:expr) => {
assert_roundtrip!($fun, $string, $string);
};
($fun:expr, $input:expr, $output:expr) => {
let mut input = ParserInput::new($input);
let mut parser = Parser::new(&mut input);
let parsed = $fun(&mut parser)
.expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
let mut input = ParserInput::new(&serialized);
let mut parser = Parser::new(&mut input);
let re_parsed = $fun(&mut parser)
.expect(&format!("Failed to parse serialization {}", $input));
let re_serialized = ToCss::to_css_string(&re_parsed);
assert_eq!(serialized, re_serialized)
}
}
macro_rules! assert_parser_exhausted {
($fun:expr, $string:expr, $should_exhausted:expr) => {{
parse(|context, input| {
let parsed = $fun(context, input);
assert_eq!(parsed.is_ok(), true);
assert_eq!(input.is_exhausted(), $should_exhausted);
Ok(())
}, $string).unwrap()
}}
}
macro_rules! parse_longhand {
($name:ident, $s:expr) => {
parse($name::parse, $s).unwrap()
};
}
mod animation;
mod background;
mod border;
mod box_;
mod column;
mod effects;
mod image;
mod inherited_text;
mod outline;
mod position;
mod selectors;
mod supports;
mod text_overflow; | mod transition_duration;
mod transition_timing_function; | random_line_split |
|
mod.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/. */
//! Tests for parsing and serialization of values/properties
use cssparser::{Parser, ParserInput};
use style::context::QuirksMode;
use style::parser::ParserContext;
use style::stylesheets::{CssRuleType, Origin};
use style_traits::{ParsingMode, ParseError};
fn parse<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> |
fn parse_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(
Origin::Author,
&url,
Some(CssRuleType::Style),
ParsingMode::DEFAULT,
QuirksMode::NoQuirks,
None,
None,
);
let mut parser = Parser::new(input);
f(&context, &mut parser)
}
fn parse_entirely<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
let mut input = ParserInput::new(s);
parse_entirely_input(f, &mut input)
}
fn parse_entirely_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
parse_input(|context, parser| parser.parse_entirely(|p| f(context, p)), input)
}
// This is a macro so that the file/line information
// is preserved in the panic
macro_rules! assert_roundtrip_with_context {
($fun:expr, $string:expr) => {
assert_roundtrip_with_context!($fun, $string, $string);
};
($fun:expr, $input:expr, $output:expr) => {{
let mut input = ::cssparser::ParserInput::new($input);
let serialized = super::parse_input(|context, i| {
let parsed = $fun(context, i)
.expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
Ok(serialized)
}, &mut input).unwrap();
let mut input = ::cssparser::ParserInput::new(&serialized);
let unwrapped = super::parse_input(|context, i| {
let re_parsed = $fun(context, i)
.expect(&format!("Failed to parse serialization {}", $input));
let re_serialized = ToCss::to_css_string(&re_parsed);
assert_eq!(serialized, re_serialized);
Ok(())
}, &mut input).unwrap();
unwrapped
}}
}
macro_rules! assert_roundtrip {
($fun:expr, $string:expr) => {
assert_roundtrip!($fun, $string, $string);
};
($fun:expr, $input:expr, $output:expr) => {
let mut input = ParserInput::new($input);
let mut parser = Parser::new(&mut input);
let parsed = $fun(&mut parser)
.expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
let mut input = ParserInput::new(&serialized);
let mut parser = Parser::new(&mut input);
let re_parsed = $fun(&mut parser)
.expect(&format!("Failed to parse serialization {}", $input));
let re_serialized = ToCss::to_css_string(&re_parsed);
assert_eq!(serialized, re_serialized)
}
}
macro_rules! assert_parser_exhausted {
($fun:expr, $string:expr, $should_exhausted:expr) => {{
parse(|context, input| {
let parsed = $fun(context, input);
assert_eq!(parsed.is_ok(), true);
assert_eq!(input.is_exhausted(), $should_exhausted);
Ok(())
}, $string).unwrap()
}}
}
macro_rules! parse_longhand {
($name:ident, $s:expr) => {
parse($name::parse, $s).unwrap()
};
}
mod animation;
mod background;
mod border;
mod box_;
mod column;
mod effects;
mod image;
mod inherited_text;
mod outline;
mod position;
mod selectors;
mod supports;
mod text_overflow;
mod transition_duration;
mod transition_timing_function;
| {
let mut input = ParserInput::new(s);
parse_input(f, &mut input)
} | identifier_body |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use js::jsapi::{HandleValue, JSContext};
use js::jsval::JSVal;
use string_cache::Atom;
// https://dom.spec.whatwg.org/#interface-customevent
#[dom_struct]
pub struct CustomEvent {
event: Event,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
detail: MutHeapJSVal,
}
impl CustomEvent {
fn new_inherited() -> CustomEvent {
CustomEvent {
event: Event::new_inherited(),
detail: MutHeapJSVal::new(),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool,
detail: HandleValue)
-> Root<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global);
ev.init_custom_event(type_, bubbles, cancelable, detail);
ev
}
#[allow(unsafe_code)]
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit)
-> Fallible<Root<CustomEvent>> {
Ok(CustomEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
unsafe { HandleValue::from_marked_location(&init.detail) }))
}
fn init_custom_event(&self,
type_: Atom,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
let event = self.upcast::<Event>();
if event.dispatching() |
self.detail.set(detail.get());
event.init_event(type_, can_bubble, cancelable);
}
}
impl CustomEventMethods for CustomEvent {
// https://dom.spec.whatwg.org/#dom-customevent-detail
fn Detail(&self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
fn InitCustomEvent(&self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
self.init_custom_event(Atom::from(type_), can_bubble, cancelable, detail)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
return;
} | conditional_block |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use js::jsapi::{HandleValue, JSContext};
use js::jsval::JSVal;
use string_cache::Atom;
// https://dom.spec.whatwg.org/#interface-customevent
#[dom_struct]
pub struct CustomEvent {
event: Event,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
detail: MutHeapJSVal,
}
impl CustomEvent {
fn new_inherited() -> CustomEvent {
CustomEvent {
event: Event::new_inherited(),
detail: MutHeapJSVal::new(),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool,
detail: HandleValue)
-> Root<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global);
ev.init_custom_event(type_, bubbles, cancelable, detail);
ev
}
#[allow(unsafe_code)]
pub fn | (global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit)
-> Fallible<Root<CustomEvent>> {
Ok(CustomEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
unsafe { HandleValue::from_marked_location(&init.detail) }))
}
fn init_custom_event(&self,
type_: Atom,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
let event = self.upcast::<Event>();
if event.dispatching() {
return;
}
self.detail.set(detail.get());
event.init_event(type_, can_bubble, cancelable);
}
}
impl CustomEventMethods for CustomEvent {
// https://dom.spec.whatwg.org/#dom-customevent-detail
fn Detail(&self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
fn InitCustomEvent(&self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
self.init_custom_event(Atom::from(type_), can_bubble, cancelable, detail)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| Constructor | identifier_name |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use js::jsapi::{HandleValue, JSContext};
use js::jsval::JSVal;
use string_cache::Atom;
// https://dom.spec.whatwg.org/#interface-customevent
#[dom_struct]
pub struct CustomEvent {
event: Event,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
detail: MutHeapJSVal,
}
impl CustomEvent {
fn new_inherited() -> CustomEvent {
CustomEvent {
event: Event::new_inherited(),
detail: MutHeapJSVal::new(),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool,
detail: HandleValue)
-> Root<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global);
ev.init_custom_event(type_, bubbles, cancelable, detail);
ev
}
#[allow(unsafe_code)]
pub fn Constructor(global: GlobalRef, | Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
unsafe { HandleValue::from_marked_location(&init.detail) }))
}
fn init_custom_event(&self,
type_: Atom,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
let event = self.upcast::<Event>();
if event.dispatching() {
return;
}
self.detail.set(detail.get());
event.init_event(type_, can_bubble, cancelable);
}
}
impl CustomEventMethods for CustomEvent {
// https://dom.spec.whatwg.org/#dom-customevent-detail
fn Detail(&self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
fn InitCustomEvent(&self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
self.init_custom_event(Atom::from(type_), can_bubble, cancelable, detail)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
} | type_: DOMString,
init: &CustomEventBinding::CustomEventInit)
-> Fallible<Root<CustomEvent>> {
Ok(CustomEvent::new(global, | random_line_split |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use js::jsapi::{HandleValue, JSContext};
use js::jsval::JSVal;
use string_cache::Atom;
// https://dom.spec.whatwg.org/#interface-customevent
#[dom_struct]
pub struct CustomEvent {
event: Event,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
detail: MutHeapJSVal,
}
impl CustomEvent {
fn new_inherited() -> CustomEvent {
CustomEvent {
event: Event::new_inherited(),
detail: MutHeapJSVal::new(),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Root<CustomEvent> |
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool,
detail: HandleValue)
-> Root<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global);
ev.init_custom_event(type_, bubbles, cancelable, detail);
ev
}
#[allow(unsafe_code)]
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit)
-> Fallible<Root<CustomEvent>> {
Ok(CustomEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
unsafe { HandleValue::from_marked_location(&init.detail) }))
}
fn init_custom_event(&self,
type_: Atom,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
let event = self.upcast::<Event>();
if event.dispatching() {
return;
}
self.detail.set(detail.get());
event.init_event(type_, can_bubble, cancelable);
}
}
impl CustomEventMethods for CustomEvent {
// https://dom.spec.whatwg.org/#dom-customevent-detail
fn Detail(&self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
fn InitCustomEvent(&self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
self.init_custom_event(Atom::from(type_), can_bubble, cancelable, detail)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
reflect_dom_object(box CustomEvent::new_inherited(),
global,
CustomEventBinding::Wrap)
} | identifier_body |
get_login_types.rs | //! [GET /_matrix/client/r0/login](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-login)
use ruma_api::ruma_api;
use serde::{Deserialize, Serialize};
ruma_api! {
metadata {
description: "Gets the homeserver's supported login types to authenticate users. Clients should pick one of these and supply it as the type when logging in.",
method: GET,
name: "get_login_types",
path: "/_matrix/client/r0/login",
rate_limited: true,
requires_authentication: false,
}
request {}
response {
/// The homeserver's supported login types.
pub flows: Vec<LoginType>
}
error: crate::Error
}
/// An authentication mechanism.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum LoginType {
/// A password is supplied to authenticate.
#[serde(rename = "m.login.password")]
Password,
/// Token-based login.
#[serde(rename = "m.login.token")]
Token,
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json};
use super::LoginType;
#[test]
fn | () {
assert_eq!(
from_json_value::<LoginType>(json!({ "type": "m.login.password" })).unwrap(),
LoginType::Password,
);
}
}
| deserialize_login_type | identifier_name |
get_login_types.rs | //! [GET /_matrix/client/r0/login](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-login)
use ruma_api::ruma_api;
use serde::{Deserialize, Serialize};
ruma_api! {
metadata {
description: "Gets the homeserver's supported login types to authenticate users. Clients should pick one of these and supply it as the type when logging in.",
method: GET,
name: "get_login_types",
path: "/_matrix/client/r0/login",
rate_limited: true,
requires_authentication: false,
}
request {}
response {
/// The homeserver's supported login types.
pub flows: Vec<LoginType>
}
error: crate::Error
}
/// An authentication mechanism.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum LoginType {
/// A password is supplied to authenticate.
#[serde(rename = "m.login.password")]
Password,
/// Token-based login. | #[serde(rename = "m.login.token")]
Token,
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json};
use super::LoginType;
#[test]
fn deserialize_login_type() {
assert_eq!(
from_json_value::<LoginType>(json!({ "type": "m.login.password" })).unwrap(),
LoginType::Password,
);
}
} | random_line_split |
|
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async fn call_where_clause<F>(f: F)
where
F: Foo,
{
f.foo()
}
pub async fn call_impl_trait(f: impl Foo) {
f.foo()
}
pub async fn call_with_ref(f: &impl Foo) {
f.foo()
}
pub fn async_fn_with_same_generic_params_unifies() {
let mut a = call_generic_bound(FooType);
a = call_generic_bound(FooType);
let mut b = call_where_clause(FooType);
b = call_where_clause(FooType);
let mut c = call_impl_trait(FooType);
c = call_impl_trait(FooType);
let f_one = FooType;
let f_two = FooType;
let mut d = call_with_ref(&f_one);
d = call_with_ref(&f_two);
}
pub fn simple_generic_block<T>() -> impl Future<Output = ()> {
async move {}
}
pub fn | <F: Foo>(f: F) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_where_clause_block<F>(f: F) -> impl Future<Output = ()>
where
F: Foo,
{
async move { f.foo() }
}
pub fn call_impl_trait_block(f: impl Foo) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_with_ref_block<'a>(f: &'a (impl Foo + 'a)) -> impl Future<Output = ()> + 'a {
async move { f.foo() }
}
pub fn async_block_with_same_generic_params_unifies() {
let mut a = call_generic_bound_block(FooType);
a = call_generic_bound_block(FooType);
let mut b = call_where_clause_block(FooType);
b = call_where_clause_block(FooType);
let mut c = call_impl_trait_block(FooType);
c = call_impl_trait_block(FooType);
let f_one = FooType;
let f_two = FooType;
let mut d = call_with_ref_block(&f_one);
d = call_with_ref_block(&f_two);
}
| call_generic_bound_block | identifier_name |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async fn call_where_clause<F>(f: F)
where
F: Foo,
{
f.foo()
}
| pub async fn call_with_ref(f: &impl Foo) {
f.foo()
}
pub fn async_fn_with_same_generic_params_unifies() {
let mut a = call_generic_bound(FooType);
a = call_generic_bound(FooType);
let mut b = call_where_clause(FooType);
b = call_where_clause(FooType);
let mut c = call_impl_trait(FooType);
c = call_impl_trait(FooType);
let f_one = FooType;
let f_two = FooType;
let mut d = call_with_ref(&f_one);
d = call_with_ref(&f_two);
}
pub fn simple_generic_block<T>() -> impl Future<Output = ()> {
async move {}
}
pub fn call_generic_bound_block<F: Foo>(f: F) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_where_clause_block<F>(f: F) -> impl Future<Output = ()>
where
F: Foo,
{
async move { f.foo() }
}
pub fn call_impl_trait_block(f: impl Foo) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_with_ref_block<'a>(f: &'a (impl Foo + 'a)) -> impl Future<Output = ()> + 'a {
async move { f.foo() }
}
pub fn async_block_with_same_generic_params_unifies() {
let mut a = call_generic_bound_block(FooType);
a = call_generic_bound_block(FooType);
let mut b = call_where_clause_block(FooType);
b = call_where_clause_block(FooType);
let mut c = call_impl_trait_block(FooType);
c = call_impl_trait_block(FooType);
let f_one = FooType;
let f_two = FooType;
let mut d = call_with_ref_block(&f_one);
d = call_with_ref_block(&f_two);
} | pub async fn call_impl_trait(f: impl Foo) {
f.foo()
}
| random_line_split |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async fn call_where_clause<F>(f: F)
where
F: Foo,
{
f.foo()
}
pub async fn call_impl_trait(f: impl Foo) {
f.foo()
}
pub async fn call_with_ref(f: &impl Foo) |
pub fn async_fn_with_same_generic_params_unifies() {
let mut a = call_generic_bound(FooType);
a = call_generic_bound(FooType);
let mut b = call_where_clause(FooType);
b = call_where_clause(FooType);
let mut c = call_impl_trait(FooType);
c = call_impl_trait(FooType);
let f_one = FooType;
let f_two = FooType;
let mut d = call_with_ref(&f_one);
d = call_with_ref(&f_two);
}
pub fn simple_generic_block<T>() -> impl Future<Output = ()> {
async move {}
}
pub fn call_generic_bound_block<F: Foo>(f: F) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_where_clause_block<F>(f: F) -> impl Future<Output = ()>
where
F: Foo,
{
async move { f.foo() }
}
pub fn call_impl_trait_block(f: impl Foo) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_with_ref_block<'a>(f: &'a (impl Foo + 'a)) -> impl Future<Output = ()> + 'a {
async move { f.foo() }
}
pub fn async_block_with_same_generic_params_unifies() {
let mut a = call_generic_bound_block(FooType);
a = call_generic_bound_block(FooType);
let mut b = call_where_clause_block(FooType);
b = call_where_clause_block(FooType);
let mut c = call_impl_trait_block(FooType);
c = call_impl_trait_block(FooType);
let f_one = FooType;
let f_two = FooType;
let mut d = call_with_ref_block(&f_one);
d = call_with_ref_block(&f_two);
}
| {
f.foo()
} | identifier_body |
shootout-binarytrees.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// |
extern mod extra;
use std::iter::range_step;
use extra::future::Future;
use extra::arena::TypedArena;
enum Tree<'a> {
Nil,
Node(&'a Tree<'a>, &'a Tree<'a>, int)
}
fn item_check(t: &Tree) -> int {
match *t {
Nil => 0,
Node(l, r, i) => i + item_check(l) - item_check(r)
}
}
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: int, depth: int)
-> &'r Tree<'r> {
if depth > 0 {
arena.alloc(Node(bottom_up_tree(arena, 2 * item - 1, depth - 1),
bottom_up_tree(arena, 2 * item, depth - 1),
item))
} else {
arena.alloc(Nil)
}
}
fn main() {
let args = std::os::args();
let n = if std::os::getenv("RUST_BENCH").is_some() {
17
} else if args.len() <= 1u {
8
} else {
from_str(args[1]).unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(tree));
}
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let mut messages = range_step(min_depth, max_depth + 1, 2).map(|depth| {
use std::int::pow;
let iterations = pow(2, (max_depth - depth + min_depth) as uint);
do Future::spawn {
let mut chk = 0;
for i in range(1, iterations + 1) {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(a) + item_check(b);
}
format!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
}
}).to_owned_vec();
for message in messages.mut_iter() {
println!("{}", *message.get_ref());
}
println!("long lived tree of depth {}\t check: {}",
max_depth, item_check(long_lived_tree));
} | // 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. | random_line_split |
shootout-binarytrees.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
use std::iter::range_step;
use extra::future::Future;
use extra::arena::TypedArena;
enum Tree<'a> {
Nil,
Node(&'a Tree<'a>, &'a Tree<'a>, int)
}
fn item_check(t: &Tree) -> int {
match *t {
Nil => 0,
Node(l, r, i) => i + item_check(l) - item_check(r)
}
}
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: int, depth: int)
-> &'r Tree<'r> {
if depth > 0 {
arena.alloc(Node(bottom_up_tree(arena, 2 * item - 1, depth - 1),
bottom_up_tree(arena, 2 * item, depth - 1),
item))
} else {
arena.alloc(Nil)
}
}
fn | () {
let args = std::os::args();
let n = if std::os::getenv("RUST_BENCH").is_some() {
17
} else if args.len() <= 1u {
8
} else {
from_str(args[1]).unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(tree));
}
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let mut messages = range_step(min_depth, max_depth + 1, 2).map(|depth| {
use std::int::pow;
let iterations = pow(2, (max_depth - depth + min_depth) as uint);
do Future::spawn {
let mut chk = 0;
for i in range(1, iterations + 1) {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(a) + item_check(b);
}
format!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
}
}).to_owned_vec();
for message in messages.mut_iter() {
println!("{}", *message.get_ref());
}
println!("long lived tree of depth {}\t check: {}",
max_depth, item_check(long_lived_tree));
}
| main | identifier_name |
shootout-binarytrees.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
use std::iter::range_step;
use extra::future::Future;
use extra::arena::TypedArena;
enum Tree<'a> {
Nil,
Node(&'a Tree<'a>, &'a Tree<'a>, int)
}
fn item_check(t: &Tree) -> int |
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: int, depth: int)
-> &'r Tree<'r> {
if depth > 0 {
arena.alloc(Node(bottom_up_tree(arena, 2 * item - 1, depth - 1),
bottom_up_tree(arena, 2 * item, depth - 1),
item))
} else {
arena.alloc(Nil)
}
}
fn main() {
let args = std::os::args();
let n = if std::os::getenv("RUST_BENCH").is_some() {
17
} else if args.len() <= 1u {
8
} else {
from_str(args[1]).unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(tree));
}
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let mut messages = range_step(min_depth, max_depth + 1, 2).map(|depth| {
use std::int::pow;
let iterations = pow(2, (max_depth - depth + min_depth) as uint);
do Future::spawn {
let mut chk = 0;
for i in range(1, iterations + 1) {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(a) + item_check(b);
}
format!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
}
}).to_owned_vec();
for message in messages.mut_iter() {
println!("{}", *message.get_ref());
}
println!("long lived tree of depth {}\t check: {}",
max_depth, item_check(long_lived_tree));
}
| {
match *t {
Nil => 0,
Node(l, r, i) => i + item_check(l) - item_check(r)
}
} | identifier_body |
lib.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/. */
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(nonzero)]
#![feature(plugin)]
#![feature(raw)]
#![feature(step_by)]
#![deny(unsafe_code)]
#![plugin(plugins)]
extern crate app_units;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
extern crate canvas_traits;
extern crate core;
extern crate cssparser;
extern crate euclid;
extern crate fnv;
extern crate gfx;
extern crate gfx_traits;
extern crate heapsize;
#[macro_use] extern crate html5ever_atoms;
extern crate ipc_channel;
extern crate libc;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate ordered_float;
extern crate parking_lot;
extern crate profile_traits;
#[macro_use]
extern crate range;
extern crate rayon;
extern crate script_layout_interface;
extern crate script_traits;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate servo_config;
extern crate servo_geometry;
extern crate servo_url;
extern crate smallvec;
extern crate style;
extern crate style_traits;
extern crate unicode_bidi;
extern crate unicode_script;
extern crate webrender_traits;
#[macro_use]
pub mod layout_debug;
pub mod animation;
mod block;
pub mod construct;
pub mod context;
mod data;
pub mod display_list_builder;
mod flex;
mod floats;
pub mod flow;
mod flow_list;
pub mod flow_ref;
mod fragment;
mod generated_content;
pub mod incremental;
mod inline;
mod linked_list;
mod list_item;
mod model;
mod multicol;
mod opaque_node;
pub mod parallel;
mod persistent_list;
pub mod query;
pub mod sequential;
mod table;
mod table_caption;
mod table_cell;
mod table_colgroup;
mod table_row; | pub mod traversal;
pub mod webrender_helpers;
pub mod wrapper;
// For unit tests:
pub use fragment::Fragment;
pub use fragment::SpecificFragmentInfo; | mod table_rowgroup;
mod table_wrapper;
mod text; | random_line_split |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[serde(skip_serializing_if = "Option::is_none")]
parse_mode: Option<ParseMode>,
#[serde(skip_serializing_if = "Not::not")]
disable_web_page_preview: bool,
#[serde(skip_serializing_if = "Not::not")]
disable_notification: bool,
#[serde(skip_serializing_if = "Option::is_none")]
reply_to_message_id: Option<MessageId>,
#[serde(skip_serializing_if = "Option::is_none")]
reply_markup: Option<ReplyMarkup>,
}
impl<'c,'s> Request for SendMessage<'s> {
type Type = JsonRequestType<Self>;
type Response = JsonIdResponse<MessageOrChannelPost>;
fn serialize(&self) -> Result<HttpRequest, Error> {
Self::Type::serialize(RequestUrl::method("sendMessage"), self)
}
}
impl<'s> SendMessage<'s> {
pub fn new<C, T>(chat: C, text: T) -> Self
where
C: ToChatRef,
T: Into<Cow<'s, str>>,
{
SendMessage {
chat_id: chat.to_chat_ref(),
text: text.into(),
parse_mode: None,
disable_web_page_preview: false,
disable_notification: false,
reply_to_message_id: None,
reply_markup: None,
}
}
pub fn parse_mode(&mut self, parse_mode: ParseMode) -> &mut Self {
self.parse_mode = Some(parse_mode);
self
}
pub fn disable_preview(&mut self) -> &mut Self {
self.disable_web_page_preview = true;
self
}
pub fn disable_notification(&mut self) -> &mut Self {
self.disable_notification = true;
self
}
pub fn reply_to<R>(&mut self, to: R) -> &mut Self
where
R: ToMessageId,
{
self.reply_to_message_id = Some(to.to_message_id());
self
}
pub fn reply_markup<R>(&mut self, reply_markup: R) -> &mut Self
where
R: Into<ReplyMarkup>,
{
self.reply_markup = Some(reply_markup.into());
self
}
}
/// Send text message.
pub trait CanSendMessage {
fn text<'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<C> CanSendMessage for C
where
C: ToChatRef,
{
fn text<'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
|
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanReplySendMessage for M
where
M: ToMessageId + ToSourceChat,
{
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
let mut rq = self.to_source_chat().text(text);
rq.reply_to(self.to_message_id());
rq
}
}
| {
SendMessage::new(self, text)
} | identifier_body |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[serde(skip_serializing_if = "Option::is_none")]
parse_mode: Option<ParseMode>,
#[serde(skip_serializing_if = "Not::not")]
disable_web_page_preview: bool,
#[serde(skip_serializing_if = "Not::not")]
disable_notification: bool,
#[serde(skip_serializing_if = "Option::is_none")]
reply_to_message_id: Option<MessageId>,
#[serde(skip_serializing_if = "Option::is_none")]
reply_markup: Option<ReplyMarkup>,
}
impl<'c,'s> Request for SendMessage<'s> {
type Type = JsonRequestType<Self>;
type Response = JsonIdResponse<MessageOrChannelPost>;
fn serialize(&self) -> Result<HttpRequest, Error> {
Self::Type::serialize(RequestUrl::method("sendMessage"), self)
}
}
| pub fn new<C, T>(chat: C, text: T) -> Self
where
C: ToChatRef,
T: Into<Cow<'s, str>>,
{
SendMessage {
chat_id: chat.to_chat_ref(),
text: text.into(),
parse_mode: None,
disable_web_page_preview: false,
disable_notification: false,
reply_to_message_id: None,
reply_markup: None,
}
}
pub fn parse_mode(&mut self, parse_mode: ParseMode) -> &mut Self {
self.parse_mode = Some(parse_mode);
self
}
pub fn disable_preview(&mut self) -> &mut Self {
self.disable_web_page_preview = true;
self
}
pub fn disable_notification(&mut self) -> &mut Self {
self.disable_notification = true;
self
}
pub fn reply_to<R>(&mut self, to: R) -> &mut Self
where
R: ToMessageId,
{
self.reply_to_message_id = Some(to.to_message_id());
self
}
pub fn reply_markup<R>(&mut self, reply_markup: R) -> &mut Self
where
R: Into<ReplyMarkup>,
{
self.reply_markup = Some(reply_markup.into());
self
}
}
/// Send text message.
pub trait CanSendMessage {
fn text<'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<C> CanSendMessage for C
where
C: ToChatRef,
{
fn text<'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
SendMessage::new(self, text)
}
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanReplySendMessage for M
where
M: ToMessageId + ToSourceChat,
{
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
let mut rq = self.to_source_chat().text(text);
rq.reply_to(self.to_message_id());
rq
}
} | impl<'s> SendMessage<'s> { | random_line_split |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[serde(skip_serializing_if = "Option::is_none")]
parse_mode: Option<ParseMode>,
#[serde(skip_serializing_if = "Not::not")]
disable_web_page_preview: bool,
#[serde(skip_serializing_if = "Not::not")]
disable_notification: bool,
#[serde(skip_serializing_if = "Option::is_none")]
reply_to_message_id: Option<MessageId>,
#[serde(skip_serializing_if = "Option::is_none")]
reply_markup: Option<ReplyMarkup>,
}
impl<'c,'s> Request for SendMessage<'s> {
type Type = JsonRequestType<Self>;
type Response = JsonIdResponse<MessageOrChannelPost>;
fn serialize(&self) -> Result<HttpRequest, Error> {
Self::Type::serialize(RequestUrl::method("sendMessage"), self)
}
}
impl<'s> SendMessage<'s> {
pub fn new<C, T>(chat: C, text: T) -> Self
where
C: ToChatRef,
T: Into<Cow<'s, str>>,
{
SendMessage {
chat_id: chat.to_chat_ref(),
text: text.into(),
parse_mode: None,
disable_web_page_preview: false,
disable_notification: false,
reply_to_message_id: None,
reply_markup: None,
}
}
pub fn parse_mode(&mut self, parse_mode: ParseMode) -> &mut Self {
self.parse_mode = Some(parse_mode);
self
}
pub fn disable_preview(&mut self) -> &mut Self {
self.disable_web_page_preview = true;
self
}
pub fn disable_notification(&mut self) -> &mut Self {
self.disable_notification = true;
self
}
pub fn reply_to<R>(&mut self, to: R) -> &mut Self
where
R: ToMessageId,
{
self.reply_to_message_id = Some(to.to_message_id());
self
}
pub fn reply_markup<R>(&mut self, reply_markup: R) -> &mut Self
where
R: Into<ReplyMarkup>,
{
self.reply_markup = Some(reply_markup.into());
self
}
}
/// Send text message.
pub trait CanSendMessage {
fn text<'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<C> CanSendMessage for C
where
C: ToChatRef,
{
fn | <'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
SendMessage::new(self, text)
}
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanReplySendMessage for M
where
M: ToMessageId + ToSourceChat,
{
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
let mut rq = self.to_source_chat().text(text);
rq.reply_to(self.to_message_id());
rq
}
}
| text | identifier_name |
base.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::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we should atomically
// reference count them.
pub type Image = stb_image::Image<u8>;
pub fn Image(width: uint, height: uint, depth: uint, data: ~[u8]) -> Image {
stb_image::new_image(width, height, depth, data)
} |
pub fn test_image_bin() -> ~[u8] {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) {
stb_image::ImageU8(image) => {
assert!(image.depth == 4);
// Do color space conversion :(
let data = do vec::from_fn(image.width * image.height * 4) |i| {
let color = i % 4;
let pixel = i / 4;
match color {
0 => image.data[pixel * 4 + 2],
1 => image.data[pixel * 4 + 1],
2 => image.data[pixel * 4 + 0],
3 => 0xffu8,
_ => fail!()
}
};
assert!(image.data.len() == data.len());
Some(Image(image.width, image.height, image.depth, data))
}
stb_image::ImageF32(_image) => fail!(~"HDR images not implemented"),
stb_image::Error => None
}
} |
static TEST_IMAGE: [u8, ..4962] = include_bin!("test.jpeg"); | random_line_split |
base.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::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we should atomically
// reference count them.
pub type Image = stb_image::Image<u8>;
pub fn Image(width: uint, height: uint, depth: uint, data: ~[u8]) -> Image {
stb_image::new_image(width, height, depth, data)
}
static TEST_IMAGE: [u8,..4962] = include_bin!("test.jpeg");
pub fn test_image_bin() -> ~[u8] |
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) {
stb_image::ImageU8(image) => {
assert!(image.depth == 4);
// Do color space conversion :(
let data = do vec::from_fn(image.width * image.height * 4) |i| {
let color = i % 4;
let pixel = i / 4;
match color {
0 => image.data[pixel * 4 + 2],
1 => image.data[pixel * 4 + 1],
2 => image.data[pixel * 4 + 0],
3 => 0xffu8,
_ => fail!()
}
};
assert!(image.data.len() == data.len());
Some(Image(image.width, image.height, image.depth, data))
}
stb_image::ImageF32(_image) => fail!(~"HDR images not implemented"),
stb_image::Error => None
}
}
| {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
} | identifier_body |
base.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::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we should atomically
// reference count them.
pub type Image = stb_image::Image<u8>;
pub fn Image(width: uint, height: uint, depth: uint, data: ~[u8]) -> Image {
stb_image::new_image(width, height, depth, data)
}
static TEST_IMAGE: [u8,..4962] = include_bin!("test.jpeg");
pub fn | () -> ~[u8] {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) {
stb_image::ImageU8(image) => {
assert!(image.depth == 4);
// Do color space conversion :(
let data = do vec::from_fn(image.width * image.height * 4) |i| {
let color = i % 4;
let pixel = i / 4;
match color {
0 => image.data[pixel * 4 + 2],
1 => image.data[pixel * 4 + 1],
2 => image.data[pixel * 4 + 0],
3 => 0xffu8,
_ => fail!()
}
};
assert!(image.data.len() == data.len());
Some(Image(image.width, image.height, image.depth, data))
}
stb_image::ImageF32(_image) => fail!(~"HDR images not implemented"),
stb_image::Error => None
}
}
| test_image_bin | identifier_name |
types.rs | #[derive(Debug, Clone)]
pub enum FnType {
Simple,
None,
}
impl<'a> Into<String> for &'a FnType {
fn into(self) -> String {
match self {
&FnType::Simple => String::from("SIMPLE"),
_ => String::from(""),
}
}
}
impl Into<String> for FnType {
fn into(self) -> String {
(&self).into()
}
}
impl From<String> for FnType {
fn | (s: String) -> FnType {
match s.as_ref() {
"SIMPLE" => FnType::Simple,
_ => FnType::None,
}
}
}
impl PartialEq for FnType {
fn eq(&self, st: &FnType) -> bool {
let s: String = self.into();
let o: String = st.into();
s == o
}
}
#[derive(Debug, Clone)]
pub enum StructType {
Link,
Node,
}
impl<'a> Into<String> for &'a StructType {
fn into(self) -> String {
match self {
&StructType::Link => String::from("LINK"),
&StructType::Node => String::from("NODE"),
}
}
}
impl Into<String> for StructType {
fn into(self) -> String {
(&self).into()
}
}
impl From<String> for StructType {
fn from(s: String) -> StructType {
match s.as_ref() {
"LINK" => StructType::Link,
"NODE" => StructType::Node,
_ => panic!("Type not found!"),
}
}
}
impl PartialEq for StructType {
fn eq(&self, ft: &StructType) -> bool {
let s: String = self.into();
let o: String = ft.into();
s == o
}
}
| from | identifier_name |
types.rs | #[derive(Debug, Clone)]
pub enum FnType {
Simple,
None,
}
impl<'a> Into<String> for &'a FnType {
fn into(self) -> String {
match self { | }
impl Into<String> for FnType {
fn into(self) -> String {
(&self).into()
}
}
impl From<String> for FnType {
fn from(s: String) -> FnType {
match s.as_ref() {
"SIMPLE" => FnType::Simple,
_ => FnType::None,
}
}
}
impl PartialEq for FnType {
fn eq(&self, st: &FnType) -> bool {
let s: String = self.into();
let o: String = st.into();
s == o
}
}
#[derive(Debug, Clone)]
pub enum StructType {
Link,
Node,
}
impl<'a> Into<String> for &'a StructType {
fn into(self) -> String {
match self {
&StructType::Link => String::from("LINK"),
&StructType::Node => String::from("NODE"),
}
}
}
impl Into<String> for StructType {
fn into(self) -> String {
(&self).into()
}
}
impl From<String> for StructType {
fn from(s: String) -> StructType {
match s.as_ref() {
"LINK" => StructType::Link,
"NODE" => StructType::Node,
_ => panic!("Type not found!"),
}
}
}
impl PartialEq for StructType {
fn eq(&self, ft: &StructType) -> bool {
let s: String = self.into();
let o: String = ft.into();
s == o
}
} | &FnType::Simple => String::from("SIMPLE"),
_ => String::from(""),
}
} | random_line_split |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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.
*
* Master Password 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 Master Password. If not, see <http://www.gnu.org/licenses/>.
*/
use self::ring::{digest, hmac};
use common;
use common::{SiteVariant, SiteType};
pub fn master_key(full_name: &str,
master_password: &str,
site_variant: &SiteVariant)
-> Option<[u8; common::KEY_LENGTH]> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let key_scope = scope.unwrap();
let mut master_key_salt = Vec::new();
master_key_salt.extend_from_slice(key_scope.as_bytes());
master_key_salt.extend_from_slice(&common::u32_to_bytes(full_name.len() as u32));
master_key_salt.extend_from_slice(full_name.as_bytes());
Some(common::derive_key(master_password.as_bytes(), master_key_salt.as_slice()))
} else {
None
}
}
pub fn password_for_site(master_key: &[u8; common::KEY_LENGTH],
site_name: &str,
site_type: &SiteType,
site_counter: &i32,
site_variant: &SiteVariant,
site_context: &str)
-> Option<String> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let site_scope = scope.unwrap();
let mut input = Vec::new();
input.extend_from_slice(site_scope.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(site_name.len() as u32));
input.extend_from_slice(site_name.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(*site_counter as u32));
if!site_context.is_empty() {
input.extend_from_slice(&common::u32_to_bytes(site_context.len() as u32));
input.extend_from_slice(site_context.as_bytes());
}
let signing_key = hmac::SigningKey::new(&digest::SHA256, master_key);
let output = hmac::sign(&signing_key, input.as_slice());
let site_password_seed = output.as_ref();
let template = common::template_for_type(site_type, &site_password_seed[0]);
if template.is_some() {
let template = template.unwrap();
let template_bytes = template.as_bytes();
let password = template_bytes
.iter()
.zip(1..template_bytes.len() + 1)
.map(|pair| {
common::character_from_class(*pair.0, site_password_seed[pair.1] as usize)
})
.collect::<Vec<Option<u8>>>();
if password.iter().any(|c| c.is_none()) {
None
} else {
Some(String::from_utf8(password.iter().map(|c| c.unwrap()).collect::<Vec<u8>>())
.unwrap())
}
} else {
None
}
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::{SiteType, SiteVariant};
#[test]
fn get_master_key_for_password() |
#[test]
fn get_master_password() {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
&(1 as i32),
&SiteVariant::Password,
"");
assert_eq!(actual, Some(String::from("QsKBWAYdT9dh^AOGVA0.")));
}
}
| {
let actual = master_key("test", "pass", &SiteVariant::Password)
.unwrap()
.to_vec();
assert_eq!(actual,
vec![51, 253, 82, 252, 68, 97, 191, 162, 127, 73, 153, 160, 52, 128, 204, 4, 183,
190, 106, 180, 68, 126, 100, 94, 132, 141, 99, 143, 106, 211, 94, 245, 245,
255, 195, 72, 28, 128, 197, 51, 99, 27, 125, 24, 54, 193, 223, 230, 118,
181, 225, 236, 171, 104, 9, 158, 214, 23, 166, 89, 36, 174, 64, 112]);
} | identifier_body |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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.
*
* Master Password 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 Master Password. If not, see <http://www.gnu.org/licenses/>.
*/
use self::ring::{digest, hmac};
use common;
use common::{SiteVariant, SiteType};
pub fn master_key(full_name: &str,
master_password: &str,
site_variant: &SiteVariant)
-> Option<[u8; common::KEY_LENGTH]> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let key_scope = scope.unwrap();
let mut master_key_salt = Vec::new();
master_key_salt.extend_from_slice(key_scope.as_bytes());
master_key_salt.extend_from_slice(&common::u32_to_bytes(full_name.len() as u32));
master_key_salt.extend_from_slice(full_name.as_bytes());
Some(common::derive_key(master_password.as_bytes(), master_key_salt.as_slice()))
} else {
None
}
}
pub fn password_for_site(master_key: &[u8; common::KEY_LENGTH],
site_name: &str,
site_type: &SiteType,
site_counter: &i32,
site_variant: &SiteVariant,
site_context: &str)
-> Option<String> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let site_scope = scope.unwrap();
let mut input = Vec::new();
input.extend_from_slice(site_scope.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(site_name.len() as u32));
input.extend_from_slice(site_name.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(*site_counter as u32));
if!site_context.is_empty() {
input.extend_from_slice(&common::u32_to_bytes(site_context.len() as u32));
input.extend_from_slice(site_context.as_bytes());
}
let signing_key = hmac::SigningKey::new(&digest::SHA256, master_key);
let output = hmac::sign(&signing_key, input.as_slice());
let site_password_seed = output.as_ref();
let template = common::template_for_type(site_type, &site_password_seed[0]);
if template.is_some() {
let template = template.unwrap();
let template_bytes = template.as_bytes();
let password = template_bytes
.iter()
.zip(1..template_bytes.len() + 1)
.map(|pair| {
common::character_from_class(*pair.0, site_password_seed[pair.1] as usize)
})
.collect::<Vec<Option<u8>>>();
if password.iter().any(|c| c.is_none()) {
None
} else {
Some(String::from_utf8(password.iter().map(|c| c.unwrap()).collect::<Vec<u8>>())
.unwrap())
}
} else {
None
}
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::{SiteType, SiteVariant};
#[test]
fn get_master_key_for_password() {
let actual = master_key("test", "pass", &SiteVariant::Password)
.unwrap()
.to_vec();
assert_eq!(actual,
vec![51, 253, 82, 252, 68, 97, 191, 162, 127, 73, 153, 160, 52, 128, 204, 4, 183,
190, 106, 180, 68, 126, 100, 94, 132, 141, 99, 143, 106, 211, 94, 245, 245,
255, 195, 72, 28, 128, 197, 51, 99, 27, 125, 24, 54, 193, 223, 230, 118,
181, 225, 236, 171, 104, 9, 158, 214, 23, 166, 89, 36, 174, 64, 112]);
}
#[test]
fn | () {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
&(1 as i32),
&SiteVariant::Password,
"");
assert_eq!(actual, Some(String::from("QsKBWAYdT9dh^AOGVA0.")));
}
}
| get_master_password | identifier_name |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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.
*
* Master Password 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.
* | use common;
use common::{SiteVariant, SiteType};
pub fn master_key(full_name: &str,
master_password: &str,
site_variant: &SiteVariant)
-> Option<[u8; common::KEY_LENGTH]> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let key_scope = scope.unwrap();
let mut master_key_salt = Vec::new();
master_key_salt.extend_from_slice(key_scope.as_bytes());
master_key_salt.extend_from_slice(&common::u32_to_bytes(full_name.len() as u32));
master_key_salt.extend_from_slice(full_name.as_bytes());
Some(common::derive_key(master_password.as_bytes(), master_key_salt.as_slice()))
} else {
None
}
}
pub fn password_for_site(master_key: &[u8; common::KEY_LENGTH],
site_name: &str,
site_type: &SiteType,
site_counter: &i32,
site_variant: &SiteVariant,
site_context: &str)
-> Option<String> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let site_scope = scope.unwrap();
let mut input = Vec::new();
input.extend_from_slice(site_scope.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(site_name.len() as u32));
input.extend_from_slice(site_name.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(*site_counter as u32));
if!site_context.is_empty() {
input.extend_from_slice(&common::u32_to_bytes(site_context.len() as u32));
input.extend_from_slice(site_context.as_bytes());
}
let signing_key = hmac::SigningKey::new(&digest::SHA256, master_key);
let output = hmac::sign(&signing_key, input.as_slice());
let site_password_seed = output.as_ref();
let template = common::template_for_type(site_type, &site_password_seed[0]);
if template.is_some() {
let template = template.unwrap();
let template_bytes = template.as_bytes();
let password = template_bytes
.iter()
.zip(1..template_bytes.len() + 1)
.map(|pair| {
common::character_from_class(*pair.0, site_password_seed[pair.1] as usize)
})
.collect::<Vec<Option<u8>>>();
if password.iter().any(|c| c.is_none()) {
None
} else {
Some(String::from_utf8(password.iter().map(|c| c.unwrap()).collect::<Vec<u8>>())
.unwrap())
}
} else {
None
}
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::{SiteType, SiteVariant};
#[test]
fn get_master_key_for_password() {
let actual = master_key("test", "pass", &SiteVariant::Password)
.unwrap()
.to_vec();
assert_eq!(actual,
vec![51, 253, 82, 252, 68, 97, 191, 162, 127, 73, 153, 160, 52, 128, 204, 4, 183,
190, 106, 180, 68, 126, 100, 94, 132, 141, 99, 143, 106, 211, 94, 245, 245,
255, 195, 72, 28, 128, 197, 51, 99, 27, 125, 24, 54, 193, 223, 230, 118,
181, 225, 236, 171, 104, 9, 158, 214, 23, 166, 89, 36, 174, 64, 112]);
}
#[test]
fn get_master_password() {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
&(1 as i32),
&SiteVariant::Password,
"");
assert_eq!(actual, Some(String::from("QsKBWAYdT9dh^AOGVA0.")));
}
} | * You should have received a copy of the GNU General Public License
* along with Master Password. If not, see <http://www.gnu.org/licenses/>.
*/
use self::ring::{digest, hmac}; | random_line_split |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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.
*
* Master Password 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 Master Password. If not, see <http://www.gnu.org/licenses/>.
*/
use self::ring::{digest, hmac};
use common;
use common::{SiteVariant, SiteType};
pub fn master_key(full_name: &str,
master_password: &str,
site_variant: &SiteVariant)
-> Option<[u8; common::KEY_LENGTH]> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let key_scope = scope.unwrap();
let mut master_key_salt = Vec::new();
master_key_salt.extend_from_slice(key_scope.as_bytes());
master_key_salt.extend_from_slice(&common::u32_to_bytes(full_name.len() as u32));
master_key_salt.extend_from_slice(full_name.as_bytes());
Some(common::derive_key(master_password.as_bytes(), master_key_salt.as_slice()))
} else {
None
}
}
pub fn password_for_site(master_key: &[u8; common::KEY_LENGTH],
site_name: &str,
site_type: &SiteType,
site_counter: &i32,
site_variant: &SiteVariant,
site_context: &str)
-> Option<String> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
let site_scope = scope.unwrap();
let mut input = Vec::new();
input.extend_from_slice(site_scope.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(site_name.len() as u32));
input.extend_from_slice(site_name.as_bytes());
input.extend_from_slice(&common::u32_to_bytes(*site_counter as u32));
if!site_context.is_empty() {
input.extend_from_slice(&common::u32_to_bytes(site_context.len() as u32));
input.extend_from_slice(site_context.as_bytes());
}
let signing_key = hmac::SigningKey::new(&digest::SHA256, master_key);
let output = hmac::sign(&signing_key, input.as_slice());
let site_password_seed = output.as_ref();
let template = common::template_for_type(site_type, &site_password_seed[0]);
if template.is_some() {
let template = template.unwrap();
let template_bytes = template.as_bytes();
let password = template_bytes
.iter()
.zip(1..template_bytes.len() + 1)
.map(|pair| {
common::character_from_class(*pair.0, site_password_seed[pair.1] as usize)
})
.collect::<Vec<Option<u8>>>();
if password.iter().any(|c| c.is_none()) | else {
Some(String::from_utf8(password.iter().map(|c| c.unwrap()).collect::<Vec<u8>>())
.unwrap())
}
} else {
None
}
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::{SiteType, SiteVariant};
#[test]
fn get_master_key_for_password() {
let actual = master_key("test", "pass", &SiteVariant::Password)
.unwrap()
.to_vec();
assert_eq!(actual,
vec![51, 253, 82, 252, 68, 97, 191, 162, 127, 73, 153, 160, 52, 128, 204, 4, 183,
190, 106, 180, 68, 126, 100, 94, 132, 141, 99, 143, 106, 211, 94, 245, 245,
255, 195, 72, 28, 128, 197, 51, 99, 27, 125, 24, 54, 193, 223, 230, 118,
181, 225, 236, 171, 104, 9, 158, 214, 23, 166, 89, 36, 174, 64, 112]);
}
#[test]
fn get_master_password() {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
&(1 as i32),
&SiteVariant::Password,
"");
assert_eq!(actual, Some(String::from("QsKBWAYdT9dh^AOGVA0.")));
}
}
| {
None
} | conditional_block |
compiletest.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.
#![crate_type = "bin"]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(int_uint)]
#![feature(old_io)]
#![feature(old_path)]
#![feature(rustc_private)]
#![feature(unboxed_closures)]
#![feature(std_misc)]
#![feature(test)]
#![feature(unicode)]
#![feature(env)]
#![deny(warnings)]
extern crate test;
extern crate getopts;
#[macro_use]
extern crate log;
use std::env;
use std::old_io;
use std::old_io::fs;
use std::thunk::Thunk;
use getopts::{optopt, optflag, reqopt};
use common::Config;
use common::{Pretty, DebugInfoGdb, DebugInfoLldb, Codegen};
use util::logv;
pub mod procsrv;
pub mod util;
pub mod header;
pub mod runtest;
pub mod common;
pub mod errors;
pub fn main() {
let config = parse_config(env::args().collect());
if config.valgrind_path.is_none() && config.force_valgrind {
panic!("Can't find Valgrind to run Valgrind tests");
}
log_config(&config);
run_tests(&config);
}
pub fn parse_config(args: Vec<String> ) -> Config {
let groups : Vec<getopts::OptGroup> =
vec!(reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"),
reqopt("", "run-lib-path", "path to target shared libraries", "PATH"),
reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"),
optopt("", "clang-path", "path to executable for codegen tests", "PATH"),
optopt("", "valgrind-path", "path to Valgrind executable for Valgrind tests", "PROGRAM"),
optflag("", "force-valgrind", "fail if Valgrind tests cannot be run under Valgrind"),
optopt("", "llvm-bin-path", "path to directory holding llvm binaries", "DIR"),
reqopt("", "src-base", "directory to scan for test files", "PATH"),
reqopt("", "build-base", "directory to deposit test outputs", "PATH"),
reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"),
reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"),
reqopt("", "mode", "which sort of compile tests to run",
"(compile-fail|run-fail|run-pass|run-pass-valgrind|pretty|debug-info)"),
optflag("", "ignored", "run tests marked as ignored"),
optopt("", "runtool", "supervisor program to run tests under \
(eg. emulator, valgrind)", "PROGRAM"),
optopt("", "host-rustcflags", "flags to pass to rustc for host", "FLAGS"),
optopt("", "target-rustcflags", "flags to pass to rustc for target", "FLAGS"),
optflag("", "verbose", "run tests verbosely, showing all output"),
optopt("", "logfile", "file to log test execution to", "FILE"),
optflag("", "jit", "run tests under the JIT"),
optopt("", "target", "the target to build for", "TARGET"),
optopt("", "host", "the host to build for", "HOST"),
optopt("", "gdb-version", "the version of GDB used", "VERSION STRING"),
optopt("", "lldb-version", "the version of LLDB used", "VERSION STRING"),
optopt("", "android-cross-path", "Android NDK standalone path", "PATH"),
optopt("", "adb-path", "path to the android debugger", "PATH"),
optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"),
optopt("", "lldb-python-dir", "directory containing LLDB's python module", "PATH"),
optflag("h", "help", "show this message"));
assert!(!args.is_empty());
let argv0 = args[0].clone();
let args_ = args.tail();
if args[1] == "-h" || args[1] == "--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
let matches =
&match getopts::getopts(args_, &groups) {
Ok(m) => m,
Err(f) => panic!("{:?}", f)
};
if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
match m.opt_str(nm) {
Some(s) => Path::new(s),
None => panic!("no option (=path) found for {}", nm),
}
}
let filter = if!matches.free.is_empty() {
Some(matches.free[0].clone())
} else {
None
};
Config {
compile_lib_path: matches.opt_str("compile-lib-path").unwrap(),
run_lib_path: matches.opt_str("run-lib-path").unwrap(),
rustc_path: opt_path(matches, "rustc-path"),
clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)),
valgrind_path: matches.opt_str("valgrind-path"),
force_valgrind: matches.opt_present("force-valgrind"),
llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)),
src_base: opt_path(matches, "src-base"),
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
stage_id: matches.opt_str("stage-id").unwrap(),
mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"),
run_ignored: matches.opt_present("ignored"),
filter: filter,
logfile: matches.opt_str("logfile").map(|s| Path::new(s)),
runtool: matches.opt_str("runtool"),
host_rustcflags: matches.opt_str("host-rustcflags"),
target_rustcflags: matches.opt_str("target-rustcflags"),
jit: matches.opt_present("jit"),
target: opt_str2(matches.opt_str("target")),
host: opt_str2(matches.opt_str("host")),
gdb_version: extract_gdb_version(matches.opt_str("gdb-version")),
lldb_version: extract_lldb_version(matches.opt_str("lldb-version")),
android_cross_path: opt_path(matches, "android-cross-path"),
adb_path: opt_str2(matches.opt_str("adb-path")),
adb_test_dir: format!("{}/{}",
opt_str2(matches.opt_str("adb-test-dir")),
opt_str2(matches.opt_str("target"))),
adb_device_status:
opt_str2(matches.opt_str("target")).contains("android") &&
"(none)"!= opt_str2(matches.opt_str("adb-test-dir")) &&
!opt_str2(matches.opt_str("adb-test-dir")).is_empty(),
lldb_python_dir: matches.opt_str("lldb-python-dir"),
verbose: matches.opt_present("verbose"),
}
}
pub fn log_config(config: &Config) {
let c = config;
logv(c, format!("configuration:"));
logv(c, format!("compile_lib_path: {:?}", config.compile_lib_path));
logv(c, format!("run_lib_path: {:?}", config.run_lib_path));
logv(c, format!("rustc_path: {:?}", config.rustc_path.display()));
logv(c, format!("src_base: {:?}", config.src_base.display()));
logv(c, format!("build_base: {:?}", config.build_base.display()));
logv(c, format!("stage_id: {}", config.stage_id));
logv(c, format!("mode: {}", config.mode));
logv(c, format!("run_ignored: {}", config.run_ignored));
logv(c, format!("filter: {}",
opt_str(&config.filter
.as_ref()
.map(|re| re.to_string()))));
logv(c, format!("runtool: {}", opt_str(&config.runtool)));
logv(c, format!("host-rustcflags: {}",
opt_str(&config.host_rustcflags)));
logv(c, format!("target-rustcflags: {}",
opt_str(&config.target_rustcflags)));
logv(c, format!("jit: {}", config.jit));
logv(c, format!("target: {}", config.target));
logv(c, format!("host: {}", config.host));
logv(c, format!("android-cross-path: {:?}",
config.android_cross_path.display()));
logv(c, format!("adb_path: {:?}", config.adb_path));
logv(c, format!("adb_test_dir: {:?}", config.adb_test_dir));
logv(c, format!("adb_device_status: {}",
config.adb_device_status));
logv(c, format!("verbose: {}", config.verbose));
logv(c, format!("\n"));
}
pub fn | <'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => s,
}
}
pub fn opt_str2(maybestr: Option<String>) -> String {
match maybestr {
None => "(none)".to_string(),
Some(s) => s,
}
}
pub fn run_tests(config: &Config) {
if config.target.contains("android") {
match config.mode {
DebugInfoGdb => {
println!("{} debug-info test uses tcp 5039 port.\
please reserve it", config.target);
}
_ =>{}
}
// android debug-info test uses remote debugger
// so, we test 1 task at once.
// also trying to isolate problems with adb_run_wrapper.sh ilooping
env::set_var("RUST_TEST_TASKS","1");
}
match config.mode {
DebugInfoLldb => {
// Some older versions of LLDB seem to have problems with multiple
// instances running in parallel, so only run one test task at a
// time.
env::set_var("RUST_TEST_TASKS", "1");
}
_ => { /* proceed */ }
}
let opts = test_opts(config);
let tests = make_tests(config);
// sadly osx needs some file descriptor limits raised for running tests in
// parallel (especially when we have lots and lots of child processes).
// For context, see #8904
old_io::test::raise_fd_limit();
// Prevent issue #21352 UAC blocking.exe containing 'patch' etc. on Windows
// If #11207 is resolved (adding manifest to.exe) this becomes unnecessary
env::set_var("__COMPAT_LAYER", "RunAsInvoker");
let res = test::run_tests_console(&opts, tests.into_iter().collect());
match res {
Ok(true) => {}
Ok(false) => panic!("Some tests failed"),
Err(e) => {
println!("I/O failure during tests: {:?}", e);
}
}
}
pub fn test_opts(config: &Config) -> test::TestOpts {
test::TestOpts {
filter: match config.filter {
None => None,
Some(ref filter) => Some(filter.clone()),
},
run_ignored: config.run_ignored,
logfile: config.logfile.clone(),
run_tests: true,
run_benchmarks: true,
nocapture: false,
color: test::AutoColor,
}
}
pub fn make_tests(config: &Config) -> Vec<test::TestDescAndFn> {
debug!("making tests from {:?}",
config.src_base.display());
let mut tests = Vec::new();
let dirs = fs::readdir(&config.src_base).unwrap();
for file in &dirs {
let file = file.clone();
debug!("inspecting file {:?}", file.display());
if is_test(config, &file) {
let t = make_test(config, &file, || {
match config.mode {
Codegen => make_metrics_test_closure(config, &file),
_ => make_test_closure(config, &file)
}
});
tests.push(t)
}
}
tests
}
pub fn is_test(config: &Config, testfile: &Path) -> bool {
// Pretty-printer does not work with.rc files yet
let valid_extensions =
match config.mode {
Pretty => vec!(".rs".to_string()),
_ => vec!(".rc".to_string(), ".rs".to_string())
};
let invalid_prefixes = vec!(".".to_string(), "#".to_string(), "~".to_string());
let name = testfile.filename_str().unwrap();
let mut valid = false;
for ext in &valid_extensions {
if name.ends_with(ext) {
valid = true;
}
}
for pre in &invalid_prefixes {
if name.starts_with(pre) {
valid = false;
}
}
return valid;
}
pub fn make_test<F>(config: &Config, testfile: &Path, f: F) -> test::TestDescAndFn where
F: FnOnce() -> test::TestFn,
{
test::TestDescAndFn {
desc: test::TestDesc {
name: make_test_name(config, testfile),
ignore: header::is_test_ignored(config, testfile),
should_fail: test::ShouldFail::No,
},
testfn: f(),
}
}
pub fn make_test_name(config: &Config, testfile: &Path) -> test::TestName {
// Try to elide redundant long paths
fn shorten(path: &Path) -> String {
let filename = path.filename_str();
let p = path.dir_path();
let dir = p.filename_str();
format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
}
test::DynTestName(format!("[{}] {}", config.mode, shorten(testfile)))
}
pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
test::DynTestFn(Thunk::new(move || {
runtest::run(config, testfile)
}))
}
pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
test::DynMetricFn(box move |mm: &mut test::MetricMap| {
runtest::run_metrics(config, testfile, mm)
})
}
fn extract_gdb_version(full_version_line: Option<String>) -> Option<String> {
match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
let full_version_line = full_version_line.trim();
// used to be a regex "(^|[^0-9])([0-9]\.[0-9])([^0-9]|$)"
for (pos, c) in full_version_line.char_indices() {
if!c.is_digit(10) { continue }
if pos + 2 >= full_version_line.len() { continue }
if full_version_line.char_at(pos + 1)!= '.' { continue }
if!full_version_line.char_at(pos + 2).is_digit(10) { continue }
if pos > 0 && full_version_line.char_at_reverse(pos).is_digit(10) {
continue
}
if pos + 3 < full_version_line.len() &&
full_version_line.char_at(pos + 3).is_digit(10) {
continue
}
return Some(full_version_line[pos..pos+3].to_string());
}
println!("Could not extract GDB version from line '{}'",
full_version_line);
None
},
_ => None
}
}
fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {
// Extract the major LLDB version from the given version string.
// LLDB version strings are different for Apple and non-Apple platforms.
// At the moment, this function only supports the Apple variant, which looks
// like this:
//
// LLDB-179.5 (older versions)
// lldb-300.2.51 (new versions)
//
// We are only interested in the major version number, so this function
// will return `Some("179")` and `Some("300")` respectively.
match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
let full_version_line = full_version_line.trim();
for (pos, l) in full_version_line.char_indices() {
if l!= 'l' && l!= 'L' { continue }
if pos + 5 >= full_version_line.len() { continue }
let l = full_version_line.char_at(pos + 1);
if l!= 'l' && l!= 'L' { continue }
let d = full_version_line.char_at(pos + 2);
if d!= 'd' && d!= 'D' { continue }
let b = full_version_line.char_at(pos + 3);
if b!= 'b' && b!= 'B' { continue }
let dash = full_version_line.char_at(pos + 4);
if dash!= '-' { continue }
let vers = full_version_line[pos + 5..].chars().take_while(|c| {
c.is_digit(10)
}).collect::<String>();
if vers.len() > 0 { return Some(vers) }
}
println!("Could not extract LLDB version from line '{}'",
full_version_line);
None
},
_ => None
}
}
| opt_str | identifier_name |
compiletest.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.
#![crate_type = "bin"]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(int_uint)]
#![feature(old_io)]
#![feature(old_path)]
#![feature(rustc_private)]
#![feature(unboxed_closures)]
#![feature(std_misc)]
#![feature(test)]
#![feature(unicode)]
#![feature(env)]
#![deny(warnings)]
extern crate test;
extern crate getopts;
#[macro_use]
extern crate log;
use std::env;
use std::old_io;
use std::old_io::fs;
use std::thunk::Thunk;
use getopts::{optopt, optflag, reqopt};
use common::Config;
use common::{Pretty, DebugInfoGdb, DebugInfoLldb, Codegen};
use util::logv;
pub mod procsrv;
pub mod util;
pub mod header;
pub mod runtest;
pub mod common;
pub mod errors;
pub fn main() {
let config = parse_config(env::args().collect());
if config.valgrind_path.is_none() && config.force_valgrind {
panic!("Can't find Valgrind to run Valgrind tests");
}
log_config(&config);
run_tests(&config);
}
pub fn parse_config(args: Vec<String> ) -> Config {
let groups : Vec<getopts::OptGroup> =
vec!(reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"),
reqopt("", "run-lib-path", "path to target shared libraries", "PATH"),
reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"),
optopt("", "clang-path", "path to executable for codegen tests", "PATH"),
optopt("", "valgrind-path", "path to Valgrind executable for Valgrind tests", "PROGRAM"),
optflag("", "force-valgrind", "fail if Valgrind tests cannot be run under Valgrind"),
optopt("", "llvm-bin-path", "path to directory holding llvm binaries", "DIR"),
reqopt("", "src-base", "directory to scan for test files", "PATH"),
reqopt("", "build-base", "directory to deposit test outputs", "PATH"),
reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"),
reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"),
reqopt("", "mode", "which sort of compile tests to run",
"(compile-fail|run-fail|run-pass|run-pass-valgrind|pretty|debug-info)"),
optflag("", "ignored", "run tests marked as ignored"),
optopt("", "runtool", "supervisor program to run tests under \
(eg. emulator, valgrind)", "PROGRAM"),
optopt("", "host-rustcflags", "flags to pass to rustc for host", "FLAGS"),
optopt("", "target-rustcflags", "flags to pass to rustc for target", "FLAGS"),
optflag("", "verbose", "run tests verbosely, showing all output"),
optopt("", "logfile", "file to log test execution to", "FILE"),
optflag("", "jit", "run tests under the JIT"),
optopt("", "target", "the target to build for", "TARGET"),
optopt("", "host", "the host to build for", "HOST"),
optopt("", "gdb-version", "the version of GDB used", "VERSION STRING"),
optopt("", "lldb-version", "the version of LLDB used", "VERSION STRING"),
optopt("", "android-cross-path", "Android NDK standalone path", "PATH"),
optopt("", "adb-path", "path to the android debugger", "PATH"),
optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"),
optopt("", "lldb-python-dir", "directory containing LLDB's python module", "PATH"),
optflag("h", "help", "show this message"));
assert!(!args.is_empty());
let argv0 = args[0].clone();
let args_ = args.tail();
if args[1] == "-h" || args[1] == "--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
let matches =
&match getopts::getopts(args_, &groups) {
Ok(m) => m,
Err(f) => panic!("{:?}", f)
};
if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
match m.opt_str(nm) {
Some(s) => Path::new(s),
None => panic!("no option (=path) found for {}", nm),
}
}
let filter = if!matches.free.is_empty() {
Some(matches.free[0].clone())
} else {
None
};
Config {
compile_lib_path: matches.opt_str("compile-lib-path").unwrap(),
run_lib_path: matches.opt_str("run-lib-path").unwrap(),
rustc_path: opt_path(matches, "rustc-path"),
clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)),
valgrind_path: matches.opt_str("valgrind-path"),
force_valgrind: matches.opt_present("force-valgrind"),
llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)),
src_base: opt_path(matches, "src-base"),
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
stage_id: matches.opt_str("stage-id").unwrap(),
mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"),
run_ignored: matches.opt_present("ignored"),
filter: filter,
logfile: matches.opt_str("logfile").map(|s| Path::new(s)),
runtool: matches.opt_str("runtool"),
host_rustcflags: matches.opt_str("host-rustcflags"),
target_rustcflags: matches.opt_str("target-rustcflags"),
jit: matches.opt_present("jit"),
target: opt_str2(matches.opt_str("target")),
host: opt_str2(matches.opt_str("host")),
gdb_version: extract_gdb_version(matches.opt_str("gdb-version")),
lldb_version: extract_lldb_version(matches.opt_str("lldb-version")),
android_cross_path: opt_path(matches, "android-cross-path"),
adb_path: opt_str2(matches.opt_str("adb-path")),
adb_test_dir: format!("{}/{}",
opt_str2(matches.opt_str("adb-test-dir")),
opt_str2(matches.opt_str("target"))),
adb_device_status:
opt_str2(matches.opt_str("target")).contains("android") &&
"(none)"!= opt_str2(matches.opt_str("adb-test-dir")) &&
!opt_str2(matches.opt_str("adb-test-dir")).is_empty(),
lldb_python_dir: matches.opt_str("lldb-python-dir"),
verbose: matches.opt_present("verbose"),
}
}
pub fn log_config(config: &Config) {
let c = config;
logv(c, format!("configuration:"));
logv(c, format!("compile_lib_path: {:?}", config.compile_lib_path));
logv(c, format!("run_lib_path: {:?}", config.run_lib_path));
logv(c, format!("rustc_path: {:?}", config.rustc_path.display()));
logv(c, format!("src_base: {:?}", config.src_base.display()));
logv(c, format!("build_base: {:?}", config.build_base.display()));
logv(c, format!("stage_id: {}", config.stage_id));
logv(c, format!("mode: {}", config.mode));
logv(c, format!("run_ignored: {}", config.run_ignored));
logv(c, format!("filter: {}",
opt_str(&config.filter
.as_ref()
.map(|re| re.to_string()))));
logv(c, format!("runtool: {}", opt_str(&config.runtool)));
logv(c, format!("host-rustcflags: {}",
opt_str(&config.host_rustcflags)));
logv(c, format!("target-rustcflags: {}",
opt_str(&config.target_rustcflags)));
logv(c, format!("jit: {}", config.jit));
logv(c, format!("target: {}", config.target));
logv(c, format!("host: {}", config.host));
logv(c, format!("android-cross-path: {:?}",
config.android_cross_path.display()));
logv(c, format!("adb_path: {:?}", config.adb_path));
logv(c, format!("adb_test_dir: {:?}", config.adb_test_dir));
logv(c, format!("adb_device_status: {}",
config.adb_device_status));
logv(c, format!("verbose: {}", config.verbose));
logv(c, format!("\n"));
}
pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => s,
}
}
pub fn opt_str2(maybestr: Option<String>) -> String {
match maybestr {
None => "(none)".to_string(),
Some(s) => s,
}
}
pub fn run_tests(config: &Config) {
if config.target.contains("android") {
match config.mode {
DebugInfoGdb => {
println!("{} debug-info test uses tcp 5039 port.\
please reserve it", config.target);
}
_ =>{}
}
// android debug-info test uses remote debugger
// so, we test 1 task at once.
// also trying to isolate problems with adb_run_wrapper.sh ilooping
env::set_var("RUST_TEST_TASKS","1");
}
match config.mode {
DebugInfoLldb => {
// Some older versions of LLDB seem to have problems with multiple
// instances running in parallel, so only run one test task at a
// time.
env::set_var("RUST_TEST_TASKS", "1");
}
_ => { /* proceed */ }
}
let opts = test_opts(config);
let tests = make_tests(config);
// sadly osx needs some file descriptor limits raised for running tests in
// parallel (especially when we have lots and lots of child processes).
// For context, see #8904
old_io::test::raise_fd_limit();
// Prevent issue #21352 UAC blocking.exe containing 'patch' etc. on Windows
// If #11207 is resolved (adding manifest to.exe) this becomes unnecessary
env::set_var("__COMPAT_LAYER", "RunAsInvoker");
let res = test::run_tests_console(&opts, tests.into_iter().collect());
match res {
Ok(true) => {}
Ok(false) => panic!("Some tests failed"),
Err(e) => {
println!("I/O failure during tests: {:?}", e);
}
}
}
pub fn test_opts(config: &Config) -> test::TestOpts {
test::TestOpts {
filter: match config.filter {
None => None,
Some(ref filter) => Some(filter.clone()),
},
run_ignored: config.run_ignored,
logfile: config.logfile.clone(),
run_tests: true,
run_benchmarks: true,
nocapture: false,
color: test::AutoColor,
}
}
pub fn make_tests(config: &Config) -> Vec<test::TestDescAndFn> {
debug!("making tests from {:?}",
config.src_base.display());
let mut tests = Vec::new();
let dirs = fs::readdir(&config.src_base).unwrap();
for file in &dirs {
let file = file.clone();
debug!("inspecting file {:?}", file.display());
if is_test(config, &file) {
let t = make_test(config, &file, || {
match config.mode {
Codegen => make_metrics_test_closure(config, &file),
_ => make_test_closure(config, &file)
}
});
tests.push(t)
}
}
tests
}
pub fn is_test(config: &Config, testfile: &Path) -> bool {
// Pretty-printer does not work with.rc files yet
let valid_extensions =
match config.mode {
Pretty => vec!(".rs".to_string()),
_ => vec!(".rc".to_string(), ".rs".to_string())
};
let invalid_prefixes = vec!(".".to_string(), "#".to_string(), "~".to_string());
let name = testfile.filename_str().unwrap();
let mut valid = false;
for ext in &valid_extensions {
if name.ends_with(ext) {
valid = true;
}
}
for pre in &invalid_prefixes {
if name.starts_with(pre) {
valid = false;
}
}
return valid;
}
pub fn make_test<F>(config: &Config, testfile: &Path, f: F) -> test::TestDescAndFn where
F: FnOnce() -> test::TestFn,
{
test::TestDescAndFn {
desc: test::TestDesc {
name: make_test_name(config, testfile),
ignore: header::is_test_ignored(config, testfile),
should_fail: test::ShouldFail::No,
},
testfn: f(),
}
}
pub fn make_test_name(config: &Config, testfile: &Path) -> test::TestName {
// Try to elide redundant long paths
fn shorten(path: &Path) -> String |
test::DynTestName(format!("[{}] {}", config.mode, shorten(testfile)))
}
pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
test::DynTestFn(Thunk::new(move || {
runtest::run(config, testfile)
}))
}
pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
test::DynMetricFn(box move |mm: &mut test::MetricMap| {
runtest::run_metrics(config, testfile, mm)
})
}
fn extract_gdb_version(full_version_line: Option<String>) -> Option<String> {
match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
let full_version_line = full_version_line.trim();
// used to be a regex "(^|[^0-9])([0-9]\.[0-9])([^0-9]|$)"
for (pos, c) in full_version_line.char_indices() {
if!c.is_digit(10) { continue }
if pos + 2 >= full_version_line.len() { continue }
if full_version_line.char_at(pos + 1)!= '.' { continue }
if!full_version_line.char_at(pos + 2).is_digit(10) { continue }
if pos > 0 && full_version_line.char_at_reverse(pos).is_digit(10) {
continue
}
if pos + 3 < full_version_line.len() &&
full_version_line.char_at(pos + 3).is_digit(10) {
continue
}
return Some(full_version_line[pos..pos+3].to_string());
}
println!("Could not extract GDB version from line '{}'",
full_version_line);
None
},
_ => None
}
}
fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {
// Extract the major LLDB version from the given version string.
// LLDB version strings are different for Apple and non-Apple platforms.
// At the moment, this function only supports the Apple variant, which looks
// like this:
//
// LLDB-179.5 (older versions)
// lldb-300.2.51 (new versions)
//
// We are only interested in the major version number, so this function
// will return `Some("179")` and `Some("300")` respectively.
match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
let full_version_line = full_version_line.trim();
for (pos, l) in full_version_line.char_indices() {
if l!= 'l' && l!= 'L' { continue }
if pos + 5 >= full_version_line.len() { continue }
let l = full_version_line.char_at(pos + 1);
if l!= 'l' && l!= 'L' { continue }
let d = full_version_line.char_at(pos + 2);
if d!= 'd' && d!= 'D' { continue }
let b = full_version_line.char_at(pos + 3);
if b!= 'b' && b!= 'B' { continue }
let dash = full_version_line.char_at(pos + 4);
if dash!= '-' { continue }
let vers = full_version_line[pos + 5..].chars().take_while(|c| {
c.is_digit(10)
}).collect::<String>();
if vers.len() > 0 { return Some(vers) }
}
println!("Could not extract LLDB version from line '{}'",
full_version_line);
None
},
_ => None
}
}
| {
let filename = path.filename_str();
let p = path.dir_path();
let dir = p.filename_str();
format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
} | identifier_body |
compiletest.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.
#![crate_type = "bin"]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(int_uint)]
#![feature(old_io)]
#![feature(old_path)]
#![feature(rustc_private)]
#![feature(unboxed_closures)]
#![feature(std_misc)]
#![feature(test)]
#![feature(unicode)]
#![feature(env)]
#![deny(warnings)]
extern crate test;
extern crate getopts;
#[macro_use]
extern crate log;
use std::env;
use std::old_io;
use std::old_io::fs;
use std::thunk::Thunk;
use getopts::{optopt, optflag, reqopt};
use common::Config;
use common::{Pretty, DebugInfoGdb, DebugInfoLldb, Codegen};
use util::logv;
pub mod procsrv;
pub mod util;
pub mod header;
pub mod runtest;
pub mod common;
pub mod errors;
pub fn main() {
let config = parse_config(env::args().collect());
if config.valgrind_path.is_none() && config.force_valgrind {
panic!("Can't find Valgrind to run Valgrind tests");
}
log_config(&config);
run_tests(&config);
}
pub fn parse_config(args: Vec<String> ) -> Config {
let groups : Vec<getopts::OptGroup> =
vec!(reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"),
reqopt("", "run-lib-path", "path to target shared libraries", "PATH"),
reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"),
optopt("", "clang-path", "path to executable for codegen tests", "PATH"),
optopt("", "valgrind-path", "path to Valgrind executable for Valgrind tests", "PROGRAM"),
optflag("", "force-valgrind", "fail if Valgrind tests cannot be run under Valgrind"),
optopt("", "llvm-bin-path", "path to directory holding llvm binaries", "DIR"),
reqopt("", "src-base", "directory to scan for test files", "PATH"),
reqopt("", "build-base", "directory to deposit test outputs", "PATH"),
reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"),
reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"),
reqopt("", "mode", "which sort of compile tests to run",
"(compile-fail|run-fail|run-pass|run-pass-valgrind|pretty|debug-info)"),
optflag("", "ignored", "run tests marked as ignored"),
optopt("", "runtool", "supervisor program to run tests under \
(eg. emulator, valgrind)", "PROGRAM"),
optopt("", "host-rustcflags", "flags to pass to rustc for host", "FLAGS"),
optopt("", "target-rustcflags", "flags to pass to rustc for target", "FLAGS"),
optflag("", "verbose", "run tests verbosely, showing all output"),
optopt("", "logfile", "file to log test execution to", "FILE"),
optflag("", "jit", "run tests under the JIT"),
optopt("", "target", "the target to build for", "TARGET"),
optopt("", "host", "the host to build for", "HOST"),
optopt("", "gdb-version", "the version of GDB used", "VERSION STRING"),
optopt("", "lldb-version", "the version of LLDB used", "VERSION STRING"),
optopt("", "android-cross-path", "Android NDK standalone path", "PATH"),
optopt("", "adb-path", "path to the android debugger", "PATH"),
optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"),
optopt("", "lldb-python-dir", "directory containing LLDB's python module", "PATH"),
optflag("h", "help", "show this message"));
assert!(!args.is_empty());
let argv0 = args[0].clone();
let args_ = args.tail();
if args[1] == "-h" || args[1] == "--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
let matches =
&match getopts::getopts(args_, &groups) {
Ok(m) => m,
Err(f) => panic!("{:?}", f)
};
if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
match m.opt_str(nm) {
Some(s) => Path::new(s),
None => panic!("no option (=path) found for {}", nm),
}
}
let filter = if!matches.free.is_empty() {
Some(matches.free[0].clone())
} else {
None
};
Config {
compile_lib_path: matches.opt_str("compile-lib-path").unwrap(),
run_lib_path: matches.opt_str("run-lib-path").unwrap(),
rustc_path: opt_path(matches, "rustc-path"),
clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)),
valgrind_path: matches.opt_str("valgrind-path"),
force_valgrind: matches.opt_present("force-valgrind"),
llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)),
src_base: opt_path(matches, "src-base"),
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
stage_id: matches.opt_str("stage-id").unwrap(),
mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"),
run_ignored: matches.opt_present("ignored"),
filter: filter,
logfile: matches.opt_str("logfile").map(|s| Path::new(s)),
runtool: matches.opt_str("runtool"),
host_rustcflags: matches.opt_str("host-rustcflags"),
target_rustcflags: matches.opt_str("target-rustcflags"),
jit: matches.opt_present("jit"),
target: opt_str2(matches.opt_str("target")),
host: opt_str2(matches.opt_str("host")),
gdb_version: extract_gdb_version(matches.opt_str("gdb-version")),
lldb_version: extract_lldb_version(matches.opt_str("lldb-version")),
android_cross_path: opt_path(matches, "android-cross-path"),
adb_path: opt_str2(matches.opt_str("adb-path")),
adb_test_dir: format!("{}/{}",
opt_str2(matches.opt_str("adb-test-dir")),
opt_str2(matches.opt_str("target"))),
adb_device_status:
opt_str2(matches.opt_str("target")).contains("android") &&
"(none)"!= opt_str2(matches.opt_str("adb-test-dir")) &&
!opt_str2(matches.opt_str("adb-test-dir")).is_empty(),
lldb_python_dir: matches.opt_str("lldb-python-dir"),
verbose: matches.opt_present("verbose"),
}
}
pub fn log_config(config: &Config) {
let c = config;
logv(c, format!("configuration:"));
logv(c, format!("compile_lib_path: {:?}", config.compile_lib_path));
logv(c, format!("run_lib_path: {:?}", config.run_lib_path));
logv(c, format!("rustc_path: {:?}", config.rustc_path.display()));
logv(c, format!("src_base: {:?}", config.src_base.display()));
logv(c, format!("build_base: {:?}", config.build_base.display()));
logv(c, format!("stage_id: {}", config.stage_id));
logv(c, format!("mode: {}", config.mode));
logv(c, format!("run_ignored: {}", config.run_ignored));
logv(c, format!("filter: {}",
opt_str(&config.filter
.as_ref()
.map(|re| re.to_string()))));
logv(c, format!("runtool: {}", opt_str(&config.runtool)));
logv(c, format!("host-rustcflags: {}",
opt_str(&config.host_rustcflags)));
logv(c, format!("target-rustcflags: {}",
opt_str(&config.target_rustcflags)));
logv(c, format!("jit: {}", config.jit));
logv(c, format!("target: {}", config.target));
logv(c, format!("host: {}", config.host));
logv(c, format!("android-cross-path: {:?}",
config.android_cross_path.display()));
logv(c, format!("adb_path: {:?}", config.adb_path));
logv(c, format!("adb_test_dir: {:?}", config.adb_test_dir));
logv(c, format!("adb_device_status: {}",
config.adb_device_status));
logv(c, format!("verbose: {}", config.verbose));
logv(c, format!("\n"));
}
pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => s,
}
}
pub fn opt_str2(maybestr: Option<String>) -> String {
match maybestr {
None => "(none)".to_string(),
Some(s) => s,
}
}
pub fn run_tests(config: &Config) {
if config.target.contains("android") {
match config.mode {
DebugInfoGdb => {
println!("{} debug-info test uses tcp 5039 port.\
please reserve it", config.target);
}
_ =>{}
}
// android debug-info test uses remote debugger
// so, we test 1 task at once.
// also trying to isolate problems with adb_run_wrapper.sh ilooping
env::set_var("RUST_TEST_TASKS","1");
}
match config.mode {
DebugInfoLldb => {
// Some older versions of LLDB seem to have problems with multiple
// instances running in parallel, so only run one test task at a
// time.
env::set_var("RUST_TEST_TASKS", "1");
}
_ => { /* proceed */ }
}
let opts = test_opts(config);
let tests = make_tests(config);
// sadly osx needs some file descriptor limits raised for running tests in
// parallel (especially when we have lots and lots of child processes).
// For context, see #8904
old_io::test::raise_fd_limit();
// Prevent issue #21352 UAC blocking.exe containing 'patch' etc. on Windows
// If #11207 is resolved (adding manifest to.exe) this becomes unnecessary
env::set_var("__COMPAT_LAYER", "RunAsInvoker");
let res = test::run_tests_console(&opts, tests.into_iter().collect());
match res {
Ok(true) => {}
Ok(false) => panic!("Some tests failed"),
Err(e) => {
println!("I/O failure during tests: {:?}", e);
}
}
}
pub fn test_opts(config: &Config) -> test::TestOpts {
test::TestOpts {
filter: match config.filter {
None => None,
Some(ref filter) => Some(filter.clone()),
},
run_ignored: config.run_ignored,
logfile: config.logfile.clone(),
run_tests: true,
run_benchmarks: true,
nocapture: false,
color: test::AutoColor,
}
}
pub fn make_tests(config: &Config) -> Vec<test::TestDescAndFn> {
debug!("making tests from {:?}",
config.src_base.display());
let mut tests = Vec::new();
let dirs = fs::readdir(&config.src_base).unwrap();
for file in &dirs {
let file = file.clone();
debug!("inspecting file {:?}", file.display());
if is_test(config, &file) {
let t = make_test(config, &file, || {
match config.mode {
Codegen => make_metrics_test_closure(config, &file),
_ => make_test_closure(config, &file)
}
});
tests.push(t)
}
}
tests
}
pub fn is_test(config: &Config, testfile: &Path) -> bool {
// Pretty-printer does not work with.rc files yet
let valid_extensions =
match config.mode {
Pretty => vec!(".rs".to_string()),
_ => vec!(".rc".to_string(), ".rs".to_string())
};
let invalid_prefixes = vec!(".".to_string(), "#".to_string(), "~".to_string());
let name = testfile.filename_str().unwrap();
let mut valid = false;
for ext in &valid_extensions {
if name.ends_with(ext) {
valid = true;
}
}
for pre in &invalid_prefixes {
if name.starts_with(pre) {
valid = false;
}
}
return valid;
}
pub fn make_test<F>(config: &Config, testfile: &Path, f: F) -> test::TestDescAndFn where
F: FnOnce() -> test::TestFn,
{
test::TestDescAndFn {
desc: test::TestDesc {
name: make_test_name(config, testfile),
ignore: header::is_test_ignored(config, testfile),
should_fail: test::ShouldFail::No,
},
testfn: f(),
}
}
pub fn make_test_name(config: &Config, testfile: &Path) -> test::TestName {
// Try to elide redundant long paths
fn shorten(path: &Path) -> String {
let filename = path.filename_str();
let p = path.dir_path();
let dir = p.filename_str();
format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
}
test::DynTestName(format!("[{}] {}", config.mode, shorten(testfile)))
}
pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
test::DynTestFn(Thunk::new(move || {
runtest::run(config, testfile)
}))
}
pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
test::DynMetricFn(box move |mm: &mut test::MetricMap| {
runtest::run_metrics(config, testfile, mm)
})
}
fn extract_gdb_version(full_version_line: Option<String>) -> Option<String> {
match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
let full_version_line = full_version_line.trim();
// used to be a regex "(^|[^0-9])([0-9]\.[0-9])([^0-9]|$)"
for (pos, c) in full_version_line.char_indices() {
if!c.is_digit(10) { continue }
if pos + 2 >= full_version_line.len() { continue }
if full_version_line.char_at(pos + 1)!= '.' { continue }
if!full_version_line.char_at(pos + 2).is_digit(10) { continue }
if pos > 0 && full_version_line.char_at_reverse(pos).is_digit(10) {
continue
}
if pos + 3 < full_version_line.len() &&
full_version_line.char_at(pos + 3).is_digit(10) {
continue
}
return Some(full_version_line[pos..pos+3].to_string());
}
println!("Could not extract GDB version from line '{}'", | },
_ => None
}
}
fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {
// Extract the major LLDB version from the given version string.
// LLDB version strings are different for Apple and non-Apple platforms.
// At the moment, this function only supports the Apple variant, which looks
// like this:
//
// LLDB-179.5 (older versions)
// lldb-300.2.51 (new versions)
//
// We are only interested in the major version number, so this function
// will return `Some("179")` and `Some("300")` respectively.
match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
let full_version_line = full_version_line.trim();
for (pos, l) in full_version_line.char_indices() {
if l!= 'l' && l!= 'L' { continue }
if pos + 5 >= full_version_line.len() { continue }
let l = full_version_line.char_at(pos + 1);
if l!= 'l' && l!= 'L' { continue }
let d = full_version_line.char_at(pos + 2);
if d!= 'd' && d!= 'D' { continue }
let b = full_version_line.char_at(pos + 3);
if b!= 'b' && b!= 'B' { continue }
let dash = full_version_line.char_at(pos + 4);
if dash!= '-' { continue }
let vers = full_version_line[pos + 5..].chars().take_while(|c| {
c.is_digit(10)
}).collect::<String>();
if vers.len() > 0 { return Some(vers) }
}
println!("Could not extract LLDB version from line '{}'",
full_version_line);
None
},
_ => None
}
} | full_version_line);
None | random_line_split |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct BitDistributorOutputType {
weight: usize, // 0 means a tiny output_type
max_bits: Option<usize>,
}
impl BitDistributorOutputType {
/// Creates a normal output with a specified weight.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `weight` is zero.
///
/// The corresponding element grows as a power of $i$. See the `BitDistributor` documentation
/// for more.
pub fn normal(weight: usize) -> BitDistributorOutputType {
assert_ne!(weight, 0);
BitDistributorOutputType {
weight,
max_bits: None,
}
}
/// Creates a tiny output.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// The corresponding element grows logarithmically. See the `BitDistributor` documentation for
/// more.
pub const fn tiny() -> BitDistributorOutputType {
BitDistributorOutputType {
weight: 0,
max_bits: None,
}
}
}
/// `BitDistributor` helps generate tuples exhaustively.
///
/// Think of `counter` as the bits of an integer. It's initialized to zero (all `false`s), and as
/// it's repeatedly incremented, it eventually takes on every 64-bit value.
///
/// `output_types` is a list of $n$ configuration structs that, together, specify how to generate an
/// n-element tuple of unsigned integers. Calling `get_output` repeatedly, passing in 0 through
/// $n - 1$ as `index`, distributes the bits of `counter` into a tuple.
///
/// This is best shown with an example. If `output_types` is set to
/// `[BitDistributorOutputType::normal(1); 2]`, the distributor will generate all pairs of unsigned
/// integers. A pair may be extracted by calling `get_output(0)` and `get_output(1)`; then `counter`
/// may be incremented to create the next pair. In this case, the pairs will be
/// $(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1), \ldots$.
///
/// If you think of these pairs as coordinates in the $xy$-plane, they are traversed along a Z-order
/// curve. Every pair of unsigned integers will be generated exactly once.
///
/// In general, setting `output_types` to `[BitDistributorOutputType::normal(1); n]` will generate
/// $n$-tuples. The elements of the tuples will be very roughly the same size, in the sense that
/// each element will grow as $O(\sqrt\[n\]{i})$, where $i$ is the counter. Sometimes we want the
/// elements to grow at different rates. To accomplish this, we can change the weights of the output
/// types. For example, if we set `output_types` to
/// `[BitDistributorOutputType::normal(1), BitDistributorOutputType::normal(2)]`, the first element
/// of the generated pairs will grow as $O(\sqrt\[3\]{i})$ and the second as $O(i^{2/3})$. In
/// general, if the weights are $w_0, w_1, \\ldots, w_{n-1}$, then the $k$th element of the output
/// tuples will grow as $O(i^{w_i/\sum_{j=0}^{n-1}w_j})$.
///
/// Apart from creating _normal_ output types with different weights, we can create _tiny_ output
/// types, which indicate that the corresponding tuple element should grow especially slowly. If
/// `output_types` contains $m$ tiny output types, each tiny tuple element grows as
/// $O(\sqrt\[m\]{\log i})$. The growth of the other elements is unaffected. Having only tiny types
/// in `output_types` is disallowed.
///
/// The above discussion of growth rates assumes that `max_bits` is not specified for any output | /// if `max_bits` wasn't specified, but will stop growing once it reaches $2^b-1$.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct BitDistributor {
pub output_types: Vec<BitDistributorOutputType>,
bit_map: [usize; COUNTER_WIDTH],
counter: [bool; COUNTER_WIDTH],
}
impl BitDistributor {
fn new_without_init(output_types: &[BitDistributorOutputType]) -> BitDistributor {
if output_types
.iter()
.all(|output_type| output_type.weight == 0)
{
panic!("All output_types cannot be tiny");
}
BitDistributor {
output_types: output_types.to_vec(),
bit_map: [0; COUNTER_WIDTH],
counter: [false; COUNTER_WIDTH],
}
}
/// Creates a new `BitDistributor`.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// BitDistributor::new(
/// &[BitDistributorOutputType::normal(2), BitDistributorOutputType::tiny()]
/// );
/// ```
pub fn new(output_types: &[BitDistributorOutputType]) -> BitDistributor {
let mut distributor = BitDistributor::new_without_init(output_types);
distributor.update_bit_map();
distributor
}
/// Returns a reference to the internal bit map as a slice.
///
/// The bit map determines which output gets each bit of the counter. For example, if the bit
/// map is $[0, 1, 0, 1, 0, 1, \ldots]$, then the first element of the output pair gets the bits
/// with indices $0, 2, 4, \ldots$ and the second element gets the bits with indices
/// $1, 3, 5, \ldots$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let bd = BitDistributor::new(&[
/// BitDistributorOutputType::normal(2),
/// BitDistributorOutputType::tiny(),
/// ]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 0, 0, 0, 0, 1
/// ][..]
/// );
/// ```
pub fn bit_map_as_slice(&self) -> &[usize] {
self.bit_map.as_ref()
}
fn update_bit_map(&mut self) {
let (mut normal_output_type_indices, mut tiny_output_type_indices): (
Vec<usize>,
Vec<usize>,
) = (0..self.output_types.len()).partition(|&i| self.output_types[i].weight!= 0);
let mut normal_output_types_bits_used = vec![0; normal_output_type_indices.len()];
let mut tiny_output_types_bits_used = vec![0; tiny_output_type_indices.len()];
let mut ni = normal_output_type_indices.len() - 1;
let mut ti = tiny_output_type_indices.len().saturating_sub(1);
let mut weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
for i in 0..COUNTER_WIDTH {
let use_normal_output_type =!normal_output_type_indices.is_empty()
&& (tiny_output_type_indices.is_empty() ||!usize::is_power_of_two(i + 1));
if use_normal_output_type {
self.bit_map[i] = normal_output_type_indices[ni];
let output_type = self.output_types[normal_output_type_indices[ni]];
normal_output_types_bits_used[ni] += 1;
weight_counter -= 1;
if output_type.max_bits == Some(normal_output_types_bits_used[ni]) {
normal_output_type_indices.remove(ni);
normal_output_types_bits_used.remove(ni);
if normal_output_type_indices.is_empty() {
continue;
}
weight_counter = 0;
}
if weight_counter == 0 {
if ni == 0 {
ni = normal_output_type_indices.len() - 1;
} else {
ni -= 1;
}
weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
}
} else {
if tiny_output_type_indices.is_empty() {
self.bit_map[i] = usize::MAX;
continue;
}
self.bit_map[i] = tiny_output_type_indices[ti];
let output_type = self.output_types[tiny_output_type_indices[ti]];
tiny_output_types_bits_used[ti] += 1;
if output_type.max_bits == Some(tiny_output_types_bits_used[ti]) {
tiny_output_type_indices.remove(ti);
tiny_output_types_bits_used.remove(ti);
if tiny_output_type_indices.is_empty() {
continue;
}
}
if ti == 0 {
ti = tiny_output_type_indices.len() - 1;
} else {
ti -= 1;
}
}
}
}
/// Sets the maximum bits for several outputs.
///
/// Given slice of output indices, sets the maximum bits for each of the outputs and rebuilds
/// the bit map.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_type_indices.len()`.
///
/// # Panics
/// Panics if `max_bits` is 0 or if any index is greater than or equal to
/// `self.output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(2); 3]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1,
/// 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2,
/// 1, 1, 0, 0, 2, 2, 1, 1
/// ][..]
/// );
///
/// bd.set_max_bits(&[0, 2], 5);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1
/// ][..]
/// );
/// ```
pub fn set_max_bits(&mut self, output_type_indices: &[usize], max_bits: usize) {
assert_ne!(max_bits, 0);
for &index in output_type_indices {
self.output_types[index].max_bits = Some(max_bits);
}
self.update_bit_map();
}
/// Increments the counter in preparation for a new set of outputs.
///
/// If the counter is incremented $2^{64}$ times, it rolls back to 0.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1)]);
/// let mut outputs = Vec::new();
/// for _ in 0..20 {
/// outputs.push(bd.get_output(0));
/// bd.increment_counter();
/// }
/// assert_eq!(
/// outputs,
/// &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
/// );
/// ```
pub fn increment_counter(&mut self) {
for b in self.counter.iter_mut() {
b.not_assign();
if *b {
break;
}
}
}
/// Gets the output at a specified index.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `index` is greater than or equal to `self.output_types.len()`.
///
/// # Examples
/// ```
/// extern crate itertools;
///
/// use itertools::Itertools;
///
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1); 2]);
/// let mut outputs = Vec::new();
/// for _ in 0..10 {
/// outputs.push((0..2).map(|i| bd.get_output(i)).collect_vec());
/// bd.increment_counter();
/// }
/// let expected_outputs: &[&[usize]] = &[
/// &[0, 0], &[0, 1], &[1, 0], &[1, 1], &[0, 2], &[0, 3], &[1, 2], &[1, 3], &[2, 0], &[2, 1]
/// ];
/// assert_eq!(outputs, expected_outputs,);
/// ```
pub fn get_output(&self, index: usize) -> usize {
assert!(index < self.output_types.len());
usize::from_bits_asc(
self.bit_map
.iter()
.zip(self.counter.iter())
.filter_map(|(&m, &c)| if m == index { Some(c) } else { None }),
)
}
} | /// type. But if `max_bits` is set to $b$, then the corresponding element will start growing just as | random_line_split |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct BitDistributorOutputType {
weight: usize, // 0 means a tiny output_type
max_bits: Option<usize>,
}
impl BitDistributorOutputType {
/// Creates a normal output with a specified weight.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `weight` is zero.
///
/// The corresponding element grows as a power of $i$. See the `BitDistributor` documentation
/// for more.
pub fn normal(weight: usize) -> BitDistributorOutputType {
assert_ne!(weight, 0);
BitDistributorOutputType {
weight,
max_bits: None,
}
}
/// Creates a tiny output.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// The corresponding element grows logarithmically. See the `BitDistributor` documentation for
/// more.
pub const fn tiny() -> BitDistributorOutputType {
BitDistributorOutputType {
weight: 0,
max_bits: None,
}
}
}
/// `BitDistributor` helps generate tuples exhaustively.
///
/// Think of `counter` as the bits of an integer. It's initialized to zero (all `false`s), and as
/// it's repeatedly incremented, it eventually takes on every 64-bit value.
///
/// `output_types` is a list of $n$ configuration structs that, together, specify how to generate an
/// n-element tuple of unsigned integers. Calling `get_output` repeatedly, passing in 0 through
/// $n - 1$ as `index`, distributes the bits of `counter` into a tuple.
///
/// This is best shown with an example. If `output_types` is set to
/// `[BitDistributorOutputType::normal(1); 2]`, the distributor will generate all pairs of unsigned
/// integers. A pair may be extracted by calling `get_output(0)` and `get_output(1)`; then `counter`
/// may be incremented to create the next pair. In this case, the pairs will be
/// $(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1), \ldots$.
///
/// If you think of these pairs as coordinates in the $xy$-plane, they are traversed along a Z-order
/// curve. Every pair of unsigned integers will be generated exactly once.
///
/// In general, setting `output_types` to `[BitDistributorOutputType::normal(1); n]` will generate
/// $n$-tuples. The elements of the tuples will be very roughly the same size, in the sense that
/// each element will grow as $O(\sqrt\[n\]{i})$, where $i$ is the counter. Sometimes we want the
/// elements to grow at different rates. To accomplish this, we can change the weights of the output
/// types. For example, if we set `output_types` to
/// `[BitDistributorOutputType::normal(1), BitDistributorOutputType::normal(2)]`, the first element
/// of the generated pairs will grow as $O(\sqrt\[3\]{i})$ and the second as $O(i^{2/3})$. In
/// general, if the weights are $w_0, w_1, \\ldots, w_{n-1}$, then the $k$th element of the output
/// tuples will grow as $O(i^{w_i/\sum_{j=0}^{n-1}w_j})$.
///
/// Apart from creating _normal_ output types with different weights, we can create _tiny_ output
/// types, which indicate that the corresponding tuple element should grow especially slowly. If
/// `output_types` contains $m$ tiny output types, each tiny tuple element grows as
/// $O(\sqrt\[m\]{\log i})$. The growth of the other elements is unaffected. Having only tiny types
/// in `output_types` is disallowed.
///
/// The above discussion of growth rates assumes that `max_bits` is not specified for any output
/// type. But if `max_bits` is set to $b$, then the corresponding element will start growing just as
/// if `max_bits` wasn't specified, but will stop growing once it reaches $2^b-1$.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct BitDistributor {
pub output_types: Vec<BitDistributorOutputType>,
bit_map: [usize; COUNTER_WIDTH],
counter: [bool; COUNTER_WIDTH],
}
impl BitDistributor {
fn new_without_init(output_types: &[BitDistributorOutputType]) -> BitDistributor {
if output_types
.iter()
.all(|output_type| output_type.weight == 0)
{
panic!("All output_types cannot be tiny");
}
BitDistributor {
output_types: output_types.to_vec(),
bit_map: [0; COUNTER_WIDTH],
counter: [false; COUNTER_WIDTH],
}
}
/// Creates a new `BitDistributor`.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// BitDistributor::new(
/// &[BitDistributorOutputType::normal(2), BitDistributorOutputType::tiny()]
/// );
/// ```
pub fn new(output_types: &[BitDistributorOutputType]) -> BitDistributor {
let mut distributor = BitDistributor::new_without_init(output_types);
distributor.update_bit_map();
distributor
}
/// Returns a reference to the internal bit map as a slice.
///
/// The bit map determines which output gets each bit of the counter. For example, if the bit
/// map is $[0, 1, 0, 1, 0, 1, \ldots]$, then the first element of the output pair gets the bits
/// with indices $0, 2, 4, \ldots$ and the second element gets the bits with indices
/// $1, 3, 5, \ldots$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let bd = BitDistributor::new(&[
/// BitDistributorOutputType::normal(2),
/// BitDistributorOutputType::tiny(),
/// ]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 0, 0, 0, 0, 1
/// ][..]
/// );
/// ```
pub fn bit_map_as_slice(&self) -> &[usize] {
self.bit_map.as_ref()
}
fn update_bit_map(&mut self) {
let (mut normal_output_type_indices, mut tiny_output_type_indices): (
Vec<usize>,
Vec<usize>,
) = (0..self.output_types.len()).partition(|&i| self.output_types[i].weight!= 0);
let mut normal_output_types_bits_used = vec![0; normal_output_type_indices.len()];
let mut tiny_output_types_bits_used = vec![0; tiny_output_type_indices.len()];
let mut ni = normal_output_type_indices.len() - 1;
let mut ti = tiny_output_type_indices.len().saturating_sub(1);
let mut weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
for i in 0..COUNTER_WIDTH {
let use_normal_output_type =!normal_output_type_indices.is_empty()
&& (tiny_output_type_indices.is_empty() ||!usize::is_power_of_two(i + 1));
if use_normal_output_type {
self.bit_map[i] = normal_output_type_indices[ni];
let output_type = self.output_types[normal_output_type_indices[ni]];
normal_output_types_bits_used[ni] += 1;
weight_counter -= 1;
if output_type.max_bits == Some(normal_output_types_bits_used[ni]) {
normal_output_type_indices.remove(ni);
normal_output_types_bits_used.remove(ni);
if normal_output_type_indices.is_empty() {
continue;
}
weight_counter = 0;
}
if weight_counter == 0 {
if ni == 0 | else {
ni -= 1;
}
weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
}
} else {
if tiny_output_type_indices.is_empty() {
self.bit_map[i] = usize::MAX;
continue;
}
self.bit_map[i] = tiny_output_type_indices[ti];
let output_type = self.output_types[tiny_output_type_indices[ti]];
tiny_output_types_bits_used[ti] += 1;
if output_type.max_bits == Some(tiny_output_types_bits_used[ti]) {
tiny_output_type_indices.remove(ti);
tiny_output_types_bits_used.remove(ti);
if tiny_output_type_indices.is_empty() {
continue;
}
}
if ti == 0 {
ti = tiny_output_type_indices.len() - 1;
} else {
ti -= 1;
}
}
}
}
/// Sets the maximum bits for several outputs.
///
/// Given slice of output indices, sets the maximum bits for each of the outputs and rebuilds
/// the bit map.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_type_indices.len()`.
///
/// # Panics
/// Panics if `max_bits` is 0 or if any index is greater than or equal to
/// `self.output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(2); 3]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1,
/// 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2,
/// 1, 1, 0, 0, 2, 2, 1, 1
/// ][..]
/// );
///
/// bd.set_max_bits(&[0, 2], 5);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1
/// ][..]
/// );
/// ```
pub fn set_max_bits(&mut self, output_type_indices: &[usize], max_bits: usize) {
assert_ne!(max_bits, 0);
for &index in output_type_indices {
self.output_types[index].max_bits = Some(max_bits);
}
self.update_bit_map();
}
/// Increments the counter in preparation for a new set of outputs.
///
/// If the counter is incremented $2^{64}$ times, it rolls back to 0.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1)]);
/// let mut outputs = Vec::new();
/// for _ in 0..20 {
/// outputs.push(bd.get_output(0));
/// bd.increment_counter();
/// }
/// assert_eq!(
/// outputs,
/// &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
/// );
/// ```
pub fn increment_counter(&mut self) {
for b in self.counter.iter_mut() {
b.not_assign();
if *b {
break;
}
}
}
/// Gets the output at a specified index.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `index` is greater than or equal to `self.output_types.len()`.
///
/// # Examples
/// ```
/// extern crate itertools;
///
/// use itertools::Itertools;
///
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1); 2]);
/// let mut outputs = Vec::new();
/// for _ in 0..10 {
/// outputs.push((0..2).map(|i| bd.get_output(i)).collect_vec());
/// bd.increment_counter();
/// }
/// let expected_outputs: &[&[usize]] = &[
/// &[0, 0], &[0, 1], &[1, 0], &[1, 1], &[0, 2], &[0, 3], &[1, 2], &[1, 3], &[2, 0], &[2, 1]
/// ];
/// assert_eq!(outputs, expected_outputs,);
/// ```
pub fn get_output(&self, index: usize) -> usize {
assert!(index < self.output_types.len());
usize::from_bits_asc(
self.bit_map
.iter()
.zip(self.counter.iter())
.filter_map(|(&m, &c)| if m == index { Some(c) } else { None }),
)
}
}
| {
ni = normal_output_type_indices.len() - 1;
} | conditional_block |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct BitDistributorOutputType {
weight: usize, // 0 means a tiny output_type
max_bits: Option<usize>,
}
impl BitDistributorOutputType {
/// Creates a normal output with a specified weight.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `weight` is zero.
///
/// The corresponding element grows as a power of $i$. See the `BitDistributor` documentation
/// for more.
pub fn normal(weight: usize) -> BitDistributorOutputType {
assert_ne!(weight, 0);
BitDistributorOutputType {
weight,
max_bits: None,
}
}
/// Creates a tiny output.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// The corresponding element grows logarithmically. See the `BitDistributor` documentation for
/// more.
pub const fn tiny() -> BitDistributorOutputType {
BitDistributorOutputType {
weight: 0,
max_bits: None,
}
}
}
/// `BitDistributor` helps generate tuples exhaustively.
///
/// Think of `counter` as the bits of an integer. It's initialized to zero (all `false`s), and as
/// it's repeatedly incremented, it eventually takes on every 64-bit value.
///
/// `output_types` is a list of $n$ configuration structs that, together, specify how to generate an
/// n-element tuple of unsigned integers. Calling `get_output` repeatedly, passing in 0 through
/// $n - 1$ as `index`, distributes the bits of `counter` into a tuple.
///
/// This is best shown with an example. If `output_types` is set to
/// `[BitDistributorOutputType::normal(1); 2]`, the distributor will generate all pairs of unsigned
/// integers. A pair may be extracted by calling `get_output(0)` and `get_output(1)`; then `counter`
/// may be incremented to create the next pair. In this case, the pairs will be
/// $(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1), \ldots$.
///
/// If you think of these pairs as coordinates in the $xy$-plane, they are traversed along a Z-order
/// curve. Every pair of unsigned integers will be generated exactly once.
///
/// In general, setting `output_types` to `[BitDistributorOutputType::normal(1); n]` will generate
/// $n$-tuples. The elements of the tuples will be very roughly the same size, in the sense that
/// each element will grow as $O(\sqrt\[n\]{i})$, where $i$ is the counter. Sometimes we want the
/// elements to grow at different rates. To accomplish this, we can change the weights of the output
/// types. For example, if we set `output_types` to
/// `[BitDistributorOutputType::normal(1), BitDistributorOutputType::normal(2)]`, the first element
/// of the generated pairs will grow as $O(\sqrt\[3\]{i})$ and the second as $O(i^{2/3})$. In
/// general, if the weights are $w_0, w_1, \\ldots, w_{n-1}$, then the $k$th element of the output
/// tuples will grow as $O(i^{w_i/\sum_{j=0}^{n-1}w_j})$.
///
/// Apart from creating _normal_ output types with different weights, we can create _tiny_ output
/// types, which indicate that the corresponding tuple element should grow especially slowly. If
/// `output_types` contains $m$ tiny output types, each tiny tuple element grows as
/// $O(\sqrt\[m\]{\log i})$. The growth of the other elements is unaffected. Having only tiny types
/// in `output_types` is disallowed.
///
/// The above discussion of growth rates assumes that `max_bits` is not specified for any output
/// type. But if `max_bits` is set to $b$, then the corresponding element will start growing just as
/// if `max_bits` wasn't specified, but will stop growing once it reaches $2^b-1$.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct BitDistributor {
pub output_types: Vec<BitDistributorOutputType>,
bit_map: [usize; COUNTER_WIDTH],
counter: [bool; COUNTER_WIDTH],
}
impl BitDistributor {
fn new_without_init(output_types: &[BitDistributorOutputType]) -> BitDistributor {
if output_types
.iter()
.all(|output_type| output_type.weight == 0)
{
panic!("All output_types cannot be tiny");
}
BitDistributor {
output_types: output_types.to_vec(),
bit_map: [0; COUNTER_WIDTH],
counter: [false; COUNTER_WIDTH],
}
}
/// Creates a new `BitDistributor`.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// BitDistributor::new(
/// &[BitDistributorOutputType::normal(2), BitDistributorOutputType::tiny()]
/// );
/// ```
pub fn new(output_types: &[BitDistributorOutputType]) -> BitDistributor {
let mut distributor = BitDistributor::new_without_init(output_types);
distributor.update_bit_map();
distributor
}
/// Returns a reference to the internal bit map as a slice.
///
/// The bit map determines which output gets each bit of the counter. For example, if the bit
/// map is $[0, 1, 0, 1, 0, 1, \ldots]$, then the first element of the output pair gets the bits
/// with indices $0, 2, 4, \ldots$ and the second element gets the bits with indices
/// $1, 3, 5, \ldots$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let bd = BitDistributor::new(&[
/// BitDistributorOutputType::normal(2),
/// BitDistributorOutputType::tiny(),
/// ]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 0, 0, 0, 0, 1
/// ][..]
/// );
/// ```
pub fn bit_map_as_slice(&self) -> &[usize] |
fn update_bit_map(&mut self) {
let (mut normal_output_type_indices, mut tiny_output_type_indices): (
Vec<usize>,
Vec<usize>,
) = (0..self.output_types.len()).partition(|&i| self.output_types[i].weight!= 0);
let mut normal_output_types_bits_used = vec![0; normal_output_type_indices.len()];
let mut tiny_output_types_bits_used = vec![0; tiny_output_type_indices.len()];
let mut ni = normal_output_type_indices.len() - 1;
let mut ti = tiny_output_type_indices.len().saturating_sub(1);
let mut weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
for i in 0..COUNTER_WIDTH {
let use_normal_output_type =!normal_output_type_indices.is_empty()
&& (tiny_output_type_indices.is_empty() ||!usize::is_power_of_two(i + 1));
if use_normal_output_type {
self.bit_map[i] = normal_output_type_indices[ni];
let output_type = self.output_types[normal_output_type_indices[ni]];
normal_output_types_bits_used[ni] += 1;
weight_counter -= 1;
if output_type.max_bits == Some(normal_output_types_bits_used[ni]) {
normal_output_type_indices.remove(ni);
normal_output_types_bits_used.remove(ni);
if normal_output_type_indices.is_empty() {
continue;
}
weight_counter = 0;
}
if weight_counter == 0 {
if ni == 0 {
ni = normal_output_type_indices.len() - 1;
} else {
ni -= 1;
}
weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
}
} else {
if tiny_output_type_indices.is_empty() {
self.bit_map[i] = usize::MAX;
continue;
}
self.bit_map[i] = tiny_output_type_indices[ti];
let output_type = self.output_types[tiny_output_type_indices[ti]];
tiny_output_types_bits_used[ti] += 1;
if output_type.max_bits == Some(tiny_output_types_bits_used[ti]) {
tiny_output_type_indices.remove(ti);
tiny_output_types_bits_used.remove(ti);
if tiny_output_type_indices.is_empty() {
continue;
}
}
if ti == 0 {
ti = tiny_output_type_indices.len() - 1;
} else {
ti -= 1;
}
}
}
}
/// Sets the maximum bits for several outputs.
///
/// Given slice of output indices, sets the maximum bits for each of the outputs and rebuilds
/// the bit map.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_type_indices.len()`.
///
/// # Panics
/// Panics if `max_bits` is 0 or if any index is greater than or equal to
/// `self.output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(2); 3]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1,
/// 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2,
/// 1, 1, 0, 0, 2, 2, 1, 1
/// ][..]
/// );
///
/// bd.set_max_bits(&[0, 2], 5);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1
/// ][..]
/// );
/// ```
pub fn set_max_bits(&mut self, output_type_indices: &[usize], max_bits: usize) {
assert_ne!(max_bits, 0);
for &index in output_type_indices {
self.output_types[index].max_bits = Some(max_bits);
}
self.update_bit_map();
}
/// Increments the counter in preparation for a new set of outputs.
///
/// If the counter is incremented $2^{64}$ times, it rolls back to 0.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1)]);
/// let mut outputs = Vec::new();
/// for _ in 0..20 {
/// outputs.push(bd.get_output(0));
/// bd.increment_counter();
/// }
/// assert_eq!(
/// outputs,
/// &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
/// );
/// ```
pub fn increment_counter(&mut self) {
for b in self.counter.iter_mut() {
b.not_assign();
if *b {
break;
}
}
}
/// Gets the output at a specified index.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `index` is greater than or equal to `self.output_types.len()`.
///
/// # Examples
/// ```
/// extern crate itertools;
///
/// use itertools::Itertools;
///
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1); 2]);
/// let mut outputs = Vec::new();
/// for _ in 0..10 {
/// outputs.push((0..2).map(|i| bd.get_output(i)).collect_vec());
/// bd.increment_counter();
/// }
/// let expected_outputs: &[&[usize]] = &[
/// &[0, 0], &[0, 1], &[1, 0], &[1, 1], &[0, 2], &[0, 3], &[1, 2], &[1, 3], &[2, 0], &[2, 1]
/// ];
/// assert_eq!(outputs, expected_outputs,);
/// ```
pub fn get_output(&self, index: usize) -> usize {
assert!(index < self.output_types.len());
usize::from_bits_asc(
self.bit_map
.iter()
.zip(self.counter.iter())
.filter_map(|(&m, &c)| if m == index { Some(c) } else { None }),
)
}
}
| {
self.bit_map.as_ref()
} | identifier_body |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct BitDistributorOutputType {
weight: usize, // 0 means a tiny output_type
max_bits: Option<usize>,
}
impl BitDistributorOutputType {
/// Creates a normal output with a specified weight.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `weight` is zero.
///
/// The corresponding element grows as a power of $i$. See the `BitDistributor` documentation
/// for more.
pub fn normal(weight: usize) -> BitDistributorOutputType {
assert_ne!(weight, 0);
BitDistributorOutputType {
weight,
max_bits: None,
}
}
/// Creates a tiny output.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// The corresponding element grows logarithmically. See the `BitDistributor` documentation for
/// more.
pub const fn tiny() -> BitDistributorOutputType {
BitDistributorOutputType {
weight: 0,
max_bits: None,
}
}
}
/// `BitDistributor` helps generate tuples exhaustively.
///
/// Think of `counter` as the bits of an integer. It's initialized to zero (all `false`s), and as
/// it's repeatedly incremented, it eventually takes on every 64-bit value.
///
/// `output_types` is a list of $n$ configuration structs that, together, specify how to generate an
/// n-element tuple of unsigned integers. Calling `get_output` repeatedly, passing in 0 through
/// $n - 1$ as `index`, distributes the bits of `counter` into a tuple.
///
/// This is best shown with an example. If `output_types` is set to
/// `[BitDistributorOutputType::normal(1); 2]`, the distributor will generate all pairs of unsigned
/// integers. A pair may be extracted by calling `get_output(0)` and `get_output(1)`; then `counter`
/// may be incremented to create the next pair. In this case, the pairs will be
/// $(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1), \ldots$.
///
/// If you think of these pairs as coordinates in the $xy$-plane, they are traversed along a Z-order
/// curve. Every pair of unsigned integers will be generated exactly once.
///
/// In general, setting `output_types` to `[BitDistributorOutputType::normal(1); n]` will generate
/// $n$-tuples. The elements of the tuples will be very roughly the same size, in the sense that
/// each element will grow as $O(\sqrt\[n\]{i})$, where $i$ is the counter. Sometimes we want the
/// elements to grow at different rates. To accomplish this, we can change the weights of the output
/// types. For example, if we set `output_types` to
/// `[BitDistributorOutputType::normal(1), BitDistributorOutputType::normal(2)]`, the first element
/// of the generated pairs will grow as $O(\sqrt\[3\]{i})$ and the second as $O(i^{2/3})$. In
/// general, if the weights are $w_0, w_1, \\ldots, w_{n-1}$, then the $k$th element of the output
/// tuples will grow as $O(i^{w_i/\sum_{j=0}^{n-1}w_j})$.
///
/// Apart from creating _normal_ output types with different weights, we can create _tiny_ output
/// types, which indicate that the corresponding tuple element should grow especially slowly. If
/// `output_types` contains $m$ tiny output types, each tiny tuple element grows as
/// $O(\sqrt\[m\]{\log i})$. The growth of the other elements is unaffected. Having only tiny types
/// in `output_types` is disallowed.
///
/// The above discussion of growth rates assumes that `max_bits` is not specified for any output
/// type. But if `max_bits` is set to $b$, then the corresponding element will start growing just as
/// if `max_bits` wasn't specified, but will stop growing once it reaches $2^b-1$.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct BitDistributor {
pub output_types: Vec<BitDistributorOutputType>,
bit_map: [usize; COUNTER_WIDTH],
counter: [bool; COUNTER_WIDTH],
}
impl BitDistributor {
fn new_without_init(output_types: &[BitDistributorOutputType]) -> BitDistributor {
if output_types
.iter()
.all(|output_type| output_type.weight == 0)
{
panic!("All output_types cannot be tiny");
}
BitDistributor {
output_types: output_types.to_vec(),
bit_map: [0; COUNTER_WIDTH],
counter: [false; COUNTER_WIDTH],
}
}
/// Creates a new `BitDistributor`.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// BitDistributor::new(
/// &[BitDistributorOutputType::normal(2), BitDistributorOutputType::tiny()]
/// );
/// ```
pub fn new(output_types: &[BitDistributorOutputType]) -> BitDistributor {
let mut distributor = BitDistributor::new_without_init(output_types);
distributor.update_bit_map();
distributor
}
/// Returns a reference to the internal bit map as a slice.
///
/// The bit map determines which output gets each bit of the counter. For example, if the bit
/// map is $[0, 1, 0, 1, 0, 1, \ldots]$, then the first element of the output pair gets the bits
/// with indices $0, 2, 4, \ldots$ and the second element gets the bits with indices
/// $1, 3, 5, \ldots$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let bd = BitDistributor::new(&[
/// BitDistributorOutputType::normal(2),
/// BitDistributorOutputType::tiny(),
/// ]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 0, 0, 0, 0, 1
/// ][..]
/// );
/// ```
pub fn bit_map_as_slice(&self) -> &[usize] {
self.bit_map.as_ref()
}
fn update_bit_map(&mut self) {
let (mut normal_output_type_indices, mut tiny_output_type_indices): (
Vec<usize>,
Vec<usize>,
) = (0..self.output_types.len()).partition(|&i| self.output_types[i].weight!= 0);
let mut normal_output_types_bits_used = vec![0; normal_output_type_indices.len()];
let mut tiny_output_types_bits_used = vec![0; tiny_output_type_indices.len()];
let mut ni = normal_output_type_indices.len() - 1;
let mut ti = tiny_output_type_indices.len().saturating_sub(1);
let mut weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
for i in 0..COUNTER_WIDTH {
let use_normal_output_type =!normal_output_type_indices.is_empty()
&& (tiny_output_type_indices.is_empty() ||!usize::is_power_of_two(i + 1));
if use_normal_output_type {
self.bit_map[i] = normal_output_type_indices[ni];
let output_type = self.output_types[normal_output_type_indices[ni]];
normal_output_types_bits_used[ni] += 1;
weight_counter -= 1;
if output_type.max_bits == Some(normal_output_types_bits_used[ni]) {
normal_output_type_indices.remove(ni);
normal_output_types_bits_used.remove(ni);
if normal_output_type_indices.is_empty() {
continue;
}
weight_counter = 0;
}
if weight_counter == 0 {
if ni == 0 {
ni = normal_output_type_indices.len() - 1;
} else {
ni -= 1;
}
weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
}
} else {
if tiny_output_type_indices.is_empty() {
self.bit_map[i] = usize::MAX;
continue;
}
self.bit_map[i] = tiny_output_type_indices[ti];
let output_type = self.output_types[tiny_output_type_indices[ti]];
tiny_output_types_bits_used[ti] += 1;
if output_type.max_bits == Some(tiny_output_types_bits_used[ti]) {
tiny_output_type_indices.remove(ti);
tiny_output_types_bits_used.remove(ti);
if tiny_output_type_indices.is_empty() {
continue;
}
}
if ti == 0 {
ti = tiny_output_type_indices.len() - 1;
} else {
ti -= 1;
}
}
}
}
/// Sets the maximum bits for several outputs.
///
/// Given slice of output indices, sets the maximum bits for each of the outputs and rebuilds
/// the bit map.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `output_type_indices.len()`.
///
/// # Panics
/// Panics if `max_bits` is 0 or if any index is greater than or equal to
/// `self.output_types.len()`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(2); 3]);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1,
/// 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2,
/// 1, 1, 0, 0, 2, 2, 1, 1
/// ][..]
/// );
///
/// bd.set_max_bits(&[0, 2], 5);
/// assert_eq!(
/// bd.bit_map_as_slice(),
/// &[
/// 2, 2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/// 1, 1, 1, 1, 1, 1, 1, 1
/// ][..]
/// );
/// ```
pub fn | (&mut self, output_type_indices: &[usize], max_bits: usize) {
assert_ne!(max_bits, 0);
for &index in output_type_indices {
self.output_types[index].max_bits = Some(max_bits);
}
self.update_bit_map();
}
/// Increments the counter in preparation for a new set of outputs.
///
/// If the counter is incremented $2^{64}$ times, it rolls back to 0.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1)]);
/// let mut outputs = Vec::new();
/// for _ in 0..20 {
/// outputs.push(bd.get_output(0));
/// bd.increment_counter();
/// }
/// assert_eq!(
/// outputs,
/// &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
/// );
/// ```
pub fn increment_counter(&mut self) {
for b in self.counter.iter_mut() {
b.not_assign();
if *b {
break;
}
}
}
/// Gets the output at a specified index.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `index` is greater than or equal to `self.output_types.len()`.
///
/// # Examples
/// ```
/// extern crate itertools;
///
/// use itertools::Itertools;
///
/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
///
/// let mut bd = BitDistributor::new(&[BitDistributorOutputType::normal(1); 2]);
/// let mut outputs = Vec::new();
/// for _ in 0..10 {
/// outputs.push((0..2).map(|i| bd.get_output(i)).collect_vec());
/// bd.increment_counter();
/// }
/// let expected_outputs: &[&[usize]] = &[
/// &[0, 0], &[0, 1], &[1, 0], &[1, 1], &[0, 2], &[0, 3], &[1, 2], &[1, 3], &[2, 0], &[2, 1]
/// ];
/// assert_eq!(outputs, expected_outputs,);
/// ```
pub fn get_output(&self, index: usize) -> usize {
assert!(index < self.output_types.len());
usize::from_bits_asc(
self.bit_map
.iter()
.zip(self.counter.iter())
.filter_map(|(&m, &c)| if m == index { Some(c) } else { None }),
)
}
}
| set_max_bits | identifier_name |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use core::PackageId;
use util::{CargoResult, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use super::{fingerprint, Kind, Context, Unit};
use super::CommandType;
/// Contains the parsed output of a custom build script.
#[derive(Clone, Debug, Hash)]
pub struct BuildOutput {
/// Paths to pass to rustc with the `-L` flag
pub library_paths: Vec<PathBuf>,
/// Names and link kinds of libraries, suitable for the `-l` flag
pub library_links: Vec<String>,
/// Various `--cfg` flags to pass to the compiler
pub cfgs: Vec<String>,
/// Metadata to pass to the immediate dependencies
pub metadata: Vec<(String, String)>,
/// Glob paths to trigger a rerun of this build script.
pub rerun_if_changed: Vec<String>,
}
pub type BuildMap = HashMap<(PackageId, Kind), BuildOutput>;
pub struct BuildState {
pub outputs: Mutex<BuildMap>,
overrides: HashMap<(String, Kind), BuildOutput>,
}
#[derive(Default)]
pub struct BuildScripts {
// Cargo will use this `to_link` vector to add -L flags to compiles as we
// propagate them upwards towards the final build. Note, however, that we
// need to preserve the ordering of `to_link` to be topologically sorted.
// This will ensure that build scripts which print their paths properly will
// correctly pick up the files they generated (if there are duplicates
// elsewhere).
//
// To preserve this ordering, the (id, kind) is stored in two places, once
// in the `Vec` and once in `seen_to_link` for a fast lookup. We maintain
// this as we're building interactively below to ensure that the memory
// usage here doesn't blow up too much.
//
// For more information, see #2354
pub to_link: Vec<(PackageId, Kind)>,
seen_to_link: HashSet<(PackageId, Kind)>,
pub plugins: BTreeSet<PackageId>,
}
/// Prepares a `Work` that executes the target as a custom build script.
///
/// The `req` given is the requirement which this run of the build script will
/// prepare work for. If the requirement is specified as both the target and the
/// host platforms it is assumed that the two are equal and the build script is
/// only run once (not twice).
pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>)
-> CargoResult<(Work, Work, Freshness)> {
let _p = profile::start(format!("build script prepare: {}/{}",
unit.pkg, unit.target.name()));
let overridden = cx.build_state.has_override(unit);
let (work_dirty, work_fresh) = if overridden {
(Work::new(|_| Ok(())), Work::new(|_| Ok(())))
} else {
try!(build_work(cx, unit))
};
// Now that we've prep'd our work, build the work needed to manage the
// fingerprint and then start returning that upwards.
let (freshness, dirty, fresh) =
try!(fingerprint::prepare_build_cmd(cx, unit)); | }
fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>)
-> CargoResult<(Work, Work)> {
let (script_output, build_output) = {
(cx.layout(unit.pkg, Kind::Host).build(unit.pkg),
cx.layout(unit.pkg, unit.kind).build_out(unit.pkg))
};
// Building the command to execute
let to_exec = script_output.join(unit.target.name());
// Start preparing the process to execute, starting out with some
// environment variables. Note that the profile-related environment
// variables are not set with this the build script's profile but rather the
// package's library profile.
let profile = cx.lib_profile(unit.pkg.package_id());
let to_exec = to_exec.into_os_string();
let mut p = try!(super::process(CommandType::Host(to_exec), unit.pkg, cx));
p.env("OUT_DIR", &build_output)
.env("CARGO_MANIFEST_DIR", unit.pkg.root())
.env("NUM_JOBS", &cx.jobs().to_string())
.env("TARGET", &match unit.kind {
Kind::Host => &cx.config.rustc_info().host[..],
Kind::Target => cx.target_triple(),
})
.env("DEBUG", &profile.debuginfo.to_string())
.env("OPT_LEVEL", &profile.opt_level.to_string())
.env("PROFILE", if cx.build_config.release {"release"} else {"debug"})
.env("HOST", &cx.config.rustc_info().host);
// Be sure to pass along all enabled features for this package, this is the
// last piece of statically known information that we have.
if let Some(features) = cx.resolve.features(unit.pkg.package_id()) {
for feat in features.iter() {
p.env(&format!("CARGO_FEATURE_{}", super::envify(feat)), "1");
}
}
// Gather the set of native dependencies that this package has along with
// some other variables to close over.
//
// This information will be used at build-time later on to figure out which
// sorts of variables need to be discovered at that time.
let lib_deps = {
try!(cx.dep_run_custom_build(unit)).iter().filter_map(|unit| {
if unit.profile.run_custom_build {
Some((unit.pkg.manifest().links().unwrap().to_string(),
unit.pkg.package_id().clone()))
} else {
None
}
}).collect::<Vec<_>>()
};
let pkg_name = unit.pkg.to_string();
let build_state = cx.build_state.clone();
let id = unit.pkg.package_id().clone();
let output_file = build_output.parent().unwrap().join("output");
let all = (id.clone(), pkg_name.clone(), build_state.clone(),
output_file.clone());
let build_scripts = super::load_build_deps(cx, unit);
let kind = unit.kind;
// Check to see if the build script as already run, and if it has keep
// track of whether it has told us about some explicit dependencies
let prev_output = BuildOutput::parse_file(&output_file, &pkg_name).ok();
let rerun_if_changed = match prev_output {
Some(ref prev) => prev.rerun_if_changed.clone(),
None => Vec::new(),
};
cx.build_explicit_deps.insert(*unit, (output_file.clone(), rerun_if_changed));
try!(fs::create_dir_all(&cx.layout(unit.pkg, Kind::Host).build(unit.pkg)));
try!(fs::create_dir_all(&cx.layout(unit.pkg, unit.kind).build(unit.pkg)));
let exec_engine = cx.exec_engine.clone();
// Prepare the unit of "dirty work" which will actually run the custom build
// command.
//
// Note that this has to do some extra work just before running the command
// to determine extra environment variables and such.
let dirty = Work::new(move |desc_tx| {
// Make sure that OUT_DIR exists.
//
// If we have an old build directory, then just move it into place,
// otherwise create it!
if fs::metadata(&build_output).is_err() {
try!(fs::create_dir(&build_output).chain_error(|| {
internal("failed to create script output directory for \
build command")
}));
}
// For all our native lib dependencies, pick up their metadata to pass
// along to this custom build command. We're also careful to augment our
// dynamic library search path in case the build script depended on any
// native dynamic libraries.
{
let build_state = build_state.outputs.lock().unwrap();
for (name, id) in lib_deps {
let key = (id.clone(), kind);
let state = try!(build_state.get(&key).chain_error(|| {
internal(format!("failed to locate build state for env \
vars: {}/{:?}", id, kind))
}));
let data = &state.metadata;
for &(ref key, ref value) in data.iter() {
p.env(&format!("DEP_{}_{}", super::envify(&name),
super::envify(key)), value);
}
}
if let Some(build_scripts) = build_scripts {
try!(super::add_plugin_deps(&mut p, &build_state,
&build_scripts));
}
}
// And now finally, run the build command itself!
desc_tx.send(p.to_string()).ok();
let output = try!(exec_engine.exec_with_output(p).map_err(|mut e| {
e.desc = format!("failed to run custom build command for `{}`\n{}",
pkg_name, e.desc);
Human(e)
}));
try!(paths::write(&output_file, &output.stdout));
// After the build command has finished running, we need to be sure to
// remember all of its output so we can later discover precisely what it
// was, even if we don't run the build command again (due to freshness).
//
// This is also the location where we provide feedback into the build
// state informing what variables were discovered via our script as
// well.
let parsed_output = try!(BuildOutput::parse(&output.stdout, &pkg_name));
build_state.insert(id, kind, parsed_output);
Ok(())
});
// Now that we've prepared our work-to-do, we need to prepare the fresh work
// itself to run when we actually end up just discarding what we calculated
// above.
let fresh = Work::new(move |_tx| {
let (id, pkg_name, build_state, output_file) = all;
let output = match prev_output {
Some(output) => output,
None => try!(BuildOutput::parse_file(&output_file, &pkg_name)),
};
build_state.insert(id, kind, output);
Ok(())
});
Ok((dirty, fresh))
}
impl BuildState {
pub fn new(config: &super::BuildConfig) -> BuildState {
let mut overrides = HashMap::new();
let i1 = config.host.overrides.iter().map(|p| (p, Kind::Host));
let i2 = config.target.overrides.iter().map(|p| (p, Kind::Target));
for ((name, output), kind) in i1.chain(i2) {
overrides.insert((name.clone(), kind), output.clone());
}
BuildState {
outputs: Mutex::new(HashMap::new()),
overrides: overrides,
}
}
fn insert(&self, id: PackageId, kind: Kind, output: BuildOutput) {
self.outputs.lock().unwrap().insert((id, kind), output);
}
fn has_override(&self, unit: &Unit) -> bool {
let key = unit.pkg.manifest().links().map(|l| (l.to_string(), unit.kind));
match key.and_then(|k| self.overrides.get(&k)) {
Some(output) => {
self.insert(unit.pkg.package_id().clone(), unit.kind,
output.clone());
true
}
None => false,
}
}
}
impl BuildOutput {
pub fn parse_file(path: &Path, pkg_name: &str) -> CargoResult<BuildOutput> {
let contents = try!(paths::read_bytes(path));
BuildOutput::parse(&contents, pkg_name)
}
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &[u8], pkg_name: &str) -> CargoResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut cfgs = Vec::new();
let mut metadata = Vec::new();
let mut rerun_if_changed = Vec::new();
let whence = format!("build script of `{}`", pkg_name);
for line in input.split(|b| *b == b'\n') {
let line = match str::from_utf8(line) {
Ok(line) => line.trim(),
Err(..) => continue,
};
let mut iter = line.splitn(2, ':');
if iter.next()!= Some("cargo") {
// skip this line since it doesn't start with "cargo:"
continue;
}
let data = match iter.next() {
Some(val) => val,
None => continue
};
// getting the `key=value` part of the line
let mut iter = data.splitn(2, '=');
let key = iter.next();
let value = iter.next();
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_right()),
// line started with `cargo:` but didn't match `key=value`
_ => bail!("Wrong output in {}: `{}`", whence, line),
};
match key {
"rustc-flags" => {
let (libs, links) = try!(
BuildOutput::parse_rustc_flags(value, &whence)
);
library_links.extend(links.into_iter());
library_paths.extend(libs.into_iter());
}
"rustc-link-lib" => library_links.push(value.to_string()),
"rustc-link-search" => library_paths.push(PathBuf::from(value)),
"rustc-cfg" => cfgs.push(value.to_string()),
"rerun-if-changed" => rerun_if_changed.push(value.to_string()),
_ => metadata.push((key.to_string(), value.to_string())),
}
}
Ok(BuildOutput {
library_paths: library_paths,
library_links: library_links,
cfgs: cfgs,
metadata: metadata,
rerun_if_changed: rerun_if_changed,
})
}
pub fn parse_rustc_flags(value: &str, whence: &str)
-> CargoResult<(Vec<PathBuf>, Vec<String>)> {
let value = value.trim();
let mut flags_iter = value.split(|c: char| c.is_whitespace())
.filter(|w| w.chars().any(|c|!c.is_whitespace()));
let (mut library_links, mut library_paths) = (Vec::new(), Vec::new());
loop {
let flag = match flags_iter.next() {
Some(f) => f,
None => break
};
if flag!= "-l" && flag!= "-L" {
bail!("Only `-l` and `-L` flags are allowed in {}: `{}`",
whence, value)
}
let value = match flags_iter.next() {
Some(v) => v,
None => bail!("Flag in rustc-flags has no value in {}: `{}`",
whence, value)
};
match flag {
"-l" => library_links.push(value.to_string()),
"-L" => library_paths.push(PathBuf::from(value)),
// was already checked above
_ => bail!("only -l and -L flags are allowed")
};
}
Ok((library_paths, library_links))
}
}
/// Compute the `build_scripts` map in the `Context` which tracks what build
/// scripts each package depends on.
///
/// The global `build_scripts` map lists for all (package, kind) tuples what set
/// of packages' build script outputs must be considered. For example this lists
/// all dependencies' `-L` flags which need to be propagated transitively.
///
/// The given set of targets to this function is the initial set of
/// targets/profiles which are being built.
pub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>,
units: &[Unit<'b>])
-> CargoResult<()> {
let mut ret = HashMap::new();
for unit in units {
try!(build(&mut ret, cx, unit));
}
cx.build_scripts.extend(ret.into_iter().map(|(k, v)| {
(k, Arc::new(v))
}));
return Ok(());
// Recursive function to build up the map we're constructing. This function
// memoizes all of its return values as it goes along.
fn build<'a, 'b, 'cfg>(out: &'a mut HashMap<Unit<'b>, BuildScripts>,
cx: &Context<'b, 'cfg>,
unit: &Unit<'b>)
-> CargoResult<&'a BuildScripts> {
// Do a quick pre-flight check to see if we've already calculated the
// set of dependencies.
if out.contains_key(unit) {
return Ok(&out[unit])
}
let mut ret = BuildScripts::default();
if!unit.target.is_custom_build() && unit.pkg.has_custom_build() {
add_to_link(&mut ret, unit.pkg.package_id(), unit.kind);
}
for unit in try!(cx.dep_targets(unit)).iter() {
let dep_scripts = try!(build(out, cx, unit));
if unit.target.for_host() {
ret.plugins.extend(dep_scripts.to_link.iter()
.map(|p| &p.0).cloned());
} else if unit.target.linkable() {
for &(ref pkg, kind) in dep_scripts.to_link.iter() {
add_to_link(&mut ret, pkg, kind);
}
}
}
let prev = out.entry(*unit).or_insert(BuildScripts::default());
for (pkg, kind) in ret.to_link {
add_to_link(prev, &pkg, kind);
}
prev.plugins.extend(ret.plugins);
Ok(prev)
}
// When adding an entry to 'to_link' we only actually push it on if the
// script hasn't seen it yet (e.g. we don't push on duplicates).
fn add_to_link(scripts: &mut BuildScripts, pkg: &PackageId, kind: Kind) {
if scripts.seen_to_link.insert((pkg.clone(), kind)) {
scripts.to_link.push((pkg.clone(), kind));
}
}
} |
Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness)) | random_line_split |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use core::PackageId;
use util::{CargoResult, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use super::{fingerprint, Kind, Context, Unit};
use super::CommandType;
/// Contains the parsed output of a custom build script.
#[derive(Clone, Debug, Hash)]
pub struct BuildOutput {
/// Paths to pass to rustc with the `-L` flag
pub library_paths: Vec<PathBuf>,
/// Names and link kinds of libraries, suitable for the `-l` flag
pub library_links: Vec<String>,
/// Various `--cfg` flags to pass to the compiler
pub cfgs: Vec<String>,
/// Metadata to pass to the immediate dependencies
pub metadata: Vec<(String, String)>,
/// Glob paths to trigger a rerun of this build script.
pub rerun_if_changed: Vec<String>,
}
pub type BuildMap = HashMap<(PackageId, Kind), BuildOutput>;
pub struct BuildState {
pub outputs: Mutex<BuildMap>,
overrides: HashMap<(String, Kind), BuildOutput>,
}
#[derive(Default)]
pub struct BuildScripts {
// Cargo will use this `to_link` vector to add -L flags to compiles as we
// propagate them upwards towards the final build. Note, however, that we
// need to preserve the ordering of `to_link` to be topologically sorted.
// This will ensure that build scripts which print their paths properly will
// correctly pick up the files they generated (if there are duplicates
// elsewhere).
//
// To preserve this ordering, the (id, kind) is stored in two places, once
// in the `Vec` and once in `seen_to_link` for a fast lookup. We maintain
// this as we're building interactively below to ensure that the memory
// usage here doesn't blow up too much.
//
// For more information, see #2354
pub to_link: Vec<(PackageId, Kind)>,
seen_to_link: HashSet<(PackageId, Kind)>,
pub plugins: BTreeSet<PackageId>,
}
/// Prepares a `Work` that executes the target as a custom build script.
///
/// The `req` given is the requirement which this run of the build script will
/// prepare work for. If the requirement is specified as both the target and the
/// host platforms it is assumed that the two are equal and the build script is
/// only run once (not twice).
pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>)
-> CargoResult<(Work, Work, Freshness)> {
let _p = profile::start(format!("build script prepare: {}/{}",
unit.pkg, unit.target.name()));
let overridden = cx.build_state.has_override(unit);
let (work_dirty, work_fresh) = if overridden {
(Work::new(|_| Ok(())), Work::new(|_| Ok(())))
} else {
try!(build_work(cx, unit))
};
// Now that we've prep'd our work, build the work needed to manage the
// fingerprint and then start returning that upwards.
let (freshness, dirty, fresh) =
try!(fingerprint::prepare_build_cmd(cx, unit));
Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness))
}
fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>)
-> CargoResult<(Work, Work)> {
let (script_output, build_output) = {
(cx.layout(unit.pkg, Kind::Host).build(unit.pkg),
cx.layout(unit.pkg, unit.kind).build_out(unit.pkg))
};
// Building the command to execute
let to_exec = script_output.join(unit.target.name());
// Start preparing the process to execute, starting out with some
// environment variables. Note that the profile-related environment
// variables are not set with this the build script's profile but rather the
// package's library profile.
let profile = cx.lib_profile(unit.pkg.package_id());
let to_exec = to_exec.into_os_string();
let mut p = try!(super::process(CommandType::Host(to_exec), unit.pkg, cx));
p.env("OUT_DIR", &build_output)
.env("CARGO_MANIFEST_DIR", unit.pkg.root())
.env("NUM_JOBS", &cx.jobs().to_string())
.env("TARGET", &match unit.kind {
Kind::Host => &cx.config.rustc_info().host[..],
Kind::Target => cx.target_triple(),
})
.env("DEBUG", &profile.debuginfo.to_string())
.env("OPT_LEVEL", &profile.opt_level.to_string())
.env("PROFILE", if cx.build_config.release {"release"} else {"debug"})
.env("HOST", &cx.config.rustc_info().host);
// Be sure to pass along all enabled features for this package, this is the
// last piece of statically known information that we have.
if let Some(features) = cx.resolve.features(unit.pkg.package_id()) {
for feat in features.iter() {
p.env(&format!("CARGO_FEATURE_{}", super::envify(feat)), "1");
}
}
// Gather the set of native dependencies that this package has along with
// some other variables to close over.
//
// This information will be used at build-time later on to figure out which
// sorts of variables need to be discovered at that time.
let lib_deps = {
try!(cx.dep_run_custom_build(unit)).iter().filter_map(|unit| {
if unit.profile.run_custom_build {
Some((unit.pkg.manifest().links().unwrap().to_string(),
unit.pkg.package_id().clone()))
} else {
None
}
}).collect::<Vec<_>>()
};
let pkg_name = unit.pkg.to_string();
let build_state = cx.build_state.clone();
let id = unit.pkg.package_id().clone();
let output_file = build_output.parent().unwrap().join("output");
let all = (id.clone(), pkg_name.clone(), build_state.clone(),
output_file.clone());
let build_scripts = super::load_build_deps(cx, unit);
let kind = unit.kind;
// Check to see if the build script as already run, and if it has keep
// track of whether it has told us about some explicit dependencies
let prev_output = BuildOutput::parse_file(&output_file, &pkg_name).ok();
let rerun_if_changed = match prev_output {
Some(ref prev) => prev.rerun_if_changed.clone(),
None => Vec::new(),
};
cx.build_explicit_deps.insert(*unit, (output_file.clone(), rerun_if_changed));
try!(fs::create_dir_all(&cx.layout(unit.pkg, Kind::Host).build(unit.pkg)));
try!(fs::create_dir_all(&cx.layout(unit.pkg, unit.kind).build(unit.pkg)));
let exec_engine = cx.exec_engine.clone();
// Prepare the unit of "dirty work" which will actually run the custom build
// command.
//
// Note that this has to do some extra work just before running the command
// to determine extra environment variables and such.
let dirty = Work::new(move |desc_tx| {
// Make sure that OUT_DIR exists.
//
// If we have an old build directory, then just move it into place,
// otherwise create it!
if fs::metadata(&build_output).is_err() {
try!(fs::create_dir(&build_output).chain_error(|| {
internal("failed to create script output directory for \
build command")
}));
}
// For all our native lib dependencies, pick up their metadata to pass
// along to this custom build command. We're also careful to augment our
// dynamic library search path in case the build script depended on any
// native dynamic libraries.
{
let build_state = build_state.outputs.lock().unwrap();
for (name, id) in lib_deps {
let key = (id.clone(), kind);
let state = try!(build_state.get(&key).chain_error(|| {
internal(format!("failed to locate build state for env \
vars: {}/{:?}", id, kind))
}));
let data = &state.metadata;
for &(ref key, ref value) in data.iter() {
p.env(&format!("DEP_{}_{}", super::envify(&name),
super::envify(key)), value);
}
}
if let Some(build_scripts) = build_scripts {
try!(super::add_plugin_deps(&mut p, &build_state,
&build_scripts));
}
}
// And now finally, run the build command itself!
desc_tx.send(p.to_string()).ok();
let output = try!(exec_engine.exec_with_output(p).map_err(|mut e| {
e.desc = format!("failed to run custom build command for `{}`\n{}",
pkg_name, e.desc);
Human(e)
}));
try!(paths::write(&output_file, &output.stdout));
// After the build command has finished running, we need to be sure to
// remember all of its output so we can later discover precisely what it
// was, even if we don't run the build command again (due to freshness).
//
// This is also the location where we provide feedback into the build
// state informing what variables were discovered via our script as
// well.
let parsed_output = try!(BuildOutput::parse(&output.stdout, &pkg_name));
build_state.insert(id, kind, parsed_output);
Ok(())
});
// Now that we've prepared our work-to-do, we need to prepare the fresh work
// itself to run when we actually end up just discarding what we calculated
// above.
let fresh = Work::new(move |_tx| {
let (id, pkg_name, build_state, output_file) = all;
let output = match prev_output {
Some(output) => output,
None => try!(BuildOutput::parse_file(&output_file, &pkg_name)),
};
build_state.insert(id, kind, output);
Ok(())
});
Ok((dirty, fresh))
}
impl BuildState {
pub fn new(config: &super::BuildConfig) -> BuildState {
let mut overrides = HashMap::new();
let i1 = config.host.overrides.iter().map(|p| (p, Kind::Host));
let i2 = config.target.overrides.iter().map(|p| (p, Kind::Target));
for ((name, output), kind) in i1.chain(i2) {
overrides.insert((name.clone(), kind), output.clone());
}
BuildState {
outputs: Mutex::new(HashMap::new()),
overrides: overrides,
}
}
fn insert(&self, id: PackageId, kind: Kind, output: BuildOutput) {
self.outputs.lock().unwrap().insert((id, kind), output);
}
fn has_override(&self, unit: &Unit) -> bool {
let key = unit.pkg.manifest().links().map(|l| (l.to_string(), unit.kind));
match key.and_then(|k| self.overrides.get(&k)) {
Some(output) => {
self.insert(unit.pkg.package_id().clone(), unit.kind,
output.clone());
true
}
None => false,
}
}
}
impl BuildOutput {
pub fn | (path: &Path, pkg_name: &str) -> CargoResult<BuildOutput> {
let contents = try!(paths::read_bytes(path));
BuildOutput::parse(&contents, pkg_name)
}
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &[u8], pkg_name: &str) -> CargoResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut cfgs = Vec::new();
let mut metadata = Vec::new();
let mut rerun_if_changed = Vec::new();
let whence = format!("build script of `{}`", pkg_name);
for line in input.split(|b| *b == b'\n') {
let line = match str::from_utf8(line) {
Ok(line) => line.trim(),
Err(..) => continue,
};
let mut iter = line.splitn(2, ':');
if iter.next()!= Some("cargo") {
// skip this line since it doesn't start with "cargo:"
continue;
}
let data = match iter.next() {
Some(val) => val,
None => continue
};
// getting the `key=value` part of the line
let mut iter = data.splitn(2, '=');
let key = iter.next();
let value = iter.next();
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_right()),
// line started with `cargo:` but didn't match `key=value`
_ => bail!("Wrong output in {}: `{}`", whence, line),
};
match key {
"rustc-flags" => {
let (libs, links) = try!(
BuildOutput::parse_rustc_flags(value, &whence)
);
library_links.extend(links.into_iter());
library_paths.extend(libs.into_iter());
}
"rustc-link-lib" => library_links.push(value.to_string()),
"rustc-link-search" => library_paths.push(PathBuf::from(value)),
"rustc-cfg" => cfgs.push(value.to_string()),
"rerun-if-changed" => rerun_if_changed.push(value.to_string()),
_ => metadata.push((key.to_string(), value.to_string())),
}
}
Ok(BuildOutput {
library_paths: library_paths,
library_links: library_links,
cfgs: cfgs,
metadata: metadata,
rerun_if_changed: rerun_if_changed,
})
}
pub fn parse_rustc_flags(value: &str, whence: &str)
-> CargoResult<(Vec<PathBuf>, Vec<String>)> {
let value = value.trim();
let mut flags_iter = value.split(|c: char| c.is_whitespace())
.filter(|w| w.chars().any(|c|!c.is_whitespace()));
let (mut library_links, mut library_paths) = (Vec::new(), Vec::new());
loop {
let flag = match flags_iter.next() {
Some(f) => f,
None => break
};
if flag!= "-l" && flag!= "-L" {
bail!("Only `-l` and `-L` flags are allowed in {}: `{}`",
whence, value)
}
let value = match flags_iter.next() {
Some(v) => v,
None => bail!("Flag in rustc-flags has no value in {}: `{}`",
whence, value)
};
match flag {
"-l" => library_links.push(value.to_string()),
"-L" => library_paths.push(PathBuf::from(value)),
// was already checked above
_ => bail!("only -l and -L flags are allowed")
};
}
Ok((library_paths, library_links))
}
}
/// Compute the `build_scripts` map in the `Context` which tracks what build
/// scripts each package depends on.
///
/// The global `build_scripts` map lists for all (package, kind) tuples what set
/// of packages' build script outputs must be considered. For example this lists
/// all dependencies' `-L` flags which need to be propagated transitively.
///
/// The given set of targets to this function is the initial set of
/// targets/profiles which are being built.
pub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>,
units: &[Unit<'b>])
-> CargoResult<()> {
let mut ret = HashMap::new();
for unit in units {
try!(build(&mut ret, cx, unit));
}
cx.build_scripts.extend(ret.into_iter().map(|(k, v)| {
(k, Arc::new(v))
}));
return Ok(());
// Recursive function to build up the map we're constructing. This function
// memoizes all of its return values as it goes along.
fn build<'a, 'b, 'cfg>(out: &'a mut HashMap<Unit<'b>, BuildScripts>,
cx: &Context<'b, 'cfg>,
unit: &Unit<'b>)
-> CargoResult<&'a BuildScripts> {
// Do a quick pre-flight check to see if we've already calculated the
// set of dependencies.
if out.contains_key(unit) {
return Ok(&out[unit])
}
let mut ret = BuildScripts::default();
if!unit.target.is_custom_build() && unit.pkg.has_custom_build() {
add_to_link(&mut ret, unit.pkg.package_id(), unit.kind);
}
for unit in try!(cx.dep_targets(unit)).iter() {
let dep_scripts = try!(build(out, cx, unit));
if unit.target.for_host() {
ret.plugins.extend(dep_scripts.to_link.iter()
.map(|p| &p.0).cloned());
} else if unit.target.linkable() {
for &(ref pkg, kind) in dep_scripts.to_link.iter() {
add_to_link(&mut ret, pkg, kind);
}
}
}
let prev = out.entry(*unit).or_insert(BuildScripts::default());
for (pkg, kind) in ret.to_link {
add_to_link(prev, &pkg, kind);
}
prev.plugins.extend(ret.plugins);
Ok(prev)
}
// When adding an entry to 'to_link' we only actually push it on if the
// script hasn't seen it yet (e.g. we don't push on duplicates).
fn add_to_link(scripts: &mut BuildScripts, pkg: &PackageId, kind: Kind) {
if scripts.seen_to_link.insert((pkg.clone(), kind)) {
scripts.to_link.push((pkg.clone(), kind));
}
}
}
| parse_file | identifier_name |
script_msg.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::AnimationState;
use crate::AuxiliaryBrowsingContextLoadInfo;
use crate::BroadcastMsg;
use crate::DocumentState;
use crate::IFrameLoadInfoWithData;
use crate::LayoutControlMsg;
use crate::LoadData;
use crate::MessagePortMsg;
use crate::PortMessageTask;
use crate::StructuredSerializedData;
use crate::WindowSizeType;
use crate::WorkerGlobalScopeInit;
use crate::WorkerScriptLoadOrigin;
use canvas_traits::canvas::{CanvasId, CanvasMsg};
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use embedder_traits::{EmbedderMsg, MediaSessionEvent};
use euclid::default::Size2D as UntypedSize2D;
use euclid::Size2D;
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use msg::constellation_msg::{
BroadcastChannelRouterId, BrowsingContextId, MessagePortId, MessagePortRouterId, PipelineId,
TopLevelBrowsingContextId,
};
use msg::constellation_msg::{HistoryStateId, TraversalDirection};
use msg::constellation_msg::{ServiceWorkerId, ServiceWorkerRegistrationId};
use net_traits::request::RequestBuilder;
use net_traits::storage_thread::StorageType;
use net_traits::CoreResourceMsg;
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use smallvec::SmallVec;
use std::collections::{HashMap, VecDeque};
use std::fmt;
use style_traits::viewport::ViewportConstraints;
use style_traits::CSSPixel;
use webgpu::{wgpu, WebGPUResponseResult};
use webrender_api::units::{DeviceIntPoint, DeviceIntSize};
/// A particular iframe's size, associated with a browsing context.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct IFrameSize {
/// The child browsing context for this iframe.
pub id: BrowsingContextId,
/// The size of the iframe.
pub size: Size2D<f32, CSSPixel>,
}
/// An iframe sizing operation.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct IFrameSizeMsg {
/// The iframe sizing data.
pub data: IFrameSize,
/// The kind of sizing operation.
pub type_: WindowSizeType,
}
/// Messages from the layout to the constellation.
#[derive(Deserialize, Serialize)]
pub enum LayoutMsg {
/// Inform the constellation of the size of the iframe's viewport.
IFrameSizes(Vec<IFrameSizeMsg>),
/// Requests that the constellation inform the compositor that it needs to record
/// the time when the frame with the given ID (epoch) is painted.
PendingPaintMetric(PipelineId, Epoch),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
impl fmt::Debug for LayoutMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::LayoutMsg::*;
let variant = match *self {
IFrameSizes(..) => "IFrameSizes",
PendingPaintMetric(..) => "PendingPaintMetric",
ViewportConstrained(..) => "ViewportConstrained",
};
write!(formatter, "LayoutMsg::{}", variant)
}
}
/// Whether a DOM event was prevented by web content
#[derive(Debug, Deserialize, Serialize)]
pub enum EventResult {
/// Allowed by web content
DefaultAllowed,
/// Prevented by web content
DefaultPrevented,
}
/// A log entry reported to the constellation
/// We don't report all log entries, just serious ones.
/// We need a separate type for this because `LogLevel` isn't serializable.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum LogEntry {
/// Panic, with a reason and backtrace
Panic(String, String),
/// Error, with a reason
Error(String),
/// warning, with a reason
Warn(String),
}
/// https://html.spec.whatwg.org/multipage/#replacement-enabled
#[derive(Debug, Deserialize, Serialize)]
pub enum HistoryEntryReplacement {
/// Traverse the history with replacement enabled.
Enabled,
/// Traverse the history with replacement disabled.
Disabled,
}
/// Messages from the script to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ScriptMsg {
/// Request to complete the transfer of a set of ports to a router.
CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>),
/// The results of attempting to complete the transfer of a batch of ports.
MessagePortTransferResult(
/* The router whose transfer of ports succeeded, if any */
Option<MessagePortRouterId>,
/* The ids of ports transferred successfully */
Vec<MessagePortId>,
/* The ids, and buffers, of ports whose transfer failed */
HashMap<MessagePortId, VecDeque<PortMessageTask>>,
),
/// A new message-port was created or transferred, with corresponding control-sender.
NewMessagePort(MessagePortRouterId, MessagePortId),
/// A global has started managing message-ports
NewMessagePortRouter(MessagePortRouterId, IpcSender<MessagePortMsg>),
/// A global has stopped managing message-ports
RemoveMessagePortRouter(MessagePortRouterId),
/// A task requires re-routing to an already shipped message-port.
RerouteMessagePort(MessagePortId, PortMessageTask),
/// A message-port was shipped, let the entangled port know.
MessagePortShipped(MessagePortId),
/// A message-port has been discarded by script.
RemoveMessagePort(MessagePortId),
/// Entangle two message-ports.
EntanglePorts(MessagePortId, MessagePortId),
/// A global has started managing broadcast-channels.
NewBroadcastChannelRouter(
BroadcastChannelRouterId,
IpcSender<BroadcastMsg>,
ImmutableOrigin,
),
/// A global has stopped managing broadcast-channels.
RemoveBroadcastChannelRouter(BroadcastChannelRouterId, ImmutableOrigin),
/// A global started managing broadcast channels for a given channel-name.
NewBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
/// A global stopped managing broadcast channels for a given channel-name.
RemoveBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
/// Broadcast a message to all same-origin broadcast channels,
/// excluding the source of the broadcast.
ScheduleBroadcast(BroadcastChannelRouterId, BroadcastMsg),
/// Forward a message to the embedder.
ForwardToEmbedder(EmbedderMsg),
/// Requests are sent to constellation and fetches are checked manually
/// for cross-origin loads
InitiateNavigateRequest(RequestBuilder, /* cancellation_chan */ IpcReceiver<()>),
/// Broadcast a storage event to every same-origin pipeline.
/// The strings are key, old value and new value.
BroadcastStorageEvent(
StorageType,
ServoUrl,
Option<String>,
Option<String>,
Option<String>,
),
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
CreateCanvasPaintThread(
UntypedSize2D<u64>,
IpcSender<(IpcSender<CanvasMsg>, CanvasId)>,
),
/// Notifies the constellation that this frame has received focus.
Focus,
/// Get the top-level browsing context info for a given browsing context.
GetTopForBrowsingContext(
BrowsingContextId,
IpcSender<Option<TopLevelBrowsingContextId>>,
),
/// Get the browsing context id of the browsing context in which pipeline is
/// embedded and the parent pipeline id of that browsing context.
GetBrowsingContextInfo(
PipelineId,
IpcSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
),
/// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
GetChildBrowsingContextId(
BrowsingContextId,
usize,
IpcSender<Option<BrowsingContextId>>,
),
/// All pending loads are complete, and the `load` event for this pipeline
/// has been dispatched.
LoadComplete,
/// A new load has been requested, with an option to replace the current entry once loaded
/// instead of adding a new entry.
LoadUrl(LoadData, HistoryEntryReplacement),
/// Abort loading after sending a LoadUrl message.
AbortLoadUrl,
/// Post a message to the currently active window of a given browsing context.
PostMessage {
/// The target of the posted message.
target: BrowsingContextId,
/// The source of the posted message.
source: PipelineId,
/// The expected origin of the target.
target_origin: Option<ImmutableOrigin>,
/// The source origin of the message.
/// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
source_origin: ImmutableOrigin,
/// The data to be posted.
data: StructuredSerializedData,
},
/// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
NavigatedToFragment(ServoUrl, HistoryEntryReplacement),
/// HTMLIFrameElement Forward or Back traversal.
TraverseHistory(TraversalDirection),
/// Inform the constellation of a pushed history state.
PushHistoryState(HistoryStateId, ServoUrl),
/// Inform the constellation of a replaced history state.
ReplaceHistoryState(HistoryStateId, ServoUrl),
/// Gets the length of the joint session history from the constellation.
JointSessionHistoryLength(IpcSender<u32>),
/// Notification that this iframe should be removed.
/// Returns a list of pipelines which were closed.
RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
/// Notifies constellation that an iframe's visibility has been changed.
VisibilityChangeComplete(bool),
/// A load has been requested in an IFrame.
ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
/// A load of the initial `about:blank` has been completed in an IFrame.
ScriptNewIFrame(IFrameLoadInfoWithData, IpcSender<LayoutControlMsg>),
/// Script has opened a new auxiliary browsing context.
ScriptNewAuxiliary(
AuxiliaryBrowsingContextLoadInfo,
IpcSender<LayoutControlMsg>,
),
/// Mark a new document as active
ActivateDocument,
/// Set the document state for a pipeline (used by screenshot / reftests)
SetDocumentState(DocumentState),
/// Update the pipeline Url, which can change after redirections.
SetFinalUrl(ServoUrl),
/// Script has handled a touch event, and either prevented or allowed default actions.
TouchEventProcessed(EventResult),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<String>, LogEntry),
/// Discard the document.
DiscardDocument,
/// Discard the browsing context.
DiscardTopLevelBrowsingContext,
/// Notifies the constellation that this pipeline has exited.
PipelineExited,
/// Send messages from postMessage calls from serviceworker
/// to constellation for storing in service worker manager
ForwardDOMMessage(DOMMessage, ServoUrl),
/// https://w3c.github.io/ServiceWorker/#schedule-job-algorithm.
ScheduleJob(Job),
/// Get Window Informations size and position
GetClientWindow(IpcSender<(DeviceIntSize, DeviceIntPoint)>),
/// Get the screen size (pixel)
GetScreenSize(IpcSender<DeviceIntSize>),
/// Get the available screen size (pixel)
GetScreenAvailSize(IpcSender<DeviceIntSize>),
/// Notifies the constellation about media session events
/// (i.e. when there is metadata for the active media session, playback state changes...).
MediaSessionEvent(PipelineId, MediaSessionEvent),
/// Create a WebGPU Adapter instance
RequestAdapter(
IpcSender<WebGPUResponseResult>,
wgpu::instance::RequestAdapterOptions,
SmallVec<[wgpu::id::AdapterId; 4]>,
),
}
impl fmt::Debug for ScriptMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ScriptMsg::*;
let variant = match *self {
CompleteMessagePortTransfer(..) => "CompleteMessagePortTransfer",
MessagePortTransferResult(..) => "MessagePortTransferResult",
NewMessagePortRouter(..) => "NewMessagePortRouter",
RemoveMessagePortRouter(..) => "RemoveMessagePortRouter",
NewMessagePort(..) => "NewMessagePort",
RerouteMessagePort(..) => "RerouteMessagePort",
RemoveMessagePort(..) => "RemoveMessagePort",
MessagePortShipped(..) => "MessagePortShipped",
EntanglePorts(..) => "EntanglePorts",
NewBroadcastChannelRouter(..) => "NewBroadcastChannelRouter",
RemoveBroadcastChannelRouter(..) => "RemoveBroadcastChannelRouter",
RemoveBroadcastChannelNameInRouter(..) => "RemoveBroadcastChannelNameInRouter",
NewBroadcastChannelNameInRouter(..) => "NewBroadcastChannelNameInRouter",
ScheduleBroadcast(..) => "ScheduleBroadcast",
ForwardToEmbedder(..) => "ForwardToEmbedder",
InitiateNavigateRequest(..) => "InitiateNavigateRequest",
BroadcastStorageEvent(..) => "BroadcastStorageEvent",
ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
CreateCanvasPaintThread(..) => "CreateCanvasPaintThread",
Focus => "Focus",
GetBrowsingContextInfo(..) => "GetBrowsingContextInfo",
GetTopForBrowsingContext(..) => "GetParentBrowsingContext",
GetChildBrowsingContextId(..) => "GetChildBrowsingContextId",
LoadComplete => "LoadComplete",
LoadUrl(..) => "LoadUrl",
AbortLoadUrl => "AbortLoadUrl",
PostMessage {.. } => "PostMessage",
NavigatedToFragment(..) => "NavigatedToFragment",
TraverseHistory(..) => "TraverseHistory",
PushHistoryState(..) => "PushHistoryState",
ReplaceHistoryState(..) => "ReplaceHistoryState",
JointSessionHistoryLength(..) => "JointSessionHistoryLength",
RemoveIFrame(..) => "RemoveIFrame",
VisibilityChangeComplete(..) => "VisibilityChangeComplete",
ScriptLoadedURLInIFrame(..) => "ScriptLoadedURLInIFrame",
ScriptNewIFrame(..) => "ScriptNewIFrame",
ScriptNewAuxiliary(..) => "ScriptNewAuxiliary",
ActivateDocument => "ActivateDocument",
SetDocumentState(..) => "SetDocumentState",
SetFinalUrl(..) => "SetFinalUrl",
TouchEventProcessed(..) => "TouchEventProcessed",
LogEntry(..) => "LogEntry",
DiscardDocument => "DiscardDocument",
DiscardTopLevelBrowsingContext => "DiscardTopLevelBrowsingContext",
PipelineExited => "PipelineExited",
ForwardDOMMessage(..) => "ForwardDOMMessage",
ScheduleJob(..) => "ScheduleJob",
GetClientWindow(..) => "GetClientWindow",
GetScreenSize(..) => "GetScreenSize",
GetScreenAvailSize(..) => "GetScreenAvailSize",
MediaSessionEvent(..) => "MediaSessionEvent",
RequestAdapter(..) => "RequestAdapter",
};
write!(formatter, "ScriptMsg::{}", variant)
}
}
/// Entities required to spawn service workers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ScopeThings {
/// script resource url
pub script_url: ServoUrl,
/// network load origin of the resource
pub worker_load_origin: WorkerScriptLoadOrigin,
/// base resources required to create worker global scopes
pub init: WorkerGlobalScopeInit,
/// the port to receive devtools message from
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// service worker id
pub worker_id: WorkerId,
}
/// Message that gets passed to service worker scope on postMessage
#[derive(Debug, Deserialize, Serialize)]
pub struct DOMMessage {
/// The origin of the message
pub origin: ImmutableOrigin,
/// The payload of the message
pub data: StructuredSerializedData,
}
/// Channels to allow service worker manager to communicate with constellation and resource thread
#[derive(Deserialize, Serialize)]
pub struct SWManagerSenders {
/// Sender of messages to the constellation.
pub swmanager_sender: IpcSender<SWManagerMsg>,
/// Sender for communicating with resource thread.
pub resource_sender: IpcSender<CoreResourceMsg>,
/// Sender of messages to the manager.
pub own_sender: IpcSender<ServiceWorkerMsg>,
/// Receiver of messages from the constellation.
pub receiver: IpcReceiver<ServiceWorkerMsg>,
}
/// Messages sent to Service Worker Manager thread
#[derive(Debug, Deserialize, Serialize)]
pub enum ServiceWorkerMsg {
/// Timeout message sent by active service workers
Timeout(ServoUrl),
/// Message sent by constellation to forward to a running service worker
ForwardDOMMessage(DOMMessage, ServoUrl),
/// https://w3c.github.io/ServiceWorker/#schedule-job-algorithm
ScheduleJob(Job),
/// Exit the service worker manager
Exit,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
/// https://w3c.github.io/ServiceWorker/#dfn-job-type
pub enum JobType {
/// <https://w3c.github.io/ServiceWorker/#register>
Register,
/// <https://w3c.github.io/ServiceWorker/#unregister-algorithm>
Unregister,
/// <https://w3c.github.io/ServiceWorker/#update-algorithm
Update,
}
#[derive(Debug, Deserialize, Serialize)]
/// The kind of error the job promise should be rejected with.
pub enum JobError {
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
TypeError,
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
SecurityError,
}
#[derive(Debug, Deserialize, Serialize)]
/// Messages sent from Job algorithms steps running in the SW manager,
/// in order to resolve or reject the job promise.
pub enum JobResult {
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
RejectPromise(JobError),
/// https://w3c.github.io/ServiceWorker/#resolve-job-promise
ResolvePromise(Job, JobResultValue),
}
#[derive(Debug, Deserialize, Serialize)]
/// Jobs are resolved with the help of various values. | /// Data representing a serviceworker registration.
Registration {
/// The Id of the registration.
id: ServiceWorkerRegistrationId,
/// The installing worker, if any.
installing_worker: Option<ServiceWorkerId>,
/// The waiting worker, if any.
waiting_worker: Option<ServiceWorkerId>,
/// The active worker, if any.
active_worker: Option<ServiceWorkerId>,
},
}
#[derive(Debug, Deserialize, Serialize)]
/// https://w3c.github.io/ServiceWorker/#dfn-job
pub struct Job {
/// <https://w3c.github.io/ServiceWorker/#dfn-job-type>
pub job_type: JobType,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-scope-url>
pub scope_url: ServoUrl,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-script-url>
pub script_url: ServoUrl,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-client>
pub client: IpcSender<JobResult>,
/// <https://w3c.github.io/ServiceWorker/#job-referrer>
pub referrer: ServoUrl,
/// Various data needed to process job.
pub scope_things: Option<ScopeThings>,
}
impl Job {
/// https://w3c.github.io/ServiceWorker/#create-job-algorithm
pub fn create_job(
job_type: JobType,
scope_url: ServoUrl,
script_url: ServoUrl,
client: IpcSender<JobResult>,
referrer: ServoUrl,
scope_things: Option<ScopeThings>,
) -> Job {
Job {
job_type,
scope_url,
script_url,
client,
referrer,
scope_things,
}
}
}
impl PartialEq for Job {
/// Equality criteria as described in https://w3c.github.io/ServiceWorker/#dfn-job-equivalent
fn eq(&self, other: &Self) -> bool {
// TODO: match on job type, take worker type and `update_via_cache_mode` into account.
let same_job = self.job_type == other.job_type;
if same_job {
match self.job_type {
JobType::Register | JobType::Update => {
self.scope_url == other.scope_url && self.script_url == other.script_url
},
JobType::Unregister => self.scope_url == other.scope_url,
}
} else {
false
}
}
}
/// Messages outgoing from the Service Worker Manager thread to constellation
#[derive(Debug, Deserialize, Serialize)]
pub enum SWManagerMsg {
/// Placeholder to keep the enum,
/// as it will be needed when implementing
/// https://github.com/servo/servo/issues/24660
PostMessageToClient,
} | pub enum JobResultValue { | random_line_split |
script_msg.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::AnimationState;
use crate::AuxiliaryBrowsingContextLoadInfo;
use crate::BroadcastMsg;
use crate::DocumentState;
use crate::IFrameLoadInfoWithData;
use crate::LayoutControlMsg;
use crate::LoadData;
use crate::MessagePortMsg;
use crate::PortMessageTask;
use crate::StructuredSerializedData;
use crate::WindowSizeType;
use crate::WorkerGlobalScopeInit;
use crate::WorkerScriptLoadOrigin;
use canvas_traits::canvas::{CanvasId, CanvasMsg};
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use embedder_traits::{EmbedderMsg, MediaSessionEvent};
use euclid::default::Size2D as UntypedSize2D;
use euclid::Size2D;
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use msg::constellation_msg::{
BroadcastChannelRouterId, BrowsingContextId, MessagePortId, MessagePortRouterId, PipelineId,
TopLevelBrowsingContextId,
};
use msg::constellation_msg::{HistoryStateId, TraversalDirection};
use msg::constellation_msg::{ServiceWorkerId, ServiceWorkerRegistrationId};
use net_traits::request::RequestBuilder;
use net_traits::storage_thread::StorageType;
use net_traits::CoreResourceMsg;
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use smallvec::SmallVec;
use std::collections::{HashMap, VecDeque};
use std::fmt;
use style_traits::viewport::ViewportConstraints;
use style_traits::CSSPixel;
use webgpu::{wgpu, WebGPUResponseResult};
use webrender_api::units::{DeviceIntPoint, DeviceIntSize};
/// A particular iframe's size, associated with a browsing context.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct IFrameSize {
/// The child browsing context for this iframe.
pub id: BrowsingContextId,
/// The size of the iframe.
pub size: Size2D<f32, CSSPixel>,
}
/// An iframe sizing operation.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct IFrameSizeMsg {
/// The iframe sizing data.
pub data: IFrameSize,
/// The kind of sizing operation.
pub type_: WindowSizeType,
}
/// Messages from the layout to the constellation.
#[derive(Deserialize, Serialize)]
pub enum LayoutMsg {
/// Inform the constellation of the size of the iframe's viewport.
IFrameSizes(Vec<IFrameSizeMsg>),
/// Requests that the constellation inform the compositor that it needs to record
/// the time when the frame with the given ID (epoch) is painted.
PendingPaintMetric(PipelineId, Epoch),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
impl fmt::Debug for LayoutMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::LayoutMsg::*;
let variant = match *self {
IFrameSizes(..) => "IFrameSizes",
PendingPaintMetric(..) => "PendingPaintMetric",
ViewportConstrained(..) => "ViewportConstrained",
};
write!(formatter, "LayoutMsg::{}", variant)
}
}
/// Whether a DOM event was prevented by web content
#[derive(Debug, Deserialize, Serialize)]
pub enum EventResult {
/// Allowed by web content
DefaultAllowed,
/// Prevented by web content
DefaultPrevented,
}
/// A log entry reported to the constellation
/// We don't report all log entries, just serious ones.
/// We need a separate type for this because `LogLevel` isn't serializable.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum LogEntry {
/// Panic, with a reason and backtrace
Panic(String, String),
/// Error, with a reason
Error(String),
/// warning, with a reason
Warn(String),
}
/// https://html.spec.whatwg.org/multipage/#replacement-enabled
#[derive(Debug, Deserialize, Serialize)]
pub enum HistoryEntryReplacement {
/// Traverse the history with replacement enabled.
Enabled,
/// Traverse the history with replacement disabled.
Disabled,
}
/// Messages from the script to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ScriptMsg {
/// Request to complete the transfer of a set of ports to a router.
CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>),
/// The results of attempting to complete the transfer of a batch of ports.
MessagePortTransferResult(
/* The router whose transfer of ports succeeded, if any */
Option<MessagePortRouterId>,
/* The ids of ports transferred successfully */
Vec<MessagePortId>,
/* The ids, and buffers, of ports whose transfer failed */
HashMap<MessagePortId, VecDeque<PortMessageTask>>,
),
/// A new message-port was created or transferred, with corresponding control-sender.
NewMessagePort(MessagePortRouterId, MessagePortId),
/// A global has started managing message-ports
NewMessagePortRouter(MessagePortRouterId, IpcSender<MessagePortMsg>),
/// A global has stopped managing message-ports
RemoveMessagePortRouter(MessagePortRouterId),
/// A task requires re-routing to an already shipped message-port.
RerouteMessagePort(MessagePortId, PortMessageTask),
/// A message-port was shipped, let the entangled port know.
MessagePortShipped(MessagePortId),
/// A message-port has been discarded by script.
RemoveMessagePort(MessagePortId),
/// Entangle two message-ports.
EntanglePorts(MessagePortId, MessagePortId),
/// A global has started managing broadcast-channels.
NewBroadcastChannelRouter(
BroadcastChannelRouterId,
IpcSender<BroadcastMsg>,
ImmutableOrigin,
),
/// A global has stopped managing broadcast-channels.
RemoveBroadcastChannelRouter(BroadcastChannelRouterId, ImmutableOrigin),
/// A global started managing broadcast channels for a given channel-name.
NewBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
/// A global stopped managing broadcast channels for a given channel-name.
RemoveBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
/// Broadcast a message to all same-origin broadcast channels,
/// excluding the source of the broadcast.
ScheduleBroadcast(BroadcastChannelRouterId, BroadcastMsg),
/// Forward a message to the embedder.
ForwardToEmbedder(EmbedderMsg),
/// Requests are sent to constellation and fetches are checked manually
/// for cross-origin loads
InitiateNavigateRequest(RequestBuilder, /* cancellation_chan */ IpcReceiver<()>),
/// Broadcast a storage event to every same-origin pipeline.
/// The strings are key, old value and new value.
BroadcastStorageEvent(
StorageType,
ServoUrl,
Option<String>,
Option<String>,
Option<String>,
),
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
CreateCanvasPaintThread(
UntypedSize2D<u64>,
IpcSender<(IpcSender<CanvasMsg>, CanvasId)>,
),
/// Notifies the constellation that this frame has received focus.
Focus,
/// Get the top-level browsing context info for a given browsing context.
GetTopForBrowsingContext(
BrowsingContextId,
IpcSender<Option<TopLevelBrowsingContextId>>,
),
/// Get the browsing context id of the browsing context in which pipeline is
/// embedded and the parent pipeline id of that browsing context.
GetBrowsingContextInfo(
PipelineId,
IpcSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
),
/// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
GetChildBrowsingContextId(
BrowsingContextId,
usize,
IpcSender<Option<BrowsingContextId>>,
),
/// All pending loads are complete, and the `load` event for this pipeline
/// has been dispatched.
LoadComplete,
/// A new load has been requested, with an option to replace the current entry once loaded
/// instead of adding a new entry.
LoadUrl(LoadData, HistoryEntryReplacement),
/// Abort loading after sending a LoadUrl message.
AbortLoadUrl,
/// Post a message to the currently active window of a given browsing context.
PostMessage {
/// The target of the posted message.
target: BrowsingContextId,
/// The source of the posted message.
source: PipelineId,
/// The expected origin of the target.
target_origin: Option<ImmutableOrigin>,
/// The source origin of the message.
/// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
source_origin: ImmutableOrigin,
/// The data to be posted.
data: StructuredSerializedData,
},
/// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
NavigatedToFragment(ServoUrl, HistoryEntryReplacement),
/// HTMLIFrameElement Forward or Back traversal.
TraverseHistory(TraversalDirection),
/// Inform the constellation of a pushed history state.
PushHistoryState(HistoryStateId, ServoUrl),
/// Inform the constellation of a replaced history state.
ReplaceHistoryState(HistoryStateId, ServoUrl),
/// Gets the length of the joint session history from the constellation.
JointSessionHistoryLength(IpcSender<u32>),
/// Notification that this iframe should be removed.
/// Returns a list of pipelines which were closed.
RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
/// Notifies constellation that an iframe's visibility has been changed.
VisibilityChangeComplete(bool),
/// A load has been requested in an IFrame.
ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
/// A load of the initial `about:blank` has been completed in an IFrame.
ScriptNewIFrame(IFrameLoadInfoWithData, IpcSender<LayoutControlMsg>),
/// Script has opened a new auxiliary browsing context.
ScriptNewAuxiliary(
AuxiliaryBrowsingContextLoadInfo,
IpcSender<LayoutControlMsg>,
),
/// Mark a new document as active
ActivateDocument,
/// Set the document state for a pipeline (used by screenshot / reftests)
SetDocumentState(DocumentState),
/// Update the pipeline Url, which can change after redirections.
SetFinalUrl(ServoUrl),
/// Script has handled a touch event, and either prevented or allowed default actions.
TouchEventProcessed(EventResult),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<String>, LogEntry),
/// Discard the document.
DiscardDocument,
/// Discard the browsing context.
DiscardTopLevelBrowsingContext,
/// Notifies the constellation that this pipeline has exited.
PipelineExited,
/// Send messages from postMessage calls from serviceworker
/// to constellation for storing in service worker manager
ForwardDOMMessage(DOMMessage, ServoUrl),
/// https://w3c.github.io/ServiceWorker/#schedule-job-algorithm.
ScheduleJob(Job),
/// Get Window Informations size and position
GetClientWindow(IpcSender<(DeviceIntSize, DeviceIntPoint)>),
/// Get the screen size (pixel)
GetScreenSize(IpcSender<DeviceIntSize>),
/// Get the available screen size (pixel)
GetScreenAvailSize(IpcSender<DeviceIntSize>),
/// Notifies the constellation about media session events
/// (i.e. when there is metadata for the active media session, playback state changes...).
MediaSessionEvent(PipelineId, MediaSessionEvent),
/// Create a WebGPU Adapter instance
RequestAdapter(
IpcSender<WebGPUResponseResult>,
wgpu::instance::RequestAdapterOptions,
SmallVec<[wgpu::id::AdapterId; 4]>,
),
}
impl fmt::Debug for ScriptMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result | ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
CreateCanvasPaintThread(..) => "CreateCanvasPaintThread",
Focus => "Focus",
GetBrowsingContextInfo(..) => "GetBrowsingContextInfo",
GetTopForBrowsingContext(..) => "GetParentBrowsingContext",
GetChildBrowsingContextId(..) => "GetChildBrowsingContextId",
LoadComplete => "LoadComplete",
LoadUrl(..) => "LoadUrl",
AbortLoadUrl => "AbortLoadUrl",
PostMessage {.. } => "PostMessage",
NavigatedToFragment(..) => "NavigatedToFragment",
TraverseHistory(..) => "TraverseHistory",
PushHistoryState(..) => "PushHistoryState",
ReplaceHistoryState(..) => "ReplaceHistoryState",
JointSessionHistoryLength(..) => "JointSessionHistoryLength",
RemoveIFrame(..) => "RemoveIFrame",
VisibilityChangeComplete(..) => "VisibilityChangeComplete",
ScriptLoadedURLInIFrame(..) => "ScriptLoadedURLInIFrame",
ScriptNewIFrame(..) => "ScriptNewIFrame",
ScriptNewAuxiliary(..) => "ScriptNewAuxiliary",
ActivateDocument => "ActivateDocument",
SetDocumentState(..) => "SetDocumentState",
SetFinalUrl(..) => "SetFinalUrl",
TouchEventProcessed(..) => "TouchEventProcessed",
LogEntry(..) => "LogEntry",
DiscardDocument => "DiscardDocument",
DiscardTopLevelBrowsingContext => "DiscardTopLevelBrowsingContext",
PipelineExited => "PipelineExited",
ForwardDOMMessage(..) => "ForwardDOMMessage",
ScheduleJob(..) => "ScheduleJob",
GetClientWindow(..) => "GetClientWindow",
GetScreenSize(..) => "GetScreenSize",
GetScreenAvailSize(..) => "GetScreenAvailSize",
MediaSessionEvent(..) => "MediaSessionEvent",
RequestAdapter(..) => "RequestAdapter",
};
write!(formatter, "ScriptMsg::{}", variant)
}
}
/// Entities required to spawn service workers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ScopeThings {
/// script resource url
pub script_url: ServoUrl,
/// network load origin of the resource
pub worker_load_origin: WorkerScriptLoadOrigin,
/// base resources required to create worker global scopes
pub init: WorkerGlobalScopeInit,
/// the port to receive devtools message from
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// service worker id
pub worker_id: WorkerId,
}
/// Message that gets passed to service worker scope on postMessage
#[derive(Debug, Deserialize, Serialize)]
pub struct DOMMessage {
/// The origin of the message
pub origin: ImmutableOrigin,
/// The payload of the message
pub data: StructuredSerializedData,
}
/// Channels to allow service worker manager to communicate with constellation and resource thread
#[derive(Deserialize, Serialize)]
pub struct SWManagerSenders {
/// Sender of messages to the constellation.
pub swmanager_sender: IpcSender<SWManagerMsg>,
/// Sender for communicating with resource thread.
pub resource_sender: IpcSender<CoreResourceMsg>,
/// Sender of messages to the manager.
pub own_sender: IpcSender<ServiceWorkerMsg>,
/// Receiver of messages from the constellation.
pub receiver: IpcReceiver<ServiceWorkerMsg>,
}
/// Messages sent to Service Worker Manager thread
#[derive(Debug, Deserialize, Serialize)]
pub enum ServiceWorkerMsg {
/// Timeout message sent by active service workers
Timeout(ServoUrl),
/// Message sent by constellation to forward to a running service worker
ForwardDOMMessage(DOMMessage, ServoUrl),
/// https://w3c.github.io/ServiceWorker/#schedule-job-algorithm
ScheduleJob(Job),
/// Exit the service worker manager
Exit,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
/// https://w3c.github.io/ServiceWorker/#dfn-job-type
pub enum JobType {
/// <https://w3c.github.io/ServiceWorker/#register>
Register,
/// <https://w3c.github.io/ServiceWorker/#unregister-algorithm>
Unregister,
/// <https://w3c.github.io/ServiceWorker/#update-algorithm
Update,
}
#[derive(Debug, Deserialize, Serialize)]
/// The kind of error the job promise should be rejected with.
pub enum JobError {
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
TypeError,
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
SecurityError,
}
#[derive(Debug, Deserialize, Serialize)]
/// Messages sent from Job algorithms steps running in the SW manager,
/// in order to resolve or reject the job promise.
pub enum JobResult {
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
RejectPromise(JobError),
/// https://w3c.github.io/ServiceWorker/#resolve-job-promise
ResolvePromise(Job, JobResultValue),
}
#[derive(Debug, Deserialize, Serialize)]
/// Jobs are resolved with the help of various values.
pub enum JobResultValue {
/// Data representing a serviceworker registration.
Registration {
/// The Id of the registration.
id: ServiceWorkerRegistrationId,
/// The installing worker, if any.
installing_worker: Option<ServiceWorkerId>,
/// The waiting worker, if any.
waiting_worker: Option<ServiceWorkerId>,
/// The active worker, if any.
active_worker: Option<ServiceWorkerId>,
},
}
#[derive(Debug, Deserialize, Serialize)]
/// https://w3c.github.io/ServiceWorker/#dfn-job
pub struct Job {
/// <https://w3c.github.io/ServiceWorker/#dfn-job-type>
pub job_type: JobType,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-scope-url>
pub scope_url: ServoUrl,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-script-url>
pub script_url: ServoUrl,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-client>
pub client: IpcSender<JobResult>,
/// <https://w3c.github.io/ServiceWorker/#job-referrer>
pub referrer: ServoUrl,
/// Various data needed to process job.
pub scope_things: Option<ScopeThings>,
}
impl Job {
/// https://w3c.github.io/ServiceWorker/#create-job-algorithm
pub fn create_job(
job_type: JobType,
scope_url: ServoUrl,
script_url: ServoUrl,
client: IpcSender<JobResult>,
referrer: ServoUrl,
scope_things: Option<ScopeThings>,
) -> Job {
Job {
job_type,
scope_url,
script_url,
client,
referrer,
scope_things,
}
}
}
impl PartialEq for Job {
/// Equality criteria as described in https://w3c.github.io/ServiceWorker/#dfn-job-equivalent
fn eq(&self, other: &Self) -> bool {
// TODO: match on job type, take worker type and `update_via_cache_mode` into account.
let same_job = self.job_type == other.job_type;
if same_job {
match self.job_type {
JobType::Register | JobType::Update => {
self.scope_url == other.scope_url && self.script_url == other.script_url
},
JobType::Unregister => self.scope_url == other.scope_url,
}
} else {
false
}
}
}
/// Messages outgoing from the Service Worker Manager thread to constellation
#[derive(Debug, Deserialize, Serialize)]
pub enum SWManagerMsg {
/// Placeholder to keep the enum,
/// as it will be needed when implementing
/// https://github.com/servo/servo/issues/24660
PostMessageToClient,
}
| {
use self::ScriptMsg::*;
let variant = match *self {
CompleteMessagePortTransfer(..) => "CompleteMessagePortTransfer",
MessagePortTransferResult(..) => "MessagePortTransferResult",
NewMessagePortRouter(..) => "NewMessagePortRouter",
RemoveMessagePortRouter(..) => "RemoveMessagePortRouter",
NewMessagePort(..) => "NewMessagePort",
RerouteMessagePort(..) => "RerouteMessagePort",
RemoveMessagePort(..) => "RemoveMessagePort",
MessagePortShipped(..) => "MessagePortShipped",
EntanglePorts(..) => "EntanglePorts",
NewBroadcastChannelRouter(..) => "NewBroadcastChannelRouter",
RemoveBroadcastChannelRouter(..) => "RemoveBroadcastChannelRouter",
RemoveBroadcastChannelNameInRouter(..) => "RemoveBroadcastChannelNameInRouter",
NewBroadcastChannelNameInRouter(..) => "NewBroadcastChannelNameInRouter",
ScheduleBroadcast(..) => "ScheduleBroadcast",
ForwardToEmbedder(..) => "ForwardToEmbedder",
InitiateNavigateRequest(..) => "InitiateNavigateRequest",
BroadcastStorageEvent(..) => "BroadcastStorageEvent", | identifier_body |
script_msg.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::AnimationState;
use crate::AuxiliaryBrowsingContextLoadInfo;
use crate::BroadcastMsg;
use crate::DocumentState;
use crate::IFrameLoadInfoWithData;
use crate::LayoutControlMsg;
use crate::LoadData;
use crate::MessagePortMsg;
use crate::PortMessageTask;
use crate::StructuredSerializedData;
use crate::WindowSizeType;
use crate::WorkerGlobalScopeInit;
use crate::WorkerScriptLoadOrigin;
use canvas_traits::canvas::{CanvasId, CanvasMsg};
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use embedder_traits::{EmbedderMsg, MediaSessionEvent};
use euclid::default::Size2D as UntypedSize2D;
use euclid::Size2D;
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use msg::constellation_msg::{
BroadcastChannelRouterId, BrowsingContextId, MessagePortId, MessagePortRouterId, PipelineId,
TopLevelBrowsingContextId,
};
use msg::constellation_msg::{HistoryStateId, TraversalDirection};
use msg::constellation_msg::{ServiceWorkerId, ServiceWorkerRegistrationId};
use net_traits::request::RequestBuilder;
use net_traits::storage_thread::StorageType;
use net_traits::CoreResourceMsg;
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use smallvec::SmallVec;
use std::collections::{HashMap, VecDeque};
use std::fmt;
use style_traits::viewport::ViewportConstraints;
use style_traits::CSSPixel;
use webgpu::{wgpu, WebGPUResponseResult};
use webrender_api::units::{DeviceIntPoint, DeviceIntSize};
/// A particular iframe's size, associated with a browsing context.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct IFrameSize {
/// The child browsing context for this iframe.
pub id: BrowsingContextId,
/// The size of the iframe.
pub size: Size2D<f32, CSSPixel>,
}
/// An iframe sizing operation.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct IFrameSizeMsg {
/// The iframe sizing data.
pub data: IFrameSize,
/// The kind of sizing operation.
pub type_: WindowSizeType,
}
/// Messages from the layout to the constellation.
#[derive(Deserialize, Serialize)]
pub enum LayoutMsg {
/// Inform the constellation of the size of the iframe's viewport.
IFrameSizes(Vec<IFrameSizeMsg>),
/// Requests that the constellation inform the compositor that it needs to record
/// the time when the frame with the given ID (epoch) is painted.
PendingPaintMetric(PipelineId, Epoch),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
impl fmt::Debug for LayoutMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::LayoutMsg::*;
let variant = match *self {
IFrameSizes(..) => "IFrameSizes",
PendingPaintMetric(..) => "PendingPaintMetric",
ViewportConstrained(..) => "ViewportConstrained",
};
write!(formatter, "LayoutMsg::{}", variant)
}
}
/// Whether a DOM event was prevented by web content
#[derive(Debug, Deserialize, Serialize)]
pub enum EventResult {
/// Allowed by web content
DefaultAllowed,
/// Prevented by web content
DefaultPrevented,
}
/// A log entry reported to the constellation
/// We don't report all log entries, just serious ones.
/// We need a separate type for this because `LogLevel` isn't serializable.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum LogEntry {
/// Panic, with a reason and backtrace
Panic(String, String),
/// Error, with a reason
Error(String),
/// warning, with a reason
Warn(String),
}
/// https://html.spec.whatwg.org/multipage/#replacement-enabled
#[derive(Debug, Deserialize, Serialize)]
pub enum HistoryEntryReplacement {
/// Traverse the history with replacement enabled.
Enabled,
/// Traverse the history with replacement disabled.
Disabled,
}
/// Messages from the script to the constellation.
#[derive(Deserialize, Serialize)]
pub enum | {
/// Request to complete the transfer of a set of ports to a router.
CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>),
/// The results of attempting to complete the transfer of a batch of ports.
MessagePortTransferResult(
/* The router whose transfer of ports succeeded, if any */
Option<MessagePortRouterId>,
/* The ids of ports transferred successfully */
Vec<MessagePortId>,
/* The ids, and buffers, of ports whose transfer failed */
HashMap<MessagePortId, VecDeque<PortMessageTask>>,
),
/// A new message-port was created or transferred, with corresponding control-sender.
NewMessagePort(MessagePortRouterId, MessagePortId),
/// A global has started managing message-ports
NewMessagePortRouter(MessagePortRouterId, IpcSender<MessagePortMsg>),
/// A global has stopped managing message-ports
RemoveMessagePortRouter(MessagePortRouterId),
/// A task requires re-routing to an already shipped message-port.
RerouteMessagePort(MessagePortId, PortMessageTask),
/// A message-port was shipped, let the entangled port know.
MessagePortShipped(MessagePortId),
/// A message-port has been discarded by script.
RemoveMessagePort(MessagePortId),
/// Entangle two message-ports.
EntanglePorts(MessagePortId, MessagePortId),
/// A global has started managing broadcast-channels.
NewBroadcastChannelRouter(
BroadcastChannelRouterId,
IpcSender<BroadcastMsg>,
ImmutableOrigin,
),
/// A global has stopped managing broadcast-channels.
RemoveBroadcastChannelRouter(BroadcastChannelRouterId, ImmutableOrigin),
/// A global started managing broadcast channels for a given channel-name.
NewBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
/// A global stopped managing broadcast channels for a given channel-name.
RemoveBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
/// Broadcast a message to all same-origin broadcast channels,
/// excluding the source of the broadcast.
ScheduleBroadcast(BroadcastChannelRouterId, BroadcastMsg),
/// Forward a message to the embedder.
ForwardToEmbedder(EmbedderMsg),
/// Requests are sent to constellation and fetches are checked manually
/// for cross-origin loads
InitiateNavigateRequest(RequestBuilder, /* cancellation_chan */ IpcReceiver<()>),
/// Broadcast a storage event to every same-origin pipeline.
/// The strings are key, old value and new value.
BroadcastStorageEvent(
StorageType,
ServoUrl,
Option<String>,
Option<String>,
Option<String>,
),
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
CreateCanvasPaintThread(
UntypedSize2D<u64>,
IpcSender<(IpcSender<CanvasMsg>, CanvasId)>,
),
/// Notifies the constellation that this frame has received focus.
Focus,
/// Get the top-level browsing context info for a given browsing context.
GetTopForBrowsingContext(
BrowsingContextId,
IpcSender<Option<TopLevelBrowsingContextId>>,
),
/// Get the browsing context id of the browsing context in which pipeline is
/// embedded and the parent pipeline id of that browsing context.
GetBrowsingContextInfo(
PipelineId,
IpcSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
),
/// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
GetChildBrowsingContextId(
BrowsingContextId,
usize,
IpcSender<Option<BrowsingContextId>>,
),
/// All pending loads are complete, and the `load` event for this pipeline
/// has been dispatched.
LoadComplete,
/// A new load has been requested, with an option to replace the current entry once loaded
/// instead of adding a new entry.
LoadUrl(LoadData, HistoryEntryReplacement),
/// Abort loading after sending a LoadUrl message.
AbortLoadUrl,
/// Post a message to the currently active window of a given browsing context.
PostMessage {
/// The target of the posted message.
target: BrowsingContextId,
/// The source of the posted message.
source: PipelineId,
/// The expected origin of the target.
target_origin: Option<ImmutableOrigin>,
/// The source origin of the message.
/// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
source_origin: ImmutableOrigin,
/// The data to be posted.
data: StructuredSerializedData,
},
/// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
NavigatedToFragment(ServoUrl, HistoryEntryReplacement),
/// HTMLIFrameElement Forward or Back traversal.
TraverseHistory(TraversalDirection),
/// Inform the constellation of a pushed history state.
PushHistoryState(HistoryStateId, ServoUrl),
/// Inform the constellation of a replaced history state.
ReplaceHistoryState(HistoryStateId, ServoUrl),
/// Gets the length of the joint session history from the constellation.
JointSessionHistoryLength(IpcSender<u32>),
/// Notification that this iframe should be removed.
/// Returns a list of pipelines which were closed.
RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
/// Notifies constellation that an iframe's visibility has been changed.
VisibilityChangeComplete(bool),
/// A load has been requested in an IFrame.
ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
/// A load of the initial `about:blank` has been completed in an IFrame.
ScriptNewIFrame(IFrameLoadInfoWithData, IpcSender<LayoutControlMsg>),
/// Script has opened a new auxiliary browsing context.
ScriptNewAuxiliary(
AuxiliaryBrowsingContextLoadInfo,
IpcSender<LayoutControlMsg>,
),
/// Mark a new document as active
ActivateDocument,
/// Set the document state for a pipeline (used by screenshot / reftests)
SetDocumentState(DocumentState),
/// Update the pipeline Url, which can change after redirections.
SetFinalUrl(ServoUrl),
/// Script has handled a touch event, and either prevented or allowed default actions.
TouchEventProcessed(EventResult),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<String>, LogEntry),
/// Discard the document.
DiscardDocument,
/// Discard the browsing context.
DiscardTopLevelBrowsingContext,
/// Notifies the constellation that this pipeline has exited.
PipelineExited,
/// Send messages from postMessage calls from serviceworker
/// to constellation for storing in service worker manager
ForwardDOMMessage(DOMMessage, ServoUrl),
/// https://w3c.github.io/ServiceWorker/#schedule-job-algorithm.
ScheduleJob(Job),
/// Get Window Informations size and position
GetClientWindow(IpcSender<(DeviceIntSize, DeviceIntPoint)>),
/// Get the screen size (pixel)
GetScreenSize(IpcSender<DeviceIntSize>),
/// Get the available screen size (pixel)
GetScreenAvailSize(IpcSender<DeviceIntSize>),
/// Notifies the constellation about media session events
/// (i.e. when there is metadata for the active media session, playback state changes...).
MediaSessionEvent(PipelineId, MediaSessionEvent),
/// Create a WebGPU Adapter instance
RequestAdapter(
IpcSender<WebGPUResponseResult>,
wgpu::instance::RequestAdapterOptions,
SmallVec<[wgpu::id::AdapterId; 4]>,
),
}
impl fmt::Debug for ScriptMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ScriptMsg::*;
let variant = match *self {
CompleteMessagePortTransfer(..) => "CompleteMessagePortTransfer",
MessagePortTransferResult(..) => "MessagePortTransferResult",
NewMessagePortRouter(..) => "NewMessagePortRouter",
RemoveMessagePortRouter(..) => "RemoveMessagePortRouter",
NewMessagePort(..) => "NewMessagePort",
RerouteMessagePort(..) => "RerouteMessagePort",
RemoveMessagePort(..) => "RemoveMessagePort",
MessagePortShipped(..) => "MessagePortShipped",
EntanglePorts(..) => "EntanglePorts",
NewBroadcastChannelRouter(..) => "NewBroadcastChannelRouter",
RemoveBroadcastChannelRouter(..) => "RemoveBroadcastChannelRouter",
RemoveBroadcastChannelNameInRouter(..) => "RemoveBroadcastChannelNameInRouter",
NewBroadcastChannelNameInRouter(..) => "NewBroadcastChannelNameInRouter",
ScheduleBroadcast(..) => "ScheduleBroadcast",
ForwardToEmbedder(..) => "ForwardToEmbedder",
InitiateNavigateRequest(..) => "InitiateNavigateRequest",
BroadcastStorageEvent(..) => "BroadcastStorageEvent",
ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
CreateCanvasPaintThread(..) => "CreateCanvasPaintThread",
Focus => "Focus",
GetBrowsingContextInfo(..) => "GetBrowsingContextInfo",
GetTopForBrowsingContext(..) => "GetParentBrowsingContext",
GetChildBrowsingContextId(..) => "GetChildBrowsingContextId",
LoadComplete => "LoadComplete",
LoadUrl(..) => "LoadUrl",
AbortLoadUrl => "AbortLoadUrl",
PostMessage {.. } => "PostMessage",
NavigatedToFragment(..) => "NavigatedToFragment",
TraverseHistory(..) => "TraverseHistory",
PushHistoryState(..) => "PushHistoryState",
ReplaceHistoryState(..) => "ReplaceHistoryState",
JointSessionHistoryLength(..) => "JointSessionHistoryLength",
RemoveIFrame(..) => "RemoveIFrame",
VisibilityChangeComplete(..) => "VisibilityChangeComplete",
ScriptLoadedURLInIFrame(..) => "ScriptLoadedURLInIFrame",
ScriptNewIFrame(..) => "ScriptNewIFrame",
ScriptNewAuxiliary(..) => "ScriptNewAuxiliary",
ActivateDocument => "ActivateDocument",
SetDocumentState(..) => "SetDocumentState",
SetFinalUrl(..) => "SetFinalUrl",
TouchEventProcessed(..) => "TouchEventProcessed",
LogEntry(..) => "LogEntry",
DiscardDocument => "DiscardDocument",
DiscardTopLevelBrowsingContext => "DiscardTopLevelBrowsingContext",
PipelineExited => "PipelineExited",
ForwardDOMMessage(..) => "ForwardDOMMessage",
ScheduleJob(..) => "ScheduleJob",
GetClientWindow(..) => "GetClientWindow",
GetScreenSize(..) => "GetScreenSize",
GetScreenAvailSize(..) => "GetScreenAvailSize",
MediaSessionEvent(..) => "MediaSessionEvent",
RequestAdapter(..) => "RequestAdapter",
};
write!(formatter, "ScriptMsg::{}", variant)
}
}
/// Entities required to spawn service workers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ScopeThings {
/// script resource url
pub script_url: ServoUrl,
/// network load origin of the resource
pub worker_load_origin: WorkerScriptLoadOrigin,
/// base resources required to create worker global scopes
pub init: WorkerGlobalScopeInit,
/// the port to receive devtools message from
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// service worker id
pub worker_id: WorkerId,
}
/// Message that gets passed to service worker scope on postMessage
#[derive(Debug, Deserialize, Serialize)]
pub struct DOMMessage {
/// The origin of the message
pub origin: ImmutableOrigin,
/// The payload of the message
pub data: StructuredSerializedData,
}
/// Channels to allow service worker manager to communicate with constellation and resource thread
#[derive(Deserialize, Serialize)]
pub struct SWManagerSenders {
/// Sender of messages to the constellation.
pub swmanager_sender: IpcSender<SWManagerMsg>,
/// Sender for communicating with resource thread.
pub resource_sender: IpcSender<CoreResourceMsg>,
/// Sender of messages to the manager.
pub own_sender: IpcSender<ServiceWorkerMsg>,
/// Receiver of messages from the constellation.
pub receiver: IpcReceiver<ServiceWorkerMsg>,
}
/// Messages sent to Service Worker Manager thread
#[derive(Debug, Deserialize, Serialize)]
pub enum ServiceWorkerMsg {
/// Timeout message sent by active service workers
Timeout(ServoUrl),
/// Message sent by constellation to forward to a running service worker
ForwardDOMMessage(DOMMessage, ServoUrl),
/// https://w3c.github.io/ServiceWorker/#schedule-job-algorithm
ScheduleJob(Job),
/// Exit the service worker manager
Exit,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
/// https://w3c.github.io/ServiceWorker/#dfn-job-type
pub enum JobType {
/// <https://w3c.github.io/ServiceWorker/#register>
Register,
/// <https://w3c.github.io/ServiceWorker/#unregister-algorithm>
Unregister,
/// <https://w3c.github.io/ServiceWorker/#update-algorithm
Update,
}
#[derive(Debug, Deserialize, Serialize)]
/// The kind of error the job promise should be rejected with.
pub enum JobError {
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
TypeError,
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
SecurityError,
}
#[derive(Debug, Deserialize, Serialize)]
/// Messages sent from Job algorithms steps running in the SW manager,
/// in order to resolve or reject the job promise.
pub enum JobResult {
/// https://w3c.github.io/ServiceWorker/#reject-job-promise
RejectPromise(JobError),
/// https://w3c.github.io/ServiceWorker/#resolve-job-promise
ResolvePromise(Job, JobResultValue),
}
#[derive(Debug, Deserialize, Serialize)]
/// Jobs are resolved with the help of various values.
pub enum JobResultValue {
/// Data representing a serviceworker registration.
Registration {
/// The Id of the registration.
id: ServiceWorkerRegistrationId,
/// The installing worker, if any.
installing_worker: Option<ServiceWorkerId>,
/// The waiting worker, if any.
waiting_worker: Option<ServiceWorkerId>,
/// The active worker, if any.
active_worker: Option<ServiceWorkerId>,
},
}
#[derive(Debug, Deserialize, Serialize)]
/// https://w3c.github.io/ServiceWorker/#dfn-job
pub struct Job {
/// <https://w3c.github.io/ServiceWorker/#dfn-job-type>
pub job_type: JobType,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-scope-url>
pub scope_url: ServoUrl,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-script-url>
pub script_url: ServoUrl,
/// <https://w3c.github.io/ServiceWorker/#dfn-job-client>
pub client: IpcSender<JobResult>,
/// <https://w3c.github.io/ServiceWorker/#job-referrer>
pub referrer: ServoUrl,
/// Various data needed to process job.
pub scope_things: Option<ScopeThings>,
}
impl Job {
/// https://w3c.github.io/ServiceWorker/#create-job-algorithm
pub fn create_job(
job_type: JobType,
scope_url: ServoUrl,
script_url: ServoUrl,
client: IpcSender<JobResult>,
referrer: ServoUrl,
scope_things: Option<ScopeThings>,
) -> Job {
Job {
job_type,
scope_url,
script_url,
client,
referrer,
scope_things,
}
}
}
impl PartialEq for Job {
/// Equality criteria as described in https://w3c.github.io/ServiceWorker/#dfn-job-equivalent
fn eq(&self, other: &Self) -> bool {
// TODO: match on job type, take worker type and `update_via_cache_mode` into account.
let same_job = self.job_type == other.job_type;
if same_job {
match self.job_type {
JobType::Register | JobType::Update => {
self.scope_url == other.scope_url && self.script_url == other.script_url
},
JobType::Unregister => self.scope_url == other.scope_url,
}
} else {
false
}
}
}
/// Messages outgoing from the Service Worker Manager thread to constellation
#[derive(Debug, Deserialize, Serialize)]
pub enum SWManagerMsg {
/// Placeholder to keep the enum,
/// as it will be needed when implementing
/// https://github.com/servo/servo/issues/24660
PostMessageToClient,
}
| ScriptMsg | identifier_name |
issue-64655-allow-unwind-when-calling-panic-directly.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// ignore-emscripten no threads support
// rust-lang/rust#64655: with panic=unwind, a panic from a subroutine
// should still run destructors as it unwinds the stack. However,
// bugs with how the nounwind LLVM attribute was applied led to this
// simple case being mishandled *if* you had fat LTO turned on.
// Unlike issue-64655-extern-rust-must-allow-unwind.rs, the issue
// embodied in this test cropped up regardless of optimization level.
// Therefore it seemed worthy of being enshrined as a dedicated unit
// test.
// LTO settings cannot be combined with -C prefer-dynamic
// no-prefer-dynamic
// The revisions just enumerate lto settings (the opt-level appeared irrelevant in practice)
// revisions: no thin fat
//[no]compile-flags: -C lto=no
//[thin]compile-flags: -C lto=thin
//[fat]compile-flags: -C lto=fat
#![feature(core_panic)]
// (For some reason, reproducing the LTO issue requires pulling in std
// explicitly this way.)
#![no_std]
extern crate std;
fn main() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::boxed::Box;
static SHARED: AtomicUsize = AtomicUsize::new(0);
assert_eq!(SHARED.fetch_add(0, Ordering::SeqCst), 0);
let old_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| { } )); // no-op on panic.
let handle = std::thread::spawn(|| {
struct | ;
impl Drop for Droppable {
fn drop(&mut self) {
SHARED.fetch_add(1, Ordering::SeqCst);
}
}
let _guard = Droppable;
core::panicking::panic("???");
});
let wait = handle.join();
// Reinstate handler to ease observation of assertion failures.
std::panic::set_hook(old_hook);
assert!(wait.is_err());
assert_eq!(SHARED.fetch_add(0, Ordering::SeqCst), 1);
}
| Droppable | identifier_name |
issue-64655-allow-unwind-when-calling-panic-directly.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// ignore-emscripten no threads support
// rust-lang/rust#64655: with panic=unwind, a panic from a subroutine
// should still run destructors as it unwinds the stack. However,
// bugs with how the nounwind LLVM attribute was applied led to this
// simple case being mishandled *if* you had fat LTO turned on.
// Unlike issue-64655-extern-rust-must-allow-unwind.rs, the issue
// embodied in this test cropped up regardless of optimization level.
// Therefore it seemed worthy of being enshrined as a dedicated unit
// test.
// LTO settings cannot be combined with -C prefer-dynamic
// no-prefer-dynamic
// The revisions just enumerate lto settings (the opt-level appeared irrelevant in practice)
// revisions: no thin fat
//[no]compile-flags: -C lto=no
//[thin]compile-flags: -C lto=thin
//[fat]compile-flags: -C lto=fat
#![feature(core_panic)]
// (For some reason, reproducing the LTO issue requires pulling in std
// explicitly this way.)
#![no_std]
extern crate std;
fn main() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::boxed::Box;
static SHARED: AtomicUsize = AtomicUsize::new(0);
assert_eq!(SHARED.fetch_add(0, Ordering::SeqCst), 0);
let old_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| { } )); // no-op on panic.
| SHARED.fetch_add(1, Ordering::SeqCst);
}
}
let _guard = Droppable;
core::panicking::panic("???");
});
let wait = handle.join();
// Reinstate handler to ease observation of assertion failures.
std::panic::set_hook(old_hook);
assert!(wait.is_err());
assert_eq!(SHARED.fetch_add(0, Ordering::SeqCst), 1);
} | let handle = std::thread::spawn(|| {
struct Droppable;
impl Drop for Droppable {
fn drop(&mut self) { | random_line_split |
login.rs | use std::io;
use cargo::ops;
use cargo::core::{MultiShell, SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const USAGE: &'static str = "
Save an api token from the registry locally
Usage:
cargo login [options] [<token>]
Options: | ";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
shell.set_verbose(options.flag_verbose);
let token = match options.arg_token.clone() {
Some(token) => token,
None => {
let err = (|:| {
let config = try!(Config::new(shell, None, None));
let src = try!(SourceId::for_central());
let mut src = RegistrySource::new(&src, &config);
try!(src.update());
let config = try!(src.config());
let host = options.flag_host.clone().unwrap_or(config.api);
println!("please visit {}me and paste the API Token below",
host);
let line = try!(io::stdin().read_line());
Ok(line)
})();
try!(err.map_err(|e| CliError::from_boxed(e, 101)))
}
};
let token = token.as_slice().trim().to_string();
try!(ops::registry_login(shell, token).map_err(|e| {
CliError::from_boxed(e, 101)
}));
Ok(None)
} | -h, --help Print this message
--host HOST Host to set the token for
-v, --verbose Use verbose output
| random_line_split |
login.rs | use std::io;
use cargo::ops;
use cargo::core::{MultiShell, SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct | {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const USAGE: &'static str = "
Save an api token from the registry locally
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token for
-v, --verbose Use verbose output
";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
shell.set_verbose(options.flag_verbose);
let token = match options.arg_token.clone() {
Some(token) => token,
None => {
let err = (|:| {
let config = try!(Config::new(shell, None, None));
let src = try!(SourceId::for_central());
let mut src = RegistrySource::new(&src, &config);
try!(src.update());
let config = try!(src.config());
let host = options.flag_host.clone().unwrap_or(config.api);
println!("please visit {}me and paste the API Token below",
host);
let line = try!(io::stdin().read_line());
Ok(line)
})();
try!(err.map_err(|e| CliError::from_boxed(e, 101)))
}
};
let token = token.as_slice().trim().to_string();
try!(ops::registry_login(shell, token).map_err(|e| {
CliError::from_boxed(e, 101)
}));
Ok(None)
}
| Options | identifier_name |
structured_errors.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc::session::Session;
use syntax_pos::Span;
use errors::{Applicability, DiagnosticId, DiagnosticBuilder};
use rustc::ty::{Ty, TypeFoldable};
pub trait StructuredDiagnostic<'tcx> {
fn session(&self) -> &Session;
fn code(&self) -> DiagnosticId;
fn common(&self) -> DiagnosticBuilder<'tcx>;
fn diagnostic(&self) -> DiagnosticBuilder<'tcx> {
let err = self.common();
if self.session().teach(&self.code()) {
self.extended(err)
} else {
self.regular(err)
}
}
fn regular(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
fn extended(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
}
pub struct VariadicError<'tcx> {
sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str,
}
impl<'tcx> VariadicError<'tcx> {
pub fn new(sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str) -> VariadicError<'tcx> {
VariadicError { sess, span, t, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for VariadicError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0617);
DiagnosticId::Error("E0617".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
let mut err = if self.t.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("can't pass `{}` to variadic function", self.t),
self.code(),
)
};
if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) {
err.span_suggestion_with_applicability(
self.span,
&format!("cast the value to `{}`", self.cast_ty),
format!("{} as {}", snippet, self.cast_ty),
Applicability::MachineApplicable,
);
} else {
err.help(&format!("cast the value to `{}`", self.cast_ty));
}
err
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.note(&format!("certain types, like `{}`, must be cast before passing them to a \
variadic function, because of arcane ABI rules dictated by the C \
standard",
self.t));
err
}
}
pub struct SizedUnsizedCastError<'tcx> {
sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String,
}
impl<'tcx> SizedUnsizedCastError<'tcx> {
pub fn new(sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String) -> SizedUnsizedCastError<'tcx> {
SizedUnsizedCastError { sess, span, expr_ty, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId |
fn common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty,
self.cast_ty),
self.code(),
)
}
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/book/first-edition/casting-between-types.html");
err
}
}
| {
__diagnostic_used!(E0607);
DiagnosticId::Error("E0607".to_owned())
} | identifier_body |
structured_errors.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc::session::Session;
use syntax_pos::Span;
use errors::{Applicability, DiagnosticId, DiagnosticBuilder};
use rustc::ty::{Ty, TypeFoldable};
pub trait StructuredDiagnostic<'tcx> {
fn session(&self) -> &Session;
fn code(&self) -> DiagnosticId;
fn common(&self) -> DiagnosticBuilder<'tcx>;
fn diagnostic(&self) -> DiagnosticBuilder<'tcx> {
let err = self.common();
if self.session().teach(&self.code()) {
self.extended(err)
} else {
self.regular(err)
}
}
fn regular(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
fn extended(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
}
pub struct VariadicError<'tcx> {
sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str,
}
impl<'tcx> VariadicError<'tcx> {
pub fn new(sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str) -> VariadicError<'tcx> {
VariadicError { sess, span, t, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for VariadicError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0617);
DiagnosticId::Error("E0617".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
let mut err = if self.t.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("can't pass `{}` to variadic function", self.t),
self.code(),
)
};
if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) {
err.span_suggestion_with_applicability(
self.span,
&format!("cast the value to `{}`", self.cast_ty),
format!("{} as {}", snippet, self.cast_ty),
Applicability::MachineApplicable,
);
} else {
err.help(&format!("cast the value to `{}`", self.cast_ty));
}
err
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.note(&format!("certain types, like `{}`, must be cast before passing them to a \
variadic function, because of arcane ABI rules dictated by the C \
standard",
self.t));
err
}
}
pub struct SizedUnsizedCastError<'tcx> {
sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String,
}
impl<'tcx> SizedUnsizedCastError<'tcx> {
pub fn | (sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String) -> SizedUnsizedCastError<'tcx> {
SizedUnsizedCastError { sess, span, expr_ty, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0607);
DiagnosticId::Error("E0607".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty,
self.cast_ty),
self.code(),
)
}
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/book/first-edition/casting-between-types.html");
err
}
}
| new | identifier_name |
structured_errors.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc::session::Session;
use syntax_pos::Span;
use errors::{Applicability, DiagnosticId, DiagnosticBuilder};
use rustc::ty::{Ty, TypeFoldable};
pub trait StructuredDiagnostic<'tcx> {
fn session(&self) -> &Session;
fn code(&self) -> DiagnosticId;
fn common(&self) -> DiagnosticBuilder<'tcx>;
fn diagnostic(&self) -> DiagnosticBuilder<'tcx> {
let err = self.common();
if self.session().teach(&self.code()) {
self.extended(err)
} else {
self.regular(err)
}
}
fn regular(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
fn extended(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
}
pub struct VariadicError<'tcx> {
sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str,
}
impl<'tcx> VariadicError<'tcx> {
pub fn new(sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str) -> VariadicError<'tcx> {
VariadicError { sess, span, t, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for VariadicError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0617);
DiagnosticId::Error("E0617".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
let mut err = if self.t.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("can't pass `{}` to variadic function", self.t),
self.code(),
)
};
if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) {
err.span_suggestion_with_applicability(
self.span,
&format!("cast the value to `{}`", self.cast_ty),
format!("{} as {}", snippet, self.cast_ty),
Applicability::MachineApplicable,
);
} else |
err
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.note(&format!("certain types, like `{}`, must be cast before passing them to a \
variadic function, because of arcane ABI rules dictated by the C \
standard",
self.t));
err
}
}
pub struct SizedUnsizedCastError<'tcx> {
sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String,
}
impl<'tcx> SizedUnsizedCastError<'tcx> {
pub fn new(sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String) -> SizedUnsizedCastError<'tcx> {
SizedUnsizedCastError { sess, span, expr_ty, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0607);
DiagnosticId::Error("E0607".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty,
self.cast_ty),
self.code(),
)
}
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/book/first-edition/casting-between-types.html");
err
}
}
| {
err.help(&format!("cast the value to `{}`", self.cast_ty));
} | conditional_block |
structured_errors.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc::session::Session;
use syntax_pos::Span;
use errors::{Applicability, DiagnosticId, DiagnosticBuilder};
use rustc::ty::{Ty, TypeFoldable};
pub trait StructuredDiagnostic<'tcx> {
fn session(&self) -> &Session;
fn code(&self) -> DiagnosticId;
fn common(&self) -> DiagnosticBuilder<'tcx>;
fn diagnostic(&self) -> DiagnosticBuilder<'tcx> {
let err = self.common();
if self.session().teach(&self.code()) {
self.extended(err)
} else {
self.regular(err)
}
}
fn regular(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
fn extended(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err
}
}
pub struct VariadicError<'tcx> {
sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str,
}
impl<'tcx> VariadicError<'tcx> {
pub fn new(sess: &'tcx Session,
span: Span,
t: Ty<'tcx>,
cast_ty: &'tcx str) -> VariadicError<'tcx> {
VariadicError { sess, span, t, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for VariadicError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0617);
DiagnosticId::Error("E0617".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
let mut err = if self.t.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("can't pass `{}` to variadic function", self.t),
self.code(),
)
};
if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) {
err.span_suggestion_with_applicability(
self.span,
&format!("cast the value to `{}`", self.cast_ty),
format!("{} as {}", snippet, self.cast_ty),
Applicability::MachineApplicable,
);
} else {
err.help(&format!("cast the value to `{}`", self.cast_ty));
}
err
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.note(&format!("certain types, like `{}`, must be cast before passing them to a \
variadic function, because of arcane ABI rules dictated by the C \
standard",
self.t));
err
}
}
pub struct SizedUnsizedCastError<'tcx> {
sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String,
}
impl<'tcx> SizedUnsizedCastError<'tcx> {
pub fn new(sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String) -> SizedUnsizedCastError<'tcx> {
SizedUnsizedCastError { sess, span, expr_ty, cast_ty } | }
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0607);
DiagnosticId::Error("E0607".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty,
self.cast_ty),
self.code(),
)
}
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/book/first-edition/casting-between-types.html");
err
}
} | random_line_split |
|
epoll.rs | use nix::fcntl::Fd;
use nix::sys::epoll::*;
use nix::unistd::close;
use io;
use os::event::{IoEvent, Interest, PollOpt};
pub struct Selector {
epfd: Fd
}
impl Selector {
pub fn new() -> io::Result<Selector> {
let epfd = try!(epoll_create().map_err(io::from_nix_error));
Ok(Selector { epfd: epfd })
}
/// Wait for events from the OS
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
use std::slice;
let dst = unsafe {
slice::from_raw_parts_mut(
evts.events.as_mut_slice().as_mut_ptr(),
evts.events.capacity())
};
// Wait for epoll events for at most timeout_ms milliseconds | Ok(())
}
/// Register event interests for the given IO handle with the OS
pub fn register(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> {
let info = EpollEvent {
events: ioevent_to_epoll(interests, opts),
data: token as u64
};
epoll_ctl(self.epfd, EpollOp::EpollCtlAdd, fd, &info)
.map_err(io::from_nix_error)
}
/// Register event interests for the given IO handle with the OS
pub fn reregister(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> {
let info = EpollEvent {
events: ioevent_to_epoll(interests, opts),
data: token as u64
};
epoll_ctl(self.epfd, EpollOp::EpollCtlMod, fd, &info)
.map_err(io::from_nix_error)
}
/// Deregister event interests for the given IO handle with the OS
pub fn deregister(&mut self, fd: Fd) -> io::Result<()> {
// The &info argument should be ignored by the system,
// but linux < 2.6.9 required it to be not null.
// For compatibility, we provide a dummy EpollEvent.
let info = EpollEvent {
events: EpollEventKind::empty(),
data: 0
};
epoll_ctl(self.epfd, EpollOp::EpollCtlDel, fd, &info)
.map_err(io::from_nix_error)
}
}
fn ioevent_to_epoll(interest: Interest, opts: PollOpt) -> EpollEventKind {
let mut kind = EpollEventKind::empty();
if interest.is_readable() {
kind.insert(EPOLLIN);
}
if interest.is_writable() {
kind.insert(EPOLLOUT);
}
if interest.is_hup() {
kind.insert(EPOLLRDHUP);
}
if opts.is_edge() {
kind.insert(EPOLLET);
}
if opts.is_oneshot() {
kind.insert(EPOLLONESHOT);
}
if opts.is_level() {
kind.remove(EPOLLET);
}
kind
}
impl Drop for Selector {
fn drop(&mut self) {
let _ = close(self.epfd);
}
}
pub struct Events {
events: Vec<EpollEvent>,
}
impl Events {
pub fn new() -> Events {
Events { events: Vec::with_capacity(1024) }
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn get(&self, idx: usize) -> IoEvent {
if idx >= self.len() {
panic!("invalid index");
}
let epoll = self.events[idx].events;
let mut kind = Interest::hinted();
if epoll.contains(EPOLLIN) {
kind = kind | Interest::readable();
}
if epoll.contains(EPOLLOUT) {
kind = kind | Interest::writable();
}
// EPOLLHUP - Usually means a socket error happened
if epoll.contains(EPOLLERR) {
kind = kind | Interest::error();
}
if epoll.contains(EPOLLRDHUP) | epoll.contains(EPOLLHUP) {
kind = kind | Interest::hup();
}
let token = self.events[idx].data;
IoEvent::new(kind, token as usize)
}
} | let cnt = try!(epoll_wait(self.epfd, dst, timeout_ms)
.map_err(io::from_nix_error));
unsafe { evts.events.set_len(cnt); }
| random_line_split |
epoll.rs | use nix::fcntl::Fd;
use nix::sys::epoll::*;
use nix::unistd::close;
use io;
use os::event::{IoEvent, Interest, PollOpt};
pub struct | {
epfd: Fd
}
impl Selector {
pub fn new() -> io::Result<Selector> {
let epfd = try!(epoll_create().map_err(io::from_nix_error));
Ok(Selector { epfd: epfd })
}
/// Wait for events from the OS
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
use std::slice;
let dst = unsafe {
slice::from_raw_parts_mut(
evts.events.as_mut_slice().as_mut_ptr(),
evts.events.capacity())
};
// Wait for epoll events for at most timeout_ms milliseconds
let cnt = try!(epoll_wait(self.epfd, dst, timeout_ms)
.map_err(io::from_nix_error));
unsafe { evts.events.set_len(cnt); }
Ok(())
}
/// Register event interests for the given IO handle with the OS
pub fn register(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> {
let info = EpollEvent {
events: ioevent_to_epoll(interests, opts),
data: token as u64
};
epoll_ctl(self.epfd, EpollOp::EpollCtlAdd, fd, &info)
.map_err(io::from_nix_error)
}
/// Register event interests for the given IO handle with the OS
pub fn reregister(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> {
let info = EpollEvent {
events: ioevent_to_epoll(interests, opts),
data: token as u64
};
epoll_ctl(self.epfd, EpollOp::EpollCtlMod, fd, &info)
.map_err(io::from_nix_error)
}
/// Deregister event interests for the given IO handle with the OS
pub fn deregister(&mut self, fd: Fd) -> io::Result<()> {
// The &info argument should be ignored by the system,
// but linux < 2.6.9 required it to be not null.
// For compatibility, we provide a dummy EpollEvent.
let info = EpollEvent {
events: EpollEventKind::empty(),
data: 0
};
epoll_ctl(self.epfd, EpollOp::EpollCtlDel, fd, &info)
.map_err(io::from_nix_error)
}
}
fn ioevent_to_epoll(interest: Interest, opts: PollOpt) -> EpollEventKind {
let mut kind = EpollEventKind::empty();
if interest.is_readable() {
kind.insert(EPOLLIN);
}
if interest.is_writable() {
kind.insert(EPOLLOUT);
}
if interest.is_hup() {
kind.insert(EPOLLRDHUP);
}
if opts.is_edge() {
kind.insert(EPOLLET);
}
if opts.is_oneshot() {
kind.insert(EPOLLONESHOT);
}
if opts.is_level() {
kind.remove(EPOLLET);
}
kind
}
impl Drop for Selector {
fn drop(&mut self) {
let _ = close(self.epfd);
}
}
pub struct Events {
events: Vec<EpollEvent>,
}
impl Events {
pub fn new() -> Events {
Events { events: Vec::with_capacity(1024) }
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn get(&self, idx: usize) -> IoEvent {
if idx >= self.len() {
panic!("invalid index");
}
let epoll = self.events[idx].events;
let mut kind = Interest::hinted();
if epoll.contains(EPOLLIN) {
kind = kind | Interest::readable();
}
if epoll.contains(EPOLLOUT) {
kind = kind | Interest::writable();
}
// EPOLLHUP - Usually means a socket error happened
if epoll.contains(EPOLLERR) {
kind = kind | Interest::error();
}
if epoll.contains(EPOLLRDHUP) | epoll.contains(EPOLLHUP) {
kind = kind | Interest::hup();
}
let token = self.events[idx].data;
IoEvent::new(kind, token as usize)
}
}
| Selector | identifier_name |
epoll.rs | use nix::fcntl::Fd;
use nix::sys::epoll::*;
use nix::unistd::close;
use io;
use os::event::{IoEvent, Interest, PollOpt};
pub struct Selector {
epfd: Fd
}
impl Selector {
pub fn new() -> io::Result<Selector> {
let epfd = try!(epoll_create().map_err(io::from_nix_error));
Ok(Selector { epfd: epfd })
}
/// Wait for events from the OS
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
use std::slice;
let dst = unsafe {
slice::from_raw_parts_mut(
evts.events.as_mut_slice().as_mut_ptr(),
evts.events.capacity())
};
// Wait for epoll events for at most timeout_ms milliseconds
let cnt = try!(epoll_wait(self.epfd, dst, timeout_ms)
.map_err(io::from_nix_error));
unsafe { evts.events.set_len(cnt); }
Ok(())
}
/// Register event interests for the given IO handle with the OS
pub fn register(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> {
let info = EpollEvent {
events: ioevent_to_epoll(interests, opts),
data: token as u64
};
epoll_ctl(self.epfd, EpollOp::EpollCtlAdd, fd, &info)
.map_err(io::from_nix_error)
}
/// Register event interests for the given IO handle with the OS
pub fn reregister(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> {
let info = EpollEvent {
events: ioevent_to_epoll(interests, opts),
data: token as u64
};
epoll_ctl(self.epfd, EpollOp::EpollCtlMod, fd, &info)
.map_err(io::from_nix_error)
}
/// Deregister event interests for the given IO handle with the OS
pub fn deregister(&mut self, fd: Fd) -> io::Result<()> {
// The &info argument should be ignored by the system,
// but linux < 2.6.9 required it to be not null.
// For compatibility, we provide a dummy EpollEvent.
let info = EpollEvent {
events: EpollEventKind::empty(),
data: 0
};
epoll_ctl(self.epfd, EpollOp::EpollCtlDel, fd, &info)
.map_err(io::from_nix_error)
}
}
fn ioevent_to_epoll(interest: Interest, opts: PollOpt) -> EpollEventKind {
let mut kind = EpollEventKind::empty();
if interest.is_readable() {
kind.insert(EPOLLIN);
}
if interest.is_writable() |
if interest.is_hup() {
kind.insert(EPOLLRDHUP);
}
if opts.is_edge() {
kind.insert(EPOLLET);
}
if opts.is_oneshot() {
kind.insert(EPOLLONESHOT);
}
if opts.is_level() {
kind.remove(EPOLLET);
}
kind
}
impl Drop for Selector {
fn drop(&mut self) {
let _ = close(self.epfd);
}
}
pub struct Events {
events: Vec<EpollEvent>,
}
impl Events {
pub fn new() -> Events {
Events { events: Vec::with_capacity(1024) }
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn get(&self, idx: usize) -> IoEvent {
if idx >= self.len() {
panic!("invalid index");
}
let epoll = self.events[idx].events;
let mut kind = Interest::hinted();
if epoll.contains(EPOLLIN) {
kind = kind | Interest::readable();
}
if epoll.contains(EPOLLOUT) {
kind = kind | Interest::writable();
}
// EPOLLHUP - Usually means a socket error happened
if epoll.contains(EPOLLERR) {
kind = kind | Interest::error();
}
if epoll.contains(EPOLLRDHUP) | epoll.contains(EPOLLHUP) {
kind = kind | Interest::hup();
}
let token = self.events[idx].data;
IoEvent::new(kind, token as usize)
}
}
| {
kind.insert(EPOLLOUT);
} | conditional_block |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion_conj;
pub use quaternion::{self, Quaternion};
pub use dual_quaternion::{self, DualQuaternion};
pub fn lerp_quaternion(q1: &Quaternion<f32>, q2: &Quaternion<f32>, blend_factor: &f32) -> Quaternion<f32> {
let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2];
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor };
let w = s * q1.0 + t * q2.0;
let x = s * q1.1[0] + t * q2.1[0];
let y = s * q1.1[1] + t * q2.1[1];
let z = s * q1.1[2] + t * q2.1[2];
let inv_sqrt_len = inv_sqrt(w * w + x * x + y * y + z * z);
(w * inv_sqrt_len, [x * inv_sqrt_len, y * inv_sqrt_len, z * inv_sqrt_len])
}
/// Dual-quaternion linear blending. See http://dcgi.felk.cvut.cz/home/zara/papers/TCD-CS-2006-46.pdf
pub fn lerp_dual_quaternion(q1: DualQuaternion<f32>, q2: DualQuaternion<f32>, blend_factor: f32) -> DualQuaternion<f32> {
let dot = dual_quaternion::dot(q1, q2);
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { blend_factor } else { -blend_factor };
let blended_sum = dual_quaternion::add(dual_quaternion::scale(q1, s), dual_quaternion::scale(q2, t));
dual_quaternion::normalize(blended_sum)
}
/// rotation matrix for `a` radians about z
pub fn mat4_rotate_z(a: f32) -> Matrix4<f32> {
[
[a.cos(), -a.sin(), 0.0, 0.0],
[a.sin(), a.cos(), 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
}
pub fn matrix_to_quaternion(m: &Matrix4<f32>) -> Quaternion<f32> {
let mut q = [0.0, 0.0, 0.0, 0.0];
let next = [1, 2, 0];
let trace = m[0][0] + m[1][1] + m[2][2];
if trace > 0.0 {
let t = trace + 1.0;
let s = inv_sqrt(t) * 0.5;
q[3] = s * t;
q[0] = (m[1][2] - m[2][1]) * s;
q[1] = (m[2][0] - m[0][2]) * s;
q[2] = (m[0][1] - m[1][0]) * s;
} else {
let mut i = 0;
if m[1][1] > m[0][0] |
if m[2][2] > m[i][i] {
i = 2;
}
let j = next[i];
let k = next[j];
let t = (m[i][i] - (m[j][j] + m[k][k])) + 1.0;
let s = inv_sqrt(t) * 0.5;
q[i] = s * t;
q[3] = (m[j][k] - m[k][j]) * s;
q[j] = (m[i][j] + m[j][i]) * s;
q[k] = (m[i][k] + m[k][i]) * s;
}
(q[3], [q[0], q[1], q[2]])
}
///
/// See http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
///
pub fn quaternion_to_matrix(q: Quaternion<f32>) -> Matrix4<f32> {
let w = q.0;
let x = q.1[0];
let y = q.1[1];
let z = q.1[2];
let x2 = x + x;
let y2 = y + y;
let z2 = z + z;
let xx2 = x2 * x;
let xy2 = x2 * y;
let xz2 = x2 * z;
let yy2 = y2 * y;
let yz2 = y2 * z;
let zz2 = z2 * z;
let wy2 = y2 * w;
let wz2 = z2 * w;
let wx2 = x2 * w;
[
[1.0 - yy2 - zz2, xy2 + wz2, xz2 - wy2, 0.0],
[xy2 - wz2, 1.0 - xx2 - zz2, yz2 + wx2, 0.0],
[xz2 + wy2, yz2 - wx2, 1.0 - xx2 - yy2, 0.0],
[0.0, 0.0, 0.0, 1.0]
]
}
pub fn inv_sqrt(x: f32) -> f32 {
let x2: f32 = x * 0.5;
let mut y: f32 = x;
let mut i: i32 = unsafe { mem::transmute(y) };
i = 0x5f3759df - (i >> 1);
y = unsafe { mem::transmute(i) };
y = y * (1.5 - (x2 * y * y));
y
}
| {
i = 1;
} | conditional_block |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion_conj;
pub use quaternion::{self, Quaternion};
pub use dual_quaternion::{self, DualQuaternion};
pub fn lerp_quaternion(q1: &Quaternion<f32>, q2: &Quaternion<f32>, blend_factor: &f32) -> Quaternion<f32> |
/// Dual-quaternion linear blending. See http://dcgi.felk.cvut.cz/home/zara/papers/TCD-CS-2006-46.pdf
pub fn lerp_dual_quaternion(q1: DualQuaternion<f32>, q2: DualQuaternion<f32>, blend_factor: f32) -> DualQuaternion<f32> {
let dot = dual_quaternion::dot(q1, q2);
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { blend_factor } else { -blend_factor };
let blended_sum = dual_quaternion::add(dual_quaternion::scale(q1, s), dual_quaternion::scale(q2, t));
dual_quaternion::normalize(blended_sum)
}
/// rotation matrix for `a` radians about z
pub fn mat4_rotate_z(a: f32) -> Matrix4<f32> {
[
[a.cos(), -a.sin(), 0.0, 0.0],
[a.sin(), a.cos(), 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
}
pub fn matrix_to_quaternion(m: &Matrix4<f32>) -> Quaternion<f32> {
let mut q = [0.0, 0.0, 0.0, 0.0];
let next = [1, 2, 0];
let trace = m[0][0] + m[1][1] + m[2][2];
if trace > 0.0 {
let t = trace + 1.0;
let s = inv_sqrt(t) * 0.5;
q[3] = s * t;
q[0] = (m[1][2] - m[2][1]) * s;
q[1] = (m[2][0] - m[0][2]) * s;
q[2] = (m[0][1] - m[1][0]) * s;
} else {
let mut i = 0;
if m[1][1] > m[0][0] {
i = 1;
}
if m[2][2] > m[i][i] {
i = 2;
}
let j = next[i];
let k = next[j];
let t = (m[i][i] - (m[j][j] + m[k][k])) + 1.0;
let s = inv_sqrt(t) * 0.5;
q[i] = s * t;
q[3] = (m[j][k] - m[k][j]) * s;
q[j] = (m[i][j] + m[j][i]) * s;
q[k] = (m[i][k] + m[k][i]) * s;
}
(q[3], [q[0], q[1], q[2]])
}
///
/// See http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
///
pub fn quaternion_to_matrix(q: Quaternion<f32>) -> Matrix4<f32> {
let w = q.0;
let x = q.1[0];
let y = q.1[1];
let z = q.1[2];
let x2 = x + x;
let y2 = y + y;
let z2 = z + z;
let xx2 = x2 * x;
let xy2 = x2 * y;
let xz2 = x2 * z;
let yy2 = y2 * y;
let yz2 = y2 * z;
let zz2 = z2 * z;
let wy2 = y2 * w;
let wz2 = z2 * w;
let wx2 = x2 * w;
[
[1.0 - yy2 - zz2, xy2 + wz2, xz2 - wy2, 0.0],
[xy2 - wz2, 1.0 - xx2 - zz2, yz2 + wx2, 0.0],
[xz2 + wy2, yz2 - wx2, 1.0 - xx2 - yy2, 0.0],
[0.0, 0.0, 0.0, 1.0]
]
}
pub fn inv_sqrt(x: f32) -> f32 {
let x2: f32 = x * 0.5;
let mut y: f32 = x;
let mut i: i32 = unsafe { mem::transmute(y) };
i = 0x5f3759df - (i >> 1);
y = unsafe { mem::transmute(i) };
y = y * (1.5 - (x2 * y * y));
y
}
| {
let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2];
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor };
let w = s * q1.0 + t * q2.0;
let x = s * q1.1[0] + t * q2.1[0];
let y = s * q1.1[1] + t * q2.1[1];
let z = s * q1.1[2] + t * q2.1[2];
let inv_sqrt_len = inv_sqrt(w * w + x * x + y * y + z * z);
(w * inv_sqrt_len, [x * inv_sqrt_len, y * inv_sqrt_len, z * inv_sqrt_len])
} | identifier_body |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion_conj;
pub use quaternion::{self, Quaternion};
pub use dual_quaternion::{self, DualQuaternion};
pub fn lerp_quaternion(q1: &Quaternion<f32>, q2: &Quaternion<f32>, blend_factor: &f32) -> Quaternion<f32> {
let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2];
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor };
let w = s * q1.0 + t * q2.0;
let x = s * q1.1[0] + t * q2.1[0];
let y = s * q1.1[1] + t * q2.1[1];
let z = s * q1.1[2] + t * q2.1[2];
let inv_sqrt_len = inv_sqrt(w * w + x * x + y * y + z * z);
(w * inv_sqrt_len, [x * inv_sqrt_len, y * inv_sqrt_len, z * inv_sqrt_len])
}
/// Dual-quaternion linear blending. See http://dcgi.felk.cvut.cz/home/zara/papers/TCD-CS-2006-46.pdf
pub fn lerp_dual_quaternion(q1: DualQuaternion<f32>, q2: DualQuaternion<f32>, blend_factor: f32) -> DualQuaternion<f32> {
let dot = dual_quaternion::dot(q1, q2);
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { blend_factor } else { -blend_factor };
let blended_sum = dual_quaternion::add(dual_quaternion::scale(q1, s), dual_quaternion::scale(q2, t));
dual_quaternion::normalize(blended_sum)
}
/// rotation matrix for `a` radians about z
pub fn mat4_rotate_z(a: f32) -> Matrix4<f32> {
[
[a.cos(), -a.sin(), 0.0, 0.0],
[a.sin(), a.cos(), 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
}
pub fn matrix_to_quaternion(m: &Matrix4<f32>) -> Quaternion<f32> {
let mut q = [0.0, 0.0, 0.0, 0.0];
let next = [1, 2, 0];
let trace = m[0][0] + m[1][1] + m[2][2];
if trace > 0.0 {
let t = trace + 1.0;
let s = inv_sqrt(t) * 0.5;
q[3] = s * t;
q[0] = (m[1][2] - m[2][1]) * s;
q[1] = (m[2][0] - m[0][2]) * s;
q[2] = (m[0][1] - m[1][0]) * s;
} else {
let mut i = 0;
if m[1][1] > m[0][0] {
i = 1;
}
if m[2][2] > m[i][i] {
i = 2;
}
let j = next[i];
let k = next[j];
let t = (m[i][i] - (m[j][j] + m[k][k])) + 1.0;
let s = inv_sqrt(t) * 0.5;
q[i] = s * t;
q[3] = (m[j][k] - m[k][j]) * s;
q[j] = (m[i][j] + m[j][i]) * s;
q[k] = (m[i][k] + m[k][i]) * s;
}
(q[3], [q[0], q[1], q[2]])
}
///
/// See http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
///
pub fn quaternion_to_matrix(q: Quaternion<f32>) -> Matrix4<f32> {
let w = q.0;
let x = q.1[0];
let y = q.1[1];
let z = q.1[2];
let x2 = x + x;
let y2 = y + y;
let z2 = z + z;
let xx2 = x2 * x;
let xy2 = x2 * y;
let xz2 = x2 * z;
let yy2 = y2 * y;
let yz2 = y2 * z;
let zz2 = z2 * z;
let wy2 = y2 * w;
let wz2 = z2 * w;
let wx2 = x2 * w;
[
[1.0 - yy2 - zz2, xy2 + wz2, xz2 - wy2, 0.0],
[xy2 - wz2, 1.0 - xx2 - zz2, yz2 + wx2, 0.0],
[xz2 + wy2, yz2 - wx2, 1.0 - xx2 - yy2, 0.0],
[0.0, 0.0, 0.0, 1.0]
]
}
| let mut i: i32 = unsafe { mem::transmute(y) };
i = 0x5f3759df - (i >> 1);
y = unsafe { mem::transmute(i) };
y = y * (1.5 - (x2 * y * y));
y
} | pub fn inv_sqrt(x: f32) -> f32 {
let x2: f32 = x * 0.5;
let mut y: f32 = x;
| random_line_split |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion_conj;
pub use quaternion::{self, Quaternion};
pub use dual_quaternion::{self, DualQuaternion};
pub fn | (q1: &Quaternion<f32>, q2: &Quaternion<f32>, blend_factor: &f32) -> Quaternion<f32> {
let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2];
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor };
let w = s * q1.0 + t * q2.0;
let x = s * q1.1[0] + t * q2.1[0];
let y = s * q1.1[1] + t * q2.1[1];
let z = s * q1.1[2] + t * q2.1[2];
let inv_sqrt_len = inv_sqrt(w * w + x * x + y * y + z * z);
(w * inv_sqrt_len, [x * inv_sqrt_len, y * inv_sqrt_len, z * inv_sqrt_len])
}
/// Dual-quaternion linear blending. See http://dcgi.felk.cvut.cz/home/zara/papers/TCD-CS-2006-46.pdf
pub fn lerp_dual_quaternion(q1: DualQuaternion<f32>, q2: DualQuaternion<f32>, blend_factor: f32) -> DualQuaternion<f32> {
let dot = dual_quaternion::dot(q1, q2);
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { blend_factor } else { -blend_factor };
let blended_sum = dual_quaternion::add(dual_quaternion::scale(q1, s), dual_quaternion::scale(q2, t));
dual_quaternion::normalize(blended_sum)
}
/// rotation matrix for `a` radians about z
pub fn mat4_rotate_z(a: f32) -> Matrix4<f32> {
[
[a.cos(), -a.sin(), 0.0, 0.0],
[a.sin(), a.cos(), 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
}
pub fn matrix_to_quaternion(m: &Matrix4<f32>) -> Quaternion<f32> {
let mut q = [0.0, 0.0, 0.0, 0.0];
let next = [1, 2, 0];
let trace = m[0][0] + m[1][1] + m[2][2];
if trace > 0.0 {
let t = trace + 1.0;
let s = inv_sqrt(t) * 0.5;
q[3] = s * t;
q[0] = (m[1][2] - m[2][1]) * s;
q[1] = (m[2][0] - m[0][2]) * s;
q[2] = (m[0][1] - m[1][0]) * s;
} else {
let mut i = 0;
if m[1][1] > m[0][0] {
i = 1;
}
if m[2][2] > m[i][i] {
i = 2;
}
let j = next[i];
let k = next[j];
let t = (m[i][i] - (m[j][j] + m[k][k])) + 1.0;
let s = inv_sqrt(t) * 0.5;
q[i] = s * t;
q[3] = (m[j][k] - m[k][j]) * s;
q[j] = (m[i][j] + m[j][i]) * s;
q[k] = (m[i][k] + m[k][i]) * s;
}
(q[3], [q[0], q[1], q[2]])
}
///
/// See http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
///
pub fn quaternion_to_matrix(q: Quaternion<f32>) -> Matrix4<f32> {
let w = q.0;
let x = q.1[0];
let y = q.1[1];
let z = q.1[2];
let x2 = x + x;
let y2 = y + y;
let z2 = z + z;
let xx2 = x2 * x;
let xy2 = x2 * y;
let xz2 = x2 * z;
let yy2 = y2 * y;
let yz2 = y2 * z;
let zz2 = z2 * z;
let wy2 = y2 * w;
let wz2 = z2 * w;
let wx2 = x2 * w;
[
[1.0 - yy2 - zz2, xy2 + wz2, xz2 - wy2, 0.0],
[xy2 - wz2, 1.0 - xx2 - zz2, yz2 + wx2, 0.0],
[xz2 + wy2, yz2 - wx2, 1.0 - xx2 - yy2, 0.0],
[0.0, 0.0, 0.0, 1.0]
]
}
pub fn inv_sqrt(x: f32) -> f32 {
let x2: f32 = x * 0.5;
let mut y: f32 = x;
let mut i: i32 = unsafe { mem::transmute(y) };
i = 0x5f3759df - (i >> 1);
y = unsafe { mem::transmute(i) };
y = y * (1.5 - (x2 * y * y));
y
}
| lerp_quaternion | identifier_name |
msg_filterload.rs | use std;
use ::serialize::{self, Serializable};
#[derive(Debug,Default,Clone)]
pub struct FilterLoadMessage {
pub data: Vec<u8>,
pub hash_funcs: u32,
pub tweak: u32,
pub flags: u8,
}
impl super::Message for FilterLoadMessage {
fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] {
super::message_header::COMMAND_FILTERLOAD
}
}
impl std::fmt::Display for FilterLoadMessage {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "FilterLoad(data={:?},funcs={},tweak={},flags={})", self.data, self.hash_funcs, self.tweak, self.flags)
}
}
impl Serializable for FilterLoadMessage {
fn get_serialize_size(&self, ser:&serialize::SerializeParam) -> usize {
self.data.get_serialize_size(ser) +
self.hash_funcs.get_serialize_size(ser) +
self.tweak.get_serialize_size(ser) +
self.flags.get_serialize_size(ser)
}
fn serialize(&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result {
let mut r:usize = 0;
r += try!(self.data.serialize(io,ser));
r += try!(self.hash_funcs.serialize(io,ser));
r += try!(self.tweak.serialize(io,ser));
r += try!(self.flags.serialize(io,ser));
Ok(r)
}
fn | (&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result {
let mut r:usize = 0;
r += try!(self.data.deserialize(io,ser));
r += try!(self.hash_funcs.deserialize(io,ser));
r += try!(self.tweak.deserialize(io,ser));
r += try!(self.flags.deserialize(io,ser));
Ok(r)
}
}
| deserialize | identifier_name |
msg_filterload.rs | use std;
use ::serialize::{self, Serializable};
#[derive(Debug,Default,Clone)]
pub struct FilterLoadMessage {
pub data: Vec<u8>,
pub hash_funcs: u32,
pub tweak: u32,
pub flags: u8,
}
impl super::Message for FilterLoadMessage {
fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] {
super::message_header::COMMAND_FILTERLOAD
}
}
impl std::fmt::Display for FilterLoadMessage {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "FilterLoad(data={:?},funcs={},tweak={},flags={})", self.data, self.hash_funcs, self.tweak, self.flags)
}
}
impl Serializable for FilterLoadMessage {
fn get_serialize_size(&self, ser:&serialize::SerializeParam) -> usize {
self.data.get_serialize_size(ser) +
self.hash_funcs.get_serialize_size(ser) +
self.tweak.get_serialize_size(ser) +
self.flags.get_serialize_size(ser)
}
fn serialize(&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result { | let mut r:usize = 0;
r += try!(self.data.serialize(io,ser));
r += try!(self.hash_funcs.serialize(io,ser));
r += try!(self.tweak.serialize(io,ser));
r += try!(self.flags.serialize(io,ser));
Ok(r)
}
fn deserialize(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result {
let mut r:usize = 0;
r += try!(self.data.deserialize(io,ser));
r += try!(self.hash_funcs.deserialize(io,ser));
r += try!(self.tweak.deserialize(io,ser));
r += try!(self.flags.deserialize(io,ser));
Ok(r)
}
} | random_line_split |
|
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
errors::invalid_url_err();
process::exit(0);
}
};
let result = http.request(&request.method)
.body_as_str(&request.body)
.header(request.headers)
.send();
match result {
Ok(response) => {
if path.is_empty() {
print_response(&response);
} else {
save_to_file(&response, path);
}
}
Err(_) => {
errors::invalid_response();
process::exit(0);
}
}
}
fn print_response(response: &Response) |
fn save_to_file(response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
Ok(_) => println!("Response was saved to file: {}", path),
Err(_) => {
errors::cant_save_response();
process::exit(0);
}
}
}
| {
println!("Status: {}\r\n", response.status);
for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
} | identifier_body |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
errors::invalid_url_err();
process::exit(0);
}
};
let result = http.request(&request.method)
.body_as_str(&request.body)
.header(request.headers)
.send();
match result {
Ok(response) => {
if path.is_empty() {
print_response(&response);
} else {
save_to_file(&response, path);
}
}
Err(_) => {
errors::invalid_response();
process::exit(0);
}
}
} | for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
}
fn save_to_file(response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
Ok(_) => println!("Response was saved to file: {}", path),
Err(_) => {
errors::cant_save_response();
process::exit(0);
}
}
} |
fn print_response(response: &Response) {
println!("Status: {}\r\n", response.status);
| random_line_split |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
errors::invalid_url_err();
process::exit(0);
}
};
let result = http.request(&request.method)
.body_as_str(&request.body)
.header(request.headers)
.send();
match result {
Ok(response) => {
if path.is_empty() {
print_response(&response);
} else {
save_to_file(&response, path);
}
}
Err(_) => {
errors::invalid_response();
process::exit(0);
}
}
}
fn print_response(response: &Response) {
println!("Status: {}\r\n", response.status);
for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
}
fn | (response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
Ok(_) => println!("Response was saved to file: {}", path),
Err(_) => {
errors::cant_save_response();
process::exit(0);
}
}
}
| save_to_file | identifier_name |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
errors::invalid_url_err();
process::exit(0);
}
};
let result = http.request(&request.method)
.body_as_str(&request.body)
.header(request.headers)
.send();
match result {
Ok(response) => {
if path.is_empty() {
print_response(&response);
} else |
}
Err(_) => {
errors::invalid_response();
process::exit(0);
}
}
}
fn print_response(response: &Response) {
println!("Status: {}\r\n", response.status);
for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
}
fn save_to_file(response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
Ok(_) => println!("Response was saved to file: {}", path),
Err(_) => {
errors::cant_save_response();
process::exit(0);
}
}
}
| {
save_to_file(&response, path);
} | conditional_block |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y |
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable borrowed content `*z` as mutable
println!("{} {}",*z,z);
//reference:
let x = 5;
let y = &x;
println!("{}", *y);
println!("{:p}", y);
println!("{}", y);//because println! will automatically dereference it for us.
let x = 5;
let y = &x;
println!("{}", succ(y));
println!("{}", succ(&x));
println!("{}", x);//unchanged
let mut x = 5;
let y = &mut x;
let x = 5;
let y = &x;
let z = &x;
let mut x = 5;
let y = &mut x;
// let z = &mut x; // error: cannot borrow `x` as mutable more than once at a time
//boxes:
let x = Box::new(5);//Boxes are appropriate to use in two situations: Recursive data structures, and occasionally, when returning data.
println!("{}", succ(&*x));
println!("{}", succ(&*x));
println!("{}", succ(&*x));
//recursive data structure
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
println!("{:?}", list);
let x = &mut 5;
if *x < 10 {
let y = &x; // uhm https://github.com/rust-lang/rust/issues/21575
println!("Oh no: {} {:p}", y,y);
println!("Oh no: {} {:p}", x,x);
//*y=&mut 6;
}
println!("Oh no: {} {:p}", x,x);
*x -= 1;
println!("Oh no: {} {:p}", x,x);
}//main //Box::new freed here
#[derive(Show)]
enum List<T> {
Cons(T, Box<List<T>>),
//The reference to another List inside of the Cons enum variant must be a box, because we don't
//know the length of the list. Because we don't know the length, we don't know the size, and
//therefore, we need to heap allocate our list.
//Working with recursive or other unknown-sized data structures is the primary use-case for boxes.
Nil,
}
fn foo(x: &mut i32) {
*x = 5
}
fn succ(x: &i32) -> i32 { *x + 1 }
fn realsucc(x: i32) -> i32 { x + 1 }
| {
println!("{:p} {} {}",z,*z, z);
} | conditional_block |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable borrowed content `*z` as mutable
println!("{} {}",*z,z);
//reference:
let x = 5;
let y = &x;
println!("{}", *y);
println!("{:p}", y);
println!("{}", y);//because println! will automatically dereference it for us.
let x = 5;
let y = &x;
println!("{}", succ(y));
println!("{}", succ(&x));
println!("{}", x);//unchanged
let mut x = 5;
let y = &mut x;
let x = 5;
let y = &x;
let z = &x;
let mut x = 5;
let y = &mut x;
// let z = &mut x; // error: cannot borrow `x` as mutable more than once at a time | println!("{}", succ(&*x));
println!("{}", succ(&*x));
println!("{}", succ(&*x));
//recursive data structure
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
println!("{:?}", list);
let x = &mut 5;
if *x < 10 {
let y = &x; // uhm https://github.com/rust-lang/rust/issues/21575
println!("Oh no: {} {:p}", y,y);
println!("Oh no: {} {:p}", x,x);
//*y=&mut 6;
}
println!("Oh no: {} {:p}", x,x);
*x -= 1;
println!("Oh no: {} {:p}", x,x);
}//main //Box::new freed here
#[derive(Show)]
enum List<T> {
Cons(T, Box<List<T>>),
//The reference to another List inside of the Cons enum variant must be a box, because we don't
//know the length of the list. Because we don't know the length, we don't know the size, and
//therefore, we need to heap allocate our list.
//Working with recursive or other unknown-sized data structures is the primary use-case for boxes.
Nil,
}
fn foo(x: &mut i32) {
*x = 5
}
fn succ(x: &i32) -> i32 { *x + 1 }
fn realsucc(x: i32) -> i32 { x + 1 } |
//boxes:
let x = Box::new(5);//Boxes are appropriate to use in two situations: Recursive data structures, and occasionally, when returning data. | random_line_split |
main.rs | fn | () {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable borrowed content `*z` as mutable
println!("{} {}",*z,z);
//reference:
let x = 5;
let y = &x;
println!("{}", *y);
println!("{:p}", y);
println!("{}", y);//because println! will automatically dereference it for us.
let x = 5;
let y = &x;
println!("{}", succ(y));
println!("{}", succ(&x));
println!("{}", x);//unchanged
let mut x = 5;
let y = &mut x;
let x = 5;
let y = &x;
let z = &x;
let mut x = 5;
let y = &mut x;
// let z = &mut x; // error: cannot borrow `x` as mutable more than once at a time
//boxes:
let x = Box::new(5);//Boxes are appropriate to use in two situations: Recursive data structures, and occasionally, when returning data.
println!("{}", succ(&*x));
println!("{}", succ(&*x));
println!("{}", succ(&*x));
//recursive data structure
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
println!("{:?}", list);
let x = &mut 5;
if *x < 10 {
let y = &x; // uhm https://github.com/rust-lang/rust/issues/21575
println!("Oh no: {} {:p}", y,y);
println!("Oh no: {} {:p}", x,x);
//*y=&mut 6;
}
println!("Oh no: {} {:p}", x,x);
*x -= 1;
println!("Oh no: {} {:p}", x,x);
}//main //Box::new freed here
#[derive(Show)]
enum List<T> {
Cons(T, Box<List<T>>),
//The reference to another List inside of the Cons enum variant must be a box, because we don't
//know the length of the list. Because we don't know the length, we don't know the size, and
//therefore, we need to heap allocate our list.
//Working with recursive or other unknown-sized data structures is the primary use-case for boxes.
Nil,
}
fn foo(x: &mut i32) {
*x = 5
}
fn succ(x: &i32) -> i32 { *x + 1 }
fn realsucc(x: i32) -> i32 { x + 1 }
| main | identifier_name |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable borrowed content `*z` as mutable
println!("{} {}",*z,z);
//reference:
let x = 5;
let y = &x;
println!("{}", *y);
println!("{:p}", y);
println!("{}", y);//because println! will automatically dereference it for us.
let x = 5;
let y = &x;
println!("{}", succ(y));
println!("{}", succ(&x));
println!("{}", x);//unchanged
let mut x = 5;
let y = &mut x;
let x = 5;
let y = &x;
let z = &x;
let mut x = 5;
let y = &mut x;
// let z = &mut x; // error: cannot borrow `x` as mutable more than once at a time
//boxes:
let x = Box::new(5);//Boxes are appropriate to use in two situations: Recursive data structures, and occasionally, when returning data.
println!("{}", succ(&*x));
println!("{}", succ(&*x));
println!("{}", succ(&*x));
//recursive data structure
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
println!("{:?}", list);
let x = &mut 5;
if *x < 10 {
let y = &x; // uhm https://github.com/rust-lang/rust/issues/21575
println!("Oh no: {} {:p}", y,y);
println!("Oh no: {} {:p}", x,x);
//*y=&mut 6;
}
println!("Oh no: {} {:p}", x,x);
*x -= 1;
println!("Oh no: {} {:p}", x,x);
}//main //Box::new freed here
#[derive(Show)]
enum List<T> {
Cons(T, Box<List<T>>),
//The reference to another List inside of the Cons enum variant must be a box, because we don't
//know the length of the list. Because we don't know the length, we don't know the size, and
//therefore, we need to heap allocate our list.
//Working with recursive or other unknown-sized data structures is the primary use-case for boxes.
Nil,
}
fn foo(x: &mut i32) {
*x = 5
}
fn succ(x: &i32) -> i32 { *x + 1 }
fn realsucc(x: i32) -> i32 | { x + 1 } | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.