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 |
---|---|---|---|---|
abstractworkerglobalscope.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::abstractworker::WorkerScriptMsg;
use crate::dom::bindings::conversions::DerivedFrom;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::dedicatedworkerglobalscope::{AutoWorkerReset, DedicatedWorkerScriptMsg};
use crate::dom::globalscope::GlobalScope;
use crate::dom::worker::TrustedWorkerAddress;
use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort};
use crate::task_queue::{QueuedTaskConversion, TaskQueue};
use crossbeam_channel::{Receiver, Sender};
use devtools_traits::DevtoolScriptControlMsg;
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// common event loop messages. While this SendableWorkerScriptChan is alive, the associated
/// Worker object will remain alive.
#[derive(Clone, JSTraceable)]
pub struct SendableWorkerScriptChan {
pub sender: Sender<DedicatedWorkerScriptMsg>,
pub worker: TrustedWorkerAddress,
}
impl ScriptChan for SendableWorkerScriptChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
let msg = DedicatedWorkerScriptMsg::CommonWorker(
self.worker.clone(),
WorkerScriptMsg::Common(msg),
);
self.sender.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
})
}
}
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// worker event loop messages. While this SendableWorkerScriptChan is alive, the associated
/// Worker object will remain alive.
#[derive(Clone, JSTraceable)]
pub struct WorkerThreadWorkerChan {
pub sender: Sender<DedicatedWorkerScriptMsg>,
pub worker: TrustedWorkerAddress,
}
impl ScriptChan for WorkerThreadWorkerChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
let msg = DedicatedWorkerScriptMsg::CommonWorker(
self.worker.clone(),
WorkerScriptMsg::Common(msg),
); | fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(WorkerThreadWorkerChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
})
}
}
impl ScriptPort for Receiver<DedicatedWorkerScriptMsg> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
let common_msg = match self.recv() {
Ok(DedicatedWorkerScriptMsg::CommonWorker(_worker, common_msg)) => common_msg,
Err(_) => return Err(()),
Ok(DedicatedWorkerScriptMsg::WakeUp) => panic!("unexpected worker event message!"),
};
match common_msg {
WorkerScriptMsg::Common(script_msg) => Ok(script_msg),
WorkerScriptMsg::DOMMessage {.. } => panic!("unexpected worker event message!"),
}
}
}
pub trait WorkerEventLoopMethods {
type TimerMsg: Send;
type WorkerMsg: QueuedTaskConversion + Send;
type Event;
fn timer_event_port(&self) -> &Receiver<Self::TimerMsg>;
fn task_queue(&self) -> &TaskQueue<Self::WorkerMsg>;
fn handle_event(&self, event: Self::Event);
fn handle_worker_post_event(&self, worker: &TrustedWorkerAddress) -> Option<AutoWorkerReset>;
fn from_worker_msg(&self, msg: Self::WorkerMsg) -> Self::Event;
fn from_timer_msg(&self, msg: Self::TimerMsg) -> Self::Event;
fn from_devtools_msg(&self, msg: DevtoolScriptControlMsg) -> Self::Event;
}
// https://html.spec.whatwg.org/multipage/#worker-event-loop
pub fn run_worker_event_loop<T, TimerMsg, WorkerMsg, Event>(
worker_scope: &T,
worker: Option<&TrustedWorkerAddress>,
) where
TimerMsg: Send,
WorkerMsg: QueuedTaskConversion + Send,
T: WorkerEventLoopMethods<TimerMsg = TimerMsg, WorkerMsg = WorkerMsg, Event = Event>
+ DerivedFrom<WorkerGlobalScope>
+ DerivedFrom<GlobalScope>
+ DomObject,
{
let scope = worker_scope.upcast::<WorkerGlobalScope>();
let timer_event_port = worker_scope.timer_event_port();
let devtools_port = match scope.from_devtools_sender() {
Some(_) => Some(scope.from_devtools_receiver()),
None => None,
};
let task_queue = worker_scope.task_queue();
let event = select! {
recv(task_queue.select()) -> msg => {
task_queue.take_tasks(msg.unwrap());
worker_scope.from_worker_msg(task_queue.recv().unwrap())
},
recv(timer_event_port) -> msg => worker_scope.from_timer_msg(msg.unwrap()),
recv(devtools_port.unwrap_or(&crossbeam_channel::never())) -> msg =>
worker_scope.from_devtools_msg(msg.unwrap()),
};
let mut sequential = vec![];
sequential.push(event);
// https://html.spec.whatwg.org/multipage/#worker-event-loop
// Once the WorkerGlobalScope's closing flag is set to true,
// the event loop's task queues must discard any further tasks
// that would be added to them
// (tasks already on the queue are unaffected except where otherwise specified).
while!scope.is_closing() {
// Batch all events that are ready.
// The task queue will throttle non-priority tasks if necessary.
match task_queue.try_recv() {
Err(_) => match timer_event_port.try_recv() {
Err(_) => match devtools_port.map(|port| port.try_recv()) {
None => {},
Some(Err(_)) => break,
Some(Ok(ev)) => sequential.push(worker_scope.from_devtools_msg(ev)),
},
Ok(ev) => sequential.push(worker_scope.from_timer_msg(ev)),
},
Ok(ev) => sequential.push(worker_scope.from_worker_msg(ev)),
}
}
// Step 3
for event in sequential {
worker_scope.handle_event(event);
// Step 6
let _ar = match worker {
Some(worker) => worker_scope.handle_worker_post_event(worker),
None => None,
};
worker_scope
.upcast::<GlobalScope>()
.perform_a_microtask_checkpoint();
}
worker_scope
.upcast::<GlobalScope>()
.perform_a_message_port_garbage_collection_checkpoint();
} | self.sender.send(msg).map_err(|_| ())
}
| random_line_split |
abstractworkerglobalscope.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::abstractworker::WorkerScriptMsg;
use crate::dom::bindings::conversions::DerivedFrom;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::dedicatedworkerglobalscope::{AutoWorkerReset, DedicatedWorkerScriptMsg};
use crate::dom::globalscope::GlobalScope;
use crate::dom::worker::TrustedWorkerAddress;
use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort};
use crate::task_queue::{QueuedTaskConversion, TaskQueue};
use crossbeam_channel::{Receiver, Sender};
use devtools_traits::DevtoolScriptControlMsg;
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// common event loop messages. While this SendableWorkerScriptChan is alive, the associated
/// Worker object will remain alive.
#[derive(Clone, JSTraceable)]
pub struct SendableWorkerScriptChan {
pub sender: Sender<DedicatedWorkerScriptMsg>,
pub worker: TrustedWorkerAddress,
}
impl ScriptChan for SendableWorkerScriptChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
let msg = DedicatedWorkerScriptMsg::CommonWorker(
self.worker.clone(),
WorkerScriptMsg::Common(msg),
);
self.sender.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
})
}
}
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// worker event loop messages. While this SendableWorkerScriptChan is alive, the associated
/// Worker object will remain alive.
#[derive(Clone, JSTraceable)]
pub struct WorkerThreadWorkerChan {
pub sender: Sender<DedicatedWorkerScriptMsg>,
pub worker: TrustedWorkerAddress,
}
impl ScriptChan for WorkerThreadWorkerChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
let msg = DedicatedWorkerScriptMsg::CommonWorker(
self.worker.clone(),
WorkerScriptMsg::Common(msg),
);
self.sender.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(WorkerThreadWorkerChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
})
}
}
impl ScriptPort for Receiver<DedicatedWorkerScriptMsg> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
let common_msg = match self.recv() {
Ok(DedicatedWorkerScriptMsg::CommonWorker(_worker, common_msg)) => common_msg,
Err(_) => return Err(()),
Ok(DedicatedWorkerScriptMsg::WakeUp) => panic!("unexpected worker event message!"),
};
match common_msg {
WorkerScriptMsg::Common(script_msg) => Ok(script_msg),
WorkerScriptMsg::DOMMessage {.. } => panic!("unexpected worker event message!"),
}
}
}
pub trait WorkerEventLoopMethods {
type TimerMsg: Send;
type WorkerMsg: QueuedTaskConversion + Send;
type Event;
fn timer_event_port(&self) -> &Receiver<Self::TimerMsg>;
fn task_queue(&self) -> &TaskQueue<Self::WorkerMsg>;
fn handle_event(&self, event: Self::Event);
fn handle_worker_post_event(&self, worker: &TrustedWorkerAddress) -> Option<AutoWorkerReset>;
fn from_worker_msg(&self, msg: Self::WorkerMsg) -> Self::Event;
fn from_timer_msg(&self, msg: Self::TimerMsg) -> Self::Event;
fn from_devtools_msg(&self, msg: DevtoolScriptControlMsg) -> Self::Event;
}
// https://html.spec.whatwg.org/multipage/#worker-event-loop
pub fn run_worker_event_loop<T, TimerMsg, WorkerMsg, Event>(
worker_scope: &T,
worker: Option<&TrustedWorkerAddress>,
) where
TimerMsg: Send,
WorkerMsg: QueuedTaskConversion + Send,
T: WorkerEventLoopMethods<TimerMsg = TimerMsg, WorkerMsg = WorkerMsg, Event = Event>
+ DerivedFrom<WorkerGlobalScope>
+ DerivedFrom<GlobalScope>
+ DomObject,
| // Once the WorkerGlobalScope's closing flag is set to true,
// the event loop's task queues must discard any further tasks
// that would be added to them
// (tasks already on the queue are unaffected except where otherwise specified).
while!scope.is_closing() {
// Batch all events that are ready.
// The task queue will throttle non-priority tasks if necessary.
match task_queue.try_recv() {
Err(_) => match timer_event_port.try_recv() {
Err(_) => match devtools_port.map(|port| port.try_recv()) {
None => {},
Some(Err(_)) => break,
Some(Ok(ev)) => sequential.push(worker_scope.from_devtools_msg(ev)),
},
Ok(ev) => sequential.push(worker_scope.from_timer_msg(ev)),
},
Ok(ev) => sequential.push(worker_scope.from_worker_msg(ev)),
}
}
// Step 3
for event in sequential {
worker_scope.handle_event(event);
// Step 6
let _ar = match worker {
Some(worker) => worker_scope.handle_worker_post_event(worker),
None => None,
};
worker_scope
.upcast::<GlobalScope>()
.perform_a_microtask_checkpoint();
}
worker_scope
.upcast::<GlobalScope>()
.perform_a_message_port_garbage_collection_checkpoint();
}
| {
let scope = worker_scope.upcast::<WorkerGlobalScope>();
let timer_event_port = worker_scope.timer_event_port();
let devtools_port = match scope.from_devtools_sender() {
Some(_) => Some(scope.from_devtools_receiver()),
None => None,
};
let task_queue = worker_scope.task_queue();
let event = select! {
recv(task_queue.select()) -> msg => {
task_queue.take_tasks(msg.unwrap());
worker_scope.from_worker_msg(task_queue.recv().unwrap())
},
recv(timer_event_port) -> msg => worker_scope.from_timer_msg(msg.unwrap()),
recv(devtools_port.unwrap_or(&crossbeam_channel::never())) -> msg =>
worker_scope.from_devtools_msg(msg.unwrap()),
};
let mut sequential = vec![];
sequential.push(event);
// https://html.spec.whatwg.org/multipage/#worker-event-loop | identifier_body |
connection.rs | use std::fmt::{self, Display};
use std::str::FromStr;
use unicase::UniCase;
pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};
const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive");
const CLOSE: UniCase<&'static str> = UniCase("close");
/// Values that can be in the `Connection` header.
#[derive(Clone, PartialEq, Debug)]
pub enum ConnectionOption {
/// The `keep-alive` connection value.
KeepAlive,
/// The `close` connection value.
Close,
/// Values in the Connection header that are supposed to be names of other Headers.
///
/// > When a header field aside from Connection is used to supply control
/// > information for or about the current connection, the sender MUST list
/// > the corresponding field-name within the Connection header field.
// TODO: it would be nice if these "Strings" could be stronger types, since
// they are supposed to relate to other Header fields (which we have strong
// types for).
ConnectionHeader(UniCase<String>),
}
impl FromStr for ConnectionOption {
type Err = ();
fn from_str(s: &str) -> Result<ConnectionOption, ()> {
if UniCase(s) == KEEP_ALIVE {
Ok(KeepAlive)
} else if UniCase(s) == CLOSE {
Ok(Close)
} else {
Ok(ConnectionHeader(UniCase(s.to_owned())))
}
}
}
impl Display for ConnectionOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
KeepAlive => "keep-alive",
Close => "close",
ConnectionHeader(UniCase(ref s)) => s.as_ref()
})
}
}
header! {
#[doc="`Connection` header, defined in"]
#[doc="[RFC7230](http://tools.ietf.org/html/rfc7230#section-6.1)"]
#[doc=""]
#[doc="The `Connection` header field allows the sender to indicate desired"]
#[doc="control options for the current connection. In order to avoid"]
#[doc="confusing downstream recipients, a proxy or gateway MUST remove or"]
#[doc="replace any received connection options before forwarding the"]
#[doc="message."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Connection = 1#connection-option"]
#[doc="connection-option = token"]
#[doc=""]
#[doc="# Example values"]
#[doc="* `close`"]
#[doc="* `keep-alive`"]
#[doc="* `upgrade`"]
#[doc="```"]
#[doc=""]
#[doc="# Examples"]
#[doc="```"]
#[doc="use hyper::header::{Headers, Connection};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set(Connection::keep_alive());"]
#[doc="```"]
#[doc="```"]
#[doc="# extern crate hyper;"]
#[doc="# extern crate unicase;"]
#[doc="# fn main() {"]
#[doc="// extern crate unicase;"]
#[doc=""]
#[doc="use hyper::header::{Headers, Connection, ConnectionOption};"]
#[doc="use unicase::UniCase;"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" Connection(vec!["]
#[doc=" ConnectionOption::ConnectionHeader(UniCase(\"upgrade\".to_owned())),"]
#[doc=" ])"]
#[doc=");"]
#[doc="# }"]
#[doc="```"]
(Connection, "Connection") => (ConnectionOption)+
test_connection {
test_header!(test1, vec![b"close"]);
test_header!(test2, vec![b"keep-alive"]);
test_header!(test3, vec![b"upgrade"]);
}
}
impl Connection {
/// A constructor to easily create a `Connection: close` header.
#[inline]
pub fn close() -> Connection {
Connection(vec![ConnectionOption::Close])
}
/// A constructor to easily create a `Connection: keep-alive` header.
#[inline]
pub fn keep_alive() -> Connection {
Connection(vec![ConnectionOption::KeepAlive])
}
}
bench_header!(close, Connection, { vec![b"close".to_vec()] });
bench_header!(keep_alive, Connection, { vec![b"keep-alive".to_vec()] });
bench_header!(header, Connection, { vec![b"authorization".to_vec()] });
#[cfg(test)]
mod tests {
use super::{Connection,ConnectionHeader}; |
fn parse_option(header: Vec<u8>) -> Connection {
let val = vec![header];
let connection: Connection = Header::parse_header(&val[..]).unwrap();
connection
}
#[test]
fn test_parse() {
assert_eq!(Connection::close(),parse_option(b"close".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"keep-alive".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"Keep-Alive".to_vec()));
assert_eq!(Connection(vec![ConnectionHeader(UniCase("upgrade".to_owned()))]),
parse_option(b"upgrade".to_vec()));
}
} | use header::Header;
use unicase::UniCase; | random_line_split |
connection.rs | use std::fmt::{self, Display};
use std::str::FromStr;
use unicase::UniCase;
pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};
const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive");
const CLOSE: UniCase<&'static str> = UniCase("close");
/// Values that can be in the `Connection` header.
#[derive(Clone, PartialEq, Debug)]
pub enum ConnectionOption {
/// The `keep-alive` connection value.
KeepAlive,
/// The `close` connection value.
Close,
/// Values in the Connection header that are supposed to be names of other Headers.
///
/// > When a header field aside from Connection is used to supply control
/// > information for or about the current connection, the sender MUST list
/// > the corresponding field-name within the Connection header field.
// TODO: it would be nice if these "Strings" could be stronger types, since
// they are supposed to relate to other Header fields (which we have strong
// types for).
ConnectionHeader(UniCase<String>),
}
impl FromStr for ConnectionOption {
type Err = ();
fn from_str(s: &str) -> Result<ConnectionOption, ()> {
if UniCase(s) == KEEP_ALIVE {
Ok(KeepAlive)
} else if UniCase(s) == CLOSE {
Ok(Close)
} else {
Ok(ConnectionHeader(UniCase(s.to_owned())))
}
}
}
impl Display for ConnectionOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
KeepAlive => "keep-alive",
Close => "close",
ConnectionHeader(UniCase(ref s)) => s.as_ref()
})
}
}
header! {
#[doc="`Connection` header, defined in"]
#[doc="[RFC7230](http://tools.ietf.org/html/rfc7230#section-6.1)"]
#[doc=""]
#[doc="The `Connection` header field allows the sender to indicate desired"]
#[doc="control options for the current connection. In order to avoid"]
#[doc="confusing downstream recipients, a proxy or gateway MUST remove or"]
#[doc="replace any received connection options before forwarding the"]
#[doc="message."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Connection = 1#connection-option"]
#[doc="connection-option = token"]
#[doc=""]
#[doc="# Example values"]
#[doc="* `close`"]
#[doc="* `keep-alive`"]
#[doc="* `upgrade`"]
#[doc="```"]
#[doc=""]
#[doc="# Examples"]
#[doc="```"]
#[doc="use hyper::header::{Headers, Connection};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set(Connection::keep_alive());"]
#[doc="```"]
#[doc="```"]
#[doc="# extern crate hyper;"]
#[doc="# extern crate unicase;"]
#[doc="# fn main() {"]
#[doc="// extern crate unicase;"]
#[doc=""]
#[doc="use hyper::header::{Headers, Connection, ConnectionOption};"]
#[doc="use unicase::UniCase;"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" Connection(vec!["]
#[doc=" ConnectionOption::ConnectionHeader(UniCase(\"upgrade\".to_owned())),"]
#[doc=" ])"]
#[doc=");"]
#[doc="# }"]
#[doc="```"]
(Connection, "Connection") => (ConnectionOption)+
test_connection {
test_header!(test1, vec![b"close"]);
test_header!(test2, vec![b"keep-alive"]);
test_header!(test3, vec![b"upgrade"]);
}
}
impl Connection {
/// A constructor to easily create a `Connection: close` header.
#[inline]
pub fn close() -> Connection {
Connection(vec![ConnectionOption::Close])
}
/// A constructor to easily create a `Connection: keep-alive` header.
#[inline]
pub fn keep_alive() -> Connection {
Connection(vec![ConnectionOption::KeepAlive])
}
}
bench_header!(close, Connection, { vec![b"close".to_vec()] });
bench_header!(keep_alive, Connection, { vec![b"keep-alive".to_vec()] });
bench_header!(header, Connection, { vec![b"authorization".to_vec()] });
#[cfg(test)]
mod tests {
use super::{Connection,ConnectionHeader};
use header::Header;
use unicase::UniCase;
fn parse_option(header: Vec<u8>) -> Connection {
let val = vec![header];
let connection: Connection = Header::parse_header(&val[..]).unwrap();
connection
}
#[test]
fn | () {
assert_eq!(Connection::close(),parse_option(b"close".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"keep-alive".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"Keep-Alive".to_vec()));
assert_eq!(Connection(vec![ConnectionHeader(UniCase("upgrade".to_owned()))]),
parse_option(b"upgrade".to_vec()));
}
}
| test_parse | identifier_name |
connection.rs | use std::fmt::{self, Display};
use std::str::FromStr;
use unicase::UniCase;
pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};
const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive");
const CLOSE: UniCase<&'static str> = UniCase("close");
/// Values that can be in the `Connection` header.
#[derive(Clone, PartialEq, Debug)]
pub enum ConnectionOption {
/// The `keep-alive` connection value.
KeepAlive,
/// The `close` connection value.
Close,
/// Values in the Connection header that are supposed to be names of other Headers.
///
/// > When a header field aside from Connection is used to supply control
/// > information for or about the current connection, the sender MUST list
/// > the corresponding field-name within the Connection header field.
// TODO: it would be nice if these "Strings" could be stronger types, since
// they are supposed to relate to other Header fields (which we have strong
// types for).
ConnectionHeader(UniCase<String>),
}
impl FromStr for ConnectionOption {
type Err = ();
fn from_str(s: &str) -> Result<ConnectionOption, ()> |
}
impl Display for ConnectionOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
KeepAlive => "keep-alive",
Close => "close",
ConnectionHeader(UniCase(ref s)) => s.as_ref()
})
}
}
header! {
#[doc="`Connection` header, defined in"]
#[doc="[RFC7230](http://tools.ietf.org/html/rfc7230#section-6.1)"]
#[doc=""]
#[doc="The `Connection` header field allows the sender to indicate desired"]
#[doc="control options for the current connection. In order to avoid"]
#[doc="confusing downstream recipients, a proxy or gateway MUST remove or"]
#[doc="replace any received connection options before forwarding the"]
#[doc="message."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Connection = 1#connection-option"]
#[doc="connection-option = token"]
#[doc=""]
#[doc="# Example values"]
#[doc="* `close`"]
#[doc="* `keep-alive`"]
#[doc="* `upgrade`"]
#[doc="```"]
#[doc=""]
#[doc="# Examples"]
#[doc="```"]
#[doc="use hyper::header::{Headers, Connection};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set(Connection::keep_alive());"]
#[doc="```"]
#[doc="```"]
#[doc="# extern crate hyper;"]
#[doc="# extern crate unicase;"]
#[doc="# fn main() {"]
#[doc="// extern crate unicase;"]
#[doc=""]
#[doc="use hyper::header::{Headers, Connection, ConnectionOption};"]
#[doc="use unicase::UniCase;"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" Connection(vec!["]
#[doc=" ConnectionOption::ConnectionHeader(UniCase(\"upgrade\".to_owned())),"]
#[doc=" ])"]
#[doc=");"]
#[doc="# }"]
#[doc="```"]
(Connection, "Connection") => (ConnectionOption)+
test_connection {
test_header!(test1, vec![b"close"]);
test_header!(test2, vec![b"keep-alive"]);
test_header!(test3, vec![b"upgrade"]);
}
}
impl Connection {
/// A constructor to easily create a `Connection: close` header.
#[inline]
pub fn close() -> Connection {
Connection(vec![ConnectionOption::Close])
}
/// A constructor to easily create a `Connection: keep-alive` header.
#[inline]
pub fn keep_alive() -> Connection {
Connection(vec![ConnectionOption::KeepAlive])
}
}
bench_header!(close, Connection, { vec![b"close".to_vec()] });
bench_header!(keep_alive, Connection, { vec![b"keep-alive".to_vec()] });
bench_header!(header, Connection, { vec![b"authorization".to_vec()] });
#[cfg(test)]
mod tests {
use super::{Connection,ConnectionHeader};
use header::Header;
use unicase::UniCase;
fn parse_option(header: Vec<u8>) -> Connection {
let val = vec![header];
let connection: Connection = Header::parse_header(&val[..]).unwrap();
connection
}
#[test]
fn test_parse() {
assert_eq!(Connection::close(),parse_option(b"close".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"keep-alive".to_vec()));
assert_eq!(Connection::keep_alive(),parse_option(b"Keep-Alive".to_vec()));
assert_eq!(Connection(vec![ConnectionHeader(UniCase("upgrade".to_owned()))]),
parse_option(b"upgrade".to_vec()));
}
}
| {
if UniCase(s) == KEEP_ALIVE {
Ok(KeepAlive)
} else if UniCase(s) == CLOSE {
Ok(Close)
} else {
Ok(ConnectionHeader(UniCase(s.to_owned())))
}
} | identifier_body |
tree_layout.rs | use std::fmt::{Debug, Display};
use std::num::Float;
use std::rc::Rc;
use tree::Tree;
use tree::Tree::{Node, Tip};
// Tree layout algorithm based on the following paper:
// "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)"
// (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf)
pub fn pretty_print<T: Clone + Display + Debug>(t: &Tree<(T, f64)>) {
fn print_spaces(n: usize) {
for _ in (0..n) {
print!(" ");
}
}
fn aux<T: Clone + Display + Debug>(current: Vec<Tree<(T, f64)>>, mut next: Vec<Tree<(T, f64)>>, offset: f64) {
// FIXME: does not take into account displacement due to the size of the printed node value
let factor = 1.0; // FIXME: hardcoded offset factor
match current.first() {
None =>
if!next.is_empty() {
println!("");
print!(" "); // FIXME: hardcoded offset
aux(next, vec![], 0.0);
},
Some(t) => {
let o =
match *t {
Tip => offset,
Node(ref l, (ref v, x), ref r) => {
let sp = x - offset;
print_spaces((sp * factor) as usize);
print!("{}", v);
next.push((**l).clone());
next.push((**r).clone());
sp
}
};
aux(current.tail().to_vec(), next, o);
}
}
}
aux(vec![], vec![(*t).clone()], 0.0);
}
pub fn move_by_leftmost<T: Clone>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn move_by_offset<T: Clone>(t: &Tree<(T, f64)>, o: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
Node(Rc::new(move_by_offset(&*l, o)), (v.clone(), x + o), Rc::new(move_by_offset(&*r, o)))
}
}
}
fn find_leftmost<T>(t: &Tree<(T, f64)>, current: f64) -> f64 {
match *t {
Tip => current,
Node(ref l, (_, x), ref r) => {
let n = x.min(current);
find_leftmost(l, n).min(find_leftmost(r, n))
}
}
}
move_by_offset(t, -find_leftmost(t, 0.0))
}
pub fn absolute_new<T: Clone + Display>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn aux<T: Clone + Display>(t: &Tree<(T, f64)>, d: f64, vd: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
let a = d + x;
let d = a + (a.signum() * vd);
let nvd = vd + (format!("{}", v).len() as f64);
println!("nvd: {}", nvd);
Node(Rc::new(aux(&*l, a, nvd)), (v.clone(), d), Rc::new(aux(&*r, a, nvd)))
}
}
}
aux(t, 0.0, 0.0)
}
pub fn absolute<T: Clone + Display>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn aux<T: Clone + Display>(t: &Tree<(T, f64)>, d: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
let a = d + x;
Node(Rc::new(aux(&*l, a)), (v.clone(), a), Rc::new(aux(&*r, a)))
}
}
}
aux(t, 0.0)
}
pub fn design<T: Clone>(t: &Tree<T>) -> Tree<(T, f64)> {
fn aux<T: Clone>(t: &Tree<T>) -> (Tree<(T, f64)>, Extent) {
match *t {
Tip => (Tip, vec![]),
Node(ref l, ref v, ref r) => {
let (trees, extents): (Vec<Tree<(T, f64)>>, Vec<Extent>) = vec![aux(l), aux(r)].into_iter().unzip();
let positions = fit_list(extents.clone());
let ptrees: Vec<Tree<(T, f64)>> = trees.iter().zip(positions.iter()).map(|f| {
let (t, x) = f;
move_tree(t, *x)
}).collect();
let pextents = extents.into_iter().zip(positions.iter()).map(|f| {
let (e, x) = f;
move_extent(e, *x)
}).collect();
let mut resultextent = merge_extents(pextents);
resultextent.insert(0, (0.0, 0.0));
let resulttree = Node(Rc::new(ptrees[0].clone()), ((*v).clone(), 0.0), Rc::new(ptrees[1].clone()));
(resulttree, resultextent)
}
}
}
aux(t).0
}
fn move_tree<T: Clone>(t: &Tree<(T, f64)>, x1: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => Node(l.clone(), (v.clone(), x + x1), r.clone())
}
}
type Extent = Vec<(f64, f64)>;
fn fit_list(es: Vec<Extent>) -> Vec<f64> {
fn mean(x: f64, y: f64) -> f64 {
(x + y) / 2.0
}
fit_list_left(es.clone()).iter().zip(
fit_list_right(es.clone()).iter())
.map(|x| mean(*x.0, *x.1)).collect()
}
fn fit_list_right(es: Vec<Extent>) -> Vec<f64> {
fn flip_extent(e: Extent) -> Extent {
e.iter().map(|&x| {
let (p, q) = x;
(-q, -p)
}).collect()
}
fit_list_left(
es.iter().rev().map(|e| flip_extent((*e).clone())).collect()).iter()
.map(|&f| -f).rev().collect()
}
fn fit_list_left(es: Vec<Extent>) -> Vec<f64> {
fn | (es: Vec<Extent>, acc: Extent) -> Vec<f64> {
match es.first() {
Some(e) => {
let x = fit(acc.clone(), e.clone());
let mut r = aux(es.tail().to_vec(), merge_extent(acc.clone(), move_extent(e.clone().to_vec(), x)));
r.insert(0, x);
r
},
None => vec![]
}
}
aux(es, vec![])
}
fn rmax(p: f64, q: f64) -> f64 {
if p > q { p } else { q }
}
fn fit(e1: Extent, e2: Extent) -> f64 {
match (e1.first(), e2.first()) {
(Some(&(_, p)), Some(&(q, _))) =>
rmax(fit(e1.tail().to_vec(), e2.tail().to_vec()), p - q + 1.0),
(_, _) => 0.0
}
}
fn merge_extent(e1: Extent, e2: Extent) -> Extent {
match (e1.first(), e2.first()) {
(None, _) => e2,
(_, None) => e1,
(Some(&(p, _)), Some(&(_, q))) => {
let mut m = merge_extent(e1.tail().to_vec(), e2.tail().to_vec());
m.insert(0, (p, q));
m
}
}
}
fn merge_extents(es: Vec<Extent>) -> Extent {
es.iter().fold(vec![], |acc, e| {
merge_extent(acc, e.clone())
})
}
fn move_extent(e: Extent, x: f64) -> Extent {
e.iter().map(|&e| {
let (p, q) = e;
(p + x, q + x)
}).collect()
}
| aux | identifier_name |
tree_layout.rs | use std::fmt::{Debug, Display};
use std::num::Float;
use std::rc::Rc;
use tree::Tree;
use tree::Tree::{Node, Tip};
// Tree layout algorithm based on the following paper:
// "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)"
// (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf)
pub fn pretty_print<T: Clone + Display + Debug>(t: &Tree<(T, f64)>) {
fn print_spaces(n: usize) {
for _ in (0..n) {
print!(" ");
}
}
fn aux<T: Clone + Display + Debug>(current: Vec<Tree<(T, f64)>>, mut next: Vec<Tree<(T, f64)>>, offset: f64) {
// FIXME: does not take into account displacement due to the size of the printed node value
let factor = 1.0; // FIXME: hardcoded offset factor
match current.first() {
None =>
if!next.is_empty() {
println!("");
print!(" "); // FIXME: hardcoded offset
aux(next, vec![], 0.0);
},
Some(t) => {
let o =
match *t {
Tip => offset,
Node(ref l, (ref v, x), ref r) => {
let sp = x - offset;
print_spaces((sp * factor) as usize);
print!("{}", v);
next.push((**l).clone());
next.push((**r).clone());
sp
}
};
aux(current.tail().to_vec(), next, o);
}
}
}
aux(vec![], vec![(*t).clone()], 0.0);
}
pub fn move_by_leftmost<T: Clone>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn move_by_offset<T: Clone>(t: &Tree<(T, f64)>, o: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
Node(Rc::new(move_by_offset(&*l, o)), (v.clone(), x + o), Rc::new(move_by_offset(&*r, o)))
}
}
}
fn find_leftmost<T>(t: &Tree<(T, f64)>, current: f64) -> f64 {
match *t {
Tip => current,
Node(ref l, (_, x), ref r) => {
let n = x.min(current);
find_leftmost(l, n).min(find_leftmost(r, n))
}
}
}
move_by_offset(t, -find_leftmost(t, 0.0))
}
pub fn absolute_new<T: Clone + Display>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn aux<T: Clone + Display>(t: &Tree<(T, f64)>, d: f64, vd: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
let a = d + x;
let d = a + (a.signum() * vd);
let nvd = vd + (format!("{}", v).len() as f64);
println!("nvd: {}", nvd);
Node(Rc::new(aux(&*l, a, nvd)), (v.clone(), d), Rc::new(aux(&*r, a, nvd)))
}
}
}
aux(t, 0.0, 0.0)
}
pub fn absolute<T: Clone + Display>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn aux<T: Clone + Display>(t: &Tree<(T, f64)>, d: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
let a = d + x;
Node(Rc::new(aux(&*l, a)), (v.clone(), a), Rc::new(aux(&*r, a)))
}
}
}
aux(t, 0.0)
}
pub fn design<T: Clone>(t: &Tree<T>) -> Tree<(T, f64)> {
fn aux<T: Clone>(t: &Tree<T>) -> (Tree<(T, f64)>, Extent) {
match *t {
Tip => (Tip, vec![]),
Node(ref l, ref v, ref r) => {
let (trees, extents): (Vec<Tree<(T, f64)>>, Vec<Extent>) = vec![aux(l), aux(r)].into_iter().unzip();
let positions = fit_list(extents.clone());
let ptrees: Vec<Tree<(T, f64)>> = trees.iter().zip(positions.iter()).map(|f| {
let (t, x) = f;
move_tree(t, *x)
}).collect();
let pextents = extents.into_iter().zip(positions.iter()).map(|f| {
let (e, x) = f;
move_extent(e, *x)
}).collect();
let mut resultextent = merge_extents(pextents);
resultextent.insert(0, (0.0, 0.0));
let resulttree = Node(Rc::new(ptrees[0].clone()), ((*v).clone(), 0.0), Rc::new(ptrees[1].clone()));
(resulttree, resultextent)
}
}
}
aux(t).0
}
fn move_tree<T: Clone>(t: &Tree<(T, f64)>, x1: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => Node(l.clone(), (v.clone(), x + x1), r.clone())
}
}
type Extent = Vec<(f64, f64)>;
fn fit_list(es: Vec<Extent>) -> Vec<f64> {
fn mean(x: f64, y: f64) -> f64 {
(x + y) / 2.0
}
fit_list_left(es.clone()).iter().zip(
fit_list_right(es.clone()).iter())
.map(|x| mean(*x.0, *x.1)).collect()
}
fn fit_list_right(es: Vec<Extent>) -> Vec<f64> |
fn fit_list_left(es: Vec<Extent>) -> Vec<f64> {
fn aux(es: Vec<Extent>, acc: Extent) -> Vec<f64> {
match es.first() {
Some(e) => {
let x = fit(acc.clone(), e.clone());
let mut r = aux(es.tail().to_vec(), merge_extent(acc.clone(), move_extent(e.clone().to_vec(), x)));
r.insert(0, x);
r
},
None => vec![]
}
}
aux(es, vec![])
}
fn rmax(p: f64, q: f64) -> f64 {
if p > q { p } else { q }
}
fn fit(e1: Extent, e2: Extent) -> f64 {
match (e1.first(), e2.first()) {
(Some(&(_, p)), Some(&(q, _))) =>
rmax(fit(e1.tail().to_vec(), e2.tail().to_vec()), p - q + 1.0),
(_, _) => 0.0
}
}
fn merge_extent(e1: Extent, e2: Extent) -> Extent {
match (e1.first(), e2.first()) {
(None, _) => e2,
(_, None) => e1,
(Some(&(p, _)), Some(&(_, q))) => {
let mut m = merge_extent(e1.tail().to_vec(), e2.tail().to_vec());
m.insert(0, (p, q));
m
}
}
}
fn merge_extents(es: Vec<Extent>) -> Extent {
es.iter().fold(vec![], |acc, e| {
merge_extent(acc, e.clone())
})
}
fn move_extent(e: Extent, x: f64) -> Extent {
e.iter().map(|&e| {
let (p, q) = e;
(p + x, q + x)
}).collect()
}
| {
fn flip_extent(e: Extent) -> Extent {
e.iter().map(|&x| {
let (p, q) = x;
(-q, -p)
}).collect()
}
fit_list_left(
es.iter().rev().map(|e| flip_extent((*e).clone())).collect()).iter()
.map(|&f| -f).rev().collect()
} | identifier_body |
tree_layout.rs | use std::fmt::{Debug, Display};
use std::num::Float;
use std::rc::Rc;
use tree::Tree;
use tree::Tree::{Node, Tip};
// Tree layout algorithm based on the following paper:
// "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)"
// (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf)
pub fn pretty_print<T: Clone + Display + Debug>(t: &Tree<(T, f64)>) {
fn print_spaces(n: usize) {
for _ in (0..n) {
print!(" ");
}
}
fn aux<T: Clone + Display + Debug>(current: Vec<Tree<(T, f64)>>, mut next: Vec<Tree<(T, f64)>>, offset: f64) {
// FIXME: does not take into account displacement due to the size of the printed node value
let factor = 1.0; // FIXME: hardcoded offset factor
match current.first() {
None =>
if!next.is_empty() {
println!("");
print!(" "); // FIXME: hardcoded offset
aux(next, vec![], 0.0);
},
Some(t) => {
let o =
match *t {
Tip => offset,
Node(ref l, (ref v, x), ref r) => {
let sp = x - offset;
print_spaces((sp * factor) as usize);
print!("{}", v);
next.push((**l).clone());
next.push((**r).clone());
sp
}
};
aux(current.tail().to_vec(), next, o);
}
}
}
aux(vec![], vec![(*t).clone()], 0.0);
}
pub fn move_by_leftmost<T: Clone>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn move_by_offset<T: Clone>(t: &Tree<(T, f64)>, o: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
Node(Rc::new(move_by_offset(&*l, o)), (v.clone(), x + o), Rc::new(move_by_offset(&*r, o)))
}
}
}
fn find_leftmost<T>(t: &Tree<(T, f64)>, current: f64) -> f64 {
match *t {
Tip => current,
Node(ref l, (_, x), ref r) => {
let n = x.min(current);
find_leftmost(l, n).min(find_leftmost(r, n))
}
}
}
move_by_offset(t, -find_leftmost(t, 0.0))
}
pub fn absolute_new<T: Clone + Display>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn aux<T: Clone + Display>(t: &Tree<(T, f64)>, d: f64, vd: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
let a = d + x;
let d = a + (a.signum() * vd);
let nvd = vd + (format!("{}", v).len() as f64);
println!("nvd: {}", nvd);
Node(Rc::new(aux(&*l, a, nvd)), (v.clone(), d), Rc::new(aux(&*r, a, nvd)))
}
}
}
aux(t, 0.0, 0.0)
}
pub fn absolute<T: Clone + Display>(t: &Tree<(T, f64)>) -> Tree<(T, f64)> {
fn aux<T: Clone + Display>(t: &Tree<(T, f64)>, d: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => {
let a = d + x;
Node(Rc::new(aux(&*l, a)), (v.clone(), a), Rc::new(aux(&*r, a)))
}
}
}
aux(t, 0.0)
}
pub fn design<T: Clone>(t: &Tree<T>) -> Tree<(T, f64)> {
fn aux<T: Clone>(t: &Tree<T>) -> (Tree<(T, f64)>, Extent) {
match *t {
Tip => (Tip, vec![]),
Node(ref l, ref v, ref r) => {
let (trees, extents): (Vec<Tree<(T, f64)>>, Vec<Extent>) = vec![aux(l), aux(r)].into_iter().unzip();
let positions = fit_list(extents.clone());
let ptrees: Vec<Tree<(T, f64)>> = trees.iter().zip(positions.iter()).map(|f| {
let (t, x) = f;
move_tree(t, *x)
}).collect();
let pextents = extents.into_iter().zip(positions.iter()).map(|f| {
let (e, x) = f;
move_extent(e, *x)
}).collect();
let mut resultextent = merge_extents(pextents);
resultextent.insert(0, (0.0, 0.0));
let resulttree = Node(Rc::new(ptrees[0].clone()), ((*v).clone(), 0.0), Rc::new(ptrees[1].clone()));
(resulttree, resultextent)
}
}
}
aux(t).0
}
fn move_tree<T: Clone>(t: &Tree<(T, f64)>, x1: f64) -> Tree<(T, f64)> {
match *t {
Tip => Tip,
Node(ref l, (ref v, x), ref r) => Node(l.clone(), (v.clone(), x + x1), r.clone())
}
}
type Extent = Vec<(f64, f64)>;
fn fit_list(es: Vec<Extent>) -> Vec<f64> { | fit_list_right(es.clone()).iter())
.map(|x| mean(*x.0, *x.1)).collect()
}
fn fit_list_right(es: Vec<Extent>) -> Vec<f64> {
fn flip_extent(e: Extent) -> Extent {
e.iter().map(|&x| {
let (p, q) = x;
(-q, -p)
}).collect()
}
fit_list_left(
es.iter().rev().map(|e| flip_extent((*e).clone())).collect()).iter()
.map(|&f| -f).rev().collect()
}
fn fit_list_left(es: Vec<Extent>) -> Vec<f64> {
fn aux(es: Vec<Extent>, acc: Extent) -> Vec<f64> {
match es.first() {
Some(e) => {
let x = fit(acc.clone(), e.clone());
let mut r = aux(es.tail().to_vec(), merge_extent(acc.clone(), move_extent(e.clone().to_vec(), x)));
r.insert(0, x);
r
},
None => vec![]
}
}
aux(es, vec![])
}
fn rmax(p: f64, q: f64) -> f64 {
if p > q { p } else { q }
}
fn fit(e1: Extent, e2: Extent) -> f64 {
match (e1.first(), e2.first()) {
(Some(&(_, p)), Some(&(q, _))) =>
rmax(fit(e1.tail().to_vec(), e2.tail().to_vec()), p - q + 1.0),
(_, _) => 0.0
}
}
fn merge_extent(e1: Extent, e2: Extent) -> Extent {
match (e1.first(), e2.first()) {
(None, _) => e2,
(_, None) => e1,
(Some(&(p, _)), Some(&(_, q))) => {
let mut m = merge_extent(e1.tail().to_vec(), e2.tail().to_vec());
m.insert(0, (p, q));
m
}
}
}
fn merge_extents(es: Vec<Extent>) -> Extent {
es.iter().fold(vec![], |acc, e| {
merge_extent(acc, e.clone())
})
}
fn move_extent(e: Extent, x: f64) -> Extent {
e.iter().map(|&e| {
let (p, q) = e;
(p + x, q + x)
}).collect()
} | fn mean(x: f64, y: f64) -> f64 {
(x + y) / 2.0
}
fit_list_left(es.clone()).iter().zip( | random_line_split |
signature.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::ops::{Deref, DerefMut};
use std::cmp::PartialEq;
use std::fmt;
use std::str::FromStr;
use std::hash::{Hash, Hasher};
use secp256k1::{Message as SecpMessage, RecoverableSignature, RecoveryId, Error as SecpError};
use secp256k1::key::{SecretKey, PublicKey};
use rustc_hex::{ToHex, FromHex};
use bigint::hash::{H520, H256};
use {Secret, Public, SECP256K1, Error, Message, public_to_address, Address};
/// Signature encoded as RSV components
#[repr(C)]
pub struct Signature([u8; 65]);
impl Signature {
/// Get a slice into the 'r' portion of the data.
pub fn r(&self) -> &[u8] {
&self.0[0..32]
}
/// Get a slice into the's' portion of the data.
pub fn s(&self) -> &[u8] {
&self.0[32..64]
}
/// Get the recovery byte.
pub fn v(&self) -> u8 {
self.0[64]
}
/// Encode the signature into RSV array (V altered to be in "Electrum" notation).
pub fn into_electrum(mut self) -> [u8; 65] {
self.0[64] += 27;
self.0
}
/// Parse bytes as a signature encoded as RSV (V in "Electrum" notation).
/// May return empty (invalid) signature if given data has invalid length.
pub fn from_electrum(data: &[u8]) -> Self {
if data.len()!= 65 || data[64] < 27 {
// fallback to empty (invalid) signature
return Signature::default();
}
let mut sig = [0u8; 65];
sig.copy_from_slice(data);
sig[64] -= 27;
Signature(sig)
}
/// Create a signature object from the sig.
pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Self {
let mut sig = [0u8; 65];
sig[0..32].copy_from_slice(&r);
sig[32..64].copy_from_slice(&s);
sig[64] = v;
Signature(sig)
}
/// Check if this is a "low" signature.
pub fn | (&self) -> bool {
H256::from_slice(self.s()) <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into()
}
/// Check if each component of the signature is in range.
pub fn is_valid(&self) -> bool {
self.v() <= 1 &&
H256::from_slice(self.r()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
H256::from_slice(self.r()) >= 1.into() &&
H256::from_slice(self.s()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
H256::from_slice(self.s()) >= 1.into()
}
}
// manual implementation large arrays don't have trait impls by default.
// remove when integer generics exist
impl PartialEq for Signature {
fn eq(&self, other: &Self) -> bool {
&self.0[..] == &other.0[..]
}
}
// manual implementation required in Rust 1.13+, see `std::cmp::AssertParamIsEq`.
impl Eq for Signature { }
// also manual for the same reason, but the pretty printing might be useful.
impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Signature")
.field("r", &self.0[0..32].to_hex())
.field("s", &self.0[32..64].to_hex())
.field("v", &self.0[64..65].to_hex())
.finish()
}
}
impl fmt::Display for Signature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_hex())
}
}
impl FromStr for Signature {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.from_hex() {
Ok(ref hex) if hex.len() == 65 => {
let mut data = [0; 65];
data.copy_from_slice(&hex[0..65]);
Ok(Signature(data))
},
_ => Err(Error::InvalidSignature)
}
}
}
impl Default for Signature {
fn default() -> Self {
Signature([0; 65])
}
}
impl Hash for Signature {
fn hash<H: Hasher>(&self, state: &mut H) {
H520::from(self.0).hash(state);
}
}
impl Clone for Signature {
fn clone(&self) -> Self {
Signature(self.0)
}
}
impl From<[u8; 65]> for Signature {
fn from(s: [u8; 65]) -> Self {
Signature(s)
}
}
impl Into<[u8; 65]> for Signature {
fn into(self) -> [u8; 65] {
self.0
}
}
impl From<Signature> for H520 {
fn from(s: Signature) -> Self {
H520::from(s.0)
}
}
impl From<H520> for Signature {
fn from(bytes: H520) -> Self {
Signature(bytes.into())
}
}
impl Deref for Signature {
type Target = [u8; 65];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Signature {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub fn sign(secret: &Secret, message: &Message) -> Result<Signature, Error> {
let context = &SECP256K1;
let sec = SecretKey::from_slice(context, &secret)?;
let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, &sec)?;
let (rec_id, data) = s.serialize_compact(context);
let mut data_arr = [0; 65];
// no need to check if s is low, it always is
data_arr[0..64].copy_from_slice(&data[0..64]);
data_arr[64] = rec_id.to_i32() as u8;
Ok(Signature(data_arr))
}
pub fn verify_public(public: &Public, signature: &Signature, message: &Message) -> Result<bool, Error> {
let context = &SECP256K1;
let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let sig = rsig.to_standard(context);
let pdata: [u8; 65] = {
let mut temp = [4u8; 65];
temp[1..65].copy_from_slice(&**public);
temp
};
let publ = PublicKey::from_slice(context, &pdata)?;
match context.verify(&SecpMessage::from_slice(&message[..])?, &sig, &publ) {
Ok(_) => Ok(true),
Err(SecpError::IncorrectSignature) => Ok(false),
Err(x) => Err(Error::from(x))
}
}
pub fn verify_address(address: &Address, signature: &Signature, message: &Message) -> Result<bool, Error> {
let public = recover(signature, message)?;
let recovered_address = public_to_address(&public);
Ok(address == &recovered_address)
}
pub fn recover(signature: &Signature, message: &Message) -> Result<Public, Error> {
let context = &SECP256K1;
let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?;
let serialized = pubkey.serialize_vec(context, false);
let mut public = Public::default();
public.copy_from_slice(&serialized[1..65]);
Ok(public)
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use {Generator, Random, Message};
use super::{sign, verify_public, verify_address, recover, Signature};
#[test]
fn vrs_conversion() {
// given
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
// when
let vrs = signature.clone().into_electrum();
let from_vrs = Signature::from_electrum(&vrs);
// then
assert_eq!(signature, from_vrs);
}
#[test]
fn signature_to_and_from_str() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
let string = format!("{}", signature);
let deserialized = Signature::from_str(&string).unwrap();
assert_eq!(signature, deserialized);
}
#[test]
fn sign_and_recover_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert_eq!(keypair.public(), &recover(&signature, &message).unwrap());
}
#[test]
fn sign_and_verify_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert!(verify_public(keypair.public(), &signature, &message).unwrap());
}
#[test]
fn sign_and_verify_address() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert!(verify_address(&keypair.address(), &signature, &message).unwrap());
}
}
| is_low_s | identifier_name |
signature.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::ops::{Deref, DerefMut};
use std::cmp::PartialEq;
use std::fmt;
use std::str::FromStr;
use std::hash::{Hash, Hasher};
use secp256k1::{Message as SecpMessage, RecoverableSignature, RecoveryId, Error as SecpError};
use secp256k1::key::{SecretKey, PublicKey};
use rustc_hex::{ToHex, FromHex};
use bigint::hash::{H520, H256};
use {Secret, Public, SECP256K1, Error, Message, public_to_address, Address};
/// Signature encoded as RSV components
#[repr(C)]
pub struct Signature([u8; 65]);
impl Signature {
/// Get a slice into the 'r' portion of the data.
pub fn r(&self) -> &[u8] {
&self.0[0..32]
}
/// Get a slice into the's' portion of the data.
pub fn s(&self) -> &[u8] {
&self.0[32..64]
}
/// Get the recovery byte.
pub fn v(&self) -> u8 {
self.0[64]
}
/// Encode the signature into RSV array (V altered to be in "Electrum" notation).
pub fn into_electrum(mut self) -> [u8; 65] {
self.0[64] += 27;
self.0
}
/// Parse bytes as a signature encoded as RSV (V in "Electrum" notation).
/// May return empty (invalid) signature if given data has invalid length.
pub fn from_electrum(data: &[u8]) -> Self {
if data.len()!= 65 || data[64] < 27 {
// fallback to empty (invalid) signature
return Signature::default();
}
let mut sig = [0u8; 65];
sig.copy_from_slice(data);
sig[64] -= 27;
Signature(sig)
}
/// Create a signature object from the sig.
pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Self {
let mut sig = [0u8; 65];
sig[0..32].copy_from_slice(&r);
sig[32..64].copy_from_slice(&s);
sig[64] = v;
Signature(sig)
}
/// Check if this is a "low" signature.
pub fn is_low_s(&self) -> bool {
H256::from_slice(self.s()) <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into()
}
/// Check if each component of the signature is in range.
pub fn is_valid(&self) -> bool {
self.v() <= 1 &&
H256::from_slice(self.r()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
H256::from_slice(self.r()) >= 1.into() &&
H256::from_slice(self.s()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
H256::from_slice(self.s()) >= 1.into()
}
}
// manual implementation large arrays don't have trait impls by default.
// remove when integer generics exist
impl PartialEq for Signature {
fn eq(&self, other: &Self) -> bool {
&self.0[..] == &other.0[..]
}
}
// manual implementation required in Rust 1.13+, see `std::cmp::AssertParamIsEq`.
impl Eq for Signature { }
// also manual for the same reason, but the pretty printing might be useful.
impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Signature")
.field("r", &self.0[0..32].to_hex())
.field("s", &self.0[32..64].to_hex())
.field("v", &self.0[64..65].to_hex())
.finish()
}
}
impl fmt::Display for Signature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_hex())
}
}
impl FromStr for Signature {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.from_hex() {
Ok(ref hex) if hex.len() == 65 => {
let mut data = [0; 65];
data.copy_from_slice(&hex[0..65]);
Ok(Signature(data))
},
_ => Err(Error::InvalidSignature)
}
}
}
impl Default for Signature {
fn default() -> Self {
Signature([0; 65])
}
}
impl Hash for Signature {
fn hash<H: Hasher>(&self, state: &mut H) {
H520::from(self.0).hash(state);
}
}
impl Clone for Signature {
fn clone(&self) -> Self {
Signature(self.0)
}
}
impl From<[u8; 65]> for Signature {
fn from(s: [u8; 65]) -> Self {
Signature(s)
}
}
impl Into<[u8; 65]> for Signature {
fn into(self) -> [u8; 65] {
self.0
}
}
impl From<Signature> for H520 {
fn from(s: Signature) -> Self {
H520::from(s.0)
}
}
impl From<H520> for Signature {
fn from(bytes: H520) -> Self {
Signature(bytes.into())
}
}
impl Deref for Signature {
type Target = [u8; 65];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Signature {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub fn sign(secret: &Secret, message: &Message) -> Result<Signature, Error> {
let context = &SECP256K1;
let sec = SecretKey::from_slice(context, &secret)?;
let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, &sec)?;
let (rec_id, data) = s.serialize_compact(context);
let mut data_arr = [0; 65];
// no need to check if s is low, it always is
data_arr[0..64].copy_from_slice(&data[0..64]);
data_arr[64] = rec_id.to_i32() as u8;
Ok(Signature(data_arr))
}
pub fn verify_public(public: &Public, signature: &Signature, message: &Message) -> Result<bool, Error> {
let context = &SECP256K1;
let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let sig = rsig.to_standard(context);
let pdata: [u8; 65] = {
let mut temp = [4u8; 65];
temp[1..65].copy_from_slice(&**public);
temp
};
let publ = PublicKey::from_slice(context, &pdata)?;
match context.verify(&SecpMessage::from_slice(&message[..])?, &sig, &publ) {
Ok(_) => Ok(true),
Err(SecpError::IncorrectSignature) => Ok(false),
Err(x) => Err(Error::from(x))
}
}
pub fn verify_address(address: &Address, signature: &Signature, message: &Message) -> Result<bool, Error> {
let public = recover(signature, message)?;
let recovered_address = public_to_address(&public);
Ok(address == &recovered_address)
}
pub fn recover(signature: &Signature, message: &Message) -> Result<Public, Error> {
let context = &SECP256K1;
let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?;
let serialized = pubkey.serialize_vec(context, false);
let mut public = Public::default();
public.copy_from_slice(&serialized[1..65]);
Ok(public)
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use {Generator, Random, Message};
use super::{sign, verify_public, verify_address, recover, Signature};
#[test]
fn vrs_conversion() {
// given
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
// when
let vrs = signature.clone().into_electrum();
let from_vrs = Signature::from_electrum(&vrs);
// then
assert_eq!(signature, from_vrs);
}
#[test]
fn signature_to_and_from_str() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
let string = format!("{}", signature);
let deserialized = Signature::from_str(&string).unwrap();
assert_eq!(signature, deserialized);
}
#[test]
fn sign_and_recover_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert_eq!(keypair.public(), &recover(&signature, &message).unwrap());
}
#[test]
fn sign_and_verify_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert!(verify_public(keypair.public(), &signature, &message).unwrap());
}
#[test]
fn sign_and_verify_address() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap(); | assert!(verify_address(&keypair.address(), &signature, &message).unwrap());
}
} | random_line_split |
|
signature.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::ops::{Deref, DerefMut};
use std::cmp::PartialEq;
use std::fmt;
use std::str::FromStr;
use std::hash::{Hash, Hasher};
use secp256k1::{Message as SecpMessage, RecoverableSignature, RecoveryId, Error as SecpError};
use secp256k1::key::{SecretKey, PublicKey};
use rustc_hex::{ToHex, FromHex};
use bigint::hash::{H520, H256};
use {Secret, Public, SECP256K1, Error, Message, public_to_address, Address};
/// Signature encoded as RSV components
#[repr(C)]
pub struct Signature([u8; 65]);
impl Signature {
/// Get a slice into the 'r' portion of the data.
pub fn r(&self) -> &[u8] {
&self.0[0..32]
}
/// Get a slice into the's' portion of the data.
pub fn s(&self) -> &[u8] {
&self.0[32..64]
}
/// Get the recovery byte.
pub fn v(&self) -> u8 {
self.0[64]
}
/// Encode the signature into RSV array (V altered to be in "Electrum" notation).
pub fn into_electrum(mut self) -> [u8; 65] {
self.0[64] += 27;
self.0
}
/// Parse bytes as a signature encoded as RSV (V in "Electrum" notation).
/// May return empty (invalid) signature if given data has invalid length.
pub fn from_electrum(data: &[u8]) -> Self {
if data.len()!= 65 || data[64] < 27 {
// fallback to empty (invalid) signature
return Signature::default();
}
let mut sig = [0u8; 65];
sig.copy_from_slice(data);
sig[64] -= 27;
Signature(sig)
}
/// Create a signature object from the sig.
pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Self {
let mut sig = [0u8; 65];
sig[0..32].copy_from_slice(&r);
sig[32..64].copy_from_slice(&s);
sig[64] = v;
Signature(sig)
}
/// Check if this is a "low" signature.
pub fn is_low_s(&self) -> bool {
H256::from_slice(self.s()) <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into()
}
/// Check if each component of the signature is in range.
pub fn is_valid(&self) -> bool {
self.v() <= 1 &&
H256::from_slice(self.r()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
H256::from_slice(self.r()) >= 1.into() &&
H256::from_slice(self.s()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
H256::from_slice(self.s()) >= 1.into()
}
}
// manual implementation large arrays don't have trait impls by default.
// remove when integer generics exist
impl PartialEq for Signature {
fn eq(&self, other: &Self) -> bool {
&self.0[..] == &other.0[..]
}
}
// manual implementation required in Rust 1.13+, see `std::cmp::AssertParamIsEq`.
impl Eq for Signature { }
// also manual for the same reason, but the pretty printing might be useful.
impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Signature")
.field("r", &self.0[0..32].to_hex())
.field("s", &self.0[32..64].to_hex())
.field("v", &self.0[64..65].to_hex())
.finish()
}
}
impl fmt::Display for Signature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_hex())
}
}
impl FromStr for Signature {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.from_hex() {
Ok(ref hex) if hex.len() == 65 => {
let mut data = [0; 65];
data.copy_from_slice(&hex[0..65]);
Ok(Signature(data))
},
_ => Err(Error::InvalidSignature)
}
}
}
impl Default for Signature {
fn default() -> Self {
Signature([0; 65])
}
}
impl Hash for Signature {
fn hash<H: Hasher>(&self, state: &mut H) {
H520::from(self.0).hash(state);
}
}
impl Clone for Signature {
fn clone(&self) -> Self {
Signature(self.0)
}
}
impl From<[u8; 65]> for Signature {
fn from(s: [u8; 65]) -> Self {
Signature(s)
}
}
impl Into<[u8; 65]> for Signature {
fn into(self) -> [u8; 65] {
self.0
}
}
impl From<Signature> for H520 {
fn from(s: Signature) -> Self {
H520::from(s.0)
}
}
impl From<H520> for Signature {
fn from(bytes: H520) -> Self {
Signature(bytes.into())
}
}
impl Deref for Signature {
type Target = [u8; 65];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Signature {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub fn sign(secret: &Secret, message: &Message) -> Result<Signature, Error> {
let context = &SECP256K1;
let sec = SecretKey::from_slice(context, &secret)?;
let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, &sec)?;
let (rec_id, data) = s.serialize_compact(context);
let mut data_arr = [0; 65];
// no need to check if s is low, it always is
data_arr[0..64].copy_from_slice(&data[0..64]);
data_arr[64] = rec_id.to_i32() as u8;
Ok(Signature(data_arr))
}
pub fn verify_public(public: &Public, signature: &Signature, message: &Message) -> Result<bool, Error> {
let context = &SECP256K1;
let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let sig = rsig.to_standard(context);
let pdata: [u8; 65] = {
let mut temp = [4u8; 65];
temp[1..65].copy_from_slice(&**public);
temp
};
let publ = PublicKey::from_slice(context, &pdata)?;
match context.verify(&SecpMessage::from_slice(&message[..])?, &sig, &publ) {
Ok(_) => Ok(true),
Err(SecpError::IncorrectSignature) => Ok(false),
Err(x) => Err(Error::from(x))
}
}
pub fn verify_address(address: &Address, signature: &Signature, message: &Message) -> Result<bool, Error> {
let public = recover(signature, message)?;
let recovered_address = public_to_address(&public);
Ok(address == &recovered_address)
}
pub fn recover(signature: &Signature, message: &Message) -> Result<Public, Error> |
#[cfg(test)]
mod tests {
use std::str::FromStr;
use {Generator, Random, Message};
use super::{sign, verify_public, verify_address, recover, Signature};
#[test]
fn vrs_conversion() {
// given
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
// when
let vrs = signature.clone().into_electrum();
let from_vrs = Signature::from_electrum(&vrs);
// then
assert_eq!(signature, from_vrs);
}
#[test]
fn signature_to_and_from_str() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
let string = format!("{}", signature);
let deserialized = Signature::from_str(&string).unwrap();
assert_eq!(signature, deserialized);
}
#[test]
fn sign_and_recover_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert_eq!(keypair.public(), &recover(&signature, &message).unwrap());
}
#[test]
fn sign_and_verify_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert!(verify_public(keypair.public(), &signature, &message).unwrap());
}
#[test]
fn sign_and_verify_address() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign(keypair.secret(), &message).unwrap();
assert!(verify_address(&keypair.address(), &signature, &message).unwrap());
}
}
| {
let context = &SECP256K1;
let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?;
let serialized = pubkey.serialize_vec(context, false);
let mut public = Public::default();
public.copy_from_slice(&serialized[1..65]);
Ok(public)
} | identifier_body |
by-value-non-immediate-argument.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.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print s
// gdb-check:$1 = {a = 1, b = 2.5}
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = {a = 3, b = 4.5}
// gdb-command:print y
// gdb-check:$3 = 5
// gdb-command:print z
// gdb-check:$4 = 6.5
// gdb-command:continue
// gdb-command:print a
// gdb-check:$5 = {7, 8, 9.5, 10.5}
// gdb-command:continue
// gdb-command:print a
// gdb-check:$6 = {11.5, 12.5, 13, 14}
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = {{RUST$ENUM$DISR = Case1, x = 0, y = 8970181431921507452}, {RUST$ENUM$DISR = Case1, 0, 2088533116, 2088533116}}
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print s
// lldb-check:[...]$0 = Struct { a: 1, b: 2.5 }
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$1 = Struct { a: 3, b: 4.5 }
// lldb-command:print y
// lldb-check:[...]$2 = 5
// lldb-command:print z
// lldb-check:[...]$3 = 6.5
// lldb-command:continue
// lldb-command:print a
// lldb-check:[...]$4 = (7, 8, 9.5, 10.5)
// lldb-command:continue
// lldb-command:print a
// lldb-check:[...]$5 = Newtype(11.5, 12.5, 13, 14)
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$6 = Case1 { x: 0, y: 8970181431921507452 }
// lldb-command:continue
#[deriving(Clone)]
struct Struct {
a: int,
b: f64
}
#[deriving(Clone)]
struct StructStruct {
a: Struct,
b: Struct
}
fn fun(s: Struct) {
zzz(); // #break
}
fn fun_fun(StructStruct { a: x, b: Struct { a: y, b: z } }: StructStruct) {
zzz(); // #break
}
fn | (a: (int, uint, f64, f64)) {
zzz(); // #break
}
struct Newtype(f64, f64, int, uint);
fn new_type(a: Newtype) {
zzz(); // #break
}
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Enum {
Case1 { x: i64, y: i64 },
Case2 (i64, i32, i32),
}
fn by_val_enum(x: Enum) {
zzz(); // #break
}
fn main() {
fun(Struct { a: 1, b: 2.5 });
fun_fun(StructStruct { a: Struct { a: 3, b: 4.5 }, b: Struct { a: 5, b: 6.5 } });
tup((7, 8, 9.5, 10.5));
new_type(Newtype(11.5, 12.5, 13, 14));
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
by_val_enum(Enum::Case1 { x: 0, y: 8970181431921507452 });
}
fn zzz() { () }
| tup | identifier_name |
by-value-non-immediate-argument.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.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print s
// gdb-check:$1 = {a = 1, b = 2.5}
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = {a = 3, b = 4.5}
// gdb-command:print y
// gdb-check:$3 = 5
// gdb-command:print z
// gdb-check:$4 = 6.5
// gdb-command:continue
// gdb-command:print a
// gdb-check:$5 = {7, 8, 9.5, 10.5}
// gdb-command:continue
// gdb-command:print a
// gdb-check:$6 = {11.5, 12.5, 13, 14}
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = {{RUST$ENUM$DISR = Case1, x = 0, y = 8970181431921507452}, {RUST$ENUM$DISR = Case1, 0, 2088533116, 2088533116}}
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print s
// lldb-check:[...]$0 = Struct { a: 1, b: 2.5 }
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$1 = Struct { a: 3, b: 4.5 }
// lldb-command:print y
// lldb-check:[...]$2 = 5
// lldb-command:print z
// lldb-check:[...]$3 = 6.5
// lldb-command:continue
// lldb-command:print a
// lldb-check:[...]$4 = (7, 8, 9.5, 10.5)
// lldb-command:continue
// lldb-command:print a
// lldb-check:[...]$5 = Newtype(11.5, 12.5, 13, 14)
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$6 = Case1 { x: 0, y: 8970181431921507452 }
// lldb-command:continue
#[deriving(Clone)]
struct Struct {
a: int,
b: f64
}
#[deriving(Clone)]
struct StructStruct {
a: Struct,
b: Struct
}
fn fun(s: Struct) {
zzz(); // #break
}
fn fun_fun(StructStruct { a: x, b: Struct { a: y, b: z } }: StructStruct) |
fn tup(a: (int, uint, f64, f64)) {
zzz(); // #break
}
struct Newtype(f64, f64, int, uint);
fn new_type(a: Newtype) {
zzz(); // #break
}
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Enum {
Case1 { x: i64, y: i64 },
Case2 (i64, i32, i32),
}
fn by_val_enum(x: Enum) {
zzz(); // #break
}
fn main() {
fun(Struct { a: 1, b: 2.5 });
fun_fun(StructStruct { a: Struct { a: 3, b: 4.5 }, b: Struct { a: 5, b: 6.5 } });
tup((7, 8, 9.5, 10.5));
new_type(Newtype(11.5, 12.5, 13, 14));
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
by_val_enum(Enum::Case1 { x: 0, y: 8970181431921507452 });
}
fn zzz() { () }
| {
zzz(); // #break
} | identifier_body |
by-value-non-immediate-argument.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.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print s
// gdb-check:$1 = {a = 1, b = 2.5}
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = {a = 3, b = 4.5}
// gdb-command:print y
// gdb-check:$3 = 5
// gdb-command:print z
// gdb-check:$4 = 6.5
// gdb-command:continue
// gdb-command:print a
// gdb-check:$5 = {7, 8, 9.5, 10.5}
// gdb-command:continue
// gdb-command:print a
// gdb-check:$6 = {11.5, 12.5, 13, 14}
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = {{RUST$ENUM$DISR = Case1, x = 0, y = 8970181431921507452}, {RUST$ENUM$DISR = Case1, 0, 2088533116, 2088533116}}
// gdb-command:continue |
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print s
// lldb-check:[...]$0 = Struct { a: 1, b: 2.5 }
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$1 = Struct { a: 3, b: 4.5 }
// lldb-command:print y
// lldb-check:[...]$2 = 5
// lldb-command:print z
// lldb-check:[...]$3 = 6.5
// lldb-command:continue
// lldb-command:print a
// lldb-check:[...]$4 = (7, 8, 9.5, 10.5)
// lldb-command:continue
// lldb-command:print a
// lldb-check:[...]$5 = Newtype(11.5, 12.5, 13, 14)
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$6 = Case1 { x: 0, y: 8970181431921507452 }
// lldb-command:continue
#[deriving(Clone)]
struct Struct {
a: int,
b: f64
}
#[deriving(Clone)]
struct StructStruct {
a: Struct,
b: Struct
}
fn fun(s: Struct) {
zzz(); // #break
}
fn fun_fun(StructStruct { a: x, b: Struct { a: y, b: z } }: StructStruct) {
zzz(); // #break
}
fn tup(a: (int, uint, f64, f64)) {
zzz(); // #break
}
struct Newtype(f64, f64, int, uint);
fn new_type(a: Newtype) {
zzz(); // #break
}
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Enum {
Case1 { x: i64, y: i64 },
Case2 (i64, i32, i32),
}
fn by_val_enum(x: Enum) {
zzz(); // #break
}
fn main() {
fun(Struct { a: 1, b: 2.5 });
fun_fun(StructStruct { a: Struct { a: 3, b: 4.5 }, b: Struct { a: 5, b: 6.5 } });
tup((7, 8, 9.5, 10.5));
new_type(Newtype(11.5, 12.5, 13, 14));
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
by_val_enum(Enum::Case1 { x: 0, y: 8970181431921507452 });
}
fn zzz() { () } | random_line_split |
|
lib.rs | ', the appropriate prefix and suffix will be
/// added based on the compilation target.
///
/// This function will exit the process with `EXIT_FAILURE` if any stage of
/// compilation or linking fails.
///
/// # Example
/// ```no_run
/// extern crate ispc_compile;
///
/// ispc_compile::compile_library("foo", &["src/foo.ispc", "src/bar.ispc"]);
/// ```
pub fn compile_library(lib: &str, files: &[&str]) {
let mut cfg = Config::new();
for f in &files[..] {
cfg.file(*f);
}
cfg.compile(lib)
}
/// Handy wrapper around calling exit that will log the message passed first
/// then exit with a failure exit code.
macro_rules! exit_failure {
($fmt:expr) => {{
eprintln!($fmt);
std::process::exit(libc::EXIT_FAILURE);
}};
($fmt:expr, $($arg:tt)*) => {{
eprintln!($fmt, $($arg)*);
std::process::exit(libc::EXIT_FAILURE);
}}
}
/// Extra configuration to be passed to ISPC
pub struct Config {
ispc_version: Version,
ispc_files: Vec<PathBuf>,
objects: Vec<PathBuf>,
headers: Vec<PathBuf>,
include_paths: Vec<PathBuf>,
// We need to generate a single header so we have one header to give bindgen
bindgen_header: PathBuf,
// These options are set from the environment if not set by the user
out_dir: Option<PathBuf>,
debug: Option<bool>,
opt_level: Option<u32>,
target: Option<String>,
cargo_metadata: bool,
// Additional ISPC compiler options that the user can set
defines: Vec<(String, Option<String>)>,
math_lib: MathLib,
addressing: Option<Addressing>,
optimization_opts: BTreeSet<OptimizationOpt>,
cpu_target: Option<CPU>,
force_alignment: Option<u32>,
no_omit_frame_ptr: bool,
no_stdlib: bool,
no_cpp: bool,
quiet: bool,
werror: bool,
woff: bool,
wno_perf: bool,
instrument: bool,
target_isa: Option<Vec<TargetISA>>,
architecture: Option<Architecture>,
target_os: Option<TargetOS>,
}
impl Config {
pub fn | () -> Config {
// Query the ISPC compiler version. This also acts as a check that we can
// find the ISPC compiler when we need it later.
let cmd_output = Command::new("ispc")
.arg("--version")
.output()
.expect("Failed to find ISPC compiler in PATH");
if!cmd_output.status.success() {
exit_failure!("Failed to get ISPC version, is it in your PATH?");
}
let ver_string = String::from_utf8_lossy(&cmd_output.stdout);
// The ISPC version will be the first version number printed
let re = Regex::new(r"(\d+\.\d+\.\d+)").unwrap();
let ispc_ver = Version::parse(
re.captures_iter(&ver_string)
.next()
.expect("Failed to parse ISPC version")
.get(1)
.expect("Failed to parse ISPC version")
.as_str(),
)
.expect("Failed to parse ISPC version");
Config {
ispc_version: ispc_ver,
ispc_files: Vec::new(),
objects: Vec::new(),
headers: Vec::new(),
include_paths: Vec::new(),
bindgen_header: PathBuf::new(),
out_dir: None,
debug: None,
opt_level: None,
target: None,
cargo_metadata: true,
defines: Vec::new(),
math_lib: MathLib::ISPCDefault,
addressing: None,
optimization_opts: BTreeSet::new(),
cpu_target: None,
force_alignment: None,
no_omit_frame_ptr: false,
no_stdlib: false,
no_cpp: false,
quiet: false,
werror: false,
woff: false,
wno_perf: false,
instrument: false,
target_isa: None,
architecture: None,
target_os: None,
}
}
/// Add an ISPC file to be compiled
pub fn file<P: AsRef<Path>>(&mut self, file: P) -> &mut Config {
self.ispc_files.push(file.as_ref().to_path_buf());
self
}
/// Set the output directory to override the default of `env!("OUT_DIR")`
pub fn out_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Config {
self.out_dir = Some(dir.as_ref().to_path_buf());
self
}
/// Set whether debug symbols should be generated, symbols are generated by
/// default if `env!("DEBUG") == "true"`
pub fn debug(&mut self, debug: bool) -> &mut Config {
self.debug = Some(debug);
self
}
/// Set the optimization level to override the default of `env!("OPT_LEVEL")`
pub fn opt_level(&mut self, opt_level: u32) -> &mut Config {
self.opt_level = Some(opt_level);
self
}
/// Set the target triple to compile for, overriding the default of `env!("TARGET")`
pub fn target(&mut self, target: &str) -> &mut Config {
self.target = Some(target.to_string());
self
}
/// Add a define to be passed to the ISPC compiler, e.g. `-DFOO`
/// or `-DBAR=FOO` if a value should also be set.
pub fn add_define(&mut self, define: &str, value: Option<&str>) -> &mut Config {
self.defines
.push((define.to_string(), value.map(|s| s.to_string())));
self
}
/// Select the 32 or 64 bit addressing calculations for addressing calculations in ISPC.
pub fn addressing(&mut self, addressing: Addressing) -> &mut Config {
self.addressing = Some(addressing);
self
}
/// Set the math library used by ISPC code, defaults to the ISPC math library.
pub fn math_lib(&mut self, math_lib: MathLib) -> &mut Config {
self.math_lib = math_lib;
self
}
/// Set an optimization option.
pub fn optimization_opt(&mut self, opt: OptimizationOpt) -> &mut Config {
self.optimization_opts.insert(opt);
self
}
/// Set the cpu target. This overrides the default choice of ISPC which
/// is to target the host CPU.
pub fn cpu(&mut self, cpu: CPU) -> &mut Config {
self.cpu_target = Some(cpu);
self
}
/// Force ISPC memory allocations to be aligned to `alignment`.
pub fn force_alignment(&mut self, alignment: u32) -> &mut Config {
self.force_alignment = Some(alignment);
self
}
/// Add an extra include path for the ispc compiler to search for files.
pub fn include_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Config {
self.include_paths.push(path.as_ref().to_path_buf());
self
}
/// Disable frame pointer omission. It may be useful for profiling to
/// disable omission.
pub fn no_omit_frame_pointer(&mut self) -> &mut Config {
self.no_omit_frame_ptr = true;
self
}
/// Don't make the ispc standard library available.
pub fn no_stdlib(&mut self) -> &mut Config {
self.no_stdlib = true;
self
}
/// Don't run the C preprocessor
pub fn no_cpp(&mut self) -> &mut Config {
self.no_cpp = true;
self
}
/// Enable suppression of all ispc compiler output.
pub fn quiet(&mut self) -> &mut Config {
self.quiet = true;
self
}
/// Enable treating warnings as errors.
pub fn werror(&mut self) -> &mut Config {
self.werror = true;
self
}
/// Disable all warnings.
pub fn woff(&mut self) -> &mut Config {
self.woff = true;
self
}
/// Don't issue warnings related to performance issues
pub fn wno_perf(&mut self) -> &mut Config {
self.wno_perf = true;
self
}
/// Emit instrumentation code for ISPC to gather performance data such
/// as vector utilization.
pub fn instrument(&mut self) -> &mut Config {
let min_ver = Version {
major: 1,
minor: 9,
patch: 1,
pre: Prerelease::EMPTY,
build: BuildMetadata::EMPTY,
};
if self.ispc_version < min_ver {
exit_failure!(
"Error: instrumentation is not supported on ISPC versions \
older than 1.9.1 as it generates a non-C compatible header"
);
}
self.instrument = true;
self
}
/// Select the target ISA and vector width. If none is specified ispc will
/// choose the host CPU ISA and vector width.
pub fn target_isa(&mut self, target: TargetISA) -> &mut Config {
self.target_isa = Some(vec![target]);
self
}
/// Select multiple target ISAs and vector widths. If none is specified ispc will
/// choose the host CPU ISA and vector width.
/// Note that certain options are not compatible with this use case,
/// e.g. AVX1.1 will replace AVX1, Host should not be passed (just use the default)
pub fn target_isas(&mut self, targets: Vec<TargetISA>) -> &mut Config {
self.target_isa = Some(targets);
self
}
/// Select the CPU architecture to target
pub fn target_arch(&mut self, arch: Architecture) -> &mut Config {
self.architecture = Some(arch);
self
}
/// Select the target OS for cross compilation
pub fn target_os(&mut self, os: TargetOS) -> &mut Config {
self.target_os = Some(os);
self
}
/// Set whether Cargo metadata should be emitted to link to the compiled library
pub fn cargo_metadata(&mut self, metadata: bool) -> &mut Config {
self.cargo_metadata = metadata;
self
}
/// The library name should not have any prefix or suffix, e.g. instead of
/// `libexample.a` or `example.lib` simply pass `example`
pub fn compile(&mut self, lib: &str) {
let dst = self.get_out_dir();
let build_dir = self.get_build_dir();
let default_args = self.default_args();
for s in &self.ispc_files[..] {
let fname = s
.file_stem()
.expect("ISPC source files must be files")
.to_str()
.expect("ISPC source file names must be valid UTF-8");
self.print(&format!("cargo:rerun-if-changed={}", s.display()));
let ispc_fname = String::from(fname) + "_ispc";
let object = build_dir.join(ispc_fname.clone()).with_extension("o");
let header = build_dir.join(ispc_fname.clone()).with_extension("h");
let deps = build_dir.join(ispc_fname.clone()).with_extension("idep");
let output = Command::new("ispc")
.args(&default_args[..])
.arg(s)
.arg("-o")
.arg(&object)
.arg("-h")
.arg(&header)
.arg("-MMM")
.arg(&deps)
.output()
.unwrap();
if!output.stderr.is_empty() {
let stderr = String::from_utf8_lossy(&output.stderr);
for l in stderr.lines() {
self.print(&format!("cargo:warning=(ISPC) {}", l));
}
}
if!output.status.success() {
exit_failure!("Failed to compile ISPC source file {}", s.display());
}
self.objects.push(object);
self.headers.push(header);
// Go this files dependencies and add them to Cargo's watch list
let deps_list = File::open(deps)
.expect(&format!("Failed to open dependencies list for {}", s.display())[..]);
let reader = BufReader::new(deps_list);
for d in reader.lines() {
// Don't depend on the ISPC "stdlib" file which is output as a dependecy
let dep_name = d.unwrap();
self.print(&format!("cargo:rerun-if-changed={}", dep_name));
}
// Push on the additional ISA-specific object files if any were generated
if let Some(ref t) = self.target_isa {
if t.len() > 1 {
for isa in t.iter() {
let isa_fname = ispc_fname.clone() + "_" + &isa.lib_suffix();
let isa_obj = build_dir.join(isa_fname).with_extension("o");
self.objects.push(isa_obj);
}
}
}
}
let libfile = lib.to_owned() + &self.get_target();
if!self.assemble(&libfile).success() {
exit_failure!("Failed to assemble ISPC objects into library {}", lib);
}
self.print(&format!("cargo:rustc-link-lib=static={}", libfile));
// Now generate a header we can give to bindgen and generate bindings
self.generate_bindgen_header(lib);
let bindings = bindgen::Builder::default().header(self.bindgen_header.to_str().unwrap());
let bindgen_file = dst.join(lib).with_extension("rs");
let generated_bindings = match bindings.generate() {
Ok(b) => b.to_string(),
Err(_) => exit_failure!("Failed to generating Rust bindings to {}", lib),
};
let mut file = match File::create(bindgen_file) {
Ok(f) => f,
Err(e) => exit_failure!("Failed to open bindgen mod file for writing: {}", e),
};
file.write_all("#[allow(non_camel_case_types,dead_code,non_upper_case_globals,non_snake_case,improper_ctypes)]\n"
.as_bytes()).unwrap();
file.write_all(format!("pub mod {} {{\n", lib).as_bytes())
.unwrap();
file.write_all(generated_bindings.as_bytes()).unwrap();
file.write_all(b"}").unwrap();
self.print(&format!("cargo:rustc-link-search=native={}", dst.display()));
self.print(&format!("cargo:rustc-env=ISPC_OUT_DIR={}", dst.display()));
}
/// Get the ISPC compiler version.
pub fn ispc_version(&self) -> &Version {
&self.ispc_version
}
/// Link the ISPC code into a static library on Unix using `ar`
#[cfg(unix)]
fn assemble(&self, lib: &str) -> ExitStatus {
Command::new("ar")
.arg("crus")
.arg(format!("lib{}.a", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Link the ISPC code into a static library on Windows using `lib.exe`
#[cfg(windows)]
fn assemble(&self, lib: &str) -> ExitStatus {
let target = self.get_target();
let mut lib_cmd = gcc::windows_registry::find_tool(&target[..], "lib.exe")
.expect("Failed to find lib.exe for MSVC toolchain, aborting")
.to_command();
lib_cmd
.arg(format!("/OUT:{}.lib", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Generate a single header that includes all of our ISPC headers which we can
/// pass to bindgen
fn generate_bindgen_header(&mut self, lib: &str) {
self.bindgen_header = self
.get_build_dir()
.join(format!("_{}_ispc_bindgen_header.h", lib));
let mut include_file = File::create(&self.bindgen_header).unwrap();
writeln!(include_file, "#include <stdint.h>").unwrap();
writeln!(include_file, "#include <stdbool.h>").unwrap();
for h in &self.headers[..] {
writeln!(include_file, "#include \"{}\"", h.display()).unwrap();
}
}
/// Build up list of basic args for each target, debug, opt level, etc.
fn default_args(&self) -> Vec<String> {
let mut ispc_args = Vec::new();
let opt_level = self.get_opt_level();
if self.get_debug() && opt_level == 0 {
ispc_args.push(String::from("-g"));
}
if let Some(ref c) = self.cpu_target {
ispc_args.push(c.to_string());
// The ispc compiler crashes if we give -O0 and --cpu=generic,
// see https://github.com/ispc/ispc/issues/1223
if *c!= CPU::Generic || (*c == CPU::Generic && opt_level!= 0) {
ispc_args.push(String::from("-O") + &opt_level.to_string());
} else {
self.print(
&"cargo:warning=ispc-rs: Omitting -O0 on CPU::Generic target, ispc bug 1223",
);
}
} else {
ispc_args.push(String::from("-O") + &opt_level.to_string());
}
// If we're on Unix we need position independent code
if cfg!(unix) {
ispc_args.push(String::from("--pic"));
}
let target = self.get_target();
if target.starts_with("i686") {
ispc_args.push(String::from("--arch=x86"));
} else if target.starts_with("x86_64") {
ispc_args.push(String::from("--arch=x86-64"));
} else if target.starts_with("aarch64") {
ispc_args.push(String::from("--arch=aarch64"));
}
for d in &self.defines {
match d.1 {
Some(ref v) => ispc_args.push(format!("-D{}={}", d.0, v)),
None => ispc_args.push(format!("-D{}", d.0)),
}
}
ispc_args.push(self.math_lib.to_string());
if let Some(ref s) = self.addressing {
ispc_args.push(s.to_string());
}
if let Some(ref f) = self.force_alignment {
ispc_args.push(String::from("--force-alignment=") + &f.to_string());
}
for o in &self.optimization_opts {
ispc_args.push(o.to_string());
}
for p in &self.include_paths {
ispc_args.push(format!("-I{}", p.display()));
}
if self.no_omit_frame_ptr {
ispc_args.push(String::from("--no-omit-frame-pointer"));
}
if self.no_stdlib {
ispc_args.push(String::from("--nostdlib"));
}
if self.no_cpp {
ispc_args.push(String::from("--nocpp"));
}
if self.quiet {
ispc_args.push(String::from("--quiet"));
}
if self.werror {
ispc_args.push(String::from("--werror"));
}
if self.woff {
ispc_args.push(String::from("--woff"));
}
if self.wno_perf {
ispc_args.push(String::from("--wno-perf"));
}
if self.instrument {
ispc_args.push(String::from("--instrument"));
}
if | new | identifier_name |
lib.rs | ', the appropriate prefix and suffix will be
/// added based on the compilation target.
///
/// This function will exit the process with `EXIT_FAILURE` if any stage of
/// compilation or linking fails.
///
/// # Example
/// ```no_run
/// extern crate ispc_compile;
///
/// ispc_compile::compile_library("foo", &["src/foo.ispc", "src/bar.ispc"]);
/// ```
pub fn compile_library(lib: &str, files: &[&str]) {
let mut cfg = Config::new();
for f in &files[..] {
cfg.file(*f);
}
cfg.compile(lib)
}
/// Handy wrapper around calling exit that will log the message passed first
/// then exit with a failure exit code.
macro_rules! exit_failure {
($fmt:expr) => {{
eprintln!($fmt);
std::process::exit(libc::EXIT_FAILURE);
}};
($fmt:expr, $($arg:tt)*) => {{
eprintln!($fmt, $($arg)*);
std::process::exit(libc::EXIT_FAILURE);
}}
}
/// Extra configuration to be passed to ISPC
pub struct Config {
ispc_version: Version,
ispc_files: Vec<PathBuf>,
objects: Vec<PathBuf>,
headers: Vec<PathBuf>,
include_paths: Vec<PathBuf>,
// We need to generate a single header so we have one header to give bindgen
bindgen_header: PathBuf,
// These options are set from the environment if not set by the user
out_dir: Option<PathBuf>,
debug: Option<bool>,
opt_level: Option<u32>,
target: Option<String>,
cargo_metadata: bool,
// Additional ISPC compiler options that the user can set
defines: Vec<(String, Option<String>)>,
math_lib: MathLib,
addressing: Option<Addressing>,
optimization_opts: BTreeSet<OptimizationOpt>,
cpu_target: Option<CPU>,
force_alignment: Option<u32>,
no_omit_frame_ptr: bool,
no_stdlib: bool,
no_cpp: bool,
quiet: bool,
werror: bool,
woff: bool,
wno_perf: bool,
instrument: bool,
target_isa: Option<Vec<TargetISA>>,
architecture: Option<Architecture>,
target_os: Option<TargetOS>,
}
impl Config {
pub fn new() -> Config {
// Query the ISPC compiler version. This also acts as a check that we can
// find the ISPC compiler when we need it later.
let cmd_output = Command::new("ispc")
.arg("--version")
.output()
.expect("Failed to find ISPC compiler in PATH");
if!cmd_output.status.success() {
exit_failure!("Failed to get ISPC version, is it in your PATH?");
}
let ver_string = String::from_utf8_lossy(&cmd_output.stdout);
// The ISPC version will be the first version number printed
let re = Regex::new(r"(\d+\.\d+\.\d+)").unwrap();
let ispc_ver = Version::parse(
re.captures_iter(&ver_string)
.next()
.expect("Failed to parse ISPC version")
.get(1)
.expect("Failed to parse ISPC version")
.as_str(),
)
.expect("Failed to parse ISPC version");
Config {
ispc_version: ispc_ver,
ispc_files: Vec::new(),
objects: Vec::new(),
headers: Vec::new(),
include_paths: Vec::new(),
bindgen_header: PathBuf::new(),
out_dir: None,
debug: None,
opt_level: None,
target: None,
cargo_metadata: true,
defines: Vec::new(),
math_lib: MathLib::ISPCDefault,
addressing: None,
optimization_opts: BTreeSet::new(),
cpu_target: None,
force_alignment: None,
no_omit_frame_ptr: false,
no_stdlib: false,
no_cpp: false,
quiet: false,
werror: false,
woff: false,
wno_perf: false,
instrument: false,
target_isa: None,
architecture: None,
target_os: None,
}
}
/// Add an ISPC file to be compiled
pub fn file<P: AsRef<Path>>(&mut self, file: P) -> &mut Config {
self.ispc_files.push(file.as_ref().to_path_buf());
self
}
/// Set the output directory to override the default of `env!("OUT_DIR")`
pub fn out_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Config {
self.out_dir = Some(dir.as_ref().to_path_buf());
self
}
/// Set whether debug symbols should be generated, symbols are generated by
/// default if `env!("DEBUG") == "true"`
pub fn debug(&mut self, debug: bool) -> &mut Config {
self.debug = Some(debug);
self
}
/// Set the optimization level to override the default of `env!("OPT_LEVEL")`
pub fn opt_level(&mut self, opt_level: u32) -> &mut Config {
self.opt_level = Some(opt_level);
self
}
/// Set the target triple to compile for, overriding the default of `env!("TARGET")`
pub fn target(&mut self, target: &str) -> &mut Config {
self.target = Some(target.to_string());
self
}
/// Add a define to be passed to the ISPC compiler, e.g. `-DFOO`
/// or `-DBAR=FOO` if a value should also be set.
pub fn add_define(&mut self, define: &str, value: Option<&str>) -> &mut Config {
self.defines
.push((define.to_string(), value.map(|s| s.to_string())));
self
}
/// Select the 32 or 64 bit addressing calculations for addressing calculations in ISPC.
pub fn addressing(&mut self, addressing: Addressing) -> &mut Config {
self.addressing = Some(addressing);
self
}
/// Set the math library used by ISPC code, defaults to the ISPC math library.
pub fn math_lib(&mut self, math_lib: MathLib) -> &mut Config {
self.math_lib = math_lib;
self
}
/// Set an optimization option.
pub fn optimization_opt(&mut self, opt: OptimizationOpt) -> &mut Config {
self.optimization_opts.insert(opt);
self
}
/// Set the cpu target. This overrides the default choice of ISPC which
/// is to target the host CPU.
pub fn cpu(&mut self, cpu: CPU) -> &mut Config {
self.cpu_target = Some(cpu);
self
}
/// Force ISPC memory allocations to be aligned to `alignment`.
pub fn force_alignment(&mut self, alignment: u32) -> &mut Config {
self.force_alignment = Some(alignment);
self
}
/// Add an extra include path for the ispc compiler to search for files.
pub fn include_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Config {
self.include_paths.push(path.as_ref().to_path_buf());
self
}
/// Disable frame pointer omission. It may be useful for profiling to
/// disable omission.
pub fn no_omit_frame_pointer(&mut self) -> &mut Config {
self.no_omit_frame_ptr = true;
self
}
/// Don't make the ispc standard library available.
pub fn no_stdlib(&mut self) -> &mut Config {
self.no_stdlib = true;
self
}
/// Don't run the C preprocessor
pub fn no_cpp(&mut self) -> &mut Config {
self.no_cpp = true;
self
}
/// Enable suppression of all ispc compiler output.
pub fn quiet(&mut self) -> &mut Config {
self.quiet = true;
self
}
/// Enable treating warnings as errors.
pub fn werror(&mut self) -> &mut Config {
self.werror = true;
self
}
/// Disable all warnings.
pub fn woff(&mut self) -> &mut Config {
self.woff = true;
self
}
/// Don't issue warnings related to performance issues
pub fn wno_perf(&mut self) -> &mut Config {
self.wno_perf = true;
self
}
/// Emit instrumentation code for ISPC to gather performance data such
/// as vector utilization.
pub fn instrument(&mut self) -> &mut Config {
let min_ver = Version {
major: 1,
minor: 9,
patch: 1,
pre: Prerelease::EMPTY,
build: BuildMetadata::EMPTY,
};
if self.ispc_version < min_ver {
exit_failure!(
"Error: instrumentation is not supported on ISPC versions \
older than 1.9.1 as it generates a non-C compatible header"
);
}
self.instrument = true;
self
}
/// Select the target ISA and vector width. If none is specified ispc will
/// choose the host CPU ISA and vector width.
pub fn target_isa(&mut self, target: TargetISA) -> &mut Config {
self.target_isa = Some(vec![target]);
self
}
/// Select multiple target ISAs and vector widths. If none is specified ispc will
/// choose the host CPU ISA and vector width.
/// Note that certain options are not compatible with this use case,
/// e.g. AVX1.1 will replace AVX1, Host should not be passed (just use the default)
pub fn target_isas(&mut self, targets: Vec<TargetISA>) -> &mut Config {
self.target_isa = Some(targets);
self
}
/// Select the CPU architecture to target
pub fn target_arch(&mut self, arch: Architecture) -> &mut Config {
self.architecture = Some(arch);
self
}
/// Select the target OS for cross compilation
pub fn target_os(&mut self, os: TargetOS) -> &mut Config {
self.target_os = Some(os);
self
}
/// Set whether Cargo metadata should be emitted to link to the compiled library
pub fn cargo_metadata(&mut self, metadata: bool) -> &mut Config {
self.cargo_metadata = metadata;
self
}
/// The library name should not have any prefix or suffix, e.g. instead of
/// `libexample.a` or `example.lib` simply pass `example`
pub fn compile(&mut self, lib: &str) {
let dst = self.get_out_dir();
let build_dir = self.get_build_dir();
let default_args = self.default_args();
for s in &self.ispc_files[..] {
let fname = s
.file_stem()
.expect("ISPC source files must be files")
.to_str()
.expect("ISPC source file names must be valid UTF-8");
self.print(&format!("cargo:rerun-if-changed={}", s.display()));
let ispc_fname = String::from(fname) + "_ispc";
let object = build_dir.join(ispc_fname.clone()).with_extension("o");
let header = build_dir.join(ispc_fname.clone()).with_extension("h");
let deps = build_dir.join(ispc_fname.clone()).with_extension("idep");
let output = Command::new("ispc")
.args(&default_args[..])
.arg(s)
.arg("-o")
.arg(&object)
.arg("-h")
.arg(&header)
.arg("-MMM")
.arg(&deps)
.output()
.unwrap();
if!output.stderr.is_empty() {
let stderr = String::from_utf8_lossy(&output.stderr);
for l in stderr.lines() {
self.print(&format!("cargo:warning=(ISPC) {}", l));
}
}
if!output.status.success() {
exit_failure!("Failed to compile ISPC source file {}", s.display());
}
self.objects.push(object);
self.headers.push(header);
// Go this files dependencies and add them to Cargo's watch list
let deps_list = File::open(deps)
.expect(&format!("Failed to open dependencies list for {}", s.display())[..]);
let reader = BufReader::new(deps_list);
for d in reader.lines() {
// Don't depend on the ISPC "stdlib" file which is output as a dependecy
let dep_name = d.unwrap();
self.print(&format!("cargo:rerun-if-changed={}", dep_name));
}
// Push on the additional ISA-specific object files if any were generated
if let Some(ref t) = self.target_isa {
if t.len() > 1 {
for isa in t.iter() {
let isa_fname = ispc_fname.clone() + "_" + &isa.lib_suffix();
let isa_obj = build_dir.join(isa_fname).with_extension("o");
self.objects.push(isa_obj);
}
}
}
}
let libfile = lib.to_owned() + &self.get_target();
if!self.assemble(&libfile).success() {
exit_failure!("Failed to assemble ISPC objects into library {}", lib);
}
self.print(&format!("cargo:rustc-link-lib=static={}", libfile));
// Now generate a header we can give to bindgen and generate bindings
self.generate_bindgen_header(lib);
let bindings = bindgen::Builder::default().header(self.bindgen_header.to_str().unwrap());
let bindgen_file = dst.join(lib).with_extension("rs");
let generated_bindings = match bindings.generate() {
Ok(b) => b.to_string(),
Err(_) => exit_failure!("Failed to generating Rust bindings to {}", lib),
};
let mut file = match File::create(bindgen_file) {
Ok(f) => f,
Err(e) => exit_failure!("Failed to open bindgen mod file for writing: {}", e),
};
file.write_all("#[allow(non_camel_case_types,dead_code,non_upper_case_globals,non_snake_case,improper_ctypes)]\n"
.as_bytes()).unwrap();
file.write_all(format!("pub mod {} {{\n", lib).as_bytes())
.unwrap();
file.write_all(generated_bindings.as_bytes()).unwrap();
file.write_all(b"}").unwrap();
self.print(&format!("cargo:rustc-link-search=native={}", dst.display()));
self.print(&format!("cargo:rustc-env=ISPC_OUT_DIR={}", dst.display()));
}
/// Get the ISPC compiler version.
pub fn ispc_version(&self) -> &Version {
&self.ispc_version
}
/// Link the ISPC code into a static library on Unix using `ar`
#[cfg(unix)]
fn assemble(&self, lib: &str) -> ExitStatus {
Command::new("ar")
.arg("crus")
.arg(format!("lib{}.a", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Link the ISPC code into a static library on Windows using `lib.exe`
#[cfg(windows)]
fn assemble(&self, lib: &str) -> ExitStatus {
let target = self.get_target();
let mut lib_cmd = gcc::windows_registry::find_tool(&target[..], "lib.exe")
.expect("Failed to find lib.exe for MSVC toolchain, aborting")
.to_command();
lib_cmd
.arg(format!("/OUT:{}.lib", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Generate a single header that includes all of our ISPC headers which we can
/// pass to bindgen
fn generate_bindgen_header(&mut self, lib: &str) {
self.bindgen_header = self
.get_build_dir()
.join(format!("_{}_ispc_bindgen_header.h", lib));
let mut include_file = File::create(&self.bindgen_header).unwrap();
writeln!(include_file, "#include <stdint.h>").unwrap();
writeln!(include_file, "#include <stdbool.h>").unwrap();
for h in &self.headers[..] {
writeln!(include_file, "#include \"{}\"", h.display()).unwrap();
}
}
/// Build up list of basic args for each target, debug, opt level, etc.
fn default_args(&self) -> Vec<String> {
let mut ispc_args = Vec::new();
let opt_level = self.get_opt_level();
if self.get_debug() && opt_level == 0 {
ispc_args.push(String::from("-g"));
}
if let Some(ref c) = self.cpu_target {
ispc_args.push(c.to_string());
// The ispc compiler crashes if we give -O0 and --cpu=generic,
// see https://github.com/ispc/ispc/issues/1223
if *c!= CPU::Generic || (*c == CPU::Generic && opt_level!= 0) {
ispc_args.push(String::from("-O") + &opt_level.to_string());
} else {
self.print(
&"cargo:warning=ispc-rs: Omitting -O0 on CPU::Generic target, ispc bug 1223",
);
}
} else {
ispc_args.push(String::from("-O") + &opt_level.to_string());
}
// If we're on Unix we need position independent code
if cfg!(unix) {
ispc_args.push(String::from("--pic"));
}
let target = self.get_target();
if target.starts_with("i686") {
ispc_args.push(String::from("--arch=x86"));
} else if target.starts_with("x86_64") {
ispc_args.push(String::from("--arch=x86-64"));
} else if target.starts_with("aarch64") {
ispc_args.push(String::from("--arch=aarch64"));
}
for d in &self.defines {
match d.1 {
Some(ref v) => ispc_args.push(format!("-D{}={}", d.0, v)),
None => ispc_args.push(format!("-D{}", d.0)),
}
}
ispc_args.push(self.math_lib.to_string());
if let Some(ref s) = self.addressing {
ispc_args.push(s.to_string());
}
if let Some(ref f) = self.force_alignment {
ispc_args.push(String::from("--force-alignment=") + &f.to_string());
}
for o in &self.optimization_opts {
ispc_args.push(o.to_string());
}
for p in &self.include_paths {
ispc_args.push(format!("-I{}", p.display()));
}
if self.no_omit_frame_ptr {
ispc_args.push(String::from("--no-omit-frame-pointer"));
}
if self.no_stdlib {
ispc_args.push(String::from("--nostdlib"));
}
if self.no_cpp {
ispc_args.push(String::from("--nocpp"));
}
if self.quiet {
ispc_args.push(String::from("--quiet"));
}
if self.werror {
ispc_args.push(String::from("--werror"));
}
if self.woff {
ispc_args.push(String::from("--woff"));
}
if self.wno_perf {
ispc_args.push(String::from("--wno-perf"));
}
if self.instrument |
if | {
ispc_args.push(String::from("--instrument"));
} | conditional_block |
lib.rs | pub mod opt;
use std::collections::BTreeSet;
use std::env;
use std::fmt::Display;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use regex::Regex;
use semver::{BuildMetadata, Prerelease, Version};
pub use opt::{Addressing, Architecture, MathLib, OptimizationOpt, TargetISA, TargetOS, CPU};
/// Compile the list of ISPC files into a static library and generate bindings
/// using bindgen. The library name should not contain a lib prefix or a lib
/// extension like '.a' or '.lib', the appropriate prefix and suffix will be
/// added based on the compilation target.
///
/// This function will exit the process with `EXIT_FAILURE` if any stage of
/// compilation or linking fails.
///
/// # Example
/// ```no_run
/// extern crate ispc_compile;
///
/// ispc_compile::compile_library("foo", &["src/foo.ispc", "src/bar.ispc"]);
/// ```
pub fn compile_library(lib: &str, files: &[&str]) {
let mut cfg = Config::new();
for f in &files[..] {
cfg.file(*f);
}
cfg.compile(lib)
}
/// Handy wrapper around calling exit that will log the message passed first
/// then exit with a failure exit code.
macro_rules! exit_failure {
($fmt:expr) => {{
eprintln!($fmt);
std::process::exit(libc::EXIT_FAILURE);
}};
($fmt:expr, $($arg:tt)*) => {{
eprintln!($fmt, $($arg)*);
std::process::exit(libc::EXIT_FAILURE);
}}
}
/// Extra configuration to be passed to ISPC
pub struct Config {
ispc_version: Version,
ispc_files: Vec<PathBuf>,
objects: Vec<PathBuf>,
headers: Vec<PathBuf>,
include_paths: Vec<PathBuf>,
// We need to generate a single header so we have one header to give bindgen
bindgen_header: PathBuf,
// These options are set from the environment if not set by the user
out_dir: Option<PathBuf>,
debug: Option<bool>,
opt_level: Option<u32>,
target: Option<String>,
cargo_metadata: bool,
// Additional ISPC compiler options that the user can set
defines: Vec<(String, Option<String>)>,
math_lib: MathLib,
addressing: Option<Addressing>,
optimization_opts: BTreeSet<OptimizationOpt>,
cpu_target: Option<CPU>,
force_alignment: Option<u32>,
no_omit_frame_ptr: bool,
no_stdlib: bool,
no_cpp: bool,
quiet: bool,
werror: bool,
woff: bool,
wno_perf: bool,
instrument: bool,
target_isa: Option<Vec<TargetISA>>,
architecture: Option<Architecture>,
target_os: Option<TargetOS>,
}
impl Config {
pub fn new() -> Config {
// Query the ISPC compiler version. This also acts as a check that we can
// find the ISPC compiler when we need it later.
let cmd_output = Command::new("ispc")
.arg("--version")
.output()
.expect("Failed to find ISPC compiler in PATH");
if!cmd_output.status.success() {
exit_failure!("Failed to get ISPC version, is it in your PATH?");
}
let ver_string = String::from_utf8_lossy(&cmd_output.stdout);
// The ISPC version will be the first version number printed
let re = Regex::new(r"(\d+\.\d+\.\d+)").unwrap();
let ispc_ver = Version::parse(
re.captures_iter(&ver_string)
.next()
.expect("Failed to parse ISPC version")
.get(1)
.expect("Failed to parse ISPC version")
.as_str(),
)
.expect("Failed to parse ISPC version");
Config {
ispc_version: ispc_ver,
ispc_files: Vec::new(),
objects: Vec::new(),
headers: Vec::new(),
include_paths: Vec::new(),
bindgen_header: PathBuf::new(),
out_dir: None,
debug: None,
opt_level: None,
target: None,
cargo_metadata: true,
defines: Vec::new(),
math_lib: MathLib::ISPCDefault,
addressing: None,
optimization_opts: BTreeSet::new(),
cpu_target: None,
force_alignment: None,
no_omit_frame_ptr: false,
no_stdlib: false,
no_cpp: false,
quiet: false,
werror: false,
woff: false,
wno_perf: false,
instrument: false,
target_isa: None,
architecture: None,
target_os: None,
}
}
/// Add an ISPC file to be compiled
pub fn file<P: AsRef<Path>>(&mut self, file: P) -> &mut Config {
self.ispc_files.push(file.as_ref().to_path_buf());
self
}
/// Set the output directory to override the default of `env!("OUT_DIR")`
pub fn out_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Config {
self.out_dir = Some(dir.as_ref().to_path_buf());
self
}
/// Set whether debug symbols should be generated, symbols are generated by
/// default if `env!("DEBUG") == "true"`
pub fn debug(&mut self, debug: bool) -> &mut Config {
self.debug = Some(debug);
self
}
/// Set the optimization level to override the default of `env!("OPT_LEVEL")`
pub fn opt_level(&mut self, opt_level: u32) -> &mut Config {
self.opt_level = Some(opt_level);
self
}
/// Set the target triple to compile for, overriding the default of `env!("TARGET")`
pub fn target(&mut self, target: &str) -> &mut Config {
self.target = Some(target.to_string());
self
}
/// Add a define to be passed to the ISPC compiler, e.g. `-DFOO`
/// or `-DBAR=FOO` if a value should also be set.
pub fn add_define(&mut self, define: &str, value: Option<&str>) -> &mut Config {
self.defines
.push((define.to_string(), value.map(|s| s.to_string())));
self
}
/// Select the 32 or 64 bit addressing calculations for addressing calculations in ISPC.
pub fn addressing(&mut self, addressing: Addressing) -> &mut Config {
self.addressing = Some(addressing);
self
}
/// Set the math library used by ISPC code, defaults to the ISPC math library.
pub fn math_lib(&mut self, math_lib: MathLib) -> &mut Config {
self.math_lib = math_lib;
self
}
/// Set an optimization option.
pub fn optimization_opt(&mut self, opt: OptimizationOpt) -> &mut Config {
self.optimization_opts.insert(opt);
self
}
/// Set the cpu target. This overrides the default choice of ISPC which
/// is to target the host CPU.
pub fn cpu(&mut self, cpu: CPU) -> &mut Config {
self.cpu_target = Some(cpu);
self
}
/// Force ISPC memory allocations to be aligned to `alignment`.
pub fn force_alignment(&mut self, alignment: u32) -> &mut Config {
self.force_alignment = Some(alignment);
self
}
/// Add an extra include path for the ispc compiler to search for files.
pub fn include_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Config {
self.include_paths.push(path.as_ref().to_path_buf());
self
}
/// Disable frame pointer omission. It may be useful for profiling to
/// disable omission.
pub fn no_omit_frame_pointer(&mut self) -> &mut Config {
self.no_omit_frame_ptr = true;
self
}
/// Don't make the ispc standard library available.
pub fn no_stdlib(&mut self) -> &mut Config {
self.no_stdlib = true;
self
}
/// Don't run the C preprocessor
pub fn no_cpp(&mut self) -> &mut Config {
self.no_cpp = true;
self
}
/// Enable suppression of all ispc compiler output.
pub fn quiet(&mut self) -> &mut Config {
self.quiet = true;
self
}
/// Enable treating warnings as errors.
pub fn werror(&mut self) -> &mut Config {
self.werror = true;
self
}
/// Disable all warnings.
pub fn woff(&mut self) -> &mut Config {
self.woff = true;
self
}
/// Don't issue warnings related to performance issues
pub fn wno_perf(&mut self) -> &mut Config {
self.wno_perf = true;
self
}
/// Emit instrumentation code for ISPC to gather performance data such
/// as vector utilization.
pub fn instrument(&mut self) -> &mut Config {
let min_ver = Version {
major: 1,
minor: 9,
patch: 1,
pre: Prerelease::EMPTY,
build: BuildMetadata::EMPTY,
};
if self.ispc_version < min_ver {
exit_failure!(
"Error: instrumentation is not supported on ISPC versions \
older than 1.9.1 as it generates a non-C compatible header"
);
}
self.instrument = true;
self
}
/// Select the target ISA and vector width. If none is specified ispc will
/// choose the host CPU ISA and vector width.
pub fn target_isa(&mut self, target: TargetISA) -> &mut Config {
self.target_isa = Some(vec![target]);
self
}
/// Select multiple target ISAs and vector widths. If none is specified ispc will
/// choose the host CPU ISA and vector width.
/// Note that certain options are not compatible with this use case,
/// e.g. AVX1.1 will replace AVX1, Host should not be passed (just use the default)
pub fn target_isas(&mut self, targets: Vec<TargetISA>) -> &mut Config {
self.target_isa = Some(targets);
self
}
/// Select the CPU architecture to target
pub fn target_arch(&mut self, arch: Architecture) -> &mut Config {
self.architecture = Some(arch);
self
}
/// Select the target OS for cross compilation
pub fn target_os(&mut self, os: TargetOS) -> &mut Config {
self.target_os = Some(os);
self
}
/// Set whether Cargo metadata should be emitted to link to the compiled library
pub fn cargo_metadata(&mut self, metadata: bool) -> &mut Config {
self.cargo_metadata = metadata;
self
}
/// The library name should not have any prefix or suffix, e.g. instead of
/// `libexample.a` or `example.lib` simply pass `example`
pub fn compile(&mut self, lib: &str) {
let dst = self.get_out_dir();
let build_dir = self.get_build_dir();
let default_args = self.default_args();
for s in &self.ispc_files[..] {
let fname = s
.file_stem()
.expect("ISPC source files must be files")
.to_str()
.expect("ISPC source file names must be valid UTF-8");
self.print(&format!("cargo:rerun-if-changed={}", s.display()));
let ispc_fname = String::from(fname) + "_ispc";
let object = build_dir.join(ispc_fname.clone()).with_extension("o");
let header = build_dir.join(ispc_fname.clone()).with_extension("h");
let deps = build_dir.join(ispc_fname.clone()).with_extension("idep");
let output = Command::new("ispc")
.args(&default_args[..])
.arg(s)
.arg("-o")
.arg(&object)
.arg("-h")
.arg(&header)
.arg("-MMM")
.arg(&deps)
.output()
.unwrap();
if!output.stderr.is_empty() {
let stderr = String::from_utf8_lossy(&output.stderr);
for l in stderr.lines() {
self.print(&format!("cargo:warning=(ISPC) {}", l));
}
}
if!output.status.success() {
exit_failure!("Failed to compile ISPC source file {}", s.display());
}
self.objects.push(object);
self.headers.push(header);
// Go this files dependencies and add them to Cargo's watch list
let deps_list = File::open(deps)
.expect(&format!("Failed to open dependencies list for {}", s.display())[..]);
let reader = BufReader::new(deps_list);
for d in reader.lines() {
// Don't depend on the ISPC "stdlib" file which is output as a dependecy
let dep_name = d.unwrap();
self.print(&format!("cargo:rerun-if-changed={}", dep_name));
}
// Push on the additional ISA-specific object files if any were generated
if let Some(ref t) = self.target_isa {
if t.len() > 1 {
for isa in t.iter() {
let isa_fname = ispc_fname.clone() + "_" + &isa.lib_suffix();
let isa_obj = build_dir.join(isa_fname).with_extension("o");
self.objects.push(isa_obj);
}
}
}
}
let libfile = lib.to_owned() + &self.get_target();
if!self.assemble(&libfile).success() {
exit_failure!("Failed to assemble ISPC objects into library {}", lib);
}
self.print(&format!("cargo:rustc-link-lib=static={}", libfile));
// Now generate a header we can give to bindgen and generate bindings
self.generate_bindgen_header(lib);
let bindings = bindgen::Builder::default().header(self.bindgen_header.to_str().unwrap());
let bindgen_file = dst.join(lib).with_extension("rs");
let generated_bindings = match bindings.generate() {
Ok(b) => b.to_string(),
Err(_) => exit_failure!("Failed to generating Rust bindings to {}", lib),
};
let mut file = match File::create(bindgen_file) {
Ok(f) => f,
Err(e) => exit_failure!("Failed to open bindgen mod file for writing: {}", e),
};
file.write_all("#[allow(non_camel_case_types,dead_code,non_upper_case_globals,non_snake_case,improper_ctypes)]\n"
.as_bytes()).unwrap();
file.write_all(format!("pub mod {} {{\n", lib).as_bytes())
.unwrap();
file.write_all(generated_bindings.as_bytes()).unwrap();
file.write_all(b"}").unwrap();
self.print(&format!("cargo:rustc-link-search=native={}", dst.display()));
self.print(&format!("cargo:rustc-env=ISPC_OUT_DIR={}", dst.display()));
}
/// Get the ISPC compiler version.
pub fn ispc_version(&self) -> &Version {
&self.ispc_version
}
/// Link the ISPC code into a static library on Unix using `ar`
#[cfg(unix)]
fn assemble(&self, lib: &str) -> ExitStatus {
Command::new("ar")
.arg("crus")
.arg(format!("lib{}.a", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Link the ISPC code into a static library on Windows using `lib.exe`
#[cfg(windows)]
fn assemble(&self, lib: &str) -> ExitStatus {
let target = self.get_target();
let mut lib_cmd = gcc::windows_registry::find_tool(&target[..], "lib.exe")
.expect("Failed to find lib.exe for MSVC toolchain, aborting")
.to_command();
lib_cmd
.arg(format!("/OUT:{}.lib", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Generate a single header that includes all of our ISPC headers which we can
/// pass to bindgen
fn generate_bindgen_header(&mut self, lib: &str) {
self.bindgen_header = self
.get_build_dir()
.join(format!("_{}_ispc_bindgen_header.h", lib));
let mut include_file = File::create(&self.bindgen_header).unwrap();
writeln!(include_file, "#include <stdint.h>").unwrap();
writeln!(include_file, "#include <stdbool.h>").unwrap();
for h in &self.headers[..] {
writeln!(include_file, "#include \"{}\"", h.display()).unwrap();
}
}
/// Build up list of basic args for each target, debug, opt level, etc.
fn default_args(&self) -> Vec<String> {
let mut ispc_args = Vec::new();
let opt_level = self.get_opt_level();
if self.get_debug() && opt_level == 0 {
ispc_args.push(String::from("-g"));
}
if let Some(ref c) = self.cpu_target {
ispc_args.push(c.to_string());
// The ispc compiler crashes if we give -O0 and --cpu=generic,
// see https://github.com/ispc/ispc/issues/1223
if *c!= CPU::Generic || (*c == CPU::Generic && opt_level!= 0) {
ispc_args.push(String::from("-O") + &opt_level.to_string());
} else {
self.print(
&"cargo:warning=ispc-rs: Omitting -O0 on CPU::Generic target, ispc bug 1223",
);
}
} else {
ispc_args.push(String::from("-O") + &opt_level.to_string());
}
// If we're on Unix we need position independent code
if cfg!(unix) {
ispc_args.push(String::from("--pic"));
}
let target = self.get_target();
if target.starts_with("i686") {
ispc_args.push(String::from("--arch=x86"));
} else if target.starts_with("x86_64") {
ispc_args.push(String::from("--arch=x86-64"));
} else if target.starts_with("aarch64") {
ispc_args.push(String::from("--arch=aarch64"));
}
for d in &self.defines {
match d.1 {
Some(ref v) => ispc_args.push(format!("-D{}={}", d.0, v)),
None => ispc_args.push(format!("-D{}", d.0)),
}
}
ispc_args.push(self.math_lib.to_string());
if let Some(ref s) = self.addressing {
ispc_args.push(s.to_string());
}
if let Some(ref f) = self.force_alignment {
ispc_args.push(String::from("--force-alignment=") + &f.to_string());
}
for o in &self.optimization_opts {
ispc_args.push(o.to_string());
}
for p in &self.include_paths {
ispc_args.push(format!("-I{}", p.display()));
}
if self.no_omit_frame_ptr {
ispc_args.push(String::from("--no-omit-frame-pointer"));
}
if self.no_stdlib {
ispc_args.push(String::from("--nostdlib"));
}
if self.no_cpp {
ispc_args.push(String::from("--nocpp"));
}
if self.quiet {
ispc_args.push(String::from("--quiet"));
}
if self.werror {
| extern crate gcc;
extern crate libc;
extern crate regex;
extern crate semver;
| random_line_split |
|
lib.rs | .arg("--version")
.output()
.expect("Failed to find ISPC compiler in PATH");
if!cmd_output.status.success() {
exit_failure!("Failed to get ISPC version, is it in your PATH?");
}
let ver_string = String::from_utf8_lossy(&cmd_output.stdout);
// The ISPC version will be the first version number printed
let re = Regex::new(r"(\d+\.\d+\.\d+)").unwrap();
let ispc_ver = Version::parse(
re.captures_iter(&ver_string)
.next()
.expect("Failed to parse ISPC version")
.get(1)
.expect("Failed to parse ISPC version")
.as_str(),
)
.expect("Failed to parse ISPC version");
Config {
ispc_version: ispc_ver,
ispc_files: Vec::new(),
objects: Vec::new(),
headers: Vec::new(),
include_paths: Vec::new(),
bindgen_header: PathBuf::new(),
out_dir: None,
debug: None,
opt_level: None,
target: None,
cargo_metadata: true,
defines: Vec::new(),
math_lib: MathLib::ISPCDefault,
addressing: None,
optimization_opts: BTreeSet::new(),
cpu_target: None,
force_alignment: None,
no_omit_frame_ptr: false,
no_stdlib: false,
no_cpp: false,
quiet: false,
werror: false,
woff: false,
wno_perf: false,
instrument: false,
target_isa: None,
architecture: None,
target_os: None,
}
}
/// Add an ISPC file to be compiled
pub fn file<P: AsRef<Path>>(&mut self, file: P) -> &mut Config {
self.ispc_files.push(file.as_ref().to_path_buf());
self
}
/// Set the output directory to override the default of `env!("OUT_DIR")`
pub fn out_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Config {
self.out_dir = Some(dir.as_ref().to_path_buf());
self
}
/// Set whether debug symbols should be generated, symbols are generated by
/// default if `env!("DEBUG") == "true"`
pub fn debug(&mut self, debug: bool) -> &mut Config {
self.debug = Some(debug);
self
}
/// Set the optimization level to override the default of `env!("OPT_LEVEL")`
pub fn opt_level(&mut self, opt_level: u32) -> &mut Config {
self.opt_level = Some(opt_level);
self
}
/// Set the target triple to compile for, overriding the default of `env!("TARGET")`
pub fn target(&mut self, target: &str) -> &mut Config {
self.target = Some(target.to_string());
self
}
/// Add a define to be passed to the ISPC compiler, e.g. `-DFOO`
/// or `-DBAR=FOO` if a value should also be set.
pub fn add_define(&mut self, define: &str, value: Option<&str>) -> &mut Config {
self.defines
.push((define.to_string(), value.map(|s| s.to_string())));
self
}
/// Select the 32 or 64 bit addressing calculations for addressing calculations in ISPC.
pub fn addressing(&mut self, addressing: Addressing) -> &mut Config {
self.addressing = Some(addressing);
self
}
/// Set the math library used by ISPC code, defaults to the ISPC math library.
pub fn math_lib(&mut self, math_lib: MathLib) -> &mut Config {
self.math_lib = math_lib;
self
}
/// Set an optimization option.
pub fn optimization_opt(&mut self, opt: OptimizationOpt) -> &mut Config {
self.optimization_opts.insert(opt);
self
}
/// Set the cpu target. This overrides the default choice of ISPC which
/// is to target the host CPU.
pub fn cpu(&mut self, cpu: CPU) -> &mut Config {
self.cpu_target = Some(cpu);
self
}
/// Force ISPC memory allocations to be aligned to `alignment`.
pub fn force_alignment(&mut self, alignment: u32) -> &mut Config {
self.force_alignment = Some(alignment);
self
}
/// Add an extra include path for the ispc compiler to search for files.
pub fn include_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Config {
self.include_paths.push(path.as_ref().to_path_buf());
self
}
/// Disable frame pointer omission. It may be useful for profiling to
/// disable omission.
pub fn no_omit_frame_pointer(&mut self) -> &mut Config {
self.no_omit_frame_ptr = true;
self
}
/// Don't make the ispc standard library available.
pub fn no_stdlib(&mut self) -> &mut Config {
self.no_stdlib = true;
self
}
/// Don't run the C preprocessor
pub fn no_cpp(&mut self) -> &mut Config {
self.no_cpp = true;
self
}
/// Enable suppression of all ispc compiler output.
pub fn quiet(&mut self) -> &mut Config {
self.quiet = true;
self
}
/// Enable treating warnings as errors.
pub fn werror(&mut self) -> &mut Config {
self.werror = true;
self
}
/// Disable all warnings.
pub fn woff(&mut self) -> &mut Config {
self.woff = true;
self
}
/// Don't issue warnings related to performance issues
pub fn wno_perf(&mut self) -> &mut Config {
self.wno_perf = true;
self
}
/// Emit instrumentation code for ISPC to gather performance data such
/// as vector utilization.
pub fn instrument(&mut self) -> &mut Config {
let min_ver = Version {
major: 1,
minor: 9,
patch: 1,
pre: Prerelease::EMPTY,
build: BuildMetadata::EMPTY,
};
if self.ispc_version < min_ver {
exit_failure!(
"Error: instrumentation is not supported on ISPC versions \
older than 1.9.1 as it generates a non-C compatible header"
);
}
self.instrument = true;
self
}
/// Select the target ISA and vector width. If none is specified ispc will
/// choose the host CPU ISA and vector width.
pub fn target_isa(&mut self, target: TargetISA) -> &mut Config {
self.target_isa = Some(vec![target]);
self
}
/// Select multiple target ISAs and vector widths. If none is specified ispc will
/// choose the host CPU ISA and vector width.
/// Note that certain options are not compatible with this use case,
/// e.g. AVX1.1 will replace AVX1, Host should not be passed (just use the default)
pub fn target_isas(&mut self, targets: Vec<TargetISA>) -> &mut Config {
self.target_isa = Some(targets);
self
}
/// Select the CPU architecture to target
pub fn target_arch(&mut self, arch: Architecture) -> &mut Config {
self.architecture = Some(arch);
self
}
/// Select the target OS for cross compilation
pub fn target_os(&mut self, os: TargetOS) -> &mut Config {
self.target_os = Some(os);
self
}
/// Set whether Cargo metadata should be emitted to link to the compiled library
pub fn cargo_metadata(&mut self, metadata: bool) -> &mut Config {
self.cargo_metadata = metadata;
self
}
/// The library name should not have any prefix or suffix, e.g. instead of
/// `libexample.a` or `example.lib` simply pass `example`
pub fn compile(&mut self, lib: &str) {
let dst = self.get_out_dir();
let build_dir = self.get_build_dir();
let default_args = self.default_args();
for s in &self.ispc_files[..] {
let fname = s
.file_stem()
.expect("ISPC source files must be files")
.to_str()
.expect("ISPC source file names must be valid UTF-8");
self.print(&format!("cargo:rerun-if-changed={}", s.display()));
let ispc_fname = String::from(fname) + "_ispc";
let object = build_dir.join(ispc_fname.clone()).with_extension("o");
let header = build_dir.join(ispc_fname.clone()).with_extension("h");
let deps = build_dir.join(ispc_fname.clone()).with_extension("idep");
let output = Command::new("ispc")
.args(&default_args[..])
.arg(s)
.arg("-o")
.arg(&object)
.arg("-h")
.arg(&header)
.arg("-MMM")
.arg(&deps)
.output()
.unwrap();
if!output.stderr.is_empty() {
let stderr = String::from_utf8_lossy(&output.stderr);
for l in stderr.lines() {
self.print(&format!("cargo:warning=(ISPC) {}", l));
}
}
if!output.status.success() {
exit_failure!("Failed to compile ISPC source file {}", s.display());
}
self.objects.push(object);
self.headers.push(header);
// Go this files dependencies and add them to Cargo's watch list
let deps_list = File::open(deps)
.expect(&format!("Failed to open dependencies list for {}", s.display())[..]);
let reader = BufReader::new(deps_list);
for d in reader.lines() {
// Don't depend on the ISPC "stdlib" file which is output as a dependecy
let dep_name = d.unwrap();
self.print(&format!("cargo:rerun-if-changed={}", dep_name));
}
// Push on the additional ISA-specific object files if any were generated
if let Some(ref t) = self.target_isa {
if t.len() > 1 {
for isa in t.iter() {
let isa_fname = ispc_fname.clone() + "_" + &isa.lib_suffix();
let isa_obj = build_dir.join(isa_fname).with_extension("o");
self.objects.push(isa_obj);
}
}
}
}
let libfile = lib.to_owned() + &self.get_target();
if!self.assemble(&libfile).success() {
exit_failure!("Failed to assemble ISPC objects into library {}", lib);
}
self.print(&format!("cargo:rustc-link-lib=static={}", libfile));
// Now generate a header we can give to bindgen and generate bindings
self.generate_bindgen_header(lib);
let bindings = bindgen::Builder::default().header(self.bindgen_header.to_str().unwrap());
let bindgen_file = dst.join(lib).with_extension("rs");
let generated_bindings = match bindings.generate() {
Ok(b) => b.to_string(),
Err(_) => exit_failure!("Failed to generating Rust bindings to {}", lib),
};
let mut file = match File::create(bindgen_file) {
Ok(f) => f,
Err(e) => exit_failure!("Failed to open bindgen mod file for writing: {}", e),
};
file.write_all("#[allow(non_camel_case_types,dead_code,non_upper_case_globals,non_snake_case,improper_ctypes)]\n"
.as_bytes()).unwrap();
file.write_all(format!("pub mod {} {{\n", lib).as_bytes())
.unwrap();
file.write_all(generated_bindings.as_bytes()).unwrap();
file.write_all(b"}").unwrap();
self.print(&format!("cargo:rustc-link-search=native={}", dst.display()));
self.print(&format!("cargo:rustc-env=ISPC_OUT_DIR={}", dst.display()));
}
/// Get the ISPC compiler version.
pub fn ispc_version(&self) -> &Version {
&self.ispc_version
}
/// Link the ISPC code into a static library on Unix using `ar`
#[cfg(unix)]
fn assemble(&self, lib: &str) -> ExitStatus {
Command::new("ar")
.arg("crus")
.arg(format!("lib{}.a", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Link the ISPC code into a static library on Windows using `lib.exe`
#[cfg(windows)]
fn assemble(&self, lib: &str) -> ExitStatus {
let target = self.get_target();
let mut lib_cmd = gcc::windows_registry::find_tool(&target[..], "lib.exe")
.expect("Failed to find lib.exe for MSVC toolchain, aborting")
.to_command();
lib_cmd
.arg(format!("/OUT:{}.lib", lib))
.args(&self.objects[..])
.current_dir(&self.get_out_dir())
.status()
.unwrap()
}
/// Generate a single header that includes all of our ISPC headers which we can
/// pass to bindgen
fn generate_bindgen_header(&mut self, lib: &str) {
self.bindgen_header = self
.get_build_dir()
.join(format!("_{}_ispc_bindgen_header.h", lib));
let mut include_file = File::create(&self.bindgen_header).unwrap();
writeln!(include_file, "#include <stdint.h>").unwrap();
writeln!(include_file, "#include <stdbool.h>").unwrap();
for h in &self.headers[..] {
writeln!(include_file, "#include \"{}\"", h.display()).unwrap();
}
}
/// Build up list of basic args for each target, debug, opt level, etc.
fn default_args(&self) -> Vec<String> {
let mut ispc_args = Vec::new();
let opt_level = self.get_opt_level();
if self.get_debug() && opt_level == 0 {
ispc_args.push(String::from("-g"));
}
if let Some(ref c) = self.cpu_target {
ispc_args.push(c.to_string());
// The ispc compiler crashes if we give -O0 and --cpu=generic,
// see https://github.com/ispc/ispc/issues/1223
if *c!= CPU::Generic || (*c == CPU::Generic && opt_level!= 0) {
ispc_args.push(String::from("-O") + &opt_level.to_string());
} else {
self.print(
&"cargo:warning=ispc-rs: Omitting -O0 on CPU::Generic target, ispc bug 1223",
);
}
} else {
ispc_args.push(String::from("-O") + &opt_level.to_string());
}
// If we're on Unix we need position independent code
if cfg!(unix) {
ispc_args.push(String::from("--pic"));
}
let target = self.get_target();
if target.starts_with("i686") {
ispc_args.push(String::from("--arch=x86"));
} else if target.starts_with("x86_64") {
ispc_args.push(String::from("--arch=x86-64"));
} else if target.starts_with("aarch64") {
ispc_args.push(String::from("--arch=aarch64"));
}
for d in &self.defines {
match d.1 {
Some(ref v) => ispc_args.push(format!("-D{}={}", d.0, v)),
None => ispc_args.push(format!("-D{}", d.0)),
}
}
ispc_args.push(self.math_lib.to_string());
if let Some(ref s) = self.addressing {
ispc_args.push(s.to_string());
}
if let Some(ref f) = self.force_alignment {
ispc_args.push(String::from("--force-alignment=") + &f.to_string());
}
for o in &self.optimization_opts {
ispc_args.push(o.to_string());
}
for p in &self.include_paths {
ispc_args.push(format!("-I{}", p.display()));
}
if self.no_omit_frame_ptr {
ispc_args.push(String::from("--no-omit-frame-pointer"));
}
if self.no_stdlib {
ispc_args.push(String::from("--nostdlib"));
}
if self.no_cpp {
ispc_args.push(String::from("--nocpp"));
}
if self.quiet {
ispc_args.push(String::from("--quiet"));
}
if self.werror {
ispc_args.push(String::from("--werror"));
}
if self.woff {
ispc_args.push(String::from("--woff"));
}
if self.wno_perf {
ispc_args.push(String::from("--wno-perf"));
}
if self.instrument {
ispc_args.push(String::from("--instrument"));
}
if let Some(ref t) = self.target_isa {
let mut isa_str = String::from("--target=");
isa_str.push_str(&t[0].to_string());
for isa in t.iter().skip(1) {
isa_str.push_str(&format!(",{}", isa.to_string()));
}
ispc_args.push(isa_str);
} else if target.starts_with("aarch64") {
// For arm we may need to override the default target ISA,
// e.g. on macOS with ISPC running in Rosetta, ISPC will default to
// SSE4, but we need NEON
ispc_args.push(String::from("--target=neon-i32x4"));
}
if let Some(ref a) = self.architecture {
ispc_args.push(a.to_string());
}
if let Some(ref o) = self.target_os {
ispc_args.push(o.to_string());
}
ispc_args
}
/// Returns the user-set output directory if they've set one, otherwise
/// returns env("OUT_DIR")
fn get_out_dir(&self) -> PathBuf {
let p = self
.out_dir
.clone()
.unwrap_or_else(|| env::var_os("OUT_DIR").map(PathBuf::from).unwrap());
if p.is_relative() {
env::current_dir().unwrap().join(p)
} else {
p
}
}
/// Returns the default cargo output dir for build scripts (env("OUT_DIR"))
fn get_build_dir(&self) -> PathBuf {
env::var_os("OUT_DIR").map(PathBuf::from).unwrap()
}
/// Returns the user-set debug flag if they've set one, otherwise returns
/// env("DEBUG")
fn get_debug(&self) -> bool | {
self.debug
.unwrap_or_else(|| env::var("DEBUG").map(|x| x == "true").unwrap())
} | identifier_body |
|
str_match.rs | /// Decompose the string pattern
pub fn decompose(rule: &str) -> Vec<String> {
let mut res = vec![String::new()];
let mut escape = false;
for c in rule.chars() {
let l = res.len();
if escape {
res[l - 1].push(c);
escape = false;
} else if c == '\\' {
escape = true;
} else if c == '*' {
res.push(String::new());
} else {
res[l - 1].push(c); | }
res
}
/// Check if a pattern matches a given string
pub fn str_match(rule: &str, other: &str) -> bool {
let mut pos = 0;
for i in decompose(rule) {
match (&other[pos..]).find(&i) {
Some(n) => pos = n,
None => return false,
}
}
true
} | } | random_line_split |
str_match.rs | /// Decompose the string pattern
pub fn decompose(rule: &str) -> Vec<String> |
/// Check if a pattern matches a given string
pub fn str_match(rule: &str, other: &str) -> bool {
let mut pos = 0;
for i in decompose(rule) {
match (&other[pos..]).find(&i) {
Some(n) => pos = n,
None => return false,
}
}
true
}
| {
let mut res = vec![String::new()];
let mut escape = false;
for c in rule.chars() {
let l = res.len();
if escape {
res[l - 1].push(c);
escape = false;
} else if c == '\\' {
escape = true;
} else if c == '*' {
res.push(String::new());
} else {
res[l - 1].push(c);
}
}
res
} | identifier_body |
str_match.rs | /// Decompose the string pattern
pub fn decompose(rule: &str) -> Vec<String> {
let mut res = vec![String::new()];
let mut escape = false;
for c in rule.chars() {
let l = res.len();
if escape {
res[l - 1].push(c);
escape = false;
} else if c == '\\' {
escape = true;
} else if c == '*' {
res.push(String::new());
} else {
res[l - 1].push(c);
}
}
res
}
/// Check if a pattern matches a given string
pub fn | (rule: &str, other: &str) -> bool {
let mut pos = 0;
for i in decompose(rule) {
match (&other[pos..]).find(&i) {
Some(n) => pos = n,
None => return false,
}
}
true
}
| str_match | identifier_name |
read.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.
//! A wrapper around any Read to treat it as an RNG.
use std::io::{self, Read};
use std::mem;
use Rng;
/// An RNG that reads random bytes straight from a `Read`. This will
/// work best with an infinite reader, but this is not required.
///
/// # Panics
///
/// It will panic if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use rand::{read, Rng};
///
/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
/// let mut rng = read::ReadRng::new(&data[..]);
/// println!("{:x}", rng.gen::<u32>());
/// ```
pub struct ReadRng<R> {
reader: R
}
impl<R: Read> ReadRng<R> {
/// Create a new `ReadRng` from a `Read`.
pub fn new(r: R) -> ReadRng<R> {
ReadRng {
reader: r
}
}
}
impl<R: Read> Rng for ReadRng<R> {
fn next_u32(&mut self) -> u32 |
fn next_u64(&mut self) -> u64 {
// see above for explanation.
let mut buf = [0; 8];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr() as *const u64) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
fill(&mut self.reader, v).unwrap();
}
}
fn fill(r: &mut Read, mut buf: &mut [u8]) -> io::Result<()> {
while buf.len() > 0 {
match try!(r.read(buf)) {
0 => return Err(io::Error::new(io::ErrorKind::Other,
"end of file reached")),
n => buf = &mut mem::replace(&mut buf, &mut [])[n..],
}
}
Ok(())
}
#[cfg(test)]
mod test {
use super::ReadRng;
use Rng;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1,
0 , 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, 0, 0, 0, 3];
let mut rng = ReadRng::new(&v[..]);
assert_eq!(rng.next_u64(), 1_u64.to_be());
assert_eq!(rng.next_u64(), 2_u64.to_be());
assert_eq!(rng.next_u64(), 3_u64.to_be());
}
#[test]
fn test_reader_rng_u32() {
let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3];
let mut rng = ReadRng::new(&v[..]);
assert_eq!(rng.next_u32(), 1_u32.to_be());
assert_eq!(rng.next_u32(), 2_u32.to_be());
assert_eq!(rng.next_u32(), 3_u32.to_be());
}
#[test]
fn test_reader_rng_fill_bytes() {
let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut w = [0u8; 8];
let mut rng = ReadRng::new(&v[..]);
rng.fill_bytes(&mut w);
assert!(v == w);
}
#[test]
#[should_panic]
#[cfg_attr(target_env = "msvc", ignore)]
fn test_reader_rng_insufficient_bytes() {
let mut rng = ReadRng::new(&[][..]);
let mut v = [0u8; 3];
rng.fill_bytes(&mut v);
}
}
| {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
let mut buf = [0; 4];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr() as *const u32) }
} | identifier_body |
read.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.
//! A wrapper around any Read to treat it as an RNG.
use std::io::{self, Read};
use std::mem;
use Rng;
/// An RNG that reads random bytes straight from a `Read`. This will
/// work best with an infinite reader, but this is not required.
///
/// # Panics
///
/// It will panic if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use rand::{read, Rng};
///
/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
/// let mut rng = read::ReadRng::new(&data[..]);
/// println!("{:x}", rng.gen::<u32>());
/// ```
pub struct ReadRng<R> {
reader: R
}
impl<R: Read> ReadRng<R> {
/// Create a new `ReadRng` from a `Read`.
pub fn new(r: R) -> ReadRng<R> {
ReadRng {
reader: r
}
}
}
impl<R: Read> Rng for ReadRng<R> {
fn next_u32(&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
let mut buf = [0; 4];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr() as *const u32) }
}
fn next_u64(&mut self) -> u64 {
// see above for explanation.
let mut buf = [0; 8];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr() as *const u64) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
fill(&mut self.reader, v).unwrap();
}
}
fn fill(r: &mut Read, mut buf: &mut [u8]) -> io::Result<()> {
while buf.len() > 0 {
match try!(r.read(buf)) {
0 => return Err(io::Error::new(io::ErrorKind::Other,
"end of file reached")),
n => buf = &mut mem::replace(&mut buf, &mut [])[n..],
}
}
Ok(())
}
#[cfg(test)]
mod test {
use super::ReadRng;
use Rng;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1,
0 , 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, 0, 0, 0, 3];
let mut rng = ReadRng::new(&v[..]);
assert_eq!(rng.next_u64(), 1_u64.to_be());
assert_eq!(rng.next_u64(), 2_u64.to_be());
assert_eq!(rng.next_u64(), 3_u64.to_be());
}
#[test]
fn test_reader_rng_u32() {
let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3];
let mut rng = ReadRng::new(&v[..]);
assert_eq!(rng.next_u32(), 1_u32.to_be());
assert_eq!(rng.next_u32(), 2_u32.to_be());
assert_eq!(rng.next_u32(), 3_u32.to_be());
}
#[test]
fn | () {
let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut w = [0u8; 8];
let mut rng = ReadRng::new(&v[..]);
rng.fill_bytes(&mut w);
assert!(v == w);
}
#[test]
#[should_panic]
#[cfg_attr(target_env = "msvc", ignore)]
fn test_reader_rng_insufficient_bytes() {
let mut rng = ReadRng::new(&[][..]);
let mut v = [0u8; 3];
rng.fill_bytes(&mut v);
}
}
| test_reader_rng_fill_bytes | identifier_name |
read.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.
//! A wrapper around any Read to treat it as an RNG.
use std::io::{self, Read};
use std::mem;
use Rng;
/// An RNG that reads random bytes straight from a `Read`. This will
/// work best with an infinite reader, but this is not required.
///
/// # Panics
///
/// It will panic if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use rand::{read, Rng};
///
/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
/// let mut rng = read::ReadRng::new(&data[..]);
/// println!("{:x}", rng.gen::<u32>());
/// ```
pub struct ReadRng<R> {
reader: R
}
impl<R: Read> ReadRng<R> {
/// Create a new `ReadRng` from a `Read`.
pub fn new(r: R) -> ReadRng<R> {
ReadRng {
reader: r
}
}
}
impl<R: Read> Rng for ReadRng<R> {
fn next_u32(&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
let mut buf = [0; 4];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr() as *const u32) }
}
fn next_u64(&mut self) -> u64 {
// see above for explanation.
let mut buf = [0; 8];
fill(&mut self.reader, &mut buf).unwrap();
unsafe { *(buf.as_ptr() as *const u64) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
fill(&mut self.reader, v).unwrap();
}
}
fn fill(r: &mut Read, mut buf: &mut [u8]) -> io::Result<()> {
while buf.len() > 0 {
match try!(r.read(buf)) { | Ok(())
}
#[cfg(test)]
mod test {
use super::ReadRng;
use Rng;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1,
0 , 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, 0, 0, 0, 3];
let mut rng = ReadRng::new(&v[..]);
assert_eq!(rng.next_u64(), 1_u64.to_be());
assert_eq!(rng.next_u64(), 2_u64.to_be());
assert_eq!(rng.next_u64(), 3_u64.to_be());
}
#[test]
fn test_reader_rng_u32() {
let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3];
let mut rng = ReadRng::new(&v[..]);
assert_eq!(rng.next_u32(), 1_u32.to_be());
assert_eq!(rng.next_u32(), 2_u32.to_be());
assert_eq!(rng.next_u32(), 3_u32.to_be());
}
#[test]
fn test_reader_rng_fill_bytes() {
let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut w = [0u8; 8];
let mut rng = ReadRng::new(&v[..]);
rng.fill_bytes(&mut w);
assert!(v == w);
}
#[test]
#[should_panic]
#[cfg_attr(target_env = "msvc", ignore)]
fn test_reader_rng_insufficient_bytes() {
let mut rng = ReadRng::new(&[][..]);
let mut v = [0u8; 3];
rng.fill_bytes(&mut v);
}
} | 0 => return Err(io::Error::new(io::ErrorKind::Other,
"end of file reached")),
n => buf = &mut mem::replace(&mut buf, &mut [])[n..],
}
} | random_line_split |
client.rs | /// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base url for requests via this Client library.
static DEFAULT_BASE_URL: &'static str = "https://api.github.com/";
/// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base upload url for requests via this Client library.
static DEFAULT_UPLOAD_BASE_URL: &'static str = "https://uploads.github.com/";
/// The `Client` struct represent the user agent and base URLs.
/// Functions in this library will never mutate a `Client` object | /// `user_agent` represents the value given
/// under the User-Agent key as part of
/// the header of each request.
pub user_agent: String,
/// The base url for non-upload requests.
pub base_url: String,
/// The base url for upload requests.
pub upload_url: String,
}
impl Client {
/// Construct a `Client` for a custom domain, other than GitHub.
pub fn custom(user: &str, base_url: &str, upload_url: &str) -> Client {
Client {
user_agent: user.to_string(),
base_url: base_url.to_string(),
upload_url: upload_url.to_string(),
}
}
/// Construct a `Client` using the default URLs as defined by GitHub.
pub fn new(user: &str) -> Client {
Client::custom(user, DEFAULT_BASE_URL, DEFAULT_UPLOAD_BASE_URL)
}
} | /// and for th sake of parallel processing, you should try to keep it immutable.
pub struct Client { | random_line_split |
client.rs | /// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base url for requests via this Client library.
static DEFAULT_BASE_URL: &'static str = "https://api.github.com/";
/// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base upload url for requests via this Client library.
static DEFAULT_UPLOAD_BASE_URL: &'static str = "https://uploads.github.com/";
/// The `Client` struct represent the user agent and base URLs.
/// Functions in this library will never mutate a `Client` object
/// and for th sake of parallel processing, you should try to keep it immutable.
pub struct Client {
/// `user_agent` represents the value given
/// under the User-Agent key as part of
/// the header of each request.
pub user_agent: String,
/// The base url for non-upload requests.
pub base_url: String,
/// The base url for upload requests.
pub upload_url: String,
}
impl Client {
/// Construct a `Client` for a custom domain, other than GitHub.
pub fn custom(user: &str, base_url: &str, upload_url: &str) -> Client {
Client {
user_agent: user.to_string(),
base_url: base_url.to_string(),
upload_url: upload_url.to_string(),
}
}
/// Construct a `Client` using the default URLs as defined by GitHub.
pub fn | (user: &str) -> Client {
Client::custom(user, DEFAULT_BASE_URL, DEFAULT_UPLOAD_BASE_URL)
}
}
| new | identifier_name |
client.rs | /// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base url for requests via this Client library.
static DEFAULT_BASE_URL: &'static str = "https://api.github.com/";
/// By default and in most scenarios, `DEFAULT_BASE_URL`
/// will be the base upload url for requests via this Client library.
static DEFAULT_UPLOAD_BASE_URL: &'static str = "https://uploads.github.com/";
/// The `Client` struct represent the user agent and base URLs.
/// Functions in this library will never mutate a `Client` object
/// and for th sake of parallel processing, you should try to keep it immutable.
pub struct Client {
/// `user_agent` represents the value given
/// under the User-Agent key as part of
/// the header of each request.
pub user_agent: String,
/// The base url for non-upload requests.
pub base_url: String,
/// The base url for upload requests.
pub upload_url: String,
}
impl Client {
/// Construct a `Client` for a custom domain, other than GitHub.
pub fn custom(user: &str, base_url: &str, upload_url: &str) -> Client |
/// Construct a `Client` using the default URLs as defined by GitHub.
pub fn new(user: &str) -> Client {
Client::custom(user, DEFAULT_BASE_URL, DEFAULT_UPLOAD_BASE_URL)
}
}
| {
Client {
user_agent: user.to_string(),
base_url: base_url.to_string(),
upload_url: upload_url.to_string(),
}
} | identifier_body |
snapshot.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::db_vector::PanicDBVector;
use crate::engine::PanicEngine;
use engine_traits::{
IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot,
};
use std::ops::Deref;
#[derive(Clone, Debug)]
pub struct PanicSnapshot;
impl Snapshot for PanicSnapshot {
fn cf_names(&self) -> Vec<&str> {
panic!()
}
}
impl Peekable for PanicSnapshot {
type DBVector = PanicDBVector;
fn get_value_opt(&self, opts: &ReadOptions, key: &[u8]) -> Result<Option<Self::DBVector>> {
panic!()
}
fn get_value_cf_opt(
&self,
opts: &ReadOptions,
cf: &str,
key: &[u8],
) -> Result<Option<Self::DBVector>> {
panic!()
}
}
impl Iterable for PanicSnapshot {
type Iterator = PanicSnapshotIterator;
fn iterator_opt(&self, opts: IterOptions) -> Result<Self::Iterator> {
panic!()
}
fn iterator_cf_opt(&self, cf: &str, opts: IterOptions) -> Result<Self::Iterator> {
panic!()
}
}
pub struct PanicSnapshotIterator;
impl Iterator for PanicSnapshotIterator {
fn seek(&mut self, key: SeekKey) -> Result<bool> {
panic!()
}
fn seek_for_prev(&mut self, key: SeekKey) -> Result<bool> {
panic!()
}
fn prev(&mut self) -> Result<bool> {
panic!()
}
fn next(&mut self) -> Result<bool> {
panic!()
}
fn key(&self) -> &[u8] {
panic!()
}
fn value(&self) -> &[u8] |
fn valid(&self) -> Result<bool> {
panic!()
}
}
| {
panic!()
} | identifier_body |
snapshot.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::db_vector::PanicDBVector;
use crate::engine::PanicEngine;
use engine_traits::{
IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot,
};
use std::ops::Deref;
#[derive(Clone, Debug)]
pub struct PanicSnapshot;
impl Snapshot for PanicSnapshot {
fn cf_names(&self) -> Vec<&str> {
panic!()
}
}
impl Peekable for PanicSnapshot {
type DBVector = PanicDBVector;
fn get_value_opt(&self, opts: &ReadOptions, key: &[u8]) -> Result<Option<Self::DBVector>> {
panic!()
}
fn get_value_cf_opt(
&self,
opts: &ReadOptions,
cf: &str,
key: &[u8],
) -> Result<Option<Self::DBVector>> {
panic!()
}
}
impl Iterable for PanicSnapshot {
type Iterator = PanicSnapshotIterator;
fn iterator_opt(&self, opts: IterOptions) -> Result<Self::Iterator> {
panic!()
}
fn iterator_cf_opt(&self, cf: &str, opts: IterOptions) -> Result<Self::Iterator> {
panic!()
}
}
pub struct PanicSnapshotIterator;
impl Iterator for PanicSnapshotIterator {
fn seek(&mut self, key: SeekKey) -> Result<bool> {
panic!()
}
fn seek_for_prev(&mut self, key: SeekKey) -> Result<bool> {
panic!()
}
fn prev(&mut self) -> Result<bool> {
panic!()
}
fn next(&mut self) -> Result<bool> {
panic!()
}
fn | (&self) -> &[u8] {
panic!()
}
fn value(&self) -> &[u8] {
panic!()
}
fn valid(&self) -> Result<bool> {
panic!()
}
}
| key | identifier_name |
snapshot.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::db_vector::PanicDBVector;
use crate::engine::PanicEngine;
use engine_traits::{
IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot,
};
use std::ops::Deref;
#[derive(Clone, Debug)]
pub struct PanicSnapshot;
impl Snapshot for PanicSnapshot {
fn cf_names(&self) -> Vec<&str> {
panic!()
}
}
impl Peekable for PanicSnapshot {
type DBVector = PanicDBVector;
fn get_value_opt(&self, opts: &ReadOptions, key: &[u8]) -> Result<Option<Self::DBVector>> {
panic!()
}
fn get_value_cf_opt(
&self,
opts: &ReadOptions,
cf: &str,
key: &[u8],
) -> Result<Option<Self::DBVector>> {
panic!()
}
}
impl Iterable for PanicSnapshot {
type Iterator = PanicSnapshotIterator;
fn iterator_opt(&self, opts: IterOptions) -> Result<Self::Iterator> {
panic!()
}
fn iterator_cf_opt(&self, cf: &str, opts: IterOptions) -> Result<Self::Iterator> {
panic!()
}
}
pub struct PanicSnapshotIterator;
impl Iterator for PanicSnapshotIterator {
fn seek(&mut self, key: SeekKey) -> Result<bool> {
panic!()
}
fn seek_for_prev(&mut self, key: SeekKey) -> Result<bool> {
panic!()
}
fn prev(&mut self) -> Result<bool> {
panic!()
}
fn next(&mut self) -> Result<bool> {
panic!()
}
fn key(&self) -> &[u8] {
panic!()
}
fn value(&self) -> &[u8] {
panic!()
}
fn valid(&self) -> Result<bool> { | panic!()
}
} | random_line_split |
|
tuples.rs | use AsMutLua;
use AsLua;
use Push;
use PushGuard;
use LuaRead;
macro_rules! tuple_impl {
($ty:ident) => (
impl<LU, $ty> Push<LU> for ($ty,) where LU: AsMutLua, $ty: Push<LU> {
fn push_to_lua(self, lua: LU) -> PushGuard<LU> {
self.0.push_to_lua(lua)
}
}
impl<LU, $ty> LuaRead<LU> for ($ty,) where LU: AsMutLua, $ty: LuaRead<LU> {
fn lua_read_at_position(lua: LU, index: i32) -> Result<($ty,), LU> {
LuaRead::lua_read_at_position(lua, index).map(|v| (v,))
}
}
);
($first:ident, $($other:ident),+) => (
#[allow(non_snake_case)]
impl<LU, $first: for<'a> Push<&'a mut LU>, $($other: for<'a> Push<&'a mut LU>),+>
Push<LU> for ($first, $($other),+) where LU: AsMutLua
{
fn push_to_lua(self, mut lua: LU) -> PushGuard<LU> {
match self {
($first, $($other),+) => {
let mut total = $first.push_to_lua(&mut lua).forget();
$(
total += $other.push_to_lua(&mut lua).forget();
)+
PushGuard { lua: lua, size: total }
}
}
}
}
// TODO: what if T or U are also tuples? indices won't match
#[allow(unused_assignments)]
#[allow(non_snake_case)]
impl<LU, $first: for<'a> LuaRead<&'a mut LU>, $($other: for<'a> LuaRead<&'a mut LU>),+> | fn lua_read_at_position(mut lua: LU, index: i32) -> Result<($first, $($other),+), LU> {
let mut i = index;
let $first: $first = match LuaRead::lua_read_at_position(&mut lua, i) {
Ok(v) => v,
Err(_) => return Err(lua)
};
i += 1;
$(
let $other: $other = match LuaRead::lua_read_at_position(&mut lua, i) {
Ok(v) => v,
Err(_) => return Err(lua)
};
i += 1;
)+
Ok(($first, $($other),+))
}
}
tuple_impl!($($other),+);
);
}
tuple_impl!(A, B, C, D, E, F, G, H, I, J, K, L, M); | LuaRead<LU> for ($first, $($other),+) where LU: AsLua
{ | random_line_split |
ice-3969.rs | // https://github.com/rust-lang/rust-clippy/issues/3969
// used to crash: error: internal compiler error:
// src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as
// std::iter::Iterator>::Item test from rustc./ui/trivial-bounds/trivial-bounds-inconsistent.rs
// Check that tautalogically false bounds are accepted, and are used
// in type inference.
#![feature(trivial_bounds)]
#![allow(unused)]
trait A {}
impl A for i32 {}
struct Dst<X:?Sized> {
x: X, | where
str: Sized;
fn unsized_local()
where
for<'a> Dst<dyn A + 'a>: Sized,
{
let x: Dst<dyn A> = *(Box::new(Dst { x: 1 }) as Box<Dst<dyn A>>);
}
fn return_str() -> str
where
str: Sized,
{
*"Sized".to_string().into_boxed_str()
}
fn use_op(s: String) -> String
where
String: ::std::ops::Neg<Output = String>,
{
-s
}
fn use_for()
where
i32: Iterator,
{
for _ in 2i32 {}
}
fn main() {} | }
struct TwoStrs(str, str) | random_line_split |
ice-3969.rs | // https://github.com/rust-lang/rust-clippy/issues/3969
// used to crash: error: internal compiler error:
// src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as
// std::iter::Iterator>::Item test from rustc./ui/trivial-bounds/trivial-bounds-inconsistent.rs
// Check that tautalogically false bounds are accepted, and are used
// in type inference.
#![feature(trivial_bounds)]
#![allow(unused)]
trait A {}
impl A for i32 {}
struct Dst<X:?Sized> {
x: X,
}
struct TwoStrs(str, str)
where
str: Sized;
fn unsized_local()
where
for<'a> Dst<dyn A + 'a>: Sized,
{
let x: Dst<dyn A> = *(Box::new(Dst { x: 1 }) as Box<Dst<dyn A>>);
}
fn return_str() -> str
where
str: Sized,
{
*"Sized".to_string().into_boxed_str()
}
fn use_op(s: String) -> String
where
String: ::std::ops::Neg<Output = String>,
{
-s
}
fn use_for()
where
i32: Iterator,
{
for _ in 2i32 {}
}
fn | () {}
| main | identifier_name |
ice-3969.rs | // https://github.com/rust-lang/rust-clippy/issues/3969
// used to crash: error: internal compiler error:
// src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as
// std::iter::Iterator>::Item test from rustc./ui/trivial-bounds/trivial-bounds-inconsistent.rs
// Check that tautalogically false bounds are accepted, and are used
// in type inference.
#![feature(trivial_bounds)]
#![allow(unused)]
trait A {}
impl A for i32 {}
struct Dst<X:?Sized> {
x: X,
}
struct TwoStrs(str, str)
where
str: Sized;
fn unsized_local()
where
for<'a> Dst<dyn A + 'a>: Sized,
|
fn return_str() -> str
where
str: Sized,
{
*"Sized".to_string().into_boxed_str()
}
fn use_op(s: String) -> String
where
String: ::std::ops::Neg<Output = String>,
{
-s
}
fn use_for()
where
i32: Iterator,
{
for _ in 2i32 {}
}
fn main() {}
| {
let x: Dst<dyn A> = *(Box::new(Dst { x: 1 }) as Box<Dst<dyn A>>);
} | identifier_body |
tok.rs | use std::str::FromStr;
#[derive(Debug)]
pub enum Tok {
Num(i32),
LParen,
RParen,
Minus,
Plus,
Times,
Div,
Comma,
}
// simplest and stupidest possible tokenizer
pub fn tokenize(s: &str) -> Vec<(usize, Tok, usize)> {
let mut tokens = vec![];
let mut chars = s.chars();
let mut lookahead = chars.next();
while let Some(c) = lookahead {
// skip whitespace characters
if!c.is_whitespace() {
match c {
'(' => tokens.push(Tok::LParen),
')' => tokens.push(Tok::RParen),
'-' => tokens.push(Tok::Minus),
'+' => tokens.push(Tok::Plus),
'*' => tokens.push(Tok::Times),
',' => tokens.push(Tok::Comma),
'/' => tokens.push(Tok::Div),
_ if c.is_digit(10) => {
let (tmp, next) = take_while(c, &mut chars, |c| c.is_digit(10));
lookahead = next;
tokens.push(Tok::Num(i32::from_str(&tmp).unwrap()));
continue;
}
_ => {
panic!("invalid character: {:?}", c);
}
}
}
// advance to next character by default
lookahead = chars.next();
}
tokens.into_iter()
.enumerate()
.map(|(i, tok)| (i*2, tok, i*2+1))
.collect()
}
fn | <C,F>(c0: char, chars: &mut C, f: F) -> (String, Option<char>)
where C: Iterator<Item=char>, F: Fn(char) -> bool
{
let mut buf = String::new();
buf.push(c0);
while let Some(c) = chars.next() {
if!f(c) {
return (buf, Some(c));
}
buf.push(c);
}
return (buf, None);
}
| take_while | identifier_name |
tok.rs | use std::str::FromStr;
#[derive(Debug)]
pub enum Tok {
Num(i32),
LParen,
RParen,
Minus,
Plus,
Times,
Div,
Comma,
}
// simplest and stupidest possible tokenizer
pub fn tokenize(s: &str) -> Vec<(usize, Tok, usize)> {
let mut tokens = vec![];
let mut chars = s.chars();
let mut lookahead = chars.next();
while let Some(c) = lookahead {
// skip whitespace characters
if!c.is_whitespace() {
match c {
'(' => tokens.push(Tok::LParen),
')' => tokens.push(Tok::RParen),
'-' => tokens.push(Tok::Minus),
'+' => tokens.push(Tok::Plus),
'*' => tokens.push(Tok::Times),
',' => tokens.push(Tok::Comma),
'/' => tokens.push(Tok::Div),
_ if c.is_digit(10) => {
let (tmp, next) = take_while(c, &mut chars, |c| c.is_digit(10));
lookahead = next;
tokens.push(Tok::Num(i32::from_str(&tmp).unwrap()));
continue;
}
_ => {
panic!("invalid character: {:?}", c);
}
}
}
// advance to next character by default
lookahead = chars.next();
}
tokens.into_iter()
.enumerate()
.map(|(i, tok)| (i*2, tok, i*2+1))
.collect()
}
fn take_while<C,F>(c0: char, chars: &mut C, f: F) -> (String, Option<char>)
where C: Iterator<Item=char>, F: Fn(char) -> bool
{
let mut buf = String::new();
buf.push(c0);
while let Some(c) = chars.next() { |
buf.push(c);
}
return (buf, None);
} | if !f(c) {
return (buf, Some(c));
} | random_line_split |
mpsc_queue.rs | // Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are
// those of the authors and should not be interpreted as representing official
// policies, either expressed or implied, of Dmitry Vyukov.
//
//! A mostly lock-free multi-producer, single consumer queue.
//!
//! This module contains an implementation of a concurrent MPSC queue. This
//! queue can be used to share data between threads, and is also used as the
//! building block of channels in rust.
//!
//! Note that the current implementation of this queue has a caveat of the `pop`
//! method, and see the method for more information about it. Due to this
//! caveat, this queue may not be appropriate for all use-cases.
// http://www.1024cores.net/home/lock-free-algorithms
// /queues/non-intrusive-mpsc-node-based-queue
pub use self::PopResult::*;
use std::boxed::Box;
use core::ptr;
use core::cell::UnsafeCell;
use std::sync::atomic::{AtomicPtr, Ordering};
/// A result of the `pop` function.
pub enum PopResult<T> {
/// Some data has been popped
Data(T),
/// The queue is empty
Empty,
/// The queue is in an inconsistent state. Popping data should succeed, but
/// some pushers have yet to make enough progress in order allow a pop to
/// succeed. It is recommended that a pop() occur "in the near future" in
/// order to see if the sender has made progress or not
Inconsistent,
}
struct Node<T> {
next: AtomicPtr<Node<T>>,
value: Option<T>,
}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: AtomicPtr<Node<T>>,
tail: UnsafeCell<*mut Node<T>>,
}
unsafe impl<T: Send> Send for Queue<T> {}
unsafe impl<T: Send> Sync for Queue<T> {}
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> {
Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
}
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
}
/// Pushes a new value onto this queue.
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
let prev = self.head.swap(n, Ordering::AcqRel);
(*prev).next.store(n, Ordering::Release);
}
}
/// Pops some data from this queue.
///
/// Note that the current implementation means that this function cannot
/// return `Option<T>`. It is possible for this queue to be in an
/// inconsistent state where many pushes have succeeded and completely
/// finished, but pops cannot return `Some(t)`. This inconsistent state
/// happens when a pusher is pre-empted at an inopportune moment.
///
/// This inconsistent state means that this queue does indeed have data, but
/// it does not currently have access to it at this time.
pub fn pop(&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if!next.is_null() {
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
let ret = (*next).value.take().unwrap();
let _: Box<Node<T>> = Box::from_raw(tail);
return Data(ret);
}
if self.head.load(Ordering::Acquire) == tail {
Empty
} else {
Inconsistent
}
}
}
}
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while!cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = Box::from_raw(cur);
cur = next;
}
}
}
}
#[cfg(all(test, not(target_os = "emscripten")))]
mod tests {
use sync::mpsc::channel;
use super::{Queue, Data, Empty, Inconsistent};
use sync::Arc;
use thread;
#[test]
fn | () {
let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
Empty => {}
Inconsistent | Data(..) => panic!(),
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move || {
for i in 0..nmsgs {
q.push(i);
}
tx.send(()).unwrap();
});
}
let mut i = 0;
while i < nthreads * nmsgs {
match q.pop() {
Empty | Inconsistent => {}
Data(_) => i += 1,
}
}
drop(tx);
for _ in 0..nthreads {
rx.recv().unwrap();
}
}
}
| test_full | identifier_name |
mpsc_queue.rs | // Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are
// those of the authors and should not be interpreted as representing official
// policies, either expressed or implied, of Dmitry Vyukov.
//
//! A mostly lock-free multi-producer, single consumer queue.
//!
//! This module contains an implementation of a concurrent MPSC queue. This
//! queue can be used to share data between threads, and is also used as the
//! building block of channels in rust.
//!
//! Note that the current implementation of this queue has a caveat of the `pop`
//! method, and see the method for more information about it. Due to this
//! caveat, this queue may not be appropriate for all use-cases.
// http://www.1024cores.net/home/lock-free-algorithms
// /queues/non-intrusive-mpsc-node-based-queue
pub use self::PopResult::*;
use std::boxed::Box;
use core::ptr;
use core::cell::UnsafeCell;
use std::sync::atomic::{AtomicPtr, Ordering};
/// A result of the `pop` function.
pub enum PopResult<T> {
/// Some data has been popped | Empty,
/// The queue is in an inconsistent state. Popping data should succeed, but
/// some pushers have yet to make enough progress in order allow a pop to
/// succeed. It is recommended that a pop() occur "in the near future" in
/// order to see if the sender has made progress or not
Inconsistent,
}
struct Node<T> {
next: AtomicPtr<Node<T>>,
value: Option<T>,
}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: AtomicPtr<Node<T>>,
tail: UnsafeCell<*mut Node<T>>,
}
unsafe impl<T: Send> Send for Queue<T> {}
unsafe impl<T: Send> Sync for Queue<T> {}
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> {
Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
}
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
}
/// Pushes a new value onto this queue.
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
let prev = self.head.swap(n, Ordering::AcqRel);
(*prev).next.store(n, Ordering::Release);
}
}
/// Pops some data from this queue.
///
/// Note that the current implementation means that this function cannot
/// return `Option<T>`. It is possible for this queue to be in an
/// inconsistent state where many pushes have succeeded and completely
/// finished, but pops cannot return `Some(t)`. This inconsistent state
/// happens when a pusher is pre-empted at an inopportune moment.
///
/// This inconsistent state means that this queue does indeed have data, but
/// it does not currently have access to it at this time.
pub fn pop(&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if!next.is_null() {
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
let ret = (*next).value.take().unwrap();
let _: Box<Node<T>> = Box::from_raw(tail);
return Data(ret);
}
if self.head.load(Ordering::Acquire) == tail {
Empty
} else {
Inconsistent
}
}
}
}
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while!cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = Box::from_raw(cur);
cur = next;
}
}
}
}
#[cfg(all(test, not(target_os = "emscripten")))]
mod tests {
use sync::mpsc::channel;
use super::{Queue, Data, Empty, Inconsistent};
use sync::Arc;
use thread;
#[test]
fn test_full() {
let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
Empty => {}
Inconsistent | Data(..) => panic!(),
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move || {
for i in 0..nmsgs {
q.push(i);
}
tx.send(()).unwrap();
});
}
let mut i = 0;
while i < nthreads * nmsgs {
match q.pop() {
Empty | Inconsistent => {}
Data(_) => i += 1,
}
}
drop(tx);
for _ in 0..nthreads {
rx.recv().unwrap();
}
}
} | Data(T),
/// The queue is empty | random_line_split |
mod.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| reason = "module just underwent fairly large reorganization and the dust \
still needs to settle")]
pub use self::c_str::CString;
pub use self::c_str::c_str_to_bytes;
pub use self::c_str::c_str_to_bytes_with_nul;
pub use self::os_str::OsString;
pub use self::os_str::OsStr;
mod c_str;
mod os_str;
// FIXME (#21670): these should be defined in the os_str module
/// Freely convertible to an `&OsStr` slice.
pub trait AsOsStr {
/// Convert to an `&OsStr` slice.
fn as_os_str(&self) -> &OsStr;
} | //! Utilities related to FFI bindings.
#![unstable(feature = "std_misc", | random_line_split |
octree.rs | use shapes::bbox::BBox;
use na::{Vector3};
use sceneobject::SceneObject;
use std::sync::Arc;
use std::fmt;
use ray::Ray;
use intersection::{RawIntersection, Intersection};
use ordered_float::OrderedFloat;
use shapes::geometry::Geometry;
#[derive(Clone)]
pub struct Octree<T: Geometry>{
root: OctreeNode,
items: Vec<Arc<T>>,
}
#[derive(Clone)]
pub struct OctreeNode {
depth: usize,
bounds: BBox,
// Octree structure:
children: [Option<Box<OctreeNode>>; 8],
items: Vec<usize>
}
fn vec3_invert(rd: Vector3<f64>) -> Vector3<f64> {
return Vector3::new(1.0/rd.x, 1.0/rd.y, 1.0/rd.z);
}
type OctreeIntersections = Option<Vec<usize>>;
impl OctreeNode {
pub fn is_leaf(&self) -> bool {
for i in 0..8 {
match self.children[i as usize] {
Some(_) => { return false },
None => {}
}
}
return true;
}
pub fn is_empty(&self) -> bool {
return self.items.len() > 0;
}
pub fn len(&self) -> usize {
return self.items.len()
}
/// Perform a breadth first search of the tree, and then sort results by distance.
pub fn naive_intersection(&self, r: &Ray, max:f64, min:f64) -> OctreeIntersections {
let invrd = vec3_invert(r.rd);
if!self.bounds.fast_intersects(&r.ro, &invrd) {
return None
}
if self.is_leaf(){
return Some(self.items.clone());
}
let intersections = self.children
.iter()
.filter(|i| i.is_some())
.map(|c| c.as_ref().unwrap().naive_intersection(r,max, min))
.filter(|i| i.is_some())
.map(|i| i.unwrap())
.flatten()
.collect::<Vec<usize>>();
if intersections.is_empty(){
return None;
}
return Some(intersections);
}
}
impl<T: Geometry> Octree<T> {
//
// Create a new node, and subdivide into further nodes up until max_depth
// or until number of children objects is 0.
//
pub fn new(max_depth: usize, b: BBox, items: &Vec<Arc<T>>) -> Octree<T> {
let items: Vec<Arc<T>> = items.into_iter().cloned().collect();
let indices: Vec<usize> = (0..items.len()).collect();
return Octree {
root: Octree::create_node(0, max_depth, b, indices, &items),
items: items,
};
}
fn create_node(depth: usize, max_depth: usize, b: BBox, items: Vec<usize>, geometries: &Vec<Arc<T>>) -> OctreeNode{
// Rust arrays suck - this defaults them to 'None'
let mut children: [Option<Box<OctreeNode>>; 8] = Default::default();
for i in 0..8 {
// Does child node have any objects in?
if depth < max_depth && items.len() > 1 {
// Equal subdivision. Enhancement: Use different split.
let cbox = BBox::for_octant(i, &b);
let inside = items.clone()
.into_iter()
.filter( |x| { cbox.intersects_bbox( &geometries[*x].bounds() ) } )
.collect::<Vec<usize>>();
if inside.len() > 0 {
let node = Octree::create_node(depth + 1, max_depth, cbox, inside, geometries);
children[i as usize] = Some(Box::new(node));
}
}
}
OctreeNode {
depth: depth,
bounds: b,
children: children,
items: items,
}
}
pub fn raw_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<RawIntersection> {
return match self.closest_intersection(r, max, min) {
Some(tupl) => Some(tupl.1),
None => None
}
}
pub fn intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(Arc<T>, RawIntersection)> |
fn closest_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(usize, RawIntersection)> {
return match self.root.naive_intersection(r, max, min) {
Some(opts) => self.items_intersection(r,max, min, opts),
None => None
}
}
// Iterate through potential items. Should only do on leaf if multiple items.
fn items_intersection(&self, r: &Ray, max:f64, min:f64, items: Vec<usize>) -> Option<(usize, RawIntersection)> {
let mut cdist = max;
let mut closest = None;
for i in items {
match self.items[i].intersects(r) {
Some(x) => {
if x.dist < cdist && x.dist >= min {
cdist = x.dist;
closest = Some((i, x));
}
},
None => (),
}
}
return closest;
}
pub fn bounds(&self) -> BBox {
return self.root.bounds;
}
/*
pub fn new_node(&self, txm:f64, x:u8, tym:f64, y:u8, tzm:f64, z:u8) -> u8{
if txm < tym {
if txm < tzm {return x;} // YZ plane
}
else{
if tym < tzm {return y;} // XZ plane
}
return z; // XY plane;
}
pub fn first_node_index(&self, tx0:f64, ty0:f64, tz0:f64, txm:f64, tym:f64, tzm:f64) -> u8 {
let mut answer:u8 = 0;
if tx0 > ty0 {
if tx0 > tz0 { // PLANE YZ
if tym < tx0 { answer|=2; } // set bit at position 1
if tzm < tx0 { answer|=1; } // set bit at position 0
return answer;
}
} else {
if ty0 > tz0 { // PLANE XZ
if txm < ty0 { answer|=4; } // set bit at position 2
if tzm < ty0 { answer|=1; } // set bit at position 0
}
}
// PLANE XY
if txm < tz0 { answer|=4; } // set bit at position 2
if tym < tz0 { answer|=2; } // set bit at position 1
return answer;
}
/// Based on:
/// An Efficient Parametric Algorithm for Octree Traversal (2000)
/// by J. Revelles, C. Ureña, M. Lastra
///
/// Status: Broken
/// Note: Missing bbox intersection?
pub fn revelles_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<Intersection> {
let mut a = 0;
let rd = r.rd.normalize();
let mut rd0 = rd[0];
let mut rd1 = rd[1];
let mut rd2 = rd[2];
let mut ro0 = r.ro[0];
let mut ro1 = r.ro[1];
let mut ro2 = r.ro[2];
// fixes for rays with negative direction
if rd0 < 0. {
ro0 = self.bounds.size()[0] - ro0;
rd0 = - rd0;
a |= 4 ; //bitwise OR (latest bits are XYZ)
}
if rd1 < 0. {
ro1 = self.bounds.size()[1] - ro1;
rd1 = - rd1;
a |= 2 ;
}
if rd2 < 0. {
ro2 = self.bounds.size()[2] - ro2;
rd2 = - rd2;
a |= 1 ;
}
let rn = Ray {
ro: Vector3::new(ro0, ro1, ro2),
rd: Vector3::new(rd0, rd1, rd2),
};
let divx:f64 = 1.0 / rn.rd[0];
let divy:f64 = 1.0 / rn.rd[1];
let divz:f64 = 1.0 / rn.rd[2];
let tx0:f64 = (self.bounds.min[0] - rn.ro[0]) * divx;
let tx1:f64 = (self.bounds.max[0] - rn.ro[0]) * divx;
let ty0:f64 = (self.bounds.min[1] - rn.ro[1]) * divy;
let ty1:f64 = (self.bounds.max[1] - rn.ro[1]) * divy;
let tz0:f64 = (self.bounds.min[2] - rn.ro[2]) * divz;
let tz1:f64 = (self.bounds.max[2] - rn.ro[2]) * divz;
if tz0.max(tx0.max(ty0)) < tz1.min(tx1.min(ty1)) {
return self.revelles_proc_subtree(r, &rn, max, min, tx0, ty0, tz0, tx1, ty1, tz1, a);
}
//println!("- magnitude miss {} {} {}", r, tz0.max(tx0.max(ty0)), tz1.min(tx1.min(ty1)));
return None;
}
pub fn revelles_proc_child(&self, ro: &Ray, r:&Ray, max:f64, min:f64, tx0:f64, ty0:f64, tz0:f64, tx1:f64, ty1:f64, tz1:f64, a:u8, i: u8)-> Option<Intersection> {
return match self.children[i as usize] {
Some (ref x) => {
return x.revelles_proc_subtree(ro, r, max, min, tx0, ty0, tz0, tx1, ty1, tz1, a)
}
None => {
return None
}
}
}
pub fn revelles_proc_subtree(&self, ro:&Ray, r:&Ray, max:f64, min:f64, tx0:f64, ty0:f64, tz0:f64, tx1:f64, ty1:f64, tz1:f64, a:u8) -> Option<Intersection> {
//println!("- node hit");
if tx1 < 0. || ty1 < 0. || tz1 < 0. {
return None;
}
if self.is_leaf(){
return self.items_intersection(ro, max, min);
}
let txm = 0.5 * (tx0 + tx1);
let tym = 0.5 * (ty0 + ty1);
let tzm = 0.5 * (tz0 + tz1);
let mut curr_node = self.first_node_index(tx0,ty0,tz0,txm,tym,tzm);
while curr_node < 8 { // TODO do-while?
let mut intersection: Option<Intersection> = None;
match curr_node {
0 => {
intersection = self.revelles_proc_child(ro, r, max, min, tx0,ty0,tz0,txm,tym,tzm, a, 0);
curr_node = self.new_node(txm,4,tym,2,tzm,1);
},
1 => {
intersection = self.revelles_proc_child(ro, r, max, min, tx0,ty0,tzm,txm,tym,tz1, a, 1^a);
curr_node = self.new_node(txm,5,tym,3,tz1,8);
}
2 => {
intersection =self.revelles_proc_child(ro, r, max, min, tx0,tym,tz0,txm,ty1,tzm, a, 2^a);
curr_node = self.new_node(txm,6,ty1,8,tzm,3);
}
3 => {
intersection =self.revelles_proc_child(ro, r, max, min, tx0,tym,tzm,txm,ty1,tz1, a, 3^a);
curr_node = self.new_node(txm,7,ty1,8,tz1,8);
}
4 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,ty0,tz0,tx1,tym,tzm, a, 4^a);
curr_node = self.new_node(tx1,8,tym,6,tzm,5);
}
5 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,ty0,tzm,tx1,tym,tz1, a, 5^a);
curr_node = self.new_node(tx1,8,tym,7,tz1,8);
}
6 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,tym,tz0,tx1,ty1,tzm, a, 6^a);
curr_node = self.new_node(tx1,8,ty1,8,tzm,7);
}
7 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,tym,tzm,tx1,ty1,tz1, a, 7^a);
curr_node = 8;
}
_ => {}
}
match intersection {
Some(_) => { return intersection; },
None => {}
}
}
return None;
}
*/
}
/*
impl fmt::Display for OctreeNode<SceneObject> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut c = "".to_string();
let mut p = "".to_string();
for _ in -1.. self.depth{
p = p + " ";
}
p = p + "|-";
for i in 0..8 {
match self.children[i as usize].as_ref() {
Some (ref r) => {
c = c + "\n" + &p + " " + &r.to_string();
},
None => {
//c = c + "\n" + &p + " None";
},
}
}
write!(f, "OctreeNode -[{}]{}", self.items.len(), c)
}
}
*/
| {
match self.closest_intersection(r, max, min) {
Some(tupl) => {
return Some((self.items[tupl.0].clone(), tupl.1))
},
None => None
}
} | identifier_body |
octree.rs | use shapes::bbox::BBox;
use na::{Vector3};
use sceneobject::SceneObject;
use std::sync::Arc;
use std::fmt;
use ray::Ray;
use intersection::{RawIntersection, Intersection};
use ordered_float::OrderedFloat;
use shapes::geometry::Geometry;
#[derive(Clone)]
pub struct Octree<T: Geometry>{
root: OctreeNode,
items: Vec<Arc<T>>,
}
#[derive(Clone)]
pub struct OctreeNode {
depth: usize,
bounds: BBox,
// Octree structure:
children: [Option<Box<OctreeNode>>; 8],
items: Vec<usize>
}
fn vec3_invert(rd: Vector3<f64>) -> Vector3<f64> {
return Vector3::new(1.0/rd.x, 1.0/rd.y, 1.0/rd.z);
}
type OctreeIntersections = Option<Vec<usize>>;
impl OctreeNode {
pub fn is_leaf(&self) -> bool {
for i in 0..8 {
match self.children[i as usize] {
Some(_) => { return false },
None => {}
}
}
return true;
}
pub fn is_empty(&self) -> bool {
return self.items.len() > 0;
}
pub fn len(&self) -> usize {
return self.items.len()
}
/// Perform a breadth first search of the tree, and then sort results by distance.
pub fn naive_intersection(&self, r: &Ray, max:f64, min:f64) -> OctreeIntersections {
let invrd = vec3_invert(r.rd);
if!self.bounds.fast_intersects(&r.ro, &invrd) {
return None
}
if self.is_leaf(){
return Some(self.items.clone());
}
let intersections = self.children
.iter()
.filter(|i| i.is_some())
.map(|c| c.as_ref().unwrap().naive_intersection(r,max, min))
.filter(|i| i.is_some())
.map(|i| i.unwrap())
.flatten()
.collect::<Vec<usize>>();
if intersections.is_empty(){
return None;
}
return Some(intersections);
}
}
impl<T: Geometry> Octree<T> {
//
// Create a new node, and subdivide into further nodes up until max_depth
// or until number of children objects is 0.
//
pub fn new(max_depth: usize, b: BBox, items: &Vec<Arc<T>>) -> Octree<T> {
let items: Vec<Arc<T>> = items.into_iter().cloned().collect();
let indices: Vec<usize> = (0..items.len()).collect();
return Octree {
root: Octree::create_node(0, max_depth, b, indices, &items),
items: items,
};
}
fn create_node(depth: usize, max_depth: usize, b: BBox, items: Vec<usize>, geometries: &Vec<Arc<T>>) -> OctreeNode{
// Rust arrays suck - this defaults them to 'None'
let mut children: [Option<Box<OctreeNode>>; 8] = Default::default();
for i in 0..8 {
// Does child node have any objects in?
if depth < max_depth && items.len() > 1 {
// Equal subdivision. Enhancement: Use different split.
let cbox = BBox::for_octant(i, &b);
let inside = items.clone()
.into_iter()
.filter( |x| { cbox.intersects_bbox( &geometries[*x].bounds() ) } )
.collect::<Vec<usize>>();
if inside.len() > 0 {
let node = Octree::create_node(depth + 1, max_depth, cbox, inside, geometries);
children[i as usize] = Some(Box::new(node));
}
}
}
OctreeNode {
depth: depth,
bounds: b,
children: children,
items: items,
}
}
pub fn raw_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<RawIntersection> {
return match self.closest_intersection(r, max, min) {
Some(tupl) => Some(tupl.1),
None => None
}
}
pub fn intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(Arc<T>, RawIntersection)> {
match self.closest_intersection(r, max, min) {
Some(tupl) => {
return Some((self.items[tupl.0].clone(), tupl.1))
},
None => None
}
}
fn closest_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(usize, RawIntersection)> {
return match self.root.naive_intersection(r, max, min) {
Some(opts) => self.items_intersection(r,max, min, opts),
None => None
}
}
// Iterate through potential items. Should only do on leaf if multiple items.
fn items_intersection(&self, r: &Ray, max:f64, min:f64, items: Vec<usize>) -> Option<(usize, RawIntersection)> {
let mut cdist = max;
let mut closest = None;
for i in items {
match self.items[i].intersects(r) {
Some(x) => {
if x.dist < cdist && x.dist >= min {
cdist = x.dist;
closest = Some((i, x));
}
},
None => (),
}
}
return closest;
}
pub fn bounds(&self) -> BBox {
return self.root.bounds;
}
/*
pub fn new_node(&self, txm:f64, x:u8, tym:f64, y:u8, tzm:f64, z:u8) -> u8{
if txm < tym {
if txm < tzm {return x;} // YZ plane
}
else{
if tym < tzm {return y;} // XZ plane
}
return z; // XY plane;
}
pub fn first_node_index(&self, tx0:f64, ty0:f64, tz0:f64, txm:f64, tym:f64, tzm:f64) -> u8 {
let mut answer:u8 = 0;
if tx0 > ty0 {
if tx0 > tz0 { // PLANE YZ
if tym < tx0 { answer|=2; } // set bit at position 1
if tzm < tx0 { answer|=1; } // set bit at position 0
return answer;
}
} else {
if ty0 > tz0 { // PLANE XZ
if txm < ty0 { answer|=4; } // set bit at position 2
if tzm < ty0 { answer|=1; } // set bit at position 0
}
}
// PLANE XY
if txm < tz0 { answer|=4; } // set bit at position 2
if tym < tz0 { answer|=2; } // set bit at position 1
return answer;
}
/// Based on:
/// An Efficient Parametric Algorithm for Octree Traversal (2000)
/// by J. Revelles, C. Ureña, M. Lastra
///
/// Status: Broken
/// Note: Missing bbox intersection?
pub fn revelles_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<Intersection> {
let mut a = 0;
let rd = r.rd.normalize();
let mut rd0 = rd[0];
let mut rd1 = rd[1];
let mut rd2 = rd[2];
let mut ro0 = r.ro[0];
let mut ro1 = r.ro[1];
let mut ro2 = r.ro[2]; | if rd0 < 0. {
ro0 = self.bounds.size()[0] - ro0;
rd0 = - rd0;
a |= 4 ; //bitwise OR (latest bits are XYZ)
}
if rd1 < 0. {
ro1 = self.bounds.size()[1] - ro1;
rd1 = - rd1;
a |= 2 ;
}
if rd2 < 0. {
ro2 = self.bounds.size()[2] - ro2;
rd2 = - rd2;
a |= 1 ;
}
let rn = Ray {
ro: Vector3::new(ro0, ro1, ro2),
rd: Vector3::new(rd0, rd1, rd2),
};
let divx:f64 = 1.0 / rn.rd[0];
let divy:f64 = 1.0 / rn.rd[1];
let divz:f64 = 1.0 / rn.rd[2];
let tx0:f64 = (self.bounds.min[0] - rn.ro[0]) * divx;
let tx1:f64 = (self.bounds.max[0] - rn.ro[0]) * divx;
let ty0:f64 = (self.bounds.min[1] - rn.ro[1]) * divy;
let ty1:f64 = (self.bounds.max[1] - rn.ro[1]) * divy;
let tz0:f64 = (self.bounds.min[2] - rn.ro[2]) * divz;
let tz1:f64 = (self.bounds.max[2] - rn.ro[2]) * divz;
if tz0.max(tx0.max(ty0)) < tz1.min(tx1.min(ty1)) {
return self.revelles_proc_subtree(r, &rn, max, min, tx0, ty0, tz0, tx1, ty1, tz1, a);
}
//println!("- magnitude miss {} {} {}", r, tz0.max(tx0.max(ty0)), tz1.min(tx1.min(ty1)));
return None;
}
pub fn revelles_proc_child(&self, ro: &Ray, r:&Ray, max:f64, min:f64, tx0:f64, ty0:f64, tz0:f64, tx1:f64, ty1:f64, tz1:f64, a:u8, i: u8)-> Option<Intersection> {
return match self.children[i as usize] {
Some (ref x) => {
return x.revelles_proc_subtree(ro, r, max, min, tx0, ty0, tz0, tx1, ty1, tz1, a)
}
None => {
return None
}
}
}
pub fn revelles_proc_subtree(&self, ro:&Ray, r:&Ray, max:f64, min:f64, tx0:f64, ty0:f64, tz0:f64, tx1:f64, ty1:f64, tz1:f64, a:u8) -> Option<Intersection> {
//println!("- node hit");
if tx1 < 0. || ty1 < 0. || tz1 < 0. {
return None;
}
if self.is_leaf(){
return self.items_intersection(ro, max, min);
}
let txm = 0.5 * (tx0 + tx1);
let tym = 0.5 * (ty0 + ty1);
let tzm = 0.5 * (tz0 + tz1);
let mut curr_node = self.first_node_index(tx0,ty0,tz0,txm,tym,tzm);
while curr_node < 8 { // TODO do-while?
let mut intersection: Option<Intersection> = None;
match curr_node {
0 => {
intersection = self.revelles_proc_child(ro, r, max, min, tx0,ty0,tz0,txm,tym,tzm, a, 0);
curr_node = self.new_node(txm,4,tym,2,tzm,1);
},
1 => {
intersection = self.revelles_proc_child(ro, r, max, min, tx0,ty0,tzm,txm,tym,tz1, a, 1^a);
curr_node = self.new_node(txm,5,tym,3,tz1,8);
}
2 => {
intersection =self.revelles_proc_child(ro, r, max, min, tx0,tym,tz0,txm,ty1,tzm, a, 2^a);
curr_node = self.new_node(txm,6,ty1,8,tzm,3);
}
3 => {
intersection =self.revelles_proc_child(ro, r, max, min, tx0,tym,tzm,txm,ty1,tz1, a, 3^a);
curr_node = self.new_node(txm,7,ty1,8,tz1,8);
}
4 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,ty0,tz0,tx1,tym,tzm, a, 4^a);
curr_node = self.new_node(tx1,8,tym,6,tzm,5);
}
5 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,ty0,tzm,tx1,tym,tz1, a, 5^a);
curr_node = self.new_node(tx1,8,tym,7,tz1,8);
}
6 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,tym,tz0,tx1,ty1,tzm, a, 6^a);
curr_node = self.new_node(tx1,8,ty1,8,tzm,7);
}
7 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,tym,tzm,tx1,ty1,tz1, a, 7^a);
curr_node = 8;
}
_ => {}
}
match intersection {
Some(_) => { return intersection; },
None => {}
}
}
return None;
}
*/
}
/*
impl fmt::Display for OctreeNode<SceneObject> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut c = "".to_string();
let mut p = "".to_string();
for _ in -1.. self.depth{
p = p + " ";
}
p = p + "|-";
for i in 0..8 {
match self.children[i as usize].as_ref() {
Some (ref r) => {
c = c + "\n" + &p + " " + &r.to_string();
},
None => {
//c = c + "\n" + &p + " None";
},
}
}
write!(f, "OctreeNode -[{}]{}", self.items.len(), c)
}
}
*/ |
// fixes for rays with negative direction | random_line_split |
octree.rs | use shapes::bbox::BBox;
use na::{Vector3};
use sceneobject::SceneObject;
use std::sync::Arc;
use std::fmt;
use ray::Ray;
use intersection::{RawIntersection, Intersection};
use ordered_float::OrderedFloat;
use shapes::geometry::Geometry;
#[derive(Clone)]
pub struct Octree<T: Geometry>{
root: OctreeNode,
items: Vec<Arc<T>>,
}
#[derive(Clone)]
pub struct OctreeNode {
depth: usize,
bounds: BBox,
// Octree structure:
children: [Option<Box<OctreeNode>>; 8],
items: Vec<usize>
}
fn vec3_invert(rd: Vector3<f64>) -> Vector3<f64> {
return Vector3::new(1.0/rd.x, 1.0/rd.y, 1.0/rd.z);
}
type OctreeIntersections = Option<Vec<usize>>;
impl OctreeNode {
pub fn is_leaf(&self) -> bool {
for i in 0..8 {
match self.children[i as usize] {
Some(_) => { return false },
None => {}
}
}
return true;
}
pub fn is_empty(&self) -> bool {
return self.items.len() > 0;
}
pub fn len(&self) -> usize {
return self.items.len()
}
/// Perform a breadth first search of the tree, and then sort results by distance.
pub fn naive_intersection(&self, r: &Ray, max:f64, min:f64) -> OctreeIntersections {
let invrd = vec3_invert(r.rd);
if!self.bounds.fast_intersects(&r.ro, &invrd) {
return None
}
if self.is_leaf(){
return Some(self.items.clone());
}
let intersections = self.children
.iter()
.filter(|i| i.is_some())
.map(|c| c.as_ref().unwrap().naive_intersection(r,max, min))
.filter(|i| i.is_some())
.map(|i| i.unwrap())
.flatten()
.collect::<Vec<usize>>();
if intersections.is_empty(){
return None;
}
return Some(intersections);
}
}
impl<T: Geometry> Octree<T> {
//
// Create a new node, and subdivide into further nodes up until max_depth
// or until number of children objects is 0.
//
pub fn new(max_depth: usize, b: BBox, items: &Vec<Arc<T>>) -> Octree<T> {
let items: Vec<Arc<T>> = items.into_iter().cloned().collect();
let indices: Vec<usize> = (0..items.len()).collect();
return Octree {
root: Octree::create_node(0, max_depth, b, indices, &items),
items: items,
};
}
fn create_node(depth: usize, max_depth: usize, b: BBox, items: Vec<usize>, geometries: &Vec<Arc<T>>) -> OctreeNode{
// Rust arrays suck - this defaults them to 'None'
let mut children: [Option<Box<OctreeNode>>; 8] = Default::default();
for i in 0..8 {
// Does child node have any objects in?
if depth < max_depth && items.len() > 1 {
// Equal subdivision. Enhancement: Use different split.
let cbox = BBox::for_octant(i, &b);
let inside = items.clone()
.into_iter()
.filter( |x| { cbox.intersects_bbox( &geometries[*x].bounds() ) } )
.collect::<Vec<usize>>();
if inside.len() > 0 {
let node = Octree::create_node(depth + 1, max_depth, cbox, inside, geometries);
children[i as usize] = Some(Box::new(node));
}
}
}
OctreeNode {
depth: depth,
bounds: b,
children: children,
items: items,
}
}
pub fn | (&self, r: &Ray, max:f64, min:f64) -> Option<RawIntersection> {
return match self.closest_intersection(r, max, min) {
Some(tupl) => Some(tupl.1),
None => None
}
}
pub fn intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(Arc<T>, RawIntersection)> {
match self.closest_intersection(r, max, min) {
Some(tupl) => {
return Some((self.items[tupl.0].clone(), tupl.1))
},
None => None
}
}
fn closest_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(usize, RawIntersection)> {
return match self.root.naive_intersection(r, max, min) {
Some(opts) => self.items_intersection(r,max, min, opts),
None => None
}
}
// Iterate through potential items. Should only do on leaf if multiple items.
fn items_intersection(&self, r: &Ray, max:f64, min:f64, items: Vec<usize>) -> Option<(usize, RawIntersection)> {
let mut cdist = max;
let mut closest = None;
for i in items {
match self.items[i].intersects(r) {
Some(x) => {
if x.dist < cdist && x.dist >= min {
cdist = x.dist;
closest = Some((i, x));
}
},
None => (),
}
}
return closest;
}
pub fn bounds(&self) -> BBox {
return self.root.bounds;
}
/*
pub fn new_node(&self, txm:f64, x:u8, tym:f64, y:u8, tzm:f64, z:u8) -> u8{
if txm < tym {
if txm < tzm {return x;} // YZ plane
}
else{
if tym < tzm {return y;} // XZ plane
}
return z; // XY plane;
}
pub fn first_node_index(&self, tx0:f64, ty0:f64, tz0:f64, txm:f64, tym:f64, tzm:f64) -> u8 {
let mut answer:u8 = 0;
if tx0 > ty0 {
if tx0 > tz0 { // PLANE YZ
if tym < tx0 { answer|=2; } // set bit at position 1
if tzm < tx0 { answer|=1; } // set bit at position 0
return answer;
}
} else {
if ty0 > tz0 { // PLANE XZ
if txm < ty0 { answer|=4; } // set bit at position 2
if tzm < ty0 { answer|=1; } // set bit at position 0
}
}
// PLANE XY
if txm < tz0 { answer|=4; } // set bit at position 2
if tym < tz0 { answer|=2; } // set bit at position 1
return answer;
}
/// Based on:
/// An Efficient Parametric Algorithm for Octree Traversal (2000)
/// by J. Revelles, C. Ureña, M. Lastra
///
/// Status: Broken
/// Note: Missing bbox intersection?
pub fn revelles_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<Intersection> {
let mut a = 0;
let rd = r.rd.normalize();
let mut rd0 = rd[0];
let mut rd1 = rd[1];
let mut rd2 = rd[2];
let mut ro0 = r.ro[0];
let mut ro1 = r.ro[1];
let mut ro2 = r.ro[2];
// fixes for rays with negative direction
if rd0 < 0. {
ro0 = self.bounds.size()[0] - ro0;
rd0 = - rd0;
a |= 4 ; //bitwise OR (latest bits are XYZ)
}
if rd1 < 0. {
ro1 = self.bounds.size()[1] - ro1;
rd1 = - rd1;
a |= 2 ;
}
if rd2 < 0. {
ro2 = self.bounds.size()[2] - ro2;
rd2 = - rd2;
a |= 1 ;
}
let rn = Ray {
ro: Vector3::new(ro0, ro1, ro2),
rd: Vector3::new(rd0, rd1, rd2),
};
let divx:f64 = 1.0 / rn.rd[0];
let divy:f64 = 1.0 / rn.rd[1];
let divz:f64 = 1.0 / rn.rd[2];
let tx0:f64 = (self.bounds.min[0] - rn.ro[0]) * divx;
let tx1:f64 = (self.bounds.max[0] - rn.ro[0]) * divx;
let ty0:f64 = (self.bounds.min[1] - rn.ro[1]) * divy;
let ty1:f64 = (self.bounds.max[1] - rn.ro[1]) * divy;
let tz0:f64 = (self.bounds.min[2] - rn.ro[2]) * divz;
let tz1:f64 = (self.bounds.max[2] - rn.ro[2]) * divz;
if tz0.max(tx0.max(ty0)) < tz1.min(tx1.min(ty1)) {
return self.revelles_proc_subtree(r, &rn, max, min, tx0, ty0, tz0, tx1, ty1, tz1, a);
}
//println!("- magnitude miss {} {} {}", r, tz0.max(tx0.max(ty0)), tz1.min(tx1.min(ty1)));
return None;
}
pub fn revelles_proc_child(&self, ro: &Ray, r:&Ray, max:f64, min:f64, tx0:f64, ty0:f64, tz0:f64, tx1:f64, ty1:f64, tz1:f64, a:u8, i: u8)-> Option<Intersection> {
return match self.children[i as usize] {
Some (ref x) => {
return x.revelles_proc_subtree(ro, r, max, min, tx0, ty0, tz0, tx1, ty1, tz1, a)
}
None => {
return None
}
}
}
pub fn revelles_proc_subtree(&self, ro:&Ray, r:&Ray, max:f64, min:f64, tx0:f64, ty0:f64, tz0:f64, tx1:f64, ty1:f64, tz1:f64, a:u8) -> Option<Intersection> {
//println!("- node hit");
if tx1 < 0. || ty1 < 0. || tz1 < 0. {
return None;
}
if self.is_leaf(){
return self.items_intersection(ro, max, min);
}
let txm = 0.5 * (tx0 + tx1);
let tym = 0.5 * (ty0 + ty1);
let tzm = 0.5 * (tz0 + tz1);
let mut curr_node = self.first_node_index(tx0,ty0,tz0,txm,tym,tzm);
while curr_node < 8 { // TODO do-while?
let mut intersection: Option<Intersection> = None;
match curr_node {
0 => {
intersection = self.revelles_proc_child(ro, r, max, min, tx0,ty0,tz0,txm,tym,tzm, a, 0);
curr_node = self.new_node(txm,4,tym,2,tzm,1);
},
1 => {
intersection = self.revelles_proc_child(ro, r, max, min, tx0,ty0,tzm,txm,tym,tz1, a, 1^a);
curr_node = self.new_node(txm,5,tym,3,tz1,8);
}
2 => {
intersection =self.revelles_proc_child(ro, r, max, min, tx0,tym,tz0,txm,ty1,tzm, a, 2^a);
curr_node = self.new_node(txm,6,ty1,8,tzm,3);
}
3 => {
intersection =self.revelles_proc_child(ro, r, max, min, tx0,tym,tzm,txm,ty1,tz1, a, 3^a);
curr_node = self.new_node(txm,7,ty1,8,tz1,8);
}
4 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,ty0,tz0,tx1,tym,tzm, a, 4^a);
curr_node = self.new_node(tx1,8,tym,6,tzm,5);
}
5 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,ty0,tzm,tx1,tym,tz1, a, 5^a);
curr_node = self.new_node(tx1,8,tym,7,tz1,8);
}
6 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,tym,tz0,tx1,ty1,tzm, a, 6^a);
curr_node = self.new_node(tx1,8,ty1,8,tzm,7);
}
7 => {
intersection = self.revelles_proc_child(ro, r, max, min, txm,tym,tzm,tx1,ty1,tz1, a, 7^a);
curr_node = 8;
}
_ => {}
}
match intersection {
Some(_) => { return intersection; },
None => {}
}
}
return None;
}
*/
}
/*
impl fmt::Display for OctreeNode<SceneObject> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut c = "".to_string();
let mut p = "".to_string();
for _ in -1.. self.depth{
p = p + " ";
}
p = p + "|-";
for i in 0..8 {
match self.children[i as usize].as_ref() {
Some (ref r) => {
c = c + "\n" + &p + " " + &r.to_string();
},
None => {
//c = c + "\n" + &p + " None";
},
}
}
write!(f, "OctreeNode -[{}]{}", self.items.len(), c)
}
}
*/
| raw_intersection | identifier_name |
block-arg.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.
use std::vec;
// Check usage and precedence of block arguments in expressions:
pub fn main() {
let v = ~[-1f, 0f, 1f, 2f, 3f];
// Statement form does not require parentheses:
for v.iter().advance |i| {
info!("%?", *i);
}
// Usable at all:
let mut any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than assignments:
any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than unary operations:
let abs_v = do v.iter().transform |e| { e.abs() }.collect::<~[float]>();
assert!(do abs_v.iter().all |e| { e.is_positive() });
assert!(!do abs_v.iter().any_ |e| { e.is_negative() });
// Usable in funny statement-like forms:
if!do v.iter().any_ |e| { e.is_positive() } {
assert!(false);
}
match do v.iter().all |e| { e.is_negative() } {
true => { fail!("incorrect answer."); }
false => { }
}
match 3 {
_ if do v.iter().any_ |e| { e.is_negative() } => {
}
_ => {
fail!("wrong answer.");
}
}
// Lower precedence than binary operations:
let w = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let y = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let z = 10f + do v.iter().fold(0f) |x, y| { x + *y };
assert_eq!(w, y);
assert_eq!(y, z);
// In the tail of a block
let w =
if true { do abs_v.iter().any_ |e| { e.is_positive() } }
else | ;
assert!(w);
}
| { false } | conditional_block |
block-arg.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.
use std::vec;
// Check usage and precedence of block arguments in expressions:
pub fn | () {
let v = ~[-1f, 0f, 1f, 2f, 3f];
// Statement form does not require parentheses:
for v.iter().advance |i| {
info!("%?", *i);
}
// Usable at all:
let mut any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than assignments:
any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than unary operations:
let abs_v = do v.iter().transform |e| { e.abs() }.collect::<~[float]>();
assert!(do abs_v.iter().all |e| { e.is_positive() });
assert!(!do abs_v.iter().any_ |e| { e.is_negative() });
// Usable in funny statement-like forms:
if!do v.iter().any_ |e| { e.is_positive() } {
assert!(false);
}
match do v.iter().all |e| { e.is_negative() } {
true => { fail!("incorrect answer."); }
false => { }
}
match 3 {
_ if do v.iter().any_ |e| { e.is_negative() } => {
}
_ => {
fail!("wrong answer.");
}
}
// Lower precedence than binary operations:
let w = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let y = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let z = 10f + do v.iter().fold(0f) |x, y| { x + *y };
assert_eq!(w, y);
assert_eq!(y, z);
// In the tail of a block
let w =
if true { do abs_v.iter().any_ |e| { e.is_positive() } }
else { false };
assert!(w);
}
| main | identifier_name |
block-arg.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.
use std::vec;
// Check usage and precedence of block arguments in expressions:
pub fn main() {
let v = ~[-1f, 0f, 1f, 2f, 3f]; | for v.iter().advance |i| {
info!("%?", *i);
}
// Usable at all:
let mut any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than assignments:
any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than unary operations:
let abs_v = do v.iter().transform |e| { e.abs() }.collect::<~[float]>();
assert!(do abs_v.iter().all |e| { e.is_positive() });
assert!(!do abs_v.iter().any_ |e| { e.is_negative() });
// Usable in funny statement-like forms:
if!do v.iter().any_ |e| { e.is_positive() } {
assert!(false);
}
match do v.iter().all |e| { e.is_negative() } {
true => { fail!("incorrect answer."); }
false => { }
}
match 3 {
_ if do v.iter().any_ |e| { e.is_negative() } => {
}
_ => {
fail!("wrong answer.");
}
}
// Lower precedence than binary operations:
let w = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let y = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let z = 10f + do v.iter().fold(0f) |x, y| { x + *y };
assert_eq!(w, y);
assert_eq!(y, z);
// In the tail of a block
let w =
if true { do abs_v.iter().any_ |e| { e.is_positive() } }
else { false };
assert!(w);
} |
// Statement form does not require parentheses: | random_line_split |
block-arg.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.
use std::vec;
// Check usage and precedence of block arguments in expressions:
pub fn main() |
// Usable at all:
let mut any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than assignments:
any_negative = do v.iter().any_ |e| { e.is_negative() };
assert!(any_negative);
// Higher precedence than unary operations:
let abs_v = do v.iter().transform |e| { e.abs() }.collect::<~[float]>();
assert!(do abs_v.iter().all |e| { e.is_positive() });
assert!(!do abs_v.iter().any_ |e| { e.is_negative() });
// Usable in funny statement-like forms:
if!do v.iter().any_ |e| { e.is_positive() } {
assert!(false);
}
match do v.iter().all |e| { e.is_negative() } {
true => { fail!("incorrect answer."); }
false => { }
}
match 3 {
_ if do v.iter().any_ |e| { e.is_negative() } => {
}
_ => {
fail!("wrong answer.");
}
}
// Lower precedence than binary operations:
let w = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let y = do v.iter().fold(0f) |x, y| { x + *y } + 10f;
let z = 10f + do v.iter().fold(0f) |x, y| { x + *y };
assert_eq!(w, y);
assert_eq!(y, z);
// In the tail of a block
let w =
if true { do abs_v.iter().any_ |e| { e.is_positive() } }
else { false };
assert!(w);
}
| {
let v = ~[-1f, 0f, 1f, 2f, 3f];
// Statement form does not require parentheses:
for v.iter().advance |i| {
info!("%?", *i);
} | identifier_body |
const-big-enum.rs | // run-pass
enum Foo {
Bar(u32),
Baz,
Quux(u64, u16)
}
static X: Foo = Foo::Baz;
pub fn main() {
match X { | Foo::Bar(s) => assert_eq!(s, 2654435769),
_ => panic!()
}
match Z {
Foo::Quux(d,h) => {
assert_eq!(d, 0x123456789abcdef0);
assert_eq!(h, 0x1234);
}
_ => panic!()
}
}
static Y: Foo = Foo::Bar(2654435769);
static Z: Foo = Foo::Quux(0x123456789abcdef0, 0x1234); | Foo::Baz => {}
_ => panic!()
}
match Y { | random_line_split |
const-big-enum.rs | // run-pass
enum | {
Bar(u32),
Baz,
Quux(u64, u16)
}
static X: Foo = Foo::Baz;
pub fn main() {
match X {
Foo::Baz => {}
_ => panic!()
}
match Y {
Foo::Bar(s) => assert_eq!(s, 2654435769),
_ => panic!()
}
match Z {
Foo::Quux(d,h) => {
assert_eq!(d, 0x123456789abcdef0);
assert_eq!(h, 0x1234);
}
_ => panic!()
}
}
static Y: Foo = Foo::Bar(2654435769);
static Z: Foo = Foo::Quux(0x123456789abcdef0, 0x1234);
| Foo | identifier_name |
trait-coercion-generic-bad.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Struct {
person: &'static str
}
trait Trait<T> {
fn f(&self, x: T);
}
impl Trait<&'static str> for Struct {
fn f(&self, x: &'static str) {
println!("Hello, {}!", x);
}
}
fn | () {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let s: Box<Trait<isize>> = Box::new(Struct { person: "Fred" });
//~^ ERROR the trait `Trait<isize>` is not implemented for the type `Struct`
s.f(1);
}
| main | identifier_name |
trait-coercion-generic-bad.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 | struct Struct {
person: &'static str
}
trait Trait<T> {
fn f(&self, x: T);
}
impl Trait<&'static str> for Struct {
fn f(&self, x: &'static str) {
println!("Hello, {}!", x);
}
}
fn main() {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let s: Box<Trait<isize>> = Box::new(Struct { person: "Fred" });
//~^ ERROR the trait `Trait<isize>` is not implemented for the type `Struct`
s.f(1);
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
settings.rs | use crate::render::object::BodyColor;
use std::fs::File;
use std::path::PathBuf;
#[derive(Deserialize)]
pub struct Car {
pub id: String,
pub color: BodyColor,
pub slots: Vec<String>,
pub pos: Option<(i32, i32)>,
}
#[derive(Copy, Clone, Deserialize)]
pub enum View {
Flat,
Perspective,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Camera {
pub angle: u8,
pub height: f32,
pub target_overhead: f32,
pub speed: f32,
pub depth_range: (f32, f32),
}
#[derive(Copy, Clone, Deserialize)]
pub enum SpawnAt {
Player,
Random,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Other {
pub count: usize,
pub spawn_at: SpawnAt,
}
#[derive(Copy, Clone, Deserialize)]
pub struct GpuCollision {
pub max_objects: usize,
pub max_polygons_total: usize,
pub max_raster_size: (u32, u32),
}
#[derive(Copy, Clone, Deserialize)]
pub struct Physics {
pub max_quant: f32,
pub shape_sampling: u8,
pub gpu_collision: Option<GpuCollision>,
}
#[derive(Deserialize)]
pub struct Game {
pub level: String,
pub cycle: String,
pub view: View,
pub camera: Camera,
pub other: Other,
pub physics: Physics,
}
#[derive(Deserialize)]
pub struct Window {
pub title: String,
pub size: [u32; 2],
pub reload_on_focus: bool,
}
#[derive(Copy, Clone, Deserialize)]
pub enum Backend {
Auto,
Metal,
Vulkan,
DX12,
DX11,
GL,
}
impl Backend {
pub fn to_wgpu(&self) -> wgpu::Backends {
match *self {
Backend::Auto => wgpu::Backends::PRIMARY,
Backend::Metal => wgpu::Backends::METAL,
Backend::Vulkan => wgpu::Backends::VULKAN,
Backend::DX12 => wgpu::Backends::DX12,
Backend::DX11 => wgpu::Backends::DX11,
Backend::GL => wgpu::Backends::GL,
}
}
}
#[derive(Copy, Clone, Default, Deserialize)]
pub struct DebugRender {
pub max_vertices: usize,
pub collision_shapes: bool,
pub collision_map: bool,
pub impulses: bool,
}
#[derive(Copy, Clone, Deserialize)]
pub enum ShadowTerrain {
RayTraced,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Shadow {
pub size: u32,
pub terrain: ShadowTerrain,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Light {
pub pos: [f32; 4],
pub color: [f32; 4],
pub shadow: Shadow,
}
#[derive(Copy, Clone, Deserialize)]
pub enum Terrain {
RayTraced,
RayMipTraced {
mip_count: u32,
max_jumps: u32,
max_steps: u32,
debug: bool,
},
Sliced,
Painted,
Scattered {
density: [u32; 3],
},
}
#[derive(Copy, Clone, Deserialize)]
pub struct Water {}
#[derive(Copy, Clone, Deserialize)]
pub struct Fog {
pub color: [f32; 4],
pub depth: f32,
}
#[derive(Clone, Deserialize)]
pub struct Render {
pub wgpu_trace_path: String,
pub light: Light,
pub terrain: Terrain,
pub water: Water,
pub fog: Fog,
pub debug: DebugRender,
}
#[derive(Deserialize)]
pub struct Settings {
pub data_path: PathBuf,
pub car: Car,
pub game: Game,
pub window: Window,
pub backend: Backend,
pub render: Render,
}
impl Settings {
pub fn load(path: &str) -> Self { | File::open(path)
.unwrap_or_else(|e| panic!("Unable to open the settings file: {:?}.\nPlease copy '{}' to '{}' and adjust 'data_path'",
e, TEMPLATE, PATH))
.read_to_string(&mut string)
.unwrap();
let set: Settings = match ron::de::from_str(&string) {
Ok(set) => set,
Err(e) => panic!(
"Unable to parse settings RON: {:?}.\nPlease check if `{}` has changed and your local config needs to be adjusted.",
e,
TEMPLATE,
),
};
if!set.check_path("options.dat") {
panic!(
"Can't find the resources of the original Vangers game at {:?}, please check your `{}`",
set.data_path, PATH,
);
}
set
}
pub fn open_relative(&self, path: &str) -> File {
File::open(self.data_path.join(path))
.unwrap_or_else(|_| panic!("Unable to open game file: {}", path))
}
pub fn check_path(&self, path: &str) -> bool {
self.data_path.join(path).exists()
}
pub fn open_palette(&self) -> File {
let path = self
.data_path
.join("resource")
.join("pal")
.join("objects.pal");
File::open(path).expect("Unable to open palette")
}
pub fn _open_vehicle_model(&self, name: &str) -> File {
let path = self
.data_path
.join("resource")
.join("m3d")
.join("mechous")
.join(name)
.with_extension("m3d");
File::open(path).unwrap_or_else(|_| panic!("Unable to open vehicle {}", name))
}
} | use std::io::Read;
const TEMPLATE: &str = "config/settings.template.ron";
const PATH: &str = "config/settings.ron";
let mut string = String::new(); | random_line_split |
settings.rs | use crate::render::object::BodyColor;
use std::fs::File;
use std::path::PathBuf;
#[derive(Deserialize)]
pub struct Car {
pub id: String,
pub color: BodyColor,
pub slots: Vec<String>,
pub pos: Option<(i32, i32)>,
}
#[derive(Copy, Clone, Deserialize)]
pub enum View {
Flat,
Perspective,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Camera {
pub angle: u8,
pub height: f32,
pub target_overhead: f32,
pub speed: f32,
pub depth_range: (f32, f32),
}
#[derive(Copy, Clone, Deserialize)]
pub enum SpawnAt {
Player,
Random,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Other {
pub count: usize,
pub spawn_at: SpawnAt,
}
#[derive(Copy, Clone, Deserialize)]
pub struct GpuCollision {
pub max_objects: usize,
pub max_polygons_total: usize,
pub max_raster_size: (u32, u32),
}
#[derive(Copy, Clone, Deserialize)]
pub struct Physics {
pub max_quant: f32,
pub shape_sampling: u8,
pub gpu_collision: Option<GpuCollision>,
}
#[derive(Deserialize)]
pub struct Game {
pub level: String,
pub cycle: String,
pub view: View,
pub camera: Camera,
pub other: Other,
pub physics: Physics,
}
#[derive(Deserialize)]
pub struct Window {
pub title: String,
pub size: [u32; 2],
pub reload_on_focus: bool,
}
#[derive(Copy, Clone, Deserialize)]
pub enum Backend {
Auto,
Metal,
Vulkan,
DX12,
DX11,
GL,
}
impl Backend {
pub fn to_wgpu(&self) -> wgpu::Backends {
match *self {
Backend::Auto => wgpu::Backends::PRIMARY,
Backend::Metal => wgpu::Backends::METAL,
Backend::Vulkan => wgpu::Backends::VULKAN,
Backend::DX12 => wgpu::Backends::DX12,
Backend::DX11 => wgpu::Backends::DX11,
Backend::GL => wgpu::Backends::GL,
}
}
}
#[derive(Copy, Clone, Default, Deserialize)]
pub struct DebugRender {
pub max_vertices: usize,
pub collision_shapes: bool,
pub collision_map: bool,
pub impulses: bool,
}
#[derive(Copy, Clone, Deserialize)]
pub enum ShadowTerrain {
RayTraced,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Shadow {
pub size: u32,
pub terrain: ShadowTerrain,
}
#[derive(Copy, Clone, Deserialize)]
pub struct Light {
pub pos: [f32; 4],
pub color: [f32; 4],
pub shadow: Shadow,
}
#[derive(Copy, Clone, Deserialize)]
pub enum Terrain {
RayTraced,
RayMipTraced {
mip_count: u32,
max_jumps: u32,
max_steps: u32,
debug: bool,
},
Sliced,
Painted,
Scattered {
density: [u32; 3],
},
}
#[derive(Copy, Clone, Deserialize)]
pub struct Water {}
#[derive(Copy, Clone, Deserialize)]
pub struct | {
pub color: [f32; 4],
pub depth: f32,
}
#[derive(Clone, Deserialize)]
pub struct Render {
pub wgpu_trace_path: String,
pub light: Light,
pub terrain: Terrain,
pub water: Water,
pub fog: Fog,
pub debug: DebugRender,
}
#[derive(Deserialize)]
pub struct Settings {
pub data_path: PathBuf,
pub car: Car,
pub game: Game,
pub window: Window,
pub backend: Backend,
pub render: Render,
}
impl Settings {
pub fn load(path: &str) -> Self {
use std::io::Read;
const TEMPLATE: &str = "config/settings.template.ron";
const PATH: &str = "config/settings.ron";
let mut string = String::new();
File::open(path)
.unwrap_or_else(|e| panic!("Unable to open the settings file: {:?}.\nPlease copy '{}' to '{}' and adjust 'data_path'",
e, TEMPLATE, PATH))
.read_to_string(&mut string)
.unwrap();
let set: Settings = match ron::de::from_str(&string) {
Ok(set) => set,
Err(e) => panic!(
"Unable to parse settings RON: {:?}.\nPlease check if `{}` has changed and your local config needs to be adjusted.",
e,
TEMPLATE,
),
};
if!set.check_path("options.dat") {
panic!(
"Can't find the resources of the original Vangers game at {:?}, please check your `{}`",
set.data_path, PATH,
);
}
set
}
pub fn open_relative(&self, path: &str) -> File {
File::open(self.data_path.join(path))
.unwrap_or_else(|_| panic!("Unable to open game file: {}", path))
}
pub fn check_path(&self, path: &str) -> bool {
self.data_path.join(path).exists()
}
pub fn open_palette(&self) -> File {
let path = self
.data_path
.join("resource")
.join("pal")
.join("objects.pal");
File::open(path).expect("Unable to open palette")
}
pub fn _open_vehicle_model(&self, name: &str) -> File {
let path = self
.data_path
.join("resource")
.join("m3d")
.join("mechous")
.join(name)
.with_extension("m3d");
File::open(path).unwrap_or_else(|_| panic!("Unable to open vehicle {}", name))
}
}
| Fog | identifier_name |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimension::{Dim, DimAdd, DimDiff, DimSub, DimSum, Dynamic, U1};
use crate::storage::{Storage, StorageMut};
/// The Cholesky decomposition of a symmetric-definite-positive matrix.
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(serialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Serialize"))
)]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Deserialize<'de>"))
)]
#[derive(Clone, Debug)]
pub struct Cholesky<N: ComplexField, D: Dim>
where
DefaultAllocator: Allocator<N, D, D>,
{
chol: MatrixN<N, D>,
}
impl<N: ComplexField, D: Dim> Copy for Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
MatrixN<N, D>: Copy,
{
}
impl<N: ComplexField, D: Dim> Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of `matrix`.
///
/// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn new(mut matrix: MatrixN<N, D>) -> Option<Self> {
assert!(matrix.is_square(), "The input matrix must be square.");
let n = matrix.nrows();
for j in 0..n {
for k in 0..j {
let factor = unsafe { -*matrix.get_unchecked((j, k)) };
let (mut col_j, col_k) = matrix.columns_range_pair_mut(j, k);
let mut col_j = col_j.rows_range_mut(j..);
let col_k = col_k.rows_range(j..);
col_j.axpy(factor.conjugate(), &col_k, N::one());
}
let diag = unsafe { *matrix.get_unchecked((j, j)) };
if!diag.is_zero() {
if let Some(denom) = diag.try_sqrt() {
unsafe {
*matrix.get_unchecked_mut((j, j)) = denom;
}
let mut col = matrix.slice_range_mut(j + 1.., j);
col /= denom;
continue;
}
}
// The diagonal element is either zero or its square root could not
// be taken (e.g. for negative real numbers).
return None;
}
Some(Cholesky { chol: matrix })
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// upper-triangular part filled with zeros.
pub fn unpack(mut self) -> MatrixN<N, D> {
self.chol.fill_upper_triangle(N::zero(), 1);
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// The values of the strict upper-triangular part are garbage and should be ignored by further
/// computations.
pub fn unpack_dirty(self) -> MatrixN<N, D> {
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// uppen-triangular part filled with zeros.
pub fn l(&self) -> MatrixN<N, D> {
self.chol.lower_triangle()
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// This is an allocation-less version of `self.l()`. The values of the strict upper-triangular
/// part are garbage and should be ignored by further computations.
pub fn l_dirty(&self) -> &MatrixN<N, D> {
&self.chol
}
/// Solves the system `self * x = b` where `self` is the decomposed matrix and `x` the unknown.
///
/// The result is stored on `b`.
pub fn solve_mut<R2: Dim, C2: Dim, S2>(&self, b: &mut Matrix<N, R2, C2, S2>)
where
S2: StorageMut<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
let _ = self.chol.solve_lower_triangular_mut(b);
let _ = self.chol.ad_solve_lower_triangular_mut(b);
}
/// Returns the solution of the system `self * x = b` where `self` is the decomposed matrix and
/// `x` the unknown.
pub fn solve<R2: Dim, C2: Dim, S2>(&self, b: &Matrix<N, R2, C2, S2>) -> MatrixMN<N, R2, C2>
where
S2: Storage<N, R2, C2>,
DefaultAllocator: Allocator<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
let mut res = b.clone_owned();
self.solve_mut(&mut res);
res
}
/// Computes the inverse of the decomposed matrix.
pub fn inverse(&self) -> MatrixN<N, D> {
let shape = self.chol.data.shape();
let mut res = MatrixN::identity_generic(shape.0, shape.1);
self.solve_mut(&mut res);
res
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `v`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (v * v.adjoint())`.
#[inline]
pub fn rank_one_update<R2: Dim, S2>(&mut self, x: &Vector<N, R2, S2>, sigma: N::RealField)
where
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, R2, U1>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
Self::xx_rank_one_update(&mut self.chol, &mut x.clone_owned(), sigma)
}
/// Updates the decomposition such that we get the decomposition of a matrix with the given column `col` in the `j`th position.
/// Since the matrix is square, an identical row will be added in the `j`th row.
pub fn insert_column<R2, S2>(
&self,
j: usize,
col: Vector<N, R2, S2>,
) -> Cholesky<N, DimSum<D, U1>>
where
D: DimAdd<U1>,
R2: Dim,
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, DimSum<D, U1>, DimSum<D, U1>> + Allocator<N, R2>,
ShapeConstraint: SameNumberOfRows<R2, DimSum<D, U1>>,
{
let mut col = col.into_owned();
// for an explanation of the formulas, see https://en.wikipedia.org/wiki/Cholesky_decomposition#Updating_the_decomposition
let n = col.nrows();
assert_eq!(
n,
self.chol.nrows() + 1,
"The new column must have the size of the factored matrix plus one."
);
assert!(j < n, "j needs to be within the bound of the new matrix.");
// loads the data into a new matrix with an additional jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.add(U1),
self.chol.data.shape().1.add(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j + 1..)
.copy_from(&self.chol.slice_range(..j, j..));
chol.slice_range_mut(j + 1..,..j)
.copy_from(&self.chol.slice_range(j..,..j));
chol.slice_range_mut(j + 1.., j + 1..)
.copy_from(&self.chol.slice_range(j.., j..));
// update the jth row
let top_left_corner = self.chol.slice_range(..j,..j);
let col_j = col[j];
let (mut new_rowj_adjoint, mut new_colj) = col.rows_range_pair_mut(..j, j + 1..);
assert!(
top_left_corner.solve_lower_triangular_mut(&mut new_rowj_adjoint),
"Cholesky::insert_column : Unable to solve lower triangular system!"
);
new_rowj_adjoint.adjoint_to(&mut chol.slice_range_mut(j,..j));
// update the center element
let center_element = N::sqrt(col_j - N::from_real(new_rowj_adjoint.norm_squared()));
chol[(j, j)] = center_element;
// update the jth column
let bottom_left_corner = self.chol.slice_range(j..,..j);
// new_colj = (col_jplus - bottom_left_corner * new_rowj.adjoint()) / center_element;
new_colj.gemm(
-N::one() / center_element,
&bottom_left_corner,
&new_rowj_adjoint,
N::one() / center_element,
);
chol.slice_range_mut(j + 1.., j).copy_from(&new_colj);
// update the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j + 1.., j + 1..);
Self::xx_rank_one_update(
&mut bottom_right_corner,
&mut new_colj,
-N::RealField::one(),
);
Cholesky { chol }
}
/// Updates the decomposition such that we get the decomposition of the factored matrix with its `j`th column removed.
/// Since the matrix is square, the `j`th row will also be removed.
pub fn remove_column(&self, j: usize) -> Cholesky<N, DimDiff<D, U1>>
where
D: DimSub<U1>,
DefaultAllocator: Allocator<N, DimDiff<D, U1>, DimDiff<D, U1>> + Allocator<N, D>,
{
let n = self.chol.nrows();
assert!(n > 0, "The matrix needs at least one column.");
assert!(j < n, "j needs to be within the bound of the matrix.");
// loads the data into a new matrix except for the jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.sub(U1),
self.chol.data.shape().1.sub(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j..)
.copy_from(&self.chol.slice_range(..j, j + 1..));
chol.slice_range_mut(j..,..j)
.copy_from(&self.chol.slice_range(j + 1..,..j));
chol.slice_range_mut(j.., j..)
.copy_from(&self.chol.slice_range(j + 1.., j + 1..));
// updates the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j.., j..);
let mut workspace = self.chol.column(j).clone_owned();
let mut old_colj = workspace.rows_range_mut(j + 1..);
Self::xx_rank_one_update(&mut bottom_right_corner, &mut old_colj, N::RealField::one());
Cholesky { chol }
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `x`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (x * x.adjoint())`.
///
/// This helper method is called by `rank_one_update` but also `insert_column` and `remove_column`
/// where it is used on a square slice of the decomposition
fn xx_rank_one_update<Dm, Sm, Rx, Sx>(
chol: &mut Matrix<N, Dm, Dm, Sm>,
x: &mut Vector<N, Rx, Sx>,
sigma: N::RealField,
) where
//N: ComplexField,
Dm: Dim,
Rx: Dim,
Sm: StorageMut<N, Dm, Dm>,
Sx: StorageMut<N, Rx, U1>,
{
// heavily inspired by Eigen's `llt_rank_update_lower` implementation https://eigen.tuxfamily.org/dox/LLT_8h_source.html
let n = x.nrows();
assert_eq!(
n,
chol.nrows(),
"The input vector must be of the same size as the factorized matrix."
);
let mut beta = crate::one::<N::RealField>();
for j in 0..n {
// updates the diagonal
let diag = N::real(unsafe { *chol.get_unchecked((j, j)) });
let diag2 = diag * diag;
let xj = unsafe { *x.get_unchecked(j) };
let sigma_xj2 = sigma * N::modulus_squared(xj);
let gamma = diag2 * beta + sigma_xj2;
let new_diag = (diag2 + sigma_xj2 / beta).sqrt();
unsafe { *chol.get_unchecked_mut((j, j)) = N::from_real(new_diag) };
beta += sigma_xj2 / diag2;
// updates the terms of L
let mut xjplus = x.rows_range_mut(j + 1..);
let mut col_j = chol.slice_range_mut(j + 1.., j);
// temp_jplus -= (wj / N::from_real(diag)) * col_j;
xjplus.axpy(-xj / N::from_real(diag), &col_j, N::one());
if gamma!= crate::zero::<N::RealField>() {
// col_j = N::from_real(nljj / diag) * col_j + (N::from_real(nljj * sigma / gamma) * N::conjugate(wj)) * temp_jplus;
col_j.axpy(
N::from_real(new_diag * sigma / gamma) * N::conjugate(xj),
&xjplus,
N::from_real(new_diag / diag),
);
}
}
}
}
impl<N: ComplexField, D: DimSub<Dynamic>, S: Storage<N, D, D>> SquareMatrix<N, D, S>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of this matrix. | /// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn cholesky(self) -> Option<Cholesky<N, D>> {
Cholesky::new(self.into_owned())
}
} | /// | random_line_split |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimension::{Dim, DimAdd, DimDiff, DimSub, DimSum, Dynamic, U1};
use crate::storage::{Storage, StorageMut};
/// The Cholesky decomposition of a symmetric-definite-positive matrix.
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(serialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Serialize"))
)]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Deserialize<'de>"))
)]
#[derive(Clone, Debug)]
pub struct Cholesky<N: ComplexField, D: Dim>
where
DefaultAllocator: Allocator<N, D, D>,
{
chol: MatrixN<N, D>,
}
impl<N: ComplexField, D: Dim> Copy for Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
MatrixN<N, D>: Copy,
{
}
impl<N: ComplexField, D: Dim> Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of `matrix`.
///
/// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn new(mut matrix: MatrixN<N, D>) -> Option<Self> {
assert!(matrix.is_square(), "The input matrix must be square.");
let n = matrix.nrows();
for j in 0..n {
for k in 0..j {
let factor = unsafe { -*matrix.get_unchecked((j, k)) };
let (mut col_j, col_k) = matrix.columns_range_pair_mut(j, k);
let mut col_j = col_j.rows_range_mut(j..);
let col_k = col_k.rows_range(j..);
col_j.axpy(factor.conjugate(), &col_k, N::one());
}
let diag = unsafe { *matrix.get_unchecked((j, j)) };
if!diag.is_zero() |
// The diagonal element is either zero or its square root could not
// be taken (e.g. for negative real numbers).
return None;
}
Some(Cholesky { chol: matrix })
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// upper-triangular part filled with zeros.
pub fn unpack(mut self) -> MatrixN<N, D> {
self.chol.fill_upper_triangle(N::zero(), 1);
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// The values of the strict upper-triangular part are garbage and should be ignored by further
/// computations.
pub fn unpack_dirty(self) -> MatrixN<N, D> {
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// uppen-triangular part filled with zeros.
pub fn l(&self) -> MatrixN<N, D> {
self.chol.lower_triangle()
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// This is an allocation-less version of `self.l()`. The values of the strict upper-triangular
/// part are garbage and should be ignored by further computations.
pub fn l_dirty(&self) -> &MatrixN<N, D> {
&self.chol
}
/// Solves the system `self * x = b` where `self` is the decomposed matrix and `x` the unknown.
///
/// The result is stored on `b`.
pub fn solve_mut<R2: Dim, C2: Dim, S2>(&self, b: &mut Matrix<N, R2, C2, S2>)
where
S2: StorageMut<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
let _ = self.chol.solve_lower_triangular_mut(b);
let _ = self.chol.ad_solve_lower_triangular_mut(b);
}
/// Returns the solution of the system `self * x = b` where `self` is the decomposed matrix and
/// `x` the unknown.
pub fn solve<R2: Dim, C2: Dim, S2>(&self, b: &Matrix<N, R2, C2, S2>) -> MatrixMN<N, R2, C2>
where
S2: Storage<N, R2, C2>,
DefaultAllocator: Allocator<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
let mut res = b.clone_owned();
self.solve_mut(&mut res);
res
}
/// Computes the inverse of the decomposed matrix.
pub fn inverse(&self) -> MatrixN<N, D> {
let shape = self.chol.data.shape();
let mut res = MatrixN::identity_generic(shape.0, shape.1);
self.solve_mut(&mut res);
res
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `v`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (v * v.adjoint())`.
#[inline]
pub fn rank_one_update<R2: Dim, S2>(&mut self, x: &Vector<N, R2, S2>, sigma: N::RealField)
where
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, R2, U1>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
Self::xx_rank_one_update(&mut self.chol, &mut x.clone_owned(), sigma)
}
/// Updates the decomposition such that we get the decomposition of a matrix with the given column `col` in the `j`th position.
/// Since the matrix is square, an identical row will be added in the `j`th row.
pub fn insert_column<R2, S2>(
&self,
j: usize,
col: Vector<N, R2, S2>,
) -> Cholesky<N, DimSum<D, U1>>
where
D: DimAdd<U1>,
R2: Dim,
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, DimSum<D, U1>, DimSum<D, U1>> + Allocator<N, R2>,
ShapeConstraint: SameNumberOfRows<R2, DimSum<D, U1>>,
{
let mut col = col.into_owned();
// for an explanation of the formulas, see https://en.wikipedia.org/wiki/Cholesky_decomposition#Updating_the_decomposition
let n = col.nrows();
assert_eq!(
n,
self.chol.nrows() + 1,
"The new column must have the size of the factored matrix plus one."
);
assert!(j < n, "j needs to be within the bound of the new matrix.");
// loads the data into a new matrix with an additional jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.add(U1),
self.chol.data.shape().1.add(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j + 1..)
.copy_from(&self.chol.slice_range(..j, j..));
chol.slice_range_mut(j + 1..,..j)
.copy_from(&self.chol.slice_range(j..,..j));
chol.slice_range_mut(j + 1.., j + 1..)
.copy_from(&self.chol.slice_range(j.., j..));
// update the jth row
let top_left_corner = self.chol.slice_range(..j,..j);
let col_j = col[j];
let (mut new_rowj_adjoint, mut new_colj) = col.rows_range_pair_mut(..j, j + 1..);
assert!(
top_left_corner.solve_lower_triangular_mut(&mut new_rowj_adjoint),
"Cholesky::insert_column : Unable to solve lower triangular system!"
);
new_rowj_adjoint.adjoint_to(&mut chol.slice_range_mut(j,..j));
// update the center element
let center_element = N::sqrt(col_j - N::from_real(new_rowj_adjoint.norm_squared()));
chol[(j, j)] = center_element;
// update the jth column
let bottom_left_corner = self.chol.slice_range(j..,..j);
// new_colj = (col_jplus - bottom_left_corner * new_rowj.adjoint()) / center_element;
new_colj.gemm(
-N::one() / center_element,
&bottom_left_corner,
&new_rowj_adjoint,
N::one() / center_element,
);
chol.slice_range_mut(j + 1.., j).copy_from(&new_colj);
// update the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j + 1.., j + 1..);
Self::xx_rank_one_update(
&mut bottom_right_corner,
&mut new_colj,
-N::RealField::one(),
);
Cholesky { chol }
}
/// Updates the decomposition such that we get the decomposition of the factored matrix with its `j`th column removed.
/// Since the matrix is square, the `j`th row will also be removed.
pub fn remove_column(&self, j: usize) -> Cholesky<N, DimDiff<D, U1>>
where
D: DimSub<U1>,
DefaultAllocator: Allocator<N, DimDiff<D, U1>, DimDiff<D, U1>> + Allocator<N, D>,
{
let n = self.chol.nrows();
assert!(n > 0, "The matrix needs at least one column.");
assert!(j < n, "j needs to be within the bound of the matrix.");
// loads the data into a new matrix except for the jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.sub(U1),
self.chol.data.shape().1.sub(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j..)
.copy_from(&self.chol.slice_range(..j, j + 1..));
chol.slice_range_mut(j..,..j)
.copy_from(&self.chol.slice_range(j + 1..,..j));
chol.slice_range_mut(j.., j..)
.copy_from(&self.chol.slice_range(j + 1.., j + 1..));
// updates the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j.., j..);
let mut workspace = self.chol.column(j).clone_owned();
let mut old_colj = workspace.rows_range_mut(j + 1..);
Self::xx_rank_one_update(&mut bottom_right_corner, &mut old_colj, N::RealField::one());
Cholesky { chol }
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `x`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (x * x.adjoint())`.
///
/// This helper method is called by `rank_one_update` but also `insert_column` and `remove_column`
/// where it is used on a square slice of the decomposition
fn xx_rank_one_update<Dm, Sm, Rx, Sx>(
chol: &mut Matrix<N, Dm, Dm, Sm>,
x: &mut Vector<N, Rx, Sx>,
sigma: N::RealField,
) where
//N: ComplexField,
Dm: Dim,
Rx: Dim,
Sm: StorageMut<N, Dm, Dm>,
Sx: StorageMut<N, Rx, U1>,
{
// heavily inspired by Eigen's `llt_rank_update_lower` implementation https://eigen.tuxfamily.org/dox/LLT_8h_source.html
let n = x.nrows();
assert_eq!(
n,
chol.nrows(),
"The input vector must be of the same size as the factorized matrix."
);
let mut beta = crate::one::<N::RealField>();
for j in 0..n {
// updates the diagonal
let diag = N::real(unsafe { *chol.get_unchecked((j, j)) });
let diag2 = diag * diag;
let xj = unsafe { *x.get_unchecked(j) };
let sigma_xj2 = sigma * N::modulus_squared(xj);
let gamma = diag2 * beta + sigma_xj2;
let new_diag = (diag2 + sigma_xj2 / beta).sqrt();
unsafe { *chol.get_unchecked_mut((j, j)) = N::from_real(new_diag) };
beta += sigma_xj2 / diag2;
// updates the terms of L
let mut xjplus = x.rows_range_mut(j + 1..);
let mut col_j = chol.slice_range_mut(j + 1.., j);
// temp_jplus -= (wj / N::from_real(diag)) * col_j;
xjplus.axpy(-xj / N::from_real(diag), &col_j, N::one());
if gamma!= crate::zero::<N::RealField>() {
// col_j = N::from_real(nljj / diag) * col_j + (N::from_real(nljj * sigma / gamma) * N::conjugate(wj)) * temp_jplus;
col_j.axpy(
N::from_real(new_diag * sigma / gamma) * N::conjugate(xj),
&xjplus,
N::from_real(new_diag / diag),
);
}
}
}
}
impl<N: ComplexField, D: DimSub<Dynamic>, S: Storage<N, D, D>> SquareMatrix<N, D, S>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of this matrix.
///
/// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn cholesky(self) -> Option<Cholesky<N, D>> {
Cholesky::new(self.into_owned())
}
}
| {
if let Some(denom) = diag.try_sqrt() {
unsafe {
*matrix.get_unchecked_mut((j, j)) = denom;
}
let mut col = matrix.slice_range_mut(j + 1.., j);
col /= denom;
continue;
}
} | conditional_block |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimension::{Dim, DimAdd, DimDiff, DimSub, DimSum, Dynamic, U1};
use crate::storage::{Storage, StorageMut};
/// The Cholesky decomposition of a symmetric-definite-positive matrix.
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(serialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Serialize"))
)]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Deserialize<'de>"))
)]
#[derive(Clone, Debug)]
pub struct Cholesky<N: ComplexField, D: Dim>
where
DefaultAllocator: Allocator<N, D, D>,
{
chol: MatrixN<N, D>,
}
impl<N: ComplexField, D: Dim> Copy for Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
MatrixN<N, D>: Copy,
{
}
impl<N: ComplexField, D: Dim> Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of `matrix`.
///
/// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn new(mut matrix: MatrixN<N, D>) -> Option<Self> {
assert!(matrix.is_square(), "The input matrix must be square.");
let n = matrix.nrows();
for j in 0..n {
for k in 0..j {
let factor = unsafe { -*matrix.get_unchecked((j, k)) };
let (mut col_j, col_k) = matrix.columns_range_pair_mut(j, k);
let mut col_j = col_j.rows_range_mut(j..);
let col_k = col_k.rows_range(j..);
col_j.axpy(factor.conjugate(), &col_k, N::one());
}
let diag = unsafe { *matrix.get_unchecked((j, j)) };
if!diag.is_zero() {
if let Some(denom) = diag.try_sqrt() {
unsafe {
*matrix.get_unchecked_mut((j, j)) = denom;
}
let mut col = matrix.slice_range_mut(j + 1.., j);
col /= denom;
continue;
}
}
// The diagonal element is either zero or its square root could not
// be taken (e.g. for negative real numbers).
return None;
}
Some(Cholesky { chol: matrix })
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// upper-triangular part filled with zeros.
pub fn unpack(mut self) -> MatrixN<N, D> {
self.chol.fill_upper_triangle(N::zero(), 1);
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// The values of the strict upper-triangular part are garbage and should be ignored by further
/// computations.
pub fn unpack_dirty(self) -> MatrixN<N, D> {
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// uppen-triangular part filled with zeros.
pub fn l(&self) -> MatrixN<N, D> {
self.chol.lower_triangle()
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// This is an allocation-less version of `self.l()`. The values of the strict upper-triangular
/// part are garbage and should be ignored by further computations.
pub fn | (&self) -> &MatrixN<N, D> {
&self.chol
}
/// Solves the system `self * x = b` where `self` is the decomposed matrix and `x` the unknown.
///
/// The result is stored on `b`.
pub fn solve_mut<R2: Dim, C2: Dim, S2>(&self, b: &mut Matrix<N, R2, C2, S2>)
where
S2: StorageMut<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
let _ = self.chol.solve_lower_triangular_mut(b);
let _ = self.chol.ad_solve_lower_triangular_mut(b);
}
/// Returns the solution of the system `self * x = b` where `self` is the decomposed matrix and
/// `x` the unknown.
pub fn solve<R2: Dim, C2: Dim, S2>(&self, b: &Matrix<N, R2, C2, S2>) -> MatrixMN<N, R2, C2>
where
S2: Storage<N, R2, C2>,
DefaultAllocator: Allocator<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
let mut res = b.clone_owned();
self.solve_mut(&mut res);
res
}
/// Computes the inverse of the decomposed matrix.
pub fn inverse(&self) -> MatrixN<N, D> {
let shape = self.chol.data.shape();
let mut res = MatrixN::identity_generic(shape.0, shape.1);
self.solve_mut(&mut res);
res
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `v`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (v * v.adjoint())`.
#[inline]
pub fn rank_one_update<R2: Dim, S2>(&mut self, x: &Vector<N, R2, S2>, sigma: N::RealField)
where
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, R2, U1>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
Self::xx_rank_one_update(&mut self.chol, &mut x.clone_owned(), sigma)
}
/// Updates the decomposition such that we get the decomposition of a matrix with the given column `col` in the `j`th position.
/// Since the matrix is square, an identical row will be added in the `j`th row.
pub fn insert_column<R2, S2>(
&self,
j: usize,
col: Vector<N, R2, S2>,
) -> Cholesky<N, DimSum<D, U1>>
where
D: DimAdd<U1>,
R2: Dim,
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, DimSum<D, U1>, DimSum<D, U1>> + Allocator<N, R2>,
ShapeConstraint: SameNumberOfRows<R2, DimSum<D, U1>>,
{
let mut col = col.into_owned();
// for an explanation of the formulas, see https://en.wikipedia.org/wiki/Cholesky_decomposition#Updating_the_decomposition
let n = col.nrows();
assert_eq!(
n,
self.chol.nrows() + 1,
"The new column must have the size of the factored matrix plus one."
);
assert!(j < n, "j needs to be within the bound of the new matrix.");
// loads the data into a new matrix with an additional jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.add(U1),
self.chol.data.shape().1.add(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j + 1..)
.copy_from(&self.chol.slice_range(..j, j..));
chol.slice_range_mut(j + 1..,..j)
.copy_from(&self.chol.slice_range(j..,..j));
chol.slice_range_mut(j + 1.., j + 1..)
.copy_from(&self.chol.slice_range(j.., j..));
// update the jth row
let top_left_corner = self.chol.slice_range(..j,..j);
let col_j = col[j];
let (mut new_rowj_adjoint, mut new_colj) = col.rows_range_pair_mut(..j, j + 1..);
assert!(
top_left_corner.solve_lower_triangular_mut(&mut new_rowj_adjoint),
"Cholesky::insert_column : Unable to solve lower triangular system!"
);
new_rowj_adjoint.adjoint_to(&mut chol.slice_range_mut(j,..j));
// update the center element
let center_element = N::sqrt(col_j - N::from_real(new_rowj_adjoint.norm_squared()));
chol[(j, j)] = center_element;
// update the jth column
let bottom_left_corner = self.chol.slice_range(j..,..j);
// new_colj = (col_jplus - bottom_left_corner * new_rowj.adjoint()) / center_element;
new_colj.gemm(
-N::one() / center_element,
&bottom_left_corner,
&new_rowj_adjoint,
N::one() / center_element,
);
chol.slice_range_mut(j + 1.., j).copy_from(&new_colj);
// update the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j + 1.., j + 1..);
Self::xx_rank_one_update(
&mut bottom_right_corner,
&mut new_colj,
-N::RealField::one(),
);
Cholesky { chol }
}
/// Updates the decomposition such that we get the decomposition of the factored matrix with its `j`th column removed.
/// Since the matrix is square, the `j`th row will also be removed.
pub fn remove_column(&self, j: usize) -> Cholesky<N, DimDiff<D, U1>>
where
D: DimSub<U1>,
DefaultAllocator: Allocator<N, DimDiff<D, U1>, DimDiff<D, U1>> + Allocator<N, D>,
{
let n = self.chol.nrows();
assert!(n > 0, "The matrix needs at least one column.");
assert!(j < n, "j needs to be within the bound of the matrix.");
// loads the data into a new matrix except for the jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.sub(U1),
self.chol.data.shape().1.sub(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j..)
.copy_from(&self.chol.slice_range(..j, j + 1..));
chol.slice_range_mut(j..,..j)
.copy_from(&self.chol.slice_range(j + 1..,..j));
chol.slice_range_mut(j.., j..)
.copy_from(&self.chol.slice_range(j + 1.., j + 1..));
// updates the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j.., j..);
let mut workspace = self.chol.column(j).clone_owned();
let mut old_colj = workspace.rows_range_mut(j + 1..);
Self::xx_rank_one_update(&mut bottom_right_corner, &mut old_colj, N::RealField::one());
Cholesky { chol }
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `x`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (x * x.adjoint())`.
///
/// This helper method is called by `rank_one_update` but also `insert_column` and `remove_column`
/// where it is used on a square slice of the decomposition
fn xx_rank_one_update<Dm, Sm, Rx, Sx>(
chol: &mut Matrix<N, Dm, Dm, Sm>,
x: &mut Vector<N, Rx, Sx>,
sigma: N::RealField,
) where
//N: ComplexField,
Dm: Dim,
Rx: Dim,
Sm: StorageMut<N, Dm, Dm>,
Sx: StorageMut<N, Rx, U1>,
{
// heavily inspired by Eigen's `llt_rank_update_lower` implementation https://eigen.tuxfamily.org/dox/LLT_8h_source.html
let n = x.nrows();
assert_eq!(
n,
chol.nrows(),
"The input vector must be of the same size as the factorized matrix."
);
let mut beta = crate::one::<N::RealField>();
for j in 0..n {
// updates the diagonal
let diag = N::real(unsafe { *chol.get_unchecked((j, j)) });
let diag2 = diag * diag;
let xj = unsafe { *x.get_unchecked(j) };
let sigma_xj2 = sigma * N::modulus_squared(xj);
let gamma = diag2 * beta + sigma_xj2;
let new_diag = (diag2 + sigma_xj2 / beta).sqrt();
unsafe { *chol.get_unchecked_mut((j, j)) = N::from_real(new_diag) };
beta += sigma_xj2 / diag2;
// updates the terms of L
let mut xjplus = x.rows_range_mut(j + 1..);
let mut col_j = chol.slice_range_mut(j + 1.., j);
// temp_jplus -= (wj / N::from_real(diag)) * col_j;
xjplus.axpy(-xj / N::from_real(diag), &col_j, N::one());
if gamma!= crate::zero::<N::RealField>() {
// col_j = N::from_real(nljj / diag) * col_j + (N::from_real(nljj * sigma / gamma) * N::conjugate(wj)) * temp_jplus;
col_j.axpy(
N::from_real(new_diag * sigma / gamma) * N::conjugate(xj),
&xjplus,
N::from_real(new_diag / diag),
);
}
}
}
}
impl<N: ComplexField, D: DimSub<Dynamic>, S: Storage<N, D, D>> SquareMatrix<N, D, S>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of this matrix.
///
/// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn cholesky(self) -> Option<Cholesky<N, D>> {
Cholesky::new(self.into_owned())
}
}
| l_dirty | identifier_name |
cholesky.rs | #[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
use num::One;
use simba::scalar::ComplexField;
use crate::allocator::Allocator;
use crate::base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, SquareMatrix, Vector};
use crate::constraint::{SameNumberOfRows, ShapeConstraint};
use crate::dimension::{Dim, DimAdd, DimDiff, DimSub, DimSum, Dynamic, U1};
use crate::storage::{Storage, StorageMut};
/// The Cholesky decomposition of a symmetric-definite-positive matrix.
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(serialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Serialize"))
)]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>,
MatrixN<N, D>: Deserialize<'de>"))
)]
#[derive(Clone, Debug)]
pub struct Cholesky<N: ComplexField, D: Dim>
where
DefaultAllocator: Allocator<N, D, D>,
{
chol: MatrixN<N, D>,
}
impl<N: ComplexField, D: Dim> Copy for Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
MatrixN<N, D>: Copy,
{
}
impl<N: ComplexField, D: Dim> Cholesky<N, D>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of `matrix`.
///
/// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn new(mut matrix: MatrixN<N, D>) -> Option<Self> {
assert!(matrix.is_square(), "The input matrix must be square.");
let n = matrix.nrows();
for j in 0..n {
for k in 0..j {
let factor = unsafe { -*matrix.get_unchecked((j, k)) };
let (mut col_j, col_k) = matrix.columns_range_pair_mut(j, k);
let mut col_j = col_j.rows_range_mut(j..);
let col_k = col_k.rows_range(j..);
col_j.axpy(factor.conjugate(), &col_k, N::one());
}
let diag = unsafe { *matrix.get_unchecked((j, j)) };
if!diag.is_zero() {
if let Some(denom) = diag.try_sqrt() {
unsafe {
*matrix.get_unchecked_mut((j, j)) = denom;
}
let mut col = matrix.slice_range_mut(j + 1.., j);
col /= denom;
continue;
}
}
// The diagonal element is either zero or its square root could not
// be taken (e.g. for negative real numbers).
return None;
}
Some(Cholesky { chol: matrix })
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// upper-triangular part filled with zeros.
pub fn unpack(mut self) -> MatrixN<N, D> {
self.chol.fill_upper_triangle(N::zero(), 1);
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// The values of the strict upper-triangular part are garbage and should be ignored by further
/// computations.
pub fn unpack_dirty(self) -> MatrixN<N, D> {
self.chol
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition with its strictly
/// uppen-triangular part filled with zeros.
pub fn l(&self) -> MatrixN<N, D> {
self.chol.lower_triangle()
}
/// Retrieves the lower-triangular factor of the Cholesky decomposition, without zeroing-out
/// its strict upper-triangular part.
///
/// This is an allocation-less version of `self.l()`. The values of the strict upper-triangular
/// part are garbage and should be ignored by further computations.
pub fn l_dirty(&self) -> &MatrixN<N, D> {
&self.chol
}
/// Solves the system `self * x = b` where `self` is the decomposed matrix and `x` the unknown.
///
/// The result is stored on `b`.
pub fn solve_mut<R2: Dim, C2: Dim, S2>(&self, b: &mut Matrix<N, R2, C2, S2>)
where
S2: StorageMut<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
let _ = self.chol.solve_lower_triangular_mut(b);
let _ = self.chol.ad_solve_lower_triangular_mut(b);
}
/// Returns the solution of the system `self * x = b` where `self` is the decomposed matrix and
/// `x` the unknown.
pub fn solve<R2: Dim, C2: Dim, S2>(&self, b: &Matrix<N, R2, C2, S2>) -> MatrixMN<N, R2, C2>
where
S2: Storage<N, R2, C2>,
DefaultAllocator: Allocator<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R2, D>,
|
/// Computes the inverse of the decomposed matrix.
pub fn inverse(&self) -> MatrixN<N, D> {
let shape = self.chol.data.shape();
let mut res = MatrixN::identity_generic(shape.0, shape.1);
self.solve_mut(&mut res);
res
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `v`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (v * v.adjoint())`.
#[inline]
pub fn rank_one_update<R2: Dim, S2>(&mut self, x: &Vector<N, R2, S2>, sigma: N::RealField)
where
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, R2, U1>,
ShapeConstraint: SameNumberOfRows<R2, D>,
{
Self::xx_rank_one_update(&mut self.chol, &mut x.clone_owned(), sigma)
}
/// Updates the decomposition such that we get the decomposition of a matrix with the given column `col` in the `j`th position.
/// Since the matrix is square, an identical row will be added in the `j`th row.
pub fn insert_column<R2, S2>(
&self,
j: usize,
col: Vector<N, R2, S2>,
) -> Cholesky<N, DimSum<D, U1>>
where
D: DimAdd<U1>,
R2: Dim,
S2: Storage<N, R2, U1>,
DefaultAllocator: Allocator<N, DimSum<D, U1>, DimSum<D, U1>> + Allocator<N, R2>,
ShapeConstraint: SameNumberOfRows<R2, DimSum<D, U1>>,
{
let mut col = col.into_owned();
// for an explanation of the formulas, see https://en.wikipedia.org/wiki/Cholesky_decomposition#Updating_the_decomposition
let n = col.nrows();
assert_eq!(
n,
self.chol.nrows() + 1,
"The new column must have the size of the factored matrix plus one."
);
assert!(j < n, "j needs to be within the bound of the new matrix.");
// loads the data into a new matrix with an additional jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.add(U1),
self.chol.data.shape().1.add(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j + 1..)
.copy_from(&self.chol.slice_range(..j, j..));
chol.slice_range_mut(j + 1..,..j)
.copy_from(&self.chol.slice_range(j..,..j));
chol.slice_range_mut(j + 1.., j + 1..)
.copy_from(&self.chol.slice_range(j.., j..));
// update the jth row
let top_left_corner = self.chol.slice_range(..j,..j);
let col_j = col[j];
let (mut new_rowj_adjoint, mut new_colj) = col.rows_range_pair_mut(..j, j + 1..);
assert!(
top_left_corner.solve_lower_triangular_mut(&mut new_rowj_adjoint),
"Cholesky::insert_column : Unable to solve lower triangular system!"
);
new_rowj_adjoint.adjoint_to(&mut chol.slice_range_mut(j,..j));
// update the center element
let center_element = N::sqrt(col_j - N::from_real(new_rowj_adjoint.norm_squared()));
chol[(j, j)] = center_element;
// update the jth column
let bottom_left_corner = self.chol.slice_range(j..,..j);
// new_colj = (col_jplus - bottom_left_corner * new_rowj.adjoint()) / center_element;
new_colj.gemm(
-N::one() / center_element,
&bottom_left_corner,
&new_rowj_adjoint,
N::one() / center_element,
);
chol.slice_range_mut(j + 1.., j).copy_from(&new_colj);
// update the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j + 1.., j + 1..);
Self::xx_rank_one_update(
&mut bottom_right_corner,
&mut new_colj,
-N::RealField::one(),
);
Cholesky { chol }
}
/// Updates the decomposition such that we get the decomposition of the factored matrix with its `j`th column removed.
/// Since the matrix is square, the `j`th row will also be removed.
pub fn remove_column(&self, j: usize) -> Cholesky<N, DimDiff<D, U1>>
where
D: DimSub<U1>,
DefaultAllocator: Allocator<N, DimDiff<D, U1>, DimDiff<D, U1>> + Allocator<N, D>,
{
let n = self.chol.nrows();
assert!(n > 0, "The matrix needs at least one column.");
assert!(j < n, "j needs to be within the bound of the matrix.");
// loads the data into a new matrix except for the jth row/column
let mut chol = unsafe {
Matrix::new_uninitialized_generic(
self.chol.data.shape().0.sub(U1),
self.chol.data.shape().1.sub(U1),
)
};
chol.slice_range_mut(..j,..j)
.copy_from(&self.chol.slice_range(..j,..j));
chol.slice_range_mut(..j, j..)
.copy_from(&self.chol.slice_range(..j, j + 1..));
chol.slice_range_mut(j..,..j)
.copy_from(&self.chol.slice_range(j + 1..,..j));
chol.slice_range_mut(j.., j..)
.copy_from(&self.chol.slice_range(j + 1.., j + 1..));
// updates the bottom right corner
let mut bottom_right_corner = chol.slice_range_mut(j.., j..);
let mut workspace = self.chol.column(j).clone_owned();
let mut old_colj = workspace.rows_range_mut(j + 1..);
Self::xx_rank_one_update(&mut bottom_right_corner, &mut old_colj, N::RealField::one());
Cholesky { chol }
}
/// Given the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `x`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (x * x.adjoint())`.
///
/// This helper method is called by `rank_one_update` but also `insert_column` and `remove_column`
/// where it is used on a square slice of the decomposition
fn xx_rank_one_update<Dm, Sm, Rx, Sx>(
chol: &mut Matrix<N, Dm, Dm, Sm>,
x: &mut Vector<N, Rx, Sx>,
sigma: N::RealField,
) where
//N: ComplexField,
Dm: Dim,
Rx: Dim,
Sm: StorageMut<N, Dm, Dm>,
Sx: StorageMut<N, Rx, U1>,
{
// heavily inspired by Eigen's `llt_rank_update_lower` implementation https://eigen.tuxfamily.org/dox/LLT_8h_source.html
let n = x.nrows();
assert_eq!(
n,
chol.nrows(),
"The input vector must be of the same size as the factorized matrix."
);
let mut beta = crate::one::<N::RealField>();
for j in 0..n {
// updates the diagonal
let diag = N::real(unsafe { *chol.get_unchecked((j, j)) });
let diag2 = diag * diag;
let xj = unsafe { *x.get_unchecked(j) };
let sigma_xj2 = sigma * N::modulus_squared(xj);
let gamma = diag2 * beta + sigma_xj2;
let new_diag = (diag2 + sigma_xj2 / beta).sqrt();
unsafe { *chol.get_unchecked_mut((j, j)) = N::from_real(new_diag) };
beta += sigma_xj2 / diag2;
// updates the terms of L
let mut xjplus = x.rows_range_mut(j + 1..);
let mut col_j = chol.slice_range_mut(j + 1.., j);
// temp_jplus -= (wj / N::from_real(diag)) * col_j;
xjplus.axpy(-xj / N::from_real(diag), &col_j, N::one());
if gamma!= crate::zero::<N::RealField>() {
// col_j = N::from_real(nljj / diag) * col_j + (N::from_real(nljj * sigma / gamma) * N::conjugate(wj)) * temp_jplus;
col_j.axpy(
N::from_real(new_diag * sigma / gamma) * N::conjugate(xj),
&xjplus,
N::from_real(new_diag / diag),
);
}
}
}
}
impl<N: ComplexField, D: DimSub<Dynamic>, S: Storage<N, D, D>> SquareMatrix<N, D, S>
where
DefaultAllocator: Allocator<N, D, D>,
{
/// Attempts to compute the Cholesky decomposition of this matrix.
///
/// Returns `None` if the input matrix is not definite-positive. The input matrix is assumed
/// to be symmetric and only the lower-triangular part is read.
pub fn cholesky(self) -> Option<Cholesky<N, D>> {
Cholesky::new(self.into_owned())
}
}
| {
let mut res = b.clone_owned();
self.solve_mut(&mut res);
res
} | identifier_body |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket;
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config;
fn main() {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount("/lodestone", routes![lodestone::rss, lodestone::jsonfeed])
.catch(errors![web::core::not_found])
.launch();
}
fn | () -> Config {
use rocket::config::*;
let env = Environment::active().unwrap();
let mut config = Config::build(env);
config = config.address("0.0.0.0");
let port = load_var("PORT", "8080");
if let Some(port) = port.parse().ok() {
config = config.port(port);
}
config.finalize().unwrap()
}
| config | identifier_name |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket;
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config;
fn main() |
fn config() -> Config {
use rocket::config::*;
let env = Environment::active().unwrap();
let mut config = Config::build(env);
config = config.address("0.0.0.0");
let port = load_var("PORT", "8080");
if let Some(port) = port.parse().ok() {
config = config.port(port);
}
config.finalize().unwrap()
}
| {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount("/lodestone", routes![lodestone::rss, lodestone::jsonfeed])
.catch(errors![web::core::not_found])
.launch();
} | identifier_body |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket;
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config;
fn main() {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount("/lodestone", routes![lodestone::rss, lodestone::jsonfeed])
.catch(errors![web::core::not_found])
.launch();
}
fn config() -> Config {
use rocket::config::*;
let env = Environment::active().unwrap();
let mut config = Config::build(env);
config = config.address("0.0.0.0");
let port = load_var("PORT", "8080");
if let Some(port) = port.parse().ok() |
config.finalize().unwrap()
}
| {
config = config.port(port);
} | conditional_block |
auracite_web.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate auracite;
extern crate rocket; |
fn main() {
rocket::custom(config(), true)
.mount("/", routes![web::root::web_root, web::assets::static_asset])
.mount("/lodestone", routes![lodestone::rss, lodestone::jsonfeed])
.catch(errors![web::core::not_found])
.launch();
}
fn config() -> Config {
use rocket::config::*;
let env = Environment::active().unwrap();
let mut config = Config::build(env);
config = config.address("0.0.0.0");
let port = load_var("PORT", "8080");
if let Some(port) = port.parse().ok() {
config = config.port(port);
}
config.finalize().unwrap()
} |
use auracite::{web, lodestone};
use auracite::env::load_var;
use rocket::config::Config; | random_line_split |
react_flight_codegen_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<569f1efa26994d3ed3c24325d2914203>>
*/
mod react_flight_codegen; | fn flight_invalid() {
let input = include_str!("react_flight_codegen/fixtures/flight.invalid.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight.invalid.expected");
test_fixture(transform_fixture, "flight.invalid.graphql", "react_flight_codegen/fixtures/flight.invalid.expected", input, expected);
}
#[test]
fn flight_props() {
let input = include_str!("react_flight_codegen/fixtures/flight-props.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight-props.expected");
test_fixture(transform_fixture, "flight-props.graphql", "react_flight_codegen/fixtures/flight-props.expected", input, expected);
} |
use react_flight_codegen::transform_fixture;
use fixture_tests::test_fixture;
#[test] | random_line_split |
react_flight_codegen_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<569f1efa26994d3ed3c24325d2914203>>
*/
mod react_flight_codegen;
use react_flight_codegen::transform_fixture;
use fixture_tests::test_fixture;
#[test]
fn flight_invalid() {
let input = include_str!("react_flight_codegen/fixtures/flight.invalid.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight.invalid.expected");
test_fixture(transform_fixture, "flight.invalid.graphql", "react_flight_codegen/fixtures/flight.invalid.expected", input, expected);
}
#[test]
fn | () {
let input = include_str!("react_flight_codegen/fixtures/flight-props.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight-props.expected");
test_fixture(transform_fixture, "flight-props.graphql", "react_flight_codegen/fixtures/flight-props.expected", input, expected);
}
| flight_props | identifier_name |
react_flight_codegen_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<569f1efa26994d3ed3c24325d2914203>>
*/
mod react_flight_codegen;
use react_flight_codegen::transform_fixture;
use fixture_tests::test_fixture;
#[test]
fn flight_invalid() |
#[test]
fn flight_props() {
let input = include_str!("react_flight_codegen/fixtures/flight-props.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight-props.expected");
test_fixture(transform_fixture, "flight-props.graphql", "react_flight_codegen/fixtures/flight-props.expected", input, expected);
}
| {
let input = include_str!("react_flight_codegen/fixtures/flight.invalid.graphql");
let expected = include_str!("react_flight_codegen/fixtures/flight.invalid.expected");
test_fixture(transform_fixture, "flight.invalid.graphql", "react_flight_codegen/fixtures/flight.invalid.expected", input, expected);
} | identifier_body |
htmloptionelement.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::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::InheritTypes::{CharacterDataCast, ElementCast, HTMLElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{HTMLOptionElementDerived};
use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived};
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::characterdata::CharacterData;
use dom::document::Document;
use dom::element::{AttributeHandlers, Element, HTMLOptionElementTypeId};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId};
use dom::virtualmethods::VirtualMethods;
use servo_util::str::{DOMString, split_html_space_chars};
use string_cache::Atom;
#[dom_struct]
pub struct HTMLOptionElement {
htmlelement: HTMLElement
}
impl HTMLOptionElementDerived for EventTarget {
fn is_htmloptionelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId))
}
}
impl HTMLOptionElement {
fn | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement {
HTMLOptionElement {
htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptionElement> {
let element = HTMLOptionElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap)
}
}
fn collect_text(node: &JSRef<Node>, value: &mut DOMString) {
let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap();
let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script";
let html_script = node.is_htmlscriptelement();
if svg_script || html_script {
return;
} else {
for child in node.children() {
if child.is_text() {
let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(child).unwrap();
value.push_str(characterdata.Data().as_slice());
} else {
collect_text(&child, value);
}
}
}
}
impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> {
// http://www.whatwg.org/html/#dom-option-disabled
make_bool_getter!(Disabled)
// http://www.whatwg.org/html/#dom-option-disabled
fn SetDisabled(self, disabled: bool) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_bool_attribute(&atom!("disabled"), disabled)
}
// http://www.whatwg.org/html/#dom-option-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
let mut content = String::new();
collect_text(&node, &mut content);
let v: Vec<&str> = split_html_space_chars(content.as_slice()).collect();
v.connect(" ")
}
// http://www.whatwg.org/html/#dom-option-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLOptionElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.set_disabled_state(true);
node.set_enabled_state(false);
},
_ => ()
}
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.set_disabled_state(false);
node.set_enabled_state(true);
node.check_parent_disabled_state_for_option();
},
_ => ()
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.check_parent_disabled_state_for_option();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.unbind_from_tree(tree_in_doc),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.parent_node().is_some() {
node.check_parent_disabled_state_for_option();
} else {
node.check_disabled_attribute();
}
}
}
impl Reflectable for HTMLOptionElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| new_inherited | identifier_name |
htmloptionelement.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::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::InheritTypes::{CharacterDataCast, ElementCast, HTMLElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{HTMLOptionElementDerived};
use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived};
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::characterdata::CharacterData;
use dom::document::Document;
use dom::element::{AttributeHandlers, Element, HTMLOptionElementTypeId};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId};
use dom::virtualmethods::VirtualMethods;
use servo_util::str::{DOMString, split_html_space_chars};
use string_cache::Atom;
#[dom_struct]
pub struct HTMLOptionElement {
htmlelement: HTMLElement
}
impl HTMLOptionElementDerived for EventTarget {
fn is_htmloptionelement(&self) -> bool |
}
impl HTMLOptionElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement {
HTMLOptionElement {
htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptionElement> {
let element = HTMLOptionElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap)
}
}
fn collect_text(node: &JSRef<Node>, value: &mut DOMString) {
let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap();
let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script";
let html_script = node.is_htmlscriptelement();
if svg_script || html_script {
return;
} else {
for child in node.children() {
if child.is_text() {
let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(child).unwrap();
value.push_str(characterdata.Data().as_slice());
} else {
collect_text(&child, value);
}
}
}
}
impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> {
// http://www.whatwg.org/html/#dom-option-disabled
make_bool_getter!(Disabled)
// http://www.whatwg.org/html/#dom-option-disabled
fn SetDisabled(self, disabled: bool) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_bool_attribute(&atom!("disabled"), disabled)
}
// http://www.whatwg.org/html/#dom-option-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
let mut content = String::new();
collect_text(&node, &mut content);
let v: Vec<&str> = split_html_space_chars(content.as_slice()).collect();
v.connect(" ")
}
// http://www.whatwg.org/html/#dom-option-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLOptionElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.set_disabled_state(true);
node.set_enabled_state(false);
},
_ => ()
}
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.set_disabled_state(false);
node.set_enabled_state(true);
node.check_parent_disabled_state_for_option();
},
_ => ()
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.check_parent_disabled_state_for_option();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.unbind_from_tree(tree_in_doc),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.parent_node().is_some() {
node.check_parent_disabled_state_for_option();
} else {
node.check_disabled_attribute();
}
}
}
impl Reflectable for HTMLOptionElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId))
} | identifier_body |
htmloptionelement.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::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::InheritTypes::{CharacterDataCast, ElementCast, HTMLElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{HTMLOptionElementDerived};
use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived};
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::characterdata::CharacterData;
use dom::document::Document;
use dom::element::{AttributeHandlers, Element, HTMLOptionElementTypeId};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId};
use dom::virtualmethods::VirtualMethods;
use servo_util::str::{DOMString, split_html_space_chars};
use string_cache::Atom;
#[dom_struct]
pub struct HTMLOptionElement {
htmlelement: HTMLElement
}
impl HTMLOptionElementDerived for EventTarget {
fn is_htmloptionelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId))
}
}
impl HTMLOptionElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement {
HTMLOptionElement {
htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptionElement> {
let element = HTMLOptionElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap)
}
}
fn collect_text(node: &JSRef<Node>, value: &mut DOMString) {
let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap();
let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script";
let html_script = node.is_htmlscriptelement();
if svg_script || html_script {
return;
} else {
for child in node.children() {
if child.is_text() {
let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(child).unwrap();
value.push_str(characterdata.Data().as_slice());
} else {
collect_text(&child, value);
}
}
}
}
impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> {
// http://www.whatwg.org/html/#dom-option-disabled
make_bool_getter!(Disabled) | let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_bool_attribute(&atom!("disabled"), disabled)
}
// http://www.whatwg.org/html/#dom-option-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
let mut content = String::new();
collect_text(&node, &mut content);
let v: Vec<&str> = split_html_space_chars(content.as_slice()).collect();
v.connect(" ")
}
// http://www.whatwg.org/html/#dom-option-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLOptionElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.set_disabled_state(true);
node.set_enabled_state(false);
},
_ => ()
}
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.set_disabled_state(false);
node.set_enabled_state(true);
node.check_parent_disabled_state_for_option();
},
_ => ()
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.check_parent_disabled_state_for_option();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.unbind_from_tree(tree_in_doc),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.parent_node().is_some() {
node.check_parent_disabled_state_for_option();
} else {
node.check_disabled_attribute();
}
}
}
impl Reflectable for HTMLOptionElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
} |
// http://www.whatwg.org/html/#dom-option-disabled
fn SetDisabled(self, disabled: bool) { | random_line_split |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig!= 0x525654 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
if ver > FILE_VER {
panic!("ERROR: FILE VERSION IS GREATER THAN PROGRAM VERSION");
}
let frame_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<Voxel>> = Vec::new();
for frame_id in 0..frame_count {
let frame_tag = file.read_u8().unwrap();
if frame_tag!= 0xFF {
panic!("ERROR: FILE CORRUPTED: {}", frame_tag);
}
let voxel_count = file.read_u32::<BigEndian>().unwrap();
let mut frame: Vec<Voxel> = Vec::new();
for voxel_id in 0..voxel_count {
let x = file.read_i8().unwrap();
let y = file.read_i8().unwrap();
let z = file.read_i8().unwrap();
let mut color: (u8, u8, u8) = (0, 0, 0);
color.0 = file.read_u8().unwrap();
color.1 = file.read_u8().unwrap();
color.2 = file.read_u8().unwrap();
frame.push(Voxel {
x: x,
y: y,
z: z,
color: color,
});
}
frames.push(frame);
}
return frames;
}
| if sig!= 0x565054 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
let frame_count = file.read_u8().unwrap();
let color_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<(u8, u8, u8)>> = Vec::new();
for frame_id in 0..frame_count {
if file.read_u8().unwrap()!= 0xFF {
panic!("FILE CORRUPTED");
}
let mut frame: Vec<(u8, u8, u8)> = Vec::new();
for color in 0..color_count {
let r = file.read_u8().unwrap();
let g = file.read_u8().unwrap();
let b = file.read_u8().unwrap();
frame.push((r, g, b));
}
frames.push(frame);
}
return frames;
} | pub fn parse_pallete(file: &mut File) -> Vec<Vec<(u8, u8, u8)>> {
let sig = file.read_u8().unwrap(); | random_line_split |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig!= 0x525654 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
if ver > FILE_VER {
panic!("ERROR: FILE VERSION IS GREATER THAN PROGRAM VERSION");
}
let frame_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<Voxel>> = Vec::new();
for frame_id in 0..frame_count {
let frame_tag = file.read_u8().unwrap();
if frame_tag!= 0xFF |
let voxel_count = file.read_u32::<BigEndian>().unwrap();
let mut frame: Vec<Voxel> = Vec::new();
for voxel_id in 0..voxel_count {
let x = file.read_i8().unwrap();
let y = file.read_i8().unwrap();
let z = file.read_i8().unwrap();
let mut color: (u8, u8, u8) = (0, 0, 0);
color.0 = file.read_u8().unwrap();
color.1 = file.read_u8().unwrap();
color.2 = file.read_u8().unwrap();
frame.push(Voxel {
x: x,
y: y,
z: z,
color: color,
});
}
frames.push(frame);
}
return frames;
}
pub fn parse_pallete(file: &mut File) -> Vec<Vec<(u8, u8, u8)>> {
let sig = file.read_u8().unwrap();
if sig!= 0x565054 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
let frame_count = file.read_u8().unwrap();
let color_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<(u8, u8, u8)>> = Vec::new();
for frame_id in 0..frame_count {
if file.read_u8().unwrap()!= 0xFF {
panic!("FILE CORRUPTED");
}
let mut frame: Vec<(u8, u8, u8)> = Vec::new();
for color in 0..color_count {
let r = file.read_u8().unwrap();
let g = file.read_u8().unwrap();
let b = file.read_u8().unwrap();
frame.push((r, g, b));
}
frames.push(frame);
}
return frames;
}
| {
panic!("ERROR: FILE CORRUPTED: {}", frame_tag);
} | conditional_block |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig!= 0x525654 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
if ver > FILE_VER {
panic!("ERROR: FILE VERSION IS GREATER THAN PROGRAM VERSION");
}
let frame_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<Voxel>> = Vec::new();
for frame_id in 0..frame_count {
let frame_tag = file.read_u8().unwrap();
if frame_tag!= 0xFF {
panic!("ERROR: FILE CORRUPTED: {}", frame_tag);
}
let voxel_count = file.read_u32::<BigEndian>().unwrap();
let mut frame: Vec<Voxel> = Vec::new();
for voxel_id in 0..voxel_count {
let x = file.read_i8().unwrap();
let y = file.read_i8().unwrap();
let z = file.read_i8().unwrap();
let mut color: (u8, u8, u8) = (0, 0, 0);
color.0 = file.read_u8().unwrap();
color.1 = file.read_u8().unwrap();
color.2 = file.read_u8().unwrap();
frame.push(Voxel {
x: x,
y: y,
z: z,
color: color,
});
}
frames.push(frame);
}
return frames;
}
pub fn | (file: &mut File) -> Vec<Vec<(u8, u8, u8)>> {
let sig = file.read_u8().unwrap();
if sig!= 0x565054 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
let frame_count = file.read_u8().unwrap();
let color_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<(u8, u8, u8)>> = Vec::new();
for frame_id in 0..frame_count {
if file.read_u8().unwrap()!= 0xFF {
panic!("FILE CORRUPTED");
}
let mut frame: Vec<(u8, u8, u8)> = Vec::new();
for color in 0..color_count {
let r = file.read_u8().unwrap();
let g = file.read_u8().unwrap();
let b = file.read_u8().unwrap();
frame.push((r, g, b));
}
frames.push(frame);
}
return frames;
}
| parse_pallete | identifier_name |
decode.rs | extern crate byteorder;
use std::env;
use std::fs::File;
use decode::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian};
use common::Voxel;
static FILE_VER: u8 = 1;
pub fn parse_voxel(file: &mut File) -> Vec<Vec<Voxel>> | }
let voxel_count = file.read_u32::<BigEndian>().unwrap();
let mut frame: Vec<Voxel> = Vec::new();
for voxel_id in 0..voxel_count {
let x = file.read_i8().unwrap();
let y = file.read_i8().unwrap();
let z = file.read_i8().unwrap();
let mut color: (u8, u8, u8) = (0, 0, 0);
color.0 = file.read_u8().unwrap();
color.1 = file.read_u8().unwrap();
color.2 = file.read_u8().unwrap();
frame.push(Voxel {
x: x,
y: y,
z: z,
color: color,
});
}
frames.push(frame);
}
return frames;
}
pub fn parse_pallete(file: &mut File) -> Vec<Vec<(u8, u8, u8)>> {
let sig = file.read_u8().unwrap();
if sig!= 0x565054 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
let frame_count = file.read_u8().unwrap();
let color_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<(u8, u8, u8)>> = Vec::new();
for frame_id in 0..frame_count {
if file.read_u8().unwrap()!= 0xFF {
panic!("FILE CORRUPTED");
}
let mut frame: Vec<(u8, u8, u8)> = Vec::new();
for color in 0..color_count {
let r = file.read_u8().unwrap();
let g = file.read_u8().unwrap();
let b = file.read_u8().unwrap();
frame.push((r, g, b));
}
frames.push(frame);
}
return frames;
}
| {
let sig = file.read_uint::<BigEndian>(3).unwrap();
if sig != 0x525654 {
panic!("UNKOWN FILETYPE");
}
let ver = file.read_u8().unwrap();
if ver > FILE_VER {
panic!("ERROR: FILE VERSION IS GREATER THAN PROGRAM VERSION");
}
let frame_count = file.read_u8().unwrap();
let mut frames: Vec<Vec<Voxel>> = Vec::new();
for frame_id in 0..frame_count {
let frame_tag = file.read_u8().unwrap();
if frame_tag != 0xFF {
panic!("ERROR: FILE CORRUPTED: {}", frame_tag); | identifier_body |
problem-048.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
#![feature(test)]
extern crate test;
/// Compute n^p mod b
fn modular_pow(n: u64, p: u64, b: u64) -> u64 {
let mut pow = n % b;
for _ in 1..p {
pow = (pow * (n % b)) % b;
}
pow
}
pub fn solution() -> u64 {
const BASE: u64 = 10000000000;
let mut sum = 0;
for n in 1..1001 {
sum += modular_pow(n, n, BASE);
}
sum % BASE
}
fn main() {
println!("The sum is {}", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(9110846700, solution());
}
#[bench]
fn bench(b: &mut Bencher) |
}
| {
b.iter(|| solution());
} | identifier_body |
problem-048.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
#![feature(test)]
extern crate test;
/// Compute n^p mod b
fn modular_pow(n: u64, p: u64, b: u64) -> u64 {
let mut pow = n % b;
for _ in 1..p {
pow = (pow * (n % b)) % b;
}
pow
}
pub fn solution() -> u64 {
const BASE: u64 = 10000000000;
let mut sum = 0;
for n in 1..1001 {
sum += modular_pow(n, n, BASE);
}
sum % BASE
}
fn main() {
println!("The sum is {}", solution());
} | #[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(9110846700, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
} | random_line_split |
|
problem-048.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
#![feature(test)]
extern crate test;
/// Compute n^p mod b
fn modular_pow(n: u64, p: u64, b: u64) -> u64 {
let mut pow = n % b;
for _ in 1..p {
pow = (pow * (n % b)) % b;
}
pow
}
pub fn | () -> u64 {
const BASE: u64 = 10000000000;
let mut sum = 0;
for n in 1..1001 {
sum += modular_pow(n, n, BASE);
}
sum % BASE
}
fn main() {
println!("The sum is {}", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(9110846700, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}
| solution | identifier_name |
gobject.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013, 2014 Mikhail Zabaluev <[email protected]>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
#![crate_name = "grust_gobject_2_0"]
#![crate_type = "lib"]
extern crate grust;
extern crate grust_glib_2_0 as glib;
extern crate gobject_2_0_sys as ffi;
use grust::gtype::GType;
use grust::object;
use grust::wrap;
#[repr(C)]
pub struct TypeInstance {
raw: ffi::GTypeInstance
}
unsafe impl wrap::Wrapper for TypeInstance {
type Raw = ffi::GTypeInstance;
}
#[repr(C)]
pub struct Object {
raw: ffi::GObject
}
| unsafe impl wrap::Wrapper for Object {
type Raw = ffi::GObject;
}
pub mod cast {
use grust::object;
pub trait AsObject {
fn as_object(&self) -> &super::Object;
}
impl<T> AsObject for T where T: object::Upcast<super::Object> {
#[inline]
fn as_object(&self) -> &super::Object { self.upcast() }
}
}
unsafe impl object::ObjectType for Object {
fn get_type() -> GType {
unsafe {
GType::from_raw(ffi::g_object_get_type())
}
}
} | random_line_split |
|
gobject.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013, 2014 Mikhail Zabaluev <[email protected]>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
#![crate_name = "grust_gobject_2_0"]
#![crate_type = "lib"]
extern crate grust;
extern crate grust_glib_2_0 as glib;
extern crate gobject_2_0_sys as ffi;
use grust::gtype::GType;
use grust::object;
use grust::wrap;
#[repr(C)]
pub struct TypeInstance {
raw: ffi::GTypeInstance
}
unsafe impl wrap::Wrapper for TypeInstance {
type Raw = ffi::GTypeInstance;
}
#[repr(C)]
pub struct Object {
raw: ffi::GObject
}
unsafe impl wrap::Wrapper for Object {
type Raw = ffi::GObject;
}
pub mod cast {
use grust::object;
pub trait AsObject {
fn as_object(&self) -> &super::Object;
}
impl<T> AsObject for T where T: object::Upcast<super::Object> {
#[inline]
fn | (&self) -> &super::Object { self.upcast() }
}
}
unsafe impl object::ObjectType for Object {
fn get_type() -> GType {
unsafe {
GType::from_raw(ffi::g_object_get_type())
}
}
}
| as_object | identifier_name |
gobject.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013, 2014 Mikhail Zabaluev <[email protected]>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
#![crate_name = "grust_gobject_2_0"]
#![crate_type = "lib"]
extern crate grust;
extern crate grust_glib_2_0 as glib;
extern crate gobject_2_0_sys as ffi;
use grust::gtype::GType;
use grust::object;
use grust::wrap;
#[repr(C)]
pub struct TypeInstance {
raw: ffi::GTypeInstance
}
unsafe impl wrap::Wrapper for TypeInstance {
type Raw = ffi::GTypeInstance;
}
#[repr(C)]
pub struct Object {
raw: ffi::GObject
}
unsafe impl wrap::Wrapper for Object {
type Raw = ffi::GObject;
}
pub mod cast {
use grust::object;
pub trait AsObject {
fn as_object(&self) -> &super::Object;
}
impl<T> AsObject for T where T: object::Upcast<super::Object> {
#[inline]
fn as_object(&self) -> &super::Object |
}
}
unsafe impl object::ObjectType for Object {
fn get_type() -> GType {
unsafe {
GType::from_raw(ffi::g_object_get_type())
}
}
}
| { self.upcast() } | identifier_body |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn | (n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
}
fn new(x: f64, y: f64) -> Point { // static method
Point { x: x, y: y }
}
}
struct Rectangle {
p1: Point,
p2: Point,
}
impl Rectangle {
// `&self` is sugar for `self: &Self`, where `Self` is the type of the
// caller object. In this case `Self` = `Rectangle`
fn area(&self) -> f64 {
let Point { x: x1, y: y1 } = self.p1;
let Point { x: x2, y: y2 } = self.p2;
2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
}
fn translate(&mut self, x: f64, y: f64) {
self.p1.x += x;
self.p2.x += x;
self.p1.y += y;
self.p2.y += y;
}
}
// 8.2
// (http://rustbyexample.com/fn/closures.html)
fn function(i: i32) -> i32 { i + 1 }
let closure1 = |i: i32| -> i32 { i + 1 };
let closure2 = |i| i + 1;
let i = 1;
println!("function: {}", function(i));
println!("closure1: {}", closure1(i));
println!("closure2: {}", closure2(i));
let one = || 1;
println!("closure returning one: {}", one());
// 8.2.1
// (http://rustbyexample.com/fn/closures/capture.html)
let s = "string"; // capture by reference: &T
let print_s = || println!("s: {}", s);
print_s();
let mut count = 0; // capture by mutable reference: &mut T
let mut inc = || { //'mut' is required
count += 1;
println!("count: {}", count);
};
inc();
inc();
// error: cannot borrow `count` as mutable more than once at a time [E0499]
// let reborrow = &mut count;
let movable = Box::new(3); // capture by value
let consume = || {
println!("movable: {}", movable);
std::mem::drop(movable);
};
consume();
// error: use of moved value: `consume` [E0382]
// consume();
// 8.2.2
// (http://rustbyexample.com/fn/closures/input_parameters.html)
// FnOnce: takes captures by value (T)
fn apply<F>(f: F) where F: FnOnce() {
f()
}
// Fn: takes captures by reference (&T)
fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32 {
f(3)
}
let greeting = "hello";
let mut farewell = "goodbye".to_owned(); // a non-copy type
let diary = || {
println!("{}", greeting); // greeting is by ference, requires Fn
farewell.push_str("!!!"); // requires FnMut
std::mem::drop(farewell); // requires FnOnce
};
let x2 = |x| 2 * x;
apply(diary);
apply_to_3(x2);
// 8.2.3
// skipped code
// 8.2.4
fn call_function<F: Fn()>(f: F) {
f()
}
fn print() {
println!("I'm a function");
}
let closure = || println!("I'm a closure");
call_function(print);
call_function(closure);
// 8.2.5
// skipped code
// 8.2.6.1, 8.2.6.2
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
let mut iter = vec1.iter();
let mut into_iter = vec2.into_iter();
println!("any in vec1: {}", iter.any(|&x| x == 2));
println!("find in vec1: {:?}", iter.find(|&&x| x == 2));
println!("any in vec2: {}", into_iter.any(|x| x == 2));
println!("find in vec2: {:?}", into_iter.find(|&x| x == 2));
// 8.3
fn is_odd(n: u32) -> bool {
n % 2 == 0
}
let upper_limit = 1000;
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n)
.take_while(|&n| n < upper_limit)
.filter(|n| is_odd(*n))
.fold(0, |sum, n| sum + n);
println!("sum_of_squared_odd_numbers: {}", sum_of_squared_odd_numbers);
}
| void_return2 | identifier_name |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
}
fn new(x: f64, y: f64) -> Point { // static method
Point { x: x, y: y }
}
}
struct Rectangle {
p1: Point,
p2: Point,
}
impl Rectangle {
// `&self` is sugar for `self: &Self`, where `Self` is the type of the
// caller object. In this case `Self` = `Rectangle`
fn area(&self) -> f64 {
let Point { x: x1, y: y1 } = self.p1;
let Point { x: x2, y: y2 } = self.p2;
2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
}
fn translate(&mut self, x: f64, y: f64) {
self.p1.x += x;
self.p2.x += x;
self.p1.y += y;
self.p2.y += y;
}
}
// 8.2
// (http://rustbyexample.com/fn/closures.html)
fn function(i: i32) -> i32 { i + 1 }
let closure1 = |i: i32| -> i32 { i + 1 };
let closure2 = |i| i + 1;
let i = 1;
println!("function: {}", function(i));
println!("closure1: {}", closure1(i));
println!("closure2: {}", closure2(i));
let one = || 1;
println!("closure returning one: {}", one());
// 8.2.1
// (http://rustbyexample.com/fn/closures/capture.html)
let s = "string"; // capture by reference: &T
let print_s = || println!("s: {}", s);
print_s();
let mut count = 0; // capture by mutable reference: &mut T
let mut inc = || { //'mut' is required
count += 1;
println!("count: {}", count);
};
inc();
inc();
// error: cannot borrow `count` as mutable more than once at a time [E0499]
// let reborrow = &mut count;
let movable = Box::new(3); // capture by value
let consume = || {
println!("movable: {}", movable); | std::mem::drop(movable);
};
consume();
// error: use of moved value: `consume` [E0382]
// consume();
// 8.2.2
// (http://rustbyexample.com/fn/closures/input_parameters.html)
// FnOnce: takes captures by value (T)
fn apply<F>(f: F) where F: FnOnce() {
f()
}
// Fn: takes captures by reference (&T)
fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32 {
f(3)
}
let greeting = "hello";
let mut farewell = "goodbye".to_owned(); // a non-copy type
let diary = || {
println!("{}", greeting); // greeting is by ference, requires Fn
farewell.push_str("!!!"); // requires FnMut
std::mem::drop(farewell); // requires FnOnce
};
let x2 = |x| 2 * x;
apply(diary);
apply_to_3(x2);
// 8.2.3
// skipped code
// 8.2.4
fn call_function<F: Fn()>(f: F) {
f()
}
fn print() {
println!("I'm a function");
}
let closure = || println!("I'm a closure");
call_function(print);
call_function(closure);
// 8.2.5
// skipped code
// 8.2.6.1, 8.2.6.2
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
let mut iter = vec1.iter();
let mut into_iter = vec2.into_iter();
println!("any in vec1: {}", iter.any(|&x| x == 2));
println!("find in vec1: {:?}", iter.find(|&&x| x == 2));
println!("any in vec2: {}", into_iter.any(|x| x == 2));
println!("find in vec2: {:?}", into_iter.find(|&x| x == 2));
// 8.3
fn is_odd(n: u32) -> bool {
n % 2 == 0
}
let upper_limit = 1000;
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n)
.take_while(|&n| n < upper_limit)
.filter(|n| is_odd(*n))
.fold(0, |sum, n| sum + n);
println!("sum_of_squared_odd_numbers: {}", sum_of_squared_odd_numbers);
} | random_line_split |
|
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 |
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
}
fn new(x: f64, y: f64) -> Point { // static method
Point { x: x, y: y }
}
}
struct Rectangle {
p1: Point,
p2: Point,
}
impl Rectangle {
// `&self` is sugar for `self: &Self`, where `Self` is the type of the
// caller object. In this case `Self` = `Rectangle`
fn area(&self) -> f64 {
let Point { x: x1, y: y1 } = self.p1;
let Point { x: x2, y: y2 } = self.p2;
2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
}
fn translate(&mut self, x: f64, y: f64) {
self.p1.x += x;
self.p2.x += x;
self.p1.y += y;
self.p2.y += y;
}
}
// 8.2
// (http://rustbyexample.com/fn/closures.html)
fn function(i: i32) -> i32 { i + 1 }
let closure1 = |i: i32| -> i32 { i + 1 };
let closure2 = |i| i + 1;
let i = 1;
println!("function: {}", function(i));
println!("closure1: {}", closure1(i));
println!("closure2: {}", closure2(i));
let one = || 1;
println!("closure returning one: {}", one());
// 8.2.1
// (http://rustbyexample.com/fn/closures/capture.html)
let s = "string"; // capture by reference: &T
let print_s = || println!("s: {}", s);
print_s();
let mut count = 0; // capture by mutable reference: &mut T
let mut inc = || { //'mut' is required
count += 1;
println!("count: {}", count);
};
inc();
inc();
// error: cannot borrow `count` as mutable more than once at a time [E0499]
// let reborrow = &mut count;
let movable = Box::new(3); // capture by value
let consume = || {
println!("movable: {}", movable);
std::mem::drop(movable);
};
consume();
// error: use of moved value: `consume` [E0382]
// consume();
// 8.2.2
// (http://rustbyexample.com/fn/closures/input_parameters.html)
// FnOnce: takes captures by value (T)
fn apply<F>(f: F) where F: FnOnce() {
f()
}
// Fn: takes captures by reference (&T)
fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32 {
f(3)
}
let greeting = "hello";
let mut farewell = "goodbye".to_owned(); // a non-copy type
let diary = || {
println!("{}", greeting); // greeting is by ference, requires Fn
farewell.push_str("!!!"); // requires FnMut
std::mem::drop(farewell); // requires FnOnce
};
let x2 = |x| 2 * x;
apply(diary);
apply_to_3(x2);
// 8.2.3
// skipped code
// 8.2.4
fn call_function<F: Fn()>(f: F) {
f()
}
fn print() {
println!("I'm a function");
}
let closure = || println!("I'm a closure");
call_function(print);
call_function(closure);
// 8.2.5
// skipped code
// 8.2.6.1, 8.2.6.2
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
let mut iter = vec1.iter();
let mut into_iter = vec2.into_iter();
println!("any in vec1: {}", iter.any(|&x| x == 2));
println!("find in vec1: {:?}", iter.find(|&&x| x == 2));
println!("any in vec2: {}", into_iter.any(|x| x == 2));
println!("find in vec2: {:?}", into_iter.find(|&x| x == 2));
// 8.3
fn is_odd(n: u32) -> bool {
n % 2 == 0
}
let upper_limit = 1000;
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n)
.take_while(|&n| n < upper_limit)
.filter(|n| is_odd(*n))
.fold(0, |sum, n| sum + n);
println!("sum_of_squared_odd_numbers: {}", sum_of_squared_odd_numbers);
}
| {
return false;
} | conditional_block |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
}
fn new(x: f64, y: f64) -> Point { // static method
Point { x: x, y: y }
}
}
struct Rectangle {
p1: Point,
p2: Point,
}
impl Rectangle {
// `&self` is sugar for `self: &Self`, where `Self` is the type of the
// caller object. In this case `Self` = `Rectangle`
fn area(&self) -> f64 {
let Point { x: x1, y: y1 } = self.p1;
let Point { x: x2, y: y2 } = self.p2;
2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
}
fn translate(&mut self, x: f64, y: f64) {
self.p1.x += x;
self.p2.x += x;
self.p1.y += y;
self.p2.y += y;
}
}
// 8.2
// (http://rustbyexample.com/fn/closures.html)
fn function(i: i32) -> i32 |
let closure1 = |i: i32| -> i32 { i + 1 };
let closure2 = |i| i + 1;
let i = 1;
println!("function: {}", function(i));
println!("closure1: {}", closure1(i));
println!("closure2: {}", closure2(i));
let one = || 1;
println!("closure returning one: {}", one());
// 8.2.1
// (http://rustbyexample.com/fn/closures/capture.html)
let s = "string"; // capture by reference: &T
let print_s = || println!("s: {}", s);
print_s();
let mut count = 0; // capture by mutable reference: &mut T
let mut inc = || { //'mut' is required
count += 1;
println!("count: {}", count);
};
inc();
inc();
// error: cannot borrow `count` as mutable more than once at a time [E0499]
// let reborrow = &mut count;
let movable = Box::new(3); // capture by value
let consume = || {
println!("movable: {}", movable);
std::mem::drop(movable);
};
consume();
// error: use of moved value: `consume` [E0382]
// consume();
// 8.2.2
// (http://rustbyexample.com/fn/closures/input_parameters.html)
// FnOnce: takes captures by value (T)
fn apply<F>(f: F) where F: FnOnce() {
f()
}
// Fn: takes captures by reference (&T)
fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32 {
f(3)
}
let greeting = "hello";
let mut farewell = "goodbye".to_owned(); // a non-copy type
let diary = || {
println!("{}", greeting); // greeting is by ference, requires Fn
farewell.push_str("!!!"); // requires FnMut
std::mem::drop(farewell); // requires FnOnce
};
let x2 = |x| 2 * x;
apply(diary);
apply_to_3(x2);
// 8.2.3
// skipped code
// 8.2.4
fn call_function<F: Fn()>(f: F) {
f()
}
fn print() {
println!("I'm a function");
}
let closure = || println!("I'm a closure");
call_function(print);
call_function(closure);
// 8.2.5
// skipped code
// 8.2.6.1, 8.2.6.2
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
let mut iter = vec1.iter();
let mut into_iter = vec2.into_iter();
println!("any in vec1: {}", iter.any(|&x| x == 2));
println!("find in vec1: {:?}", iter.find(|&&x| x == 2));
println!("any in vec2: {}", into_iter.any(|x| x == 2));
println!("find in vec2: {:?}", into_iter.find(|&x| x == 2));
// 8.3
fn is_odd(n: u32) -> bool {
n % 2 == 0
}
let upper_limit = 1000;
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n)
.take_while(|&n| n < upper_limit)
.filter(|n| is_odd(*n))
.fold(0, |sum, n| sum + n);
println!("sum_of_squared_odd_numbers: {}", sum_of_squared_odd_numbers);
}
| { i + 1 } | identifier_body |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue: &Vec<u8>) -> Option<i64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(i) = utf8.parse::<i64>() {
return Some(i);
}
}
}
}
return None;
}
fn to_f64(newvalue: &Vec<u8>) -> Option<f64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(f) = utf8.parse::<f64>() {
return Some(f);
}
}
}
}
return None;
}
impl ValueString {
pub fn new(newvalue: Vec<u8>) -> Self {
match to_i64(&newvalue) {
Some(i) => ValueString::Integer(i),
None => ValueString::Data(newvalue),
}
}
pub fn | (&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.len(),
ValueString::Integer(ref int) => format!("{}", int).len(),
}
}
pub fn append(&mut self, newvalue: Vec<u8>) {
match *self {
ValueString::Data(ref mut data) => data.extend(newvalue),
ValueString::Integer(i) => {
let oldstr = format!("{}", i);
*self = ValueString::new([oldstr.into_bytes(), newvalue].concat());
},
};
}
pub fn incr(&mut self, incr: i64) -> Result<i64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i,
ValueString::Data(ref data) => {
match to_i64(data) {
Some(i) => i,
None => return Err(OperationError::ValueError("ERR value is not a valid integer".to_owned())),
}
},
};
let newval = try!(val.checked_add(incr).ok_or(OperationError::OverflowError));
*self = ValueString::Integer(newval.clone());
Ok(newval)
}
pub fn incrbyfloat(&mut self, incr: f64) -> Result<f64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i as f64,
ValueString::Data(ref data) => {
match to_f64(data) {
Some(f) => f,
None => return Err(OperationError::ValueError("ERR value is not a valid float".to_owned())),
}
},
};
let newval = val + incr;
*self = ValueString::Data(format!("{}", newval).into_bytes());
Ok(newval)
}
pub fn getrange(&self, _start: i64, _stop: i64) -> Vec<u8> {
let s = match *self {
ValueString::Integer(ref i) => format!("{}", i).into_bytes(),
ValueString::Data(ref s) => s.clone(),
};
let len = s.len();
let start = match normalize_position(_start, len) {
Ok(i) => i,
Err(g) => if!g { 0 } else { return Vec::new(); }
} as usize;
let stop = match normalize_position(_stop, len) {
Ok(i) => i,
Err(g) => if!g { return Vec::new(); } else { len - 1 }
} as usize;
if stop < start {
return Vec::new();
}
let mut v = Vec::with_capacity(stop - start + 1);
v.extend(s[start..stop + 1].iter());
v
}
pub fn setbit(&mut self, bitoffset: usize, on: bool) -> bool {
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
};
let mut d = match *self {
ValueString::Data(ref mut d) => d,
_ => panic!("Value should be data"),
};
let byte = bitoffset >> 3;
while byte + 1 > d.len() {
d.push(0);
}
let mut byteval = d[byte];
let bit = 7 - (bitoffset & 0x7);
let bitval = byteval & (1 << bit);
byteval &=!(1 << bit);
byteval |= (if on { 1 } else { 0 } & 0x1) << bit;
d[byte] = byteval;
bitval!= 0
}
pub fn getbit(&self, bitoffset: usize) -> bool {
let tmp;
let d = match *self {
ValueString::Integer(i) => { tmp = format!("{}", i).into_bytes(); &tmp },
ValueString::Data(ref d) => d,
};
let byte = bitoffset >> 3;
if byte >= d.len() {
return false;
}
let bit = 7 - (bitoffset & 0x7);;
let bitval = d[byte] & (1 << bit);
bitval!= 0
}
pub fn setrange(&mut self, _index: usize, data: Vec<u8>) -> usize {
if data.len() == 0 {
return self.strlen();
}
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
}
let mut d = match self {
&mut ValueString::Data(ref mut s) => s,
_ => panic!("String must be data"),
};
let mut index = _index;
for _ in d.len()..index {
d.push(0);
}
for c in data {
d.push(c);
if index < d.len() - 1 {
d.swap_remove(index);
}
index += 1;
}
d.len()
}
pub fn dump<T: Write>(&self, writer: &mut T) -> io::Result<usize> {
let mut v = vec![];
match *self {
ValueString::Integer(ref i) => match encode_i64(i.clone(), &mut v) {
Ok(s) => s,
Err(e) => match e {
EncodeError::IOError(e) => return Err(e),
EncodeError::OverflowError => try!(encode_slice_u8(&*self.to_vec(), &mut v, false))
}
},
ValueString::Data(ref d) => try!(encode_slice_u8(&*d, &mut v, true)),
};
let data = [
vec![TYPE_STRING],
v,
vec![(VERSION & 0xff) as u8],
vec![((VERSION >> 8) & 0xff) as u8],
].concat();
writer.write(&*data)
}
pub fn debug_object(&self) -> String {
let mut serialized_data = vec![];
let serialized = self.dump(&mut serialized_data).unwrap();
let encoding = match *self {
ValueString::Integer(_) => "int",
ValueString::Data(_) => "raw",
};
format!("Value at:0x0000000000 refcount:1 encoding:{} serializedlength:{} lru:0 lru_seconds_idle:0", encoding, serialized).to_owned()
}
}
#[cfg(test)]
mod test_rdb {
use std::i64;
use super::ValueString;
#[test]
fn dump_integer() {
let mut v = vec![];
ValueString::Integer(1).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\xc0\x01\x07\x00");
}
#[test]
fn dump_integer_overflow() {
let mut v = vec![];
ValueString::Integer(i64::MAX).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x139223372036854775807\x07\x00");
}
#[test]
fn dump_string() {
let mut v = vec![];
ValueString::Data(b"hello world".to_vec()).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x0bhello world\x07\x00");
}
}
| to_vec | identifier_name |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue: &Vec<u8>) -> Option<i64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) |
}
}
return None;
}
fn to_f64(newvalue: &Vec<u8>) -> Option<f64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(f) = utf8.parse::<f64>() {
return Some(f);
}
}
}
}
return None;
}
impl ValueString {
pub fn new(newvalue: Vec<u8>) -> Self {
match to_i64(&newvalue) {
Some(i) => ValueString::Integer(i),
None => ValueString::Data(newvalue),
}
}
pub fn to_vec(&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.len(),
ValueString::Integer(ref int) => format!("{}", int).len(),
}
}
pub fn append(&mut self, newvalue: Vec<u8>) {
match *self {
ValueString::Data(ref mut data) => data.extend(newvalue),
ValueString::Integer(i) => {
let oldstr = format!("{}", i);
*self = ValueString::new([oldstr.into_bytes(), newvalue].concat());
},
};
}
pub fn incr(&mut self, incr: i64) -> Result<i64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i,
ValueString::Data(ref data) => {
match to_i64(data) {
Some(i) => i,
None => return Err(OperationError::ValueError("ERR value is not a valid integer".to_owned())),
}
},
};
let newval = try!(val.checked_add(incr).ok_or(OperationError::OverflowError));
*self = ValueString::Integer(newval.clone());
Ok(newval)
}
pub fn incrbyfloat(&mut self, incr: f64) -> Result<f64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i as f64,
ValueString::Data(ref data) => {
match to_f64(data) {
Some(f) => f,
None => return Err(OperationError::ValueError("ERR value is not a valid float".to_owned())),
}
},
};
let newval = val + incr;
*self = ValueString::Data(format!("{}", newval).into_bytes());
Ok(newval)
}
pub fn getrange(&self, _start: i64, _stop: i64) -> Vec<u8> {
let s = match *self {
ValueString::Integer(ref i) => format!("{}", i).into_bytes(),
ValueString::Data(ref s) => s.clone(),
};
let len = s.len();
let start = match normalize_position(_start, len) {
Ok(i) => i,
Err(g) => if!g { 0 } else { return Vec::new(); }
} as usize;
let stop = match normalize_position(_stop, len) {
Ok(i) => i,
Err(g) => if!g { return Vec::new(); } else { len - 1 }
} as usize;
if stop < start {
return Vec::new();
}
let mut v = Vec::with_capacity(stop - start + 1);
v.extend(s[start..stop + 1].iter());
v
}
pub fn setbit(&mut self, bitoffset: usize, on: bool) -> bool {
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
};
let mut d = match *self {
ValueString::Data(ref mut d) => d,
_ => panic!("Value should be data"),
};
let byte = bitoffset >> 3;
while byte + 1 > d.len() {
d.push(0);
}
let mut byteval = d[byte];
let bit = 7 - (bitoffset & 0x7);
let bitval = byteval & (1 << bit);
byteval &=!(1 << bit);
byteval |= (if on { 1 } else { 0 } & 0x1) << bit;
d[byte] = byteval;
bitval!= 0
}
pub fn getbit(&self, bitoffset: usize) -> bool {
let tmp;
let d = match *self {
ValueString::Integer(i) => { tmp = format!("{}", i).into_bytes(); &tmp },
ValueString::Data(ref d) => d,
};
let byte = bitoffset >> 3;
if byte >= d.len() {
return false;
}
let bit = 7 - (bitoffset & 0x7);;
let bitval = d[byte] & (1 << bit);
bitval!= 0
}
pub fn setrange(&mut self, _index: usize, data: Vec<u8>) -> usize {
if data.len() == 0 {
return self.strlen();
}
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
}
let mut d = match self {
&mut ValueString::Data(ref mut s) => s,
_ => panic!("String must be data"),
};
let mut index = _index;
for _ in d.len()..index {
d.push(0);
}
for c in data {
d.push(c);
if index < d.len() - 1 {
d.swap_remove(index);
}
index += 1;
}
d.len()
}
pub fn dump<T: Write>(&self, writer: &mut T) -> io::Result<usize> {
let mut v = vec![];
match *self {
ValueString::Integer(ref i) => match encode_i64(i.clone(), &mut v) {
Ok(s) => s,
Err(e) => match e {
EncodeError::IOError(e) => return Err(e),
EncodeError::OverflowError => try!(encode_slice_u8(&*self.to_vec(), &mut v, false))
}
},
ValueString::Data(ref d) => try!(encode_slice_u8(&*d, &mut v, true)),
};
let data = [
vec![TYPE_STRING],
v,
vec![(VERSION & 0xff) as u8],
vec![((VERSION >> 8) & 0xff) as u8],
].concat();
writer.write(&*data)
}
pub fn debug_object(&self) -> String {
let mut serialized_data = vec![];
let serialized = self.dump(&mut serialized_data).unwrap();
let encoding = match *self {
ValueString::Integer(_) => "int",
ValueString::Data(_) => "raw",
};
format!("Value at:0x0000000000 refcount:1 encoding:{} serializedlength:{} lru:0 lru_seconds_idle:0", encoding, serialized).to_owned()
}
}
#[cfg(test)]
mod test_rdb {
use std::i64;
use super::ValueString;
#[test]
fn dump_integer() {
let mut v = vec![];
ValueString::Integer(1).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\xc0\x01\x07\x00");
}
#[test]
fn dump_integer_overflow() {
let mut v = vec![];
ValueString::Integer(i64::MAX).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x139223372036854775807\x07\x00");
}
#[test]
fn dump_string() {
let mut v = vec![];
ValueString::Data(b"hello world".to_vec()).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x0bhello world\x07\x00");
}
}
| {
if let Ok(i) = utf8.parse::<i64>() {
return Some(i);
}
} | conditional_block |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue: &Vec<u8>) -> Option<i64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(i) = utf8.parse::<i64>() {
return Some(i);
}
}
}
}
return None;
}
fn to_f64(newvalue: &Vec<u8>) -> Option<f64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(f) = utf8.parse::<f64>() {
return Some(f);
}
}
}
}
return None;
}
impl ValueString {
pub fn new(newvalue: Vec<u8>) -> Self |
pub fn to_vec(&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.len(),
ValueString::Integer(ref int) => format!("{}", int).len(),
}
}
pub fn append(&mut self, newvalue: Vec<u8>) {
match *self {
ValueString::Data(ref mut data) => data.extend(newvalue),
ValueString::Integer(i) => {
let oldstr = format!("{}", i);
*self = ValueString::new([oldstr.into_bytes(), newvalue].concat());
},
};
}
pub fn incr(&mut self, incr: i64) -> Result<i64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i,
ValueString::Data(ref data) => {
match to_i64(data) {
Some(i) => i,
None => return Err(OperationError::ValueError("ERR value is not a valid integer".to_owned())),
}
},
};
let newval = try!(val.checked_add(incr).ok_or(OperationError::OverflowError));
*self = ValueString::Integer(newval.clone());
Ok(newval)
}
pub fn incrbyfloat(&mut self, incr: f64) -> Result<f64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i as f64,
ValueString::Data(ref data) => {
match to_f64(data) {
Some(f) => f,
None => return Err(OperationError::ValueError("ERR value is not a valid float".to_owned())),
}
},
};
let newval = val + incr;
*self = ValueString::Data(format!("{}", newval).into_bytes());
Ok(newval)
}
pub fn getrange(&self, _start: i64, _stop: i64) -> Vec<u8> {
let s = match *self {
ValueString::Integer(ref i) => format!("{}", i).into_bytes(),
ValueString::Data(ref s) => s.clone(),
};
let len = s.len();
let start = match normalize_position(_start, len) {
Ok(i) => i,
Err(g) => if!g { 0 } else { return Vec::new(); }
} as usize;
let stop = match normalize_position(_stop, len) {
Ok(i) => i,
Err(g) => if!g { return Vec::new(); } else { len - 1 }
} as usize;
if stop < start {
return Vec::new();
}
let mut v = Vec::with_capacity(stop - start + 1);
v.extend(s[start..stop + 1].iter());
v
}
pub fn setbit(&mut self, bitoffset: usize, on: bool) -> bool {
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
};
let mut d = match *self {
ValueString::Data(ref mut d) => d,
_ => panic!("Value should be data"),
};
let byte = bitoffset >> 3;
while byte + 1 > d.len() {
d.push(0);
}
let mut byteval = d[byte];
let bit = 7 - (bitoffset & 0x7);
let bitval = byteval & (1 << bit);
byteval &=!(1 << bit);
byteval |= (if on { 1 } else { 0 } & 0x1) << bit;
d[byte] = byteval;
bitval!= 0
}
pub fn getbit(&self, bitoffset: usize) -> bool {
let tmp;
let d = match *self {
ValueString::Integer(i) => { tmp = format!("{}", i).into_bytes(); &tmp },
ValueString::Data(ref d) => d,
};
let byte = bitoffset >> 3;
if byte >= d.len() {
return false;
}
let bit = 7 - (bitoffset & 0x7);;
let bitval = d[byte] & (1 << bit);
bitval!= 0
}
pub fn setrange(&mut self, _index: usize, data: Vec<u8>) -> usize {
if data.len() == 0 {
return self.strlen();
}
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
}
let mut d = match self {
&mut ValueString::Data(ref mut s) => s,
_ => panic!("String must be data"),
};
let mut index = _index;
for _ in d.len()..index {
d.push(0);
}
for c in data {
d.push(c);
if index < d.len() - 1 {
d.swap_remove(index);
}
index += 1;
}
d.len()
}
pub fn dump<T: Write>(&self, writer: &mut T) -> io::Result<usize> {
let mut v = vec![];
match *self {
ValueString::Integer(ref i) => match encode_i64(i.clone(), &mut v) {
Ok(s) => s,
Err(e) => match e {
EncodeError::IOError(e) => return Err(e),
EncodeError::OverflowError => try!(encode_slice_u8(&*self.to_vec(), &mut v, false))
}
},
ValueString::Data(ref d) => try!(encode_slice_u8(&*d, &mut v, true)),
};
let data = [
vec![TYPE_STRING],
v,
vec![(VERSION & 0xff) as u8],
vec![((VERSION >> 8) & 0xff) as u8],
].concat();
writer.write(&*data)
}
pub fn debug_object(&self) -> String {
let mut serialized_data = vec![];
let serialized = self.dump(&mut serialized_data).unwrap();
let encoding = match *self {
ValueString::Integer(_) => "int",
ValueString::Data(_) => "raw",
};
format!("Value at:0x0000000000 refcount:1 encoding:{} serializedlength:{} lru:0 lru_seconds_idle:0", encoding, serialized).to_owned()
}
}
#[cfg(test)]
mod test_rdb {
use std::i64;
use super::ValueString;
#[test]
fn dump_integer() {
let mut v = vec![];
ValueString::Integer(1).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\xc0\x01\x07\x00");
}
#[test]
fn dump_integer_overflow() {
let mut v = vec![];
ValueString::Integer(i64::MAX).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x139223372036854775807\x07\x00");
}
#[test]
fn dump_string() {
let mut v = vec![];
ValueString::Data(b"hello world".to_vec()).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x0bhello world\x07\x00");
}
}
| {
match to_i64(&newvalue) {
Some(i) => ValueString::Integer(i),
None => ValueString::Data(newvalue),
}
} | identifier_body |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue: &Vec<u8>) -> Option<i64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(i) = utf8.parse::<i64>() {
return Some(i);
}
}
}
}
return None;
}
fn to_f64(newvalue: &Vec<u8>) -> Option<f64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char!= '0' && newvalue[0] as char!='' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(f) = utf8.parse::<f64>() {
return Some(f);
}
}
}
}
return None;
}
impl ValueString {
pub fn new(newvalue: Vec<u8>) -> Self {
match to_i64(&newvalue) {
Some(i) => ValueString::Integer(i),
None => ValueString::Data(newvalue),
}
}
pub fn to_vec(&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.len(),
ValueString::Integer(ref int) => format!("{}", int).len(),
}
}
pub fn append(&mut self, newvalue: Vec<u8>) {
match *self {
ValueString::Data(ref mut data) => data.extend(newvalue),
ValueString::Integer(i) => {
let oldstr = format!("{}", i);
*self = ValueString::new([oldstr.into_bytes(), newvalue].concat());
},
};
}
pub fn incr(&mut self, incr: i64) -> Result<i64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i,
ValueString::Data(ref data) => {
match to_i64(data) {
Some(i) => i,
None => return Err(OperationError::ValueError("ERR value is not a valid integer".to_owned())),
}
},
};
let newval = try!(val.checked_add(incr).ok_or(OperationError::OverflowError));
*self = ValueString::Integer(newval.clone());
Ok(newval)
}
pub fn incrbyfloat(&mut self, incr: f64) -> Result<f64, OperationError> {
let val = match *self {
ValueString::Integer(i) => i as f64,
ValueString::Data(ref data) => {
match to_f64(data) {
Some(f) => f,
None => return Err(OperationError::ValueError("ERR value is not a valid float".to_owned())),
}
},
};
let newval = val + incr;
*self = ValueString::Data(format!("{}", newval).into_bytes());
Ok(newval)
}
pub fn getrange(&self, _start: i64, _stop: i64) -> Vec<u8> {
let s = match *self {
ValueString::Integer(ref i) => format!("{}", i).into_bytes(),
ValueString::Data(ref s) => s.clone(),
};
let len = s.len();
let start = match normalize_position(_start, len) {
Ok(i) => i,
Err(g) => if!g { 0 } else { return Vec::new(); }
} as usize;
let stop = match normalize_position(_stop, len) {
Ok(i) => i,
Err(g) => if!g { return Vec::new(); } else { len - 1 }
} as usize;
if stop < start {
return Vec::new();
}
let mut v = Vec::with_capacity(stop - start + 1);
v.extend(s[start..stop + 1].iter());
v
}
pub fn setbit(&mut self, bitoffset: usize, on: bool) -> bool {
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
};
let mut d = match *self {
ValueString::Data(ref mut d) => d,
_ => panic!("Value should be data"),
};
let byte = bitoffset >> 3;
while byte + 1 > d.len() {
d.push(0);
}
let mut byteval = d[byte];
let bit = 7 - (bitoffset & 0x7);
let bitval = byteval & (1 << bit);
byteval &=!(1 << bit);
byteval |= (if on { 1 } else { 0 } & 0x1) << bit;
d[byte] = byteval;
bitval!= 0
}
pub fn getbit(&self, bitoffset: usize) -> bool {
let tmp;
let d = match *self {
ValueString::Integer(i) => { tmp = format!("{}", i).into_bytes(); &tmp },
ValueString::Data(ref d) => d,
};
let byte = bitoffset >> 3;
if byte >= d.len() {
return false;
}
let bit = 7 - (bitoffset & 0x7);;
let bitval = d[byte] & (1 << bit);
bitval!= 0
}
pub fn setrange(&mut self, _index: usize, data: Vec<u8>) -> usize {
if data.len() == 0 {
return self.strlen();
}
match *self {
ValueString::Integer(i) => *self = ValueString::Data(format!("{}", i).into_bytes()),
ValueString::Data(_) => (),
}
let mut d = match self {
&mut ValueString::Data(ref mut s) => s,
_ => panic!("String must be data"),
};
let mut index = _index;
for _ in d.len()..index {
d.push(0);
}
for c in data {
d.push(c);
if index < d.len() - 1 {
d.swap_remove(index);
}
index += 1;
}
d.len()
}
pub fn dump<T: Write>(&self, writer: &mut T) -> io::Result<usize> {
let mut v = vec![];
match *self {
ValueString::Integer(ref i) => match encode_i64(i.clone(), &mut v) {
Ok(s) => s,
Err(e) => match e {
EncodeError::IOError(e) => return Err(e),
EncodeError::OverflowError => try!(encode_slice_u8(&*self.to_vec(), &mut v, false))
}
},
ValueString::Data(ref d) => try!(encode_slice_u8(&*d, &mut v, true)),
};
let data = [
vec![TYPE_STRING],
v,
vec![(VERSION & 0xff) as u8],
vec![((VERSION >> 8) & 0xff) as u8],
].concat();
writer.write(&*data)
}
pub fn debug_object(&self) -> String {
let mut serialized_data = vec![];
let serialized = self.dump(&mut serialized_data).unwrap();
let encoding = match *self {
ValueString::Integer(_) => "int",
ValueString::Data(_) => "raw",
};
format!("Value at:0x0000000000 refcount:1 encoding:{} serializedlength:{} lru:0 lru_seconds_idle:0", encoding, serialized).to_owned()
}
}
#[cfg(test)]
mod test_rdb {
use std::i64;
use super::ValueString;
#[test]
fn dump_integer() {
let mut v = vec![];
ValueString::Integer(1).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\xc0\x01\x07\x00");
}
#[test]
fn dump_integer_overflow() {
let mut v = vec![];
ValueString::Integer(i64::MAX).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x139223372036854775807\x07\x00"); | #[test]
fn dump_string() {
let mut v = vec![];
ValueString::Data(b"hello world".to_vec()).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x0bhello world\x07\x00");
}
} | }
| random_line_split |
local_data_priv.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.
#[allow(missing_doc)];
use cast;
use cmp::Eq;
use libc;
use prelude::*;
use task::rt;
use local_data::LocalDataKey;
use super::rt::rust_task;
use rt::task::{Task, LocalStorage};
pub enum Handle {
OldHandle(*rust_task),
NewHandle(*mut LocalStorage)
}
impl Handle {
pub fn new() -> Handle {
use rt::{context, OldTaskContext};
use rt::local::Local;
unsafe {
match context() {
OldTaskContext => {
OldHandle(rt::rust_get_task())
}
_ => {
let task = Local::unsafe_borrow::<Task>();
NewHandle(&mut (*task).storage)
}
}
}
}
}
pub trait LocalData { }
impl<T:'static> LocalData for @T { }
impl Eq for @LocalData {
fn eq(&self, other: &@LocalData) -> bool {
unsafe {
let ptr_a: &(uint, uint) = cast::transmute(self);
let ptr_b: &(uint, uint) = cast::transmute(other);
return ptr_a == ptr_b;
}
}
fn ne(&self, other: &@LocalData) -> bool {!(*self).eq(other) }
}
// If TLS is used heavily in future, this could be made more efficient with a
// proper map.
type TaskLocalElement = (*libc::c_void, *libc::c_void, @LocalData);
// Has to be a pointer at outermost layer; the foreign call returns void *.
type TaskLocalMap = @mut ~[Option<TaskLocalElement>];
fn cleanup_task_local_map(map_ptr: *libc::c_void) {
unsafe {
assert!(!map_ptr.is_null());
// Get and keep the single reference that was created at the
// beginning.
let _map: TaskLocalMap = cast::transmute(map_ptr);
// All local_data will be destroyed along with the map.
}
}
// Gets the map from the runtime. Lazily initialises if not done so already.
unsafe fn get_local_map(handle: Handle) -> TaskLocalMap {
match handle {
OldHandle(task) => get_task_local_map(task),
NewHandle(local_storage) => get_newsched_local_map(local_storage)
}
}
unsafe fn get_task_local_map(task: *rust_task) -> TaskLocalMap {
extern fn cleanup_task_local_map_extern_cb(map_ptr: *libc::c_void) {
cleanup_task_local_map(map_ptr);
}
// Relies on the runtime initialising the pointer to null.
// Note: The map's box lives in TLS invisibly referenced once. Each time
// we retrieve it for get/set, we make another reference, which get/set
// drop when they finish. No "re-storing after modifying" is needed.
let map_ptr = rt::rust_get_task_local_data(task);
if map_ptr.is_null() {
let map: TaskLocalMap = @mut ~[];
// NB: This bumps the ref count before converting to an unsafe pointer,
// keeping the map alive until TLS is destroyed
rt::rust_set_task_local_data(task, cast::transmute(map));
rt::rust_task_local_data_atexit(task, cleanup_task_local_map_extern_cb);
map
} else {
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
map
}
}
unsafe fn get_newsched_local_map(local: *mut LocalStorage) -> TaskLocalMap {
match &mut *local {
&LocalStorage(map_ptr, Some(_)) => |
&LocalStorage(ref mut map_ptr, ref mut at_exit) => {
assert!((*map_ptr).is_null());
let map: TaskLocalMap = @mut ~[];
*map_ptr = cast::transmute(map);
let at_exit_fn: ~fn(*libc::c_void) = |p|cleanup_task_local_map(p);
*at_exit = Some(at_exit_fn);
return map;
}
}
}
unsafe fn key_to_key_value<T:'static>(key: LocalDataKey<T>) -> *libc::c_void {
// Keys are closures, which are (fnptr,envptr) pairs. Use fnptr.
// Use reinterpret_cast -- transmute would leak (forget) the closure.
let pair: (*libc::c_void, *libc::c_void) = cast::transmute_copy(&key);
pair.first()
}
// If returning Some(..), returns with @T with the map's reference. Careful!
unsafe fn local_data_lookup<T:'static>(
map: TaskLocalMap, key: LocalDataKey<T>)
-> Option<(uint, *libc::c_void)> {
let key_value = key_to_key_value(key);
let map_pos = (*map).iter().position(|entry|
match *entry {
Some((k,_,_)) => k == key_value,
None => false
}
);
do map_pos.map |index| {
//.get() is guaranteed because of "None { false }" above.
let (_, data_ptr, _) = (*map)[*index].get();
(*index, data_ptr)
}
}
unsafe fn local_get_helper<T:'static>(
handle: Handle, key: LocalDataKey<T>,
do_pop: bool) -> Option<@T> {
let map = get_local_map(handle);
// Interpreturn our findings from the map
do local_data_lookup(map, key).map |result| {
// A reference count magically appears on 'data' out of thin air. It
// was referenced in the local_data box, though, not here, so before
// overwriting the local_data_box we need to give an extra reference.
// We must also give an extra reference when not removing.
let (index, data_ptr) = *result;
let data: @T = cast::transmute(data_ptr);
cast::bump_box_refcount(data);
if do_pop {
map[index] = None;
}
data
}
}
pub unsafe fn local_pop<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(handle, key, true)
}
pub unsafe fn local_get<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(handle, key, false)
}
pub unsafe fn local_set<T:'static>(
handle: Handle, key: LocalDataKey<T>, data: @T) {
let map = get_local_map(handle);
// Store key+data as *voids. Data is invisibly referenced once; key isn't.
let keyval = key_to_key_value(key);
// We keep the data in two forms: one as an unsafe pointer, so we can get
// it back by casting; another in an existential box, so the reference we
// own on it can be dropped when the box is destroyed. The unsafe pointer
// does not have a reference associated with it, so it may become invalid
// when the box is destroyed.
let data_ptr = *cast::transmute::<&@T, &*libc::c_void>(&data);
let data_box = @data as @LocalData;
// Construct new entry to store in the map.
let new_entry = Some((keyval, data_ptr, data_box));
// Find a place to put it.
match local_data_lookup(map, key) {
Some((index, _old_data_ptr)) => {
// Key already had a value set, _old_data_ptr, whose reference
// will get dropped when the local_data box is overwritten.
map[index] = new_entry;
}
None => {
// Find an empty slot. If not, grow the vector.
match (*map).iter().position(|x| x.is_none()) {
Some(empty_index) => { map[empty_index] = new_entry; }
None => { map.push(new_entry); }
}
}
}
}
pub unsafe fn local_modify<T:'static>(
handle: Handle, key: LocalDataKey<T>,
modify_fn: &fn(Option<@T>) -> Option<@T>) {
// Could be more efficient by doing the lookup work, but this is easy.
let newdata = modify_fn(local_pop(handle, key));
if newdata.is_some() {
local_set(handle, key, newdata.unwrap());
}
}
| {
assert!(map_ptr.is_not_null());
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
return map;
} | conditional_block |
local_data_priv.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.
#[allow(missing_doc)];
use cast;
use cmp::Eq;
use libc;
use prelude::*;
use task::rt;
use local_data::LocalDataKey;
use super::rt::rust_task;
use rt::task::{Task, LocalStorage};
pub enum Handle {
OldHandle(*rust_task),
NewHandle(*mut LocalStorage)
}
impl Handle {
pub fn new() -> Handle {
use rt::{context, OldTaskContext};
use rt::local::Local;
unsafe {
match context() {
OldTaskContext => {
OldHandle(rt::rust_get_task())
}
_ => {
let task = Local::unsafe_borrow::<Task>();
NewHandle(&mut (*task).storage)
}
}
}
}
}
pub trait LocalData { }
impl<T:'static> LocalData for @T { }
impl Eq for @LocalData {
fn eq(&self, other: &@LocalData) -> bool {
unsafe {
let ptr_a: &(uint, uint) = cast::transmute(self);
let ptr_b: &(uint, uint) = cast::transmute(other);
return ptr_a == ptr_b;
}
}
fn ne(&self, other: &@LocalData) -> bool {!(*self).eq(other) }
}
// If TLS is used heavily in future, this could be made more efficient with a
// proper map.
type TaskLocalElement = (*libc::c_void, *libc::c_void, @LocalData);
// Has to be a pointer at outermost layer; the foreign call returns void *.
type TaskLocalMap = @mut ~[Option<TaskLocalElement>];
fn cleanup_task_local_map(map_ptr: *libc::c_void) {
unsafe {
assert!(!map_ptr.is_null());
// Get and keep the single reference that was created at the
// beginning.
let _map: TaskLocalMap = cast::transmute(map_ptr);
// All local_data will be destroyed along with the map.
}
}
// Gets the map from the runtime. Lazily initialises if not done so already.
unsafe fn get_local_map(handle: Handle) -> TaskLocalMap {
match handle {
OldHandle(task) => get_task_local_map(task),
NewHandle(local_storage) => get_newsched_local_map(local_storage)
}
}
unsafe fn get_task_local_map(task: *rust_task) -> TaskLocalMap {
extern fn cleanup_task_local_map_extern_cb(map_ptr: *libc::c_void) {
cleanup_task_local_map(map_ptr);
}
// Relies on the runtime initialising the pointer to null.
// Note: The map's box lives in TLS invisibly referenced once. Each time
// we retrieve it for get/set, we make another reference, which get/set
// drop when they finish. No "re-storing after modifying" is needed.
let map_ptr = rt::rust_get_task_local_data(task);
if map_ptr.is_null() {
let map: TaskLocalMap = @mut ~[];
// NB: This bumps the ref count before converting to an unsafe pointer,
// keeping the map alive until TLS is destroyed
rt::rust_set_task_local_data(task, cast::transmute(map));
rt::rust_task_local_data_atexit(task, cleanup_task_local_map_extern_cb);
map
} else {
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
map
}
}
unsafe fn get_newsched_local_map(local: *mut LocalStorage) -> TaskLocalMap {
match &mut *local {
&LocalStorage(map_ptr, Some(_)) => {
assert!(map_ptr.is_not_null());
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
return map;
}
&LocalStorage(ref mut map_ptr, ref mut at_exit) => {
assert!((*map_ptr).is_null());
let map: TaskLocalMap = @mut ~[];
*map_ptr = cast::transmute(map);
let at_exit_fn: ~fn(*libc::c_void) = |p|cleanup_task_local_map(p);
*at_exit = Some(at_exit_fn);
return map;
}
}
}
unsafe fn | <T:'static>(key: LocalDataKey<T>) -> *libc::c_void {
// Keys are closures, which are (fnptr,envptr) pairs. Use fnptr.
// Use reinterpret_cast -- transmute would leak (forget) the closure.
let pair: (*libc::c_void, *libc::c_void) = cast::transmute_copy(&key);
pair.first()
}
// If returning Some(..), returns with @T with the map's reference. Careful!
unsafe fn local_data_lookup<T:'static>(
map: TaskLocalMap, key: LocalDataKey<T>)
-> Option<(uint, *libc::c_void)> {
let key_value = key_to_key_value(key);
let map_pos = (*map).iter().position(|entry|
match *entry {
Some((k,_,_)) => k == key_value,
None => false
}
);
do map_pos.map |index| {
//.get() is guaranteed because of "None { false }" above.
let (_, data_ptr, _) = (*map)[*index].get();
(*index, data_ptr)
}
}
unsafe fn local_get_helper<T:'static>(
handle: Handle, key: LocalDataKey<T>,
do_pop: bool) -> Option<@T> {
let map = get_local_map(handle);
// Interpreturn our findings from the map
do local_data_lookup(map, key).map |result| {
// A reference count magically appears on 'data' out of thin air. It
// was referenced in the local_data box, though, not here, so before
// overwriting the local_data_box we need to give an extra reference.
// We must also give an extra reference when not removing.
let (index, data_ptr) = *result;
let data: @T = cast::transmute(data_ptr);
cast::bump_box_refcount(data);
if do_pop {
map[index] = None;
}
data
}
}
pub unsafe fn local_pop<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(handle, key, true)
}
pub unsafe fn local_get<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(handle, key, false)
}
pub unsafe fn local_set<T:'static>(
handle: Handle, key: LocalDataKey<T>, data: @T) {
let map = get_local_map(handle);
// Store key+data as *voids. Data is invisibly referenced once; key isn't.
let keyval = key_to_key_value(key);
// We keep the data in two forms: one as an unsafe pointer, so we can get
// it back by casting; another in an existential box, so the reference we
// own on it can be dropped when the box is destroyed. The unsafe pointer
// does not have a reference associated with it, so it may become invalid
// when the box is destroyed.
let data_ptr = *cast::transmute::<&@T, &*libc::c_void>(&data);
let data_box = @data as @LocalData;
// Construct new entry to store in the map.
let new_entry = Some((keyval, data_ptr, data_box));
// Find a place to put it.
match local_data_lookup(map, key) {
Some((index, _old_data_ptr)) => {
// Key already had a value set, _old_data_ptr, whose reference
// will get dropped when the local_data box is overwritten.
map[index] = new_entry;
}
None => {
// Find an empty slot. If not, grow the vector.
match (*map).iter().position(|x| x.is_none()) {
Some(empty_index) => { map[empty_index] = new_entry; }
None => { map.push(new_entry); }
}
}
}
}
pub unsafe fn local_modify<T:'static>(
handle: Handle, key: LocalDataKey<T>,
modify_fn: &fn(Option<@T>) -> Option<@T>) {
// Could be more efficient by doing the lookup work, but this is easy.
let newdata = modify_fn(local_pop(handle, key));
if newdata.is_some() {
local_set(handle, key, newdata.unwrap());
}
}
| key_to_key_value | identifier_name |
local_data_priv.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.
#[allow(missing_doc)];
use cast;
use cmp::Eq;
use libc;
use prelude::*;
use task::rt;
use local_data::LocalDataKey;
use super::rt::rust_task;
use rt::task::{Task, LocalStorage};
pub enum Handle {
OldHandle(*rust_task),
NewHandle(*mut LocalStorage)
}
impl Handle {
pub fn new() -> Handle {
use rt::{context, OldTaskContext};
use rt::local::Local;
unsafe {
match context() {
OldTaskContext => {
OldHandle(rt::rust_get_task())
}
_ => {
let task = Local::unsafe_borrow::<Task>();
NewHandle(&mut (*task).storage)
}
}
}
}
}
pub trait LocalData { }
impl<T:'static> LocalData for @T { }
impl Eq for @LocalData {
fn eq(&self, other: &@LocalData) -> bool {
unsafe {
let ptr_a: &(uint, uint) = cast::transmute(self);
let ptr_b: &(uint, uint) = cast::transmute(other);
return ptr_a == ptr_b;
}
}
fn ne(&self, other: &@LocalData) -> bool {!(*self).eq(other) }
}
// If TLS is used heavily in future, this could be made more efficient with a
// proper map.
type TaskLocalElement = (*libc::c_void, *libc::c_void, @LocalData);
// Has to be a pointer at outermost layer; the foreign call returns void *.
type TaskLocalMap = @mut ~[Option<TaskLocalElement>];
fn cleanup_task_local_map(map_ptr: *libc::c_void) { | assert!(!map_ptr.is_null());
// Get and keep the single reference that was created at the
// beginning.
let _map: TaskLocalMap = cast::transmute(map_ptr);
// All local_data will be destroyed along with the map.
}
}
// Gets the map from the runtime. Lazily initialises if not done so already.
unsafe fn get_local_map(handle: Handle) -> TaskLocalMap {
match handle {
OldHandle(task) => get_task_local_map(task),
NewHandle(local_storage) => get_newsched_local_map(local_storage)
}
}
unsafe fn get_task_local_map(task: *rust_task) -> TaskLocalMap {
extern fn cleanup_task_local_map_extern_cb(map_ptr: *libc::c_void) {
cleanup_task_local_map(map_ptr);
}
// Relies on the runtime initialising the pointer to null.
// Note: The map's box lives in TLS invisibly referenced once. Each time
// we retrieve it for get/set, we make another reference, which get/set
// drop when they finish. No "re-storing after modifying" is needed.
let map_ptr = rt::rust_get_task_local_data(task);
if map_ptr.is_null() {
let map: TaskLocalMap = @mut ~[];
// NB: This bumps the ref count before converting to an unsafe pointer,
// keeping the map alive until TLS is destroyed
rt::rust_set_task_local_data(task, cast::transmute(map));
rt::rust_task_local_data_atexit(task, cleanup_task_local_map_extern_cb);
map
} else {
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
map
}
}
unsafe fn get_newsched_local_map(local: *mut LocalStorage) -> TaskLocalMap {
match &mut *local {
&LocalStorage(map_ptr, Some(_)) => {
assert!(map_ptr.is_not_null());
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
return map;
}
&LocalStorage(ref mut map_ptr, ref mut at_exit) => {
assert!((*map_ptr).is_null());
let map: TaskLocalMap = @mut ~[];
*map_ptr = cast::transmute(map);
let at_exit_fn: ~fn(*libc::c_void) = |p|cleanup_task_local_map(p);
*at_exit = Some(at_exit_fn);
return map;
}
}
}
unsafe fn key_to_key_value<T:'static>(key: LocalDataKey<T>) -> *libc::c_void {
// Keys are closures, which are (fnptr,envptr) pairs. Use fnptr.
// Use reinterpret_cast -- transmute would leak (forget) the closure.
let pair: (*libc::c_void, *libc::c_void) = cast::transmute_copy(&key);
pair.first()
}
// If returning Some(..), returns with @T with the map's reference. Careful!
unsafe fn local_data_lookup<T:'static>(
map: TaskLocalMap, key: LocalDataKey<T>)
-> Option<(uint, *libc::c_void)> {
let key_value = key_to_key_value(key);
let map_pos = (*map).iter().position(|entry|
match *entry {
Some((k,_,_)) => k == key_value,
None => false
}
);
do map_pos.map |index| {
//.get() is guaranteed because of "None { false }" above.
let (_, data_ptr, _) = (*map)[*index].get();
(*index, data_ptr)
}
}
unsafe fn local_get_helper<T:'static>(
handle: Handle, key: LocalDataKey<T>,
do_pop: bool) -> Option<@T> {
let map = get_local_map(handle);
// Interpreturn our findings from the map
do local_data_lookup(map, key).map |result| {
// A reference count magically appears on 'data' out of thin air. It
// was referenced in the local_data box, though, not here, so before
// overwriting the local_data_box we need to give an extra reference.
// We must also give an extra reference when not removing.
let (index, data_ptr) = *result;
let data: @T = cast::transmute(data_ptr);
cast::bump_box_refcount(data);
if do_pop {
map[index] = None;
}
data
}
}
pub unsafe fn local_pop<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(handle, key, true)
}
pub unsafe fn local_get<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(handle, key, false)
}
pub unsafe fn local_set<T:'static>(
handle: Handle, key: LocalDataKey<T>, data: @T) {
let map = get_local_map(handle);
// Store key+data as *voids. Data is invisibly referenced once; key isn't.
let keyval = key_to_key_value(key);
// We keep the data in two forms: one as an unsafe pointer, so we can get
// it back by casting; another in an existential box, so the reference we
// own on it can be dropped when the box is destroyed. The unsafe pointer
// does not have a reference associated with it, so it may become invalid
// when the box is destroyed.
let data_ptr = *cast::transmute::<&@T, &*libc::c_void>(&data);
let data_box = @data as @LocalData;
// Construct new entry to store in the map.
let new_entry = Some((keyval, data_ptr, data_box));
// Find a place to put it.
match local_data_lookup(map, key) {
Some((index, _old_data_ptr)) => {
// Key already had a value set, _old_data_ptr, whose reference
// will get dropped when the local_data box is overwritten.
map[index] = new_entry;
}
None => {
// Find an empty slot. If not, grow the vector.
match (*map).iter().position(|x| x.is_none()) {
Some(empty_index) => { map[empty_index] = new_entry; }
None => { map.push(new_entry); }
}
}
}
}
pub unsafe fn local_modify<T:'static>(
handle: Handle, key: LocalDataKey<T>,
modify_fn: &fn(Option<@T>) -> Option<@T>) {
// Could be more efficient by doing the lookup work, but this is easy.
let newdata = modify_fn(local_pop(handle, key));
if newdata.is_some() {
local_set(handle, key, newdata.unwrap());
}
} | unsafe { | random_line_split |
local_data_priv.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.
#[allow(missing_doc)];
use cast;
use cmp::Eq;
use libc;
use prelude::*;
use task::rt;
use local_data::LocalDataKey;
use super::rt::rust_task;
use rt::task::{Task, LocalStorage};
pub enum Handle {
OldHandle(*rust_task),
NewHandle(*mut LocalStorage)
}
impl Handle {
pub fn new() -> Handle {
use rt::{context, OldTaskContext};
use rt::local::Local;
unsafe {
match context() {
OldTaskContext => {
OldHandle(rt::rust_get_task())
}
_ => {
let task = Local::unsafe_borrow::<Task>();
NewHandle(&mut (*task).storage)
}
}
}
}
}
pub trait LocalData { }
impl<T:'static> LocalData for @T { }
impl Eq for @LocalData {
fn eq(&self, other: &@LocalData) -> bool {
unsafe {
let ptr_a: &(uint, uint) = cast::transmute(self);
let ptr_b: &(uint, uint) = cast::transmute(other);
return ptr_a == ptr_b;
}
}
fn ne(&self, other: &@LocalData) -> bool {!(*self).eq(other) }
}
// If TLS is used heavily in future, this could be made more efficient with a
// proper map.
type TaskLocalElement = (*libc::c_void, *libc::c_void, @LocalData);
// Has to be a pointer at outermost layer; the foreign call returns void *.
type TaskLocalMap = @mut ~[Option<TaskLocalElement>];
fn cleanup_task_local_map(map_ptr: *libc::c_void) {
unsafe {
assert!(!map_ptr.is_null());
// Get and keep the single reference that was created at the
// beginning.
let _map: TaskLocalMap = cast::transmute(map_ptr);
// All local_data will be destroyed along with the map.
}
}
// Gets the map from the runtime. Lazily initialises if not done so already.
unsafe fn get_local_map(handle: Handle) -> TaskLocalMap {
match handle {
OldHandle(task) => get_task_local_map(task),
NewHandle(local_storage) => get_newsched_local_map(local_storage)
}
}
unsafe fn get_task_local_map(task: *rust_task) -> TaskLocalMap {
extern fn cleanup_task_local_map_extern_cb(map_ptr: *libc::c_void) {
cleanup_task_local_map(map_ptr);
}
// Relies on the runtime initialising the pointer to null.
// Note: The map's box lives in TLS invisibly referenced once. Each time
// we retrieve it for get/set, we make another reference, which get/set
// drop when they finish. No "re-storing after modifying" is needed.
let map_ptr = rt::rust_get_task_local_data(task);
if map_ptr.is_null() {
let map: TaskLocalMap = @mut ~[];
// NB: This bumps the ref count before converting to an unsafe pointer,
// keeping the map alive until TLS is destroyed
rt::rust_set_task_local_data(task, cast::transmute(map));
rt::rust_task_local_data_atexit(task, cleanup_task_local_map_extern_cb);
map
} else {
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
map
}
}
unsafe fn get_newsched_local_map(local: *mut LocalStorage) -> TaskLocalMap {
match &mut *local {
&LocalStorage(map_ptr, Some(_)) => {
assert!(map_ptr.is_not_null());
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
return map;
}
&LocalStorage(ref mut map_ptr, ref mut at_exit) => {
assert!((*map_ptr).is_null());
let map: TaskLocalMap = @mut ~[];
*map_ptr = cast::transmute(map);
let at_exit_fn: ~fn(*libc::c_void) = |p|cleanup_task_local_map(p);
*at_exit = Some(at_exit_fn);
return map;
}
}
}
unsafe fn key_to_key_value<T:'static>(key: LocalDataKey<T>) -> *libc::c_void {
// Keys are closures, which are (fnptr,envptr) pairs. Use fnptr.
// Use reinterpret_cast -- transmute would leak (forget) the closure.
let pair: (*libc::c_void, *libc::c_void) = cast::transmute_copy(&key);
pair.first()
}
// If returning Some(..), returns with @T with the map's reference. Careful!
unsafe fn local_data_lookup<T:'static>(
map: TaskLocalMap, key: LocalDataKey<T>)
-> Option<(uint, *libc::c_void)> {
let key_value = key_to_key_value(key);
let map_pos = (*map).iter().position(|entry|
match *entry {
Some((k,_,_)) => k == key_value,
None => false
}
);
do map_pos.map |index| {
//.get() is guaranteed because of "None { false }" above.
let (_, data_ptr, _) = (*map)[*index].get();
(*index, data_ptr)
}
}
unsafe fn local_get_helper<T:'static>(
handle: Handle, key: LocalDataKey<T>,
do_pop: bool) -> Option<@T> {
let map = get_local_map(handle);
// Interpreturn our findings from the map
do local_data_lookup(map, key).map |result| {
// A reference count magically appears on 'data' out of thin air. It
// was referenced in the local_data box, though, not here, so before
// overwriting the local_data_box we need to give an extra reference.
// We must also give an extra reference when not removing.
let (index, data_ptr) = *result;
let data: @T = cast::transmute(data_ptr);
cast::bump_box_refcount(data);
if do_pop {
map[index] = None;
}
data
}
}
pub unsafe fn local_pop<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(handle, key, true)
}
pub unsafe fn local_get<T:'static>(
handle: Handle,
key: LocalDataKey<T>) -> Option<@T> |
pub unsafe fn local_set<T:'static>(
handle: Handle, key: LocalDataKey<T>, data: @T) {
let map = get_local_map(handle);
// Store key+data as *voids. Data is invisibly referenced once; key isn't.
let keyval = key_to_key_value(key);
// We keep the data in two forms: one as an unsafe pointer, so we can get
// it back by casting; another in an existential box, so the reference we
// own on it can be dropped when the box is destroyed. The unsafe pointer
// does not have a reference associated with it, so it may become invalid
// when the box is destroyed.
let data_ptr = *cast::transmute::<&@T, &*libc::c_void>(&data);
let data_box = @data as @LocalData;
// Construct new entry to store in the map.
let new_entry = Some((keyval, data_ptr, data_box));
// Find a place to put it.
match local_data_lookup(map, key) {
Some((index, _old_data_ptr)) => {
// Key already had a value set, _old_data_ptr, whose reference
// will get dropped when the local_data box is overwritten.
map[index] = new_entry;
}
None => {
// Find an empty slot. If not, grow the vector.
match (*map).iter().position(|x| x.is_none()) {
Some(empty_index) => { map[empty_index] = new_entry; }
None => { map.push(new_entry); }
}
}
}
}
pub unsafe fn local_modify<T:'static>(
handle: Handle, key: LocalDataKey<T>,
modify_fn: &fn(Option<@T>) -> Option<@T>) {
// Could be more efficient by doing the lookup work, but this is easy.
let newdata = modify_fn(local_pop(handle, key));
if newdata.is_some() {
local_set(handle, key, newdata.unwrap());
}
}
| {
local_get_helper(handle, key, false)
} | identifier_body |
type-infer-generalize-ty-var.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
#![allow(unused_assignments)]
#![allow(unused_variables)]
// Test a scenario where we generate a constraint like `?1 <: &?2`.
// In such a case, it is important that we instantiate `?1` with `&?3`
// where `?3 <:?2`, and not with `&?2`. This is a regression test for
// #18653. The important thing is that we build.
use std::cell::RefCell;
enum Wrap<A> {
WrapSome(A),
WrapNone
}
use Wrap::*;
struct T;
struct U;
trait Get<T:?Sized> {
fn get(&self) -> &T;
}
impl Get<MyShow +'static> for Wrap<T> {
fn | (&self) -> &(MyShow +'static) {
static x: usize = 42;
&x
}
}
impl Get<usize> for Wrap<U> {
fn get(&self) -> &usize {
static x: usize = 55;
&x
}
}
trait MyShow { fn dummy(&self) { } }
impl<'a> MyShow for &'a (MyShow + 'a) { }
impl MyShow for usize { }
fn constrain<'a>(rc: RefCell<&'a (MyShow + 'a)>) { }
fn main() {
let mut collection: Wrap<_> = WrapNone;
{
let __arg0 = Get::get(&collection);
let __args_cell = RefCell::new(__arg0);
constrain(__args_cell);
}
collection = WrapSome(T);
}
| get | identifier_name |
type-infer-generalize-ty-var.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
#![allow(unused_assignments)]
#![allow(unused_variables)]
// Test a scenario where we generate a constraint like `?1 <: &?2`.
// In such a case, it is important that we instantiate `?1` with `&?3`
// where `?3 <:?2`, and not with `&?2`. This is a regression test for
// #18653. The important thing is that we build.
use std::cell::RefCell;
enum Wrap<A> {
WrapSome(A),
WrapNone
}
use Wrap::*;
struct T;
struct U;
trait Get<T:?Sized> {
fn get(&self) -> &T;
}
impl Get<MyShow +'static> for Wrap<T> { | static x: usize = 42;
&x
}
}
impl Get<usize> for Wrap<U> {
fn get(&self) -> &usize {
static x: usize = 55;
&x
}
}
trait MyShow { fn dummy(&self) { } }
impl<'a> MyShow for &'a (MyShow + 'a) { }
impl MyShow for usize { }
fn constrain<'a>(rc: RefCell<&'a (MyShow + 'a)>) { }
fn main() {
let mut collection: Wrap<_> = WrapNone;
{
let __arg0 = Get::get(&collection);
let __args_cell = RefCell::new(__arg0);
constrain(__args_cell);
}
collection = WrapSome(T);
} | fn get(&self) -> &(MyShow + 'static) { | random_line_split |
primitives_scale.rs | extern crate rand;
extern crate kiss3d;
extern crate nalgebra as na;
use rand::random;
use na::{Vec3, Translation, RotationWithTranslation};
use kiss3d::window::Window;
use kiss3d::light::Light;
fn main() {
let mut window = Window::new("Kiss3d: primitives_scale");
// NOTE: scaling is not possible.
for i in 0usize.. 11 {
let dim: f32 = random::<f32>() / 2.0;
let dim2 = dim / 2.0;
let offset = i as f32 * 1.0 - 5.0;
let mut cu = window.add_cube(dim2, dim2, dim2);
let mut sp = window.add_sphere(dim2);
let mut co = window.add_cone(dim2, dim);
let mut cy = window.add_cylinder(dim2, dim);
let mut ca = window.add_capsule(dim2, dim);
cu.append_translation(&Vec3::new(offset, 1.0, 0.0));
sp.append_translation(&Vec3::new(offset, -1.0, 0.0));
co.append_translation(&Vec3::new(offset, 2.0, 0.0));
cy.append_translation(&Vec3::new(offset, -2.0, 0.0)); | sp.set_color(random(), random(), random());
co.set_color(random(), random(), random());
cy.set_color(random(), random(), random());
ca.set_color(random(), random(), random());
}
window.set_light(Light::StickToCamera);
while window.render() {
// XXX: applying this to each object individually became complicated…
window.scene_mut().append_rotation_wrt_center(&Vec3::new(0.0f32, 0.014, 0.0));
}
} | ca.append_translation(&Vec3::new(offset, 0.0, 0.0));
cu.set_color(random(), random(), random()); | random_line_split |
primitives_scale.rs | extern crate rand;
extern crate kiss3d;
extern crate nalgebra as na;
use rand::random;
use na::{Vec3, Translation, RotationWithTranslation};
use kiss3d::window::Window;
use kiss3d::light::Light;
fn main() | ca.append_translation(&Vec3::new(offset, 0.0, 0.0));
cu.set_color(random(), random(), random());
sp.set_color(random(), random(), random());
co.set_color(random(), random(), random());
cy.set_color(random(), random(), random());
ca.set_color(random(), random(), random());
}
window.set_light(Light::StickToCamera);
while window.render() {
// XXX: applying this to each object individually became complicated…
window.scene_mut().append_rotation_wrt_center(&Vec3::new(0.0f32, 0.014, 0.0));
}
}
| {
let mut window = Window::new("Kiss3d: primitives_scale");
// NOTE: scaling is not possible.
for i in 0usize .. 11 {
let dim: f32 = random::<f32>() / 2.0;
let dim2 = dim / 2.0;
let offset = i as f32 * 1.0 - 5.0;
let mut cu = window.add_cube(dim2, dim2, dim2);
let mut sp = window.add_sphere(dim2);
let mut co = window.add_cone(dim2, dim);
let mut cy = window.add_cylinder(dim2, dim);
let mut ca = window.add_capsule(dim2, dim);
cu.append_translation(&Vec3::new(offset, 1.0, 0.0));
sp.append_translation(&Vec3::new(offset, -1.0, 0.0));
co.append_translation(&Vec3::new(offset, 2.0, 0.0));
cy.append_translation(&Vec3::new(offset, -2.0, 0.0)); | identifier_body |
primitives_scale.rs | extern crate rand;
extern crate kiss3d;
extern crate nalgebra as na;
use rand::random;
use na::{Vec3, Translation, RotationWithTranslation};
use kiss3d::window::Window;
use kiss3d::light::Light;
fn | () {
let mut window = Window::new("Kiss3d: primitives_scale");
// NOTE: scaling is not possible.
for i in 0usize.. 11 {
let dim: f32 = random::<f32>() / 2.0;
let dim2 = dim / 2.0;
let offset = i as f32 * 1.0 - 5.0;
let mut cu = window.add_cube(dim2, dim2, dim2);
let mut sp = window.add_sphere(dim2);
let mut co = window.add_cone(dim2, dim);
let mut cy = window.add_cylinder(dim2, dim);
let mut ca = window.add_capsule(dim2, dim);
cu.append_translation(&Vec3::new(offset, 1.0, 0.0));
sp.append_translation(&Vec3::new(offset, -1.0, 0.0));
co.append_translation(&Vec3::new(offset, 2.0, 0.0));
cy.append_translation(&Vec3::new(offset, -2.0, 0.0));
ca.append_translation(&Vec3::new(offset, 0.0, 0.0));
cu.set_color(random(), random(), random());
sp.set_color(random(), random(), random());
co.set_color(random(), random(), random());
cy.set_color(random(), random(), random());
ca.set_color(random(), random(), random());
}
window.set_light(Light::StickToCamera);
while window.render() {
// XXX: applying this to each object individually became complicated…
window.scene_mut().append_rotation_wrt_center(&Vec3::new(0.0f32, 0.014, 0.0));
}
}
| main | identifier_name |
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Context`.
#[derive(Clone)]
pub struct Gfx(Rc<Context>);
impl Gfx {
pub fn new(ctx: Context) -> Gfx {
Gfx(Rc::new(ctx))
}
}
impl Deref for Gfx {
type Target = Context;
fn deref(&self) -> &Context {
&*self.0
}
}
/// Context handle object.
///
/// Manage `glium::Display` context and current frame.
pub struct Context {
pub display: Display,
frame: UnsafeCell<Option<RefCell<Frame>>>,
clear_color: (f32, f32, f32, f32),
}
impl Context {
/// Builds OpenGL context and create a window.
pub fn create<T: ToString>(title: T, (width, height): (u32, u32)) -> Context {
let display = WindowBuilder::new()
.with_title(title.to_string())
.with_dimensions(width, height)
.with_depth_buffer(24)
.with_vsync()
.build_glium()
.unwrap();
Context {
display: display,
frame: UnsafeCell::new(None),
clear_color: (0.0, 0.0, 0.0, 0.0),
}
}
/// Sets clear color.
pub fn clear_color(self, r: f32, g: f32, b: f32, a: f32) -> Context {
Context { clear_color: (r, g, b, a),..self }
}
/// Into be a reference.
pub fn gfx(self) -> Gfx {
Gfx::new(self)
}
unsafe fn get_cell(&self) -> &mut Option<RefCell<Frame>> {
self.frame.get().as_mut().unwrap()
}
/// Start a new frame.
fn start_frame(&self) {
unsafe {
let mut cell = self.get_cell();
if cell.is_some() {
println!("Frame has already started.");
} else {
let mut frame = self.display.draw();
frame.clear_color_and_depth(self.clear_color, 1.0);
*cell = Some(RefCell::new(frame));
}
}
}
/// Get frame immutable reference.
/// # Panics
/// Panic if frame not created or something is mutable borrowing the frame.
pub fn get_frame(&self) -> Ref<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow()
}
}
/// Get frame mutable reference.
/// # Panics
/// Panic if something is borrowing the frame.
pub fn get_frame_mut(&self) -> RefMut<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow_mut()
}
}
/// End the frame.
fn end_frame(&self) -> Result<(), SwapBuffersError> {
unsafe {
let mut cell = self.get_cell();
if cell.is_none() {
println!("Frame has already ended.");
Ok(())
} else {
// Test whether the frame is borrowed.
// TODO: Waiting `borrow_state` stabilization:
// https://github.com/rust-lang/rust/issues/27733
let _ = cell.as_ref().unwrap().borrow_mut();
let frame = cell.take().unwrap().into_inner();
frame.finish()
}
}
}
/// Start a new frame and auto end it.
pub fn frame<F>(&self, f: F) -> Result<(), SwapBuffersError>
where F: FnOnce()
{
// TODO: Refactor and error handling.
self.start_frame();
f();
self.end_frame()
}
/// Returns the ratio between the backing framebuffer resolution
/// and the window size in screen pixels.
pub fn hidpi_factor(&self) -> f32 {
self.display.get_window().unwrap().hidpi_factor() | }
} | random_line_split |
|
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Context`.
#[derive(Clone)]
pub struct Gfx(Rc<Context>);
impl Gfx {
pub fn new(ctx: Context) -> Gfx {
Gfx(Rc::new(ctx))
}
}
impl Deref for Gfx {
type Target = Context;
fn deref(&self) -> &Context {
&*self.0
}
}
/// Context handle object.
///
/// Manage `glium::Display` context and current frame.
pub struct Context {
pub display: Display,
frame: UnsafeCell<Option<RefCell<Frame>>>,
clear_color: (f32, f32, f32, f32),
}
impl Context {
/// Builds OpenGL context and create a window.
pub fn create<T: ToString>(title: T, (width, height): (u32, u32)) -> Context {
let display = WindowBuilder::new()
.with_title(title.to_string())
.with_dimensions(width, height)
.with_depth_buffer(24)
.with_vsync()
.build_glium()
.unwrap();
Context {
display: display,
frame: UnsafeCell::new(None),
clear_color: (0.0, 0.0, 0.0, 0.0),
}
}
/// Sets clear color.
pub fn clear_color(self, r: f32, g: f32, b: f32, a: f32) -> Context {
Context { clear_color: (r, g, b, a),..self }
}
/// Into be a reference.
pub fn gfx(self) -> Gfx {
Gfx::new(self)
}
unsafe fn get_cell(&self) -> &mut Option<RefCell<Frame>> {
self.frame.get().as_mut().unwrap()
}
/// Start a new frame.
fn start_frame(&self) {
unsafe {
let mut cell = self.get_cell();
if cell.is_some() {
println!("Frame has already started.");
} else {
let mut frame = self.display.draw();
frame.clear_color_and_depth(self.clear_color, 1.0);
*cell = Some(RefCell::new(frame));
}
}
}
/// Get frame immutable reference.
/// # Panics
/// Panic if frame not created or something is mutable borrowing the frame.
pub fn | (&self) -> Ref<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow()
}
}
/// Get frame mutable reference.
/// # Panics
/// Panic if something is borrowing the frame.
pub fn get_frame_mut(&self) -> RefMut<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow_mut()
}
}
/// End the frame.
fn end_frame(&self) -> Result<(), SwapBuffersError> {
unsafe {
let mut cell = self.get_cell();
if cell.is_none() {
println!("Frame has already ended.");
Ok(())
} else {
// Test whether the frame is borrowed.
// TODO: Waiting `borrow_state` stabilization:
// https://github.com/rust-lang/rust/issues/27733
let _ = cell.as_ref().unwrap().borrow_mut();
let frame = cell.take().unwrap().into_inner();
frame.finish()
}
}
}
/// Start a new frame and auto end it.
pub fn frame<F>(&self, f: F) -> Result<(), SwapBuffersError>
where F: FnOnce()
{
// TODO: Refactor and error handling.
self.start_frame();
f();
self.end_frame()
}
/// Returns the ratio between the backing framebuffer resolution
/// and the window size in screen pixels.
pub fn hidpi_factor(&self) -> f32 {
self.display.get_window().unwrap().hidpi_factor()
}
}
| get_frame | identifier_name |
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Context`.
#[derive(Clone)]
pub struct Gfx(Rc<Context>);
impl Gfx {
pub fn new(ctx: Context) -> Gfx {
Gfx(Rc::new(ctx))
}
}
impl Deref for Gfx {
type Target = Context;
fn deref(&self) -> &Context {
&*self.0
}
}
/// Context handle object.
///
/// Manage `glium::Display` context and current frame.
pub struct Context {
pub display: Display,
frame: UnsafeCell<Option<RefCell<Frame>>>,
clear_color: (f32, f32, f32, f32),
}
impl Context {
/// Builds OpenGL context and create a window.
pub fn create<T: ToString>(title: T, (width, height): (u32, u32)) -> Context {
let display = WindowBuilder::new()
.with_title(title.to_string())
.with_dimensions(width, height)
.with_depth_buffer(24)
.with_vsync()
.build_glium()
.unwrap();
Context {
display: display,
frame: UnsafeCell::new(None),
clear_color: (0.0, 0.0, 0.0, 0.0),
}
}
/// Sets clear color.
pub fn clear_color(self, r: f32, g: f32, b: f32, a: f32) -> Context {
Context { clear_color: (r, g, b, a),..self }
}
/// Into be a reference.
pub fn gfx(self) -> Gfx {
Gfx::new(self)
}
unsafe fn get_cell(&self) -> &mut Option<RefCell<Frame>> {
self.frame.get().as_mut().unwrap()
}
/// Start a new frame.
fn start_frame(&self) {
unsafe {
let mut cell = self.get_cell();
if cell.is_some() {
println!("Frame has already started.");
} else |
}
}
/// Get frame immutable reference.
/// # Panics
/// Panic if frame not created or something is mutable borrowing the frame.
pub fn get_frame(&self) -> Ref<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow()
}
}
/// Get frame mutable reference.
/// # Panics
/// Panic if something is borrowing the frame.
pub fn get_frame_mut(&self) -> RefMut<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow_mut()
}
}
/// End the frame.
fn end_frame(&self) -> Result<(), SwapBuffersError> {
unsafe {
let mut cell = self.get_cell();
if cell.is_none() {
println!("Frame has already ended.");
Ok(())
} else {
// Test whether the frame is borrowed.
// TODO: Waiting `borrow_state` stabilization:
// https://github.com/rust-lang/rust/issues/27733
let _ = cell.as_ref().unwrap().borrow_mut();
let frame = cell.take().unwrap().into_inner();
frame.finish()
}
}
}
/// Start a new frame and auto end it.
pub fn frame<F>(&self, f: F) -> Result<(), SwapBuffersError>
where F: FnOnce()
{
// TODO: Refactor and error handling.
self.start_frame();
f();
self.end_frame()
}
/// Returns the ratio between the backing framebuffer resolution
/// and the window size in screen pixels.
pub fn hidpi_factor(&self) -> f32 {
self.display.get_window().unwrap().hidpi_factor()
}
}
| {
let mut frame = self.display.draw();
frame.clear_color_and_depth(self.clear_color, 1.0);
*cell = Some(RefCell::new(frame));
} | conditional_block |
context.rs | //! Manage OpenGL context and window.
use std::string::ToString;
use std::rc::Rc;
use std::ops::Deref;
use std::cell::{UnsafeCell, RefCell, RefMut, Ref};
use glium::{Display, DisplayBuild};
use glium::glutin::WindowBuilder;
pub use glium::{Frame, Surface, SwapBuffersError, DrawError};
/// Just a reference of `Context`.
#[derive(Clone)]
pub struct Gfx(Rc<Context>);
impl Gfx {
pub fn new(ctx: Context) -> Gfx |
}
impl Deref for Gfx {
type Target = Context;
fn deref(&self) -> &Context {
&*self.0
}
}
/// Context handle object.
///
/// Manage `glium::Display` context and current frame.
pub struct Context {
pub display: Display,
frame: UnsafeCell<Option<RefCell<Frame>>>,
clear_color: (f32, f32, f32, f32),
}
impl Context {
/// Builds OpenGL context and create a window.
pub fn create<T: ToString>(title: T, (width, height): (u32, u32)) -> Context {
let display = WindowBuilder::new()
.with_title(title.to_string())
.with_dimensions(width, height)
.with_depth_buffer(24)
.with_vsync()
.build_glium()
.unwrap();
Context {
display: display,
frame: UnsafeCell::new(None),
clear_color: (0.0, 0.0, 0.0, 0.0),
}
}
/// Sets clear color.
pub fn clear_color(self, r: f32, g: f32, b: f32, a: f32) -> Context {
Context { clear_color: (r, g, b, a),..self }
}
/// Into be a reference.
pub fn gfx(self) -> Gfx {
Gfx::new(self)
}
unsafe fn get_cell(&self) -> &mut Option<RefCell<Frame>> {
self.frame.get().as_mut().unwrap()
}
/// Start a new frame.
fn start_frame(&self) {
unsafe {
let mut cell = self.get_cell();
if cell.is_some() {
println!("Frame has already started.");
} else {
let mut frame = self.display.draw();
frame.clear_color_and_depth(self.clear_color, 1.0);
*cell = Some(RefCell::new(frame));
}
}
}
/// Get frame immutable reference.
/// # Panics
/// Panic if frame not created or something is mutable borrowing the frame.
pub fn get_frame(&self) -> Ref<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow()
}
}
/// Get frame mutable reference.
/// # Panics
/// Panic if something is borrowing the frame.
pub fn get_frame_mut(&self) -> RefMut<Frame> {
unsafe {
let cell = self.get_cell();
if cell.is_none() {
panic!("Frame not exist.")
}
cell.as_ref().unwrap().borrow_mut()
}
}
/// End the frame.
fn end_frame(&self) -> Result<(), SwapBuffersError> {
unsafe {
let mut cell = self.get_cell();
if cell.is_none() {
println!("Frame has already ended.");
Ok(())
} else {
// Test whether the frame is borrowed.
// TODO: Waiting `borrow_state` stabilization:
// https://github.com/rust-lang/rust/issues/27733
let _ = cell.as_ref().unwrap().borrow_mut();
let frame = cell.take().unwrap().into_inner();
frame.finish()
}
}
}
/// Start a new frame and auto end it.
pub fn frame<F>(&self, f: F) -> Result<(), SwapBuffersError>
where F: FnOnce()
{
// TODO: Refactor and error handling.
self.start_frame();
f();
self.end_frame()
}
/// Returns the ratio between the backing framebuffer resolution
/// and the window size in screen pixels.
pub fn hidpi_factor(&self) -> f32 {
self.display.get_window().unwrap().hidpi_factor()
}
}
| {
Gfx(Rc::new(ctx))
} | identifier_body |
error.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use crate::dom::bindings::codegen::PrototypeList::proto_id_to_name;
use crate::dom::bindings::conversions::root_from_object;
use crate::dom::bindings::conversions::{
ConversionResult, FromJSValConvertible, ToJSValConvertible,
};
use crate::dom::bindings::str::USVString;
use crate::dom::domexception::{DOMErrorName, DOMException};
use crate::dom::globalscope::GlobalScope;
#[cfg(feature = "js_backtrace")]
use backtrace::Backtrace;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsval::UndefinedValue;
use js::rust::wrappers::JS_ErrorFromException;
use js::rust::wrappers::JS_GetPendingException;
use js::rust::wrappers::JS_SetPendingException;
use js::rust::HandleObject;
use js::rust::MutableHandleValue;
use libc::c_uint;
use std::slice::from_raw_parts;
#[cfg(feature = "js_backtrace")]
thread_local! {
/// An optional stringified JS backtrace and stringified native backtrace from the
/// the last DOM exception that was reported.
static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None);
}
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// NotReadableError DOMException
NotReadable,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
});
}
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::NotReadable => DOMErrorName::NotReadableError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
},
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report)._base.filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
let message = {
let message = (*report)._base.message_.data_ as *const u8;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf8_lossy(message).into_owned()
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if!JS_IsExceptionPending(cx) {
return;
}
rooted!(in(cx) let mut value = UndefinedValue());
if!JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!(
"Error at {}:{}:{} {}",
error_info.filename, error_info.lineno, error_info.column, error_info.message | LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
if let Some(stack) = js_backtrace {
eprintln!("JS backtrace:\n{}", stack);
}
eprintln!("Rust backtrace:\n{}", rust_backtrace);
}
});
}
if dispatch_event {
GlobalScope::from_context(cx).report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!(
"\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id)
);
throw_type_error(cx, &error);
}
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(
self,
cx: *mut JSContext,
global: &GlobalScope,
rval: MutableHandleValue,
) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, self);
assert!(JS_IsExceptionPending(cx));
assert!(JS_GetPendingException(cx, rval));
JS_ClearPendingException(cx);
}
} | );
#[cfg(feature = "js_backtrace")]
{ | random_line_split |
error.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use crate::dom::bindings::codegen::PrototypeList::proto_id_to_name;
use crate::dom::bindings::conversions::root_from_object;
use crate::dom::bindings::conversions::{
ConversionResult, FromJSValConvertible, ToJSValConvertible,
};
use crate::dom::bindings::str::USVString;
use crate::dom::domexception::{DOMErrorName, DOMException};
use crate::dom::globalscope::GlobalScope;
#[cfg(feature = "js_backtrace")]
use backtrace::Backtrace;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsval::UndefinedValue;
use js::rust::wrappers::JS_ErrorFromException;
use js::rust::wrappers::JS_GetPendingException;
use js::rust::wrappers::JS_SetPendingException;
use js::rust::HandleObject;
use js::rust::MutableHandleValue;
use libc::c_uint;
use std::slice::from_raw_parts;
#[cfg(feature = "js_backtrace")]
thread_local! {
/// An optional stringified JS backtrace and stringified native backtrace from the
/// the last DOM exception that was reported.
static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None);
}
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// NotReadableError DOMException
NotReadable,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
});
}
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::NotReadable => DOMErrorName::NotReadableError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
},
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct | {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report)._base.filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
let message = {
let message = (*report)._base.message_.data_ as *const u8;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf8_lossy(message).into_owned()
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if!JS_IsExceptionPending(cx) {
return;
}
rooted!(in(cx) let mut value = UndefinedValue());
if!JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!(
"Error at {}:{}:{} {}",
error_info.filename, error_info.lineno, error_info.column, error_info.message
);
#[cfg(feature = "js_backtrace")]
{
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
if let Some(stack) = js_backtrace {
eprintln!("JS backtrace:\n{}", stack);
}
eprintln!("Rust backtrace:\n{}", rust_backtrace);
}
});
}
if dispatch_event {
GlobalScope::from_context(cx).report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!(
"\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id)
);
throw_type_error(cx, &error);
}
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(
self,
cx: *mut JSContext,
global: &GlobalScope,
rval: MutableHandleValue,
) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, self);
assert!(JS_IsExceptionPending(cx));
assert!(JS_GetPendingException(cx, rval));
JS_ClearPendingException(cx);
}
}
| ErrorInfo | identifier_name |
error.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use crate::dom::bindings::codegen::PrototypeList::proto_id_to_name;
use crate::dom::bindings::conversions::root_from_object;
use crate::dom::bindings::conversions::{
ConversionResult, FromJSValConvertible, ToJSValConvertible,
};
use crate::dom::bindings::str::USVString;
use crate::dom::domexception::{DOMErrorName, DOMException};
use crate::dom::globalscope::GlobalScope;
#[cfg(feature = "js_backtrace")]
use backtrace::Backtrace;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsval::UndefinedValue;
use js::rust::wrappers::JS_ErrorFromException;
use js::rust::wrappers::JS_GetPendingException;
use js::rust::wrappers::JS_SetPendingException;
use js::rust::HandleObject;
use js::rust::MutableHandleValue;
use libc::c_uint;
use std::slice::from_raw_parts;
#[cfg(feature = "js_backtrace")]
thread_local! {
/// An optional stringified JS backtrace and stringified native backtrace from the
/// the last DOM exception that was reported.
static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None);
}
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// NotReadableError DOMException
NotReadable,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
});
}
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::NotReadable => DOMErrorName::NotReadableError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
},
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report)._base.filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
let message = {
let message = (*report)._base.message_.data_ as *const u8;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf8_lossy(message).into_owned()
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if!JS_IsExceptionPending(cx) {
return;
}
rooted!(in(cx) let mut value = UndefinedValue());
if!JS_GetPendingException(cx, value.handle_mut()) |
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!(
"Error at {}:{}:{} {}",
error_info.filename, error_info.lineno, error_info.column, error_info.message
);
#[cfg(feature = "js_backtrace")]
{
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
if let Some(stack) = js_backtrace {
eprintln!("JS backtrace:\n{}", stack);
}
eprintln!("Rust backtrace:\n{}", rust_backtrace);
}
});
}
if dispatch_event {
GlobalScope::from_context(cx).report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!(
"\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id)
);
throw_type_error(cx, &error);
}
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(
self,
cx: *mut JSContext,
global: &GlobalScope,
rval: MutableHandleValue,
) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, self);
assert!(JS_IsExceptionPending(cx));
assert!(JS_GetPendingException(cx, rval));
JS_ClearPendingException(cx);
}
}
| {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.