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 |
---|---|---|---|---|
p041.rs
|
//! [Problem 41](https://projecteuler.net/problem=41) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate iter;
extern crate integer;
extern crate prime;
use iter::Permutations;
use integer::Integer;
use prime::PrimeSet;
// 1 + 2 +... + 9 = 45 (dividable by 9 => 9-pandigimal number is dividable by 9)
// 1 + 2 +... + 8 = 36 (dividable by 9 => 9-pandigimal number is dividable by 9)
// 7-pandigimal may be the largest pandigimal prime.
fn compute() -> u64
|
fn solve() -> String {
compute().to_string()
}
problem!("7652413", solve);
|
{
let radix = 10;
let ps = PrimeSet::new();
for (perm, _) in Permutations::new(&[7, 6, 5, 4, 3, 2, 1], 7) {
let n = Integer::from_digits(perm.iter().rev().map(|&x| x), radix);
if ps.contains(n) {
return n
}
}
unreachable!()
}
|
identifier_body
|
p041.rs
|
//! [Problem 41](https://projecteuler.net/problem=41) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate iter;
extern crate integer;
extern crate prime;
use iter::Permutations;
use integer::Integer;
use prime::PrimeSet;
// 1 + 2 +... + 9 = 45 (dividable by 9 => 9-pandigimal number is dividable by 9)
// 1 + 2 +... + 8 = 36 (dividable by 9 => 9-pandigimal number is dividable by 9)
// 7-pandigimal may be the largest pandigimal prime.
fn compute() -> u64 {
let radix = 10;
let ps = PrimeSet::new();
for (perm, _) in Permutations::new(&[7, 6, 5, 4, 3, 2, 1], 7) {
let n = Integer::from_digits(perm.iter().rev().map(|&x| x), radix);
if ps.contains(n) {
return n
}
|
}
unreachable!()
}
fn solve() -> String {
compute().to_string()
}
problem!("7652413", solve);
|
random_line_split
|
|
dedicatedworkerglobalscope.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::DedicatedWorkerGlobalScopeDerived;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, WorkerGlobalScopeCast};
use dom::bindings::error::ErrorResult;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, RootCollection};
use dom::bindings::refcounted::LiveDOMReferences;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::utils::Reflectable;
use dom::errorevent::ErrorEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use dom::worker::{TrustedWorkerAddress, WorkerMessageHandler, Worker};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::workerglobalscope::WorkerGlobalScopeTypeId;
use script_task::{ScriptTask, ScriptChan, ScriptMsg, TimerSource};
use script_task::ScriptMsg::WorkerDispatchErrorEvent;
use script_task::StackRootTLS;
use net::resource_task::{ResourceTask, load_whole_resource};
use util::task::spawn_named;
use util::task_state;
use util::task_state::{SCRIPT, IN_WORKER};
use js::jsapi::JSContext;
use js::jsval::JSVal;
use js::rust::Cx;
use std::rc::Rc;
use std::sync::mpsc::{Sender, Receiver};
use url::Url;
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// every message. While this SendableWorkerScriptChan is alive, the associated Worker object
/// will remain alive.
#[derive(Clone)]
#[jstraceable]
pub struct SendableWorkerScriptChan {
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: TrustedWorkerAddress,
}
impl ScriptChan for SendableWorkerScriptChan {
fn send(&self, msg: ScriptMsg) {
self.sender.send((self.worker.clone(), msg)).unwrap();
}
fn clone(&self) -> Box<ScriptChan + Send> {
box SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
}
}
}
/// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
/// value for the duration of this object's lifetime. This ensures that the related Worker
/// object only lives as long as necessary (ie. while events are being executed), while
/// providing a reference that can be cloned freely.
struct AutoWorkerReset<'a> {
workerscope: JSRef<'a, DedicatedWorkerGlobalScope>,
old_worker: Option<TrustedWorkerAddress>,
}
impl<'a> AutoWorkerReset<'a> {
fn new(workerscope: JSRef<'a, DedicatedWorkerGlobalScope>, worker: TrustedWorkerAddress) -> AutoWorkerReset<'a> {
let reset = AutoWorkerReset {
workerscope: workerscope,
old_worker: workerscope.worker.borrow().clone()
};
*workerscope.worker.borrow_mut() = Some(worker);
reset
}
}
#[unsafe_destructor]
impl<'a> Drop for AutoWorkerReset<'a> {
fn drop(&mut self) {
*self.workerscope.worker.borrow_mut() = self.old_worker.clone();
}
}
#[dom_struct]
pub struct DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: DOMRefCell<Option<TrustedWorkerAddress>>,
/// Sender to the parent thread.
parent_sender: Box<ScriptChan+Send>,
}
impl DedicatedWorkerGlobalScope {
fn new_inherited(worker_url: Url,
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> DedicatedWorkerGlobalScope {
DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(
WorkerGlobalScopeTypeId::DedicatedGlobalScope, worker_url, cx, resource_task),
receiver: receiver,
own_sender: own_sender,
parent_sender: parent_sender,
worker: DOMRefCell::new(None),
}
}
pub fn new(worker_url: Url,
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> Temporary<DedicatedWorkerGlobalScope> {
let scope = box DedicatedWorkerGlobalScope::new_inherited(
worker_url, cx.clone(), resource_task, parent_sender,
own_sender, receiver);
DedicatedWorkerGlobalScopeBinding::Wrap(cx.ptr, scope)
}
}
impl DedicatedWorkerGlobalScope {
pub fn run_worker_scope(worker_url: Url,
worker: TrustedWorkerAddress,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>) {
spawn_named(format!("WebWorker for {}", worker_url.serialize()), move || {
task_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(&resource_task, worker_url.clone()) {
Err(_) => {
println!("error loading script {}", worker_url.serialize());
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let (_js_runtime, js_context) = ScriptTask::new_rt_and_cx();
let global = DedicatedWorkerGlobalScope::new(
worker_url, js_context.clone(), resource_task,
parent_sender, own_sender, receiver).root();
{
let _ar = AutoWorkerReset::new(global.r(), worker);
match js_context.evaluate_script(
global.r().reflector().get_jsobject(), source, url.serialize(), 1) {
Ok(_) => (),
Err(_) => println!("evaluate_script failed")
}
}
loop {
match global.r().receiver.recv() {
Ok((linked_worker, msg)) => {
let _ar = AutoWorkerReset::new(global.r(), linked_worker);
global.r().handle_event(msg);
}
Err(_) => break,
}
}
});
}
}
pub trait DedicatedWorkerGlobalScopeHelpers {
fn script_chan(self) -> Box<ScriptChan+Send>;
}
impl<'a> DedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn script_chan(self) -> Box<ScriptChan+Send>
|
}
trait PrivateDedicatedWorkerGlobalScopeHelpers {
fn handle_event(self, msg: ScriptMsg);
fn dispatch_error_to_worker(self, JSRef<ErrorEvent>);
}
impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn handle_event(self, msg: ScriptMsg) {
match msg {
ScriptMsg::DOMMessage(data) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
let message = data.read(GlobalRef::Worker(scope));
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message);
},
ScriptMsg::RunnableMsg(runnable) => {
runnable.handler()
},
ScriptMsg::RefcountCleanup(addr) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
LiveDOMReferences::cleanup(scope.get_cx(), addr);
}
ScriptMsg::WorkerDispatchErrorEvent(addr, msg, file_name, line_num, col_num) => {
Worker::handle_error_message(addr, msg, file_name, line_num, col_num);
},
ScriptMsg::FireTimer(TimerSource::FromWorker, timer_id) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
scope.handle_fire_timer(timer_id);
}
_ => panic!("Unexpected message"),
}
}
fn dispatch_error_to_worker(self, errorevent: JSRef<ErrorEvent>) {
let msg = errorevent.Message();
let file_name = errorevent.Filename();
let line_num = errorevent.Lineno();
let col_num = errorevent.Colno();
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::WorkerDispatchErrorEvent(worker, msg, file_name,
line_num, col_num));
}
}
impl<'a> DedicatedWorkerGlobalScopeMethods for JSRef<'a, DedicatedWorkerGlobalScope> {
fn PostMessage(self, cx: *mut JSContext, message: JSVal) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::RunnableMsg(
box WorkerMessageHandler::new(worker, data)));
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
impl DedicatedWorkerGlobalScopeDerived for EventTarget {
fn is_dedicatedworkerglobalscope(&self) -> bool {
match *self.type_id() {
EventTargetTypeId::WorkerGlobalScope(WorkerGlobalScopeTypeId::DedicatedGlobalScope) => true,
_ => false
}
}
}
|
{
box SendableWorkerScriptChan {
sender: self.own_sender.clone(),
worker: self.worker.borrow().as_ref().unwrap().clone(),
}
}
|
identifier_body
|
dedicatedworkerglobalscope.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::DedicatedWorkerGlobalScopeDerived;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, WorkerGlobalScopeCast};
use dom::bindings::error::ErrorResult;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, RootCollection};
use dom::bindings::refcounted::LiveDOMReferences;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::utils::Reflectable;
use dom::errorevent::ErrorEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use dom::worker::{TrustedWorkerAddress, WorkerMessageHandler, Worker};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::workerglobalscope::WorkerGlobalScopeTypeId;
use script_task::{ScriptTask, ScriptChan, ScriptMsg, TimerSource};
use script_task::ScriptMsg::WorkerDispatchErrorEvent;
use script_task::StackRootTLS;
use net::resource_task::{ResourceTask, load_whole_resource};
use util::task::spawn_named;
use util::task_state;
use util::task_state::{SCRIPT, IN_WORKER};
use js::jsapi::JSContext;
use js::jsval::JSVal;
use js::rust::Cx;
use std::rc::Rc;
use std::sync::mpsc::{Sender, Receiver};
use url::Url;
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// every message. While this SendableWorkerScriptChan is alive, the associated Worker object
/// will remain alive.
#[derive(Clone)]
#[jstraceable]
pub struct SendableWorkerScriptChan {
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: TrustedWorkerAddress,
}
impl ScriptChan for SendableWorkerScriptChan {
fn send(&self, msg: ScriptMsg) {
self.sender.send((self.worker.clone(), msg)).unwrap();
}
fn clone(&self) -> Box<ScriptChan + Send> {
box SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
}
}
}
/// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
/// value for the duration of this object's lifetime. This ensures that the related Worker
/// object only lives as long as necessary (ie. while events are being executed), while
/// providing a reference that can be cloned freely.
struct AutoWorkerReset<'a> {
workerscope: JSRef<'a, DedicatedWorkerGlobalScope>,
old_worker: Option<TrustedWorkerAddress>,
}
impl<'a> AutoWorkerReset<'a> {
fn new(workerscope: JSRef<'a, DedicatedWorkerGlobalScope>, worker: TrustedWorkerAddress) -> AutoWorkerReset<'a> {
let reset = AutoWorkerReset {
workerscope: workerscope,
old_worker: workerscope.worker.borrow().clone()
};
*workerscope.worker.borrow_mut() = Some(worker);
reset
}
}
#[unsafe_destructor]
impl<'a> Drop for AutoWorkerReset<'a> {
fn drop(&mut self) {
*self.workerscope.worker.borrow_mut() = self.old_worker.clone();
}
}
#[dom_struct]
pub struct DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: DOMRefCell<Option<TrustedWorkerAddress>>,
/// Sender to the parent thread.
parent_sender: Box<ScriptChan+Send>,
}
impl DedicatedWorkerGlobalScope {
fn new_inherited(worker_url: Url,
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> DedicatedWorkerGlobalScope {
DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(
WorkerGlobalScopeTypeId::DedicatedGlobalScope, worker_url, cx, resource_task),
receiver: receiver,
own_sender: own_sender,
parent_sender: parent_sender,
worker: DOMRefCell::new(None),
|
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> Temporary<DedicatedWorkerGlobalScope> {
let scope = box DedicatedWorkerGlobalScope::new_inherited(
worker_url, cx.clone(), resource_task, parent_sender,
own_sender, receiver);
DedicatedWorkerGlobalScopeBinding::Wrap(cx.ptr, scope)
}
}
impl DedicatedWorkerGlobalScope {
pub fn run_worker_scope(worker_url: Url,
worker: TrustedWorkerAddress,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>) {
spawn_named(format!("WebWorker for {}", worker_url.serialize()), move || {
task_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(&resource_task, worker_url.clone()) {
Err(_) => {
println!("error loading script {}", worker_url.serialize());
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let (_js_runtime, js_context) = ScriptTask::new_rt_and_cx();
let global = DedicatedWorkerGlobalScope::new(
worker_url, js_context.clone(), resource_task,
parent_sender, own_sender, receiver).root();
{
let _ar = AutoWorkerReset::new(global.r(), worker);
match js_context.evaluate_script(
global.r().reflector().get_jsobject(), source, url.serialize(), 1) {
Ok(_) => (),
Err(_) => println!("evaluate_script failed")
}
}
loop {
match global.r().receiver.recv() {
Ok((linked_worker, msg)) => {
let _ar = AutoWorkerReset::new(global.r(), linked_worker);
global.r().handle_event(msg);
}
Err(_) => break,
}
}
});
}
}
pub trait DedicatedWorkerGlobalScopeHelpers {
fn script_chan(self) -> Box<ScriptChan+Send>;
}
impl<'a> DedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn script_chan(self) -> Box<ScriptChan+Send> {
box SendableWorkerScriptChan {
sender: self.own_sender.clone(),
worker: self.worker.borrow().as_ref().unwrap().clone(),
}
}
}
trait PrivateDedicatedWorkerGlobalScopeHelpers {
fn handle_event(self, msg: ScriptMsg);
fn dispatch_error_to_worker(self, JSRef<ErrorEvent>);
}
impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn handle_event(self, msg: ScriptMsg) {
match msg {
ScriptMsg::DOMMessage(data) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
let message = data.read(GlobalRef::Worker(scope));
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message);
},
ScriptMsg::RunnableMsg(runnable) => {
runnable.handler()
},
ScriptMsg::RefcountCleanup(addr) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
LiveDOMReferences::cleanup(scope.get_cx(), addr);
}
ScriptMsg::WorkerDispatchErrorEvent(addr, msg, file_name, line_num, col_num) => {
Worker::handle_error_message(addr, msg, file_name, line_num, col_num);
},
ScriptMsg::FireTimer(TimerSource::FromWorker, timer_id) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
scope.handle_fire_timer(timer_id);
}
_ => panic!("Unexpected message"),
}
}
fn dispatch_error_to_worker(self, errorevent: JSRef<ErrorEvent>) {
let msg = errorevent.Message();
let file_name = errorevent.Filename();
let line_num = errorevent.Lineno();
let col_num = errorevent.Colno();
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::WorkerDispatchErrorEvent(worker, msg, file_name,
line_num, col_num));
}
}
impl<'a> DedicatedWorkerGlobalScopeMethods for JSRef<'a, DedicatedWorkerGlobalScope> {
fn PostMessage(self, cx: *mut JSContext, message: JSVal) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::RunnableMsg(
box WorkerMessageHandler::new(worker, data)));
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
impl DedicatedWorkerGlobalScopeDerived for EventTarget {
fn is_dedicatedworkerglobalscope(&self) -> bool {
match *self.type_id() {
EventTargetTypeId::WorkerGlobalScope(WorkerGlobalScopeTypeId::DedicatedGlobalScope) => true,
_ => false
}
}
}
|
}
}
pub fn new(worker_url: Url,
|
random_line_split
|
dedicatedworkerglobalscope.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::DedicatedWorkerGlobalScopeDerived;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, WorkerGlobalScopeCast};
use dom::bindings::error::ErrorResult;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, RootCollection};
use dom::bindings::refcounted::LiveDOMReferences;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::utils::Reflectable;
use dom::errorevent::ErrorEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use dom::worker::{TrustedWorkerAddress, WorkerMessageHandler, Worker};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::workerglobalscope::WorkerGlobalScopeTypeId;
use script_task::{ScriptTask, ScriptChan, ScriptMsg, TimerSource};
use script_task::ScriptMsg::WorkerDispatchErrorEvent;
use script_task::StackRootTLS;
use net::resource_task::{ResourceTask, load_whole_resource};
use util::task::spawn_named;
use util::task_state;
use util::task_state::{SCRIPT, IN_WORKER};
use js::jsapi::JSContext;
use js::jsval::JSVal;
use js::rust::Cx;
use std::rc::Rc;
use std::sync::mpsc::{Sender, Receiver};
use url::Url;
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// every message. While this SendableWorkerScriptChan is alive, the associated Worker object
/// will remain alive.
#[derive(Clone)]
#[jstraceable]
pub struct SendableWorkerScriptChan {
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: TrustedWorkerAddress,
}
impl ScriptChan for SendableWorkerScriptChan {
fn send(&self, msg: ScriptMsg) {
self.sender.send((self.worker.clone(), msg)).unwrap();
}
fn clone(&self) -> Box<ScriptChan + Send> {
box SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
}
}
}
/// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
/// value for the duration of this object's lifetime. This ensures that the related Worker
/// object only lives as long as necessary (ie. while events are being executed), while
/// providing a reference that can be cloned freely.
struct AutoWorkerReset<'a> {
workerscope: JSRef<'a, DedicatedWorkerGlobalScope>,
old_worker: Option<TrustedWorkerAddress>,
}
impl<'a> AutoWorkerReset<'a> {
fn new(workerscope: JSRef<'a, DedicatedWorkerGlobalScope>, worker: TrustedWorkerAddress) -> AutoWorkerReset<'a> {
let reset = AutoWorkerReset {
workerscope: workerscope,
old_worker: workerscope.worker.borrow().clone()
};
*workerscope.worker.borrow_mut() = Some(worker);
reset
}
}
#[unsafe_destructor]
impl<'a> Drop for AutoWorkerReset<'a> {
fn drop(&mut self) {
*self.workerscope.worker.borrow_mut() = self.old_worker.clone();
}
}
#[dom_struct]
pub struct DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: DOMRefCell<Option<TrustedWorkerAddress>>,
/// Sender to the parent thread.
parent_sender: Box<ScriptChan+Send>,
}
impl DedicatedWorkerGlobalScope {
fn new_inherited(worker_url: Url,
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> DedicatedWorkerGlobalScope {
DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(
WorkerGlobalScopeTypeId::DedicatedGlobalScope, worker_url, cx, resource_task),
receiver: receiver,
own_sender: own_sender,
parent_sender: parent_sender,
worker: DOMRefCell::new(None),
}
}
pub fn new(worker_url: Url,
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> Temporary<DedicatedWorkerGlobalScope> {
let scope = box DedicatedWorkerGlobalScope::new_inherited(
worker_url, cx.clone(), resource_task, parent_sender,
own_sender, receiver);
DedicatedWorkerGlobalScopeBinding::Wrap(cx.ptr, scope)
}
}
impl DedicatedWorkerGlobalScope {
pub fn run_worker_scope(worker_url: Url,
worker: TrustedWorkerAddress,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>) {
spawn_named(format!("WebWorker for {}", worker_url.serialize()), move || {
task_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(&resource_task, worker_url.clone()) {
Err(_) => {
println!("error loading script {}", worker_url.serialize());
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let (_js_runtime, js_context) = ScriptTask::new_rt_and_cx();
let global = DedicatedWorkerGlobalScope::new(
worker_url, js_context.clone(), resource_task,
parent_sender, own_sender, receiver).root();
{
let _ar = AutoWorkerReset::new(global.r(), worker);
match js_context.evaluate_script(
global.r().reflector().get_jsobject(), source, url.serialize(), 1) {
Ok(_) => (),
Err(_) => println!("evaluate_script failed")
}
}
loop {
match global.r().receiver.recv() {
Ok((linked_worker, msg)) => {
let _ar = AutoWorkerReset::new(global.r(), linked_worker);
global.r().handle_event(msg);
}
Err(_) => break,
}
}
});
}
}
pub trait DedicatedWorkerGlobalScopeHelpers {
fn script_chan(self) -> Box<ScriptChan+Send>;
}
impl<'a> DedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn script_chan(self) -> Box<ScriptChan+Send> {
box SendableWorkerScriptChan {
sender: self.own_sender.clone(),
worker: self.worker.borrow().as_ref().unwrap().clone(),
}
}
}
trait PrivateDedicatedWorkerGlobalScopeHelpers {
fn handle_event(self, msg: ScriptMsg);
fn dispatch_error_to_worker(self, JSRef<ErrorEvent>);
}
impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn handle_event(self, msg: ScriptMsg) {
match msg {
ScriptMsg::DOMMessage(data) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
let message = data.read(GlobalRef::Worker(scope));
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message);
},
ScriptMsg::RunnableMsg(runnable) => {
runnable.handler()
},
ScriptMsg::RefcountCleanup(addr) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
LiveDOMReferences::cleanup(scope.get_cx(), addr);
}
ScriptMsg::WorkerDispatchErrorEvent(addr, msg, file_name, line_num, col_num) => {
Worker::handle_error_message(addr, msg, file_name, line_num, col_num);
},
ScriptMsg::FireTimer(TimerSource::FromWorker, timer_id) =>
|
_ => panic!("Unexpected message"),
}
}
fn dispatch_error_to_worker(self, errorevent: JSRef<ErrorEvent>) {
let msg = errorevent.Message();
let file_name = errorevent.Filename();
let line_num = errorevent.Lineno();
let col_num = errorevent.Colno();
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::WorkerDispatchErrorEvent(worker, msg, file_name,
line_num, col_num));
}
}
impl<'a> DedicatedWorkerGlobalScopeMethods for JSRef<'a, DedicatedWorkerGlobalScope> {
fn PostMessage(self, cx: *mut JSContext, message: JSVal) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::RunnableMsg(
box WorkerMessageHandler::new(worker, data)));
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
impl DedicatedWorkerGlobalScopeDerived for EventTarget {
fn is_dedicatedworkerglobalscope(&self) -> bool {
match *self.type_id() {
EventTargetTypeId::WorkerGlobalScope(WorkerGlobalScopeTypeId::DedicatedGlobalScope) => true,
_ => false
}
}
}
|
{
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
scope.handle_fire_timer(timer_id);
}
|
conditional_block
|
dedicatedworkerglobalscope.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::DedicatedWorkerGlobalScopeDerived;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, WorkerGlobalScopeCast};
use dom::bindings::error::ErrorResult;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, RootCollection};
use dom::bindings::refcounted::LiveDOMReferences;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::utils::Reflectable;
use dom::errorevent::ErrorEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use dom::worker::{TrustedWorkerAddress, WorkerMessageHandler, Worker};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::workerglobalscope::WorkerGlobalScopeTypeId;
use script_task::{ScriptTask, ScriptChan, ScriptMsg, TimerSource};
use script_task::ScriptMsg::WorkerDispatchErrorEvent;
use script_task::StackRootTLS;
use net::resource_task::{ResourceTask, load_whole_resource};
use util::task::spawn_named;
use util::task_state;
use util::task_state::{SCRIPT, IN_WORKER};
use js::jsapi::JSContext;
use js::jsval::JSVal;
use js::rust::Cx;
use std::rc::Rc;
use std::sync::mpsc::{Sender, Receiver};
use url::Url;
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// every message. While this SendableWorkerScriptChan is alive, the associated Worker object
/// will remain alive.
#[derive(Clone)]
#[jstraceable]
pub struct SendableWorkerScriptChan {
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: TrustedWorkerAddress,
}
impl ScriptChan for SendableWorkerScriptChan {
fn send(&self, msg: ScriptMsg) {
self.sender.send((self.worker.clone(), msg)).unwrap();
}
fn clone(&self) -> Box<ScriptChan + Send> {
box SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
}
}
}
/// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
/// value for the duration of this object's lifetime. This ensures that the related Worker
/// object only lives as long as necessary (ie. while events are being executed), while
/// providing a reference that can be cloned freely.
struct AutoWorkerReset<'a> {
workerscope: JSRef<'a, DedicatedWorkerGlobalScope>,
old_worker: Option<TrustedWorkerAddress>,
}
impl<'a> AutoWorkerReset<'a> {
fn new(workerscope: JSRef<'a, DedicatedWorkerGlobalScope>, worker: TrustedWorkerAddress) -> AutoWorkerReset<'a> {
let reset = AutoWorkerReset {
workerscope: workerscope,
old_worker: workerscope.worker.borrow().clone()
};
*workerscope.worker.borrow_mut() = Some(worker);
reset
}
}
#[unsafe_destructor]
impl<'a> Drop for AutoWorkerReset<'a> {
fn drop(&mut self) {
*self.workerscope.worker.borrow_mut() = self.old_worker.clone();
}
}
#[dom_struct]
pub struct DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
worker: DOMRefCell<Option<TrustedWorkerAddress>>,
/// Sender to the parent thread.
parent_sender: Box<ScriptChan+Send>,
}
impl DedicatedWorkerGlobalScope {
fn new_inherited(worker_url: Url,
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> DedicatedWorkerGlobalScope {
DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(
WorkerGlobalScopeTypeId::DedicatedGlobalScope, worker_url, cx, resource_task),
receiver: receiver,
own_sender: own_sender,
parent_sender: parent_sender,
worker: DOMRefCell::new(None),
}
}
pub fn new(worker_url: Url,
cx: Rc<Cx>,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>)
-> Temporary<DedicatedWorkerGlobalScope> {
let scope = box DedicatedWorkerGlobalScope::new_inherited(
worker_url, cx.clone(), resource_task, parent_sender,
own_sender, receiver);
DedicatedWorkerGlobalScopeBinding::Wrap(cx.ptr, scope)
}
}
impl DedicatedWorkerGlobalScope {
pub fn run_worker_scope(worker_url: Url,
worker: TrustedWorkerAddress,
resource_task: ResourceTask,
parent_sender: Box<ScriptChan+Send>,
own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>) {
spawn_named(format!("WebWorker for {}", worker_url.serialize()), move || {
task_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(&resource_task, worker_url.clone()) {
Err(_) => {
println!("error loading script {}", worker_url.serialize());
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let (_js_runtime, js_context) = ScriptTask::new_rt_and_cx();
let global = DedicatedWorkerGlobalScope::new(
worker_url, js_context.clone(), resource_task,
parent_sender, own_sender, receiver).root();
{
let _ar = AutoWorkerReset::new(global.r(), worker);
match js_context.evaluate_script(
global.r().reflector().get_jsobject(), source, url.serialize(), 1) {
Ok(_) => (),
Err(_) => println!("evaluate_script failed")
}
}
loop {
match global.r().receiver.recv() {
Ok((linked_worker, msg)) => {
let _ar = AutoWorkerReset::new(global.r(), linked_worker);
global.r().handle_event(msg);
}
Err(_) => break,
}
}
});
}
}
pub trait DedicatedWorkerGlobalScopeHelpers {
fn script_chan(self) -> Box<ScriptChan+Send>;
}
impl<'a> DedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn
|
(self) -> Box<ScriptChan+Send> {
box SendableWorkerScriptChan {
sender: self.own_sender.clone(),
worker: self.worker.borrow().as_ref().unwrap().clone(),
}
}
}
trait PrivateDedicatedWorkerGlobalScopeHelpers {
fn handle_event(self, msg: ScriptMsg);
fn dispatch_error_to_worker(self, JSRef<ErrorEvent>);
}
impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for JSRef<'a, DedicatedWorkerGlobalScope> {
fn handle_event(self, msg: ScriptMsg) {
match msg {
ScriptMsg::DOMMessage(data) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
let message = data.read(GlobalRef::Worker(scope));
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message);
},
ScriptMsg::RunnableMsg(runnable) => {
runnable.handler()
},
ScriptMsg::RefcountCleanup(addr) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
LiveDOMReferences::cleanup(scope.get_cx(), addr);
}
ScriptMsg::WorkerDispatchErrorEvent(addr, msg, file_name, line_num, col_num) => {
Worker::handle_error_message(addr, msg, file_name, line_num, col_num);
},
ScriptMsg::FireTimer(TimerSource::FromWorker, timer_id) => {
let scope: JSRef<WorkerGlobalScope> = WorkerGlobalScopeCast::from_ref(self);
scope.handle_fire_timer(timer_id);
}
_ => panic!("Unexpected message"),
}
}
fn dispatch_error_to_worker(self, errorevent: JSRef<ErrorEvent>) {
let msg = errorevent.Message();
let file_name = errorevent.Filename();
let line_num = errorevent.Lineno();
let col_num = errorevent.Colno();
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::WorkerDispatchErrorEvent(worker, msg, file_name,
line_num, col_num));
}
}
impl<'a> DedicatedWorkerGlobalScopeMethods for JSRef<'a, DedicatedWorkerGlobalScope> {
fn PostMessage(self, cx: *mut JSContext, message: JSVal) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender.send(ScriptMsg::RunnableMsg(
box WorkerMessageHandler::new(worker, data)));
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
impl DedicatedWorkerGlobalScopeDerived for EventTarget {
fn is_dedicatedworkerglobalscope(&self) -> bool {
match *self.type_id() {
EventTargetTypeId::WorkerGlobalScope(WorkerGlobalScopeTypeId::DedicatedGlobalScope) => true,
_ => false
}
}
}
|
script_chan
|
identifier_name
|
sequence.rs
|
// Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use back::compiler::*;
pub struct SequenceCompiler
{
seq: Vec<usize>,
compiler: ExprCompilerFn
}
impl SequenceCompiler
{
pub fn recognizer(seq: Vec<usize>) -> SequenceCompiler
|
pub fn parser(seq: Vec<usize>) -> SequenceCompiler {
SequenceCompiler {
seq: seq,
compiler: parser_compiler
}
}
}
impl CompileExpr for SequenceCompiler
{
fn compile_expr<'a>(&self, context: &mut Context<'a>,
continuation: Continuation) -> syn::Expr
{
self.seq.clone().into_iter()
.rev()
.fold(continuation, |continuation, idx|
continuation.compile_success(context, self.compiler, idx))
.unwrap_success()
}
}
|
{
SequenceCompiler {
seq: seq,
compiler: recognizer_compiler
}
}
|
identifier_body
|
sequence.rs
|
// Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use back::compiler::*;
pub struct SequenceCompiler
{
seq: Vec<usize>,
compiler: ExprCompilerFn
}
impl SequenceCompiler
{
pub fn recognizer(seq: Vec<usize>) -> SequenceCompiler {
SequenceCompiler {
seq: seq,
compiler: recognizer_compiler
}
}
pub fn parser(seq: Vec<usize>) -> SequenceCompiler {
SequenceCompiler {
seq: seq,
compiler: parser_compiler
}
}
}
impl CompileExpr for SequenceCompiler
{
fn compile_expr<'a>(&self, context: &mut Context<'a>,
continuation: Continuation) -> syn::Expr
{
self.seq.clone().into_iter()
|
}
|
.rev()
.fold(continuation, |continuation, idx|
continuation.compile_success(context, self.compiler, idx))
.unwrap_success()
}
|
random_line_split
|
sequence.rs
|
// Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use back::compiler::*;
pub struct SequenceCompiler
{
seq: Vec<usize>,
compiler: ExprCompilerFn
}
impl SequenceCompiler
{
pub fn
|
(seq: Vec<usize>) -> SequenceCompiler {
SequenceCompiler {
seq: seq,
compiler: recognizer_compiler
}
}
pub fn parser(seq: Vec<usize>) -> SequenceCompiler {
SequenceCompiler {
seq: seq,
compiler: parser_compiler
}
}
}
impl CompileExpr for SequenceCompiler
{
fn compile_expr<'a>(&self, context: &mut Context<'a>,
continuation: Continuation) -> syn::Expr
{
self.seq.clone().into_iter()
.rev()
.fold(continuation, |continuation, idx|
continuation.compile_success(context, self.compiler, idx))
.unwrap_success()
}
}
|
recognizer
|
identifier_name
|
lib.rs
|
/*
* Panopticon - A libre disassembler
* Copyright (C) 2014, 2015 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! MOS 6502 disassembler.
//!
//! This disassembler handles all documented opcode of the MOS Technology 6502 microprocessor.
#![allow(missing_docs)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate panopticon_core;
#[macro_use]
extern crate lazy_static;
extern crate byteorder;
mod syntax;
|
mod disassembler;
pub use crate::disassembler::{Mos, Variant};
|
mod semantic;
|
random_line_split
|
const-cast.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.
extern crate libc;
extern fn
|
() {}
static x: extern "C" fn() = foo;
static y: *libc::c_void = x as *libc::c_void;
static a: &'static int = &10;
static b: *int = a as *int;
pub fn main() {
assert_eq!(x as *libc::c_void, y);
assert_eq!(a as *int, b);
}
|
foo
|
identifier_name
|
const-cast.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.
|
// <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 crate libc;
extern fn foo() {}
static x: extern "C" fn() = foo;
static y: *libc::c_void = x as *libc::c_void;
static a: &'static int = &10;
static b: *int = a as *int;
pub fn main() {
assert_eq!(x as *libc::c_void, y);
assert_eq!(a as *int, b);
}
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
random_line_split
|
const-cast.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.
extern crate libc;
extern fn foo()
|
static x: extern "C" fn() = foo;
static y: *libc::c_void = x as *libc::c_void;
static a: &'static int = &10;
static b: *int = a as *int;
pub fn main() {
assert_eq!(x as *libc::c_void, y);
assert_eq!(a as *int, b);
}
|
{}
|
identifier_body
|
static-mut-foreign.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Constants (static variables) can be used to match in patterns, but mutable
// statics cannot. This ensures that there's some form of error if this is
// attempted.
// pretty-expanded FIXME #23616
#![feature(libc)]
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
static mut rust_dbg_static_mut: libc::c_int;
pub fn rust_dbg_static_mut_check_four();
}
unsafe fn
|
(_: &'static libc::c_int) {}
fn static_bound_set(a: &'static mut libc::c_int) {
*a = 3;
}
unsafe fn run() {
assert!(rust_dbg_static_mut == 3);
rust_dbg_static_mut = 4;
assert!(rust_dbg_static_mut == 4);
rust_dbg_static_mut_check_four();
rust_dbg_static_mut += 1;
assert!(rust_dbg_static_mut == 5);
rust_dbg_static_mut *= 3;
assert!(rust_dbg_static_mut == 15);
rust_dbg_static_mut = -3;
assert!(rust_dbg_static_mut == -3);
static_bound(&rust_dbg_static_mut);
static_bound_set(&mut rust_dbg_static_mut);
}
pub fn main() {
unsafe { run() }
}
|
static_bound
|
identifier_name
|
static-mut-foreign.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Constants (static variables) can be used to match in patterns, but mutable
// statics cannot. This ensures that there's some form of error if this is
// attempted.
// pretty-expanded FIXME #23616
#![feature(libc)]
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
static mut rust_dbg_static_mut: libc::c_int;
pub fn rust_dbg_static_mut_check_four();
}
unsafe fn static_bound(_: &'static libc::c_int)
|
fn static_bound_set(a: &'static mut libc::c_int) {
*a = 3;
}
unsafe fn run() {
assert!(rust_dbg_static_mut == 3);
rust_dbg_static_mut = 4;
assert!(rust_dbg_static_mut == 4);
rust_dbg_static_mut_check_four();
rust_dbg_static_mut += 1;
assert!(rust_dbg_static_mut == 5);
rust_dbg_static_mut *= 3;
assert!(rust_dbg_static_mut == 15);
rust_dbg_static_mut = -3;
assert!(rust_dbg_static_mut == -3);
static_bound(&rust_dbg_static_mut);
static_bound_set(&mut rust_dbg_static_mut);
}
pub fn main() {
unsafe { run() }
}
|
{}
|
identifier_body
|
static-mut-foreign.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Constants (static variables) can be used to match in patterns, but mutable
// statics cannot. This ensures that there's some form of error if this is
// attempted.
// pretty-expanded FIXME #23616
#![feature(libc)]
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
static mut rust_dbg_static_mut: libc::c_int;
pub fn rust_dbg_static_mut_check_four();
}
unsafe fn static_bound(_: &'static libc::c_int) {}
fn static_bound_set(a: &'static mut libc::c_int) {
*a = 3;
}
unsafe fn run() {
|
rust_dbg_static_mut = 4;
assert!(rust_dbg_static_mut == 4);
rust_dbg_static_mut_check_four();
rust_dbg_static_mut += 1;
assert!(rust_dbg_static_mut == 5);
rust_dbg_static_mut *= 3;
assert!(rust_dbg_static_mut == 15);
rust_dbg_static_mut = -3;
assert!(rust_dbg_static_mut == -3);
static_bound(&rust_dbg_static_mut);
static_bound_set(&mut rust_dbg_static_mut);
}
pub fn main() {
unsafe { run() }
}
|
assert!(rust_dbg_static_mut == 3);
|
random_line_split
|
project.rs
|
/*
* Panopticon - A libre disassembler
* Copyright (C) 2015 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate panopticon_core;
use panopticon_core::Project;
use std::path::Path;
#[test]
fn project_open() {
|
assert!(maybe_project.ok().is_some());
}
|
let maybe_project = Project::open(Path::new("../test-data/save.panop"));
|
random_line_split
|
project.rs
|
/*
* Panopticon - A libre disassembler
* Copyright (C) 2015 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate panopticon_core;
use panopticon_core::Project;
use std::path::Path;
#[test]
fn
|
() {
let maybe_project = Project::open(Path::new("../test-data/save.panop"));
assert!(maybe_project.ok().is_some());
}
|
project_open
|
identifier_name
|
project.rs
|
/*
* Panopticon - A libre disassembler
* Copyright (C) 2015 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate panopticon_core;
use panopticon_core::Project;
use std::path::Path;
#[test]
fn project_open()
|
{
let maybe_project = Project::open(Path::new("../test-data/save.panop"));
assert!(maybe_project.ok().is_some());
}
|
identifier_body
|
|
defer.rs
|
#![feature(test)]
extern crate test;
use crossbeam_epoch::{self as epoch, Owned};
use crossbeam_utils::thread::scope;
use test::Bencher;
#[bench]
fn single_alloc_defer_free(b: &mut Bencher) {
b.iter(|| {
let guard = &epoch::pin();
let p = Owned::new(1).into_shared(guard);
unsafe {
guard.defer_destroy(p);
}
});
}
#[bench]
fn single_defer(b: &mut Bencher) {
b.iter(|| {
let guard = &epoch::pin();
guard.defer(move || ());
});
}
#[bench]
fn multi_alloc_defer_free(b: &mut Bencher) {
const THREADS: usize = 16;
const STEPS: usize = 10_000;
b.iter(|| {
scope(|s| {
for _ in 0..THREADS {
s.spawn(|_| {
for _ in 0..STEPS {
let guard = &epoch::pin();
let p = Owned::new(1).into_shared(guard);
unsafe {
guard.defer_destroy(p);
}
}
});
}
})
.unwrap();
});
}
#[bench]
fn multi_defer(b: &mut Bencher) {
const THREADS: usize = 16;
const STEPS: usize = 10_000;
b.iter(|| {
scope(|s| {
for _ in 0..THREADS {
|
for _ in 0..STEPS {
let guard = &epoch::pin();
guard.defer(move || ());
}
});
}
})
.unwrap();
});
}
|
s.spawn(|_| {
|
random_line_split
|
defer.rs
|
#![feature(test)]
extern crate test;
use crossbeam_epoch::{self as epoch, Owned};
use crossbeam_utils::thread::scope;
use test::Bencher;
#[bench]
fn single_alloc_defer_free(b: &mut Bencher) {
b.iter(|| {
let guard = &epoch::pin();
let p = Owned::new(1).into_shared(guard);
unsafe {
guard.defer_destroy(p);
}
});
}
#[bench]
fn single_defer(b: &mut Bencher)
|
#[bench]
fn multi_alloc_defer_free(b: &mut Bencher) {
const THREADS: usize = 16;
const STEPS: usize = 10_000;
b.iter(|| {
scope(|s| {
for _ in 0..THREADS {
s.spawn(|_| {
for _ in 0..STEPS {
let guard = &epoch::pin();
let p = Owned::new(1).into_shared(guard);
unsafe {
guard.defer_destroy(p);
}
}
});
}
})
.unwrap();
});
}
#[bench]
fn multi_defer(b: &mut Bencher) {
const THREADS: usize = 16;
const STEPS: usize = 10_000;
b.iter(|| {
scope(|s| {
for _ in 0..THREADS {
s.spawn(|_| {
for _ in 0..STEPS {
let guard = &epoch::pin();
guard.defer(move || ());
}
});
}
})
.unwrap();
});
}
|
{
b.iter(|| {
let guard = &epoch::pin();
guard.defer(move || ());
});
}
|
identifier_body
|
defer.rs
|
#![feature(test)]
extern crate test;
use crossbeam_epoch::{self as epoch, Owned};
use crossbeam_utils::thread::scope;
use test::Bencher;
#[bench]
fn single_alloc_defer_free(b: &mut Bencher) {
b.iter(|| {
let guard = &epoch::pin();
let p = Owned::new(1).into_shared(guard);
unsafe {
guard.defer_destroy(p);
}
});
}
#[bench]
fn single_defer(b: &mut Bencher) {
b.iter(|| {
let guard = &epoch::pin();
guard.defer(move || ());
});
}
#[bench]
fn
|
(b: &mut Bencher) {
const THREADS: usize = 16;
const STEPS: usize = 10_000;
b.iter(|| {
scope(|s| {
for _ in 0..THREADS {
s.spawn(|_| {
for _ in 0..STEPS {
let guard = &epoch::pin();
let p = Owned::new(1).into_shared(guard);
unsafe {
guard.defer_destroy(p);
}
}
});
}
})
.unwrap();
});
}
#[bench]
fn multi_defer(b: &mut Bencher) {
const THREADS: usize = 16;
const STEPS: usize = 10_000;
b.iter(|| {
scope(|s| {
for _ in 0..THREADS {
s.spawn(|_| {
for _ in 0..STEPS {
let guard = &epoch::pin();
guard.defer(move || ());
}
});
}
})
.unwrap();
});
}
|
multi_alloc_defer_free
|
identifier_name
|
syntax-extension-minor.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.
// xfail-test
// this now fails (correctly, I claim) because hygiene prevents
// the assembled identifier from being a reference to the binding.
pub fn main() {
|
"use_mention_distinction");
}
|
let asdf_fdsa = ~"<.<";
assert_eq!(concat_idents!(asd, f_f, dsa), ~"<.<");
assert!(stringify!(use_mention_distinction) ==
|
random_line_split
|
syntax-extension-minor.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.
// xfail-test
// this now fails (correctly, I claim) because hygiene prevents
// the assembled identifier from being a reference to the binding.
pub fn main()
|
{
let asdf_fdsa = ~"<.<";
assert_eq!(concat_idents!(asd, f_f, dsa), ~"<.<");
assert!(stringify!(use_mention_distinction) ==
"use_mention_distinction");
}
|
identifier_body
|
|
syntax-extension-minor.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.
// xfail-test
// this now fails (correctly, I claim) because hygiene prevents
// the assembled identifier from being a reference to the binding.
pub fn
|
() {
let asdf_fdsa = ~"<.<";
assert_eq!(concat_idents!(asd, f_f, dsa), ~"<.<");
assert!(stringify!(use_mention_distinction) ==
"use_mention_distinction");
}
|
main
|
identifier_name
|
trace_macros-format.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(trace_macros)]
fn main() {
trace_macros!(); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(1); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(ident); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(for); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(true,); //~ ERROR trace_macros! accepts only `true` or `false`
|
// should be fine:
macro_rules! expando {
($x: ident) => { trace_macros!($x) }
}
expando!(true);
}
|
trace_macros!(false 1); //~ ERROR trace_macros! accepts only `true` or `false`
|
random_line_split
|
trace_macros-format.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(trace_macros)]
fn main()
|
{
trace_macros!(); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(1); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(ident); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(for); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(true,); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(false 1); //~ ERROR trace_macros! accepts only `true` or `false`
// should be fine:
macro_rules! expando {
($x: ident) => { trace_macros!($x) }
}
expando!(true);
}
|
identifier_body
|
|
trace_macros-format.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(trace_macros)]
fn
|
() {
trace_macros!(); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(1); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(ident); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(for); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(true,); //~ ERROR trace_macros! accepts only `true` or `false`
trace_macros!(false 1); //~ ERROR trace_macros! accepts only `true` or `false`
// should be fine:
macro_rules! expando {
($x: ident) => { trace_macros!($x) }
}
expando!(true);
}
|
main
|
identifier_name
|
namespaced_enum_emulate_flat.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs, struct_variant)]
pub use Foo::*;
pub enum Foo {
A,
B(int),
C { a: int },
}
impl Foo {
pub fn foo() {}
}
|
D,
E(int),
F { a: int },
}
impl Bar {
pub fn foo() {}
}
}
|
pub mod nest {
pub use self::Bar::*;
pub enum Bar {
|
random_line_split
|
namespaced_enum_emulate_flat.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs, struct_variant)]
pub use Foo::*;
pub enum Foo {
A,
B(int),
C { a: int },
}
impl Foo {
pub fn foo() {}
}
pub mod nest {
pub use self::Bar::*;
pub enum
|
{
D,
E(int),
F { a: int },
}
impl Bar {
pub fn foo() {}
}
}
|
Bar
|
identifier_name
|
main.rs
|
// Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "bin"]
#![crate_name = "mkdir"]
static UTIL: Prog = Prog { name: "mkdir", vers: "0.1.0", yr: "2015" };
extern crate pgetopts;
extern crate rpf;
use pgetopts::{Options};
use rpf::*;
use std::fs;
use std::env;
use std::path::{PathBuf};
fn mk_dir(dir: Vec<String>, verbose: bool) {
for item in dir {
match fs::create_dir(PathBuf::from(&item)) {
Ok(_) => {
if verbose {
println!("{}: created directory '{}'", UTIL.name, item);
}
},
Err(e) => {
UTIL.error(e.to_string(), ExitStatus::Error);
}
};
}
}
fn mk_dir_p(dir: Vec<String>, verbose: bool) {
for item in dir {
match fs::create_dir_all(PathBuf::from(&item)) {
Ok(_) => {
if verbose {
println!("{}: created directory '{}'", UTIL.name, item);
}
},
Err(e) => {
UTIL.error(e.to_string(), ExitStatus::Error);
}
};
}
}
fn
|
(opts: Options) {
print!("{}: {} {}... {}...\n\
Create DIRECTORY(ies) if they do not already exist.", "Usage".bold(),
UTIL.name.bold(), "[OPTION]".underline(), "DIRECTORY".underline());
println!("{}", opts.options());
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("v", "verbose", "Print the name of each created directory");
opts.optflag("p", "parents", "No error if existing, make parent directories as needed");
opts.optflag("h", "help", "Print help information");
opts.optflag("", "version", "Print version information");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => {
UTIL.error(f.to_string(), ExitStatus::OptError);
panic!(f);
}
};
let verb = matches.opt_present("v");
if matches.opt_present("p") {
mk_dir_p(matches.free, verb);
} else if matches.opt_present("h") {
print_usage(opts);
} else if matches.opt_present("version") {
UTIL.copyright("Copyright (C) 2015 core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n",
&["Alberto Corona"]);
} else if matches.free.is_empty() {
UTIL.prog_try();
} else {
mk_dir(matches.free, verb);
}
}
|
print_usage
|
identifier_name
|
main.rs
|
// Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "bin"]
#![crate_name = "mkdir"]
static UTIL: Prog = Prog { name: "mkdir", vers: "0.1.0", yr: "2015" };
extern crate pgetopts;
extern crate rpf;
use pgetopts::{Options};
use rpf::*;
use std::fs;
use std::env;
use std::path::{PathBuf};
fn mk_dir(dir: Vec<String>, verbose: bool) {
for item in dir {
match fs::create_dir(PathBuf::from(&item)) {
Ok(_) => {
if verbose {
println!("{}: created directory '{}'", UTIL.name, item);
}
},
Err(e) => {
UTIL.error(e.to_string(), ExitStatus::Error);
}
};
}
}
fn mk_dir_p(dir: Vec<String>, verbose: bool) {
for item in dir {
match fs::create_dir_all(PathBuf::from(&item)) {
Ok(_) => {
if verbose {
println!("{}: created directory '{}'", UTIL.name, item);
|
Err(e) => {
UTIL.error(e.to_string(), ExitStatus::Error);
}
};
}
}
fn print_usage(opts: Options) {
print!("{}: {} {}... {}...\n\
Create DIRECTORY(ies) if they do not already exist.", "Usage".bold(),
UTIL.name.bold(), "[OPTION]".underline(), "DIRECTORY".underline());
println!("{}", opts.options());
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("v", "verbose", "Print the name of each created directory");
opts.optflag("p", "parents", "No error if existing, make parent directories as needed");
opts.optflag("h", "help", "Print help information");
opts.optflag("", "version", "Print version information");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => {
UTIL.error(f.to_string(), ExitStatus::OptError);
panic!(f);
}
};
let verb = matches.opt_present("v");
if matches.opt_present("p") {
mk_dir_p(matches.free, verb);
} else if matches.opt_present("h") {
print_usage(opts);
} else if matches.opt_present("version") {
UTIL.copyright("Copyright (C) 2015 core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n",
&["Alberto Corona"]);
} else if matches.free.is_empty() {
UTIL.prog_try();
} else {
mk_dir(matches.free, verb);
}
}
|
}
},
|
random_line_split
|
main.rs
|
// Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "bin"]
#![crate_name = "mkdir"]
static UTIL: Prog = Prog { name: "mkdir", vers: "0.1.0", yr: "2015" };
extern crate pgetopts;
extern crate rpf;
use pgetopts::{Options};
use rpf::*;
use std::fs;
use std::env;
use std::path::{PathBuf};
fn mk_dir(dir: Vec<String>, verbose: bool) {
for item in dir {
match fs::create_dir(PathBuf::from(&item)) {
Ok(_) => {
if verbose {
println!("{}: created directory '{}'", UTIL.name, item);
}
},
Err(e) => {
UTIL.error(e.to_string(), ExitStatus::Error);
}
};
}
}
fn mk_dir_p(dir: Vec<String>, verbose: bool) {
for item in dir {
match fs::create_dir_all(PathBuf::from(&item)) {
Ok(_) => {
if verbose {
println!("{}: created directory '{}'", UTIL.name, item);
}
},
Err(e) => {
UTIL.error(e.to_string(), ExitStatus::Error);
}
};
}
}
fn print_usage(opts: Options)
|
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("v", "verbose", "Print the name of each created directory");
opts.optflag("p", "parents", "No error if existing, make parent directories as needed");
opts.optflag("h", "help", "Print help information");
opts.optflag("", "version", "Print version information");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => {
UTIL.error(f.to_string(), ExitStatus::OptError);
panic!(f);
}
};
let verb = matches.opt_present("v");
if matches.opt_present("p") {
mk_dir_p(matches.free, verb);
} else if matches.opt_present("h") {
print_usage(opts);
} else if matches.opt_present("version") {
UTIL.copyright("Copyright (C) 2015 core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n",
&["Alberto Corona"]);
} else if matches.free.is_empty() {
UTIL.prog_try();
} else {
mk_dir(matches.free, verb);
}
}
|
{
print!("{}: {} {}... {}...\n\
Create DIRECTORY(ies) if they do not already exist.", "Usage".bold(),
UTIL.name.bold(), "[OPTION]".underline(), "DIRECTORY".underline());
println!("{}", opts.options());
}
|
identifier_body
|
ui.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use clap::{Arg, App};
pub fn build_ui<'a>() -> App<'a, 'a> {
|
.version(&version!()[..])
.author("Matthias Beyer <[email protected]>")
.about("Initialize a ~/.imag repository. Optionally with git")
.arg(Arg::with_name("devel")
.long("dev")
.takes_value(false)
.required(false)
.multiple(false)
.help("Put dev configuration into the generated repo (with debugging enabled)"))
.arg(Arg::with_name("nogit")
.long("no-git")
.takes_value(false)
.required(false)
.multiple(false)
.help("Do not initialize git repository, even if 'git' executable is in $PATH"))
.arg(Arg::with_name("path")
.long("path")
.takes_value(true)
.required(false)
.multiple(false)
.help("Alternative path where to put the repository. Default: ~/.imag"))
}
|
App::new("imag-init")
|
random_line_split
|
ui.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use clap::{Arg, App};
pub fn build_ui<'a>() -> App<'a, 'a>
|
.arg(Arg::with_name("path")
.long("path")
.takes_value(true)
.required(false)
.multiple(false)
.help("Alternative path where to put the repository. Default: ~/.imag"))
}
|
{
App::new("imag-init")
.version(&version!()[..])
.author("Matthias Beyer <[email protected]>")
.about("Initialize a ~/.imag repository. Optionally with git")
.arg(Arg::with_name("devel")
.long("dev")
.takes_value(false)
.required(false)
.multiple(false)
.help("Put dev configuration into the generated repo (with debugging enabled)"))
.arg(Arg::with_name("nogit")
.long("no-git")
.takes_value(false)
.required(false)
.multiple(false)
.help("Do not initialize git repository, even if 'git' executable is in $PATH"))
|
identifier_body
|
ui.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use clap::{Arg, App};
pub fn
|
<'a>() -> App<'a, 'a> {
App::new("imag-init")
.version(&version!()[..])
.author("Matthias Beyer <[email protected]>")
.about("Initialize a ~/.imag repository. Optionally with git")
.arg(Arg::with_name("devel")
.long("dev")
.takes_value(false)
.required(false)
.multiple(false)
.help("Put dev configuration into the generated repo (with debugging enabled)"))
.arg(Arg::with_name("nogit")
.long("no-git")
.takes_value(false)
.required(false)
.multiple(false)
.help("Do not initialize git repository, even if 'git' executable is in $PATH"))
.arg(Arg::with_name("path")
.long("path")
.takes_value(true)
.required(false)
.multiple(false)
.help("Alternative path where to put the repository. Default: ~/.imag"))
}
|
build_ui
|
identifier_name
|
location.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::LocationBinding;
use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods;
use dom::bindings::global::Window;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::urlhelper::UrlHelper;
use dom::window::Window;
use page::Page;
use servo_util::str::DOMString;
use std::rc::Rc;
#[deriving(Encodable)]
#[must_root]
pub struct Location {
reflector_: Reflector, //XXXjdm cycle: window->Location->window
page: Rc<Page>,
}
impl Location {
pub fn new_inherited(page: Rc<Page>) -> Location {
Location {
reflector_: Reflector::new(),
page: page
}
}
pub fn new(window: JSRef<Window>, page: Rc<Page>) -> Temporary<Location> {
reflect_dom_object(box Location::new_inherited(page),
&Window(window),
LocationBinding::Wrap)
}
}
impl<'a> LocationMethods for JSRef<'a, Location> {
fn Href(self) -> DOMString {
UrlHelper::Href(&self.page.get_url())
}
fn Search(self) -> DOMString {
UrlHelper::Search(&self.page.get_url())
}
fn Hash(self) -> DOMString {
UrlHelper::Hash(&self.page.get_url())
}
}
impl Reflectable for Location {
fn reflector<'a>(&'a self) -> &'a Reflector
|
}
|
{
&self.reflector_
}
|
identifier_body
|
location.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::LocationBinding;
use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods;
use dom::bindings::global::Window;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::urlhelper::UrlHelper;
use dom::window::Window;
use page::Page;
use servo_util::str::DOMString;
use std::rc::Rc;
#[deriving(Encodable)]
#[must_root]
pub struct Location {
reflector_: Reflector, //XXXjdm cycle: window->Location->window
page: Rc<Page>,
}
impl Location {
pub fn new_inherited(page: Rc<Page>) -> Location {
Location {
reflector_: Reflector::new(),
page: page
}
}
pub fn new(window: JSRef<Window>, page: Rc<Page>) -> Temporary<Location> {
reflect_dom_object(box Location::new_inherited(page),
&Window(window),
LocationBinding::Wrap)
}
}
impl<'a> LocationMethods for JSRef<'a, Location> {
fn
|
(self) -> DOMString {
UrlHelper::Href(&self.page.get_url())
}
fn Search(self) -> DOMString {
UrlHelper::Search(&self.page.get_url())
}
fn Hash(self) -> DOMString {
UrlHelper::Hash(&self.page.get_url())
}
}
impl Reflectable for Location {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
}
|
Href
|
identifier_name
|
location.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::LocationBinding;
use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods;
use dom::bindings::global::Window;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::urlhelper::UrlHelper;
use dom::window::Window;
use page::Page;
use servo_util::str::DOMString;
use std::rc::Rc;
#[deriving(Encodable)]
#[must_root]
pub struct Location {
reflector_: Reflector, //XXXjdm cycle: window->Location->window
page: Rc<Page>,
}
impl Location {
pub fn new_inherited(page: Rc<Page>) -> Location {
Location {
reflector_: Reflector::new(),
page: page
}
}
pub fn new(window: JSRef<Window>, page: Rc<Page>) -> Temporary<Location> {
reflect_dom_object(box Location::new_inherited(page),
&Window(window),
LocationBinding::Wrap)
}
}
impl<'a> LocationMethods for JSRef<'a, Location> {
fn Href(self) -> DOMString {
UrlHelper::Href(&self.page.get_url())
}
fn Search(self) -> DOMString {
UrlHelper::Search(&self.page.get_url())
}
fn Hash(self) -> DOMString {
UrlHelper::Hash(&self.page.get_url())
}
}
impl Reflectable for Location {
|
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
}
|
random_line_split
|
|
exposure.rs
|
use leelib::math;
use leelib::matrix::Matrix;
pub struct ExposureInfo {
pub floor: usize,
pub ceil: usize,
pub bias: f64
}
/**
* 'Static' class
* Finds the'meaningful' range of values in a matrix, along with a 'bias' value.
* Experiment.
*/
pub struct ExposureUtil;
impl ExposureUtil {
/**
* max_val - the max value of anything in the matrix; used to create 'histogram'
* lower/upper_thresh_ratio - the ratio of the amount of upper and lower values to discard when calculating the range
*
* returns the range where values occur, and the 'center of gravity' ratio (-1 to +1) within that range
*/
pub fn calc(matrix: &Matrix<u16>, max_val: u16, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> ExposureInfo {
// count the values in `matrix`
let mut histogram = vec!(0u16; (max_val + 1) as usize);
for val in matrix {
histogram[val as usize] += 1;
}
let range = ExposureUtil::get_range(&histogram, &matrix, lower_thresh_ratio, upper_thresh_ratio);
let bias = ExposureUtil::calc_bias(&histogram, range.0, range.1);
ExposureInfo { floor: range.0, ceil: range.1, bias: bias }
}
/**
* Finds the range where values occur,
* discounting the extreme values as described by lower/upper_thresh_ratio
*/
fn get_range(histogram: &Vec<u16>, matrix: &Matrix<u16>, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> (usize, usize) {
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * lower_thresh_ratio;
let mut lower_index = 0;
let mut sum = 0;
for i in 0..histogram.len() {
sum += histogram[i];
if sum as f64 > sum_thresh {
lower_index = if i <= 1 {
0 as usize
} else {
i - 1 // rewind by 1
};
break;
}
}
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * upper_thresh_ratio;
let mut upper_index = 0;
let mut sum = 0;
for i in (0..histogram.len()).rev() {
sum += histogram[i];
if sum as f64 > sum_thresh {
upper_index = if i == histogram.len() - 1 {
histogram.len() - 1
} else if i <= 1 {
0
} else {
i - 1
};
break;
}
}
(lower_index, upper_index)
}
/**
* Returns a value in range (-1, +1)
*/
fn calc_bias(histogram: &Vec<u16>, lower: usize, upper: usize) -> f64 {
if lower == upper {
return 0.0;
}
if upper == lower + 1 {
return if histogram[lower] < histogram[upper] {
return -1.0;
} else {
return 1.0;
}
}
// get sum of all values
let mut sum = 0u64;
for i in lower..(upper + 1) {
sum += histogram[i] as u64;
}
// find index at the 16%, 50%, 84%
let mut i_a = 0 as usize;
let thresh = sum as f64 * (0.5 - 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 16th percentile; 1 standard deviation
i_a = i;
break;
}
}
let mut i_b = 0 as usize;
let thresh = sum as f64 * 0.5;
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// think 'center of gravity'
|
}
let mut i_c = 0 as usize;
let thresh = sum as f64 * (0.5 + 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 84th percentile
i_c = i;
break;
}
}
// make hand-wavey value using the above to represent 'bias'
let a = math::map(i_a as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let b = math::map(i_b as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let c = math::map(i_c as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
return (a + b + c) / 3.0;
}
}
|
i_b = i;
break;
}
|
random_line_split
|
exposure.rs
|
use leelib::math;
use leelib::matrix::Matrix;
pub struct ExposureInfo {
pub floor: usize,
pub ceil: usize,
pub bias: f64
}
/**
* 'Static' class
* Finds the'meaningful' range of values in a matrix, along with a 'bias' value.
* Experiment.
*/
pub struct ExposureUtil;
impl ExposureUtil {
/**
* max_val - the max value of anything in the matrix; used to create 'histogram'
* lower/upper_thresh_ratio - the ratio of the amount of upper and lower values to discard when calculating the range
*
* returns the range where values occur, and the 'center of gravity' ratio (-1 to +1) within that range
*/
pub fn
|
(matrix: &Matrix<u16>, max_val: u16, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> ExposureInfo {
// count the values in `matrix`
let mut histogram = vec!(0u16; (max_val + 1) as usize);
for val in matrix {
histogram[val as usize] += 1;
}
let range = ExposureUtil::get_range(&histogram, &matrix, lower_thresh_ratio, upper_thresh_ratio);
let bias = ExposureUtil::calc_bias(&histogram, range.0, range.1);
ExposureInfo { floor: range.0, ceil: range.1, bias: bias }
}
/**
* Finds the range where values occur,
* discounting the extreme values as described by lower/upper_thresh_ratio
*/
fn get_range(histogram: &Vec<u16>, matrix: &Matrix<u16>, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> (usize, usize) {
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * lower_thresh_ratio;
let mut lower_index = 0;
let mut sum = 0;
for i in 0..histogram.len() {
sum += histogram[i];
if sum as f64 > sum_thresh {
lower_index = if i <= 1 {
0 as usize
} else {
i - 1 // rewind by 1
};
break;
}
}
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * upper_thresh_ratio;
let mut upper_index = 0;
let mut sum = 0;
for i in (0..histogram.len()).rev() {
sum += histogram[i];
if sum as f64 > sum_thresh {
upper_index = if i == histogram.len() - 1 {
histogram.len() - 1
} else if i <= 1 {
0
} else {
i - 1
};
break;
}
}
(lower_index, upper_index)
}
/**
* Returns a value in range (-1, +1)
*/
fn calc_bias(histogram: &Vec<u16>, lower: usize, upper: usize) -> f64 {
if lower == upper {
return 0.0;
}
if upper == lower + 1 {
return if histogram[lower] < histogram[upper] {
return -1.0;
} else {
return 1.0;
}
}
// get sum of all values
let mut sum = 0u64;
for i in lower..(upper + 1) {
sum += histogram[i] as u64;
}
// find index at the 16%, 50%, 84%
let mut i_a = 0 as usize;
let thresh = sum as f64 * (0.5 - 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 16th percentile; 1 standard deviation
i_a = i;
break;
}
}
let mut i_b = 0 as usize;
let thresh = sum as f64 * 0.5;
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// think 'center of gravity'
i_b = i;
break;
}
}
let mut i_c = 0 as usize;
let thresh = sum as f64 * (0.5 + 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 84th percentile
i_c = i;
break;
}
}
// make hand-wavey value using the above to represent 'bias'
let a = math::map(i_a as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let b = math::map(i_b as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let c = math::map(i_c as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
return (a + b + c) / 3.0;
}
}
|
calc
|
identifier_name
|
exposure.rs
|
use leelib::math;
use leelib::matrix::Matrix;
pub struct ExposureInfo {
pub floor: usize,
pub ceil: usize,
pub bias: f64
}
/**
* 'Static' class
* Finds the'meaningful' range of values in a matrix, along with a 'bias' value.
* Experiment.
*/
pub struct ExposureUtil;
impl ExposureUtil {
/**
* max_val - the max value of anything in the matrix; used to create 'histogram'
* lower/upper_thresh_ratio - the ratio of the amount of upper and lower values to discard when calculating the range
*
* returns the range where values occur, and the 'center of gravity' ratio (-1 to +1) within that range
*/
pub fn calc(matrix: &Matrix<u16>, max_val: u16, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> ExposureInfo {
// count the values in `matrix`
let mut histogram = vec!(0u16; (max_val + 1) as usize);
for val in matrix {
histogram[val as usize] += 1;
}
let range = ExposureUtil::get_range(&histogram, &matrix, lower_thresh_ratio, upper_thresh_ratio);
let bias = ExposureUtil::calc_bias(&histogram, range.0, range.1);
ExposureInfo { floor: range.0, ceil: range.1, bias: bias }
}
/**
* Finds the range where values occur,
* discounting the extreme values as described by lower/upper_thresh_ratio
*/
fn get_range(histogram: &Vec<u16>, matrix: &Matrix<u16>, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> (usize, usize)
|
for i in (0..histogram.len()).rev() {
sum += histogram[i];
if sum as f64 > sum_thresh {
upper_index = if i == histogram.len() - 1 {
histogram.len() - 1
} else if i <= 1 {
0
} else {
i - 1
};
break;
}
}
(lower_index, upper_index)
}
/**
* Returns a value in range (-1, +1)
*/
fn calc_bias(histogram: &Vec<u16>, lower: usize, upper: usize) -> f64 {
if lower == upper {
return 0.0;
}
if upper == lower + 1 {
return if histogram[lower] < histogram[upper] {
return -1.0;
} else {
return 1.0;
}
}
// get sum of all values
let mut sum = 0u64;
for i in lower..(upper + 1) {
sum += histogram[i] as u64;
}
// find index at the 16%, 50%, 84%
let mut i_a = 0 as usize;
let thresh = sum as f64 * (0.5 - 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 16th percentile; 1 standard deviation
i_a = i;
break;
}
}
let mut i_b = 0 as usize;
let thresh = sum as f64 * 0.5;
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// think 'center of gravity'
i_b = i;
break;
}
}
let mut i_c = 0 as usize;
let thresh = sum as f64 * (0.5 + 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 84th percentile
i_c = i;
break;
}
}
// make hand-wavey value using the above to represent 'bias'
let a = math::map(i_a as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let b = math::map(i_b as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let c = math::map(i_c as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
return (a + b + c) / 3.0;
}
}
|
{
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * lower_thresh_ratio;
let mut lower_index = 0;
let mut sum = 0;
for i in 0..histogram.len() {
sum += histogram[i];
if sum as f64 > sum_thresh {
lower_index = if i <= 1 {
0 as usize
} else {
i - 1 // rewind by 1
};
break;
}
}
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * upper_thresh_ratio;
let mut upper_index = 0;
let mut sum = 0;
|
identifier_body
|
exposure.rs
|
use leelib::math;
use leelib::matrix::Matrix;
pub struct ExposureInfo {
pub floor: usize,
pub ceil: usize,
pub bias: f64
}
/**
* 'Static' class
* Finds the'meaningful' range of values in a matrix, along with a 'bias' value.
* Experiment.
*/
pub struct ExposureUtil;
impl ExposureUtil {
/**
* max_val - the max value of anything in the matrix; used to create 'histogram'
* lower/upper_thresh_ratio - the ratio of the amount of upper and lower values to discard when calculating the range
*
* returns the range where values occur, and the 'center of gravity' ratio (-1 to +1) within that range
*/
pub fn calc(matrix: &Matrix<u16>, max_val: u16, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> ExposureInfo {
// count the values in `matrix`
let mut histogram = vec!(0u16; (max_val + 1) as usize);
for val in matrix {
histogram[val as usize] += 1;
}
let range = ExposureUtil::get_range(&histogram, &matrix, lower_thresh_ratio, upper_thresh_ratio);
let bias = ExposureUtil::calc_bias(&histogram, range.0, range.1);
ExposureInfo { floor: range.0, ceil: range.1, bias: bias }
}
/**
* Finds the range where values occur,
* discounting the extreme values as described by lower/upper_thresh_ratio
*/
fn get_range(histogram: &Vec<u16>, matrix: &Matrix<u16>, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> (usize, usize) {
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * lower_thresh_ratio;
let mut lower_index = 0;
let mut sum = 0;
for i in 0..histogram.len() {
sum += histogram[i];
if sum as f64 > sum_thresh
|
}
let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * upper_thresh_ratio;
let mut upper_index = 0;
let mut sum = 0;
for i in (0..histogram.len()).rev() {
sum += histogram[i];
if sum as f64 > sum_thresh {
upper_index = if i == histogram.len() - 1 {
histogram.len() - 1
} else if i <= 1 {
0
} else {
i - 1
};
break;
}
}
(lower_index, upper_index)
}
/**
* Returns a value in range (-1, +1)
*/
fn calc_bias(histogram: &Vec<u16>, lower: usize, upper: usize) -> f64 {
if lower == upper {
return 0.0;
}
if upper == lower + 1 {
return if histogram[lower] < histogram[upper] {
return -1.0;
} else {
return 1.0;
}
}
// get sum of all values
let mut sum = 0u64;
for i in lower..(upper + 1) {
sum += histogram[i] as u64;
}
// find index at the 16%, 50%, 84%
let mut i_a = 0 as usize;
let thresh = sum as f64 * (0.5 - 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 16th percentile; 1 standard deviation
i_a = i;
break;
}
}
let mut i_b = 0 as usize;
let thresh = sum as f64 * 0.5;
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// think 'center of gravity'
i_b = i;
break;
}
}
let mut i_c = 0 as usize;
let thresh = sum as f64 * (0.5 + 0.34);
let mut s = 0;
for i in lower..(upper + 1) {
s += histogram[i] as u64;
if s as f64 > thresh {
// is like 84th percentile
i_c = i;
break;
}
}
// make hand-wavey value using the above to represent 'bias'
let a = math::map(i_a as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let b = math::map(i_b as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
let c = math::map(i_c as f64, lower as f64, (upper - 1) as f64, -1.0, 1.0);
return (a + b + c) / 3.0;
}
}
|
{
lower_index = if i <= 1 {
0 as usize
} else {
i - 1 // rewind by 1
};
break;
}
|
conditional_block
|
lib.rs
|
#![feature(test, i128_type)]
extern crate test;
use test::Bencher;
extern crate rand;
extern crate speck;
use rand::Rng;
use rand::OsRng;
use speck::Key;
#[bench]
fn generate_key(mut bencher: &mut Bencher) {
let mut rng = OsRng::new().unwrap();
let key_input = rng.gen();
bencher.iter(|| test::black_box(Key::new(key_input)));
}
#[bench]
fn encrypt(mut bencher: &mut Bencher) {
let (key, block) = gen_test();
bencher.iter(|| test::black_box(key.encrypt_block(block)));
}
#[bench]
fn decrypt(mut bencher: &mut Bencher) {
let (key, block) = gen_test();
bencher.iter(|| test::black_box(key.decrypt_block(block)));
}
fn gen_test() -> (Key, u128)
|
{
let mut rng = OsRng::new().unwrap();
(Key::new(rng.gen()), rng.gen())
}
|
identifier_body
|
|
lib.rs
|
#![feature(test, i128_type)]
extern crate test;
use test::Bencher;
extern crate rand;
extern crate speck;
use rand::Rng;
use rand::OsRng;
use speck::Key;
#[bench]
fn generate_key(mut bencher: &mut Bencher) {
let mut rng = OsRng::new().unwrap();
let key_input = rng.gen();
bencher.iter(|| test::black_box(Key::new(key_input)));
}
#[bench]
fn
|
(mut bencher: &mut Bencher) {
let (key, block) = gen_test();
bencher.iter(|| test::black_box(key.encrypt_block(block)));
}
#[bench]
fn decrypt(mut bencher: &mut Bencher) {
let (key, block) = gen_test();
bencher.iter(|| test::black_box(key.decrypt_block(block)));
}
fn gen_test() -> (Key, u128) {
let mut rng = OsRng::new().unwrap();
(Key::new(rng.gen()), rng.gen())
}
|
encrypt
|
identifier_name
|
lib.rs
|
#![feature(test, i128_type)]
extern crate test;
use test::Bencher;
extern crate rand;
extern crate speck;
use rand::Rng;
use rand::OsRng;
|
#[bench]
fn generate_key(mut bencher: &mut Bencher) {
let mut rng = OsRng::new().unwrap();
let key_input = rng.gen();
bencher.iter(|| test::black_box(Key::new(key_input)));
}
#[bench]
fn encrypt(mut bencher: &mut Bencher) {
let (key, block) = gen_test();
bencher.iter(|| test::black_box(key.encrypt_block(block)));
}
#[bench]
fn decrypt(mut bencher: &mut Bencher) {
let (key, block) = gen_test();
bencher.iter(|| test::black_box(key.decrypt_block(block)));
}
fn gen_test() -> (Key, u128) {
let mut rng = OsRng::new().unwrap();
(Key::new(rng.gen()), rng.gen())
}
|
use speck::Key;
|
random_line_split
|
base.rs
|
token_tree: &[ast::TokenTree])
-> ~MacResult {
(self.expander)(ecx, span, token_tree)
}
}
pub struct BasicIdentMacroExpander {
pub expander: IdentMacroExpanderFn,
pub span: Option<Span>
}
pub trait IdentMacroExpander {
fn expand(&self,
cx: &mut ExtCtxt,
sp: Span,
ident: ast::Ident,
token_tree: Vec<ast::TokenTree> )
-> ~MacResult;
}
impl IdentMacroExpander for BasicIdentMacroExpander {
fn expand(&self,
cx: &mut ExtCtxt,
sp: Span,
ident: ast::Ident,
token_tree: Vec<ast::TokenTree> )
-> ~MacResult {
(self.expander)(cx, sp, ident, token_tree)
}
}
pub type IdentMacroExpanderFn =
fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree> ) -> ~MacResult;
pub type MacroCrateRegistrationFun =
fn(|ast::Name, SyntaxExtension|);
/// The result of a macro expansion. The return values of the various
/// methods are spliced into the AST at the callsite of the macro (or
/// just into the compiler's internal macro table, for `make_def`).
pub trait MacResult {
/// Define a new macro.
fn make_def(&self) -> Option<MacroDef> {
None
}
/// Create an expression.
fn make_expr(&self) -> Option<@ast::Expr> {
None
}
/// Create zero or more items.
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
None
}
/// Create a statement.
///
/// By default this attempts to create an expression statement,
/// returning None if that fails.
fn make_stmt(&self) -> Option<@ast::Stmt> {
self.make_expr()
.map(|e| @codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID)))
}
}
/// A convenience type for macros that return a single expression.
pub struct MacExpr {
e: @ast::Expr
}
impl MacExpr {
pub fn new(e: @ast::Expr) -> ~MacResult {
~MacExpr { e: e } as ~MacResult
}
}
impl MacResult for MacExpr {
fn make_expr(&self) -> Option<@ast::Expr> {
Some(self.e)
}
}
/// A convenience type for macros that return a single item.
pub struct MacItem {
i: @ast::Item
}
impl MacItem {
pub fn new(i: @ast::Item) -> ~MacResult {
~MacItem { i: i } as ~MacResult
}
}
impl MacResult for MacItem {
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
Some(SmallVector::one(self.i))
}
fn make_stmt(&self) -> Option<@ast::Stmt> {
Some(@codemap::respan(
self.i.span,
ast::StmtDecl(
@codemap::respan(self.i.span, ast::DeclItem(self.i)),
ast::DUMMY_NODE_ID)))
}
}
/// Fill-in macro expansion result, to allow compilation to continue
/// after hitting errors.
pub struct DummyResult {
expr_only: bool,
span: Span
}
impl DummyResult {
/// Create a default MacResult that can be anything.
///
/// Use this as a return value after hitting any errors and
/// calling `span_err`.
pub fn any(sp: Span) -> ~MacResult {
~DummyResult { expr_only: false, span: sp } as ~MacResult
}
/// Create a default MacResult that can only be an expression.
///
/// Use this for macros that must expand to an expression, so even
/// if an error is encountered internally, the user will recieve
/// an error that they also used it in the wrong place.
pub fn expr(sp: Span) -> ~MacResult {
~DummyResult { expr_only: true, span: sp } as ~MacResult
}
/// A plain dummy expression.
pub fn raw_expr(sp: Span) -> @ast::Expr {
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)),
span: sp,
}
}
}
impl MacResult for DummyResult {
fn make_expr(&self) -> Option<@ast::Expr> {
Some(DummyResult::raw_expr(self.span))
}
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
if self.expr_only {
None
} else {
Some(SmallVector::zero())
}
}
fn make_stmt(&self) -> Option<@ast::Stmt> {
Some(@codemap::respan(self.span,
ast::StmtExpr(DummyResult::raw_expr(self.span),
ast::DUMMY_NODE_ID)))
}
}
/// An enum representing the different kinds of syntax extensions.
pub enum SyntaxExtension {
|
/// A syntax extension that is attached to an item and modifies it
/// in-place.
ItemModifier(ItemModifier),
/// A normal, function-like syntax extension.
///
/// `bytes!` is a `NormalTT`.
NormalTT(~MacroExpander:'static, Option<Span>),
/// A function-like syntax extension that has an extra ident before
/// the block.
///
/// `macro_rules!` is an `IdentTT`.
IdentTT(~IdentMacroExpander:'static, Option<Span>),
}
pub struct BlockInfo {
// should macros escape from this scope?
pub macros_escape: bool,
// what are the pending renames?
pub pending_renames: RenameList,
}
impl BlockInfo {
pub fn new() -> BlockInfo {
BlockInfo {
macros_escape: false,
pending_renames: Vec::new(),
}
}
}
// a list of ident->name renamings
pub type RenameList = Vec<(ast::Ident, Name)>;
// The base map of methods for expanding syntax extension
// AST nodes into full ASTs
pub fn syntax_expander_table() -> SyntaxEnv {
// utility function to simplify creating NormalTT syntax extensions
fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
NormalTT(~BasicMacroExpander {
expander: f,
span: None,
},
None)
}
let mut syntax_expanders = SyntaxEnv::new();
syntax_expanders.insert(intern(&"macro_rules"),
IdentTT(~BasicIdentMacroExpander {
expander: ext::tt::macro_rules::add_new_extension,
span: None,
},
None));
syntax_expanders.insert(intern(&"fmt"),
builtin_normal_expander(
ext::fmt::expand_syntax_ext));
syntax_expanders.insert(intern(&"format_args"),
builtin_normal_expander(
ext::format::expand_args));
syntax_expanders.insert(intern(&"env"),
builtin_normal_expander(
ext::env::expand_env));
syntax_expanders.insert(intern(&"option_env"),
builtin_normal_expander(
ext::env::expand_option_env));
syntax_expanders.insert(intern("bytes"),
builtin_normal_expander(
ext::bytes::expand_syntax_ext));
syntax_expanders.insert(intern("concat_idents"),
builtin_normal_expander(
ext::concat_idents::expand_syntax_ext));
syntax_expanders.insert(intern("concat"),
builtin_normal_expander(
ext::concat::expand_syntax_ext));
syntax_expanders.insert(intern(&"log_syntax"),
builtin_normal_expander(
ext::log_syntax::expand_syntax_ext));
syntax_expanders.insert(intern(&"deriving"),
ItemDecorator(ext::deriving::expand_meta_deriving));
// Quasi-quoting expanders
syntax_expanders.insert(intern(&"quote_tokens"),
builtin_normal_expander(
ext::quote::expand_quote_tokens));
syntax_expanders.insert(intern(&"quote_expr"),
builtin_normal_expander(
ext::quote::expand_quote_expr));
syntax_expanders.insert(intern(&"quote_ty"),
builtin_normal_expander(
ext::quote::expand_quote_ty));
syntax_expanders.insert(intern(&"quote_item"),
builtin_normal_expander(
ext::quote::expand_quote_item));
syntax_expanders.insert(intern(&"quote_pat"),
builtin_normal_expander(
ext::quote::expand_quote_pat));
syntax_expanders.insert(intern(&"quote_stmt"),
builtin_normal_expander(
ext::quote::expand_quote_stmt));
syntax_expanders.insert(intern(&"line"),
builtin_normal_expander(
ext::source_util::expand_line));
syntax_expanders.insert(intern(&"col"),
builtin_normal_expander(
ext::source_util::expand_col));
syntax_expanders.insert(intern(&"file"),
builtin_normal_expander(
ext::source_util::expand_file));
syntax_expanders.insert(intern(&"stringify"),
builtin_normal_expander(
ext::source_util::expand_stringify));
syntax_expanders.insert(intern(&"include"),
builtin_normal_expander(
ext::source_util::expand_include));
syntax_expanders.insert(intern(&"include_str"),
builtin_normal_expander(
ext::source_util::expand_include_str));
syntax_expanders.insert(intern(&"include_bin"),
builtin_normal_expander(
ext::source_util::expand_include_bin));
syntax_expanders.insert(intern(&"module_path"),
builtin_normal_expander(
ext::source_util::expand_mod));
syntax_expanders.insert(intern(&"asm"),
builtin_normal_expander(
ext::asm::expand_asm));
syntax_expanders.insert(intern(&"cfg"),
builtin_normal_expander(
ext::cfg::expand_cfg));
syntax_expanders.insert(intern(&"trace_macros"),
builtin_normal_expander(
ext::trace_macros::expand_trace_macros));
syntax_expanders
}
pub struct MacroCrate {
pub lib: Option<Path>,
pub macros: Vec<~str>,
pub registrar_symbol: Option<~str>,
}
pub trait CrateLoader {
fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate;
}
// One of these is made during expansion and incrementally updated as we go;
// when a macro expansion occurs, the resulting nodes have the backtrace()
// -> expn_info of their expansion context stored into their span.
pub struct ExtCtxt<'a> {
pub parse_sess: &'a parse::ParseSess,
pub cfg: ast::CrateConfig,
pub backtrace: Option<@ExpnInfo>,
pub ecfg: expand::ExpansionConfig<'a>,
pub mod_path: Vec<ast::Ident>,
pub trace_mac: bool,
}
impl<'a> ExtCtxt<'a> {
pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
ecfg: expand::ExpansionConfig<'a>) -> ExtCtxt<'a> {
ExtCtxt {
parse_sess: parse_sess,
cfg: cfg,
backtrace: None,
mod_path: Vec::new(),
ecfg: ecfg,
trace_mac: false
}
}
pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
loop {
match e.node {
ast::ExprMac(..) => {
let mut expander = expand::MacroExpander {
extsbox: syntax_expander_table(),
cx: self,
};
e = expand::expand_expr(e, &mut expander);
}
_ => return e
}
}
}
pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
pub fn call_site(&self) -> Span {
match self.backtrace {
Some(expn_info) => expn_info.call_site,
None => self.bug("missing top span")
}
}
pub fn print_backtrace(&self) { }
pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace }
pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
pub fn mod_path(&self) -> Vec<ast::Ident> {
let mut v = Vec::new();
v.push(token::str_to_ident(self.ecfg.crate_id.name));
v.extend(self.mod_path.iter().map(|a| *a));
return v;
}
pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
match ei {
ExpnInfo {call_site: cs, callee: ref callee} => {
self.backtrace =
Some(@ExpnInfo {
call_site: Span {lo: cs.lo, hi: cs.hi,
expn_info: self.backtrace},
callee: (*callee).clone()
});
}
}
}
pub fn bt_pop(&mut self) {
match self.backtrace {
Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
_ => self.bug("tried to pop without a push")
}
}
/// Emit `msg` attached to `sp`, and stop compilation immediately.
///
/// `span_err` should be strongly prefered where-ever possible:
/// this should *only* be used when
/// - continuing has a high risk of flow-on errors (e.g. errors in
/// declaring a macro would cause all uses of that macro to
/// complain about "undefined macro"), or
/// - there is literally nothing else that can be done (however,
/// in most cases one can construct a dummy expression/item to
/// substitute; we never hit resolve/type-checking so the dummy
/// value doesn't have to match anything)
pub fn span_fatal(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_fatal(sp, msg);
}
/// Emit `msg` attached to `sp`, without immediately stopping
/// compilation.
///
/// Compilation will be stopped in the near future (at the end of
/// the macro expansion phase).
pub fn span_err(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_err(sp, msg);
}
pub fn span_warn(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_warn(sp, msg);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
}
pub fn span_bug(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_bug(sp, msg);
}
pub fn span_note(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_note(sp, msg);
}
pub fn bug(&self, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.handler().bug(msg);
}
pub fn trace_macros(&self) -> bool {
self.trace_mac
}
pub fn set_trace_macros(&mut self, x: bool) {
self.trace_mac = x
}
pub fn ident_of(&self, st: &str) -> ast::Ident {
str_to_ident(st)
}
}
/// Extract a string literal from the macro expanded version of `expr`,
/// emitting `err_msg` if `expr` is not a string literal. This does not stop
/// compilation on error, merely emits a non-fatal error and returns None.
pub fn expr_to_str(cx: &mut ExtCtxt, expr: @ast::Expr, err_msg: &str)
-> Option<(InternedString, ast::StrStyle)> {
// we want to be able to handle e.g. concat("foo", "bar")
let expr = cx.expand_expr(expr);
match expr.node {
ast::ExprLit(l) => match l.node {
ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
_ => cx.span_err(l.span, err_msg)
},
_ => cx.span_err(expr.span, err_msg)
}
None
}
/// Non-fatally assert that `tts` is empty. Note that this function
/// returns even when `tts` is non-empty, macros that *need* to stop
/// compilation should call
/// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
/// done as rarely as possible).
pub fn check_zero_tts(cx: &ExtCtxt,
sp: Span,
tts: &[ast::TokenTree],
name: &str) {
if tts.len()!= 0 {
cx.span_err(sp, format!("{} takes no arguments", name));
}
}
/// Extract the string literal from the first token of `tts`. If this
/// is not a string literal, emit an error and return None.
pub fn get_single_str_from_tts(cx: &ExtCtxt,
sp: Span,
tts: &[ast::TokenTree],
name: &str)
-> Option<~str> {
if tts.len()!= 1 {
cx.span_err(sp, format!("{} takes 1 argument.", name));
} else {
match tts[0] {
ast::TTTok(_, token::LIT_STR(ident))
|
/// A syntax extension that is attached to an item and creates new items
/// based upon it.
///
/// `#[deriving(...)]` is an `ItemDecorator`.
ItemDecorator(ItemDecorator),
|
random_line_split
|
base.rs
|
token_tree: &[ast::TokenTree])
-> ~MacResult {
(self.expander)(ecx, span, token_tree)
}
}
pub struct BasicIdentMacroExpander {
pub expander: IdentMacroExpanderFn,
pub span: Option<Span>
}
pub trait IdentMacroExpander {
fn expand(&self,
cx: &mut ExtCtxt,
sp: Span,
ident: ast::Ident,
token_tree: Vec<ast::TokenTree> )
-> ~MacResult;
}
impl IdentMacroExpander for BasicIdentMacroExpander {
fn expand(&self,
cx: &mut ExtCtxt,
sp: Span,
ident: ast::Ident,
token_tree: Vec<ast::TokenTree> )
-> ~MacResult {
(self.expander)(cx, sp, ident, token_tree)
}
}
pub type IdentMacroExpanderFn =
fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree> ) -> ~MacResult;
pub type MacroCrateRegistrationFun =
fn(|ast::Name, SyntaxExtension|);
/// The result of a macro expansion. The return values of the various
/// methods are spliced into the AST at the callsite of the macro (or
/// just into the compiler's internal macro table, for `make_def`).
pub trait MacResult {
/// Define a new macro.
fn make_def(&self) -> Option<MacroDef> {
None
}
/// Create an expression.
fn make_expr(&self) -> Option<@ast::Expr> {
None
}
/// Create zero or more items.
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
None
}
/// Create a statement.
///
/// By default this attempts to create an expression statement,
/// returning None if that fails.
fn make_stmt(&self) -> Option<@ast::Stmt> {
self.make_expr()
.map(|e| @codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID)))
}
}
/// A convenience type for macros that return a single expression.
pub struct MacExpr {
e: @ast::Expr
}
impl MacExpr {
pub fn new(e: @ast::Expr) -> ~MacResult {
~MacExpr { e: e } as ~MacResult
}
}
impl MacResult for MacExpr {
fn make_expr(&self) -> Option<@ast::Expr> {
Some(self.e)
}
}
/// A convenience type for macros that return a single item.
pub struct MacItem {
i: @ast::Item
}
impl MacItem {
pub fn new(i: @ast::Item) -> ~MacResult {
~MacItem { i: i } as ~MacResult
}
}
impl MacResult for MacItem {
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
Some(SmallVector::one(self.i))
}
fn make_stmt(&self) -> Option<@ast::Stmt> {
Some(@codemap::respan(
self.i.span,
ast::StmtDecl(
@codemap::respan(self.i.span, ast::DeclItem(self.i)),
ast::DUMMY_NODE_ID)))
}
}
/// Fill-in macro expansion result, to allow compilation to continue
/// after hitting errors.
pub struct DummyResult {
expr_only: bool,
span: Span
}
impl DummyResult {
/// Create a default MacResult that can be anything.
///
/// Use this as a return value after hitting any errors and
/// calling `span_err`.
pub fn any(sp: Span) -> ~MacResult {
~DummyResult { expr_only: false, span: sp } as ~MacResult
}
/// Create a default MacResult that can only be an expression.
///
/// Use this for macros that must expand to an expression, so even
/// if an error is encountered internally, the user will recieve
/// an error that they also used it in the wrong place.
pub fn expr(sp: Span) -> ~MacResult {
~DummyResult { expr_only: true, span: sp } as ~MacResult
}
/// A plain dummy expression.
pub fn raw_expr(sp: Span) -> @ast::Expr {
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)),
span: sp,
}
}
}
impl MacResult for DummyResult {
fn make_expr(&self) -> Option<@ast::Expr> {
Some(DummyResult::raw_expr(self.span))
}
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
if self.expr_only {
None
} else {
Some(SmallVector::zero())
}
}
fn make_stmt(&self) -> Option<@ast::Stmt> {
Some(@codemap::respan(self.span,
ast::StmtExpr(DummyResult::raw_expr(self.span),
ast::DUMMY_NODE_ID)))
}
}
/// An enum representing the different kinds of syntax extensions.
pub enum SyntaxExtension {
/// A syntax extension that is attached to an item and creates new items
/// based upon it.
///
/// `#[deriving(...)]` is an `ItemDecorator`.
ItemDecorator(ItemDecorator),
/// A syntax extension that is attached to an item and modifies it
/// in-place.
ItemModifier(ItemModifier),
/// A normal, function-like syntax extension.
///
/// `bytes!` is a `NormalTT`.
NormalTT(~MacroExpander:'static, Option<Span>),
/// A function-like syntax extension that has an extra ident before
/// the block.
///
/// `macro_rules!` is an `IdentTT`.
IdentTT(~IdentMacroExpander:'static, Option<Span>),
}
pub struct BlockInfo {
// should macros escape from this scope?
pub macros_escape: bool,
// what are the pending renames?
pub pending_renames: RenameList,
}
impl BlockInfo {
pub fn new() -> BlockInfo {
BlockInfo {
macros_escape: false,
pending_renames: Vec::new(),
}
}
}
// a list of ident->name renamings
pub type RenameList = Vec<(ast::Ident, Name)>;
// The base map of methods for expanding syntax extension
// AST nodes into full ASTs
pub fn syntax_expander_table() -> SyntaxEnv {
// utility function to simplify creating NormalTT syntax extensions
fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
NormalTT(~BasicMacroExpander {
expander: f,
span: None,
},
None)
}
let mut syntax_expanders = SyntaxEnv::new();
syntax_expanders.insert(intern(&"macro_rules"),
IdentTT(~BasicIdentMacroExpander {
expander: ext::tt::macro_rules::add_new_extension,
span: None,
},
None));
syntax_expanders.insert(intern(&"fmt"),
builtin_normal_expander(
ext::fmt::expand_syntax_ext));
syntax_expanders.insert(intern(&"format_args"),
builtin_normal_expander(
ext::format::expand_args));
syntax_expanders.insert(intern(&"env"),
builtin_normal_expander(
ext::env::expand_env));
syntax_expanders.insert(intern(&"option_env"),
builtin_normal_expander(
ext::env::expand_option_env));
syntax_expanders.insert(intern("bytes"),
builtin_normal_expander(
ext::bytes::expand_syntax_ext));
syntax_expanders.insert(intern("concat_idents"),
builtin_normal_expander(
ext::concat_idents::expand_syntax_ext));
syntax_expanders.insert(intern("concat"),
builtin_normal_expander(
ext::concat::expand_syntax_ext));
syntax_expanders.insert(intern(&"log_syntax"),
builtin_normal_expander(
ext::log_syntax::expand_syntax_ext));
syntax_expanders.insert(intern(&"deriving"),
ItemDecorator(ext::deriving::expand_meta_deriving));
// Quasi-quoting expanders
syntax_expanders.insert(intern(&"quote_tokens"),
builtin_normal_expander(
ext::quote::expand_quote_tokens));
syntax_expanders.insert(intern(&"quote_expr"),
builtin_normal_expander(
ext::quote::expand_quote_expr));
syntax_expanders.insert(intern(&"quote_ty"),
builtin_normal_expander(
ext::quote::expand_quote_ty));
syntax_expanders.insert(intern(&"quote_item"),
builtin_normal_expander(
ext::quote::expand_quote_item));
syntax_expanders.insert(intern(&"quote_pat"),
builtin_normal_expander(
ext::quote::expand_quote_pat));
syntax_expanders.insert(intern(&"quote_stmt"),
builtin_normal_expander(
ext::quote::expand_quote_stmt));
syntax_expanders.insert(intern(&"line"),
builtin_normal_expander(
ext::source_util::expand_line));
syntax_expanders.insert(intern(&"col"),
builtin_normal_expander(
ext::source_util::expand_col));
syntax_expanders.insert(intern(&"file"),
builtin_normal_expander(
ext::source_util::expand_file));
syntax_expanders.insert(intern(&"stringify"),
builtin_normal_expander(
ext::source_util::expand_stringify));
syntax_expanders.insert(intern(&"include"),
builtin_normal_expander(
ext::source_util::expand_include));
syntax_expanders.insert(intern(&"include_str"),
builtin_normal_expander(
ext::source_util::expand_include_str));
syntax_expanders.insert(intern(&"include_bin"),
builtin_normal_expander(
ext::source_util::expand_include_bin));
syntax_expanders.insert(intern(&"module_path"),
builtin_normal_expander(
ext::source_util::expand_mod));
syntax_expanders.insert(intern(&"asm"),
builtin_normal_expander(
ext::asm::expand_asm));
syntax_expanders.insert(intern(&"cfg"),
builtin_normal_expander(
ext::cfg::expand_cfg));
syntax_expanders.insert(intern(&"trace_macros"),
builtin_normal_expander(
ext::trace_macros::expand_trace_macros));
syntax_expanders
}
pub struct MacroCrate {
pub lib: Option<Path>,
pub macros: Vec<~str>,
pub registrar_symbol: Option<~str>,
}
pub trait CrateLoader {
fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate;
}
// One of these is made during expansion and incrementally updated as we go;
// when a macro expansion occurs, the resulting nodes have the backtrace()
// -> expn_info of their expansion context stored into their span.
pub struct ExtCtxt<'a> {
pub parse_sess: &'a parse::ParseSess,
pub cfg: ast::CrateConfig,
pub backtrace: Option<@ExpnInfo>,
pub ecfg: expand::ExpansionConfig<'a>,
pub mod_path: Vec<ast::Ident>,
pub trace_mac: bool,
}
impl<'a> ExtCtxt<'a> {
pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
ecfg: expand::ExpansionConfig<'a>) -> ExtCtxt<'a> {
ExtCtxt {
parse_sess: parse_sess,
cfg: cfg,
backtrace: None,
mod_path: Vec::new(),
ecfg: ecfg,
trace_mac: false
}
}
pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
loop {
match e.node {
ast::ExprMac(..) => {
let mut expander = expand::MacroExpander {
extsbox: syntax_expander_table(),
cx: self,
};
e = expand::expand_expr(e, &mut expander);
}
_ => return e
}
}
}
pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
pub fn call_site(&self) -> Span {
match self.backtrace {
Some(expn_info) => expn_info.call_site,
None => self.bug("missing top span")
}
}
pub fn print_backtrace(&self) { }
pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace }
pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
pub fn mod_path(&self) -> Vec<ast::Ident>
|
pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
match ei {
ExpnInfo {call_site: cs, callee: ref callee} => {
self.backtrace =
Some(@ExpnInfo {
call_site: Span {lo: cs.lo, hi: cs.hi,
expn_info: self.backtrace},
callee: (*callee).clone()
});
}
}
}
pub fn bt_pop(&mut self) {
match self.backtrace {
Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
_ => self.bug("tried to pop without a push")
}
}
/// Emit `msg` attached to `sp`, and stop compilation immediately.
///
/// `span_err` should be strongly prefered where-ever possible:
/// this should *only* be used when
/// - continuing has a high risk of flow-on errors (e.g. errors in
/// declaring a macro would cause all uses of that macro to
/// complain about "undefined macro"), or
/// - there is literally nothing else that can be done (however,
/// in most cases one can construct a dummy expression/item to
/// substitute; we never hit resolve/type-checking so the dummy
/// value doesn't have to match anything)
pub fn span_fatal(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_fatal(sp, msg);
}
/// Emit `msg` attached to `sp`, without immediately stopping
/// compilation.
///
/// Compilation will be stopped in the near future (at the end of
/// the macro expansion phase).
pub fn span_err(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_err(sp, msg);
}
pub fn span_warn(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_warn(sp, msg);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
}
pub fn span_bug(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_bug(sp, msg);
}
pub fn span_note(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_note(sp, msg);
}
pub fn bug(&self, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.handler().bug(msg);
}
pub fn trace_macros(&self) -> bool {
self.trace_mac
}
pub fn set_trace_macros(&mut self, x: bool) {
self.trace_mac = x
}
pub fn ident_of(&self, st: &str) -> ast::Ident {
str_to_ident(st)
}
}
/// Extract a string literal from the macro expanded version of `expr`,
/// emitting `err_msg` if `expr` is not a string literal. This does not stop
/// compilation on error, merely emits a non-fatal error and returns None.
pub fn expr_to_str(cx: &mut ExtCtxt, expr: @ast::Expr, err_msg: &str)
-> Option<(InternedString, ast::StrStyle)> {
// we want to be able to handle e.g. concat("foo", "bar")
let expr = cx.expand_expr(expr);
match expr.node {
ast::ExprLit(l) => match l.node {
ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
_ => cx.span_err(l.span, err_msg)
},
_ => cx.span_err(expr.span, err_msg)
}
None
}
/// Non-fatally assert that `tts` is empty. Note that this function
/// returns even when `tts` is non-empty, macros that *need* to stop
/// compilation should call
/// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
/// done as rarely as possible).
pub fn check_zero_tts(cx: &ExtCtxt,
sp: Span,
tts: &[ast::TokenTree],
name: &str) {
if tts.len()!= 0 {
cx.span_err(sp, format!("{} takes no arguments", name));
}
}
/// Extract the string literal from the first token of `tts`. If this
/// is not a string literal, emit an error and return None.
pub fn get_single_str_from_tts(cx: &ExtCtxt,
sp: Span,
tts: &[ast::TokenTree],
name: &str)
-> Option<~str> {
if tts.len()!= 1 {
cx.span_err(sp, format!("{} takes 1 argument.", name));
} else {
match tts[0] {
ast::TTTok(_, token::LIT_STR(ident))
|
{
let mut v = Vec::new();
v.push(token::str_to_ident(self.ecfg.crate_id.name));
v.extend(self.mod_path.iter().map(|a| *a));
return v;
}
|
identifier_body
|
base.rs
|
token_tree: &[ast::TokenTree])
-> ~MacResult {
(self.expander)(ecx, span, token_tree)
}
}
pub struct BasicIdentMacroExpander {
pub expander: IdentMacroExpanderFn,
pub span: Option<Span>
}
pub trait IdentMacroExpander {
fn expand(&self,
cx: &mut ExtCtxt,
sp: Span,
ident: ast::Ident,
token_tree: Vec<ast::TokenTree> )
-> ~MacResult;
}
impl IdentMacroExpander for BasicIdentMacroExpander {
fn expand(&self,
cx: &mut ExtCtxt,
sp: Span,
ident: ast::Ident,
token_tree: Vec<ast::TokenTree> )
-> ~MacResult {
(self.expander)(cx, sp, ident, token_tree)
}
}
pub type IdentMacroExpanderFn =
fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree> ) -> ~MacResult;
pub type MacroCrateRegistrationFun =
fn(|ast::Name, SyntaxExtension|);
/// The result of a macro expansion. The return values of the various
/// methods are spliced into the AST at the callsite of the macro (or
/// just into the compiler's internal macro table, for `make_def`).
pub trait MacResult {
/// Define a new macro.
fn make_def(&self) -> Option<MacroDef> {
None
}
/// Create an expression.
fn make_expr(&self) -> Option<@ast::Expr> {
None
}
/// Create zero or more items.
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
None
}
/// Create a statement.
///
/// By default this attempts to create an expression statement,
/// returning None if that fails.
fn make_stmt(&self) -> Option<@ast::Stmt> {
self.make_expr()
.map(|e| @codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID)))
}
}
/// A convenience type for macros that return a single expression.
pub struct MacExpr {
e: @ast::Expr
}
impl MacExpr {
pub fn new(e: @ast::Expr) -> ~MacResult {
~MacExpr { e: e } as ~MacResult
}
}
impl MacResult for MacExpr {
fn make_expr(&self) -> Option<@ast::Expr> {
Some(self.e)
}
}
/// A convenience type for macros that return a single item.
pub struct MacItem {
i: @ast::Item
}
impl MacItem {
pub fn new(i: @ast::Item) -> ~MacResult {
~MacItem { i: i } as ~MacResult
}
}
impl MacResult for MacItem {
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
Some(SmallVector::one(self.i))
}
fn make_stmt(&self) -> Option<@ast::Stmt> {
Some(@codemap::respan(
self.i.span,
ast::StmtDecl(
@codemap::respan(self.i.span, ast::DeclItem(self.i)),
ast::DUMMY_NODE_ID)))
}
}
/// Fill-in macro expansion result, to allow compilation to continue
/// after hitting errors.
pub struct DummyResult {
expr_only: bool,
span: Span
}
impl DummyResult {
/// Create a default MacResult that can be anything.
///
/// Use this as a return value after hitting any errors and
/// calling `span_err`.
pub fn any(sp: Span) -> ~MacResult {
~DummyResult { expr_only: false, span: sp } as ~MacResult
}
/// Create a default MacResult that can only be an expression.
///
/// Use this for macros that must expand to an expression, so even
/// if an error is encountered internally, the user will recieve
/// an error that they also used it in the wrong place.
pub fn expr(sp: Span) -> ~MacResult {
~DummyResult { expr_only: true, span: sp } as ~MacResult
}
/// A plain dummy expression.
pub fn raw_expr(sp: Span) -> @ast::Expr {
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)),
span: sp,
}
}
}
impl MacResult for DummyResult {
fn make_expr(&self) -> Option<@ast::Expr> {
Some(DummyResult::raw_expr(self.span))
}
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
if self.expr_only {
None
} else {
Some(SmallVector::zero())
}
}
fn make_stmt(&self) -> Option<@ast::Stmt> {
Some(@codemap::respan(self.span,
ast::StmtExpr(DummyResult::raw_expr(self.span),
ast::DUMMY_NODE_ID)))
}
}
/// An enum representing the different kinds of syntax extensions.
pub enum SyntaxExtension {
/// A syntax extension that is attached to an item and creates new items
/// based upon it.
///
/// `#[deriving(...)]` is an `ItemDecorator`.
ItemDecorator(ItemDecorator),
/// A syntax extension that is attached to an item and modifies it
/// in-place.
ItemModifier(ItemModifier),
/// A normal, function-like syntax extension.
///
/// `bytes!` is a `NormalTT`.
NormalTT(~MacroExpander:'static, Option<Span>),
/// A function-like syntax extension that has an extra ident before
/// the block.
///
/// `macro_rules!` is an `IdentTT`.
IdentTT(~IdentMacroExpander:'static, Option<Span>),
}
pub struct BlockInfo {
// should macros escape from this scope?
pub macros_escape: bool,
// what are the pending renames?
pub pending_renames: RenameList,
}
impl BlockInfo {
pub fn new() -> BlockInfo {
BlockInfo {
macros_escape: false,
pending_renames: Vec::new(),
}
}
}
// a list of ident->name renamings
pub type RenameList = Vec<(ast::Ident, Name)>;
// The base map of methods for expanding syntax extension
// AST nodes into full ASTs
pub fn syntax_expander_table() -> SyntaxEnv {
// utility function to simplify creating NormalTT syntax extensions
fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
NormalTT(~BasicMacroExpander {
expander: f,
span: None,
},
None)
}
let mut syntax_expanders = SyntaxEnv::new();
syntax_expanders.insert(intern(&"macro_rules"),
IdentTT(~BasicIdentMacroExpander {
expander: ext::tt::macro_rules::add_new_extension,
span: None,
},
None));
syntax_expanders.insert(intern(&"fmt"),
builtin_normal_expander(
ext::fmt::expand_syntax_ext));
syntax_expanders.insert(intern(&"format_args"),
builtin_normal_expander(
ext::format::expand_args));
syntax_expanders.insert(intern(&"env"),
builtin_normal_expander(
ext::env::expand_env));
syntax_expanders.insert(intern(&"option_env"),
builtin_normal_expander(
ext::env::expand_option_env));
syntax_expanders.insert(intern("bytes"),
builtin_normal_expander(
ext::bytes::expand_syntax_ext));
syntax_expanders.insert(intern("concat_idents"),
builtin_normal_expander(
ext::concat_idents::expand_syntax_ext));
syntax_expanders.insert(intern("concat"),
builtin_normal_expander(
ext::concat::expand_syntax_ext));
syntax_expanders.insert(intern(&"log_syntax"),
builtin_normal_expander(
ext::log_syntax::expand_syntax_ext));
syntax_expanders.insert(intern(&"deriving"),
ItemDecorator(ext::deriving::expand_meta_deriving));
// Quasi-quoting expanders
syntax_expanders.insert(intern(&"quote_tokens"),
builtin_normal_expander(
ext::quote::expand_quote_tokens));
syntax_expanders.insert(intern(&"quote_expr"),
builtin_normal_expander(
ext::quote::expand_quote_expr));
syntax_expanders.insert(intern(&"quote_ty"),
builtin_normal_expander(
ext::quote::expand_quote_ty));
syntax_expanders.insert(intern(&"quote_item"),
builtin_normal_expander(
ext::quote::expand_quote_item));
syntax_expanders.insert(intern(&"quote_pat"),
builtin_normal_expander(
ext::quote::expand_quote_pat));
syntax_expanders.insert(intern(&"quote_stmt"),
builtin_normal_expander(
ext::quote::expand_quote_stmt));
syntax_expanders.insert(intern(&"line"),
builtin_normal_expander(
ext::source_util::expand_line));
syntax_expanders.insert(intern(&"col"),
builtin_normal_expander(
ext::source_util::expand_col));
syntax_expanders.insert(intern(&"file"),
builtin_normal_expander(
ext::source_util::expand_file));
syntax_expanders.insert(intern(&"stringify"),
builtin_normal_expander(
ext::source_util::expand_stringify));
syntax_expanders.insert(intern(&"include"),
builtin_normal_expander(
ext::source_util::expand_include));
syntax_expanders.insert(intern(&"include_str"),
builtin_normal_expander(
ext::source_util::expand_include_str));
syntax_expanders.insert(intern(&"include_bin"),
builtin_normal_expander(
ext::source_util::expand_include_bin));
syntax_expanders.insert(intern(&"module_path"),
builtin_normal_expander(
ext::source_util::expand_mod));
syntax_expanders.insert(intern(&"asm"),
builtin_normal_expander(
ext::asm::expand_asm));
syntax_expanders.insert(intern(&"cfg"),
builtin_normal_expander(
ext::cfg::expand_cfg));
syntax_expanders.insert(intern(&"trace_macros"),
builtin_normal_expander(
ext::trace_macros::expand_trace_macros));
syntax_expanders
}
pub struct MacroCrate {
pub lib: Option<Path>,
pub macros: Vec<~str>,
pub registrar_symbol: Option<~str>,
}
pub trait CrateLoader {
fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate;
}
// One of these is made during expansion and incrementally updated as we go;
// when a macro expansion occurs, the resulting nodes have the backtrace()
// -> expn_info of their expansion context stored into their span.
pub struct ExtCtxt<'a> {
pub parse_sess: &'a parse::ParseSess,
pub cfg: ast::CrateConfig,
pub backtrace: Option<@ExpnInfo>,
pub ecfg: expand::ExpansionConfig<'a>,
pub mod_path: Vec<ast::Ident>,
pub trace_mac: bool,
}
impl<'a> ExtCtxt<'a> {
pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
ecfg: expand::ExpansionConfig<'a>) -> ExtCtxt<'a> {
ExtCtxt {
parse_sess: parse_sess,
cfg: cfg,
backtrace: None,
mod_path: Vec::new(),
ecfg: ecfg,
trace_mac: false
}
}
pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
loop {
match e.node {
ast::ExprMac(..) => {
let mut expander = expand::MacroExpander {
extsbox: syntax_expander_table(),
cx: self,
};
e = expand::expand_expr(e, &mut expander);
}
_ => return e
}
}
}
pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
pub fn call_site(&self) -> Span {
match self.backtrace {
Some(expn_info) => expn_info.call_site,
None => self.bug("missing top span")
}
}
pub fn
|
(&self) { }
pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace }
pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
pub fn mod_path(&self) -> Vec<ast::Ident> {
let mut v = Vec::new();
v.push(token::str_to_ident(self.ecfg.crate_id.name));
v.extend(self.mod_path.iter().map(|a| *a));
return v;
}
pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
match ei {
ExpnInfo {call_site: cs, callee: ref callee} => {
self.backtrace =
Some(@ExpnInfo {
call_site: Span {lo: cs.lo, hi: cs.hi,
expn_info: self.backtrace},
callee: (*callee).clone()
});
}
}
}
pub fn bt_pop(&mut self) {
match self.backtrace {
Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
_ => self.bug("tried to pop without a push")
}
}
/// Emit `msg` attached to `sp`, and stop compilation immediately.
///
/// `span_err` should be strongly prefered where-ever possible:
/// this should *only* be used when
/// - continuing has a high risk of flow-on errors (e.g. errors in
/// declaring a macro would cause all uses of that macro to
/// complain about "undefined macro"), or
/// - there is literally nothing else that can be done (however,
/// in most cases one can construct a dummy expression/item to
/// substitute; we never hit resolve/type-checking so the dummy
/// value doesn't have to match anything)
pub fn span_fatal(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_fatal(sp, msg);
}
/// Emit `msg` attached to `sp`, without immediately stopping
/// compilation.
///
/// Compilation will be stopped in the near future (at the end of
/// the macro expansion phase).
pub fn span_err(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_err(sp, msg);
}
pub fn span_warn(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_warn(sp, msg);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
}
pub fn span_bug(&self, sp: Span, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_bug(sp, msg);
}
pub fn span_note(&self, sp: Span, msg: &str) {
self.print_backtrace();
self.parse_sess.span_diagnostic.span_note(sp, msg);
}
pub fn bug(&self, msg: &str) ->! {
self.print_backtrace();
self.parse_sess.span_diagnostic.handler().bug(msg);
}
pub fn trace_macros(&self) -> bool {
self.trace_mac
}
pub fn set_trace_macros(&mut self, x: bool) {
self.trace_mac = x
}
pub fn ident_of(&self, st: &str) -> ast::Ident {
str_to_ident(st)
}
}
/// Extract a string literal from the macro expanded version of `expr`,
/// emitting `err_msg` if `expr` is not a string literal. This does not stop
/// compilation on error, merely emits a non-fatal error and returns None.
pub fn expr_to_str(cx: &mut ExtCtxt, expr: @ast::Expr, err_msg: &str)
-> Option<(InternedString, ast::StrStyle)> {
// we want to be able to handle e.g. concat("foo", "bar")
let expr = cx.expand_expr(expr);
match expr.node {
ast::ExprLit(l) => match l.node {
ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
_ => cx.span_err(l.span, err_msg)
},
_ => cx.span_err(expr.span, err_msg)
}
None
}
/// Non-fatally assert that `tts` is empty. Note that this function
/// returns even when `tts` is non-empty, macros that *need* to stop
/// compilation should call
/// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
/// done as rarely as possible).
pub fn check_zero_tts(cx: &ExtCtxt,
sp: Span,
tts: &[ast::TokenTree],
name: &str) {
if tts.len()!= 0 {
cx.span_err(sp, format!("{} takes no arguments", name));
}
}
/// Extract the string literal from the first token of `tts`. If this
/// is not a string literal, emit an error and return None.
pub fn get_single_str_from_tts(cx: &ExtCtxt,
sp: Span,
tts: &[ast::TokenTree],
name: &str)
-> Option<~str> {
if tts.len()!= 1 {
cx.span_err(sp, format!("{} takes 1 argument.", name));
} else {
match tts[0] {
ast::TTTok(_, token::LIT_STR(ident))
|
print_backtrace
|
identifier_name
|
opaque_node.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/. */
#![allow(unsafe_code)]
use gfx::display_list::OpaqueNode;
use libc::{c_void, uintptr_t};
use script::layout_interface::LayoutJS;
use script::layout_interface::Node;
use script::layout_interface::TrustedNodeAddress;
use script_traits::UntrustedNodeAddress;
pub trait OpaqueNodeMethods {
/// Converts a DOM node (script view) to an `OpaqueNode`.
fn from_script_node(node: TrustedNodeAddress) -> Self;
/// Converts a DOM node to an `OpaqueNode'.
fn from_jsmanaged(node: &LayoutJS<Node>) -> Self;
|
/// of node that script expects to receive in a hit test.
fn to_untrusted_node_address(&self) -> UntrustedNodeAddress;
}
impl OpaqueNodeMethods for OpaqueNode {
fn from_script_node(node: TrustedNodeAddress) -> OpaqueNode {
unsafe {
OpaqueNodeMethods::from_jsmanaged(&LayoutJS::from_trusted_node_address(node))
}
}
fn from_jsmanaged(node: &LayoutJS<Node>) -> OpaqueNode {
unsafe {
let ptr: uintptr_t = node.get_jsobject() as uintptr_t;
OpaqueNode(ptr)
}
}
fn to_untrusted_node_address(&self) -> UntrustedNodeAddress {
UntrustedNodeAddress(self.0 as *const c_void)
}
}
|
/// Converts this node to an `UntrustedNodeAddress`. An `UntrustedNodeAddress` is just the type
|
random_line_split
|
opaque_node.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/. */
#![allow(unsafe_code)]
use gfx::display_list::OpaqueNode;
use libc::{c_void, uintptr_t};
use script::layout_interface::LayoutJS;
use script::layout_interface::Node;
use script::layout_interface::TrustedNodeAddress;
use script_traits::UntrustedNodeAddress;
pub trait OpaqueNodeMethods {
/// Converts a DOM node (script view) to an `OpaqueNode`.
fn from_script_node(node: TrustedNodeAddress) -> Self;
/// Converts a DOM node to an `OpaqueNode'.
fn from_jsmanaged(node: &LayoutJS<Node>) -> Self;
/// Converts this node to an `UntrustedNodeAddress`. An `UntrustedNodeAddress` is just the type
/// of node that script expects to receive in a hit test.
fn to_untrusted_node_address(&self) -> UntrustedNodeAddress;
}
impl OpaqueNodeMethods for OpaqueNode {
fn
|
(node: TrustedNodeAddress) -> OpaqueNode {
unsafe {
OpaqueNodeMethods::from_jsmanaged(&LayoutJS::from_trusted_node_address(node))
}
}
fn from_jsmanaged(node: &LayoutJS<Node>) -> OpaqueNode {
unsafe {
let ptr: uintptr_t = node.get_jsobject() as uintptr_t;
OpaqueNode(ptr)
}
}
fn to_untrusted_node_address(&self) -> UntrustedNodeAddress {
UntrustedNodeAddress(self.0 as *const c_void)
}
}
|
from_script_node
|
identifier_name
|
opaque_node.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/. */
#![allow(unsafe_code)]
use gfx::display_list::OpaqueNode;
use libc::{c_void, uintptr_t};
use script::layout_interface::LayoutJS;
use script::layout_interface::Node;
use script::layout_interface::TrustedNodeAddress;
use script_traits::UntrustedNodeAddress;
pub trait OpaqueNodeMethods {
/// Converts a DOM node (script view) to an `OpaqueNode`.
fn from_script_node(node: TrustedNodeAddress) -> Self;
/// Converts a DOM node to an `OpaqueNode'.
fn from_jsmanaged(node: &LayoutJS<Node>) -> Self;
/// Converts this node to an `UntrustedNodeAddress`. An `UntrustedNodeAddress` is just the type
/// of node that script expects to receive in a hit test.
fn to_untrusted_node_address(&self) -> UntrustedNodeAddress;
}
impl OpaqueNodeMethods for OpaqueNode {
fn from_script_node(node: TrustedNodeAddress) -> OpaqueNode {
unsafe {
OpaqueNodeMethods::from_jsmanaged(&LayoutJS::from_trusted_node_address(node))
}
}
fn from_jsmanaged(node: &LayoutJS<Node>) -> OpaqueNode {
unsafe {
let ptr: uintptr_t = node.get_jsobject() as uintptr_t;
OpaqueNode(ptr)
}
}
fn to_untrusted_node_address(&self) -> UntrustedNodeAddress
|
}
|
{
UntrustedNodeAddress(self.0 as *const c_void)
}
|
identifier_body
|
geniza-net.rs
|
// Free Software under GPL-3.0, see LICENSE
// Copyright 2017 Bryan Newbold
extern crate clap;
extern crate env_logger;
#[macro_use]
extern crate error_chain;
extern crate geniza;
extern crate sodiumoxide;
// TODO: more careful import
use geniza::*;
use std::path::Path;
use clap::{App, SubCommand, Arg};
use sodiumoxide::crypto::stream::Key;
fn run() -> Result<()>
|
)
.subcommand(
SubCommand::with_name("discover-dns")
.about("Does a centralized DNS lookup for peers with the given key")
.arg_from_usage("<dat_key> 'dat key (public key) to lookup"),
)
.subcommand(
SubCommand::with_name("naive-clone")
.about("Pulls a drive from a single (known) peer, using a naive algorithm")
.arg(Arg::with_name("dat-dir")
.short("d")
.long("dat-dir")
.value_name("PATH")
.help("dat drive directory")
.default_value(".dat")
.takes_value(true))
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to pull"),
)
.get_matches();
match matches.subcommand() {
("connect", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let key = Key::from_slice(&key_bytes).unwrap();
DatConnection::connect(host_port, &key, false, None)?;
println!("Done!");
}
("discovery-key", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in disc_key {
print!("{:02x}", b);
}
println!("");
}
("discovery-dns-name", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in 0..20 {
print!("{:02x}", disc_key[b]);
}
println!(".dat.local");
}
("discover-dns", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let peers = discover_peers_dns(&key_bytes)?;
if peers.len() == 0 {
println!("No peers found!");
} else {
for p in peers {
println!("{}", p);
}
}
}
("naive-clone", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let dir = Path::new(subm.value_of("dat-dir").unwrap());
let mut metadata = SleepDirRegister::create(&dir, "metadata")?;
node_simple_clone(host_port, &key_bytes, &mut metadata, 0)?;
// TODO: read out content key from metadata register
//let content = SleepDirRegister::create(&dir, "content")?;
//node_simple_clone(host_port, &key_bytes, &mut content, true)?;
}
_ => {
println!("Missing or unimplemented command!");
println!("{}", matches.usage());
::std::process::exit(-1);
}
}
Ok(())
}
quick_main!(run);
|
{
env_logger::init().unwrap();
let matches = App::new("geniza-net")
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
SubCommand::with_name("connect")
.about("Connects to a peer and exchanges handshake")
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to register with'"),
)
.subcommand(
SubCommand::with_name("discovery-key")
.about("Prints (in hex) the discovery key for a dat archive")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
)
.subcommand(
SubCommand::with_name("discovery-dns-name")
.about("Prints the DNS name to query (mDNS or centrally) for peers")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
|
identifier_body
|
geniza-net.rs
|
// Free Software under GPL-3.0, see LICENSE
// Copyright 2017 Bryan Newbold
extern crate clap;
extern crate env_logger;
#[macro_use]
extern crate error_chain;
extern crate geniza;
extern crate sodiumoxide;
// TODO: more careful import
use geniza::*;
use std::path::Path;
use clap::{App, SubCommand, Arg};
use sodiumoxide::crypto::stream::Key;
fn
|
() -> Result<()> {
env_logger::init().unwrap();
let matches = App::new("geniza-net")
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
SubCommand::with_name("connect")
.about("Connects to a peer and exchanges handshake")
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to register with'"),
)
.subcommand(
SubCommand::with_name("discovery-key")
.about("Prints (in hex) the discovery key for a dat archive")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
)
.subcommand(
SubCommand::with_name("discovery-dns-name")
.about("Prints the DNS name to query (mDNS or centrally) for peers")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
)
.subcommand(
SubCommand::with_name("discover-dns")
.about("Does a centralized DNS lookup for peers with the given key")
.arg_from_usage("<dat_key> 'dat key (public key) to lookup"),
)
.subcommand(
SubCommand::with_name("naive-clone")
.about("Pulls a drive from a single (known) peer, using a naive algorithm")
.arg(Arg::with_name("dat-dir")
.short("d")
.long("dat-dir")
.value_name("PATH")
.help("dat drive directory")
.default_value(".dat")
.takes_value(true))
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to pull"),
)
.get_matches();
match matches.subcommand() {
("connect", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let key = Key::from_slice(&key_bytes).unwrap();
DatConnection::connect(host_port, &key, false, None)?;
println!("Done!");
}
("discovery-key", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in disc_key {
print!("{:02x}", b);
}
println!("");
}
("discovery-dns-name", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in 0..20 {
print!("{:02x}", disc_key[b]);
}
println!(".dat.local");
}
("discover-dns", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let peers = discover_peers_dns(&key_bytes)?;
if peers.len() == 0 {
println!("No peers found!");
} else {
for p in peers {
println!("{}", p);
}
}
}
("naive-clone", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let dir = Path::new(subm.value_of("dat-dir").unwrap());
let mut metadata = SleepDirRegister::create(&dir, "metadata")?;
node_simple_clone(host_port, &key_bytes, &mut metadata, 0)?;
// TODO: read out content key from metadata register
//let content = SleepDirRegister::create(&dir, "content")?;
//node_simple_clone(host_port, &key_bytes, &mut content, true)?;
}
_ => {
println!("Missing or unimplemented command!");
println!("{}", matches.usage());
::std::process::exit(-1);
}
}
Ok(())
}
quick_main!(run);
|
run
|
identifier_name
|
geniza-net.rs
|
// Free Software under GPL-3.0, see LICENSE
// Copyright 2017 Bryan Newbold
extern crate clap;
extern crate env_logger;
#[macro_use]
extern crate error_chain;
extern crate geniza;
extern crate sodiumoxide;
// TODO: more careful import
use geniza::*;
use std::path::Path;
use clap::{App, SubCommand, Arg};
use sodiumoxide::crypto::stream::Key;
fn run() -> Result<()> {
env_logger::init().unwrap();
let matches = App::new("geniza-net")
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
SubCommand::with_name("connect")
.about("Connects to a peer and exchanges handshake")
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to register with'"),
)
.subcommand(
SubCommand::with_name("discovery-key")
.about("Prints (in hex) the discovery key for a dat archive")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
)
.subcommand(
SubCommand::with_name("discovery-dns-name")
.about("Prints the DNS name to query (mDNS or centrally) for peers")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
)
|
.arg_from_usage("<dat_key> 'dat key (public key) to lookup"),
)
.subcommand(
SubCommand::with_name("naive-clone")
.about("Pulls a drive from a single (known) peer, using a naive algorithm")
.arg(Arg::with_name("dat-dir")
.short("d")
.long("dat-dir")
.value_name("PATH")
.help("dat drive directory")
.default_value(".dat")
.takes_value(true))
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to pull"),
)
.get_matches();
match matches.subcommand() {
("connect", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let key = Key::from_slice(&key_bytes).unwrap();
DatConnection::connect(host_port, &key, false, None)?;
println!("Done!");
}
("discovery-key", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in disc_key {
print!("{:02x}", b);
}
println!("");
}
("discovery-dns-name", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in 0..20 {
print!("{:02x}", disc_key[b]);
}
println!(".dat.local");
}
("discover-dns", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let peers = discover_peers_dns(&key_bytes)?;
if peers.len() == 0 {
println!("No peers found!");
} else {
for p in peers {
println!("{}", p);
}
}
}
("naive-clone", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let dir = Path::new(subm.value_of("dat-dir").unwrap());
let mut metadata = SleepDirRegister::create(&dir, "metadata")?;
node_simple_clone(host_port, &key_bytes, &mut metadata, 0)?;
// TODO: read out content key from metadata register
//let content = SleepDirRegister::create(&dir, "content")?;
//node_simple_clone(host_port, &key_bytes, &mut content, true)?;
}
_ => {
println!("Missing or unimplemented command!");
println!("{}", matches.usage());
::std::process::exit(-1);
}
}
Ok(())
}
quick_main!(run);
|
.subcommand(
SubCommand::with_name("discover-dns")
.about("Does a centralized DNS lookup for peers with the given key")
|
random_line_split
|
geniza-net.rs
|
// Free Software under GPL-3.0, see LICENSE
// Copyright 2017 Bryan Newbold
extern crate clap;
extern crate env_logger;
#[macro_use]
extern crate error_chain;
extern crate geniza;
extern crate sodiumoxide;
// TODO: more careful import
use geniza::*;
use std::path::Path;
use clap::{App, SubCommand, Arg};
use sodiumoxide::crypto::stream::Key;
fn run() -> Result<()> {
env_logger::init().unwrap();
let matches = App::new("geniza-net")
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
SubCommand::with_name("connect")
.about("Connects to a peer and exchanges handshake")
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to register with'"),
)
.subcommand(
SubCommand::with_name("discovery-key")
.about("Prints (in hex) the discovery key for a dat archive")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
)
.subcommand(
SubCommand::with_name("discovery-dns-name")
.about("Prints the DNS name to query (mDNS or centrally) for peers")
.arg_from_usage("<dat_key> 'dat key (public key) to convert (in hex)'"),
)
.subcommand(
SubCommand::with_name("discover-dns")
.about("Does a centralized DNS lookup for peers with the given key")
.arg_from_usage("<dat_key> 'dat key (public key) to lookup"),
)
.subcommand(
SubCommand::with_name("naive-clone")
.about("Pulls a drive from a single (known) peer, using a naive algorithm")
.arg(Arg::with_name("dat-dir")
.short("d")
.long("dat-dir")
.value_name("PATH")
.help("dat drive directory")
.default_value(".dat")
.takes_value(true))
.arg_from_usage("<host_port> 'peer host:port to connect to'")
.arg_from_usage("<dat_key> 'dat key (public key) to pull"),
)
.get_matches();
match matches.subcommand() {
("connect", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let key = Key::from_slice(&key_bytes).unwrap();
DatConnection::connect(host_port, &key, false, None)?;
println!("Done!");
}
("discovery-key", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in disc_key {
print!("{:02x}", b);
}
println!("");
}
("discovery-dns-name", Some(subm)) =>
|
("discover-dns", Some(subm)) => {
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let peers = discover_peers_dns(&key_bytes)?;
if peers.len() == 0 {
println!("No peers found!");
} else {
for p in peers {
println!("{}", p);
}
}
}
("naive-clone", Some(subm)) => {
let host_port = subm.value_of("host_port").unwrap();
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let dir = Path::new(subm.value_of("dat-dir").unwrap());
let mut metadata = SleepDirRegister::create(&dir, "metadata")?;
node_simple_clone(host_port, &key_bytes, &mut metadata, 0)?;
// TODO: read out content key from metadata register
//let content = SleepDirRegister::create(&dir, "content")?;
//node_simple_clone(host_port, &key_bytes, &mut content, true)?;
}
_ => {
println!("Missing or unimplemented command!");
println!("{}", matches.usage());
::std::process::exit(-1);
}
}
Ok(())
}
quick_main!(run);
|
{
let dat_key = subm.value_of("dat_key").unwrap();
let key_bytes = parse_dat_address(&dat_key)?;
let disc_key = make_discovery_key(&key_bytes);
for b in 0..20 {
print!("{:02x}", disc_key[b]);
}
println!(".dat.local");
}
|
conditional_block
|
dispatcher.rs
|
use color_printer::ColorPrinter;
use command::{Command, WorkResult, WorkType};
use std::{collections::BTreeMap, sync::mpsc::Receiver};
use threadpool::ThreadPool;
const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work";
pub struct Dispatcher<'a> {
queue: BTreeMap<usize, Option<Box<dyn WorkResult>>>,
next_index: usize,
command: Box<dyn Command>,
pool: &'a ThreadPool,
printer: ColorPrinter<'a>,
}
impl<'a> Dispatcher<'a> {
pub fn new(pool: &'a ThreadPool, printer: ColorPrinter<'a>, command: Box<dyn Command>) -> Self {
Self {
queue: BTreeMap::new(),
next_index: 0,
pool,
command,
printer,
}
}
pub fn run(&mut self, rx: &Receiver<WorkType>) {
while let Ok(result) = rx.recv() {
match result {
WorkType::Repo { index, repo, tx } => {
let worker = self.command.box_clone();
self.pool.execute(move || {
let result = match worker.process(repo) {
Some(r) => WorkType::result(index, r),
None => WorkType::empty(index),
};
tx.send(result).expect(THREAD_SIGNAL)
})
}
WorkType::WorkEmpty { index } => {
if index == self.next_index {
self.process_queue();
} else {
self.queue.insert(index, None);
}
}
WorkType::Work { index, result } => {
if self.next_index!= index {
self.queue.insert(index, Some(result));
continue;
}
result.print(&mut self.printer);
|
}
}
}
// Sanity check
if!self.queue.is_empty() {
panic!(
"There are {} unprocessed items in the queue. \
Did you forget to send WorkEmpty::WorkEmpty messages?",
self.queue.len()
);
}
}
fn process_queue(&mut self) {
self.next_index += 1;
while let Some(result) = self.queue.remove(&self.next_index) {
if let Some(work_result) = result {
work_result.print(&mut self.printer);
}
self.next_index += 1;
}
}
}
|
// If there are adjacent items in the queue, process them.
self.process_queue();
|
random_line_split
|
dispatcher.rs
|
use color_printer::ColorPrinter;
use command::{Command, WorkResult, WorkType};
use std::{collections::BTreeMap, sync::mpsc::Receiver};
use threadpool::ThreadPool;
const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work";
pub struct Dispatcher<'a> {
queue: BTreeMap<usize, Option<Box<dyn WorkResult>>>,
next_index: usize,
command: Box<dyn Command>,
pool: &'a ThreadPool,
printer: ColorPrinter<'a>,
}
impl<'a> Dispatcher<'a> {
pub fn new(pool: &'a ThreadPool, printer: ColorPrinter<'a>, command: Box<dyn Command>) -> Self {
Self {
queue: BTreeMap::new(),
next_index: 0,
pool,
command,
printer,
}
}
pub fn
|
(&mut self, rx: &Receiver<WorkType>) {
while let Ok(result) = rx.recv() {
match result {
WorkType::Repo { index, repo, tx } => {
let worker = self.command.box_clone();
self.pool.execute(move || {
let result = match worker.process(repo) {
Some(r) => WorkType::result(index, r),
None => WorkType::empty(index),
};
tx.send(result).expect(THREAD_SIGNAL)
})
}
WorkType::WorkEmpty { index } => {
if index == self.next_index {
self.process_queue();
} else {
self.queue.insert(index, None);
}
}
WorkType::Work { index, result } => {
if self.next_index!= index {
self.queue.insert(index, Some(result));
continue;
}
result.print(&mut self.printer);
// If there are adjacent items in the queue, process them.
self.process_queue();
}
}
}
// Sanity check
if!self.queue.is_empty() {
panic!(
"There are {} unprocessed items in the queue. \
Did you forget to send WorkEmpty::WorkEmpty messages?",
self.queue.len()
);
}
}
fn process_queue(&mut self) {
self.next_index += 1;
while let Some(result) = self.queue.remove(&self.next_index) {
if let Some(work_result) = result {
work_result.print(&mut self.printer);
}
self.next_index += 1;
}
}
}
|
run
|
identifier_name
|
dispatcher.rs
|
use color_printer::ColorPrinter;
use command::{Command, WorkResult, WorkType};
use std::{collections::BTreeMap, sync::mpsc::Receiver};
use threadpool::ThreadPool;
const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work";
pub struct Dispatcher<'a> {
queue: BTreeMap<usize, Option<Box<dyn WorkResult>>>,
next_index: usize,
command: Box<dyn Command>,
pool: &'a ThreadPool,
printer: ColorPrinter<'a>,
}
impl<'a> Dispatcher<'a> {
pub fn new(pool: &'a ThreadPool, printer: ColorPrinter<'a>, command: Box<dyn Command>) -> Self {
Self {
queue: BTreeMap::new(),
next_index: 0,
pool,
command,
printer,
}
}
pub fn run(&mut self, rx: &Receiver<WorkType>) {
while let Ok(result) = rx.recv() {
match result {
WorkType::Repo { index, repo, tx } =>
|
WorkType::WorkEmpty { index } => {
if index == self.next_index {
self.process_queue();
} else {
self.queue.insert(index, None);
}
}
WorkType::Work { index, result } => {
if self.next_index!= index {
self.queue.insert(index, Some(result));
continue;
}
result.print(&mut self.printer);
// If there are adjacent items in the queue, process them.
self.process_queue();
}
}
}
// Sanity check
if!self.queue.is_empty() {
panic!(
"There are {} unprocessed items in the queue. \
Did you forget to send WorkEmpty::WorkEmpty messages?",
self.queue.len()
);
}
}
fn process_queue(&mut self) {
self.next_index += 1;
while let Some(result) = self.queue.remove(&self.next_index) {
if let Some(work_result) = result {
work_result.print(&mut self.printer);
}
self.next_index += 1;
}
}
}
|
{
let worker = self.command.box_clone();
self.pool.execute(move || {
let result = match worker.process(repo) {
Some(r) => WorkType::result(index, r),
None => WorkType::empty(index),
};
tx.send(result).expect(THREAD_SIGNAL)
})
}
|
conditional_block
|
dispatcher.rs
|
use color_printer::ColorPrinter;
use command::{Command, WorkResult, WorkType};
use std::{collections::BTreeMap, sync::mpsc::Receiver};
use threadpool::ThreadPool;
const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work";
pub struct Dispatcher<'a> {
queue: BTreeMap<usize, Option<Box<dyn WorkResult>>>,
next_index: usize,
command: Box<dyn Command>,
pool: &'a ThreadPool,
printer: ColorPrinter<'a>,
}
impl<'a> Dispatcher<'a> {
pub fn new(pool: &'a ThreadPool, printer: ColorPrinter<'a>, command: Box<dyn Command>) -> Self {
Self {
queue: BTreeMap::new(),
next_index: 0,
pool,
command,
printer,
}
}
pub fn run(&mut self, rx: &Receiver<WorkType>) {
while let Ok(result) = rx.recv() {
match result {
WorkType::Repo { index, repo, tx } => {
let worker = self.command.box_clone();
self.pool.execute(move || {
let result = match worker.process(repo) {
Some(r) => WorkType::result(index, r),
None => WorkType::empty(index),
};
tx.send(result).expect(THREAD_SIGNAL)
})
}
WorkType::WorkEmpty { index } => {
if index == self.next_index {
self.process_queue();
} else {
self.queue.insert(index, None);
}
}
WorkType::Work { index, result } => {
if self.next_index!= index {
self.queue.insert(index, Some(result));
continue;
}
result.print(&mut self.printer);
// If there are adjacent items in the queue, process them.
self.process_queue();
}
}
}
// Sanity check
if!self.queue.is_empty() {
panic!(
"There are {} unprocessed items in the queue. \
Did you forget to send WorkEmpty::WorkEmpty messages?",
self.queue.len()
);
}
}
fn process_queue(&mut self)
|
}
|
{
self.next_index += 1;
while let Some(result) = self.queue.remove(&self.next_index) {
if let Some(work_result) = result {
work_result.print(&mut self.printer);
}
self.next_index += 1;
}
}
|
identifier_body
|
badge.rs
|
use krate::Crate;
use schema::badges;
use diesel::pg::Pg;
use diesel::prelude::*;
use serde_json;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")]
pub enum Badge {
TravisCi {
repository: String,
branch: Option<String>,
},
Appveyor {
repository: String,
branch: Option<String>,
service: Option<String>,
},
#[serde(rename = "gitlab")]
GitLab {
repository: String,
branch: Option<String>,
},
CircleCi {
repository: String,
branch: Option<String>,
},
IsItMaintainedIssueResolution { repository: String },
IsItMaintainedOpenIssues { repository: String },
Codecov {
repository: String,
branch: Option<String>,
service: Option<String>,
},
Coveralls {
repository: String,
branch: Option<String>,
service: Option<String>,
},
Maintenance { status: MaintenanceStatus },
}
#[derive(Debug, PartialEq, Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum MaintenanceStatus {
ActivelyDeveloped,
PassivelyMaintained,
AsIs,
None,
Experimental,
|
pub struct EncodableBadge {
pub badge_type: String,
pub attributes: HashMap<String, Option<String>>,
}
impl Queryable<badges::SqlType, Pg> for Badge {
type Row = (i32, String, serde_json::Value);
fn build((_, badge_type, attributes): Self::Row) -> Self {
let json = json!({"badge_type": badge_type, "attributes": attributes});
serde_json::from_value(json).expect("Invalid CI badge in the database")
}
}
impl Badge {
pub fn encodable(self) -> EncodableBadge {
serde_json::from_value(serde_json::to_value(self).unwrap()).unwrap()
}
pub fn update_crate<'a>(
conn: &PgConnection,
krate: &Crate,
badges: Option<&'a HashMap<String, HashMap<String, String>>>,
) -> QueryResult<Vec<&'a str>> {
use diesel::{insert, delete};
#[derive(Insertable, Debug)]
#[table_name = "badges"]
struct NewBadge<'a> {
crate_id: i32,
badge_type: &'a str,
attributes: serde_json::Value,
}
let mut invalid_badges = vec![];
let mut new_badges = vec![];
if let Some(badges) = badges {
for (k, v) in badges {
let attributes_json = serde_json::to_value(v).unwrap();
let json = json!({"badge_type": k, "attributes": attributes_json});
if serde_json::from_value::<Badge>(json).is_ok() {
new_badges.push(NewBadge {
crate_id: krate.id,
badge_type: &**k,
attributes: attributes_json,
});
} else {
invalid_badges.push(&**k);
}
}
}
conn.transaction(|| {
delete(badges::table.filter(badges::crate_id.eq(krate.id)))
.execute(conn)?;
insert(&new_badges).into(badges::table).execute(conn)?;
Ok(invalid_badges)
})
}
}
|
LookingForMaintainer,
Deprecated,
}
#[derive(PartialEq, Debug, Serialize, Deserialize)]
|
random_line_split
|
badge.rs
|
use krate::Crate;
use schema::badges;
use diesel::pg::Pg;
use diesel::prelude::*;
use serde_json;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")]
pub enum Badge {
TravisCi {
repository: String,
branch: Option<String>,
},
Appveyor {
repository: String,
branch: Option<String>,
service: Option<String>,
},
#[serde(rename = "gitlab")]
GitLab {
repository: String,
branch: Option<String>,
},
CircleCi {
repository: String,
branch: Option<String>,
},
IsItMaintainedIssueResolution { repository: String },
IsItMaintainedOpenIssues { repository: String },
Codecov {
repository: String,
branch: Option<String>,
service: Option<String>,
},
Coveralls {
repository: String,
branch: Option<String>,
service: Option<String>,
},
Maintenance { status: MaintenanceStatus },
}
#[derive(Debug, PartialEq, Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum MaintenanceStatus {
ActivelyDeveloped,
PassivelyMaintained,
AsIs,
None,
Experimental,
LookingForMaintainer,
Deprecated,
}
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct EncodableBadge {
pub badge_type: String,
pub attributes: HashMap<String, Option<String>>,
}
impl Queryable<badges::SqlType, Pg> for Badge {
type Row = (i32, String, serde_json::Value);
fn build((_, badge_type, attributes): Self::Row) -> Self {
let json = json!({"badge_type": badge_type, "attributes": attributes});
serde_json::from_value(json).expect("Invalid CI badge in the database")
}
}
impl Badge {
pub fn encodable(self) -> EncodableBadge {
serde_json::from_value(serde_json::to_value(self).unwrap()).unwrap()
}
pub fn
|
<'a>(
conn: &PgConnection,
krate: &Crate,
badges: Option<&'a HashMap<String, HashMap<String, String>>>,
) -> QueryResult<Vec<&'a str>> {
use diesel::{insert, delete};
#[derive(Insertable, Debug)]
#[table_name = "badges"]
struct NewBadge<'a> {
crate_id: i32,
badge_type: &'a str,
attributes: serde_json::Value,
}
let mut invalid_badges = vec![];
let mut new_badges = vec![];
if let Some(badges) = badges {
for (k, v) in badges {
let attributes_json = serde_json::to_value(v).unwrap();
let json = json!({"badge_type": k, "attributes": attributes_json});
if serde_json::from_value::<Badge>(json).is_ok() {
new_badges.push(NewBadge {
crate_id: krate.id,
badge_type: &**k,
attributes: attributes_json,
});
} else {
invalid_badges.push(&**k);
}
}
}
conn.transaction(|| {
delete(badges::table.filter(badges::crate_id.eq(krate.id)))
.execute(conn)?;
insert(&new_badges).into(badges::table).execute(conn)?;
Ok(invalid_badges)
})
}
}
|
update_crate
|
identifier_name
|
badge.rs
|
use krate::Crate;
use schema::badges;
use diesel::pg::Pg;
use diesel::prelude::*;
use serde_json;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")]
pub enum Badge {
TravisCi {
repository: String,
branch: Option<String>,
},
Appveyor {
repository: String,
branch: Option<String>,
service: Option<String>,
},
#[serde(rename = "gitlab")]
GitLab {
repository: String,
branch: Option<String>,
},
CircleCi {
repository: String,
branch: Option<String>,
},
IsItMaintainedIssueResolution { repository: String },
IsItMaintainedOpenIssues { repository: String },
Codecov {
repository: String,
branch: Option<String>,
service: Option<String>,
},
Coveralls {
repository: String,
branch: Option<String>,
service: Option<String>,
},
Maintenance { status: MaintenanceStatus },
}
#[derive(Debug, PartialEq, Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum MaintenanceStatus {
ActivelyDeveloped,
PassivelyMaintained,
AsIs,
None,
Experimental,
LookingForMaintainer,
Deprecated,
}
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct EncodableBadge {
pub badge_type: String,
pub attributes: HashMap<String, Option<String>>,
}
impl Queryable<badges::SqlType, Pg> for Badge {
type Row = (i32, String, serde_json::Value);
fn build((_, badge_type, attributes): Self::Row) -> Self {
let json = json!({"badge_type": badge_type, "attributes": attributes});
serde_json::from_value(json).expect("Invalid CI badge in the database")
}
}
impl Badge {
pub fn encodable(self) -> EncodableBadge {
serde_json::from_value(serde_json::to_value(self).unwrap()).unwrap()
}
pub fn update_crate<'a>(
conn: &PgConnection,
krate: &Crate,
badges: Option<&'a HashMap<String, HashMap<String, String>>>,
) -> QueryResult<Vec<&'a str>> {
use diesel::{insert, delete};
#[derive(Insertable, Debug)]
#[table_name = "badges"]
struct NewBadge<'a> {
crate_id: i32,
badge_type: &'a str,
attributes: serde_json::Value,
}
let mut invalid_badges = vec![];
let mut new_badges = vec![];
if let Some(badges) = badges {
for (k, v) in badges {
let attributes_json = serde_json::to_value(v).unwrap();
let json = json!({"badge_type": k, "attributes": attributes_json});
if serde_json::from_value::<Badge>(json).is_ok()
|
else {
invalid_badges.push(&**k);
}
}
}
conn.transaction(|| {
delete(badges::table.filter(badges::crate_id.eq(krate.id)))
.execute(conn)?;
insert(&new_badges).into(badges::table).execute(conn)?;
Ok(invalid_badges)
})
}
}
|
{
new_badges.push(NewBadge {
crate_id: krate.id,
badge_type: &**k,
attributes: attributes_json,
});
}
|
conditional_block
|
cssrulelist.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::csskeyframerule::CSSKeyframeRule;
use dom::cssrule::CSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::stylesheets::{CssRules, KeyframesRule, RulesMutateError};
#[allow(unsafe_code)]
unsafe_no_jsmanaged_fields!(RulesSource);
unsafe_no_jsmanaged_fields!(CssRules);
impl From<RulesMutateError> for Error {
fn from(other: RulesMutateError) -> Self {
match other {
RulesMutateError::Syntax => Error::Syntax,
RulesMutateError::IndexSize => Error::IndexSize,
RulesMutateError::HierarchyRequest => Error::HierarchyRequest,
RulesMutateError::InvalidState => Error::InvalidState,
}
}
}
#[dom_struct]
pub struct CSSRuleList {
reflector_: Reflector,
parent_stylesheet: JS<CSSStyleSheet>,
#[ignore_heap_size_of = "Arc"]
rules: RulesSource,
dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>>
}
pub enum RulesSource {
Rules(Arc<RwLock<CssRules>>),
Keyframes(Arc<RwLock<KeyframesRule>>),
}
impl CSSRuleList {
#[allow(unrooted_must_root)]
pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList {
let dom_rules = match rules {
RulesSource::Rules(ref rules) => {
rules.read().0.iter().map(|_| MutNullableJS::new(None)).collect()
}
RulesSource::Keyframes(ref rules) => {
rules.read().keyframes.iter().map(|_| MutNullableJS::new(None)).collect()
}
};
CSSRuleList {
reflector_: Reflector::new(),
parent_stylesheet: JS::from_ref(parent_stylesheet),
rules: rules,
dom_rules: DOMRefCell::new(dom_rules),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
rules: RulesSource) -> Root<CSSRuleList> {
reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules),
window,
CSSRuleListBinding::Wrap)
}
/// Should only be called for CssRules-backed rules. Use append_lazy_rule
/// for keyframes-backed rules.
pub fn insert_rule(&self, rule: &str, idx: u32, nested: bool) -> Fallible<u32> {
let css_rules = if let RulesSource::Rules(ref rules) = self.rules {
rules
} else {
panic!("Called insert_rule on non-CssRule-backed CSSRuleList");
};
let global = self.global();
let window = global.as_window();
let index = idx as usize;
let parent_stylesheet = self.parent_stylesheet.style_stylesheet();
let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?;
let parent_stylesheet = &*self.parent_stylesheet;
let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule);
self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule)));
Ok((idx))
}
// In case of a keyframe rule, index must be valid.
pub fn remove_rule(&self, index: u32) -> ErrorResult {
let index = index as usize;
match self.rules {
RulesSource::Rules(ref css_rules) => {
css_rules.write().remove_rule(index)?;
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
Ok(())
}
RulesSource::Keyframes(ref kf) => {
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
kf.write().keyframes.remove(index);
Ok(())
}
}
}
// Remove parent stylesheets from all children
pub fn deparent_all(&self) {
for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| Root::upcast(r).deparent());
}
}
pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> {
self.dom_rules.borrow().get(idx as usize).map(|rule| {
rule.or_init(|| {
let parent_stylesheet = &self.parent_stylesheet;
match self.rules {
RulesSource::Rules(ref rules) => {
CSSRule::new_specific(self.global().as_window(),
parent_stylesheet,
rules.read().0[idx as usize].clone())
}
RulesSource::Keyframes(ref rules) => {
Root::upcast(CSSKeyframeRule::new(self.global().as_window(),
parent_stylesheet,
rules.read()
.keyframes[idx as usize]
.clone()))
}
}
})
})
}
/// Add a rule to the list of DOM rules. This list is lazy,
/// so we just append a placeholder.
///
/// Should only be called for keyframes-backed rules, use insert_rule
/// for CssRules-backed rules
pub fn append_lazy_dom_rule(&self) {
if let RulesSource::Rules(..) = self.rules {
panic!("Can only call append_lazy_rule with keyframes-backed CSSRules");
}
self.dom_rules.borrow_mut().push(MutNullableJS::new(None));
}
}
impl CSSRuleListMethods for CSSRuleList {
// https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1
fn Item(&self, idx: u32) -> Option<Root<CSSRule>> {
self.item(idx)
}
// https://drafts.csswg.org/cssom/#dom-cssrulelist-length
fn Length(&self) -> u32 {
self.dom_rules.borrow().len() as u32
}
// check-tidy: no specs after this line
fn
|
(&self, index: u32) -> Option<Root<CSSRule>> {
self.Item(index)
}
}
|
IndexedGetter
|
identifier_name
|
cssrulelist.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::csskeyframerule::CSSKeyframeRule;
use dom::cssrule::CSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::stylesheets::{CssRules, KeyframesRule, RulesMutateError};
#[allow(unsafe_code)]
unsafe_no_jsmanaged_fields!(RulesSource);
unsafe_no_jsmanaged_fields!(CssRules);
impl From<RulesMutateError> for Error {
fn from(other: RulesMutateError) -> Self {
match other {
RulesMutateError::Syntax => Error::Syntax,
RulesMutateError::IndexSize => Error::IndexSize,
RulesMutateError::HierarchyRequest => Error::HierarchyRequest,
RulesMutateError::InvalidState => Error::InvalidState,
}
}
}
#[dom_struct]
pub struct CSSRuleList {
reflector_: Reflector,
parent_stylesheet: JS<CSSStyleSheet>,
#[ignore_heap_size_of = "Arc"]
rules: RulesSource,
dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>>
}
pub enum RulesSource {
Rules(Arc<RwLock<CssRules>>),
Keyframes(Arc<RwLock<KeyframesRule>>),
}
impl CSSRuleList {
#[allow(unrooted_must_root)]
pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList {
let dom_rules = match rules {
RulesSource::Rules(ref rules) => {
rules.read().0.iter().map(|_| MutNullableJS::new(None)).collect()
}
RulesSource::Keyframes(ref rules) => {
rules.read().keyframes.iter().map(|_| MutNullableJS::new(None)).collect()
}
};
CSSRuleList {
reflector_: Reflector::new(),
parent_stylesheet: JS::from_ref(parent_stylesheet),
rules: rules,
dom_rules: DOMRefCell::new(dom_rules),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
rules: RulesSource) -> Root<CSSRuleList> {
reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules),
window,
CSSRuleListBinding::Wrap)
}
/// Should only be called for CssRules-backed rules. Use append_lazy_rule
/// for keyframes-backed rules.
pub fn insert_rule(&self, rule: &str, idx: u32, nested: bool) -> Fallible<u32>
|
// In case of a keyframe rule, index must be valid.
pub fn remove_rule(&self, index: u32) -> ErrorResult {
let index = index as usize;
match self.rules {
RulesSource::Rules(ref css_rules) => {
css_rules.write().remove_rule(index)?;
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
Ok(())
}
RulesSource::Keyframes(ref kf) => {
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
kf.write().keyframes.remove(index);
Ok(())
}
}
}
// Remove parent stylesheets from all children
pub fn deparent_all(&self) {
for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| Root::upcast(r).deparent());
}
}
pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> {
self.dom_rules.borrow().get(idx as usize).map(|rule| {
rule.or_init(|| {
let parent_stylesheet = &self.parent_stylesheet;
match self.rules {
RulesSource::Rules(ref rules) => {
CSSRule::new_specific(self.global().as_window(),
parent_stylesheet,
rules.read().0[idx as usize].clone())
}
RulesSource::Keyframes(ref rules) => {
Root::upcast(CSSKeyframeRule::new(self.global().as_window(),
parent_stylesheet,
rules.read()
.keyframes[idx as usize]
.clone()))
}
}
})
})
}
/// Add a rule to the list of DOM rules. This list is lazy,
/// so we just append a placeholder.
///
/// Should only be called for keyframes-backed rules, use insert_rule
/// for CssRules-backed rules
pub fn append_lazy_dom_rule(&self) {
if let RulesSource::Rules(..) = self.rules {
panic!("Can only call append_lazy_rule with keyframes-backed CSSRules");
}
self.dom_rules.borrow_mut().push(MutNullableJS::new(None));
}
}
impl CSSRuleListMethods for CSSRuleList {
// https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1
fn Item(&self, idx: u32) -> Option<Root<CSSRule>> {
self.item(idx)
}
// https://drafts.csswg.org/cssom/#dom-cssrulelist-length
fn Length(&self) -> u32 {
self.dom_rules.borrow().len() as u32
}
// check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32) -> Option<Root<CSSRule>> {
self.Item(index)
}
}
|
{
let css_rules = if let RulesSource::Rules(ref rules) = self.rules {
rules
} else {
panic!("Called insert_rule on non-CssRule-backed CSSRuleList");
};
let global = self.global();
let window = global.as_window();
let index = idx as usize;
let parent_stylesheet = self.parent_stylesheet.style_stylesheet();
let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?;
let parent_stylesheet = &*self.parent_stylesheet;
let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule);
self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule)));
Ok((idx))
}
|
identifier_body
|
cssrulelist.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::csskeyframerule::CSSKeyframeRule;
use dom::cssrule::CSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::stylesheets::{CssRules, KeyframesRule, RulesMutateError};
#[allow(unsafe_code)]
unsafe_no_jsmanaged_fields!(RulesSource);
unsafe_no_jsmanaged_fields!(CssRules);
impl From<RulesMutateError> for Error {
fn from(other: RulesMutateError) -> Self {
match other {
RulesMutateError::Syntax => Error::Syntax,
RulesMutateError::IndexSize => Error::IndexSize,
RulesMutateError::HierarchyRequest => Error::HierarchyRequest,
RulesMutateError::InvalidState => Error::InvalidState,
}
}
}
#[dom_struct]
pub struct CSSRuleList {
reflector_: Reflector,
parent_stylesheet: JS<CSSStyleSheet>,
#[ignore_heap_size_of = "Arc"]
rules: RulesSource,
dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>>
}
pub enum RulesSource {
Rules(Arc<RwLock<CssRules>>),
Keyframes(Arc<RwLock<KeyframesRule>>),
}
impl CSSRuleList {
#[allow(unrooted_must_root)]
pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList {
let dom_rules = match rules {
RulesSource::Rules(ref rules) => {
rules.read().0.iter().map(|_| MutNullableJS::new(None)).collect()
}
RulesSource::Keyframes(ref rules) => {
rules.read().keyframes.iter().map(|_| MutNullableJS::new(None)).collect()
}
};
CSSRuleList {
reflector_: Reflector::new(),
parent_stylesheet: JS::from_ref(parent_stylesheet),
rules: rules,
dom_rules: DOMRefCell::new(dom_rules),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
rules: RulesSource) -> Root<CSSRuleList> {
reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules),
window,
CSSRuleListBinding::Wrap)
}
/// Should only be called for CssRules-backed rules. Use append_lazy_rule
/// for keyframes-backed rules.
pub fn insert_rule(&self, rule: &str, idx: u32, nested: bool) -> Fallible<u32> {
let css_rules = if let RulesSource::Rules(ref rules) = self.rules {
rules
} else {
panic!("Called insert_rule on non-CssRule-backed CSSRuleList");
};
|
let global = self.global();
let window = global.as_window();
let index = idx as usize;
let parent_stylesheet = self.parent_stylesheet.style_stylesheet();
let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?;
let parent_stylesheet = &*self.parent_stylesheet;
let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule);
self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule)));
Ok((idx))
}
// In case of a keyframe rule, index must be valid.
pub fn remove_rule(&self, index: u32) -> ErrorResult {
let index = index as usize;
match self.rules {
RulesSource::Rules(ref css_rules) => {
css_rules.write().remove_rule(index)?;
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
Ok(())
}
RulesSource::Keyframes(ref kf) => {
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
kf.write().keyframes.remove(index);
Ok(())
}
}
}
// Remove parent stylesheets from all children
pub fn deparent_all(&self) {
for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| Root::upcast(r).deparent());
}
}
pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> {
self.dom_rules.borrow().get(idx as usize).map(|rule| {
rule.or_init(|| {
let parent_stylesheet = &self.parent_stylesheet;
match self.rules {
RulesSource::Rules(ref rules) => {
CSSRule::new_specific(self.global().as_window(),
parent_stylesheet,
rules.read().0[idx as usize].clone())
}
RulesSource::Keyframes(ref rules) => {
Root::upcast(CSSKeyframeRule::new(self.global().as_window(),
parent_stylesheet,
rules.read()
.keyframes[idx as usize]
.clone()))
}
}
})
})
}
/// Add a rule to the list of DOM rules. This list is lazy,
/// so we just append a placeholder.
///
/// Should only be called for keyframes-backed rules, use insert_rule
/// for CssRules-backed rules
pub fn append_lazy_dom_rule(&self) {
if let RulesSource::Rules(..) = self.rules {
panic!("Can only call append_lazy_rule with keyframes-backed CSSRules");
}
self.dom_rules.borrow_mut().push(MutNullableJS::new(None));
}
}
impl CSSRuleListMethods for CSSRuleList {
// https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1
fn Item(&self, idx: u32) -> Option<Root<CSSRule>> {
self.item(idx)
}
// https://drafts.csswg.org/cssom/#dom-cssrulelist-length
fn Length(&self) -> u32 {
self.dom_rules.borrow().len() as u32
}
// check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32) -> Option<Root<CSSRule>> {
self.Item(index)
}
}
|
random_line_split
|
|
tcp.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(deprecated)]
use prelude::v1::*;
use old_io::net::ip;
use old_io::IoResult;
use libc;
use mem;
use ptr;
use super::{last_error, last_net_error, sock_t};
use sync::Arc;
use sync::atomic::{AtomicBool, Ordering};
use sys::{self, c, set_nonblocking, wouldblock, timer};
use sys_common::{timeout, eof, net};
pub use sys_common::net::TcpStream;
pub struct
|
(c::WSAEVENT);
unsafe impl Send for Event {}
unsafe impl Sync for Event {}
impl Event {
pub fn new() -> IoResult<Event> {
let event = unsafe { c::WSACreateEvent() };
if event == c::WSA_INVALID_EVENT {
Err(super::last_error())
} else {
Ok(Event(event))
}
}
pub fn handle(&self) -> c::WSAEVENT { let Event(handle) = *self; handle }
}
impl Drop for Event {
fn drop(&mut self) {
unsafe { let _ = c::WSACloseEvent(self.handle()); }
}
}
////////////////////////////////////////////////////////////////////////////////
// TCP listeners
////////////////////////////////////////////////////////////////////////////////
pub struct TcpListener { sock: sock_t }
unsafe impl Send for TcpListener {}
unsafe impl Sync for TcpListener {}
impl TcpListener {
pub fn bind(addr: ip::SocketAddr) -> IoResult<TcpListener> {
sys::init_net();
let sock = try!(net::socket(addr, libc::SOCK_STREAM));
let ret = TcpListener { sock: sock };
let mut storage = unsafe { mem::zeroed() };
let len = net::addr_to_sockaddr(addr, &mut storage);
let addrp = &storage as *const _ as *const libc::sockaddr;
match unsafe { libc::bind(sock, addrp, len) } {
-1 => Err(last_net_error()),
_ => Ok(ret),
}
}
pub fn socket(&self) -> sock_t { self.sock }
pub fn listen(self, backlog: int) -> IoResult<TcpAcceptor> {
match unsafe { libc::listen(self.socket(), backlog as libc::c_int) } {
-1 => Err(last_net_error()),
_ => {
let accept = try!(Event::new());
let ret = unsafe {
c::WSAEventSelect(self.socket(), accept.handle(), c::FD_ACCEPT)
};
if ret!= 0 {
return Err(last_net_error())
}
Ok(TcpAcceptor {
inner: Arc::new(AcceptorInner {
listener: self,
abort: try!(Event::new()),
accept: accept,
closed: AtomicBool::new(false),
}),
deadline: 0,
})
}
}
}
pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> {
net::sockname(self.socket(), libc::getsockname)
}
}
impl Drop for TcpListener {
fn drop(&mut self) {
unsafe { super::close_sock(self.sock); }
}
}
pub struct TcpAcceptor {
inner: Arc<AcceptorInner>,
deadline: u64,
}
struct AcceptorInner {
listener: TcpListener,
abort: Event,
accept: Event,
closed: AtomicBool,
}
unsafe impl Sync for AcceptorInner {}
impl TcpAcceptor {
pub fn socket(&self) -> sock_t { self.inner.listener.socket() }
pub fn accept(&mut self) -> IoResult<TcpStream> {
// Unlink unix, windows cannot invoke `select` on arbitrary file
// descriptors like pipes, only sockets. Consequently, windows cannot
// use the same implementation as unix for accept() when close_accept()
// is considered.
//
// In order to implement close_accept() and timeouts, windows uses
// event handles. An acceptor-specific abort event is created which
// will only get set in close_accept(), and it will never be un-set.
// Additionally, another acceptor-specific event is associated with the
// FD_ACCEPT network event.
//
// These two events are then passed to WaitForMultipleEvents to see
// which one triggers first, and the timeout passed to this function is
// the local timeout for the acceptor.
//
// If the wait times out, then the accept timed out. If the wait
// succeeds with the abort event, then we were closed, and if the wait
// succeeds otherwise, then we do a nonblocking poll via `accept` to
// see if we can accept a connection. The connection is candidate to be
// stolen, so we do all of this in a loop as well.
let events = [self.inner.abort.handle(), self.inner.accept.handle()];
while!self.inner.closed.load(Ordering::SeqCst) {
let ms = if self.deadline == 0 {
c::WSA_INFINITE as u64
} else {
let now = timer::now();
if self.deadline < now {0} else {self.deadline - now}
};
let ret = unsafe {
c::WSAWaitForMultipleEvents(2, events.as_ptr(), libc::FALSE,
ms as libc::DWORD, libc::FALSE)
};
match ret {
c::WSA_WAIT_TIMEOUT => {
return Err(timeout("accept timed out"))
}
c::WSA_WAIT_FAILED => return Err(last_net_error()),
c::WSA_WAIT_EVENT_0 => break,
n => assert_eq!(n, c::WSA_WAIT_EVENT_0 + 1),
}
let mut wsaevents: c::WSANETWORKEVENTS = unsafe { mem::zeroed() };
let ret = unsafe {
c::WSAEnumNetworkEvents(self.socket(), events[1], &mut wsaevents)
};
if ret!= 0 { return Err(last_net_error()) }
if wsaevents.lNetworkEvents & c::FD_ACCEPT == 0 { continue }
match unsafe {
libc::accept(self.socket(), ptr::null_mut(), ptr::null_mut())
} {
-1 if wouldblock() => {}
-1 => return Err(last_net_error()),
// Accepted sockets inherit the same properties as the caller,
// so we need to deregister our event and switch the socket back
// to blocking mode
socket => {
let stream = TcpStream::new(socket);
let ret = unsafe {
c::WSAEventSelect(socket, events[1], 0)
};
if ret!= 0 { return Err(last_net_error()) }
set_nonblocking(socket, false);
return Ok(stream)
}
}
}
Err(eof())
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn close_accept(&mut self) -> IoResult<()> {
self.inner.closed.store(true, Ordering::SeqCst);
let ret = unsafe { c::WSASetEvent(self.inner.abort.handle()) };
if ret == libc::TRUE {
Ok(())
} else {
Err(last_net_error())
}
}
}
impl Clone for TcpAcceptor {
fn clone(&self) -> TcpAcceptor {
TcpAcceptor {
inner: self.inner.clone(),
deadline: 0,
}
}
}
|
Event
|
identifier_name
|
tcp.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(deprecated)]
use prelude::v1::*;
use old_io::net::ip;
use old_io::IoResult;
use libc;
use mem;
use ptr;
use super::{last_error, last_net_error, sock_t};
use sync::Arc;
use sync::atomic::{AtomicBool, Ordering};
use sys::{self, c, set_nonblocking, wouldblock, timer};
use sys_common::{timeout, eof, net};
pub use sys_common::net::TcpStream;
pub struct Event(c::WSAEVENT);
unsafe impl Send for Event {}
unsafe impl Sync for Event {}
impl Event {
pub fn new() -> IoResult<Event> {
let event = unsafe { c::WSACreateEvent() };
if event == c::WSA_INVALID_EVENT {
Err(super::last_error())
} else {
Ok(Event(event))
}
}
pub fn handle(&self) -> c::WSAEVENT { let Event(handle) = *self; handle }
}
impl Drop for Event {
fn drop(&mut self) {
unsafe { let _ = c::WSACloseEvent(self.handle()); }
}
}
////////////////////////////////////////////////////////////////////////////////
// TCP listeners
////////////////////////////////////////////////////////////////////////////////
pub struct TcpListener { sock: sock_t }
unsafe impl Send for TcpListener {}
unsafe impl Sync for TcpListener {}
impl TcpListener {
pub fn bind(addr: ip::SocketAddr) -> IoResult<TcpListener> {
sys::init_net();
let sock = try!(net::socket(addr, libc::SOCK_STREAM));
let ret = TcpListener { sock: sock };
let mut storage = unsafe { mem::zeroed() };
let len = net::addr_to_sockaddr(addr, &mut storage);
let addrp = &storage as *const _ as *const libc::sockaddr;
match unsafe { libc::bind(sock, addrp, len) } {
-1 => Err(last_net_error()),
_ => Ok(ret),
}
}
pub fn socket(&self) -> sock_t { self.sock }
pub fn listen(self, backlog: int) -> IoResult<TcpAcceptor> {
match unsafe { libc::listen(self.socket(), backlog as libc::c_int) } {
-1 => Err(last_net_error()),
_ => {
let accept = try!(Event::new());
let ret = unsafe {
c::WSAEventSelect(self.socket(), accept.handle(), c::FD_ACCEPT)
};
if ret!= 0 {
return Err(last_net_error())
}
Ok(TcpAcceptor {
inner: Arc::new(AcceptorInner {
listener: self,
abort: try!(Event::new()),
accept: accept,
closed: AtomicBool::new(false),
}),
deadline: 0,
})
}
}
}
pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> {
net::sockname(self.socket(), libc::getsockname)
}
}
impl Drop for TcpListener {
fn drop(&mut self) {
unsafe { super::close_sock(self.sock); }
}
}
pub struct TcpAcceptor {
inner: Arc<AcceptorInner>,
deadline: u64,
}
struct AcceptorInner {
listener: TcpListener,
abort: Event,
accept: Event,
closed: AtomicBool,
}
unsafe impl Sync for AcceptorInner {}
impl TcpAcceptor {
pub fn socket(&self) -> sock_t { self.inner.listener.socket() }
pub fn accept(&mut self) -> IoResult<TcpStream> {
// Unlink unix, windows cannot invoke `select` on arbitrary file
// descriptors like pipes, only sockets. Consequently, windows cannot
// use the same implementation as unix for accept() when close_accept()
// is considered.
//
// In order to implement close_accept() and timeouts, windows uses
// event handles. An acceptor-specific abort event is created which
// will only get set in close_accept(), and it will never be un-set.
// Additionally, another acceptor-specific event is associated with the
// FD_ACCEPT network event.
//
// These two events are then passed to WaitForMultipleEvents to see
// which one triggers first, and the timeout passed to this function is
// the local timeout for the acceptor.
//
// If the wait times out, then the accept timed out. If the wait
// succeeds with the abort event, then we were closed, and if the wait
// succeeds otherwise, then we do a nonblocking poll via `accept` to
// see if we can accept a connection. The connection is candidate to be
// stolen, so we do all of this in a loop as well.
let events = [self.inner.abort.handle(), self.inner.accept.handle()];
while!self.inner.closed.load(Ordering::SeqCst) {
let ms = if self.deadline == 0 {
c::WSA_INFINITE as u64
} else {
let now = timer::now();
if self.deadline < now {0} else {self.deadline - now}
};
let ret = unsafe {
c::WSAWaitForMultipleEvents(2, events.as_ptr(), libc::FALSE,
ms as libc::DWORD, libc::FALSE)
};
match ret {
c::WSA_WAIT_TIMEOUT => {
return Err(timeout("accept timed out"))
}
c::WSA_WAIT_FAILED => return Err(last_net_error()),
c::WSA_WAIT_EVENT_0 => break,
n => assert_eq!(n, c::WSA_WAIT_EVENT_0 + 1),
}
let mut wsaevents: c::WSANETWORKEVENTS = unsafe { mem::zeroed() };
let ret = unsafe {
c::WSAEnumNetworkEvents(self.socket(), events[1], &mut wsaevents)
};
if ret!= 0 { return Err(last_net_error()) }
if wsaevents.lNetworkEvents & c::FD_ACCEPT == 0 { continue }
match unsafe {
libc::accept(self.socket(), ptr::null_mut(), ptr::null_mut())
} {
-1 if wouldblock() => {}
-1 => return Err(last_net_error()),
// Accepted sockets inherit the same properties as the caller,
// so we need to deregister our event and switch the socket back
// to blocking mode
socket => {
let stream = TcpStream::new(socket);
let ret = unsafe {
c::WSAEventSelect(socket, events[1], 0)
};
if ret!= 0 { return Err(last_net_error()) }
set_nonblocking(socket, false);
return Ok(stream)
}
}
}
Err(eof())
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn close_accept(&mut self) -> IoResult<()> {
self.inner.closed.store(true, Ordering::SeqCst);
let ret = unsafe { c::WSASetEvent(self.inner.abort.handle()) };
if ret == libc::TRUE {
Ok(())
} else {
Err(last_net_error())
}
}
}
impl Clone for TcpAcceptor {
fn clone(&self) -> TcpAcceptor
|
}
|
{
TcpAcceptor {
inner: self.inner.clone(),
deadline: 0,
}
}
|
identifier_body
|
tcp.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(deprecated)]
use prelude::v1::*;
use old_io::net::ip;
use old_io::IoResult;
use libc;
use mem;
use ptr;
use super::{last_error, last_net_error, sock_t};
use sync::Arc;
use sync::atomic::{AtomicBool, Ordering};
use sys::{self, c, set_nonblocking, wouldblock, timer};
use sys_common::{timeout, eof, net};
pub use sys_common::net::TcpStream;
pub struct Event(c::WSAEVENT);
unsafe impl Send for Event {}
unsafe impl Sync for Event {}
impl Event {
pub fn new() -> IoResult<Event> {
let event = unsafe { c::WSACreateEvent() };
if event == c::WSA_INVALID_EVENT {
Err(super::last_error())
} else {
Ok(Event(event))
}
}
pub fn handle(&self) -> c::WSAEVENT { let Event(handle) = *self; handle }
}
impl Drop for Event {
fn drop(&mut self) {
unsafe { let _ = c::WSACloseEvent(self.handle()); }
}
}
////////////////////////////////////////////////////////////////////////////////
// TCP listeners
////////////////////////////////////////////////////////////////////////////////
pub struct TcpListener { sock: sock_t }
unsafe impl Send for TcpListener {}
unsafe impl Sync for TcpListener {}
impl TcpListener {
pub fn bind(addr: ip::SocketAddr) -> IoResult<TcpListener> {
sys::init_net();
let sock = try!(net::socket(addr, libc::SOCK_STREAM));
let ret = TcpListener { sock: sock };
let mut storage = unsafe { mem::zeroed() };
let len = net::addr_to_sockaddr(addr, &mut storage);
let addrp = &storage as *const _ as *const libc::sockaddr;
match unsafe { libc::bind(sock, addrp, len) } {
-1 => Err(last_net_error()),
_ => Ok(ret),
}
}
pub fn socket(&self) -> sock_t { self.sock }
pub fn listen(self, backlog: int) -> IoResult<TcpAcceptor> {
match unsafe { libc::listen(self.socket(), backlog as libc::c_int) } {
-1 => Err(last_net_error()),
_ => {
let accept = try!(Event::new());
let ret = unsafe {
c::WSAEventSelect(self.socket(), accept.handle(), c::FD_ACCEPT)
};
if ret!= 0 {
return Err(last_net_error())
}
Ok(TcpAcceptor {
inner: Arc::new(AcceptorInner {
listener: self,
abort: try!(Event::new()),
accept: accept,
closed: AtomicBool::new(false),
}),
deadline: 0,
})
}
}
}
pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> {
net::sockname(self.socket(), libc::getsockname)
}
}
impl Drop for TcpListener {
fn drop(&mut self) {
unsafe { super::close_sock(self.sock); }
}
}
pub struct TcpAcceptor {
inner: Arc<AcceptorInner>,
deadline: u64,
}
struct AcceptorInner {
listener: TcpListener,
abort: Event,
accept: Event,
closed: AtomicBool,
}
unsafe impl Sync for AcceptorInner {}
impl TcpAcceptor {
pub fn socket(&self) -> sock_t { self.inner.listener.socket() }
pub fn accept(&mut self) -> IoResult<TcpStream> {
// Unlink unix, windows cannot invoke `select` on arbitrary file
// descriptors like pipes, only sockets. Consequently, windows cannot
// use the same implementation as unix for accept() when close_accept()
// is considered.
//
// In order to implement close_accept() and timeouts, windows uses
// event handles. An acceptor-specific abort event is created which
// will only get set in close_accept(), and it will never be un-set.
// Additionally, another acceptor-specific event is associated with the
// FD_ACCEPT network event.
//
// These two events are then passed to WaitForMultipleEvents to see
// which one triggers first, and the timeout passed to this function is
// the local timeout for the acceptor.
//
// If the wait times out, then the accept timed out. If the wait
// succeeds with the abort event, then we were closed, and if the wait
// succeeds otherwise, then we do a nonblocking poll via `accept` to
// see if we can accept a connection. The connection is candidate to be
// stolen, so we do all of this in a loop as well.
let events = [self.inner.abort.handle(), self.inner.accept.handle()];
while!self.inner.closed.load(Ordering::SeqCst) {
let ms = if self.deadline == 0 {
c::WSA_INFINITE as u64
} else {
let now = timer::now();
if self.deadline < now {0} else {self.deadline - now}
};
let ret = unsafe {
c::WSAWaitForMultipleEvents(2, events.as_ptr(), libc::FALSE,
ms as libc::DWORD, libc::FALSE)
};
match ret {
c::WSA_WAIT_TIMEOUT => {
return Err(timeout("accept timed out"))
}
c::WSA_WAIT_FAILED => return Err(last_net_error()),
c::WSA_WAIT_EVENT_0 => break,
n => assert_eq!(n, c::WSA_WAIT_EVENT_0 + 1),
}
let mut wsaevents: c::WSANETWORKEVENTS = unsafe { mem::zeroed() };
let ret = unsafe {
c::WSAEnumNetworkEvents(self.socket(), events[1], &mut wsaevents)
};
if ret!= 0 { return Err(last_net_error()) }
if wsaevents.lNetworkEvents & c::FD_ACCEPT == 0 { continue }
match unsafe {
libc::accept(self.socket(), ptr::null_mut(), ptr::null_mut())
} {
-1 if wouldblock() => {}
-1 => return Err(last_net_error()),
// Accepted sockets inherit the same properties as the caller,
|
let ret = unsafe {
c::WSAEventSelect(socket, events[1], 0)
};
if ret!= 0 { return Err(last_net_error()) }
set_nonblocking(socket, false);
return Ok(stream)
}
}
}
Err(eof())
}
pub fn set_timeout(&mut self, timeout: Option<u64>) {
self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn close_accept(&mut self) -> IoResult<()> {
self.inner.closed.store(true, Ordering::SeqCst);
let ret = unsafe { c::WSASetEvent(self.inner.abort.handle()) };
if ret == libc::TRUE {
Ok(())
} else {
Err(last_net_error())
}
}
}
impl Clone for TcpAcceptor {
fn clone(&self) -> TcpAcceptor {
TcpAcceptor {
inner: self.inner.clone(),
deadline: 0,
}
}
}
|
// so we need to deregister our event and switch the socket back
// to blocking mode
socket => {
let stream = TcpStream::new(socket);
|
random_line_split
|
card.rs
|
use game_state::GameState;
use minion_card::UID;
use client_option::{OptionGenerator, ClientOption, OptionType};
use tags_list::TARGET;
use controller::Controller;
use hlua;
#[derive(Copy, Clone)]
#[allow(dead_code)]
pub enum ECardType {
Minion,
Spell,
Weapon,
}
#[derive(Clone)]
pub struct Card {
cost: u8,
card_type: ECardType,
id: String,
uid: UID,
name: String,
// for play minion cards this is the uid of the minion
// for spells this is the rhai file that executes the spell
content: String,
}
impl Card {
pub fn new(cost: u8,
card_type: ECardType,
id: String,
uid: UID,
name: String,
content: String)
-> Card {
Card {
cost: cost,
card_type: card_type,
id: id,
uid: uid,
name: name,
content: content,
}
}
pub fn get_cost(&self) -> u8 {
self.cost.clone()
}
pub fn get_uid(&self) -> u32 {
self.uid.clone()
}
pub fn _get_name(&self) -> String {
self.name.clone()
}
pub fn get_card_type(&self) -> ECardType {
self.card_type
}
pub fn _get_id(&self) -> String
|
pub fn get_content(&self) -> String {
self.content.clone()
}
// fn set_cost(&mut self, cost: u16){
// self.cost = cost;
// }
//
// fn set_uid(&mut self, uid: String){
// self.uid = uid;
// }
//
// fn set_name(&mut self, name: String){
// self.name = name;
// }
//
// fn set_set(&mut self, set: String){
// self.set = set;
// }
//
// fn set_card_type(&mut self, card_type: ECardType){
// self.card_type = card_type;
// }
//
// fn set_id(&mut self, id: String){
// self.id = id;
// }
//
}
impl OptionGenerator for Card {
fn generate_options(&self,
game_state: &mut GameState,
controller: &Controller)
-> Vec<ClientOption> {
if controller.get_mana() >= self.cost {
if!self.content.contains("default") {
let minion = game_state.get_minion(self.content.parse().unwrap()).unwrap().clone();
if minion.has_tag(TARGET.to_string()) {
let start = game_state.run_lua_statement::<hlua::LuaTable<_>>(&minion.get_function("target_function".to_string()).unwrap(), false);
match start {
Some(mut start) => {
return start.iter::<i32, ClientOption>()
.filter_map(|e| e)
.map(|(_, v)| v)
.collect();
}
None => {
return vec![];
}
}
} else {
let mut co = vec![];
co.push(ClientOption::new(self.uid, 0, OptionType::EPlayCard));
return co;
}
}
let mut co = vec![];
co.push(ClientOption::new(self.uid, 0, OptionType::EPlayCard));
return co;
}
return vec![];
}
}
|
{
self.id.clone()
}
|
identifier_body
|
card.rs
|
use game_state::GameState;
use minion_card::UID;
use client_option::{OptionGenerator, ClientOption, OptionType};
use tags_list::TARGET;
use controller::Controller;
use hlua;
#[derive(Copy, Clone)]
#[allow(dead_code)]
pub enum ECardType {
Minion,
Spell,
Weapon,
}
#[derive(Clone)]
pub struct Card {
cost: u8,
card_type: ECardType,
id: String,
uid: UID,
name: String,
// for play minion cards this is the uid of the minion
// for spells this is the rhai file that executes the spell
content: String,
}
impl Card {
pub fn new(cost: u8,
card_type: ECardType,
id: String,
uid: UID,
name: String,
content: String)
-> Card {
Card {
cost: cost,
card_type: card_type,
id: id,
uid: uid,
name: name,
content: content,
}
}
pub fn get_cost(&self) -> u8 {
self.cost.clone()
}
pub fn
|
(&self) -> u32 {
self.uid.clone()
}
pub fn _get_name(&self) -> String {
self.name.clone()
}
pub fn get_card_type(&self) -> ECardType {
self.card_type
}
pub fn _get_id(&self) -> String {
self.id.clone()
}
pub fn get_content(&self) -> String {
self.content.clone()
}
// fn set_cost(&mut self, cost: u16){
// self.cost = cost;
// }
//
// fn set_uid(&mut self, uid: String){
// self.uid = uid;
// }
//
// fn set_name(&mut self, name: String){
// self.name = name;
// }
//
// fn set_set(&mut self, set: String){
// self.set = set;
// }
//
// fn set_card_type(&mut self, card_type: ECardType){
// self.card_type = card_type;
// }
//
// fn set_id(&mut self, id: String){
// self.id = id;
// }
//
}
impl OptionGenerator for Card {
fn generate_options(&self,
game_state: &mut GameState,
controller: &Controller)
-> Vec<ClientOption> {
if controller.get_mana() >= self.cost {
if!self.content.contains("default") {
let minion = game_state.get_minion(self.content.parse().unwrap()).unwrap().clone();
if minion.has_tag(TARGET.to_string()) {
let start = game_state.run_lua_statement::<hlua::LuaTable<_>>(&minion.get_function("target_function".to_string()).unwrap(), false);
match start {
Some(mut start) => {
return start.iter::<i32, ClientOption>()
.filter_map(|e| e)
.map(|(_, v)| v)
.collect();
}
None => {
return vec![];
}
}
} else {
let mut co = vec![];
co.push(ClientOption::new(self.uid, 0, OptionType::EPlayCard));
return co;
}
}
let mut co = vec![];
co.push(ClientOption::new(self.uid, 0, OptionType::EPlayCard));
return co;
}
return vec![];
}
}
|
get_uid
|
identifier_name
|
card.rs
|
use game_state::GameState;
use minion_card::UID;
use client_option::{OptionGenerator, ClientOption, OptionType};
use tags_list::TARGET;
use controller::Controller;
use hlua;
#[derive(Copy, Clone)]
#[allow(dead_code)]
pub enum ECardType {
Minion,
|
Weapon,
}
#[derive(Clone)]
pub struct Card {
cost: u8,
card_type: ECardType,
id: String,
uid: UID,
name: String,
// for play minion cards this is the uid of the minion
// for spells this is the rhai file that executes the spell
content: String,
}
impl Card {
pub fn new(cost: u8,
card_type: ECardType,
id: String,
uid: UID,
name: String,
content: String)
-> Card {
Card {
cost: cost,
card_type: card_type,
id: id,
uid: uid,
name: name,
content: content,
}
}
pub fn get_cost(&self) -> u8 {
self.cost.clone()
}
pub fn get_uid(&self) -> u32 {
self.uid.clone()
}
pub fn _get_name(&self) -> String {
self.name.clone()
}
pub fn get_card_type(&self) -> ECardType {
self.card_type
}
pub fn _get_id(&self) -> String {
self.id.clone()
}
pub fn get_content(&self) -> String {
self.content.clone()
}
// fn set_cost(&mut self, cost: u16){
// self.cost = cost;
// }
//
// fn set_uid(&mut self, uid: String){
// self.uid = uid;
// }
//
// fn set_name(&mut self, name: String){
// self.name = name;
// }
//
// fn set_set(&mut self, set: String){
// self.set = set;
// }
//
// fn set_card_type(&mut self, card_type: ECardType){
// self.card_type = card_type;
// }
//
// fn set_id(&mut self, id: String){
// self.id = id;
// }
//
}
impl OptionGenerator for Card {
fn generate_options(&self,
game_state: &mut GameState,
controller: &Controller)
-> Vec<ClientOption> {
if controller.get_mana() >= self.cost {
if!self.content.contains("default") {
let minion = game_state.get_minion(self.content.parse().unwrap()).unwrap().clone();
if minion.has_tag(TARGET.to_string()) {
let start = game_state.run_lua_statement::<hlua::LuaTable<_>>(&minion.get_function("target_function".to_string()).unwrap(), false);
match start {
Some(mut start) => {
return start.iter::<i32, ClientOption>()
.filter_map(|e| e)
.map(|(_, v)| v)
.collect();
}
None => {
return vec![];
}
}
} else {
let mut co = vec![];
co.push(ClientOption::new(self.uid, 0, OptionType::EPlayCard));
return co;
}
}
let mut co = vec![];
co.push(ClientOption::new(self.uid, 0, OptionType::EPlayCard));
return co;
}
return vec![];
}
}
|
Spell,
|
random_line_split
|
mem.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.
//! Basic functions for dealing with memory
//!
//! This module contains functions for querying the size and alignment of
//! types, initializing and manipulating memory.
use intrinsics;
use ptr;
pub use intrinsics::transmute;
/// Moves a thing into the void.
///
/// The forget function will take ownership of the provided value but neglect
/// to run any required cleanup or memory management operations on it.
///
/// This function is the unsafe version of the `drop` function because it does
/// not run any destructors.
#[stable]
pub use intrinsics::forget;
/// Returns the size of a type in bytes.
#[inline]
#[stable]
pub fn size_of<T>() -> uint {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the type that `_val` points to in bytes.
#[inline]
#[stable]
pub fn size_of_val<T>(_val: &T) -> uint {
size_of::<T>()
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller
/// than the preferred alignment.
#[inline]
#[stable]
pub fn min_align_of<T>() -> uint {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that
/// `_val` points to
#[inline]
#[stable]
pub fn min_align_of_val<T>(_val: &T) -> uint {
min_align_of::<T>()
}
/// Returns the alignment in memory for a type.
///
/// This function will return the alignment, in bytes, of a type in memory. If
/// the alignment returned is adhered to, then the type is guaranteed to
/// function properly.
#[inline]
#[stable]
pub fn align_of<T>() -> uint {
// We use the preferred alignment as the default alignment for a type. This
// appears to be what clang migrated towards as well:
//
// http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20110725/044411.html
unsafe { intrinsics::pref_align_of::<T>() }
}
/// Returns the alignment of the type of the value that `_val` points to.
///
/// This is similar to `align_of`, but function will properly handle types such
/// as trait objects (in the future), returning the alignment for an arbitrary
/// value at runtime.
#[inline]
#[stable]
pub fn align_of_val<T>(_val: &T) -> uint {
align_of::<T>()
}
/// Create a value initialized to zero.
///
/// This function is similar to allocating space for a local variable and
/// zeroing it out (an unsafe operation).
///
/// Care must be taken when using this function, if the type `T` has a
/// destructor and the value falls out of scope (due to unwinding or returning)
/// before being initialized, then the destructor will run on zeroed
/// data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
#[inline]
#[stable]
pub unsafe fn zeroed<T>() -> T {
intrinsics::init()
}
/// Create an uninitialized value.
///
/// Care must be taken when using this function, if the type `T` has a
/// destructor and the value falls out of scope (due to unwinding or returning)
/// before being initialized, then the destructor will run on uninitialized
/// data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
#[inline]
#[stable]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without
/// deinitialising or copying either one.
#[inline]
#[stable]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
ptr::copy_nonoverlapping_memory(x, &*y, 1);
ptr::copy_nonoverlapping_memory(y, &t, 1);
// y and t now point to the same thing, but we need to completely forget `t`
// because it's no longer relevant.
forget(t);
}
}
/// Replace the value at a mutable location with a new one, returning the old
/// value, without deinitialising or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value
|
/// one field of a struct by replacing it with another value. The normal approach
/// doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// // error: cannot move out of dereference of `&mut`-pointer
/// let buf = self.buf;
/// self.buf = Vec::new();
/// buf
/// }
/// }
/// ```
///
/// Note that `T` does not necessarily implement `Clone`, so it can't even
/// clone and reset `self.buf`. But `replace` can be used to disassociate
/// the original value of `self.buf` from `self`, allowing it to be returned:
///
/// ```rust
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// use std::mem::replace;
/// replace(&mut self.buf, Vec::new())
/// }
/// }
/// ```
#[inline]
#[stable]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
}
/// Disposes of a value.
///
/// This function can be used to destroy any value by allowing `drop` to take
/// ownership of its argument.
///
/// # Example
///
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1i);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
///
/// let borrow = x.borrow();
/// println!("{}", *borrow);
/// ```
#[inline]
#[stable]
pub fn drop<T>(_x: T) { }
/// Interprets `src` as `&U`, and then reads `src` without moving the contained
/// value.
///
/// This function will unsafely assume the pointer `src` is valid for
/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
/// will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers undefined behavior if `U` is larger than
/// `T`.
#[inline]
#[stable]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
ptr::read(src as *const T as *const U)
}
/// Transforms lifetime of the second pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
questionable utility"]
pub unsafe fn copy_lifetime<'a, S, T:'a>(_ptr: &'a S, ptr: &T) -> &'a T {
transmute(ptr)
}
/// Transforms lifetime of the second mutable pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
questionable utility"]
pub unsafe fn copy_mut_lifetime<'a, S, T:'a>(_ptr: &'a mut S,
ptr: &mut T) -> &'a mut T {
transmute(ptr)
}
|
/// in a mutable location. For example, this function allows consumption of
|
random_line_split
|
mem.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.
//! Basic functions for dealing with memory
//!
//! This module contains functions for querying the size and alignment of
//! types, initializing and manipulating memory.
use intrinsics;
use ptr;
pub use intrinsics::transmute;
/// Moves a thing into the void.
///
/// The forget function will take ownership of the provided value but neglect
/// to run any required cleanup or memory management operations on it.
///
/// This function is the unsafe version of the `drop` function because it does
/// not run any destructors.
#[stable]
pub use intrinsics::forget;
/// Returns the size of a type in bytes.
#[inline]
#[stable]
pub fn
|
<T>() -> uint {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the type that `_val` points to in bytes.
#[inline]
#[stable]
pub fn size_of_val<T>(_val: &T) -> uint {
size_of::<T>()
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller
/// than the preferred alignment.
#[inline]
#[stable]
pub fn min_align_of<T>() -> uint {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that
/// `_val` points to
#[inline]
#[stable]
pub fn min_align_of_val<T>(_val: &T) -> uint {
min_align_of::<T>()
}
/// Returns the alignment in memory for a type.
///
/// This function will return the alignment, in bytes, of a type in memory. If
/// the alignment returned is adhered to, then the type is guaranteed to
/// function properly.
#[inline]
#[stable]
pub fn align_of<T>() -> uint {
// We use the preferred alignment as the default alignment for a type. This
// appears to be what clang migrated towards as well:
//
// http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20110725/044411.html
unsafe { intrinsics::pref_align_of::<T>() }
}
/// Returns the alignment of the type of the value that `_val` points to.
///
/// This is similar to `align_of`, but function will properly handle types such
/// as trait objects (in the future), returning the alignment for an arbitrary
/// value at runtime.
#[inline]
#[stable]
pub fn align_of_val<T>(_val: &T) -> uint {
align_of::<T>()
}
/// Create a value initialized to zero.
///
/// This function is similar to allocating space for a local variable and
/// zeroing it out (an unsafe operation).
///
/// Care must be taken when using this function, if the type `T` has a
/// destructor and the value falls out of scope (due to unwinding or returning)
/// before being initialized, then the destructor will run on zeroed
/// data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
#[inline]
#[stable]
pub unsafe fn zeroed<T>() -> T {
intrinsics::init()
}
/// Create an uninitialized value.
///
/// Care must be taken when using this function, if the type `T` has a
/// destructor and the value falls out of scope (due to unwinding or returning)
/// before being initialized, then the destructor will run on uninitialized
/// data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
#[inline]
#[stable]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without
/// deinitialising or copying either one.
#[inline]
#[stable]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
ptr::copy_nonoverlapping_memory(x, &*y, 1);
ptr::copy_nonoverlapping_memory(y, &t, 1);
// y and t now point to the same thing, but we need to completely forget `t`
// because it's no longer relevant.
forget(t);
}
}
/// Replace the value at a mutable location with a new one, returning the old
/// value, without deinitialising or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value
/// in a mutable location. For example, this function allows consumption of
/// one field of a struct by replacing it with another value. The normal approach
/// doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// // error: cannot move out of dereference of `&mut`-pointer
/// let buf = self.buf;
/// self.buf = Vec::new();
/// buf
/// }
/// }
/// ```
///
/// Note that `T` does not necessarily implement `Clone`, so it can't even
/// clone and reset `self.buf`. But `replace` can be used to disassociate
/// the original value of `self.buf` from `self`, allowing it to be returned:
///
/// ```rust
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// use std::mem::replace;
/// replace(&mut self.buf, Vec::new())
/// }
/// }
/// ```
#[inline]
#[stable]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
}
/// Disposes of a value.
///
/// This function can be used to destroy any value by allowing `drop` to take
/// ownership of its argument.
///
/// # Example
///
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1i);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
///
/// let borrow = x.borrow();
/// println!("{}", *borrow);
/// ```
#[inline]
#[stable]
pub fn drop<T>(_x: T) { }
/// Interprets `src` as `&U`, and then reads `src` without moving the contained
/// value.
///
/// This function will unsafely assume the pointer `src` is valid for
/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
/// will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers undefined behavior if `U` is larger than
/// `T`.
#[inline]
#[stable]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
ptr::read(src as *const T as *const U)
}
/// Transforms lifetime of the second pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
questionable utility"]
pub unsafe fn copy_lifetime<'a, S, T:'a>(_ptr: &'a S, ptr: &T) -> &'a T {
transmute(ptr)
}
/// Transforms lifetime of the second mutable pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
questionable utility"]
pub unsafe fn copy_mut_lifetime<'a, S, T:'a>(_ptr: &'a mut S,
ptr: &mut T) -> &'a mut T {
transmute(ptr)
}
|
size_of
|
identifier_name
|
mem.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.
//! Basic functions for dealing with memory
//!
//! This module contains functions for querying the size and alignment of
//! types, initializing and manipulating memory.
use intrinsics;
use ptr;
pub use intrinsics::transmute;
/// Moves a thing into the void.
///
/// The forget function will take ownership of the provided value but neglect
/// to run any required cleanup or memory management operations on it.
///
/// This function is the unsafe version of the `drop` function because it does
/// not run any destructors.
#[stable]
pub use intrinsics::forget;
/// Returns the size of a type in bytes.
#[inline]
#[stable]
pub fn size_of<T>() -> uint {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the type that `_val` points to in bytes.
#[inline]
#[stable]
pub fn size_of_val<T>(_val: &T) -> uint {
size_of::<T>()
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller
/// than the preferred alignment.
#[inline]
#[stable]
pub fn min_align_of<T>() -> uint {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that
/// `_val` points to
#[inline]
#[stable]
pub fn min_align_of_val<T>(_val: &T) -> uint {
min_align_of::<T>()
}
/// Returns the alignment in memory for a type.
///
/// This function will return the alignment, in bytes, of a type in memory. If
/// the alignment returned is adhered to, then the type is guaranteed to
/// function properly.
#[inline]
#[stable]
pub fn align_of<T>() -> uint {
// We use the preferred alignment as the default alignment for a type. This
// appears to be what clang migrated towards as well:
//
// http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20110725/044411.html
unsafe { intrinsics::pref_align_of::<T>() }
}
/// Returns the alignment of the type of the value that `_val` points to.
///
/// This is similar to `align_of`, but function will properly handle types such
/// as trait objects (in the future), returning the alignment for an arbitrary
/// value at runtime.
#[inline]
#[stable]
pub fn align_of_val<T>(_val: &T) -> uint {
align_of::<T>()
}
/// Create a value initialized to zero.
///
/// This function is similar to allocating space for a local variable and
/// zeroing it out (an unsafe operation).
///
/// Care must be taken when using this function, if the type `T` has a
/// destructor and the value falls out of scope (due to unwinding or returning)
/// before being initialized, then the destructor will run on zeroed
/// data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
#[inline]
#[stable]
pub unsafe fn zeroed<T>() -> T {
intrinsics::init()
}
/// Create an uninitialized value.
///
/// Care must be taken when using this function, if the type `T` has a
/// destructor and the value falls out of scope (due to unwinding or returning)
/// before being initialized, then the destructor will run on uninitialized
/// data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
#[inline]
#[stable]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without
/// deinitialising or copying either one.
#[inline]
#[stable]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
ptr::copy_nonoverlapping_memory(x, &*y, 1);
ptr::copy_nonoverlapping_memory(y, &t, 1);
// y and t now point to the same thing, but we need to completely forget `t`
// because it's no longer relevant.
forget(t);
}
}
/// Replace the value at a mutable location with a new one, returning the old
/// value, without deinitialising or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value
/// in a mutable location. For example, this function allows consumption of
/// one field of a struct by replacing it with another value. The normal approach
/// doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// // error: cannot move out of dereference of `&mut`-pointer
/// let buf = self.buf;
/// self.buf = Vec::new();
/// buf
/// }
/// }
/// ```
///
/// Note that `T` does not necessarily implement `Clone`, so it can't even
/// clone and reset `self.buf`. But `replace` can be used to disassociate
/// the original value of `self.buf` from `self`, allowing it to be returned:
///
/// ```rust
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// use std::mem::replace;
/// replace(&mut self.buf, Vec::new())
/// }
/// }
/// ```
#[inline]
#[stable]
pub fn replace<T>(dest: &mut T, mut src: T) -> T
|
/// Disposes of a value.
///
/// This function can be used to destroy any value by allowing `drop` to take
/// ownership of its argument.
///
/// # Example
///
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1i);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
///
/// let borrow = x.borrow();
/// println!("{}", *borrow);
/// ```
#[inline]
#[stable]
pub fn drop<T>(_x: T) { }
/// Interprets `src` as `&U`, and then reads `src` without moving the contained
/// value.
///
/// This function will unsafely assume the pointer `src` is valid for
/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
/// will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers undefined behavior if `U` is larger than
/// `T`.
#[inline]
#[stable]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
ptr::read(src as *const T as *const U)
}
/// Transforms lifetime of the second pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
questionable utility"]
pub unsafe fn copy_lifetime<'a, S, T:'a>(_ptr: &'a S, ptr: &T) -> &'a T {
transmute(ptr)
}
/// Transforms lifetime of the second mutable pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
questionable utility"]
pub unsafe fn copy_mut_lifetime<'a, S, T:'a>(_ptr: &'a mut S,
ptr: &mut T) -> &'a mut T {
transmute(ptr)
}
|
{
swap(dest, &mut src);
src
}
|
identifier_body
|
dump.rs
|
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn main() {
let stdout = io::stdout();
let mut out = stdout.lock();
for arg in env::args().skip(1) {
match File::open(&arg) {
Ok(ref mut file) => dump_file(&mut out, file),
Err(err) => writeln!(out, "Could not open {}: {}", arg, err).unwrap()
}
}
}
fn dump_file<F,W>(mut out: &mut W, mut file: &mut F) where F: Read + Seek, W: Write {
let mut magic = [0u8; 8];
let mut template_offset = [0u8; 8];
file.read(&mut magic[..]).unwrap();
file.read(&mut template_offset[..]).unwrap();
if &magic[..]!= b"NETFLO00" {
writeln!(out, "Invalid file magic: {:?}.", magic).unwrap();
return;
}
let template_offset: u64 = unsafe { mem::transmute::<[u8; 8], u64>(template_offset).to_be()};
writeln!(out, "template_offset: {}", template_offset).unwrap();
if template_offset == 0 {
writeln!(out, "Incomplete file, skipping").unwrap();
return;
}
let sought = file.seek(io::SeekFrom::Current(template_offset as i64)).unwrap();
assert_eq!(sought, template_offset + 16);
let mut extractors: HashMap<u16, FlowRecordExtractor> = HashMap::new();
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
if let Ok(_) = file.read_exact(&mut tid[..]) {
file.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let template_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
writeln!(out, "template_id: {}, template_length: {}", template_id, template_length).unwrap();
let mut template_raw = Vec::with_capacity(template_length);
file.take(template_length as u64).read_to_end(&mut template_raw).unwrap();
//println!("raw template: {:?}", &template_raw[..]);
let template: DataTemplate = DataTemplate {
template_id: template_id,
field_count: (template_length / 4) as u16,
fields: TemplateFieldIter { raw: &template_raw[..]}
};
extractors.insert(template_id, template.build_extractor());
// for (_len, field) in template.fields.clone() {
// println!("\tfield: {:?} ", field);
// }
} else {
break;
}
}
file.seek(io::SeekFrom::Start(16)).unwrap();
let mut records = ZlibDecoder::new(file.take(template_offset));
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
let mut buf = [0u8; 2048];
if let Ok(_) = records.read_exact(&mut tid[..]) {
records.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let record_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
records.read_exact(&mut buf[..record_length]).unwrap();
// println!("record template id: {}", template_id);
// println!("record length: {}", record_length);
let data_records = DataRecords{ template_id: template_id, raw: &buf[..record_length]};
if let Some(extractor) = extractors.get(&template_id) {
for record in extractor.records(&data_records) {
// writeln!(out, "record: {:?}", record).unwrap();
print_record(&mut out, &record);
}
}
} else {
break;
}
}
}
fn print_record<W>(w: &mut W, rec: &Record) where W: Write
|
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
let destination_ip = rec.destination_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.destination_ipv6_address()
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
// let packet_time = header.seconds() as u64 * 1000;
// let sys_uptime = header.sys_uptime() as u64;
// let boot_time = packet_time - sys_uptime;
let flow_start = rec.flow_start_sys_uptime().unwrap_or(0) as u64;
let flow_end = rec.flow_end_sys_uptime().unwrap_or(0) as u64;
let duration = flow_end - flow_start;
// let start = time::at_utc(time::Timespec{ sec: (flow_start / 1000) as i64, nsec: 0});
//let end = time::at_utc(time::Timespec{ sec: (flow_end / 1000) as i64, nsec: 0});
writeln!(w, "{:>5.1}s {:6} bytes {:5} pkts {:6} {} -> {}",
// start.rfc3339(),
(duration as f64) / 1000.0,
rec.octet_delta_count().unwrap_or(0),
rec.packet_delta_count().unwrap_or(0),
protocol_name,
SocketAddr::new(source_ip,rec.source_transport_port().unwrap_or(0)),
SocketAddr::new(destination_ip,rec.destination_transport_port().unwrap_or(0)),
).unwrap();
}
|
{
let strbuf: String;
let protocol_name = match rec.protocol_identifier() {
Some(1) => "ICMP",
Some(4) => "IPIP",
Some(6) => "TCP",
Some(17) => "UDP",
Some(41) => "IP6IP",
Some(47) => "GRE",
Some(50) => "ESP",
Some(58) => "ICMP",
Some(n) => {
strbuf = format!("{}", n);
&strbuf
},
_ => return
};
let source_ip = rec.source_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.source_ipv6_address()
|
identifier_body
|
dump.rs
|
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn
|
() {
let stdout = io::stdout();
let mut out = stdout.lock();
for arg in env::args().skip(1) {
match File::open(&arg) {
Ok(ref mut file) => dump_file(&mut out, file),
Err(err) => writeln!(out, "Could not open {}: {}", arg, err).unwrap()
}
}
}
fn dump_file<F,W>(mut out: &mut W, mut file: &mut F) where F: Read + Seek, W: Write {
let mut magic = [0u8; 8];
let mut template_offset = [0u8; 8];
file.read(&mut magic[..]).unwrap();
file.read(&mut template_offset[..]).unwrap();
if &magic[..]!= b"NETFLO00" {
writeln!(out, "Invalid file magic: {:?}.", magic).unwrap();
return;
}
let template_offset: u64 = unsafe { mem::transmute::<[u8; 8], u64>(template_offset).to_be()};
writeln!(out, "template_offset: {}", template_offset).unwrap();
if template_offset == 0 {
writeln!(out, "Incomplete file, skipping").unwrap();
return;
}
let sought = file.seek(io::SeekFrom::Current(template_offset as i64)).unwrap();
assert_eq!(sought, template_offset + 16);
let mut extractors: HashMap<u16, FlowRecordExtractor> = HashMap::new();
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
if let Ok(_) = file.read_exact(&mut tid[..]) {
file.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let template_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
writeln!(out, "template_id: {}, template_length: {}", template_id, template_length).unwrap();
let mut template_raw = Vec::with_capacity(template_length);
file.take(template_length as u64).read_to_end(&mut template_raw).unwrap();
//println!("raw template: {:?}", &template_raw[..]);
let template: DataTemplate = DataTemplate {
template_id: template_id,
field_count: (template_length / 4) as u16,
fields: TemplateFieldIter { raw: &template_raw[..]}
};
extractors.insert(template_id, template.build_extractor());
// for (_len, field) in template.fields.clone() {
// println!("\tfield: {:?} ", field);
// }
} else {
break;
}
}
file.seek(io::SeekFrom::Start(16)).unwrap();
let mut records = ZlibDecoder::new(file.take(template_offset));
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
let mut buf = [0u8; 2048];
if let Ok(_) = records.read_exact(&mut tid[..]) {
records.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let record_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
records.read_exact(&mut buf[..record_length]).unwrap();
// println!("record template id: {}", template_id);
// println!("record length: {}", record_length);
let data_records = DataRecords{ template_id: template_id, raw: &buf[..record_length]};
if let Some(extractor) = extractors.get(&template_id) {
for record in extractor.records(&data_records) {
// writeln!(out, "record: {:?}", record).unwrap();
print_record(&mut out, &record);
}
}
} else {
break;
}
}
}
fn print_record<W>(w: &mut W, rec: &Record) where W: Write {
let strbuf: String;
let protocol_name = match rec.protocol_identifier() {
Some(1) => "ICMP",
Some(4) => "IPIP",
Some(6) => "TCP",
Some(17) => "UDP",
Some(41) => "IP6IP",
Some(47) => "GRE",
Some(50) => "ESP",
Some(58) => "ICMP",
Some(n) => {
strbuf = format!("{}", n);
&strbuf
},
_ => return
};
let source_ip = rec.source_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.source_ipv6_address()
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
let destination_ip = rec.destination_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.destination_ipv6_address()
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
// let packet_time = header.seconds() as u64 * 1000;
// let sys_uptime = header.sys_uptime() as u64;
// let boot_time = packet_time - sys_uptime;
let flow_start = rec.flow_start_sys_uptime().unwrap_or(0) as u64;
let flow_end = rec.flow_end_sys_uptime().unwrap_or(0) as u64;
let duration = flow_end - flow_start;
// let start = time::at_utc(time::Timespec{ sec: (flow_start / 1000) as i64, nsec: 0});
//let end = time::at_utc(time::Timespec{ sec: (flow_end / 1000) as i64, nsec: 0});
writeln!(w, "{:>5.1}s {:6} bytes {:5} pkts {:6} {} -> {}",
// start.rfc3339(),
(duration as f64) / 1000.0,
rec.octet_delta_count().unwrap_or(0),
rec.packet_delta_count().unwrap_or(0),
protocol_name,
SocketAddr::new(source_ip,rec.source_transport_port().unwrap_or(0)),
SocketAddr::new(destination_ip,rec.destination_transport_port().unwrap_or(0)),
).unwrap();
}
|
main
|
identifier_name
|
dump.rs
|
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn main() {
let stdout = io::stdout();
let mut out = stdout.lock();
for arg in env::args().skip(1) {
match File::open(&arg) {
Ok(ref mut file) => dump_file(&mut out, file),
Err(err) => writeln!(out, "Could not open {}: {}", arg, err).unwrap()
}
}
}
fn dump_file<F,W>(mut out: &mut W, mut file: &mut F) where F: Read + Seek, W: Write {
let mut magic = [0u8; 8];
let mut template_offset = [0u8; 8];
file.read(&mut magic[..]).unwrap();
file.read(&mut template_offset[..]).unwrap();
if &magic[..]!= b"NETFLO00" {
writeln!(out, "Invalid file magic: {:?}.", magic).unwrap();
return;
}
let template_offset: u64 = unsafe { mem::transmute::<[u8; 8], u64>(template_offset).to_be()};
writeln!(out, "template_offset: {}", template_offset).unwrap();
if template_offset == 0 {
writeln!(out, "Incomplete file, skipping").unwrap();
return;
}
let sought = file.seek(io::SeekFrom::Current(template_offset as i64)).unwrap();
assert_eq!(sought, template_offset + 16);
let mut extractors: HashMap<u16, FlowRecordExtractor> = HashMap::new();
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
if let Ok(_) = file.read_exact(&mut tid[..]) {
file.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let template_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
|
//println!("raw template: {:?}", &template_raw[..]);
let template: DataTemplate = DataTemplate {
template_id: template_id,
field_count: (template_length / 4) as u16,
fields: TemplateFieldIter { raw: &template_raw[..]}
};
extractors.insert(template_id, template.build_extractor());
// for (_len, field) in template.fields.clone() {
// println!("\tfield: {:?} ", field);
// }
} else {
break;
}
}
file.seek(io::SeekFrom::Start(16)).unwrap();
let mut records = ZlibDecoder::new(file.take(template_offset));
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
let mut buf = [0u8; 2048];
if let Ok(_) = records.read_exact(&mut tid[..]) {
records.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let record_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
records.read_exact(&mut buf[..record_length]).unwrap();
// println!("record template id: {}", template_id);
// println!("record length: {}", record_length);
let data_records = DataRecords{ template_id: template_id, raw: &buf[..record_length]};
if let Some(extractor) = extractors.get(&template_id) {
for record in extractor.records(&data_records) {
// writeln!(out, "record: {:?}", record).unwrap();
print_record(&mut out, &record);
}
}
} else {
break;
}
}
}
fn print_record<W>(w: &mut W, rec: &Record) where W: Write {
let strbuf: String;
let protocol_name = match rec.protocol_identifier() {
Some(1) => "ICMP",
Some(4) => "IPIP",
Some(6) => "TCP",
Some(17) => "UDP",
Some(41) => "IP6IP",
Some(47) => "GRE",
Some(50) => "ESP",
Some(58) => "ICMP",
Some(n) => {
strbuf = format!("{}", n);
&strbuf
},
_ => return
};
let source_ip = rec.source_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.source_ipv6_address()
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
let destination_ip = rec.destination_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.destination_ipv6_address()
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
// let packet_time = header.seconds() as u64 * 1000;
// let sys_uptime = header.sys_uptime() as u64;
// let boot_time = packet_time - sys_uptime;
let flow_start = rec.flow_start_sys_uptime().unwrap_or(0) as u64;
let flow_end = rec.flow_end_sys_uptime().unwrap_or(0) as u64;
let duration = flow_end - flow_start;
// let start = time::at_utc(time::Timespec{ sec: (flow_start / 1000) as i64, nsec: 0});
//let end = time::at_utc(time::Timespec{ sec: (flow_end / 1000) as i64, nsec: 0});
writeln!(w, "{:>5.1}s {:6} bytes {:5} pkts {:6} {} -> {}",
// start.rfc3339(),
(duration as f64) / 1000.0,
rec.octet_delta_count().unwrap_or(0),
rec.packet_delta_count().unwrap_or(0),
protocol_name,
SocketAddr::new(source_ip,rec.source_transport_port().unwrap_or(0)),
SocketAddr::new(destination_ip,rec.destination_transport_port().unwrap_or(0)),
).unwrap();
}
|
writeln!(out, "template_id: {}, template_length: {}", template_id, template_length).unwrap();
let mut template_raw = Vec::with_capacity(template_length);
file.take(template_length as u64).read_to_end(&mut template_raw).unwrap();
|
random_line_split
|
dump.rs
|
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn main() {
let stdout = io::stdout();
let mut out = stdout.lock();
for arg in env::args().skip(1) {
match File::open(&arg) {
Ok(ref mut file) => dump_file(&mut out, file),
Err(err) => writeln!(out, "Could not open {}: {}", arg, err).unwrap()
}
}
}
fn dump_file<F,W>(mut out: &mut W, mut file: &mut F) where F: Read + Seek, W: Write {
let mut magic = [0u8; 8];
let mut template_offset = [0u8; 8];
file.read(&mut magic[..]).unwrap();
file.read(&mut template_offset[..]).unwrap();
if &magic[..]!= b"NETFLO00" {
writeln!(out, "Invalid file magic: {:?}.", magic).unwrap();
return;
}
let template_offset: u64 = unsafe { mem::transmute::<[u8; 8], u64>(template_offset).to_be()};
writeln!(out, "template_offset: {}", template_offset).unwrap();
if template_offset == 0 {
writeln!(out, "Incomplete file, skipping").unwrap();
return;
}
let sought = file.seek(io::SeekFrom::Current(template_offset as i64)).unwrap();
assert_eq!(sought, template_offset + 16);
let mut extractors: HashMap<u16, FlowRecordExtractor> = HashMap::new();
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
if let Ok(_) = file.read_exact(&mut tid[..]) {
file.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let template_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
writeln!(out, "template_id: {}, template_length: {}", template_id, template_length).unwrap();
let mut template_raw = Vec::with_capacity(template_length);
file.take(template_length as u64).read_to_end(&mut template_raw).unwrap();
//println!("raw template: {:?}", &template_raw[..]);
let template: DataTemplate = DataTemplate {
template_id: template_id,
field_count: (template_length / 4) as u16,
fields: TemplateFieldIter { raw: &template_raw[..]}
};
extractors.insert(template_id, template.build_extractor());
// for (_len, field) in template.fields.clone() {
// println!("\tfield: {:?} ", field);
// }
} else {
break;
}
}
file.seek(io::SeekFrom::Start(16)).unwrap();
let mut records = ZlibDecoder::new(file.take(template_offset));
loop {
let mut tid = [0u8; 2];
let mut len = [0u8; 2];
let mut buf = [0u8; 2048];
if let Ok(_) = records.read_exact(&mut tid[..])
|
else {
break;
}
}
}
fn print_record<W>(w: &mut W, rec: &Record) where W: Write {
let strbuf: String;
let protocol_name = match rec.protocol_identifier() {
Some(1) => "ICMP",
Some(4) => "IPIP",
Some(6) => "TCP",
Some(17) => "UDP",
Some(41) => "IP6IP",
Some(47) => "GRE",
Some(50) => "ESP",
Some(58) => "ICMP",
Some(n) => {
strbuf = format!("{}", n);
&strbuf
},
_ => return
};
let source_ip = rec.source_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.source_ipv6_address()
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
let destination_ip = rec.destination_ipv4_address()
.map(|ip| IpAddr::V4(ip.into()))
.or(rec.destination_ipv6_address()
.map(|ip| IpAddr::V6(ip.into()))).unwrap();
// let packet_time = header.seconds() as u64 * 1000;
// let sys_uptime = header.sys_uptime() as u64;
// let boot_time = packet_time - sys_uptime;
let flow_start = rec.flow_start_sys_uptime().unwrap_or(0) as u64;
let flow_end = rec.flow_end_sys_uptime().unwrap_or(0) as u64;
let duration = flow_end - flow_start;
// let start = time::at_utc(time::Timespec{ sec: (flow_start / 1000) as i64, nsec: 0});
//let end = time::at_utc(time::Timespec{ sec: (flow_end / 1000) as i64, nsec: 0});
writeln!(w, "{:>5.1}s {:6} bytes {:5} pkts {:6} {} -> {}",
// start.rfc3339(),
(duration as f64) / 1000.0,
rec.octet_delta_count().unwrap_or(0),
rec.packet_delta_count().unwrap_or(0),
protocol_name,
SocketAddr::new(source_ip,rec.source_transport_port().unwrap_or(0)),
SocketAddr::new(destination_ip,rec.destination_transport_port().unwrap_or(0)),
).unwrap();
}
|
{
records.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let record_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
records.read_exact(&mut buf[..record_length]).unwrap();
// println!("record template id: {}", template_id);
// println!("record length: {}", record_length);
let data_records = DataRecords{ template_id: template_id, raw: &buf[..record_length]};
if let Some(extractor) = extractors.get(&template_id) {
for record in extractor.records(&data_records) {
// writeln!(out, "record: {:?}", record).unwrap();
print_record(&mut out, &record);
}
}
}
|
conditional_block
|
more-gates.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.
// force-host
// no-prefer-dynamic
#![crate_type = "proc-macro"]
extern crate proc_macro;
use proc_macro::*;
#[proc_macro_attribute]
pub fn attr2mac1(_: TokenStream, _: TokenStream) -> TokenStream
|
#[proc_macro_attribute]
pub fn attr2mac2(_: TokenStream, _: TokenStream) -> TokenStream {
"macro foo2(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac1(_: TokenStream) -> TokenStream {
"macro_rules! foo3 { (a) => (a) }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac2(_: TokenStream) -> TokenStream {
"macro foo4(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn tricky(_: TokenStream) -> TokenStream {
"fn foo() {
macro_rules! foo { (a) => (a) }
}".parse().unwrap()
}
|
{
"macro_rules! foo1 { (a) => (a) }".parse().unwrap()
}
|
identifier_body
|
more-gates.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.
// force-host
// no-prefer-dynamic
#![crate_type = "proc-macro"]
extern crate proc_macro;
use proc_macro::*;
#[proc_macro_attribute]
pub fn attr2mac1(_: TokenStream, _: TokenStream) -> TokenStream {
"macro_rules! foo1 { (a) => (a) }".parse().unwrap()
}
#[proc_macro_attribute]
pub fn attr2mac2(_: TokenStream, _: TokenStream) -> TokenStream {
"macro foo2(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac1(_: TokenStream) -> TokenStream {
"macro_rules! foo3 { (a) => (a) }".parse().unwrap()
}
#[proc_macro]
pub fn
|
(_: TokenStream) -> TokenStream {
"macro foo4(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn tricky(_: TokenStream) -> TokenStream {
"fn foo() {
macro_rules! foo { (a) => (a) }
}".parse().unwrap()
}
|
mac2mac2
|
identifier_name
|
more-gates.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.
// force-host
// no-prefer-dynamic
#![crate_type = "proc-macro"]
extern crate proc_macro;
use proc_macro::*;
|
"macro_rules! foo1 { (a) => (a) }".parse().unwrap()
}
#[proc_macro_attribute]
pub fn attr2mac2(_: TokenStream, _: TokenStream) -> TokenStream {
"macro foo2(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac1(_: TokenStream) -> TokenStream {
"macro_rules! foo3 { (a) => (a) }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac2(_: TokenStream) -> TokenStream {
"macro foo4(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn tricky(_: TokenStream) -> TokenStream {
"fn foo() {
macro_rules! foo { (a) => (a) }
}".parse().unwrap()
}
|
#[proc_macro_attribute]
pub fn attr2mac1(_: TokenStream, _: TokenStream) -> TokenStream {
|
random_line_split
|
framerate.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_traits::DevtoolScriptControlMsg;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use rustc_serialize::json;
use std::mem;
use std::net::TcpStream;
use time::precise_time_ns;
pub struct FramerateActor {
name: String,
pipeline: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>,
start_time: Option<u64>,
is_recording: bool,
ticks: Vec<HighResolutionStamp>,
}
impl Actor for FramerateActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &json::Object,
_stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessageStatus::Ignored)
}
}
impl FramerateActor {
/// return name of actor
pub fn create(registry: &ActorRegistry,
pipeline_id: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>) -> String {
let actor_name = registry.new_name("framerate");
let mut actor = FramerateActor {
name: actor_name.clone(),
pipeline: pipeline_id,
script_sender: script_sender,
start_time: None,
is_recording: false,
ticks: Vec::new(),
};
actor.start_recording();
registry.register_later(box actor);
actor_name
}
pub fn add_tick(&mut self, tick: f64) {
self.ticks.push(HighResolutionStamp::wrap(tick));
if self.is_recording {
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
}
pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> {
mem::replace(&mut self.ticks, Vec::new())
}
fn start_recording(&mut self)
|
fn stop_recording(&mut self) {
if!self.is_recording {
return;
}
self.is_recording = false;
self.start_time = None;
}
}
impl Drop for FramerateActor {
fn drop(&mut self) {
self.stop_recording();
}
}
|
{
if self.is_recording {
return;
}
self.start_time = Some(precise_time_ns());
self.is_recording = true;
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
|
identifier_body
|
framerate.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_traits::DevtoolScriptControlMsg;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use rustc_serialize::json;
use std::mem;
use std::net::TcpStream;
use time::precise_time_ns;
pub struct FramerateActor {
name: String,
pipeline: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>,
start_time: Option<u64>,
is_recording: bool,
ticks: Vec<HighResolutionStamp>,
}
impl Actor for FramerateActor {
fn
|
(&self) -> String {
self.name.clone()
}
fn handle_message(&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &json::Object,
_stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessageStatus::Ignored)
}
}
impl FramerateActor {
/// return name of actor
pub fn create(registry: &ActorRegistry,
pipeline_id: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>) -> String {
let actor_name = registry.new_name("framerate");
let mut actor = FramerateActor {
name: actor_name.clone(),
pipeline: pipeline_id,
script_sender: script_sender,
start_time: None,
is_recording: false,
ticks: Vec::new(),
};
actor.start_recording();
registry.register_later(box actor);
actor_name
}
pub fn add_tick(&mut self, tick: f64) {
self.ticks.push(HighResolutionStamp::wrap(tick));
if self.is_recording {
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
}
pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> {
mem::replace(&mut self.ticks, Vec::new())
}
fn start_recording(&mut self) {
if self.is_recording {
return;
}
self.start_time = Some(precise_time_ns());
self.is_recording = true;
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
fn stop_recording(&mut self) {
if!self.is_recording {
return;
}
self.is_recording = false;
self.start_time = None;
}
}
impl Drop for FramerateActor {
fn drop(&mut self) {
self.stop_recording();
}
}
|
name
|
identifier_name
|
framerate.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_traits::DevtoolScriptControlMsg;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use rustc_serialize::json;
use std::mem;
use std::net::TcpStream;
use time::precise_time_ns;
pub struct FramerateActor {
name: String,
pipeline: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>,
start_time: Option<u64>,
is_recording: bool,
ticks: Vec<HighResolutionStamp>,
}
impl Actor for FramerateActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &json::Object,
_stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessageStatus::Ignored)
}
}
impl FramerateActor {
/// return name of actor
pub fn create(registry: &ActorRegistry,
pipeline_id: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>) -> String {
let actor_name = registry.new_name("framerate");
let mut actor = FramerateActor {
name: actor_name.clone(),
pipeline: pipeline_id,
script_sender: script_sender,
start_time: None,
is_recording: false,
ticks: Vec::new(),
};
actor.start_recording();
registry.register_later(box actor);
actor_name
}
pub fn add_tick(&mut self, tick: f64) {
self.ticks.push(HighResolutionStamp::wrap(tick));
if self.is_recording {
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
}
pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> {
mem::replace(&mut self.ticks, Vec::new())
}
fn start_recording(&mut self) {
if self.is_recording
|
self.start_time = Some(precise_time_ns());
self.is_recording = true;
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
fn stop_recording(&mut self) {
if!self.is_recording {
return;
}
self.is_recording = false;
self.start_time = None;
}
}
impl Drop for FramerateActor {
fn drop(&mut self) {
self.stop_recording();
}
}
|
{
return;
}
|
conditional_block
|
framerate.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_traits::DevtoolScriptControlMsg;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use rustc_serialize::json;
use std::mem;
use std::net::TcpStream;
use time::precise_time_ns;
pub struct FramerateActor {
name: String,
pipeline: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>,
start_time: Option<u64>,
is_recording: bool,
ticks: Vec<HighResolutionStamp>,
}
impl Actor for FramerateActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &json::Object,
_stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessageStatus::Ignored)
}
}
impl FramerateActor {
/// return name of actor
pub fn create(registry: &ActorRegistry,
pipeline_id: PipelineId,
script_sender: IpcSender<DevtoolScriptControlMsg>) -> String {
let actor_name = registry.new_name("framerate");
let mut actor = FramerateActor {
name: actor_name.clone(),
pipeline: pipeline_id,
script_sender: script_sender,
start_time: None,
is_recording: false,
ticks: Vec::new(),
};
actor.start_recording();
registry.register_later(box actor);
actor_name
}
pub fn add_tick(&mut self, tick: f64) {
self.ticks.push(HighResolutionStamp::wrap(tick));
if self.is_recording {
|
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
}
pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> {
mem::replace(&mut self.ticks, Vec::new())
}
fn start_recording(&mut self) {
if self.is_recording {
return;
}
self.start_time = Some(precise_time_ns());
self.is_recording = true;
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
fn stop_recording(&mut self) {
if!self.is_recording {
return;
}
self.is_recording = false;
self.start_time = None;
}
}
impl Drop for FramerateActor {
fn drop(&mut self) {
self.stop_recording();
}
}
|
random_line_split
|
|
extra-unused-mut.rs
|
// extra unused mut lint tests for #51918
// check-pass
#![feature(generators, nll)]
#![deny(unused_mut)]
fn ref_argument(ref _y: i32) {}
// #51801
fn mutable_upvar() {
let mut x = 0;
move || {
x = 1;
};
}
|
x = 1;
yield;
};
}
// #51830
fn ref_closure_argument() {
let _ = Some(0).as_ref().map(|ref _a| true);
}
struct Expr {
attrs: Vec<u32>,
}
// #51904
fn parse_dot_or_call_expr_with(mut attrs: Vec<u32>) {
let x = Expr { attrs: vec![] };
Some(Some(x)).map(|expr|
expr.map(|mut expr| {
attrs.push(666);
expr.attrs = attrs;
expr
})
);
}
// Found when trying to bootstrap rustc
fn if_guard(x: Result<i32, i32>) {
match x {
Ok(mut r) | Err(mut r) if true => r = 1,
_ => (),
}
}
// #59620
fn nested_closures() {
let mut i = 0;
[].iter().for_each(|_: &i32| {
[].iter().for_each(move |_: &i32| {
i += 1;
});
});
}
fn main() {}
|
// #50897
fn generator_mutable_upvar() {
let mut x = 0;
move || {
|
random_line_split
|
extra-unused-mut.rs
|
// extra unused mut lint tests for #51918
// check-pass
#![feature(generators, nll)]
#![deny(unused_mut)]
fn ref_argument(ref _y: i32) {}
// #51801
fn mutable_upvar() {
let mut x = 0;
move || {
x = 1;
};
}
// #50897
fn generator_mutable_upvar() {
let mut x = 0;
move || {
x = 1;
yield;
};
}
// #51830
fn ref_closure_argument() {
let _ = Some(0).as_ref().map(|ref _a| true);
}
struct Expr {
attrs: Vec<u32>,
}
// #51904
fn parse_dot_or_call_expr_with(mut attrs: Vec<u32>) {
let x = Expr { attrs: vec![] };
Some(Some(x)).map(|expr|
expr.map(|mut expr| {
attrs.push(666);
expr.attrs = attrs;
expr
})
);
}
// Found when trying to bootstrap rustc
fn if_guard(x: Result<i32, i32>)
|
// #59620
fn nested_closures() {
let mut i = 0;
[].iter().for_each(|_: &i32| {
[].iter().for_each(move |_: &i32| {
i += 1;
});
});
}
fn main() {}
|
{
match x {
Ok(mut r) | Err(mut r) if true => r = 1,
_ => (),
}
}
|
identifier_body
|
extra-unused-mut.rs
|
// extra unused mut lint tests for #51918
// check-pass
#![feature(generators, nll)]
#![deny(unused_mut)]
fn ref_argument(ref _y: i32) {}
// #51801
fn mutable_upvar() {
let mut x = 0;
move || {
x = 1;
};
}
// #50897
fn generator_mutable_upvar() {
let mut x = 0;
move || {
x = 1;
yield;
};
}
// #51830
fn ref_closure_argument() {
let _ = Some(0).as_ref().map(|ref _a| true);
}
struct Expr {
attrs: Vec<u32>,
}
// #51904
fn parse_dot_or_call_expr_with(mut attrs: Vec<u32>) {
let x = Expr { attrs: vec![] };
Some(Some(x)).map(|expr|
expr.map(|mut expr| {
attrs.push(666);
expr.attrs = attrs;
expr
})
);
}
// Found when trying to bootstrap rustc
fn
|
(x: Result<i32, i32>) {
match x {
Ok(mut r) | Err(mut r) if true => r = 1,
_ => (),
}
}
// #59620
fn nested_closures() {
let mut i = 0;
[].iter().for_each(|_: &i32| {
[].iter().for_each(move |_: &i32| {
i += 1;
});
});
}
fn main() {}
|
if_guard
|
identifier_name
|
trait-bounds-in-arc.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Send.
use std::sync::Arc;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: String,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: String,
}
struct Goldfyshe {
swim_speed: uint,
name: String,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn
|
(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_string() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
name: "alan_turing".to_string(),
};
let dogge2 = Dogge {
bark_decibels: 55,
tricks_known: 11,
name: "albert_einstein".to_string(),
};
let fishe = Goldfyshe {
swim_speed: 998,
name: "alec_guinness".to_string(),
};
let arc = Arc::new(vec!(box catte as Box<Pet+Share+Send>,
box dogge1 as Box<Pet+Share+Send>,
box fishe as Box<Pet+Share+Send>,
box dogge2 as Box<Pet+Share+Send>));
let (tx1, rx1) = channel();
let arc1 = arc.clone();
task::spawn(proc() { check_legs(arc1); tx1.send(()); });
let (tx2, rx2) = channel();
let arc2 = arc.clone();
task::spawn(proc() { check_names(arc2); tx2.send(()); });
let (tx3, rx3) = channel();
let arc3 = arc.clone();
task::spawn(proc() { check_pedigree(arc3); tx3.send(()); });
rx1.recv();
rx2.recv();
rx3.recv();
}
fn check_legs(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
let mut legs = 0;
for pet in arc.iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
for pet in arc.iter() {
pet.name(|name| {
assert!(name.as_bytes()[0] == 'a' as u8 && name.as_bytes()[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
}
|
of_good_pedigree
|
identifier_name
|
trait-bounds-in-arc.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Send.
use std::sync::Arc;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: String,
|
bark_decibels: uint,
tricks_known: uint,
name: String,
}
struct Goldfyshe {
swim_speed: uint,
name: String,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_string() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
name: "alan_turing".to_string(),
};
let dogge2 = Dogge {
bark_decibels: 55,
tricks_known: 11,
name: "albert_einstein".to_string(),
};
let fishe = Goldfyshe {
swim_speed: 998,
name: "alec_guinness".to_string(),
};
let arc = Arc::new(vec!(box catte as Box<Pet+Share+Send>,
box dogge1 as Box<Pet+Share+Send>,
box fishe as Box<Pet+Share+Send>,
box dogge2 as Box<Pet+Share+Send>));
let (tx1, rx1) = channel();
let arc1 = arc.clone();
task::spawn(proc() { check_legs(arc1); tx1.send(()); });
let (tx2, rx2) = channel();
let arc2 = arc.clone();
task::spawn(proc() { check_names(arc2); tx2.send(()); });
let (tx3, rx3) = channel();
let arc3 = arc.clone();
task::spawn(proc() { check_pedigree(arc3); tx3.send(()); });
rx1.recv();
rx2.recv();
rx3.recv();
}
fn check_legs(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
let mut legs = 0;
for pet in arc.iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
for pet in arc.iter() {
pet.name(|name| {
assert!(name.as_bytes()[0] == 'a' as u8 && name.as_bytes()[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
}
|
}
struct Dogge {
|
random_line_split
|
trait-bounds-in-arc.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Send.
use std::sync::Arc;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: String,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: String,
}
struct Goldfyshe {
swim_speed: uint,
name: String,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint
|
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_string() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
name: "alan_turing".to_string(),
};
let dogge2 = Dogge {
bark_decibels: 55,
tricks_known: 11,
name: "albert_einstein".to_string(),
};
let fishe = Goldfyshe {
swim_speed: 998,
name: "alec_guinness".to_string(),
};
let arc = Arc::new(vec!(box catte as Box<Pet+Share+Send>,
box dogge1 as Box<Pet+Share+Send>,
box fishe as Box<Pet+Share+Send>,
box dogge2 as Box<Pet+Share+Send>));
let (tx1, rx1) = channel();
let arc1 = arc.clone();
task::spawn(proc() { check_legs(arc1); tx1.send(()); });
let (tx2, rx2) = channel();
let arc2 = arc.clone();
task::spawn(proc() { check_names(arc2); tx2.send(()); });
let (tx3, rx3) = channel();
let arc3 = arc.clone();
task::spawn(proc() { check_pedigree(arc3); tx3.send(()); });
rx1.recv();
rx2.recv();
rx3.recv();
}
fn check_legs(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
let mut legs = 0;
for pet in arc.iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
for pet in arc.iter() {
pet.name(|name| {
assert!(name.as_bytes()[0] == 'a' as u8 && name.as_bytes()[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: Arc<Vec<Box<Pet+Share+Send>>>) {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
}
|
{ 0 }
|
identifier_body
|
channel_dao_testing.rs
|
extern crate proton_cli;
use proton_cli::dao::ChannelDao;
use proton_cli::error::Error;
use proton_cli::project_types::Channel;
/// Implementation of ChannelDao for testing purposes. Uses given functions to return values.
/// Functions are boxed so their sizes are known (pointers).
/// The general naming convention used is trait_function_name_fn, for all trait functions.
/// &str references are converted to Strings so we don't have to deal with lifetime headaches (bookdude13 tried on 12/25/16)
#[allow(dead_code)]
pub struct ChannelDaoTesting {
pub new_channel_fn: Box<Fn(
String,
Option<u32>,
Option<u32>,
String,
u32,
u32,
(Option<i32>, Option<i32>, Option<i32>),
(Option<i32>, Option<i32>, Option<i32>)) -> Result<Channel, Error>>,
pub get_channel_fn: Box<Fn(u32) -> Result<Channel, Error>>,
pub get_last_channel_fn: Box<Fn(String) -> Result<Channel, Error>>,
}
impl ChannelDaoTesting {
/// Creates a new ChannelDaoTesting struct with all functions set to return Error::TodoErr
#[allow(dead_code)]
pub fn new() -> ChannelDaoTesting {
ChannelDaoTesting {
new_channel_fn: Box::new(|_, _, _, _, _, _, _, _| -> Result<Channel, Error> { Err(Error::TodoErr) }),
get_channel_fn: Box::new(|_| -> Result<Channel, Error> { Err(Error::TodoErr) }),
get_last_channel_fn: Box::new(|_| -> Result<Channel, Error> { Err(Error::TodoErr) })
}
}
}
/// The Dao implementation simply calls the corresponding stored function
impl ChannelDao for ChannelDaoTesting {
/// Add a channel
fn
|
(
&self,
name: &str,
primary_num: Option<u32>,
secondary_num: Option<u32>,
color: &str,
channel_internal: u32,
channel_dmx: u32,
location: (Option<i32>, Option<i32>, Option<i32>),
rotation: (Option<i32>, Option<i32>, Option<i32>)
) -> Result<Channel, Error> {
(self.new_channel_fn)(
name.to_owned(),
primary_num,
secondary_num,
color.to_owned(),
channel_internal,
channel_dmx,
location,
rotation)
}
/// Fetch a Channel with the given channel id
fn get_channel(&self, chanid: u32) -> Result<Channel, Error> {
(self.get_channel_fn)(chanid)
}
fn get_last_channel(&self, name: &str) -> Result<Channel, Error> {
(self.get_last_channel_fn)(name.to_owned())
}
}
|
new_channel
|
identifier_name
|
channel_dao_testing.rs
|
extern crate proton_cli;
use proton_cli::dao::ChannelDao;
|
/// Implementation of ChannelDao for testing purposes. Uses given functions to return values.
/// Functions are boxed so their sizes are known (pointers).
/// The general naming convention used is trait_function_name_fn, for all trait functions.
/// &str references are converted to Strings so we don't have to deal with lifetime headaches (bookdude13 tried on 12/25/16)
#[allow(dead_code)]
pub struct ChannelDaoTesting {
pub new_channel_fn: Box<Fn(
String,
Option<u32>,
Option<u32>,
String,
u32,
u32,
(Option<i32>, Option<i32>, Option<i32>),
(Option<i32>, Option<i32>, Option<i32>)) -> Result<Channel, Error>>,
pub get_channel_fn: Box<Fn(u32) -> Result<Channel, Error>>,
pub get_last_channel_fn: Box<Fn(String) -> Result<Channel, Error>>,
}
impl ChannelDaoTesting {
/// Creates a new ChannelDaoTesting struct with all functions set to return Error::TodoErr
#[allow(dead_code)]
pub fn new() -> ChannelDaoTesting {
ChannelDaoTesting {
new_channel_fn: Box::new(|_, _, _, _, _, _, _, _| -> Result<Channel, Error> { Err(Error::TodoErr) }),
get_channel_fn: Box::new(|_| -> Result<Channel, Error> { Err(Error::TodoErr) }),
get_last_channel_fn: Box::new(|_| -> Result<Channel, Error> { Err(Error::TodoErr) })
}
}
}
/// The Dao implementation simply calls the corresponding stored function
impl ChannelDao for ChannelDaoTesting {
/// Add a channel
fn new_channel(
&self,
name: &str,
primary_num: Option<u32>,
secondary_num: Option<u32>,
color: &str,
channel_internal: u32,
channel_dmx: u32,
location: (Option<i32>, Option<i32>, Option<i32>),
rotation: (Option<i32>, Option<i32>, Option<i32>)
) -> Result<Channel, Error> {
(self.new_channel_fn)(
name.to_owned(),
primary_num,
secondary_num,
color.to_owned(),
channel_internal,
channel_dmx,
location,
rotation)
}
/// Fetch a Channel with the given channel id
fn get_channel(&self, chanid: u32) -> Result<Channel, Error> {
(self.get_channel_fn)(chanid)
}
fn get_last_channel(&self, name: &str) -> Result<Channel, Error> {
(self.get_last_channel_fn)(name.to_owned())
}
}
|
use proton_cli::error::Error;
use proton_cli::project_types::Channel;
|
random_line_split
|
tag-align-shape.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.
// xfail-fast: check-fast screws up repr paths
enum a_tag {
a_tag(u64)
}
|
t: a_tag
}
pub fn main() {
let x = t_rec {c8: 22u8, t: a_tag(44u64)};
let y = fmt!("%?", x);
info!("y = %s", y);
assert_eq!(y, ~"t_rec{c8: 22u8, t: a_tag(44u64)}");
}
|
struct t_rec {
c8: u8,
|
random_line_split
|
tag-align-shape.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.
// xfail-fast: check-fast screws up repr paths
enum a_tag {
a_tag(u64)
}
struct t_rec {
c8: u8,
t: a_tag
}
pub fn
|
() {
let x = t_rec {c8: 22u8, t: a_tag(44u64)};
let y = fmt!("%?", x);
info!("y = %s", y);
assert_eq!(y, ~"t_rec{c8: 22u8, t: a_tag(44u64)}");
}
|
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/. */
//! A simple application that uses glutin to open a window for Servo to display in.
#![feature(box_syntax, result_expect)]
#[macro_use] extern crate bitflags;
#[cfg(target_os="macos")] extern crate cgl;
extern crate compositing;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate layers;
extern crate libc;
extern crate msg;
extern crate net_traits;
#[cfg(feature = "window")] extern crate script_traits;
extern crate time;
extern crate util;
#[cfg(target_os="android")] extern crate egl;
extern crate url;
#[cfg(target_os="linux")] extern crate x11;
use compositing::windowing::WindowEvent;
use euclid::scale_factor::ScaleFactor;
use std::rc::Rc;
use util::opts;
use window::Window;
pub mod window;
|
pub trait NestedEventLoopListener {
fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool;
}
pub fn create_window(parent: WindowID) -> Rc<Window> {
// Read command-line options.
let opts = opts::get();
let foreground = opts.output_file.is_none();
let scale_factor = ScaleFactor::new(opts.device_pixels_per_px.unwrap_or(1.0));
let size = opts.initial_window_size.as_f32() * scale_factor;
// Open a window.
Window::new(foreground, size.as_uint().cast().unwrap(), parent)
}
|
pub type WindowID = glutin::WindowID;
|
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 http://mozilla.org/MPL/2.0/. */
//! A simple application that uses glutin to open a window for Servo to display in.
#![feature(box_syntax, result_expect)]
#[macro_use] extern crate bitflags;
#[cfg(target_os="macos")] extern crate cgl;
extern crate compositing;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate layers;
extern crate libc;
extern crate msg;
extern crate net_traits;
#[cfg(feature = "window")] extern crate script_traits;
extern crate time;
extern crate util;
#[cfg(target_os="android")] extern crate egl;
extern crate url;
#[cfg(target_os="linux")] extern crate x11;
use compositing::windowing::WindowEvent;
use euclid::scale_factor::ScaleFactor;
use std::rc::Rc;
use util::opts;
use window::Window;
pub mod window;
pub type WindowID = glutin::WindowID;
pub trait NestedEventLoopListener {
fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool;
}
pub fn
|
(parent: WindowID) -> Rc<Window> {
// Read command-line options.
let opts = opts::get();
let foreground = opts.output_file.is_none();
let scale_factor = ScaleFactor::new(opts.device_pixels_per_px.unwrap_or(1.0));
let size = opts.initial_window_size.as_f32() * scale_factor;
// Open a window.
Window::new(foreground, size.as_uint().cast().unwrap(), parent)
}
|
create_window
|
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/. */
//! A simple application that uses glutin to open a window for Servo to display in.
#![feature(box_syntax, result_expect)]
#[macro_use] extern crate bitflags;
#[cfg(target_os="macos")] extern crate cgl;
extern crate compositing;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate layers;
extern crate libc;
extern crate msg;
extern crate net_traits;
#[cfg(feature = "window")] extern crate script_traits;
extern crate time;
extern crate util;
#[cfg(target_os="android")] extern crate egl;
extern crate url;
#[cfg(target_os="linux")] extern crate x11;
use compositing::windowing::WindowEvent;
use euclid::scale_factor::ScaleFactor;
use std::rc::Rc;
use util::opts;
use window::Window;
pub mod window;
pub type WindowID = glutin::WindowID;
pub trait NestedEventLoopListener {
fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool;
}
pub fn create_window(parent: WindowID) -> Rc<Window>
|
{
// Read command-line options.
let opts = opts::get();
let foreground = opts.output_file.is_none();
let scale_factor = ScaleFactor::new(opts.device_pixels_per_px.unwrap_or(1.0));
let size = opts.initial_window_size.as_f32() * scale_factor;
// Open a window.
Window::new(foreground, size.as_uint().cast().unwrap(), parent)
}
|
identifier_body
|
|
media_queries.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/. */
//! [Media queries][mq].
//!
//! [mq]: https://drafts.csswg.org/mediaqueries/
use Atom;
use context::QuirksMode;
use cssparser::{Delimiter, Parser, Token, ParserInput};
use parser::ParserContext;
use selectors::parser::SelectorParseError;
use serialize_comma_separated_list;
use std::fmt;
use str::string_as_ascii_lowercase;
use style_traits::{ToCss, ParseError, StyleParseError};
use values::CustomIdent;
#[cfg(feature = "servo")]
pub use servo::media_queries::{Device, Expression};
#[cfg(feature = "gecko")]
pub use gecko::media_queries::{Device, Expression};
/// A type that encapsulates a media query list.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct MediaList {
/// The list of media queries.
pub media_queries: Vec<MediaQuery>,
}
impl ToCss for MediaList {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write
{
serialize_comma_separated_list(dest, &self.media_queries)
}
}
impl MediaList {
/// Create an empty MediaList.
pub fn empty() -> Self {
MediaList { media_queries: vec![] }
}
}
/// https://drafts.csswg.org/mediaqueries/#mq-prefix
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, Eq, PartialEq, ToCss)]
pub enum Qualifier {
/// Hide a media query from legacy UAs:
/// https://drafts.csswg.org/mediaqueries/#mq-only
Only,
/// Negate a media query:
/// https://drafts.csswg.org/mediaqueries/#mq-not
Not,
}
/// A [media query][mq].
///
/// [mq]: https://drafts.csswg.org/mediaqueries/
#[derive(PartialEq, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct MediaQuery {
/// The qualifier for this query.
pub qualifier: Option<Qualifier>,
/// The media type for this query, that can be known, unknown, or "all".
pub media_type: MediaQueryType,
/// The set of expressions that this media query contains.
pub expressions: Vec<Expression>,
}
impl MediaQuery {
/// Return a media query that never matches, used for when we fail to parse
/// a given media query.
fn never_matching() -> Self {
Self::new(Some(Qualifier::Not), MediaQueryType::All, vec![])
}
/// Trivially constructs a new media query.
pub fn new(qualifier: Option<Qualifier>,
media_type: MediaQueryType,
expressions: Vec<Expression>) -> MediaQuery {
MediaQuery {
qualifier: qualifier,
media_type: media_type,
expressions: expressions,
}
}
}
impl ToCss for MediaQuery {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
if let Some(qual) = self.qualifier {
qual.to_css(dest)?;
write!(dest, " ")?;
}
match self.media_type {
MediaQueryType::All => {
// We need to print "all" if there's a qualifier, or there's
// just an empty list of expressions.
//
// Otherwise, we'd serialize media queries like "(min-width:
// 40px)" in "all (min-width: 40px)", which is unexpected.
if self.qualifier.is_some() || self.expressions.is_empty() {
write!(dest, "all")?;
}
},
MediaQueryType::Concrete(MediaType(ref desc)) => desc.to_css(dest)?,
}
if self.expressions.is_empty() {
return Ok(());
}
if self.media_type!= MediaQueryType::All || self.qualifier.is_some() {
write!(dest, " and ")?;
}
self.expressions[0].to_css(dest)?;
for expr in self.expressions.iter().skip(1) {
write!(dest, " and ")?;
expr.to_css(dest)?;
}
Ok(())
}
}
/// http://dev.w3.org/csswg/mediaqueries-3/#media0
#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum MediaQueryType {
/// A media type that matches every device.
All,
/// A specific media type.
Concrete(MediaType),
}
impl MediaQueryType {
fn parse(ident: &str) -> Result<Self, ()> {
match_ignore_ascii_case! { ident,
"all" => return Ok(MediaQueryType::All),
_ => (),
};
// If parseable, accept this type as a concrete type.
MediaType::parse(ident).map(MediaQueryType::Concrete)
}
fn matches(&self, other: MediaType) -> bool {
match *self {
MediaQueryType::All => true,
MediaQueryType::Concrete(ref known_type) => *known_type == other,
}
}
}
/// https://drafts.csswg.org/mediaqueries/#media-types
#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct MediaType(pub CustomIdent);
impl MediaType {
/// The `screen` media type.
pub fn screen() -> Self {
MediaType(CustomIdent(atom!("screen")))
}
|
fn parse(name: &str) -> Result<Self, ()> {
// From https://drafts.csswg.org/mediaqueries/#mq-syntax:
//
// The <media-type> production does not include the keywords not, or, and, and only.
//
// Here we also perform the to-ascii-lowercase part of the serialization
// algorithm: https://drafts.csswg.org/cssom/#serializing-media-queries
match_ignore_ascii_case! { name,
"not" | "or" | "and" | "only" => Err(()),
_ => Ok(MediaType(CustomIdent(Atom::from(string_as_ascii_lowercase(name))))),
}
}
}
impl MediaQuery {
/// Parse a media query given css input.
///
/// Returns an error if any of the expressions is unknown.
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<MediaQuery, ParseError<'i>> {
let mut expressions = vec![];
let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() {
Some(Qualifier::Only)
} else if input.try(|input| input.expect_ident_matching("not")).is_ok() {
Some(Qualifier::Not)
} else {
None
};
let media_type = match input.try(|i| i.expect_ident_cloned()) {
Ok(ident) => {
let result: Result<_, ParseError> = MediaQueryType::parse(&*ident)
.map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into());
result?
}
Err(_) => {
// Media type is only optional if qualifier is not specified.
if qualifier.is_some() {
return Err(StyleParseError::UnspecifiedError.into())
}
// Without a media type, require at least one expression.
expressions.push(Expression::parse(context, input)?);
MediaQueryType::All
}
};
// Parse any subsequent expressions
loop {
if input.try(|input| input.expect_ident_matching("and")).is_err() {
return Ok(MediaQuery::new(qualifier, media_type, expressions))
}
expressions.push(Expression::parse(context, input)?)
}
}
}
/// Parse a media query list from CSS.
///
/// Always returns a media query list. If any invalid media query is found, the
/// media query list is only filled with the equivalent of "not all", see:
///
/// https://drafts.csswg.org/mediaqueries/#error-handling
pub fn parse_media_query_list(context: &ParserContext, input: &mut Parser) -> MediaList {
if input.is_exhausted() {
return MediaList::empty()
}
let mut media_queries = vec![];
loop {
match input.parse_until_before(Delimiter::Comma, |i| MediaQuery::parse(context, i)) {
Ok(mq) => {
media_queries.push(mq);
},
Err(..) => {
media_queries.push(MediaQuery::never_matching());
},
}
match input.next() {
Ok(&Token::Comma) => {},
Ok(_) => unreachable!(),
Err(_) => break,
}
}
MediaList {
media_queries: media_queries,
}
}
impl MediaList {
/// Evaluate a whole `MediaList` against `Device`.
pub fn evaluate(&self, device: &Device, quirks_mode: QuirksMode) -> bool {
// Check if it is an empty media query list or any queries match (OR condition)
// https://drafts.csswg.org/mediaqueries-4/#mq-list
self.media_queries.is_empty() || self.media_queries.iter().any(|mq| {
let media_match = mq.media_type.matches(device.media_type());
// Check if all conditions match (AND condition)
let query_match =
media_match &&
mq.expressions.iter()
.all(|expression| expression.matches(&device, quirks_mode));
// Apply the logical NOT qualifier to the result
match mq.qualifier {
Some(Qualifier::Not) =>!query_match,
_ => query_match,
}
})
}
/// Whether this `MediaList` contains no media queries.
pub fn is_empty(&self) -> bool {
self.media_queries.is_empty()
}
/// Append a new media query item to the media list.
/// https://drafts.csswg.org/cssom/#dom-medialist-appendmedium
///
/// Returns true if added, false if fail to parse the medium string.
pub fn append_medium(&mut self, context: &ParserContext, new_medium: &str) -> bool {
let mut input = ParserInput::new(new_medium);
let mut parser = Parser::new(&mut input);
let new_query = match MediaQuery::parse(&context, &mut parser) {
Ok(query) => query,
Err(_) => { return false; }
};
// This algorithm doesn't actually matches the current spec,
// but it matches the behavior of Gecko and Edge.
// See https://github.com/w3c/csswg-drafts/issues/697
self.media_queries.retain(|query| query!= &new_query);
self.media_queries.push(new_query);
true
}
/// Delete a media query from the media list.
/// https://drafts.csswg.org/cssom/#dom-medialist-deletemedium
///
/// Returns true if found and deleted, false otherwise.
pub fn delete_medium(&mut self, context: &ParserContext, old_medium: &str) -> bool {
let mut input = ParserInput::new(old_medium);
let mut parser = Parser::new(&mut input);
let old_query = match MediaQuery::parse(context, &mut parser) {
Ok(query) => query,
Err(_) => { return false; }
};
let old_len = self.media_queries.len();
self.media_queries.retain(|query| query!= &old_query);
old_len!= self.media_queries.len()
}
}
|
/// The `print` media type.
pub fn print() -> Self {
MediaType(CustomIdent(atom!("print")))
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.