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 |
---|---|---|---|---|
timer.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.
use std::comm::{oneshot, stream, PortOne, ChanOne, SendDeferred};
use std::libc::c_int;
use std::rt::BlockedTask;
use std::rt::local::Local;
use std::rt::rtio::RtioTimer;
use std::rt::sched::{Scheduler, SchedHandle};
use std::util;
use uvll;
use super::{Loop, UvHandle, ForbidUnwind, ForbidSwitch};
use uvio::HomingIO;
pub struct TimerWatcher {
handle: *uvll::uv_timer_t,
home: SchedHandle,
action: Option<NextAction>,
}
pub enum NextAction {
WakeTask(BlockedTask),
SendOnce(ChanOne<()>),
SendMany(Chan<()>),
}
impl TimerWatcher {
pub fn new(loop_: &mut Loop) -> ~TimerWatcher {
let handle = UvHandle::alloc(None::<TimerWatcher>, uvll::UV_TIMER);
assert_eq!(unsafe {
uvll::uv_timer_init(loop_.handle, handle)
}, 0);
let me = ~TimerWatcher {
handle: handle,
action: None,
home: get_handle_to_current_scheduler!(),
};
return me.install();
}
fn start(&mut self, msecs: u64, period: u64) {
assert_eq!(unsafe {
uvll::uv_timer_start(self.handle, timer_cb, msecs, period)
}, 0)
}
fn stop(&mut self) {
assert_eq!(unsafe { uvll::uv_timer_stop(self.handle) }, 0)
}
}
impl HomingIO for TimerWatcher {
fn home<'r>(&'r mut self) -> &'r mut SchedHandle { &mut self.home }
}
impl UvHandle<uvll::uv_timer_t> for TimerWatcher {
fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle }
}
impl RtioTimer for TimerWatcher {
fn sleep(&mut self, msecs: u64) {
// As with all of the below functions, we must be extra careful when
// destroying the previous action. If the previous action was a channel,
// destroying it could invoke a context switch. For these situtations,
// we must temporarily un-home ourselves, then destroy the action, and
// then re-home again.
let missile = self.fire_homing_missile();
self.stop();
let _missile = match util::replace(&mut self.action, None) {
None => missile, // no need to do a homing dance
Some(action) => {
drop(missile); // un-home ourself
drop(action); // destroy the previous action
self.fire_homing_missile() // re-home ourself
}
};
// If the descheduling operation unwinds after the timer has been
// started, then we need to call stop on the timer.
let _f = ForbidUnwind::new("timer");
let sched: ~Scheduler = Local::take();
sched.deschedule_running_task_and_then(|_sched, task| {
self.action = Some(WakeTask(task));
self.start(msecs, 0);
});
self.stop();
}
fn oneshot(&mut self, msecs: u64) -> PortOne<()> {
let (port, chan) = oneshot();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.stop();
self.start(msecs, 0);
util::replace(&mut self.action, Some(SendOnce(chan)))
};
return port;
}
fn period(&mut self, msecs: u64) -> Port<()> {
let (port, chan) = stream();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.stop();
self.start(msecs, msecs);
util::replace(&mut self.action, Some(SendMany(chan)))
};
return port;
}
}
extern fn timer_cb(handle: *uvll::uv_timer_t, status: c_int) {
let _f = ForbidSwitch::new("timer callback can't switch");
assert_eq!(status, 0);
let timer: &mut TimerWatcher = unsafe { UvHandle::from_uv_handle(&handle) };
match timer.action.take_unwrap() {
WakeTask(task) => {
let sched: ~Scheduler = Local::take();
sched.resume_blocked_task_immediately(task);
}
SendOnce(chan) => chan.send_deferred(()),
SendMany(chan) => {
chan.send_deferred(());
timer.action = Some(SendMany(chan));
}
}
}
impl Drop for TimerWatcher {
fn drop(&mut self) {
// note that this drop is a little subtle. Dropping a channel which is
// held internally may invoke some scheduling operations. We can't take
// the channel unless we're on the home scheduler, but once we're on the
// home scheduler we should never move. Hence, we take the timer's
// action item and then move it outside of the homing block.
let _action = {
let _m = self.fire_homing_missile();
self.stop();
self.close_async_();
self.action.take()
};
}
}
#[cfg(test)]
mod test {
use super::*;
use std::rt::rtio::RtioTimer;
use super::super::local_loop;
#[test]
fn oneshot() {
let mut timer = TimerWatcher::new(local_loop());
let port = timer.oneshot(1);
port.recv();
let port = timer.oneshot(1);
port.recv();
}
#[test]
fn override() {
let mut timer = TimerWatcher::new(local_loop());
let oport = timer.oneshot(1);
let pport = timer.period(1);
timer.sleep(1);
assert_eq!(oport.try_recv(), None);
assert_eq!(pport.try_recv(), None);
timer.oneshot(1).recv();
}
#[test]
fn period()
|
#[test]
fn sleep() {
let mut timer = TimerWatcher::new(local_loop());
timer.sleep(1);
timer.sleep(1);
}
#[test] #[should_fail]
fn oneshot_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.oneshot(1);
fail!();
}
#[test] #[should_fail]
fn period_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.period(1);
fail!();
}
#[test] #[should_fail]
fn normal_fail() {
let _timer = TimerWatcher::new(local_loop());
fail!();
}
#[test]
fn closing_channel_during_drop_doesnt_kill_everything() {
// see issue #10375
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
// when we drop the TimerWatcher we're going to destroy the channel,
// which must wake up the task on the other end
}
#[test]
fn reset_doesnt_switch_tasks() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
timer.oneshot(1);
}
#[test]
fn reset_doesnt_switch_tasks2() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
timer.sleep(1);
}
#[test]
fn sender_goes_away_oneshot() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.oneshot(1000)
};
assert_eq!(port.try_recv(), None);
}
#[test]
fn sender_goes_away_period() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.period(1000)
};
assert_eq!(port.try_recv(), None);
}
#[test]
fn receiver_goes_away_oneshot() {
let mut timer1 = TimerWatcher::new(local_loop());
timer1.oneshot(1);
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
#[test]
fn receiver_goes_away_period() {
let mut timer1 = TimerWatcher::new(local_loop());
timer1.period(1);
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
}
|
{
let mut timer = TimerWatcher::new(local_loop());
let port = timer.period(1);
port.recv();
port.recv();
let port = timer.period(1);
port.recv();
port.recv();
}
|
identifier_body
|
timer.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.
use std::comm::{oneshot, stream, PortOne, ChanOne, SendDeferred};
use std::libc::c_int;
use std::rt::BlockedTask;
use std::rt::local::Local;
use std::rt::rtio::RtioTimer;
use std::rt::sched::{Scheduler, SchedHandle};
use std::util;
use uvll;
use super::{Loop, UvHandle, ForbidUnwind, ForbidSwitch};
use uvio::HomingIO;
pub struct TimerWatcher {
handle: *uvll::uv_timer_t,
home: SchedHandle,
action: Option<NextAction>,
}
pub enum NextAction {
WakeTask(BlockedTask),
SendOnce(ChanOne<()>),
SendMany(Chan<()>),
}
impl TimerWatcher {
pub fn
|
(loop_: &mut Loop) -> ~TimerWatcher {
let handle = UvHandle::alloc(None::<TimerWatcher>, uvll::UV_TIMER);
assert_eq!(unsafe {
uvll::uv_timer_init(loop_.handle, handle)
}, 0);
let me = ~TimerWatcher {
handle: handle,
action: None,
home: get_handle_to_current_scheduler!(),
};
return me.install();
}
fn start(&mut self, msecs: u64, period: u64) {
assert_eq!(unsafe {
uvll::uv_timer_start(self.handle, timer_cb, msecs, period)
}, 0)
}
fn stop(&mut self) {
assert_eq!(unsafe { uvll::uv_timer_stop(self.handle) }, 0)
}
}
impl HomingIO for TimerWatcher {
fn home<'r>(&'r mut self) -> &'r mut SchedHandle { &mut self.home }
}
impl UvHandle<uvll::uv_timer_t> for TimerWatcher {
fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle }
}
impl RtioTimer for TimerWatcher {
fn sleep(&mut self, msecs: u64) {
// As with all of the below functions, we must be extra careful when
// destroying the previous action. If the previous action was a channel,
// destroying it could invoke a context switch. For these situtations,
// we must temporarily un-home ourselves, then destroy the action, and
// then re-home again.
let missile = self.fire_homing_missile();
self.stop();
let _missile = match util::replace(&mut self.action, None) {
None => missile, // no need to do a homing dance
Some(action) => {
drop(missile); // un-home ourself
drop(action); // destroy the previous action
self.fire_homing_missile() // re-home ourself
}
};
// If the descheduling operation unwinds after the timer has been
// started, then we need to call stop on the timer.
let _f = ForbidUnwind::new("timer");
let sched: ~Scheduler = Local::take();
sched.deschedule_running_task_and_then(|_sched, task| {
self.action = Some(WakeTask(task));
self.start(msecs, 0);
});
self.stop();
}
fn oneshot(&mut self, msecs: u64) -> PortOne<()> {
let (port, chan) = oneshot();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.stop();
self.start(msecs, 0);
util::replace(&mut self.action, Some(SendOnce(chan)))
};
return port;
}
fn period(&mut self, msecs: u64) -> Port<()> {
let (port, chan) = stream();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.stop();
self.start(msecs, msecs);
util::replace(&mut self.action, Some(SendMany(chan)))
};
return port;
}
}
extern fn timer_cb(handle: *uvll::uv_timer_t, status: c_int) {
let _f = ForbidSwitch::new("timer callback can't switch");
assert_eq!(status, 0);
let timer: &mut TimerWatcher = unsafe { UvHandle::from_uv_handle(&handle) };
match timer.action.take_unwrap() {
WakeTask(task) => {
let sched: ~Scheduler = Local::take();
sched.resume_blocked_task_immediately(task);
}
SendOnce(chan) => chan.send_deferred(()),
SendMany(chan) => {
chan.send_deferred(());
timer.action = Some(SendMany(chan));
}
}
}
impl Drop for TimerWatcher {
fn drop(&mut self) {
// note that this drop is a little subtle. Dropping a channel which is
// held internally may invoke some scheduling operations. We can't take
// the channel unless we're on the home scheduler, but once we're on the
// home scheduler we should never move. Hence, we take the timer's
// action item and then move it outside of the homing block.
let _action = {
let _m = self.fire_homing_missile();
self.stop();
self.close_async_();
self.action.take()
};
}
}
#[cfg(test)]
mod test {
use super::*;
use std::rt::rtio::RtioTimer;
use super::super::local_loop;
#[test]
fn oneshot() {
let mut timer = TimerWatcher::new(local_loop());
let port = timer.oneshot(1);
port.recv();
let port = timer.oneshot(1);
port.recv();
}
#[test]
fn override() {
let mut timer = TimerWatcher::new(local_loop());
let oport = timer.oneshot(1);
let pport = timer.period(1);
timer.sleep(1);
assert_eq!(oport.try_recv(), None);
assert_eq!(pport.try_recv(), None);
timer.oneshot(1).recv();
}
#[test]
fn period() {
let mut timer = TimerWatcher::new(local_loop());
let port = timer.period(1);
port.recv();
port.recv();
let port = timer.period(1);
port.recv();
port.recv();
}
#[test]
fn sleep() {
let mut timer = TimerWatcher::new(local_loop());
timer.sleep(1);
timer.sleep(1);
}
#[test] #[should_fail]
fn oneshot_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.oneshot(1);
fail!();
}
#[test] #[should_fail]
fn period_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.period(1);
fail!();
}
#[test] #[should_fail]
fn normal_fail() {
let _timer = TimerWatcher::new(local_loop());
fail!();
}
#[test]
fn closing_channel_during_drop_doesnt_kill_everything() {
// see issue #10375
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
// when we drop the TimerWatcher we're going to destroy the channel,
// which must wake up the task on the other end
}
#[test]
fn reset_doesnt_switch_tasks() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
timer.oneshot(1);
}
#[test]
fn reset_doesnt_switch_tasks2() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
timer.sleep(1);
}
#[test]
fn sender_goes_away_oneshot() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.oneshot(1000)
};
assert_eq!(port.try_recv(), None);
}
#[test]
fn sender_goes_away_period() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.period(1000)
};
assert_eq!(port.try_recv(), None);
}
#[test]
fn receiver_goes_away_oneshot() {
let mut timer1 = TimerWatcher::new(local_loop());
timer1.oneshot(1);
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
#[test]
fn receiver_goes_away_period() {
let mut timer1 = TimerWatcher::new(local_loop());
timer1.period(1);
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
}
|
new
|
identifier_name
|
timer.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.
use std::comm::{oneshot, stream, PortOne, ChanOne, SendDeferred};
use std::libc::c_int;
use std::rt::BlockedTask;
use std::rt::local::Local;
use std::rt::rtio::RtioTimer;
use std::rt::sched::{Scheduler, SchedHandle};
use std::util;
use uvll;
use super::{Loop, UvHandle, ForbidUnwind, ForbidSwitch};
use uvio::HomingIO;
pub struct TimerWatcher {
handle: *uvll::uv_timer_t,
home: SchedHandle,
action: Option<NextAction>,
}
pub enum NextAction {
WakeTask(BlockedTask),
SendOnce(ChanOne<()>),
SendMany(Chan<()>),
}
impl TimerWatcher {
pub fn new(loop_: &mut Loop) -> ~TimerWatcher {
let handle = UvHandle::alloc(None::<TimerWatcher>, uvll::UV_TIMER);
assert_eq!(unsafe {
uvll::uv_timer_init(loop_.handle, handle)
}, 0);
let me = ~TimerWatcher {
handle: handle,
action: None,
home: get_handle_to_current_scheduler!(),
};
return me.install();
}
fn start(&mut self, msecs: u64, period: u64) {
assert_eq!(unsafe {
uvll::uv_timer_start(self.handle, timer_cb, msecs, period)
}, 0)
}
fn stop(&mut self) {
assert_eq!(unsafe { uvll::uv_timer_stop(self.handle) }, 0)
}
}
impl HomingIO for TimerWatcher {
fn home<'r>(&'r mut self) -> &'r mut SchedHandle { &mut self.home }
}
impl UvHandle<uvll::uv_timer_t> for TimerWatcher {
fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle }
}
impl RtioTimer for TimerWatcher {
fn sleep(&mut self, msecs: u64) {
// As with all of the below functions, we must be extra careful when
// destroying the previous action. If the previous action was a channel,
// destroying it could invoke a context switch. For these situtations,
// we must temporarily un-home ourselves, then destroy the action, and
// then re-home again.
let missile = self.fire_homing_missile();
self.stop();
let _missile = match util::replace(&mut self.action, None) {
None => missile, // no need to do a homing dance
Some(action) => {
drop(missile); // un-home ourself
drop(action); // destroy the previous action
self.fire_homing_missile() // re-home ourself
}
};
// If the descheduling operation unwinds after the timer has been
// started, then we need to call stop on the timer.
let _f = ForbidUnwind::new("timer");
let sched: ~Scheduler = Local::take();
sched.deschedule_running_task_and_then(|_sched, task| {
|
self.action = Some(WakeTask(task));
self.start(msecs, 0);
});
self.stop();
}
fn oneshot(&mut self, msecs: u64) -> PortOne<()> {
let (port, chan) = oneshot();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.stop();
self.start(msecs, 0);
util::replace(&mut self.action, Some(SendOnce(chan)))
};
return port;
}
fn period(&mut self, msecs: u64) -> Port<()> {
let (port, chan) = stream();
// similarly to the destructor, we must drop the previous action outside
// of the homing missile
let _prev_action = {
let _m = self.fire_homing_missile();
self.stop();
self.start(msecs, msecs);
util::replace(&mut self.action, Some(SendMany(chan)))
};
return port;
}
}
extern fn timer_cb(handle: *uvll::uv_timer_t, status: c_int) {
let _f = ForbidSwitch::new("timer callback can't switch");
assert_eq!(status, 0);
let timer: &mut TimerWatcher = unsafe { UvHandle::from_uv_handle(&handle) };
match timer.action.take_unwrap() {
WakeTask(task) => {
let sched: ~Scheduler = Local::take();
sched.resume_blocked_task_immediately(task);
}
SendOnce(chan) => chan.send_deferred(()),
SendMany(chan) => {
chan.send_deferred(());
timer.action = Some(SendMany(chan));
}
}
}
impl Drop for TimerWatcher {
fn drop(&mut self) {
// note that this drop is a little subtle. Dropping a channel which is
// held internally may invoke some scheduling operations. We can't take
// the channel unless we're on the home scheduler, but once we're on the
// home scheduler we should never move. Hence, we take the timer's
// action item and then move it outside of the homing block.
let _action = {
let _m = self.fire_homing_missile();
self.stop();
self.close_async_();
self.action.take()
};
}
}
#[cfg(test)]
mod test {
use super::*;
use std::rt::rtio::RtioTimer;
use super::super::local_loop;
#[test]
fn oneshot() {
let mut timer = TimerWatcher::new(local_loop());
let port = timer.oneshot(1);
port.recv();
let port = timer.oneshot(1);
port.recv();
}
#[test]
fn override() {
let mut timer = TimerWatcher::new(local_loop());
let oport = timer.oneshot(1);
let pport = timer.period(1);
timer.sleep(1);
assert_eq!(oport.try_recv(), None);
assert_eq!(pport.try_recv(), None);
timer.oneshot(1).recv();
}
#[test]
fn period() {
let mut timer = TimerWatcher::new(local_loop());
let port = timer.period(1);
port.recv();
port.recv();
let port = timer.period(1);
port.recv();
port.recv();
}
#[test]
fn sleep() {
let mut timer = TimerWatcher::new(local_loop());
timer.sleep(1);
timer.sleep(1);
}
#[test] #[should_fail]
fn oneshot_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.oneshot(1);
fail!();
}
#[test] #[should_fail]
fn period_fail() {
let mut timer = TimerWatcher::new(local_loop());
let _port = timer.period(1);
fail!();
}
#[test] #[should_fail]
fn normal_fail() {
let _timer = TimerWatcher::new(local_loop());
fail!();
}
#[test]
fn closing_channel_during_drop_doesnt_kill_everything() {
// see issue #10375
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
// when we drop the TimerWatcher we're going to destroy the channel,
// which must wake up the task on the other end
}
#[test]
fn reset_doesnt_switch_tasks() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
timer.oneshot(1);
}
#[test]
fn reset_doesnt_switch_tasks2() {
// similar test to the one above.
let mut timer = TimerWatcher::new(local_loop());
let timer_port = timer.period(1000);
do spawn {
timer_port.try_recv();
}
timer.sleep(1);
}
#[test]
fn sender_goes_away_oneshot() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.oneshot(1000)
};
assert_eq!(port.try_recv(), None);
}
#[test]
fn sender_goes_away_period() {
let port = {
let mut timer = TimerWatcher::new(local_loop());
timer.period(1000)
};
assert_eq!(port.try_recv(), None);
}
#[test]
fn receiver_goes_away_oneshot() {
let mut timer1 = TimerWatcher::new(local_loop());
timer1.oneshot(1);
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
#[test]
fn receiver_goes_away_period() {
let mut timer1 = TimerWatcher::new(local_loop());
timer1.period(1);
let mut timer2 = TimerWatcher::new(local_loop());
// while sleeping, the prevous timer should fire and not have its
// callback do something terrible.
timer2.sleep(2);
}
}
|
random_line_split
|
|
lib.rs
|
//! # Mime
//!
//! Mime is now Media Type, technically, but `Mime` is more immediately
//! understandable, so the main type here is `Mime`.
//!
//! ## What is Mime?
//!
//! Example mime string: `text/plain;charset=utf-8`
//!
//! ```rust
//! # #[macro_use] extern crate mime;
//! # fn main() {
//! let plain_text: mime::Mime = "text/plain;charset=utf-8".parse().unwrap();
//! assert_eq!(plain_text, mime!(Text/Plain; Charset=Utf8));
//! # }
//! ```
#![doc(html_root_url = "https://hyperium.github.io/mime.rs")]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(all(feature = "nightly", test), feature(test))]
#[macro_use]
extern crate log;
#[cfg(feature = "nightly")]
#[cfg(test)]
extern crate test;
use std::ascii::AsciiExt;
use std::fmt;
use std::iter::Enumerate;
use std::str::{FromStr, Chars};
macro_rules! inspect(
($s:expr, $t:expr) => ({
let t = $t;
trace!("inspect {}: {:?}", $s, t);
t
})
);
/// Mime, or Media Type. Encapsulates common registers types.
///
/// Consider that a traditional mime type contains a "top level type",
/// a "sub level type", and 0-N "parameters". And they're all strings.
/// Strings everywhere. Strings mean typos. Rust has type safety. We should
/// use types!
///
/// So, Mime bundles together this data into types so the compiler can catch
/// your typos.
///
/// This improves things so you use match without Strings:
///
/// ```rust
/// use mime::{Mime, TopLevel, SubLevel};
///
/// let mime: Mime = "application/json".parse().unwrap();
///
/// match mime {
/// Mime(TopLevel::Application, SubLevel::Json, _) => println!("matched json!"),
/// _ => ()
/// }
/// ```
#[derive(Clone, Debug)]
pub struct Mime<T: AsRef<[Param]> = Vec<Param>>(pub TopLevel, pub SubLevel, pub T);
impl<LHS: AsRef<[Param]>, RHS: AsRef<[Param]>> PartialEq<Mime<RHS>> for Mime<LHS> {
fn eq(&self, other: &Mime<RHS>) -> bool {
self.0 == other.0 && self.1 == other.1 && self.2.as_ref() == other.2.as_ref()
}
}
/// Easily create a Mime without having to import so many enums.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate mime;
///
/// # fn main() {
/// let json = mime!(Application/Json);
/// let plain = mime!(Text/Plain; Charset=Utf8);
/// let text = mime!(Text/Html; Charset=("bar"), ("baz")=("quux"));
/// let img = mime!(Image/_);
/// # }
/// ```
#[macro_export]
macro_rules! mime {
($top:tt / $sub:tt) => (
mime!($top / $sub;)
);
($top:tt / $sub:tt ; $($attr:tt = $val:tt),*) => (
$crate::Mime(
__mime__ident_or_ext!(TopLevel::$top),
__mime__ident_or_ext!(SubLevel::$sub),
[ $((__mime__ident_or_ext!(Attr::$attr), __mime__ident_or_ext!(Value::$val))),* ]
)
);
}
#[doc(hidden)]
#[macro_export]
macro_rules! __mime__ident_or_ext {
($enoom:ident::_) => (
$crate::$enoom::Star
);
($enoom:ident::($inner:expr)) => (
$crate::$enoom::Ext($inner.to_string())
);
($enoom:ident::$var:ident) => (
$crate::$enoom::$var
)
}
macro_rules! enoom {
(pub enum $en:ident; $ext:ident; $($ty:ident, $text:expr;)*) => (
#[derive(Clone, Debug)]
pub enum $en {
$($ty),*,
$ext(String)
}
impl PartialEq for $en {
fn eq(&self, other: &$en) -> bool {
match (self, other) {
$( (&$en::$ty, &$en::$ty) => true ),*,
(&$en::$ext(ref a), &$en::$ext(ref b)) => a == b,
_ => self.to_string() == other.to_string()
}
}
}
impl fmt::Display for $en {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(match *self {
$($en::$ty => $text),*,
$en::$ext(ref s) => s
})
}
}
impl FromStr for $en {
type Err = ();
fn from_str(s: &str) -> Result<$en, ()> {
Ok(match s {
$(_s if _s == $text => $en::$ty),*,
s => $en::$ext(inspect!(stringify!($ext), s).to_string())
})
}
}
)
}
enoom! {
pub enum TopLevel;
Ext;
Star, "*";
Text, "text";
Image, "image";
Audio, "audio";
Video, "video";
Application, "application";
Multipart, "multipart";
Message, "message";
Model, "model";
}
enoom! {
pub enum SubLevel;
Ext;
Star, "*";
// common text/*
Plain, "plain";
Html, "html";
Xml, "xml";
Javascript, "javascript";
Css, "css";
// common application/*
Json, "json";
WwwFormUrlEncoded, "x-www-form-urlencoded";
// multipart/*
FormData, "form-data";
// common image/*
Png, "png";
Gif, "gif";
Bmp, "bmp";
Jpeg, "jpeg";
}
enoom! {
pub enum Attr;
Ext;
Charset, "charset";
Q, "q";
}
enoom! {
pub enum Value;
Ext;
Utf8, "utf-8";
}
pub type Param = (Attr, Value);
impl<T: AsRef<[Param]>> fmt::Display for Mime<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Mime(ref top, ref sub, ref params) = *self;
try!(write!(fmt, "{}/{}", top, sub));
fmt_params(params.as_ref(), fmt)
}
}
impl FromStr for Mime {
type Err = ();
fn from_str(raw: &str) -> Result<Mime, ()> {
let ascii = raw.to_ascii_lowercase(); // lifetimes :(
let len = ascii.len();
let mut iter = ascii.chars().enumerate();
let mut params = vec![];
// toplevel
let mut start;
let mut top;
loop {
match inspect!("top iter", iter.next()) {
Some((0, c)) if is_restricted_name_first_char(c) => (),
Some((i, c)) if i > 0 && is_restricted_name_char(c) => (),
Some((i, '/')) if i > 0 => match FromStr::from_str(&ascii[..i]) {
Ok(t) => {
top = t;
start = i + 1;
break;
}
Err(_) => return Err(())
},
_ => return Err(()) // EOF and no toplevel is no Mime
};
}
// sublevel
let mut sub;
loop {
match inspect!("sub iter", iter.next()) {
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, c)) if i > start && is_restricted_name_char(c) => (),
Some((i, ';')) if i > start => match FromStr::from_str(&ascii[start..i]) {
Ok(s) => {
sub = s;
start = i + 1;
break;
}
Err(_) => return Err(())
},
None => match FromStr::from_str(&ascii[start..]) {
Ok(s) => return Ok(Mime(top, s, params)),
Err(_) => return Err(())
},
_ => return Err(())
};
}
// params
debug!("starting params, len={}", len);
loop {
match inspect!("param", param_from_str(&ascii, &mut iter, start)) {
Some((p, end)) => {
params.push(p);
start = end;
if start >= len {
break;
}
}
None => break
}
}
Ok(Mime(top, sub, params))
}
}
fn param_from_str(raw: &str, iter: &mut Enumerate<Chars>, mut start: usize) -> Option<(Param, usize)> {
let mut attr;
debug!("param_from_str, start={}", start);
loop {
match inspect!("attr iter", iter.next()) {
Some((i,'')) if i == start => start = i + 1,
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, c)) if i > start && is_restricted_name_char(c) => (),
Some((i, '=')) if i > start => match FromStr::from_str(&raw[start..i]) {
Ok(a) => {
attr = inspect!("attr", a);
start = i + 1;
break;
},
Err(_) => return None
},
_ => return None
}
}
let mut value;
// values must be restrict-name-char or "anything goes"
let mut is_quoted = false;
loop {
match inspect!("value iter", iter.next()) {
Some((i, '"')) if i == start => {
debug!("quoted");
is_quoted = true;
start = i + 1;
},
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, '"')) if i > start && is_quoted => match FromStr::from_str(&raw[start..i]) {
Ok(v) => {
value = v;
start = i + 1;
break;
},
Err(_) => return None
},
Some((i, c)) if i > start && is_quoted || is_restricted_name_char(c) => (),
Some((i, ';')) if i > start => match FromStr::from_str(&raw[start..i]) {
Ok(v) => {
value = v;
start = i + 1;
break;
},
Err(_) => return None
},
None => match FromStr::from_str(&raw[start..]) {
Ok(v) => {
value = v;
start = raw.len();
break;
},
Err(_) => return None
},
_ => return None
}
}
Some(((attr, value), start))
}
// From [RFC6838](http://tools.ietf.org/html/rfc6838#section-4.2):
//
// > All registered media types MUST be assigned top-level type and
// > subtype names. The combination of these names serves to uniquely
// > identify the media type, and the subtype name facet (or the absence
// > of one) identifies the registration tree. Both top-level type and
// > subtype names are case-insensitive.
// >
// > Type and subtype names MUST conform to the following ABNF:
// >
// > type-name = restricted-name
// > subtype-name = restricted-name
// >
// > restricted-name = restricted-name-first *126restricted-name-chars
// > restricted-name-first = ALPHA / DIGIT
// > restricted-name-chars = ALPHA / DIGIT / "!" / "#" /
// > "$" / "&" / "-" / "^" / "_"
// > restricted-name-chars =/ "." ; Characters before first dot always
// > ; specify a facet name
// > restricted-name-chars =/ "+" ; Characters after last plus always
// > ; specify a structured syntax suffix
//
fn
|
(c: char) -> bool {
match c {
'a'...'z' |
'0'...'9' => true,
_ => false
}
}
fn is_restricted_name_char(c: char) -> bool {
if is_restricted_name_first_char(c) {
true
} else {
match c {
'!' |
'#' |
'$' |
'&' |
'-' |
'^' |
'.' |
'+' |
'_' => true,
_ => false
}
}
}
#[inline]
fn fmt_params(params: &[Param], fmt: &mut fmt::Formatter) -> fmt::Result {
for param in params.iter() {
try!(fmt_param(param, fmt));
}
Ok(())
}
#[inline]
fn fmt_param(param: &Param, fmt: &mut fmt::Formatter) -> fmt::Result {
let (ref attr, ref value) = *param;
write!(fmt, "; {}={}", attr, value)
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
#[cfg(feature = "nightly")]
use test::Bencher;
use super::Mime;
#[test]
fn test_mime_show() {
let mime = mime!(Text/Plain);
assert_eq!(mime.to_string(), "text/plain".to_string());
let mime = mime!(Text/Plain; Charset=Utf8);
assert_eq!(mime.to_string(), "text/plain; charset=utf-8".to_string());
}
#[test]
fn test_mime_from_str() {
assert_eq!(Mime::from_str("text/plain").unwrap(), mime!(Text/Plain));
assert_eq!(Mime::from_str("TEXT/PLAIN").unwrap(), mime!(Text/Plain));
assert_eq!(Mime::from_str("text/plain; charset=utf-8").unwrap(), mime!(Text/Plain; Charset=Utf8));
assert_eq!(Mime::from_str("text/plain;charset=\"utf-8\"").unwrap(), mime!(Text/Plain; Charset=Utf8));
assert_eq!(Mime::from_str("text/plain; charset=utf-8; foo=bar").unwrap(),
mime!(Text/Plain; Charset=Utf8, ("foo")=("bar")));
}
#[cfg(feature = "nightly")]
#[bench]
fn bench_show(b: &mut Bencher) {
let mime = mime!(Text/Plain; Charset=Utf8, ("foo")=("bar"));
b.bytes = mime.to_string().as_bytes().len() as u64;
b.iter(|| mime.to_string())
}
#[cfg(feature = "nightly")]
#[bench]
fn bench_from_str(b: &mut Bencher) {
let s = "text/plain; charset=utf-8; foo=bar";
b.bytes = s.as_bytes().len() as u64;
b.iter(|| s.parse::<Mime>())
}
}
|
is_restricted_name_first_char
|
identifier_name
|
lib.rs
|
//! # Mime
//!
//! Mime is now Media Type, technically, but `Mime` is more immediately
//! understandable, so the main type here is `Mime`.
//!
//! ## What is Mime?
//!
//! Example mime string: `text/plain;charset=utf-8`
//!
//! ```rust
//! # #[macro_use] extern crate mime;
//! # fn main() {
//! let plain_text: mime::Mime = "text/plain;charset=utf-8".parse().unwrap();
//! assert_eq!(plain_text, mime!(Text/Plain; Charset=Utf8));
//! # }
//! ```
#![doc(html_root_url = "https://hyperium.github.io/mime.rs")]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(all(feature = "nightly", test), feature(test))]
#[macro_use]
extern crate log;
#[cfg(feature = "nightly")]
#[cfg(test)]
extern crate test;
use std::ascii::AsciiExt;
use std::fmt;
use std::iter::Enumerate;
use std::str::{FromStr, Chars};
macro_rules! inspect(
($s:expr, $t:expr) => ({
let t = $t;
trace!("inspect {}: {:?}", $s, t);
t
})
);
/// Mime, or Media Type. Encapsulates common registers types.
///
/// Consider that a traditional mime type contains a "top level type",
/// a "sub level type", and 0-N "parameters". And they're all strings.
/// Strings everywhere. Strings mean typos. Rust has type safety. We should
/// use types!
///
/// So, Mime bundles together this data into types so the compiler can catch
/// your typos.
///
/// This improves things so you use match without Strings:
///
/// ```rust
/// use mime::{Mime, TopLevel, SubLevel};
///
/// let mime: Mime = "application/json".parse().unwrap();
///
/// match mime {
/// Mime(TopLevel::Application, SubLevel::Json, _) => println!("matched json!"),
/// _ => ()
/// }
/// ```
#[derive(Clone, Debug)]
pub struct Mime<T: AsRef<[Param]> = Vec<Param>>(pub TopLevel, pub SubLevel, pub T);
impl<LHS: AsRef<[Param]>, RHS: AsRef<[Param]>> PartialEq<Mime<RHS>> for Mime<LHS> {
fn eq(&self, other: &Mime<RHS>) -> bool {
self.0 == other.0 && self.1 == other.1 && self.2.as_ref() == other.2.as_ref()
}
}
/// Easily create a Mime without having to import so many enums.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate mime;
///
/// # fn main() {
/// let json = mime!(Application/Json);
/// let plain = mime!(Text/Plain; Charset=Utf8);
/// let text = mime!(Text/Html; Charset=("bar"), ("baz")=("quux"));
/// let img = mime!(Image/_);
/// # }
/// ```
#[macro_export]
macro_rules! mime {
($top:tt / $sub:tt) => (
mime!($top / $sub;)
);
($top:tt / $sub:tt ; $($attr:tt = $val:tt),*) => (
$crate::Mime(
__mime__ident_or_ext!(TopLevel::$top),
__mime__ident_or_ext!(SubLevel::$sub),
[ $((__mime__ident_or_ext!(Attr::$attr), __mime__ident_or_ext!(Value::$val))),* ]
)
);
}
#[doc(hidden)]
#[macro_export]
macro_rules! __mime__ident_or_ext {
($enoom:ident::_) => (
$crate::$enoom::Star
);
($enoom:ident::($inner:expr)) => (
$crate::$enoom::Ext($inner.to_string())
);
($enoom:ident::$var:ident) => (
$crate::$enoom::$var
)
}
macro_rules! enoom {
(pub enum $en:ident; $ext:ident; $($ty:ident, $text:expr;)*) => (
#[derive(Clone, Debug)]
pub enum $en {
$($ty),*,
$ext(String)
}
impl PartialEq for $en {
fn eq(&self, other: &$en) -> bool {
match (self, other) {
$( (&$en::$ty, &$en::$ty) => true ),*,
(&$en::$ext(ref a), &$en::$ext(ref b)) => a == b,
_ => self.to_string() == other.to_string()
}
}
}
impl fmt::Display for $en {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(match *self {
$($en::$ty => $text),*,
$en::$ext(ref s) => s
})
}
}
impl FromStr for $en {
type Err = ();
fn from_str(s: &str) -> Result<$en, ()> {
Ok(match s {
$(_s if _s == $text => $en::$ty),*,
s => $en::$ext(inspect!(stringify!($ext), s).to_string())
})
}
}
)
}
enoom! {
pub enum TopLevel;
Ext;
Star, "*";
Text, "text";
Image, "image";
Audio, "audio";
Video, "video";
Application, "application";
Multipart, "multipart";
Message, "message";
Model, "model";
}
enoom! {
pub enum SubLevel;
Ext;
Star, "*";
// common text/*
Plain, "plain";
Html, "html";
Xml, "xml";
Javascript, "javascript";
Css, "css";
// common application/*
Json, "json";
WwwFormUrlEncoded, "x-www-form-urlencoded";
// multipart/*
FormData, "form-data";
// common image/*
Png, "png";
Gif, "gif";
Bmp, "bmp";
Jpeg, "jpeg";
}
enoom! {
pub enum Attr;
Ext;
Charset, "charset";
Q, "q";
}
enoom! {
pub enum Value;
Ext;
Utf8, "utf-8";
}
pub type Param = (Attr, Value);
impl<T: AsRef<[Param]>> fmt::Display for Mime<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Mime(ref top, ref sub, ref params) = *self;
try!(write!(fmt, "{}/{}", top, sub));
fmt_params(params.as_ref(), fmt)
}
}
impl FromStr for Mime {
type Err = ();
fn from_str(raw: &str) -> Result<Mime, ()> {
let ascii = raw.to_ascii_lowercase(); // lifetimes :(
let len = ascii.len();
let mut iter = ascii.chars().enumerate();
let mut params = vec![];
// toplevel
let mut start;
let mut top;
loop {
match inspect!("top iter", iter.next()) {
Some((0, c)) if is_restricted_name_first_char(c) => (),
Some((i, c)) if i > 0 && is_restricted_name_char(c) => (),
Some((i, '/')) if i > 0 => match FromStr::from_str(&ascii[..i]) {
Ok(t) => {
top = t;
start = i + 1;
break;
}
Err(_) => return Err(())
},
_ => return Err(()) // EOF and no toplevel is no Mime
};
}
// sublevel
let mut sub;
loop {
match inspect!("sub iter", iter.next()) {
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, c)) if i > start && is_restricted_name_char(c) => (),
Some((i, ';')) if i > start => match FromStr::from_str(&ascii[start..i]) {
Ok(s) => {
sub = s;
start = i + 1;
break;
}
Err(_) => return Err(())
},
None => match FromStr::from_str(&ascii[start..]) {
Ok(s) => return Ok(Mime(top, s, params)),
Err(_) => return Err(())
},
_ => return Err(())
};
}
// params
debug!("starting params, len={}", len);
loop {
match inspect!("param", param_from_str(&ascii, &mut iter, start)) {
Some((p, end)) => {
params.push(p);
start = end;
if start >= len {
break;
}
}
None => break
}
}
Ok(Mime(top, sub, params))
}
}
fn param_from_str(raw: &str, iter: &mut Enumerate<Chars>, mut start: usize) -> Option<(Param, usize)> {
let mut attr;
debug!("param_from_str, start={}", start);
loop {
match inspect!("attr iter", iter.next()) {
Some((i,'')) if i == start => start = i + 1,
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, c)) if i > start && is_restricted_name_char(c) => (),
Some((i, '=')) if i > start => match FromStr::from_str(&raw[start..i]) {
Ok(a) => {
attr = inspect!("attr", a);
start = i + 1;
break;
},
Err(_) => return None
},
_ => return None
}
}
let mut value;
// values must be restrict-name-char or "anything goes"
let mut is_quoted = false;
loop {
match inspect!("value iter", iter.next()) {
Some((i, '"')) if i == start => {
debug!("quoted");
is_quoted = true;
start = i + 1;
},
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, '"')) if i > start && is_quoted => match FromStr::from_str(&raw[start..i]) {
Ok(v) => {
value = v;
start = i + 1;
break;
},
Err(_) => return None
},
Some((i, c)) if i > start && is_quoted || is_restricted_name_char(c) => (),
Some((i, ';')) if i > start => match FromStr::from_str(&raw[start..i]) {
Ok(v) => {
value = v;
start = i + 1;
break;
},
Err(_) => return None
},
None => match FromStr::from_str(&raw[start..]) {
Ok(v) => {
value = v;
start = raw.len();
break;
},
Err(_) => return None
},
_ => return None
}
}
Some(((attr, value), start))
}
// From [RFC6838](http://tools.ietf.org/html/rfc6838#section-4.2):
//
// > All registered media types MUST be assigned top-level type and
// > subtype names. The combination of these names serves to uniquely
// > identify the media type, and the subtype name facet (or the absence
// > of one) identifies the registration tree. Both top-level type and
// > subtype names are case-insensitive.
// >
// > Type and subtype names MUST conform to the following ABNF:
// >
// > type-name = restricted-name
// > subtype-name = restricted-name
// >
// > restricted-name = restricted-name-first *126restricted-name-chars
// > restricted-name-first = ALPHA / DIGIT
// > restricted-name-chars = ALPHA / DIGIT / "!" / "#" /
// > "$" / "&" / "-" / "^" / "_"
// > restricted-name-chars =/ "." ; Characters before first dot always
// > ; specify a facet name
// > restricted-name-chars =/ "+" ; Characters after last plus always
// > ; specify a structured syntax suffix
//
fn is_restricted_name_first_char(c: char) -> bool {
match c {
'a'...'z' |
'0'...'9' => true,
_ => false
}
}
fn is_restricted_name_char(c: char) -> bool {
if is_restricted_name_first_char(c) {
true
} else {
match c {
'!' |
'#' |
'$' |
'&' |
'-' |
'^' |
'.' |
'+' |
'_' => true,
_ => false
}
}
}
#[inline]
fn fmt_params(params: &[Param], fmt: &mut fmt::Formatter) -> fmt::Result {
for param in params.iter() {
try!(fmt_param(param, fmt));
}
Ok(())
}
#[inline]
fn fmt_param(param: &Param, fmt: &mut fmt::Formatter) -> fmt::Result {
let (ref attr, ref value) = *param;
write!(fmt, "; {}={}", attr, value)
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
#[cfg(feature = "nightly")]
use test::Bencher;
use super::Mime;
#[test]
fn test_mime_show()
|
#[test]
fn test_mime_from_str() {
assert_eq!(Mime::from_str("text/plain").unwrap(), mime!(Text/Plain));
assert_eq!(Mime::from_str("TEXT/PLAIN").unwrap(), mime!(Text/Plain));
assert_eq!(Mime::from_str("text/plain; charset=utf-8").unwrap(), mime!(Text/Plain; Charset=Utf8));
assert_eq!(Mime::from_str("text/plain;charset=\"utf-8\"").unwrap(), mime!(Text/Plain; Charset=Utf8));
assert_eq!(Mime::from_str("text/plain; charset=utf-8; foo=bar").unwrap(),
mime!(Text/Plain; Charset=Utf8, ("foo")=("bar")));
}
#[cfg(feature = "nightly")]
#[bench]
fn bench_show(b: &mut Bencher) {
let mime = mime!(Text/Plain; Charset=Utf8, ("foo")=("bar"));
b.bytes = mime.to_string().as_bytes().len() as u64;
b.iter(|| mime.to_string())
}
#[cfg(feature = "nightly")]
#[bench]
fn bench_from_str(b: &mut Bencher) {
let s = "text/plain; charset=utf-8; foo=bar";
b.bytes = s.as_bytes().len() as u64;
b.iter(|| s.parse::<Mime>())
}
}
|
{
let mime = mime!(Text/Plain);
assert_eq!(mime.to_string(), "text/plain".to_string());
let mime = mime!(Text/Plain; Charset=Utf8);
assert_eq!(mime.to_string(), "text/plain; charset=utf-8".to_string());
}
|
identifier_body
|
lib.rs
|
//! # Mime
//!
//! Mime is now Media Type, technically, but `Mime` is more immediately
//! understandable, so the main type here is `Mime`.
//!
//! ## What is Mime?
//!
//! Example mime string: `text/plain;charset=utf-8`
//!
//! ```rust
//! # #[macro_use] extern crate mime;
//! # fn main() {
//! let plain_text: mime::Mime = "text/plain;charset=utf-8".parse().unwrap();
//! assert_eq!(plain_text, mime!(Text/Plain; Charset=Utf8));
//! # }
//! ```
#![doc(html_root_url = "https://hyperium.github.io/mime.rs")]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(all(feature = "nightly", test), feature(test))]
#[macro_use]
extern crate log;
#[cfg(feature = "nightly")]
#[cfg(test)]
extern crate test;
use std::ascii::AsciiExt;
use std::fmt;
use std::iter::Enumerate;
use std::str::{FromStr, Chars};
macro_rules! inspect(
($s:expr, $t:expr) => ({
let t = $t;
trace!("inspect {}: {:?}", $s, t);
t
})
);
/// Mime, or Media Type. Encapsulates common registers types.
///
/// Consider that a traditional mime type contains a "top level type",
/// a "sub level type", and 0-N "parameters". And they're all strings.
/// Strings everywhere. Strings mean typos. Rust has type safety. We should
/// use types!
///
/// So, Mime bundles together this data into types so the compiler can catch
/// your typos.
///
/// This improves things so you use match without Strings:
///
/// ```rust
/// use mime::{Mime, TopLevel, SubLevel};
///
/// let mime: Mime = "application/json".parse().unwrap();
///
/// match mime {
/// Mime(TopLevel::Application, SubLevel::Json, _) => println!("matched json!"),
/// _ => ()
/// }
/// ```
#[derive(Clone, Debug)]
pub struct Mime<T: AsRef<[Param]> = Vec<Param>>(pub TopLevel, pub SubLevel, pub T);
impl<LHS: AsRef<[Param]>, RHS: AsRef<[Param]>> PartialEq<Mime<RHS>> for Mime<LHS> {
fn eq(&self, other: &Mime<RHS>) -> bool {
self.0 == other.0 && self.1 == other.1 && self.2.as_ref() == other.2.as_ref()
}
}
/// Easily create a Mime without having to import so many enums.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate mime;
///
/// # fn main() {
/// let json = mime!(Application/Json);
/// let plain = mime!(Text/Plain; Charset=Utf8);
/// let text = mime!(Text/Html; Charset=("bar"), ("baz")=("quux"));
/// let img = mime!(Image/_);
/// # }
/// ```
#[macro_export]
macro_rules! mime {
($top:tt / $sub:tt) => (
mime!($top / $sub;)
);
($top:tt / $sub:tt ; $($attr:tt = $val:tt),*) => (
$crate::Mime(
__mime__ident_or_ext!(TopLevel::$top),
__mime__ident_or_ext!(SubLevel::$sub),
[ $((__mime__ident_or_ext!(Attr::$attr), __mime__ident_or_ext!(Value::$val))),* ]
)
);
}
#[doc(hidden)]
#[macro_export]
macro_rules! __mime__ident_or_ext {
($enoom:ident::_) => (
$crate::$enoom::Star
);
($enoom:ident::($inner:expr)) => (
$crate::$enoom::Ext($inner.to_string())
);
($enoom:ident::$var:ident) => (
$crate::$enoom::$var
)
}
macro_rules! enoom {
(pub enum $en:ident; $ext:ident; $($ty:ident, $text:expr;)*) => (
#[derive(Clone, Debug)]
pub enum $en {
$($ty),*,
$ext(String)
}
impl PartialEq for $en {
fn eq(&self, other: &$en) -> bool {
match (self, other) {
$( (&$en::$ty, &$en::$ty) => true ),*,
(&$en::$ext(ref a), &$en::$ext(ref b)) => a == b,
_ => self.to_string() == other.to_string()
}
}
}
impl fmt::Display for $en {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(match *self {
$($en::$ty => $text),*,
$en::$ext(ref s) => s
})
}
}
impl FromStr for $en {
type Err = ();
fn from_str(s: &str) -> Result<$en, ()> {
Ok(match s {
$(_s if _s == $text => $en::$ty),*,
s => $en::$ext(inspect!(stringify!($ext), s).to_string())
})
}
}
)
}
enoom! {
pub enum TopLevel;
Ext;
Star, "*";
Text, "text";
Image, "image";
Audio, "audio";
Video, "video";
Application, "application";
Multipart, "multipart";
Message, "message";
Model, "model";
}
enoom! {
pub enum SubLevel;
Ext;
Star, "*";
// common text/*
Plain, "plain";
Html, "html";
Xml, "xml";
Javascript, "javascript";
Css, "css";
// common application/*
Json, "json";
WwwFormUrlEncoded, "x-www-form-urlencoded";
// multipart/*
FormData, "form-data";
// common image/*
Png, "png";
Gif, "gif";
Bmp, "bmp";
Jpeg, "jpeg";
}
enoom! {
pub enum Attr;
Ext;
Charset, "charset";
Q, "q";
}
enoom! {
pub enum Value;
Ext;
Utf8, "utf-8";
}
pub type Param = (Attr, Value);
impl<T: AsRef<[Param]>> fmt::Display for Mime<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Mime(ref top, ref sub, ref params) = *self;
try!(write!(fmt, "{}/{}", top, sub));
fmt_params(params.as_ref(), fmt)
}
}
impl FromStr for Mime {
type Err = ();
fn from_str(raw: &str) -> Result<Mime, ()> {
let ascii = raw.to_ascii_lowercase(); // lifetimes :(
let len = ascii.len();
let mut iter = ascii.chars().enumerate();
let mut params = vec![];
// toplevel
let mut start;
let mut top;
loop {
match inspect!("top iter", iter.next()) {
Some((0, c)) if is_restricted_name_first_char(c) => (),
Some((i, c)) if i > 0 && is_restricted_name_char(c) => (),
Some((i, '/')) if i > 0 => match FromStr::from_str(&ascii[..i]) {
Ok(t) => {
top = t;
start = i + 1;
break;
}
Err(_) => return Err(())
},
_ => return Err(()) // EOF and no toplevel is no Mime
};
}
// sublevel
let mut sub;
loop {
match inspect!("sub iter", iter.next()) {
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, c)) if i > start && is_restricted_name_char(c) => (),
Some((i, ';')) if i > start => match FromStr::from_str(&ascii[start..i]) {
Ok(s) => {
sub = s;
start = i + 1;
break;
}
Err(_) => return Err(())
},
None => match FromStr::from_str(&ascii[start..]) {
Ok(s) => return Ok(Mime(top, s, params)),
Err(_) => return Err(())
},
_ => return Err(())
};
}
// params
debug!("starting params, len={}", len);
loop {
match inspect!("param", param_from_str(&ascii, &mut iter, start)) {
Some((p, end)) => {
params.push(p);
start = end;
if start >= len {
break;
}
}
None => break
}
}
Ok(Mime(top, sub, params))
}
}
fn param_from_str(raw: &str, iter: &mut Enumerate<Chars>, mut start: usize) -> Option<(Param, usize)> {
let mut attr;
debug!("param_from_str, start={}", start);
loop {
match inspect!("attr iter", iter.next()) {
Some((i,'')) if i == start => start = i + 1,
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, c)) if i > start && is_restricted_name_char(c) => (),
Some((i, '=')) if i > start => match FromStr::from_str(&raw[start..i]) {
Ok(a) => {
attr = inspect!("attr", a);
start = i + 1;
break;
},
Err(_) => return None
},
_ => return None
}
}
let mut value;
// values must be restrict-name-char or "anything goes"
let mut is_quoted = false;
loop {
match inspect!("value iter", iter.next()) {
Some((i, '"')) if i == start => {
debug!("quoted");
is_quoted = true;
start = i + 1;
},
Some((i, c)) if i == start && is_restricted_name_first_char(c) => (),
Some((i, '"')) if i > start && is_quoted => match FromStr::from_str(&raw[start..i]) {
Ok(v) => {
value = v;
start = i + 1;
break;
},
Err(_) => return None
},
Some((i, c)) if i > start && is_quoted || is_restricted_name_char(c) => (),
Some((i, ';')) if i > start => match FromStr::from_str(&raw[start..i]) {
Ok(v) => {
value = v;
start = i + 1;
break;
},
Err(_) => return None
},
None => match FromStr::from_str(&raw[start..]) {
Ok(v) => {
value = v;
start = raw.len();
break;
},
Err(_) => return None
},
_ => return None
}
}
Some(((attr, value), start))
}
// From [RFC6838](http://tools.ietf.org/html/rfc6838#section-4.2):
//
// > All registered media types MUST be assigned top-level type and
// > subtype names. The combination of these names serves to uniquely
// > identify the media type, and the subtype name facet (or the absence
// > of one) identifies the registration tree. Both top-level type and
// > subtype names are case-insensitive.
// >
// > Type and subtype names MUST conform to the following ABNF:
|
// >
// > type-name = restricted-name
// > subtype-name = restricted-name
// >
// > restricted-name = restricted-name-first *126restricted-name-chars
// > restricted-name-first = ALPHA / DIGIT
// > restricted-name-chars = ALPHA / DIGIT / "!" / "#" /
// > "$" / "&" / "-" / "^" / "_"
// > restricted-name-chars =/ "." ; Characters before first dot always
// > ; specify a facet name
// > restricted-name-chars =/ "+" ; Characters after last plus always
// > ; specify a structured syntax suffix
//
fn is_restricted_name_first_char(c: char) -> bool {
match c {
'a'...'z' |
'0'...'9' => true,
_ => false
}
}
fn is_restricted_name_char(c: char) -> bool {
if is_restricted_name_first_char(c) {
true
} else {
match c {
'!' |
'#' |
'$' |
'&' |
'-' |
'^' |
'.' |
'+' |
'_' => true,
_ => false
}
}
}
#[inline]
fn fmt_params(params: &[Param], fmt: &mut fmt::Formatter) -> fmt::Result {
for param in params.iter() {
try!(fmt_param(param, fmt));
}
Ok(())
}
#[inline]
fn fmt_param(param: &Param, fmt: &mut fmt::Formatter) -> fmt::Result {
let (ref attr, ref value) = *param;
write!(fmt, "; {}={}", attr, value)
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
#[cfg(feature = "nightly")]
use test::Bencher;
use super::Mime;
#[test]
fn test_mime_show() {
let mime = mime!(Text/Plain);
assert_eq!(mime.to_string(), "text/plain".to_string());
let mime = mime!(Text/Plain; Charset=Utf8);
assert_eq!(mime.to_string(), "text/plain; charset=utf-8".to_string());
}
#[test]
fn test_mime_from_str() {
assert_eq!(Mime::from_str("text/plain").unwrap(), mime!(Text/Plain));
assert_eq!(Mime::from_str("TEXT/PLAIN").unwrap(), mime!(Text/Plain));
assert_eq!(Mime::from_str("text/plain; charset=utf-8").unwrap(), mime!(Text/Plain; Charset=Utf8));
assert_eq!(Mime::from_str("text/plain;charset=\"utf-8\"").unwrap(), mime!(Text/Plain; Charset=Utf8));
assert_eq!(Mime::from_str("text/plain; charset=utf-8; foo=bar").unwrap(),
mime!(Text/Plain; Charset=Utf8, ("foo")=("bar")));
}
#[cfg(feature = "nightly")]
#[bench]
fn bench_show(b: &mut Bencher) {
let mime = mime!(Text/Plain; Charset=Utf8, ("foo")=("bar"));
b.bytes = mime.to_string().as_bytes().len() as u64;
b.iter(|| mime.to_string())
}
#[cfg(feature = "nightly")]
#[bench]
fn bench_from_str(b: &mut Bencher) {
let s = "text/plain; charset=utf-8; foo=bar";
b.bytes = s.as_bytes().len() as u64;
b.iter(|| s.parse::<Mime>())
}
}
|
random_line_split
|
|
hash.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::fmt;
use std::str::FromStr;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use serde;
use rustc_serialize::hex::{ToHex, FromHex};
use util::{H64 as Eth64, H160 as Eth160, H256 as Eth256, H520 as Eth520, H512 as Eth512, H2048 as Eth2048};
macro_rules! impl_hash {
($name: ident, $other: ident, $size: expr) => {
/// Hash serialization
pub struct $name([u8; $size]);
impl Eq for $name { }
impl Default for $name {
fn default() -> Self {
$name([0; $size])
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.0.to_hex())
}
}
impl<T> From<T> for $name where $other: From<T> {
fn from(o: T) -> Self {
$name($other::from(o).0)
}
}
impl FromStr for $name {
type Err = <$other as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
$other::from_str(s).map(|x| $name(x.0))
}
}
impl Into<$other> for $name {
fn into(self) -> $other {
$other(self.0)
}
}
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
let self_ref: &[u8] = &self.0;
let other_ref: &[u8] = &other.0;
self_ref == other_ref
}
}
impl PartialOrd for $name {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
let self_ref: &[u8] = &self.0;
let other_ref: &[u8] = &other.0;
self_ref.partial_cmp(other_ref)
}
}
impl Ord for $name {
fn cmp(&self, other: &Self) -> Ordering {
let self_ref: &[u8] = &self.0;
let other_ref: &[u8] = &other.0;
self_ref.cmp(other_ref)
}
}
impl Hash for $name {
fn hash<H>(&self, state: &mut H) where H: Hasher {
let self_ref: &[u8] = &self.0;
Hash::hash(self_ref, state)
}
}
impl Clone for $name {
fn clone(&self) -> Self {
let mut r = [0; $size];
r.copy_from_slice(&self.0);
$name(r)
|
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer {
let mut hex = "0x".to_owned();
hex.push_str(&self.0.to_hex());
serializer.serialize_str(&hex)
}
}
impl serde::Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<$name, D::Error> where D: serde::Deserializer {
struct HashVisitor;
impl serde::de::Visitor for HashVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: serde::Error {
if value.len()!= 2 + $size * 2 {
return Err(serde::Error::custom("Invalid length."));
}
match value[2..].from_hex() {
Ok(ref v) => {
let mut result = [0u8; $size];
result.copy_from_slice(v);
Ok($name(result))
},
_ => Err(serde::Error::custom("Invalid hex value."))
}
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: serde::Error {
self.visit_str(value.as_ref())
}
}
deserializer.deserialize(HashVisitor)
}
}
}
}
impl_hash!(H64, Eth64, 8);
impl_hash!(H160, Eth160, 20);
impl_hash!(H256, Eth256, 32);
impl_hash!(H512, Eth512, 64);
impl_hash!(H520, Eth520, 65);
impl_hash!(H2048, Eth2048, 256);
|
}
|
random_line_split
|
main.rs
|
use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::time::Duration;
// struct to cache results of expensive calculations
struct Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Eq + Hash + Copy,
V: Copy,
{
calculation: T,
values: HashMap<U, V>,
}
impl<T, U, V> Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Eq + Hash + Copy,
V: Copy,
{
fn new(calculation: T) -> Cacher<T, U, V> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> V {
match self.values.get(&arg) {
Some(v) => v.to_owned(),
None => {
let v = (self.calculation)(arg);
self.values.insert(arg, v);
v
}
}
}
}
fn generate_workout(intensity: u32, random_number: u32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
} else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
expensive_result.value(intensity)
);
}
}
}
fn main()
|
#[test]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_ne!(v2, v1);
assert_eq!(v2, 2);
}
#[test]
fn call_with_different_types() {
let mut c1 = Cacher::new(|a| a);
let mut c2 = Cacher::new(|a| a);
let v1 = c1.value(1);
let v2 = c2.value("Test");
assert_eq!(v1, 1);
assert_eq!(v2, "Test");
}
|
{
let simulated_user_specified_value = 10;
let simulated_randon_number = 7;
generate_workout(simulated_user_specified_value, simulated_randon_number);
}
|
identifier_body
|
main.rs
|
use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::time::Duration;
// struct to cache results of expensive calculations
struct Cacher<T, U, V>
where
T: Fn(U) -> V,
|
}
impl<T, U, V> Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Eq + Hash + Copy,
V: Copy,
{
fn new(calculation: T) -> Cacher<T, U, V> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> V {
match self.values.get(&arg) {
Some(v) => v.to_owned(),
None => {
let v = (self.calculation)(arg);
self.values.insert(arg, v);
v
}
}
}
}
fn generate_workout(intensity: u32, random_number: u32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
} else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
expensive_result.value(intensity)
);
}
}
}
fn main() {
let simulated_user_specified_value = 10;
let simulated_randon_number = 7;
generate_workout(simulated_user_specified_value, simulated_randon_number);
}
#[test]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_ne!(v2, v1);
assert_eq!(v2, 2);
}
#[test]
fn call_with_different_types() {
let mut c1 = Cacher::new(|a| a);
let mut c2 = Cacher::new(|a| a);
let v1 = c1.value(1);
let v2 = c2.value("Test");
assert_eq!(v1, 1);
assert_eq!(v2, "Test");
}
|
U: Eq + Hash + Copy,
V: Copy,
{
calculation: T,
values: HashMap<U, V>,
|
random_line_split
|
main.rs
|
use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::time::Duration;
// struct to cache results of expensive calculations
struct Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Eq + Hash + Copy,
V: Copy,
{
calculation: T,
values: HashMap<U, V>,
}
impl<T, U, V> Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Eq + Hash + Copy,
V: Copy,
{
fn new(calculation: T) -> Cacher<T, U, V> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> V {
match self.values.get(&arg) {
Some(v) => v.to_owned(),
None => {
let v = (self.calculation)(arg);
self.values.insert(arg, v);
v
}
}
}
}
fn generate_workout(intensity: u32, random_number: u32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25
|
else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
expensive_result.value(intensity)
);
}
}
}
fn main() {
let simulated_user_specified_value = 10;
let simulated_randon_number = 7;
generate_workout(simulated_user_specified_value, simulated_randon_number);
}
#[test]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_ne!(v2, v1);
assert_eq!(v2, 2);
}
#[test]
fn call_with_different_types() {
let mut c1 = Cacher::new(|a| a);
let mut c2 = Cacher::new(|a| a);
let v1 = c1.value(1);
let v2 = c2.value("Test");
assert_eq!(v1, 1);
assert_eq!(v2, "Test");
}
|
{
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
}
|
conditional_block
|
main.rs
|
use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::time::Duration;
// struct to cache results of expensive calculations
struct Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Eq + Hash + Copy,
V: Copy,
{
calculation: T,
values: HashMap<U, V>,
}
impl<T, U, V> Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Eq + Hash + Copy,
V: Copy,
{
fn new(calculation: T) -> Cacher<T, U, V> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> V {
match self.values.get(&arg) {
Some(v) => v.to_owned(),
None => {
let v = (self.calculation)(arg);
self.values.insert(arg, v);
v
}
}
}
}
fn generate_workout(intensity: u32, random_number: u32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
} else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
expensive_result.value(intensity)
);
}
}
}
fn main() {
let simulated_user_specified_value = 10;
let simulated_randon_number = 7;
generate_workout(simulated_user_specified_value, simulated_randon_number);
}
#[test]
fn
|
() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_ne!(v2, v1);
assert_eq!(v2, 2);
}
#[test]
fn call_with_different_types() {
let mut c1 = Cacher::new(|a| a);
let mut c2 = Cacher::new(|a| a);
let v1 = c1.value(1);
let v2 = c2.value("Test");
assert_eq!(v1, 1);
assert_eq!(v2, "Test");
}
|
call_with_different_values
|
identifier_name
|
custom_mesh.rs
|
extern crate kiss3d;
extern crate nalgebra as na;
use kiss3d::light::Light;
use kiss3d::resource::Mesh;
use kiss3d::window::Window;
use na::{Point3, UnitQuaternion, Vector3};
use std::cell::RefCell;
use std::rc::Rc;
fn
|
() {
let mut window = Window::new("Kiss3d: custom_mesh");
let a = Point3::new(-1.0, -1.0, 0.0);
let b = Point3::new(1.0, -1.0, 0.0);
let c = Point3::new(0.0, 1.0, 0.0);
let vertices = vec![a, b, c];
let indices = vec![Point3::new(0u16, 1, 2)];
let mesh = Rc::new(RefCell::new(Mesh::new(
vertices, indices, None, None, false,
)));
let mut c = window.add_mesh(mesh, Vector3::new(1.0, 1.0, 1.0));
c.set_color(1.0, 0.0, 0.0);
c.enable_backface_culling(false);
window.set_light(Light::StickToCamera);
let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014);
while window.render() {
c.prepend_to_local_rotation(&rot);
}
}
|
main
|
identifier_name
|
custom_mesh.rs
|
extern crate kiss3d;
extern crate nalgebra as na;
use kiss3d::light::Light;
use kiss3d::resource::Mesh;
use kiss3d::window::Window;
use na::{Point3, UnitQuaternion, Vector3};
use std::cell::RefCell;
use std::rc::Rc;
fn main()
|
let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014);
while window.render() {
c.prepend_to_local_rotation(&rot);
}
}
|
{
let mut window = Window::new("Kiss3d: custom_mesh");
let a = Point3::new(-1.0, -1.0, 0.0);
let b = Point3::new(1.0, -1.0, 0.0);
let c = Point3::new(0.0, 1.0, 0.0);
let vertices = vec![a, b, c];
let indices = vec![Point3::new(0u16, 1, 2)];
let mesh = Rc::new(RefCell::new(Mesh::new(
vertices, indices, None, None, false,
)));
let mut c = window.add_mesh(mesh, Vector3::new(1.0, 1.0, 1.0));
c.set_color(1.0, 0.0, 0.0);
c.enable_backface_culling(false);
window.set_light(Light::StickToCamera);
|
identifier_body
|
custom_mesh.rs
|
extern crate kiss3d;
extern crate nalgebra as na;
use kiss3d::light::Light;
use kiss3d::resource::Mesh;
|
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let mut window = Window::new("Kiss3d: custom_mesh");
let a = Point3::new(-1.0, -1.0, 0.0);
let b = Point3::new(1.0, -1.0, 0.0);
let c = Point3::new(0.0, 1.0, 0.0);
let vertices = vec![a, b, c];
let indices = vec![Point3::new(0u16, 1, 2)];
let mesh = Rc::new(RefCell::new(Mesh::new(
vertices, indices, None, None, false,
)));
let mut c = window.add_mesh(mesh, Vector3::new(1.0, 1.0, 1.0));
c.set_color(1.0, 0.0, 0.0);
c.enable_backface_culling(false);
window.set_light(Light::StickToCamera);
let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014);
while window.render() {
c.prepend_to_local_rotation(&rot);
}
}
|
use kiss3d::window::Window;
use na::{Point3, UnitQuaternion, Vector3};
|
random_line_split
|
cull.rs
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
#pragma version(1)
#pragma rs java_package_name(com.android.scenegraph)
#include "scenegraph_objects.rsh"
static void getTransformedSphere(SgRenderable *obj) {
obj->worldBoundingSphere = obj->boundingSphere;
obj->worldBoundingSphere.w = 1.0f;
const SgTransform *objTransform = (const SgTransform *)rsGetElementAt(obj->transformMatrix, 0);
obj->worldBoundingSphere = rsMatrixMultiply(&objTransform->globalMat, obj->worldBoundingSphere);
const float4 unitVec = {0.57735f, 0.57735f, 0.57735f, 0.0f};
float4 scaledVec = rsMatrixMultiply(&objTransform->globalMat, unitVec);
scaledVec.w = 0.0f;
obj->worldBoundingSphere.w = obj->boundingSphere.w * length(scaledVec);
}
static bool frustumCulled(SgRenderable *obj, SgCamera *cam) {
if (!obj->bVolInitialized) {
float minX, minY, minZ, maxX, maxY, maxZ;
rsgMeshComputeBoundingBox(obj->mesh,
&minX, &minY, &minZ,
&maxX, &maxY, &maxZ);
//rsDebug("min", minX, minY, minZ);
//rsDebug("max", maxX, maxY, maxZ);
float4 sphere;
sphere.x = (maxX + minX) * 0.5f;
sphere.y = (maxY + minY) * 0.5f;
sphere.z = (maxZ + minZ) * 0.5f;
float3 radius;
radius.x = (maxX - sphere.x);
radius.y = (maxY - sphere.y);
radius.z = (maxZ - sphere.z);
sphere.w = length(radius);
obj->boundingSphere = sphere;
obj->bVolInitialized = 1;
//rsDebug("Sphere", sphere);
}
getTransformedSphere(obj);
return!rsIsSphereInFrustum(&obj->worldBoundingSphere,
&cam->frustumPlanes[0], &cam->frustumPlanes[1],
&cam->frustumPlanes[2], &cam->frustumPlanes[3],
&cam->frustumPlanes[4], &cam->frustumPlanes[5]);
}
void root(rs_allocation *v_out, const void *usrData) {
SgRenderable *drawable = (SgRenderable *)rsGetElementAt(*v_out, 0);
const SgCamera *camera = (const SgCamera*)usrData;
drawable->isVisible = 0;
// Not loaded yet
if (!rsIsObject(drawable->mesh) || drawable->cullType == CULL_ALWAYS) {
return;
}
// check to see if we are culling this object and if it's
// outside the frustum
if (drawable->cullType == CULL_FRUSTUM && frustumCulled(drawable, (SgCamera*)camera)) {
#ifdef DEBUG_RENDERABLES
rsDebug("Culled", drawable);
printName(drawable->name);
#endif // DEBUG_RENDERABLES
return;
}
drawable->isVisible = 1;
}
|
// See the License for the specific language governing permissions and
// limitations under the License.
|
random_line_split
|
cull.rs
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma version(1)
#pragma rs java_package_name(com.android.scenegraph)
#include "scenegraph_objects.rsh"
static void getTransformedSphere(SgRenderable *obj) {
obj->worldBoundingSphere = obj->boundingSphere;
obj->worldBoundingSphere.w = 1.0f;
const SgTransform *objTransform = (const SgTransform *)rsGetElementAt(obj->transformMatrix, 0);
obj->worldBoundingSphere = rsMatrixMultiply(&objTransform->globalMat, obj->worldBoundingSphere);
const float4 unitVec = {0.57735f, 0.57735f, 0.57735f, 0.0f};
float4 scaledVec = rsMatrixMultiply(&objTransform->globalMat, unitVec);
scaledVec.w = 0.0f;
obj->worldBoundingSphere.w = obj->boundingSphere.w * length(scaledVec);
}
static bool frustumCulled(SgRenderable *obj, SgCamera *cam) {
if (!obj->bVolInitialized)
|
}
getTransformedSphere(obj);
return!rsIsSphereInFrustum(&obj->worldBoundingSphere,
&cam->frustumPlanes[0], &cam->frustumPlanes[1],
&cam->frustumPlanes[2], &cam->frustumPlanes[3],
&cam->frustumPlanes[4], &cam->frustumPlanes[5]);
}
void root(rs_allocation *v_out, const void *usrData) {
SgRenderable *drawable = (SgRenderable *)rsGetElementAt(*v_out, 0);
const SgCamera *camera = (const SgCamera*)usrData;
drawable->isVisible = 0;
// Not loaded yet
if (!rsIsObject(drawable->mesh) || drawable->cullType == CULL_ALWAYS) {
return;
}
// check to see if we are culling this object and if it's
// outside the frustum
if (drawable->cullType == CULL_FRUSTUM && frustumCulled(drawable, (SgCamera*)camera)) {
#ifdef DEBUG_RENDERABLES
rsDebug("Culled", drawable);
printName(drawable->name);
#endif // DEBUG_RENDERABLES
return;
}
drawable->isVisible = 1;
}
|
{
float minX, minY, minZ, maxX, maxY, maxZ;
rsgMeshComputeBoundingBox(obj->mesh,
&minX, &minY, &minZ,
&maxX, &maxY, &maxZ);
//rsDebug("min", minX, minY, minZ);
//rsDebug("max", maxX, maxY, maxZ);
float4 sphere;
sphere.x = (maxX + minX) * 0.5f;
sphere.y = (maxY + minY) * 0.5f;
sphere.z = (maxZ + minZ) * 0.5f;
float3 radius;
radius.x = (maxX - sphere.x);
radius.y = (maxY - sphere.y);
radius.z = (maxZ - sphere.z);
sphere.w = length(radius);
obj->boundingSphere = sphere;
obj->bVolInitialized = 1;
//rsDebug("Sphere", sphere);
|
conditional_block
|
ident.rs
|
use super::error::TomlHelper;
use log::error;
use regex::Regex;
use std::fmt;
use toml::Value;
#[derive(Clone, Debug)]
pub enum Ident {
Name(String),
Pattern(Box<Regex>),
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Ident::Name(name) => f.write_str(name),
Ident::Pattern(regex) => write!(f, "Regex {}", regex),
}
}
}
impl PartialEq for Ident {
fn eq(&self, other: &Ident) -> bool {
pub use self::Ident::*;
match (self, other) {
(Name(s1), Name(s2)) => s1 == s2,
(Pattern(r1), Pattern(r2)) => r1.as_str() == r2.as_str(),
_ => false,
}
}
}
impl Eq for Ident {}
impl Ident {
pub fn parse(toml: &Value, object_name: &str, what: &str) -> Option<Ident> {
match toml.lookup("pattern").and_then(Value::as_str) {
Some(s) => Regex::new(&format!("^{}$", s))
.map(Box::new)
.map(Ident::Pattern)
|
s, what, object_name, e
);
e
})
.ok(),
None => match toml.lookup("name").and_then(Value::as_str) {
Some(name) => {
if name.contains(['.', '+', '*'].as_ref()) {
error!(
"Should be `pattern` instead of `name` in {} for `{}`",
what, object_name
);
None
} else {
Some(Ident::Name(name.into()))
}
}
None => None,
},
}
}
pub fn is_match(&self, name: &str) -> bool {
use self::Ident::*;
match self {
Name(n) => name == n,
Pattern(regex) => regex.is_match(name),
}
}
}
|
.map_err(|e| {
error!(
"Bad pattern `{}` in {} for `{}`: {}",
|
random_line_split
|
ident.rs
|
use super::error::TomlHelper;
use log::error;
use regex::Regex;
use std::fmt;
use toml::Value;
#[derive(Clone, Debug)]
pub enum Ident {
Name(String),
Pattern(Box<Regex>),
}
impl fmt::Display for Ident {
fn
|
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Ident::Name(name) => f.write_str(name),
Ident::Pattern(regex) => write!(f, "Regex {}", regex),
}
}
}
impl PartialEq for Ident {
fn eq(&self, other: &Ident) -> bool {
pub use self::Ident::*;
match (self, other) {
(Name(s1), Name(s2)) => s1 == s2,
(Pattern(r1), Pattern(r2)) => r1.as_str() == r2.as_str(),
_ => false,
}
}
}
impl Eq for Ident {}
impl Ident {
pub fn parse(toml: &Value, object_name: &str, what: &str) -> Option<Ident> {
match toml.lookup("pattern").and_then(Value::as_str) {
Some(s) => Regex::new(&format!("^{}$", s))
.map(Box::new)
.map(Ident::Pattern)
.map_err(|e| {
error!(
"Bad pattern `{}` in {} for `{}`: {}",
s, what, object_name, e
);
e
})
.ok(),
None => match toml.lookup("name").and_then(Value::as_str) {
Some(name) => {
if name.contains(['.', '+', '*'].as_ref()) {
error!(
"Should be `pattern` instead of `name` in {} for `{}`",
what, object_name
);
None
} else {
Some(Ident::Name(name.into()))
}
}
None => None,
},
}
}
pub fn is_match(&self, name: &str) -> bool {
use self::Ident::*;
match self {
Name(n) => name == n,
Pattern(regex) => regex.is_match(name),
}
}
}
|
fmt
|
identifier_name
|
ident.rs
|
use super::error::TomlHelper;
use log::error;
use regex::Regex;
use std::fmt;
use toml::Value;
#[derive(Clone, Debug)]
pub enum Ident {
Name(String),
Pattern(Box<Regex>),
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Ident::Name(name) => f.write_str(name),
Ident::Pattern(regex) => write!(f, "Regex {}", regex),
}
}
}
impl PartialEq for Ident {
fn eq(&self, other: &Ident) -> bool {
pub use self::Ident::*;
match (self, other) {
(Name(s1), Name(s2)) => s1 == s2,
(Pattern(r1), Pattern(r2)) => r1.as_str() == r2.as_str(),
_ => false,
}
}
}
impl Eq for Ident {}
impl Ident {
pub fn parse(toml: &Value, object_name: &str, what: &str) -> Option<Ident> {
match toml.lookup("pattern").and_then(Value::as_str) {
Some(s) => Regex::new(&format!("^{}$", s))
.map(Box::new)
.map(Ident::Pattern)
.map_err(|e| {
error!(
"Bad pattern `{}` in {} for `{}`: {}",
s, what, object_name, e
);
e
})
.ok(),
None => match toml.lookup("name").and_then(Value::as_str) {
Some(name) => {
if name.contains(['.', '+', '*'].as_ref()) {
error!(
"Should be `pattern` instead of `name` in {} for `{}`",
what, object_name
);
None
} else {
Some(Ident::Name(name.into()))
}
}
None => None,
},
}
}
pub fn is_match(&self, name: &str) -> bool
|
}
|
{
use self::Ident::*;
match self {
Name(n) => name == n,
Pattern(regex) => regex.is_match(name),
}
}
|
identifier_body
|
lib.rs
|
#![feature(const_fn)]
#![feature(alloc, allocator_api)]
#![no_std]
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(feature = "use_spin")]
extern crate spin;
extern crate alloc;
use alloc::alloc::{Alloc, AllocErr, Layout};
use core::alloc::{GlobalAlloc};
use core::mem;
#[cfg(feature = "use_spin")]
use core::ops::Deref;
use core::ptr::NonNull;
use hole::{Hole, HoleList};
#[cfg(feature = "use_spin")]
use spin::Mutex;
mod hole;
#[cfg(test)]
mod test;
/// A fixed size heap backed by a linked list of free memory blocks.
pub struct Heap {
bottom: usize,
size: usize,
holes: HoleList,
}
impl Heap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> Heap
|
/// Initializes an empty heap
///
/// # Unsafety
///
/// This function must be called at most once and must only be used on an
/// empty heap.
pub unsafe fn init(&mut self, heap_bottom: usize, heap_size: usize) {
self.bottom = heap_bottom;
self.size = heap_size;
self.holes = HoleList::new(heap_bottom, heap_size);
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> Heap {
Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}
}
/// Allocates a chunk of the given size with the given alignment. Returns a pointer to the
/// beginning of that chunk if it was successful. Else it returns `None`.
/// This function scans the list of free memory blocks and uses the first block that is big
/// enough. The runtime is in O(n) where n is the number of free blocks, but it should be
/// reasonably fast for small allocations.
pub fn allocate_first_fit(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
let mut size = layout.size();
if size < HoleList::min_size() {
size = HoleList::min_size();
}
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.allocate_first_fit(layout)
}
/// Frees the given allocation. `ptr` must be a pointer returned
/// by a call to the `allocate_first_fit` function with identical size and alignment. Undefined
/// behavior may occur for invalid arguments, thus this function is unsafe.
///
/// This function walks the list of free memory blocks and inserts the freed block at the
/// correct place. If the freed block is adjacent to another free block, the blocks are merged
/// again. This operation is in `O(n)` since the list needs to be sorted by address.
pub unsafe fn deallocate(&mut self, ptr: NonNull<u8>, layout: Layout) {
let mut size = layout.size();
if size < HoleList::min_size() {
size = HoleList::min_size();
}
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.deallocate(ptr, layout);
}
/// Returns the bottom address of the heap.
pub fn bottom(&self) -> usize {
self.bottom
}
/// Returns the size of the heap.
pub fn size(&self) -> usize {
self.size
}
/// Return the top address of the heap
pub fn top(&self) -> usize {
self.bottom + self.size
}
/// Extends the size of the heap by creating a new hole at the end
///
/// # Unsafety
///
/// The new extended area must be valid
pub unsafe fn extend(&mut self, by: usize) {
let top = self.top();
let layout = Layout::from_size_align(by, 1).unwrap();
self.holes
.deallocate(NonNull::new_unchecked(top as *mut u8), layout);
self.size += by;
}
}
unsafe impl Alloc for Heap {
unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
self.allocate_first_fit(layout)
}
unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
self.deallocate(ptr, layout)
}
}
#[cfg(feature = "use_spin")]
pub struct LockedHeap(Mutex<Heap>);
#[cfg(feature = "use_spin")]
impl LockedHeap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> LockedHeap {
LockedHeap(Mutex::new(Heap::empty()))
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> LockedHeap {
LockedHeap(Mutex::new(Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}))
}
}
#[cfg(feature = "use_spin")]
impl Deref for LockedHeap {
type Target = Mutex<Heap>;
fn deref(&self) -> &Mutex<Heap> {
&self.0
}
}
#[cfg(feature = "use_spin")]
unsafe impl GlobalAlloc for LockedHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.0
.lock()
.allocate_first_fit(layout)
.ok()
.map_or(0 as *mut u8, |allocation| allocation.as_ptr())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.0
.lock()
.deallocate(NonNull::new_unchecked(ptr), layout)
}
}
/// Align downwards. Returns the greatest x with alignment `align`
/// so that x <= addr. The alignment must be a power of 2.
pub fn align_down(addr: usize, align: usize) -> usize {
if align.is_power_of_two() {
addr &!(align - 1)
} else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
}
}
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, align)
}
|
{
Heap {
bottom: 0,
size: 0,
holes: HoleList::empty(),
}
}
|
identifier_body
|
lib.rs
|
#![feature(const_fn)]
#![feature(alloc, allocator_api)]
#![no_std]
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(feature = "use_spin")]
extern crate spin;
extern crate alloc;
use alloc::alloc::{Alloc, AllocErr, Layout};
use core::alloc::{GlobalAlloc};
use core::mem;
#[cfg(feature = "use_spin")]
use core::ops::Deref;
use core::ptr::NonNull;
use hole::{Hole, HoleList};
#[cfg(feature = "use_spin")]
use spin::Mutex;
mod hole;
#[cfg(test)]
mod test;
/// A fixed size heap backed by a linked list of free memory blocks.
pub struct Heap {
bottom: usize,
size: usize,
holes: HoleList,
}
impl Heap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> Heap {
Heap {
bottom: 0,
size: 0,
holes: HoleList::empty(),
}
}
/// Initializes an empty heap
///
/// # Unsafety
///
/// This function must be called at most once and must only be used on an
/// empty heap.
pub unsafe fn init(&mut self, heap_bottom: usize, heap_size: usize) {
self.bottom = heap_bottom;
self.size = heap_size;
self.holes = HoleList::new(heap_bottom, heap_size);
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> Heap {
Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}
}
/// Allocates a chunk of the given size with the given alignment. Returns a pointer to the
/// beginning of that chunk if it was successful. Else it returns `None`.
/// This function scans the list of free memory blocks and uses the first block that is big
/// enough. The runtime is in O(n) where n is the number of free blocks, but it should be
/// reasonably fast for small allocations.
pub fn allocate_first_fit(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
let mut size = layout.size();
if size < HoleList::min_size() {
size = HoleList::min_size();
}
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.allocate_first_fit(layout)
}
/// Frees the given allocation. `ptr` must be a pointer returned
/// by a call to the `allocate_first_fit` function with identical size and alignment. Undefined
/// behavior may occur for invalid arguments, thus this function is unsafe.
///
/// This function walks the list of free memory blocks and inserts the freed block at the
/// correct place. If the freed block is adjacent to another free block, the blocks are merged
/// again. This operation is in `O(n)` since the list needs to be sorted by address.
pub unsafe fn deallocate(&mut self, ptr: NonNull<u8>, layout: Layout) {
let mut size = layout.size();
if size < HoleList::min_size()
|
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.deallocate(ptr, layout);
}
/// Returns the bottom address of the heap.
pub fn bottom(&self) -> usize {
self.bottom
}
/// Returns the size of the heap.
pub fn size(&self) -> usize {
self.size
}
/// Return the top address of the heap
pub fn top(&self) -> usize {
self.bottom + self.size
}
/// Extends the size of the heap by creating a new hole at the end
///
/// # Unsafety
///
/// The new extended area must be valid
pub unsafe fn extend(&mut self, by: usize) {
let top = self.top();
let layout = Layout::from_size_align(by, 1).unwrap();
self.holes
.deallocate(NonNull::new_unchecked(top as *mut u8), layout);
self.size += by;
}
}
unsafe impl Alloc for Heap {
unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
self.allocate_first_fit(layout)
}
unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
self.deallocate(ptr, layout)
}
}
#[cfg(feature = "use_spin")]
pub struct LockedHeap(Mutex<Heap>);
#[cfg(feature = "use_spin")]
impl LockedHeap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> LockedHeap {
LockedHeap(Mutex::new(Heap::empty()))
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> LockedHeap {
LockedHeap(Mutex::new(Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}))
}
}
#[cfg(feature = "use_spin")]
impl Deref for LockedHeap {
type Target = Mutex<Heap>;
fn deref(&self) -> &Mutex<Heap> {
&self.0
}
}
#[cfg(feature = "use_spin")]
unsafe impl GlobalAlloc for LockedHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.0
.lock()
.allocate_first_fit(layout)
.ok()
.map_or(0 as *mut u8, |allocation| allocation.as_ptr())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.0
.lock()
.deallocate(NonNull::new_unchecked(ptr), layout)
}
}
/// Align downwards. Returns the greatest x with alignment `align`
/// so that x <= addr. The alignment must be a power of 2.
pub fn align_down(addr: usize, align: usize) -> usize {
if align.is_power_of_two() {
addr &!(align - 1)
} else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
}
}
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, align)
}
|
{
size = HoleList::min_size();
}
|
conditional_block
|
lib.rs
|
#![feature(const_fn)]
#![feature(alloc, allocator_api)]
#![no_std]
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(feature = "use_spin")]
extern crate spin;
extern crate alloc;
use alloc::alloc::{Alloc, AllocErr, Layout};
use core::alloc::{GlobalAlloc};
use core::mem;
#[cfg(feature = "use_spin")]
use core::ops::Deref;
use core::ptr::NonNull;
use hole::{Hole, HoleList};
#[cfg(feature = "use_spin")]
use spin::Mutex;
mod hole;
#[cfg(test)]
mod test;
/// A fixed size heap backed by a linked list of free memory blocks.
pub struct Heap {
bottom: usize,
size: usize,
holes: HoleList,
}
impl Heap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> Heap {
Heap {
bottom: 0,
size: 0,
holes: HoleList::empty(),
}
}
/// Initializes an empty heap
///
/// # Unsafety
///
/// This function must be called at most once and must only be used on an
/// empty heap.
pub unsafe fn init(&mut self, heap_bottom: usize, heap_size: usize) {
self.bottom = heap_bottom;
self.size = heap_size;
self.holes = HoleList::new(heap_bottom, heap_size);
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> Heap {
Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}
}
/// Allocates a chunk of the given size with the given alignment. Returns a pointer to the
/// beginning of that chunk if it was successful. Else it returns `None`.
/// This function scans the list of free memory blocks and uses the first block that is big
/// enough. The runtime is in O(n) where n is the number of free blocks, but it should be
/// reasonably fast for small allocations.
pub fn allocate_first_fit(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
let mut size = layout.size();
if size < HoleList::min_size() {
size = HoleList::min_size();
}
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.allocate_first_fit(layout)
}
/// Frees the given allocation. `ptr` must be a pointer returned
/// by a call to the `allocate_first_fit` function with identical size and alignment. Undefined
/// behavior may occur for invalid arguments, thus this function is unsafe.
///
/// This function walks the list of free memory blocks and inserts the freed block at the
/// correct place. If the freed block is adjacent to another free block, the blocks are merged
/// again. This operation is in `O(n)` since the list needs to be sorted by address.
pub unsafe fn
|
(&mut self, ptr: NonNull<u8>, layout: Layout) {
let mut size = layout.size();
if size < HoleList::min_size() {
size = HoleList::min_size();
}
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.deallocate(ptr, layout);
}
/// Returns the bottom address of the heap.
pub fn bottom(&self) -> usize {
self.bottom
}
/// Returns the size of the heap.
pub fn size(&self) -> usize {
self.size
}
/// Return the top address of the heap
pub fn top(&self) -> usize {
self.bottom + self.size
}
/// Extends the size of the heap by creating a new hole at the end
///
/// # Unsafety
///
/// The new extended area must be valid
pub unsafe fn extend(&mut self, by: usize) {
let top = self.top();
let layout = Layout::from_size_align(by, 1).unwrap();
self.holes
.deallocate(NonNull::new_unchecked(top as *mut u8), layout);
self.size += by;
}
}
unsafe impl Alloc for Heap {
unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
self.allocate_first_fit(layout)
}
unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
self.deallocate(ptr, layout)
}
}
#[cfg(feature = "use_spin")]
pub struct LockedHeap(Mutex<Heap>);
#[cfg(feature = "use_spin")]
impl LockedHeap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> LockedHeap {
LockedHeap(Mutex::new(Heap::empty()))
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> LockedHeap {
LockedHeap(Mutex::new(Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}))
}
}
#[cfg(feature = "use_spin")]
impl Deref for LockedHeap {
type Target = Mutex<Heap>;
fn deref(&self) -> &Mutex<Heap> {
&self.0
}
}
#[cfg(feature = "use_spin")]
unsafe impl GlobalAlloc for LockedHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.0
.lock()
.allocate_first_fit(layout)
.ok()
.map_or(0 as *mut u8, |allocation| allocation.as_ptr())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.0
.lock()
.deallocate(NonNull::new_unchecked(ptr), layout)
}
}
/// Align downwards. Returns the greatest x with alignment `align`
/// so that x <= addr. The alignment must be a power of 2.
pub fn align_down(addr: usize, align: usize) -> usize {
if align.is_power_of_two() {
addr &!(align - 1)
} else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
}
}
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, align)
}
|
deallocate
|
identifier_name
|
lib.rs
|
#![feature(const_fn)]
#![feature(alloc, allocator_api)]
#![no_std]
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(feature = "use_spin")]
extern crate spin;
extern crate alloc;
use alloc::alloc::{Alloc, AllocErr, Layout};
use core::alloc::{GlobalAlloc};
use core::mem;
#[cfg(feature = "use_spin")]
use core::ops::Deref;
use core::ptr::NonNull;
use hole::{Hole, HoleList};
#[cfg(feature = "use_spin")]
use spin::Mutex;
mod hole;
#[cfg(test)]
mod test;
/// A fixed size heap backed by a linked list of free memory blocks.
pub struct Heap {
bottom: usize,
size: usize,
holes: HoleList,
}
impl Heap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> Heap {
Heap {
bottom: 0,
size: 0,
holes: HoleList::empty(),
}
}
/// Initializes an empty heap
///
/// # Unsafety
///
/// This function must be called at most once and must only be used on an
/// empty heap.
pub unsafe fn init(&mut self, heap_bottom: usize, heap_size: usize) {
self.bottom = heap_bottom;
self.size = heap_size;
self.holes = HoleList::new(heap_bottom, heap_size);
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> Heap {
Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}
}
/// Allocates a chunk of the given size with the given alignment. Returns a pointer to the
/// beginning of that chunk if it was successful. Else it returns `None`.
/// This function scans the list of free memory blocks and uses the first block that is big
/// enough. The runtime is in O(n) where n is the number of free blocks, but it should be
/// reasonably fast for small allocations.
pub fn allocate_first_fit(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
let mut size = layout.size();
if size < HoleList::min_size() {
size = HoleList::min_size();
}
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.allocate_first_fit(layout)
}
/// Frees the given allocation. `ptr` must be a pointer returned
/// by a call to the `allocate_first_fit` function with identical size and alignment. Undefined
/// behavior may occur for invalid arguments, thus this function is unsafe.
///
/// This function walks the list of free memory blocks and inserts the freed block at the
/// correct place. If the freed block is adjacent to another free block, the blocks are merged
/// again. This operation is in `O(n)` since the list needs to be sorted by address.
pub unsafe fn deallocate(&mut self, ptr: NonNull<u8>, layout: Layout) {
let mut size = layout.size();
if size < HoleList::min_size() {
size = HoleList::min_size();
}
let size = align_up(size, mem::align_of::<Hole>());
let layout = Layout::from_size_align(size, layout.align()).unwrap();
self.holes.deallocate(ptr, layout);
}
/// Returns the bottom address of the heap.
pub fn bottom(&self) -> usize {
self.bottom
}
/// Returns the size of the heap.
pub fn size(&self) -> usize {
self.size
}
/// Return the top address of the heap
pub fn top(&self) -> usize {
self.bottom + self.size
}
/// Extends the size of the heap by creating a new hole at the end
///
/// # Unsafety
///
/// The new extended area must be valid
pub unsafe fn extend(&mut self, by: usize) {
let top = self.top();
let layout = Layout::from_size_align(by, 1).unwrap();
self.holes
.deallocate(NonNull::new_unchecked(top as *mut u8), layout);
self.size += by;
}
}
unsafe impl Alloc for Heap {
unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
self.allocate_first_fit(layout)
}
unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
self.deallocate(ptr, layout)
}
}
#[cfg(feature = "use_spin")]
pub struct LockedHeap(Mutex<Heap>);
#[cfg(feature = "use_spin")]
impl LockedHeap {
/// Creates an empty heap. All allocate calls will return `None`.
pub const fn empty() -> LockedHeap {
LockedHeap(Mutex::new(Heap::empty()))
}
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
/// anything else. This function is unsafe because it can cause undefined behavior if the
/// given address is invalid.
pub unsafe fn new(heap_bottom: usize, heap_size: usize) -> LockedHeap {
LockedHeap(Mutex::new(Heap {
bottom: heap_bottom,
size: heap_size,
holes: HoleList::new(heap_bottom, heap_size),
}))
}
}
#[cfg(feature = "use_spin")]
impl Deref for LockedHeap {
type Target = Mutex<Heap>;
fn deref(&self) -> &Mutex<Heap> {
&self.0
}
}
#[cfg(feature = "use_spin")]
unsafe impl GlobalAlloc for LockedHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.0
.lock()
.allocate_first_fit(layout)
.ok()
.map_or(0 as *mut u8, |allocation| allocation.as_ptr())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.0
.lock()
.deallocate(NonNull::new_unchecked(ptr), layout)
}
}
/// Align downwards. Returns the greatest x with alignment `align`
/// so that x <= addr. The alignment must be a power of 2.
pub fn align_down(addr: usize, align: usize) -> usize {
if align.is_power_of_two() {
addr &!(align - 1)
} else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
|
}
}
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, align)
}
|
random_line_split
|
|
buffer.rs
|
//! A buffer is used for decoding raw bytes
//!
//! It is represented by a copyable slice
//!
//! This is normally imported as buffer::* such that the
//! pub's can be considered to be in the global namespace
use std::mem;
use std::marker;
#[derive(Debug)]
pub struct EndOfBufferError;
#[derive(Clone,Copy,Debug)]
pub struct Buffer<'a> {
pub inner: &'a[u8]
}
/// Trait implemented for types that can be converted to a raw slice
/// Normally this is done by keeping the raw slice as part of the data structure
pub trait ToRaw<'a>
{
fn to_raw(&self) -> &[u8];
}
/// Trait implemented for types that can read itself from a Buffer
///
/// Should be implemented with zero-copying
pub trait Parse<'a>
where Self: marker::Sized
{
fn parse(buf: &mut Buffer<'a>) -> Result<Self, EndOfBufferError>;
}
impl<'a> Buffer<'a> {
/// Constructs a buffer from a slice
/// The buffer makes the slice Copyable
pub fn new(slice: &'a[u8]) -> Self {
Buffer {
inner: slice
}
|
}
/// Returns the buffer of what is contained in `original` that is no longer
/// in self. That is: returns whatever is consumed since original
pub fn consumed_since(self, original: Buffer) -> Buffer {
let len = original.inner.len() - self.inner.len();
Buffer {
inner: &original.inner[..len]
}
}
/// Reads a compact-size prefixed vector (like Vec::parse), but also returns a
/// vector if indices since the start of the buffer
pub fn parse_vec_with_indices<T>(&mut self, original: Buffer) -> Result<(Vec<T>,Vec<u32>), EndOfBufferError>
where T: Parse<'a> {
let original_len = original.inner.len() as u32;
let count = self.parse_compact_size()?;
let mut result: Vec<T> = Vec::with_capacity(count);
let mut result_idx: Vec<u32> = Vec::with_capacity(count);
for _ in 0..count {
result_idx.push(original_len - self.inner.len() as u32);
result.push(try!(T::parse(self)));
}
Ok((result, result_idx))
}
/// Parse a compact size
/// This can be 1-8 bytes; see bitcoin-spec for details
pub fn parse_compact_size(&mut self) -> Result<usize, EndOfBufferError> {
let byte1 = { try!(u8::parse(self)) };
Ok(match byte1 {
0xff => { try!(u64::parse(self)) as usize },
0xfe => { try!(u32::parse(self)) as usize },
0xfd => { try!(u16::parse(self)) as usize },
_ => byte1 as usize
})
}
/// Parses given amount of bytes
pub fn parse_bytes(&mut self, count: usize) -> Result<&'a[u8], EndOfBufferError> {
if self.inner.len() < count {
return Err(EndOfBufferError);
}
// split in result, and remaining
let result = &self.inner[..count];
self.inner = &self.inner[count..];
Ok(result)
}
pub fn parse_compact_size_bytes(&mut self) -> Result<&'a[u8], EndOfBufferError> {
let count = try!(self.parse_compact_size());
self.parse_bytes(count)
}
}
impl<'a, T : Parse<'a>> Parse<'a> for Vec<T> {
/// Parses a compact-size prefix vector of parsable stuff
fn parse(buffer: &mut Buffer<'a>) -> Result<Vec<T>, EndOfBufferError> {
let count = try!(buffer.parse_compact_size());
let mut result: Vec<T> = Vec::with_capacity(count);
for _ in 0..count {
result.push(try!(T::parse(buffer)));
}
Ok(result)
}
}
macro_rules! impl_parse_primitive {
($prim_type: ty) =>
(
impl<'a> Parse<'a> for $prim_type {
fn parse(buffer: &mut Buffer<'a>) -> Result<$prim_type, EndOfBufferError> {
let sz = mem::size_of::<$prim_type>();
if buffer.inner.len() < sz {
return Err(EndOfBufferError);
}
// Shift-n-fold
let result = (0..sz)
.map(|n| (buffer.inner[n] as $prim_type) << (8* n) )
.fold(0, |a,b| a | b);
buffer.inner = &buffer.inner[sz..];
Ok(result)
}
}
)
}
impl_parse_primitive!(u32);
impl_parse_primitive!(i64);
impl_parse_primitive!(i32);
impl_parse_primitive!(u8);
impl_parse_primitive!(u16);
impl_parse_primitive!(u64);
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_primitive() {
let x = &[0xff_u8, 0x00_u8, 0x00_u8, 0x00_u8];
let mut buf = Buffer { inner: x };
let org_buf = buf;
assert_eq!(u32::parse(&mut buf).unwrap(), 0xff_u32);
assert_eq!(buf.len(), 0);
assert_eq!(buf.consumed_since(org_buf).len(), 4);
}
}
|
}
pub fn len(self) -> usize {
self.inner.len()
|
random_line_split
|
buffer.rs
|
//! A buffer is used for decoding raw bytes
//!
//! It is represented by a copyable slice
//!
//! This is normally imported as buffer::* such that the
//! pub's can be considered to be in the global namespace
use std::mem;
use std::marker;
#[derive(Debug)]
pub struct EndOfBufferError;
#[derive(Clone,Copy,Debug)]
pub struct Buffer<'a> {
pub inner: &'a[u8]
}
/// Trait implemented for types that can be converted to a raw slice
/// Normally this is done by keeping the raw slice as part of the data structure
pub trait ToRaw<'a>
{
fn to_raw(&self) -> &[u8];
}
/// Trait implemented for types that can read itself from a Buffer
///
/// Should be implemented with zero-copying
pub trait Parse<'a>
where Self: marker::Sized
{
fn parse(buf: &mut Buffer<'a>) -> Result<Self, EndOfBufferError>;
}
impl<'a> Buffer<'a> {
/// Constructs a buffer from a slice
/// The buffer makes the slice Copyable
pub fn new(slice: &'a[u8]) -> Self {
Buffer {
inner: slice
}
}
pub fn len(self) -> usize {
self.inner.len()
}
/// Returns the buffer of what is contained in `original` that is no longer
/// in self. That is: returns whatever is consumed since original
pub fn consumed_since(self, original: Buffer) -> Buffer {
let len = original.inner.len() - self.inner.len();
Buffer {
inner: &original.inner[..len]
}
}
/// Reads a compact-size prefixed vector (like Vec::parse), but also returns a
/// vector if indices since the start of the buffer
pub fn parse_vec_with_indices<T>(&mut self, original: Buffer) -> Result<(Vec<T>,Vec<u32>), EndOfBufferError>
where T: Parse<'a> {
let original_len = original.inner.len() as u32;
let count = self.parse_compact_size()?;
let mut result: Vec<T> = Vec::with_capacity(count);
let mut result_idx: Vec<u32> = Vec::with_capacity(count);
for _ in 0..count {
result_idx.push(original_len - self.inner.len() as u32);
result.push(try!(T::parse(self)));
}
Ok((result, result_idx))
}
/// Parse a compact size
/// This can be 1-8 bytes; see bitcoin-spec for details
pub fn parse_compact_size(&mut self) -> Result<usize, EndOfBufferError> {
let byte1 = { try!(u8::parse(self)) };
Ok(match byte1 {
0xff => { try!(u64::parse(self)) as usize },
0xfe => { try!(u32::parse(self)) as usize },
0xfd => { try!(u16::parse(self)) as usize },
_ => byte1 as usize
})
}
/// Parses given amount of bytes
pub fn parse_bytes(&mut self, count: usize) -> Result<&'a[u8], EndOfBufferError> {
if self.inner.len() < count {
return Err(EndOfBufferError);
}
// split in result, and remaining
let result = &self.inner[..count];
self.inner = &self.inner[count..];
Ok(result)
}
pub fn parse_compact_size_bytes(&mut self) -> Result<&'a[u8], EndOfBufferError> {
let count = try!(self.parse_compact_size());
self.parse_bytes(count)
}
}
impl<'a, T : Parse<'a>> Parse<'a> for Vec<T> {
/// Parses a compact-size prefix vector of parsable stuff
fn parse(buffer: &mut Buffer<'a>) -> Result<Vec<T>, EndOfBufferError> {
let count = try!(buffer.parse_compact_size());
let mut result: Vec<T> = Vec::with_capacity(count);
for _ in 0..count {
result.push(try!(T::parse(buffer)));
}
Ok(result)
}
}
macro_rules! impl_parse_primitive {
($prim_type: ty) =>
(
impl<'a> Parse<'a> for $prim_type {
fn parse(buffer: &mut Buffer<'a>) -> Result<$prim_type, EndOfBufferError> {
let sz = mem::size_of::<$prim_type>();
if buffer.inner.len() < sz {
return Err(EndOfBufferError);
}
// Shift-n-fold
let result = (0..sz)
.map(|n| (buffer.inner[n] as $prim_type) << (8* n) )
.fold(0, |a,b| a | b);
buffer.inner = &buffer.inner[sz..];
Ok(result)
}
}
)
}
impl_parse_primitive!(u32);
impl_parse_primitive!(i64);
impl_parse_primitive!(i32);
impl_parse_primitive!(u8);
impl_parse_primitive!(u16);
impl_parse_primitive!(u64);
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_primitive()
|
}
|
{
let x = &[0xff_u8, 0x00_u8, 0x00_u8, 0x00_u8];
let mut buf = Buffer { inner: x };
let org_buf = buf;
assert_eq!(u32::parse(&mut buf).unwrap(), 0xff_u32);
assert_eq!(buf.len(), 0);
assert_eq!(buf.consumed_since(org_buf).len(), 4);
}
|
identifier_body
|
buffer.rs
|
//! A buffer is used for decoding raw bytes
//!
//! It is represented by a copyable slice
//!
//! This is normally imported as buffer::* such that the
//! pub's can be considered to be in the global namespace
use std::mem;
use std::marker;
#[derive(Debug)]
pub struct EndOfBufferError;
#[derive(Clone,Copy,Debug)]
pub struct Buffer<'a> {
pub inner: &'a[u8]
}
/// Trait implemented for types that can be converted to a raw slice
/// Normally this is done by keeping the raw slice as part of the data structure
pub trait ToRaw<'a>
{
fn to_raw(&self) -> &[u8];
}
/// Trait implemented for types that can read itself from a Buffer
///
/// Should be implemented with zero-copying
pub trait Parse<'a>
where Self: marker::Sized
{
fn parse(buf: &mut Buffer<'a>) -> Result<Self, EndOfBufferError>;
}
impl<'a> Buffer<'a> {
/// Constructs a buffer from a slice
/// The buffer makes the slice Copyable
pub fn new(slice: &'a[u8]) -> Self {
Buffer {
inner: slice
}
}
pub fn len(self) -> usize {
self.inner.len()
}
/// Returns the buffer of what is contained in `original` that is no longer
/// in self. That is: returns whatever is consumed since original
pub fn consumed_since(self, original: Buffer) -> Buffer {
let len = original.inner.len() - self.inner.len();
Buffer {
inner: &original.inner[..len]
}
}
/// Reads a compact-size prefixed vector (like Vec::parse), but also returns a
/// vector if indices since the start of the buffer
pub fn parse_vec_with_indices<T>(&mut self, original: Buffer) -> Result<(Vec<T>,Vec<u32>), EndOfBufferError>
where T: Parse<'a> {
let original_len = original.inner.len() as u32;
let count = self.parse_compact_size()?;
let mut result: Vec<T> = Vec::with_capacity(count);
let mut result_idx: Vec<u32> = Vec::with_capacity(count);
for _ in 0..count {
result_idx.push(original_len - self.inner.len() as u32);
result.push(try!(T::parse(self)));
}
Ok((result, result_idx))
}
/// Parse a compact size
/// This can be 1-8 bytes; see bitcoin-spec for details
pub fn parse_compact_size(&mut self) -> Result<usize, EndOfBufferError> {
let byte1 = { try!(u8::parse(self)) };
Ok(match byte1 {
0xff => { try!(u64::parse(self)) as usize },
0xfe => { try!(u32::parse(self)) as usize },
0xfd => { try!(u16::parse(self)) as usize },
_ => byte1 as usize
})
}
/// Parses given amount of bytes
pub fn parse_bytes(&mut self, count: usize) -> Result<&'a[u8], EndOfBufferError> {
if self.inner.len() < count {
return Err(EndOfBufferError);
}
// split in result, and remaining
let result = &self.inner[..count];
self.inner = &self.inner[count..];
Ok(result)
}
pub fn parse_compact_size_bytes(&mut self) -> Result<&'a[u8], EndOfBufferError> {
let count = try!(self.parse_compact_size());
self.parse_bytes(count)
}
}
impl<'a, T : Parse<'a>> Parse<'a> for Vec<T> {
/// Parses a compact-size prefix vector of parsable stuff
fn
|
(buffer: &mut Buffer<'a>) -> Result<Vec<T>, EndOfBufferError> {
let count = try!(buffer.parse_compact_size());
let mut result: Vec<T> = Vec::with_capacity(count);
for _ in 0..count {
result.push(try!(T::parse(buffer)));
}
Ok(result)
}
}
macro_rules! impl_parse_primitive {
($prim_type: ty) =>
(
impl<'a> Parse<'a> for $prim_type {
fn parse(buffer: &mut Buffer<'a>) -> Result<$prim_type, EndOfBufferError> {
let sz = mem::size_of::<$prim_type>();
if buffer.inner.len() < sz {
return Err(EndOfBufferError);
}
// Shift-n-fold
let result = (0..sz)
.map(|n| (buffer.inner[n] as $prim_type) << (8* n) )
.fold(0, |a,b| a | b);
buffer.inner = &buffer.inner[sz..];
Ok(result)
}
}
)
}
impl_parse_primitive!(u32);
impl_parse_primitive!(i64);
impl_parse_primitive!(i32);
impl_parse_primitive!(u8);
impl_parse_primitive!(u16);
impl_parse_primitive!(u64);
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_primitive() {
let x = &[0xff_u8, 0x00_u8, 0x00_u8, 0x00_u8];
let mut buf = Buffer { inner: x };
let org_buf = buf;
assert_eq!(u32::parse(&mut buf).unwrap(), 0xff_u32);
assert_eq!(buf.len(), 0);
assert_eq!(buf.consumed_since(org_buf).len(), 4);
}
}
|
parse
|
identifier_name
|
buffer.rs
|
//! A buffer is used for decoding raw bytes
//!
//! It is represented by a copyable slice
//!
//! This is normally imported as buffer::* such that the
//! pub's can be considered to be in the global namespace
use std::mem;
use std::marker;
#[derive(Debug)]
pub struct EndOfBufferError;
#[derive(Clone,Copy,Debug)]
pub struct Buffer<'a> {
pub inner: &'a[u8]
}
/// Trait implemented for types that can be converted to a raw slice
/// Normally this is done by keeping the raw slice as part of the data structure
pub trait ToRaw<'a>
{
fn to_raw(&self) -> &[u8];
}
/// Trait implemented for types that can read itself from a Buffer
///
/// Should be implemented with zero-copying
pub trait Parse<'a>
where Self: marker::Sized
{
fn parse(buf: &mut Buffer<'a>) -> Result<Self, EndOfBufferError>;
}
impl<'a> Buffer<'a> {
/// Constructs a buffer from a slice
/// The buffer makes the slice Copyable
pub fn new(slice: &'a[u8]) -> Self {
Buffer {
inner: slice
}
}
pub fn len(self) -> usize {
self.inner.len()
}
/// Returns the buffer of what is contained in `original` that is no longer
/// in self. That is: returns whatever is consumed since original
pub fn consumed_since(self, original: Buffer) -> Buffer {
let len = original.inner.len() - self.inner.len();
Buffer {
inner: &original.inner[..len]
}
}
/// Reads a compact-size prefixed vector (like Vec::parse), but also returns a
/// vector if indices since the start of the buffer
pub fn parse_vec_with_indices<T>(&mut self, original: Buffer) -> Result<(Vec<T>,Vec<u32>), EndOfBufferError>
where T: Parse<'a> {
let original_len = original.inner.len() as u32;
let count = self.parse_compact_size()?;
let mut result: Vec<T> = Vec::with_capacity(count);
let mut result_idx: Vec<u32> = Vec::with_capacity(count);
for _ in 0..count {
result_idx.push(original_len - self.inner.len() as u32);
result.push(try!(T::parse(self)));
}
Ok((result, result_idx))
}
/// Parse a compact size
/// This can be 1-8 bytes; see bitcoin-spec for details
pub fn parse_compact_size(&mut self) -> Result<usize, EndOfBufferError> {
let byte1 = { try!(u8::parse(self)) };
Ok(match byte1 {
0xff => { try!(u64::parse(self)) as usize },
0xfe => { try!(u32::parse(self)) as usize },
0xfd =>
|
,
_ => byte1 as usize
})
}
/// Parses given amount of bytes
pub fn parse_bytes(&mut self, count: usize) -> Result<&'a[u8], EndOfBufferError> {
if self.inner.len() < count {
return Err(EndOfBufferError);
}
// split in result, and remaining
let result = &self.inner[..count];
self.inner = &self.inner[count..];
Ok(result)
}
pub fn parse_compact_size_bytes(&mut self) -> Result<&'a[u8], EndOfBufferError> {
let count = try!(self.parse_compact_size());
self.parse_bytes(count)
}
}
impl<'a, T : Parse<'a>> Parse<'a> for Vec<T> {
/// Parses a compact-size prefix vector of parsable stuff
fn parse(buffer: &mut Buffer<'a>) -> Result<Vec<T>, EndOfBufferError> {
let count = try!(buffer.parse_compact_size());
let mut result: Vec<T> = Vec::with_capacity(count);
for _ in 0..count {
result.push(try!(T::parse(buffer)));
}
Ok(result)
}
}
macro_rules! impl_parse_primitive {
($prim_type: ty) =>
(
impl<'a> Parse<'a> for $prim_type {
fn parse(buffer: &mut Buffer<'a>) -> Result<$prim_type, EndOfBufferError> {
let sz = mem::size_of::<$prim_type>();
if buffer.inner.len() < sz {
return Err(EndOfBufferError);
}
// Shift-n-fold
let result = (0..sz)
.map(|n| (buffer.inner[n] as $prim_type) << (8* n) )
.fold(0, |a,b| a | b);
buffer.inner = &buffer.inner[sz..];
Ok(result)
}
}
)
}
impl_parse_primitive!(u32);
impl_parse_primitive!(i64);
impl_parse_primitive!(i32);
impl_parse_primitive!(u8);
impl_parse_primitive!(u16);
impl_parse_primitive!(u64);
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_primitive() {
let x = &[0xff_u8, 0x00_u8, 0x00_u8, 0x00_u8];
let mut buf = Buffer { inner: x };
let org_buf = buf;
assert_eq!(u32::parse(&mut buf).unwrap(), 0xff_u32);
assert_eq!(buf.len(), 0);
assert_eq!(buf.consumed_since(org_buf).len(), 4);
}
}
|
{ try!(u16::parse(self)) as usize }
|
conditional_block
|
if-check.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.
fn even(x: uint) -> bool {
if x < 2u {
return false;
} else if x == 2u { return true; } else { return even(x - 2u); }
}
fn
|
(x: uint) {
if even(x) {
info2!("{}", x);
} else {
fail2!();
}
}
pub fn main() { foo(2u); }
|
foo
|
identifier_name
|
if-check.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.
fn even(x: uint) -> bool {
if x < 2u {
return false;
} else if x == 2u { return true; } else { return even(x - 2u); }
}
fn foo(x: uint) {
if even(x) {
info2!("{}", x);
} else
|
}
pub fn main() { foo(2u); }
|
{
fail2!();
}
|
conditional_block
|
if-check.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.
fn even(x: uint) -> bool {
if x < 2u {
return false;
} else if x == 2u { return true; } else { return even(x - 2u); }
}
fn foo(x: uint)
|
pub fn main() { foo(2u); }
|
{
if even(x) {
info2!("{}", x);
} else {
fail2!();
}
}
|
identifier_body
|
if-check.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
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn even(x: uint) -> bool {
if x < 2u {
return false;
} else if x == 2u { return true; } else { return even(x - 2u); }
}
fn foo(x: uint) {
if even(x) {
info2!("{}", x);
} else {
fail2!();
}
}
pub fn main() { foo(2u); }
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
random_line_split
|
proxyhandler.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/. */
//! Utilities for the implementation of JSAPI proxy handlers.
#![deny(missing_docs)]
use dom::bindings::conversions::is_dom_proxy;
use dom::bindings::utils::delete_property_by_id;
use js::glue::GetProxyExtra;
use js::glue::InvokeGetOwnPropertyDescriptor;
use js::glue::{GetProxyHandler, SetProxyExtra};
use js::jsapi::GetObjectProto;
use js::jsapi::{Handle, HandleId, HandleObject, MutableHandle, ObjectOpResult, RootedObject};
use js::jsapi::{JSContext, JSObject, JSPropertyDescriptor};
use js::jsapi::{JSErrNum, JS_StrictPropertyStub};
use js::jsapi::{JS_DefinePropertyById6, JS_NewObjectWithGivenProto};
use js::jsapi::{JS_GetPropertyDescriptorById};
use js::jsval::ObjectValue;
use js::{JSPROP_ENUMERATE, JSPROP_GETTER, JSPROP_READONLY};
use libc;
use std::{mem, ptr};
static JSPROXYSLOT_EXPANDO: u32 = 0;
/// Invoke the [[GetOwnProperty]] trap (`getOwnPropertyDescriptor`) on `proxy`,
/// with argument `id` and return the result, if it is not `undefined`.
/// Otherwise, walk along the prototype chain to find a property with that
/// name.
pub unsafe extern fn get_property_descriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
desc: MutableHandle<JSPropertyDescriptor>)
-> bool {
let handler = GetProxyHandler(proxy.get());
if!InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, desc) {
return false;
}
if!desc.get().obj.is_null() {
return true;
}
let mut proto = RootedObject::new(cx, ptr::null_mut());
if!GetObjectProto(cx, proxy, proto.handle_mut()) {
desc.get().obj = ptr::null_mut();
return true;
}
JS_GetPropertyDescriptorById(cx, proto.handle(), id, desc)
}
/// Defines an expando on the given `proxy`.
pub unsafe extern fn define_property(cx: *mut JSContext, proxy: HandleObject,
id: HandleId, desc: Handle<JSPropertyDescriptor>,
result: *mut ObjectOpResult)
-> bool {
//FIXME: Workaround for https://github.com/mozilla/rust/issues/13385
let setter: *const libc::c_void = mem::transmute(desc.get().setter);
let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub);
if (desc.get().attrs & JSPROP_GETTER)!= 0 && setter == setter_stub {
(*result).code_ = JSErrNum::JSMSG_GETTER_ONLY as ::libc::uintptr_t;
return true;
}
let expando = RootedObject::new(cx, ensure_expando_object(cx, proxy));
JS_DefinePropertyById6(cx, expando.handle(), id, desc, result)
}
/// Deletes an expando off the given `proxy`.
pub unsafe extern fn delete(cx: *mut JSContext, proxy: HandleObject, id: HandleId,
bp: *mut ObjectOpResult) -> bool {
let expando = RootedObject::new(cx, get_expando_object(proxy));
if expando.ptr.is_null() {
(*bp).code_ = 0 /* OkCode */;
return true;
}
delete_property_by_id(cx, expando.handle(), id, bp)
}
/// Controls whether the Extensible bit can be changed
pub unsafe extern fn prevent_extensions(_cx: *mut JSContext,
_proxy: HandleObject,
result: *mut ObjectOpResult) -> bool {
(*result).code_ = JSErrNum::JSMSG_CANT_PREVENT_EXTENSIONS as ::libc::uintptr_t;
true
}
/// Reports whether the object is Extensible
pub unsafe extern fn is_extensible(_cx: *mut JSContext, _proxy: HandleObject,
succeeded: *mut bool) -> bool {
*succeeded = true;
true
}
/// Get the expando object, or null if there is none.
pub fn get_expando_object(obj: HandleObject) -> *mut JSObject {
unsafe {
assert!(is_dom_proxy(obj.get()));
let val = GetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO);
if val.is_undefined() {
ptr::null_mut()
} else {
val.to_object()
}
}
}
/// Get the expando object, or create it if it doesn't exist yet.
/// Fails on JSAPI failure.
pub fn ensure_expando_object(cx: *mut JSContext, obj: HandleObject)
-> *mut JSObject
|
/// Set the property descriptor's object to `obj` and set it to enumerable,
/// and writable if `readonly` is true.
pub fn fill_property_descriptor(desc: &mut JSPropertyDescriptor,
obj: *mut JSObject, readonly: bool) {
desc.obj = obj;
desc.attrs = if readonly { JSPROP_READONLY } else { 0 } | JSPROP_ENUMERATE;
desc.getter = None;
desc.setter = None;
}
|
{
unsafe {
assert!(is_dom_proxy(obj.get()));
let mut expando = get_expando_object(obj);
if expando.is_null() {
expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null());
assert!(!expando.is_null());
SetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO, ObjectValue(&*expando));
}
expando
}
}
|
identifier_body
|
proxyhandler.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/. */
//! Utilities for the implementation of JSAPI proxy handlers.
#![deny(missing_docs)]
use dom::bindings::conversions::is_dom_proxy;
use dom::bindings::utils::delete_property_by_id;
use js::glue::GetProxyExtra;
use js::glue::InvokeGetOwnPropertyDescriptor;
use js::glue::{GetProxyHandler, SetProxyExtra};
use js::jsapi::GetObjectProto;
use js::jsapi::{Handle, HandleId, HandleObject, MutableHandle, ObjectOpResult, RootedObject};
use js::jsapi::{JSContext, JSObject, JSPropertyDescriptor};
use js::jsapi::{JSErrNum, JS_StrictPropertyStub};
use js::jsapi::{JS_DefinePropertyById6, JS_NewObjectWithGivenProto};
use js::jsapi::{JS_GetPropertyDescriptorById};
use js::jsval::ObjectValue;
use js::{JSPROP_ENUMERATE, JSPROP_GETTER, JSPROP_READONLY};
use libc;
use std::{mem, ptr};
static JSPROXYSLOT_EXPANDO: u32 = 0;
/// Invoke the [[GetOwnProperty]] trap (`getOwnPropertyDescriptor`) on `proxy`,
/// with argument `id` and return the result, if it is not `undefined`.
/// Otherwise, walk along the prototype chain to find a property with that
/// name.
pub unsafe extern fn get_property_descriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
desc: MutableHandle<JSPropertyDescriptor>)
-> bool {
let handler = GetProxyHandler(proxy.get());
if!InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, desc) {
return false;
}
if!desc.get().obj.is_null() {
return true;
}
let mut proto = RootedObject::new(cx, ptr::null_mut());
if!GetObjectProto(cx, proxy, proto.handle_mut())
|
JS_GetPropertyDescriptorById(cx, proto.handle(), id, desc)
}
/// Defines an expando on the given `proxy`.
pub unsafe extern fn define_property(cx: *mut JSContext, proxy: HandleObject,
id: HandleId, desc: Handle<JSPropertyDescriptor>,
result: *mut ObjectOpResult)
-> bool {
//FIXME: Workaround for https://github.com/mozilla/rust/issues/13385
let setter: *const libc::c_void = mem::transmute(desc.get().setter);
let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub);
if (desc.get().attrs & JSPROP_GETTER)!= 0 && setter == setter_stub {
(*result).code_ = JSErrNum::JSMSG_GETTER_ONLY as ::libc::uintptr_t;
return true;
}
let expando = RootedObject::new(cx, ensure_expando_object(cx, proxy));
JS_DefinePropertyById6(cx, expando.handle(), id, desc, result)
}
/// Deletes an expando off the given `proxy`.
pub unsafe extern fn delete(cx: *mut JSContext, proxy: HandleObject, id: HandleId,
bp: *mut ObjectOpResult) -> bool {
let expando = RootedObject::new(cx, get_expando_object(proxy));
if expando.ptr.is_null() {
(*bp).code_ = 0 /* OkCode */;
return true;
}
delete_property_by_id(cx, expando.handle(), id, bp)
}
/// Controls whether the Extensible bit can be changed
pub unsafe extern fn prevent_extensions(_cx: *mut JSContext,
_proxy: HandleObject,
result: *mut ObjectOpResult) -> bool {
(*result).code_ = JSErrNum::JSMSG_CANT_PREVENT_EXTENSIONS as ::libc::uintptr_t;
true
}
/// Reports whether the object is Extensible
pub unsafe extern fn is_extensible(_cx: *mut JSContext, _proxy: HandleObject,
succeeded: *mut bool) -> bool {
*succeeded = true;
true
}
/// Get the expando object, or null if there is none.
pub fn get_expando_object(obj: HandleObject) -> *mut JSObject {
unsafe {
assert!(is_dom_proxy(obj.get()));
let val = GetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO);
if val.is_undefined() {
ptr::null_mut()
} else {
val.to_object()
}
}
}
/// Get the expando object, or create it if it doesn't exist yet.
/// Fails on JSAPI failure.
pub fn ensure_expando_object(cx: *mut JSContext, obj: HandleObject)
-> *mut JSObject {
unsafe {
assert!(is_dom_proxy(obj.get()));
let mut expando = get_expando_object(obj);
if expando.is_null() {
expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null());
assert!(!expando.is_null());
SetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO, ObjectValue(&*expando));
}
expando
}
}
/// Set the property descriptor's object to `obj` and set it to enumerable,
/// and writable if `readonly` is true.
pub fn fill_property_descriptor(desc: &mut JSPropertyDescriptor,
obj: *mut JSObject, readonly: bool) {
desc.obj = obj;
desc.attrs = if readonly { JSPROP_READONLY } else { 0 } | JSPROP_ENUMERATE;
desc.getter = None;
desc.setter = None;
}
|
{
desc.get().obj = ptr::null_mut();
return true;
}
|
conditional_block
|
proxyhandler.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/. */
//! Utilities for the implementation of JSAPI proxy handlers.
#![deny(missing_docs)]
use dom::bindings::conversions::is_dom_proxy;
use dom::bindings::utils::delete_property_by_id;
use js::glue::GetProxyExtra;
use js::glue::InvokeGetOwnPropertyDescriptor;
use js::glue::{GetProxyHandler, SetProxyExtra};
use js::jsapi::GetObjectProto;
use js::jsapi::{Handle, HandleId, HandleObject, MutableHandle, ObjectOpResult, RootedObject};
use js::jsapi::{JSContext, JSObject, JSPropertyDescriptor};
use js::jsapi::{JSErrNum, JS_StrictPropertyStub};
use js::jsapi::{JS_DefinePropertyById6, JS_NewObjectWithGivenProto};
use js::jsapi::{JS_GetPropertyDescriptorById};
use js::jsval::ObjectValue;
use js::{JSPROP_ENUMERATE, JSPROP_GETTER, JSPROP_READONLY};
use libc;
use std::{mem, ptr};
static JSPROXYSLOT_EXPANDO: u32 = 0;
/// Invoke the [[GetOwnProperty]] trap (`getOwnPropertyDescriptor`) on `proxy`,
/// with argument `id` and return the result, if it is not `undefined`.
/// Otherwise, walk along the prototype chain to find a property with that
/// name.
pub unsafe extern fn get_property_descriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
desc: MutableHandle<JSPropertyDescriptor>)
-> bool {
let handler = GetProxyHandler(proxy.get());
if!InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, desc) {
return false;
}
if!desc.get().obj.is_null() {
return true;
}
let mut proto = RootedObject::new(cx, ptr::null_mut());
if!GetObjectProto(cx, proxy, proto.handle_mut()) {
desc.get().obj = ptr::null_mut();
return true;
}
JS_GetPropertyDescriptorById(cx, proto.handle(), id, desc)
}
/// Defines an expando on the given `proxy`.
pub unsafe extern fn
|
(cx: *mut JSContext, proxy: HandleObject,
id: HandleId, desc: Handle<JSPropertyDescriptor>,
result: *mut ObjectOpResult)
-> bool {
//FIXME: Workaround for https://github.com/mozilla/rust/issues/13385
let setter: *const libc::c_void = mem::transmute(desc.get().setter);
let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub);
if (desc.get().attrs & JSPROP_GETTER)!= 0 && setter == setter_stub {
(*result).code_ = JSErrNum::JSMSG_GETTER_ONLY as ::libc::uintptr_t;
return true;
}
let expando = RootedObject::new(cx, ensure_expando_object(cx, proxy));
JS_DefinePropertyById6(cx, expando.handle(), id, desc, result)
}
/// Deletes an expando off the given `proxy`.
pub unsafe extern fn delete(cx: *mut JSContext, proxy: HandleObject, id: HandleId,
bp: *mut ObjectOpResult) -> bool {
let expando = RootedObject::new(cx, get_expando_object(proxy));
if expando.ptr.is_null() {
(*bp).code_ = 0 /* OkCode */;
return true;
}
delete_property_by_id(cx, expando.handle(), id, bp)
}
/// Controls whether the Extensible bit can be changed
pub unsafe extern fn prevent_extensions(_cx: *mut JSContext,
_proxy: HandleObject,
result: *mut ObjectOpResult) -> bool {
(*result).code_ = JSErrNum::JSMSG_CANT_PREVENT_EXTENSIONS as ::libc::uintptr_t;
true
}
/// Reports whether the object is Extensible
pub unsafe extern fn is_extensible(_cx: *mut JSContext, _proxy: HandleObject,
succeeded: *mut bool) -> bool {
*succeeded = true;
true
}
/// Get the expando object, or null if there is none.
pub fn get_expando_object(obj: HandleObject) -> *mut JSObject {
unsafe {
assert!(is_dom_proxy(obj.get()));
let val = GetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO);
if val.is_undefined() {
ptr::null_mut()
} else {
val.to_object()
}
}
}
/// Get the expando object, or create it if it doesn't exist yet.
/// Fails on JSAPI failure.
pub fn ensure_expando_object(cx: *mut JSContext, obj: HandleObject)
-> *mut JSObject {
unsafe {
assert!(is_dom_proxy(obj.get()));
let mut expando = get_expando_object(obj);
if expando.is_null() {
expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null());
assert!(!expando.is_null());
SetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO, ObjectValue(&*expando));
}
expando
}
}
/// Set the property descriptor's object to `obj` and set it to enumerable,
/// and writable if `readonly` is true.
pub fn fill_property_descriptor(desc: &mut JSPropertyDescriptor,
obj: *mut JSObject, readonly: bool) {
desc.obj = obj;
desc.attrs = if readonly { JSPROP_READONLY } else { 0 } | JSPROP_ENUMERATE;
desc.getter = None;
desc.setter = None;
}
|
define_property
|
identifier_name
|
issue-4252.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.
//
|
#![feature(unsafe_destructor)]
trait X {
fn call<T: std::fmt::Debug>(&self, x: &T);
fn default_method<T: std::fmt::Debug>(&self, x: &T) {
println!("X::default_method {:?}", x);
}
}
#[derive(Debug)]
struct Y(int);
#[derive(Debug)]
struct Z<T> {
x: T
}
impl X for Y {
fn call<T: std::fmt::Debug>(&self, x: &T) {
println!("X::call {:?} {:?}", self, x);
}
}
#[unsafe_destructor]
impl<T: X + std::fmt::Debug> Drop for Z<T> {
fn drop(&mut self) {
// These statements used to cause an ICE.
self.x.call(self);
self.x.default_method(self);
}
}
pub fn main() {
let _z = Z {x: Y(42)};
}
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
random_line_split
|
issue-4252.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.
#![feature(unsafe_destructor)]
trait X {
fn call<T: std::fmt::Debug>(&self, x: &T);
fn default_method<T: std::fmt::Debug>(&self, x: &T) {
println!("X::default_method {:?}", x);
}
}
#[derive(Debug)]
struct Y(int);
#[derive(Debug)]
struct Z<T> {
x: T
}
impl X for Y {
fn call<T: std::fmt::Debug>(&self, x: &T) {
println!("X::call {:?} {:?}", self, x);
}
}
#[unsafe_destructor]
impl<T: X + std::fmt::Debug> Drop for Z<T> {
fn drop(&mut self) {
// These statements used to cause an ICE.
self.x.call(self);
self.x.default_method(self);
}
}
pub fn main()
|
{
let _z = Z {x: Y(42)};
}
|
identifier_body
|
|
issue-4252.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.
#![feature(unsafe_destructor)]
trait X {
fn call<T: std::fmt::Debug>(&self, x: &T);
fn default_method<T: std::fmt::Debug>(&self, x: &T) {
println!("X::default_method {:?}", x);
}
}
#[derive(Debug)]
struct Y(int);
#[derive(Debug)]
struct Z<T> {
x: T
}
impl X for Y {
fn call<T: std::fmt::Debug>(&self, x: &T) {
println!("X::call {:?} {:?}", self, x);
}
}
#[unsafe_destructor]
impl<T: X + std::fmt::Debug> Drop for Z<T> {
fn drop(&mut self) {
// These statements used to cause an ICE.
self.x.call(self);
self.x.default_method(self);
}
}
pub fn
|
() {
let _z = Z {x: Y(42)};
}
|
main
|
identifier_name
|
error.rs
|
use std::error;
use std::fmt;
use log::SetLoggerError;
use error::Error as NoritamaError;
// @TODO Implement ErrorKind
#[derive(Debug)]
pub enum Error {
InvalidArgError(String),
LibError(NoritamaError),
LoggerError(SetLoggerError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::InvalidArgError(ref err) => write!(f, "InvalidError: {}", err),
Error::LibError(ref err) => write!(f, "LibError: {}", err),
Error::LoggerError(ref err) => write!(f, "LoggerError: {}", err),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::InvalidArgError(ref err) => err,
|
Error::LoggerError(ref err) => err.description(),
}
}
}
impl From<NoritamaError> for Error {
fn from(err: NoritamaError) -> Error {
Error::LibError(err)
}
}
impl From<SetLoggerError> for Error {
fn from(err: SetLoggerError) -> Error {
Error::LoggerError(err)
}
}
|
Error::LibError(ref err) => err.description(),
|
random_line_split
|
error.rs
|
use std::error;
use std::fmt;
use log::SetLoggerError;
use error::Error as NoritamaError;
// @TODO Implement ErrorKind
#[derive(Debug)]
pub enum Error {
InvalidArgError(String),
LibError(NoritamaError),
LoggerError(SetLoggerError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::InvalidArgError(ref err) => write!(f, "InvalidError: {}", err),
Error::LibError(ref err) => write!(f, "LibError: {}", err),
Error::LoggerError(ref err) => write!(f, "LoggerError: {}", err),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str
|
}
impl From<NoritamaError> for Error {
fn from(err: NoritamaError) -> Error {
Error::LibError(err)
}
}
impl From<SetLoggerError> for Error {
fn from(err: SetLoggerError) -> Error {
Error::LoggerError(err)
}
}
|
{
match *self {
Error::InvalidArgError(ref err) => err,
Error::LibError(ref err) => err.description(),
Error::LoggerError(ref err) => err.description(),
}
}
|
identifier_body
|
error.rs
|
use std::error;
use std::fmt;
use log::SetLoggerError;
use error::Error as NoritamaError;
// @TODO Implement ErrorKind
#[derive(Debug)]
pub enum Error {
InvalidArgError(String),
LibError(NoritamaError),
LoggerError(SetLoggerError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::InvalidArgError(ref err) => write!(f, "InvalidError: {}", err),
Error::LibError(ref err) => write!(f, "LibError: {}", err),
Error::LoggerError(ref err) => write!(f, "LoggerError: {}", err),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::InvalidArgError(ref err) => err,
Error::LibError(ref err) => err.description(),
Error::LoggerError(ref err) => err.description(),
}
}
}
impl From<NoritamaError> for Error {
fn from(err: NoritamaError) -> Error {
Error::LibError(err)
}
}
impl From<SetLoggerError> for Error {
fn
|
(err: SetLoggerError) -> Error {
Error::LoggerError(err)
}
}
|
from
|
identifier_name
|
users.rs
|
use std::io::prelude::*;
use std::io::BufReader;
use std::io::Result;
use std::fs::File;
use std::option::Option;
#[derive(Debug, Clone)]
pub struct User {
pub username: String,
pub phone_number: Option<String>,
pub slack_username: Option<String>
}
pub fn read_users(path: String) -> Result<Vec<User>> {
let f = try!(File::open(path));
let reader = BufReader::new(f);
let mut users: Vec<User> = Vec::new();
for line in reader.lines() {
let line = try!(line);
match parse_user(&line) {
Some(user) => { users.push(user) },
None => { warn!("Invalid user line: {}", line); }
}
}
info!("Read {} users", users.len());
return Ok(users);
}
fn
|
(line: &str) -> Option<User> {
let parts: Vec<String> = line.split(",").map( |s| s.to_owned() ).collect();
let username = parts.get(0);
if username.is_none() || username.expect("Read invalid user").is_empty() {
return None;
}
let phone_number = match parts.get(1) {
Some(number) => Some(number.to_owned()),
None => None
};
let slack_username = match parts.get(2) {
Some(number) => Some(number.to_owned()),
None => None
};
if phone_number.is_some() || slack_username.is_some() {
return Some(User {
username: username.expect("Invalid username").to_owned(),
phone_number: phone_number,
slack_username: slack_username
});
} else {
return None;
}
}
#[test]
fn test_parse_user() {
let line = "patrickod,+16507017829,patrickod";
let user = parse_user(line).unwrap();
assert_eq!(user.username, "patrickod".to_string());
assert_eq!(user.slack_username.unwrap(), "patrickod".to_string());
assert_eq!(user.phone_number.unwrap(), "+16507017829".to_string());
}
#[test]
fn test_parse_empty_user() {
let line = "";
assert!(parse_user(line).is_none());
}
#[test]
fn test_parse_user_username_only() {
let line = "patrickod";
assert!(parse_user(line).is_none());
}
|
parse_user
|
identifier_name
|
users.rs
|
use std::io::prelude::*;
use std::io::BufReader;
use std::io::Result;
use std::fs::File;
use std::option::Option;
#[derive(Debug, Clone)]
pub struct User {
pub username: String,
pub phone_number: Option<String>,
pub slack_username: Option<String>
}
pub fn read_users(path: String) -> Result<Vec<User>> {
let f = try!(File::open(path));
let reader = BufReader::new(f);
let mut users: Vec<User> = Vec::new();
for line in reader.lines() {
let line = try!(line);
match parse_user(&line) {
Some(user) => { users.push(user) },
None => { warn!("Invalid user line: {}", line); }
}
}
info!("Read {} users", users.len());
return Ok(users);
}
fn parse_user(line: &str) -> Option<User>
|
phone_number: phone_number,
slack_username: slack_username
});
} else {
return None;
}
}
#[test]
fn test_parse_user() {
let line = "patrickod,+16507017829,patrickod";
let user = parse_user(line).unwrap();
assert_eq!(user.username, "patrickod".to_string());
assert_eq!(user.slack_username.unwrap(), "patrickod".to_string());
assert_eq!(user.phone_number.unwrap(), "+16507017829".to_string());
}
#[test]
fn test_parse_empty_user() {
let line = "";
assert!(parse_user(line).is_none());
}
#[test]
fn test_parse_user_username_only() {
let line = "patrickod";
assert!(parse_user(line).is_none());
}
|
{
let parts: Vec<String> = line.split(",").map( |s| s.to_owned() ).collect();
let username = parts.get(0);
if username.is_none() || username.expect("Read invalid user").is_empty() {
return None;
}
let phone_number = match parts.get(1) {
Some(number) => Some(number.to_owned()),
None => None
};
let slack_username = match parts.get(2) {
Some(number) => Some(number.to_owned()),
None => None
};
if phone_number.is_some() || slack_username.is_some() {
return Some(User {
username: username.expect("Invalid username").to_owned(),
|
identifier_body
|
users.rs
|
use std::io::prelude::*;
use std::io::BufReader;
use std::io::Result;
use std::fs::File;
use std::option::Option;
#[derive(Debug, Clone)]
pub struct User {
pub username: String,
pub phone_number: Option<String>,
pub slack_username: Option<String>
}
pub fn read_users(path: String) -> Result<Vec<User>> {
let f = try!(File::open(path));
let reader = BufReader::new(f);
let mut users: Vec<User> = Vec::new();
for line in reader.lines() {
let line = try!(line);
match parse_user(&line) {
Some(user) => { users.push(user) },
None => { warn!("Invalid user line: {}", line); }
}
}
info!("Read {} users", users.len());
return Ok(users);
}
fn parse_user(line: &str) -> Option<User> {
let parts: Vec<String> = line.split(",").map( |s| s.to_owned() ).collect();
let username = parts.get(0);
if username.is_none() || username.expect("Read invalid user").is_empty() {
return None;
|
let phone_number = match parts.get(1) {
Some(number) => Some(number.to_owned()),
None => None
};
let slack_username = match parts.get(2) {
Some(number) => Some(number.to_owned()),
None => None
};
if phone_number.is_some() || slack_username.is_some() {
return Some(User {
username: username.expect("Invalid username").to_owned(),
phone_number: phone_number,
slack_username: slack_username
});
} else {
return None;
}
}
#[test]
fn test_parse_user() {
let line = "patrickod,+16507017829,patrickod";
let user = parse_user(line).unwrap();
assert_eq!(user.username, "patrickod".to_string());
assert_eq!(user.slack_username.unwrap(), "patrickod".to_string());
assert_eq!(user.phone_number.unwrap(), "+16507017829".to_string());
}
#[test]
fn test_parse_empty_user() {
let line = "";
assert!(parse_user(line).is_none());
}
#[test]
fn test_parse_user_username_only() {
let line = "patrickod";
assert!(parse_user(line).is_none());
}
|
}
|
random_line_split
|
TestLog.rs
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
|
*/
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime.
float __attribute__((kernel)) testLogFloatFloat(float in) {
return log(in);
}
float2 __attribute__((kernel)) testLogFloat2Float2(float2 in) {
return log(in);
}
float3 __attribute__((kernel)) testLogFloat3Float3(float3 in) {
return log(in);
}
float4 __attribute__((kernel)) testLogFloat4Float4(float4 in) {
return log(in);
}
|
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
|
random_line_split
|
url.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/. */
//! Common handling for the specified value CSS url() values.
use cssparser::{CssStringWriter, Parser};
#[cfg(feature = "gecko")]
use gecko_bindings::structs::ServoBundledURI;
#[cfg(feature = "gecko")]
use gecko_bindings::sugar::refptr::{GeckoArcPrincipal, GeckoArcURI};
use parser::{Parse, ParserContext};
#[cfg(feature = "gecko")]
use parser::ParserContextExtraData;
use servo_url::ServoUrl;
use std::borrow::Cow;
use std::fmt::{self, Write};
use std::sync::Arc;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::computed::ComputedValueAsSpecified;
/// A set of data needed in Gecko to represent a URL.
#[derive(PartialEq, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize, Eq))]
pub struct UrlExtraData {
/// The base URI.
#[cfg(feature = "gecko")]
pub base: GeckoArcURI,
/// The referrer.
#[cfg(feature = "gecko")]
pub referrer: GeckoArcURI,
/// The principal that originated this URI.
#[cfg(feature = "gecko")]
pub principal: GeckoArcPrincipal,
}
impl UrlExtraData {
/// Constructs a `UrlExtraData`.
#[cfg(feature = "servo")]
pub fn make_from(_: &ParserContext) -> Option<UrlExtraData> {
Some(UrlExtraData { })
}
/// Constructs a `UrlExtraData`.
#[cfg(feature = "gecko")]
pub fn make_from(context: &ParserContext) -> Option<UrlExtraData> {
match context.extra_data {
ParserContextExtraData {
base: Some(ref base),
referrer: Some(ref referrer),
principal: Some(ref principal),
} => {
Some(UrlExtraData {
base: base.clone(),
referrer: referrer.clone(),
principal: principal.clone(),
})
},
_ => None,
}
}
}
/// A specified url() value.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize))]
pub struct SpecifiedUrl {
/// The original URI. This might be optional since we may insert computed
/// values of images into the cascade directly, and we don't bother to
/// convert their serialization.
///
/// Refcounted since cloning this should be cheap and data: uris can be
/// really large.
original: Option<Arc<String>>,
/// The resolved value for the url, if valid.
resolved: Option<ServoUrl>,
/// Extra data used for Stylo.
extra_data: UrlExtraData,
}
impl Parse for SpecifiedUrl {
fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let url = try!(input.expect_url());
Self::parse_from_string(url, context)
}
}
impl SpecifiedUrl {
/// Try to parse a URL from a string value that is a valid CSS token for a
/// URL.
///
/// Only returns `Err` for Gecko, in the case we can't construct a
/// `URLExtraData`.
pub fn parse_from_string<'a>(url: Cow<'a, str>,
context: &ParserContext)
-> Result<Self, ()> {
let extra_data = match UrlExtraData::make_from(context) {
Some(extra_data) => extra_data,
None => {
// FIXME(heycam) should ensure we always have a principal, etc.,
// when parsing style attributes and re-parsing due to CSS
// Variables.
warn!("stylo: skipping declaration without ParserContextExtraData");
return Err(())
},
};
let serialization = Arc::new(url.into_owned());
let resolved = context.base_url.join(&serialization).ok();
Ok(SpecifiedUrl {
original: Some(serialization),
resolved: resolved,
extra_data: extra_data,
})
}
/// Get this URL's extra data.
pub fn extra_data(&self) -> &UrlExtraData {
&self.extra_data
}
/// Returns the resolved url if it was valid.
pub fn url(&self) -> Option<&ServoUrl> {
self.resolved.as_ref()
}
/// Return the resolved url as string, or the empty string if it's invalid.
///
/// TODO(emilio): Should we return the original one if needed?
pub fn as_str(&self) -> &str {
match self.resolved {
Some(ref url) => url.as_str(),
None => "",
}
}
/// Little helper for Gecko's ffi.
#[cfg(feature = "gecko")]
pub fn as_slice_components(&self) -> Result<(*const u8, usize), (*const u8, usize)> {
match self.resolved {
Some(ref url) => Ok((url.as_str().as_ptr(), url.as_str().len())),
None => {
let url = self.original.as_ref()
.expect("We should always have either the original or the resolved value");
Err((url.as_str().as_ptr(), url.as_str().len()))
}
}
}
/// Check if it has a resolved URI
pub fn has_resolved(&self) -> bool
|
/// Creates an already specified url value from an already resolved URL
/// for insertion in the cascade.
pub fn for_cascade(url: ServoUrl, extra_data: UrlExtraData) -> Self {
SpecifiedUrl {
original: None,
resolved: Some(url),
extra_data: extra_data,
}
}
/// Gets a new url from a string for unit tests.
#[cfg(feature = "servo")]
pub fn new_for_testing(url: &str) -> Self {
SpecifiedUrl {
original: Some(Arc::new(url.into())),
resolved: ServoUrl::parse(url).ok(),
extra_data: UrlExtraData {}
}
}
/// Create a bundled URI suitable for sending to Gecko
/// to be constructed into a css::URLValue
#[cfg(feature = "gecko")]
pub fn for_ffi(&self) -> ServoBundledURI {
let extra_data = self.extra_data();
let (ptr, len) = match self.as_slice_components() {
Ok(value) => value,
// we're okay with passing down the unresolved relative URI
Err(value) => value,
};
ServoBundledURI {
mURLString: ptr,
mURLStringLength: len as u32,
mBaseURI: extra_data.base.get(),
mReferrer: extra_data.referrer.get(),
mPrincipal: extra_data.principal.get(),
}
}
}
impl PartialEq for SpecifiedUrl {
fn eq(&self, other: &Self) -> bool {
// TODO(emilio): maybe we care about equality of the specified values if
// present? Seems not.
self.resolved == other.resolved &&
self.extra_data == other.extra_data
}
}
impl Eq for SpecifiedUrl {}
impl ToCss for SpecifiedUrl {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(dest.write_str("url(\""));
let string = match self.original {
Some(ref original) => &**original,
None => match self.resolved {
Some(ref url) => url.as_str(),
// This can only happen if the url wasn't specified by the
// user *and* it's an invalid url that has been transformed
// back to specified value via the "uncompute" functionality.
None => "about:invalid",
}
};
try!(CssStringWriter::new(dest).write_str(string));
dest.write_str("\")")
}
}
// TODO(emilio): Maybe consider ComputedUrl to save a word in style structs?
impl ComputedValueAsSpecified for SpecifiedUrl {}
no_viewport_percentage!(SpecifiedUrl);
|
{
self.resolved.is_some()
}
|
identifier_body
|
url.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/. */
//! Common handling for the specified value CSS url() values.
use cssparser::{CssStringWriter, Parser};
#[cfg(feature = "gecko")]
use gecko_bindings::structs::ServoBundledURI;
#[cfg(feature = "gecko")]
use gecko_bindings::sugar::refptr::{GeckoArcPrincipal, GeckoArcURI};
use parser::{Parse, ParserContext};
#[cfg(feature = "gecko")]
use parser::ParserContextExtraData;
use servo_url::ServoUrl;
use std::borrow::Cow;
use std::fmt::{self, Write};
use std::sync::Arc;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::computed::ComputedValueAsSpecified;
/// A set of data needed in Gecko to represent a URL.
#[derive(PartialEq, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize, Eq))]
pub struct UrlExtraData {
/// The base URI.
#[cfg(feature = "gecko")]
pub base: GeckoArcURI,
/// The referrer.
#[cfg(feature = "gecko")]
pub referrer: GeckoArcURI,
/// The principal that originated this URI.
#[cfg(feature = "gecko")]
pub principal: GeckoArcPrincipal,
}
impl UrlExtraData {
/// Constructs a `UrlExtraData`.
#[cfg(feature = "servo")]
pub fn make_from(_: &ParserContext) -> Option<UrlExtraData> {
Some(UrlExtraData { })
}
/// Constructs a `UrlExtraData`.
#[cfg(feature = "gecko")]
pub fn make_from(context: &ParserContext) -> Option<UrlExtraData> {
match context.extra_data {
ParserContextExtraData {
base: Some(ref base),
referrer: Some(ref referrer),
principal: Some(ref principal),
} => {
Some(UrlExtraData {
base: base.clone(),
referrer: referrer.clone(),
principal: principal.clone(),
})
},
_ => None,
}
}
}
/// A specified url() value.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize))]
pub struct SpecifiedUrl {
/// The original URI. This might be optional since we may insert computed
/// values of images into the cascade directly, and we don't bother to
/// convert their serialization.
///
/// Refcounted since cloning this should be cheap and data: uris can be
/// really large.
original: Option<Arc<String>>,
/// The resolved value for the url, if valid.
resolved: Option<ServoUrl>,
/// Extra data used for Stylo.
extra_data: UrlExtraData,
}
impl Parse for SpecifiedUrl {
fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let url = try!(input.expect_url());
Self::parse_from_string(url, context)
}
}
impl SpecifiedUrl {
/// Try to parse a URL from a string value that is a valid CSS token for a
/// URL.
///
/// Only returns `Err` for Gecko, in the case we can't construct a
/// `URLExtraData`.
pub fn parse_from_string<'a>(url: Cow<'a, str>,
context: &ParserContext)
-> Result<Self, ()> {
let extra_data = match UrlExtraData::make_from(context) {
Some(extra_data) => extra_data,
None => {
// FIXME(heycam) should ensure we always have a principal, etc.,
// when parsing style attributes and re-parsing due to CSS
// Variables.
warn!("stylo: skipping declaration without ParserContextExtraData");
return Err(())
},
};
let serialization = Arc::new(url.into_owned());
let resolved = context.base_url.join(&serialization).ok();
Ok(SpecifiedUrl {
original: Some(serialization),
resolved: resolved,
extra_data: extra_data,
})
}
/// Get this URL's extra data.
pub fn extra_data(&self) -> &UrlExtraData {
&self.extra_data
}
/// Returns the resolved url if it was valid.
pub fn url(&self) -> Option<&ServoUrl> {
self.resolved.as_ref()
}
/// Return the resolved url as string, or the empty string if it's invalid.
///
/// TODO(emilio): Should we return the original one if needed?
pub fn as_str(&self) -> &str {
match self.resolved {
Some(ref url) => url.as_str(),
None => "",
}
}
/// Little helper for Gecko's ffi.
#[cfg(feature = "gecko")]
pub fn as_slice_components(&self) -> Result<(*const u8, usize), (*const u8, usize)> {
match self.resolved {
Some(ref url) => Ok((url.as_str().as_ptr(), url.as_str().len())),
None => {
let url = self.original.as_ref()
.expect("We should always have either the original or the resolved value");
Err((url.as_str().as_ptr(), url.as_str().len()))
}
}
}
/// Check if it has a resolved URI
pub fn has_resolved(&self) -> bool {
self.resolved.is_some()
}
/// Creates an already specified url value from an already resolved URL
/// for insertion in the cascade.
pub fn
|
(url: ServoUrl, extra_data: UrlExtraData) -> Self {
SpecifiedUrl {
original: None,
resolved: Some(url),
extra_data: extra_data,
}
}
/// Gets a new url from a string for unit tests.
#[cfg(feature = "servo")]
pub fn new_for_testing(url: &str) -> Self {
SpecifiedUrl {
original: Some(Arc::new(url.into())),
resolved: ServoUrl::parse(url).ok(),
extra_data: UrlExtraData {}
}
}
/// Create a bundled URI suitable for sending to Gecko
/// to be constructed into a css::URLValue
#[cfg(feature = "gecko")]
pub fn for_ffi(&self) -> ServoBundledURI {
let extra_data = self.extra_data();
let (ptr, len) = match self.as_slice_components() {
Ok(value) => value,
// we're okay with passing down the unresolved relative URI
Err(value) => value,
};
ServoBundledURI {
mURLString: ptr,
mURLStringLength: len as u32,
mBaseURI: extra_data.base.get(),
mReferrer: extra_data.referrer.get(),
mPrincipal: extra_data.principal.get(),
}
}
}
impl PartialEq for SpecifiedUrl {
fn eq(&self, other: &Self) -> bool {
// TODO(emilio): maybe we care about equality of the specified values if
// present? Seems not.
self.resolved == other.resolved &&
self.extra_data == other.extra_data
}
}
impl Eq for SpecifiedUrl {}
impl ToCss for SpecifiedUrl {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(dest.write_str("url(\""));
let string = match self.original {
Some(ref original) => &**original,
None => match self.resolved {
Some(ref url) => url.as_str(),
// This can only happen if the url wasn't specified by the
// user *and* it's an invalid url that has been transformed
// back to specified value via the "uncompute" functionality.
None => "about:invalid",
}
};
try!(CssStringWriter::new(dest).write_str(string));
dest.write_str("\")")
}
}
// TODO(emilio): Maybe consider ComputedUrl to save a word in style structs?
impl ComputedValueAsSpecified for SpecifiedUrl {}
no_viewport_percentage!(SpecifiedUrl);
|
for_cascade
|
identifier_name
|
url.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/. */
//! Common handling for the specified value CSS url() values.
use cssparser::{CssStringWriter, Parser};
#[cfg(feature = "gecko")]
use gecko_bindings::structs::ServoBundledURI;
#[cfg(feature = "gecko")]
use gecko_bindings::sugar::refptr::{GeckoArcPrincipal, GeckoArcURI};
use parser::{Parse, ParserContext};
#[cfg(feature = "gecko")]
use parser::ParserContextExtraData;
use servo_url::ServoUrl;
use std::borrow::Cow;
use std::fmt::{self, Write};
use std::sync::Arc;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::computed::ComputedValueAsSpecified;
/// A set of data needed in Gecko to represent a URL.
#[derive(PartialEq, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize, Eq))]
pub struct UrlExtraData {
/// The base URI.
#[cfg(feature = "gecko")]
pub base: GeckoArcURI,
/// The referrer.
#[cfg(feature = "gecko")]
pub referrer: GeckoArcURI,
/// The principal that originated this URI.
#[cfg(feature = "gecko")]
pub principal: GeckoArcPrincipal,
}
impl UrlExtraData {
/// Constructs a `UrlExtraData`.
#[cfg(feature = "servo")]
pub fn make_from(_: &ParserContext) -> Option<UrlExtraData> {
Some(UrlExtraData { })
}
/// Constructs a `UrlExtraData`.
#[cfg(feature = "gecko")]
pub fn make_from(context: &ParserContext) -> Option<UrlExtraData> {
match context.extra_data {
ParserContextExtraData {
base: Some(ref base),
referrer: Some(ref referrer),
principal: Some(ref principal),
} => {
Some(UrlExtraData {
base: base.clone(),
referrer: referrer.clone(),
principal: principal.clone(),
})
},
_ => None,
}
}
}
/// A specified url() value.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize))]
pub struct SpecifiedUrl {
/// The original URI. This might be optional since we may insert computed
/// values of images into the cascade directly, and we don't bother to
/// convert their serialization.
///
/// Refcounted since cloning this should be cheap and data: uris can be
/// really large.
original: Option<Arc<String>>,
/// The resolved value for the url, if valid.
resolved: Option<ServoUrl>,
|
}
impl Parse for SpecifiedUrl {
fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let url = try!(input.expect_url());
Self::parse_from_string(url, context)
}
}
impl SpecifiedUrl {
/// Try to parse a URL from a string value that is a valid CSS token for a
/// URL.
///
/// Only returns `Err` for Gecko, in the case we can't construct a
/// `URLExtraData`.
pub fn parse_from_string<'a>(url: Cow<'a, str>,
context: &ParserContext)
-> Result<Self, ()> {
let extra_data = match UrlExtraData::make_from(context) {
Some(extra_data) => extra_data,
None => {
// FIXME(heycam) should ensure we always have a principal, etc.,
// when parsing style attributes and re-parsing due to CSS
// Variables.
warn!("stylo: skipping declaration without ParserContextExtraData");
return Err(())
},
};
let serialization = Arc::new(url.into_owned());
let resolved = context.base_url.join(&serialization).ok();
Ok(SpecifiedUrl {
original: Some(serialization),
resolved: resolved,
extra_data: extra_data,
})
}
/// Get this URL's extra data.
pub fn extra_data(&self) -> &UrlExtraData {
&self.extra_data
}
/// Returns the resolved url if it was valid.
pub fn url(&self) -> Option<&ServoUrl> {
self.resolved.as_ref()
}
/// Return the resolved url as string, or the empty string if it's invalid.
///
/// TODO(emilio): Should we return the original one if needed?
pub fn as_str(&self) -> &str {
match self.resolved {
Some(ref url) => url.as_str(),
None => "",
}
}
/// Little helper for Gecko's ffi.
#[cfg(feature = "gecko")]
pub fn as_slice_components(&self) -> Result<(*const u8, usize), (*const u8, usize)> {
match self.resolved {
Some(ref url) => Ok((url.as_str().as_ptr(), url.as_str().len())),
None => {
let url = self.original.as_ref()
.expect("We should always have either the original or the resolved value");
Err((url.as_str().as_ptr(), url.as_str().len()))
}
}
}
/// Check if it has a resolved URI
pub fn has_resolved(&self) -> bool {
self.resolved.is_some()
}
/// Creates an already specified url value from an already resolved URL
/// for insertion in the cascade.
pub fn for_cascade(url: ServoUrl, extra_data: UrlExtraData) -> Self {
SpecifiedUrl {
original: None,
resolved: Some(url),
extra_data: extra_data,
}
}
/// Gets a new url from a string for unit tests.
#[cfg(feature = "servo")]
pub fn new_for_testing(url: &str) -> Self {
SpecifiedUrl {
original: Some(Arc::new(url.into())),
resolved: ServoUrl::parse(url).ok(),
extra_data: UrlExtraData {}
}
}
/// Create a bundled URI suitable for sending to Gecko
/// to be constructed into a css::URLValue
#[cfg(feature = "gecko")]
pub fn for_ffi(&self) -> ServoBundledURI {
let extra_data = self.extra_data();
let (ptr, len) = match self.as_slice_components() {
Ok(value) => value,
// we're okay with passing down the unresolved relative URI
Err(value) => value,
};
ServoBundledURI {
mURLString: ptr,
mURLStringLength: len as u32,
mBaseURI: extra_data.base.get(),
mReferrer: extra_data.referrer.get(),
mPrincipal: extra_data.principal.get(),
}
}
}
impl PartialEq for SpecifiedUrl {
fn eq(&self, other: &Self) -> bool {
// TODO(emilio): maybe we care about equality of the specified values if
// present? Seems not.
self.resolved == other.resolved &&
self.extra_data == other.extra_data
}
}
impl Eq for SpecifiedUrl {}
impl ToCss for SpecifiedUrl {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(dest.write_str("url(\""));
let string = match self.original {
Some(ref original) => &**original,
None => match self.resolved {
Some(ref url) => url.as_str(),
// This can only happen if the url wasn't specified by the
// user *and* it's an invalid url that has been transformed
// back to specified value via the "uncompute" functionality.
None => "about:invalid",
}
};
try!(CssStringWriter::new(dest).write_str(string));
dest.write_str("\")")
}
}
// TODO(emilio): Maybe consider ComputedUrl to save a word in style structs?
impl ComputedValueAsSpecified for SpecifiedUrl {}
no_viewport_percentage!(SpecifiedUrl);
|
/// Extra data used for Stylo.
extra_data: UrlExtraData,
|
random_line_split
|
mod.rs
|
use rustc_ast::{self as ast, MetaItem};
use rustc_middle::ty;
use rustc_session::Session;
use rustc_span::symbol::{sym, Symbol};
pub(crate) use self::drop_flag_effects::*;
pub use self::framework::{
fmt, graphviz, lattice, visit_results, Analysis, AnalysisDomain, Backward, BorrowckFlowState,
BorrowckResults, Engine, Forward, GenKill, GenKillAnalysis, JoinSemiLattice, Results,
ResultsCursor, ResultsRefCursor, ResultsVisitor, SwitchIntEdgeEffects,
};
use self::move_paths::MoveData;
pub mod drop_flag_effects;
mod framework;
pub mod impls;
pub mod move_paths;
pub(crate) mod indexes {
pub(crate) use super::{
impls::borrows::BorrowIndex,
move_paths::{InitIndex, MoveOutIndex, MovePathIndex},
};
}
pub struct MoveDataParamEnv<'tcx> {
pub(crate) move_data: MoveData<'tcx>,
pub(crate) param_env: ty::ParamEnv<'tcx>,
}
pub(crate) fn has_rustc_mir_with(
_sess: &Session,
attrs: &[ast::Attribute],
name: Symbol,
) -> Option<MetaItem>
|
{
for attr in attrs {
if attr.has_name(sym::rustc_mir) {
let items = attr.meta_item_list();
for item in items.iter().flat_map(|l| l.iter()) {
match item.meta_item() {
Some(mi) if mi.has_name(name) => return Some(mi.clone()),
_ => continue,
}
}
}
}
None
}
|
identifier_body
|
|
mod.rs
|
use rustc_ast::{self as ast, MetaItem};
use rustc_middle::ty;
use rustc_session::Session;
use rustc_span::symbol::{sym, Symbol};
pub(crate) use self::drop_flag_effects::*;
pub use self::framework::{
fmt, graphviz, lattice, visit_results, Analysis, AnalysisDomain, Backward, BorrowckFlowState,
BorrowckResults, Engine, Forward, GenKill, GenKillAnalysis, JoinSemiLattice, Results,
ResultsCursor, ResultsRefCursor, ResultsVisitor, SwitchIntEdgeEffects,
};
use self::move_paths::MoveData;
pub mod drop_flag_effects;
mod framework;
pub mod impls;
pub mod move_paths;
pub(crate) mod indexes {
pub(crate) use super::{
impls::borrows::BorrowIndex,
move_paths::{InitIndex, MoveOutIndex, MovePathIndex},
};
}
pub struct MoveDataParamEnv<'tcx> {
pub(crate) move_data: MoveData<'tcx>,
pub(crate) param_env: ty::ParamEnv<'tcx>,
}
pub(crate) fn
|
(
_sess: &Session,
attrs: &[ast::Attribute],
name: Symbol,
) -> Option<MetaItem> {
for attr in attrs {
if attr.has_name(sym::rustc_mir) {
let items = attr.meta_item_list();
for item in items.iter().flat_map(|l| l.iter()) {
match item.meta_item() {
Some(mi) if mi.has_name(name) => return Some(mi.clone()),
_ => continue,
}
}
}
}
None
}
|
has_rustc_mir_with
|
identifier_name
|
mod.rs
|
use rustc_ast::{self as ast, MetaItem};
use rustc_middle::ty;
use rustc_session::Session;
|
pub(crate) use self::drop_flag_effects::*;
pub use self::framework::{
fmt, graphviz, lattice, visit_results, Analysis, AnalysisDomain, Backward, BorrowckFlowState,
BorrowckResults, Engine, Forward, GenKill, GenKillAnalysis, JoinSemiLattice, Results,
ResultsCursor, ResultsRefCursor, ResultsVisitor, SwitchIntEdgeEffects,
};
use self::move_paths::MoveData;
pub mod drop_flag_effects;
mod framework;
pub mod impls;
pub mod move_paths;
pub(crate) mod indexes {
pub(crate) use super::{
impls::borrows::BorrowIndex,
move_paths::{InitIndex, MoveOutIndex, MovePathIndex},
};
}
pub struct MoveDataParamEnv<'tcx> {
pub(crate) move_data: MoveData<'tcx>,
pub(crate) param_env: ty::ParamEnv<'tcx>,
}
pub(crate) fn has_rustc_mir_with(
_sess: &Session,
attrs: &[ast::Attribute],
name: Symbol,
) -> Option<MetaItem> {
for attr in attrs {
if attr.has_name(sym::rustc_mir) {
let items = attr.meta_item_list();
for item in items.iter().flat_map(|l| l.iter()) {
match item.meta_item() {
Some(mi) if mi.has_name(name) => return Some(mi.clone()),
_ => continue,
}
}
}
}
None
}
|
use rustc_span::symbol::{sym, Symbol};
|
random_line_split
|
aor-13.rs
|
use std::cmp::min;
use std::cmp::max;
use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::cell::RefCell;
const INFTY: i32 = 1 << 30;
struct Node {
adj: Vec<(String, i32)>
}
struct Graph {
names: HashMap<String, usize>,
nodes: Vec<RefCell<Node>>
}
impl Node {
fn new() -> Node {
Node {
adj: Vec::new()
}
}
}
impl Graph {
fn new() -> Graph {
Graph {
names: HashMap::new(),
nodes: Vec::new()
}
}
fn spawn_if_missing(&mut self, name: String) {
if!self.names.contains_key(&name) {
let index = self.nodes.len();
self.nodes.push(RefCell::new(Node::new()));
self.names.insert(name, index);
}
}
fn add_edge(&mut self, from: String, to: String, dist: i32) {
self.spawn_if_missing(from.clone());
self.spawn_if_missing(to.clone());
let mut node_a = self.nodes[self.names[&from]].borrow_mut();
node_a.adj.push((to.clone(), dist));
}
fn get_tsp_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
dp[1][0] = 0;
for mask in 2..lim {
if mask % 2 == 1 {
for i in 1..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
}
let mut ret = -INFTY;
let neighbours = self.nodes[0].borrow().adj.clone();
for neighbour in neighbours.iter() {
let i = self.names[&neighbour.0];
let weight = neighbour.1;
ret = max(ret, dp[lim - 1][i] + weight);
}
ret
}
fn get_longest_ham_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
for i in 0..n {
dp[1 << i][i] = 0;
}
for mask in 0..lim {
for i in 0..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
let mut ret = -INFTY;
for i in 0..n {
|
ret = max(ret, dp[lim - 1][i]);
}
ret
}
}
fn main() {
let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
.ok()
.expect("Failed to open the input file!");
let mut input = String::new();
f.read_to_string(&mut input)
.ok()
.expect("Failed to read from the input file!");
let mut graph = Graph::new();
let mut edges: HashMap<(String, String), i32> = HashMap::new();
for line in input.lines() {
let parts: Vec<_> = line.split_whitespace().collect();
let a = parts[0].to_string();
let g = parts[2].to_string();
let d: i32 = parts[3].to_string().parse().ok().expect("Could not parse into an integer!");
let mut b = parts[10].to_string();
b.pop();
let w = if g == "gain" {
d
} else if g == "lose" {
-d
} else {
panic!("Something is wrong, no gain/lose in line!");
};
let key = (min(a.clone(), b.clone()), max(a.clone(), b.clone()));
if edges.contains_key(&key) {
let val = edges[&key];
edges.insert(key, val + w);
} else {
edges.insert(key, w);
}
}
for (key, w) in &edges {
let (a, b) = key.clone();
graph.add_edge(a.clone(), b.clone(), *w);
graph.add_edge(b.clone(), a.clone(), *w);
}
let ret = graph.get_tsp_length();
println!("The longest Hamiltonian cycle length is {}.", ret);
let ret = graph.get_longest_ham_length();
println!("The longest Hamiltonian path length is {}.", ret);
}
|
random_line_split
|
|
aor-13.rs
|
use std::cmp::min;
use std::cmp::max;
use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::cell::RefCell;
const INFTY: i32 = 1 << 30;
struct Node {
adj: Vec<(String, i32)>
}
struct Graph {
names: HashMap<String, usize>,
nodes: Vec<RefCell<Node>>
}
impl Node {
fn new() -> Node {
Node {
adj: Vec::new()
}
}
}
impl Graph {
fn new() -> Graph {
Graph {
names: HashMap::new(),
nodes: Vec::new()
}
}
fn spawn_if_missing(&mut self, name: String) {
if!self.names.contains_key(&name) {
let index = self.nodes.len();
self.nodes.push(RefCell::new(Node::new()));
self.names.insert(name, index);
}
}
fn add_edge(&mut self, from: String, to: String, dist: i32) {
self.spawn_if_missing(from.clone());
self.spawn_if_missing(to.clone());
let mut node_a = self.nodes[self.names[&from]].borrow_mut();
node_a.adj.push((to.clone(), dist));
}
fn get_tsp_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
dp[1][0] = 0;
for mask in 2..lim {
if mask % 2 == 1 {
for i in 1..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
}
let mut ret = -INFTY;
let neighbours = self.nodes[0].borrow().adj.clone();
for neighbour in neighbours.iter() {
let i = self.names[&neighbour.0];
let weight = neighbour.1;
ret = max(ret, dp[lim - 1][i] + weight);
}
ret
}
fn get_longest_ham_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
for i in 0..n {
dp[1 << i][i] = 0;
}
for mask in 0..lim {
for i in 0..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
let mut ret = -INFTY;
for i in 0..n {
ret = max(ret, dp[lim - 1][i]);
}
ret
}
}
fn main()
|
b.pop();
let w = if g == "gain" {
d
} else if g == "lose" {
-d
} else {
panic!("Something is wrong, no gain/lose in line!");
};
let key = (min(a.clone(), b.clone()), max(a.clone(), b.clone()));
if edges.contains_key(&key) {
let val = edges[&key];
edges.insert(key, val + w);
} else {
edges.insert(key, w);
}
}
for (key, w) in &edges {
let (a, b) = key.clone();
graph.add_edge(a.clone(), b.clone(), *w);
graph.add_edge(b.clone(), a.clone(), *w);
}
let ret = graph.get_tsp_length();
println!("The longest Hamiltonian cycle length is {}.", ret);
let ret = graph.get_longest_ham_length();
println!("The longest Hamiltonian path length is {}.", ret);
}
|
{
let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
.ok()
.expect("Failed to open the input file!");
let mut input = String::new();
f.read_to_string(&mut input)
.ok()
.expect("Failed to read from the input file!");
let mut graph = Graph::new();
let mut edges: HashMap<(String, String), i32> = HashMap::new();
for line in input.lines() {
let parts: Vec<_> = line.split_whitespace().collect();
let a = parts[0].to_string();
let g = parts[2].to_string();
let d: i32 = parts[3].to_string().parse().ok().expect("Could not parse into an integer!");
let mut b = parts[10].to_string();
|
identifier_body
|
aor-13.rs
|
use std::cmp::min;
use std::cmp::max;
use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::cell::RefCell;
const INFTY: i32 = 1 << 30;
struct Node {
adj: Vec<(String, i32)>
}
struct Graph {
names: HashMap<String, usize>,
nodes: Vec<RefCell<Node>>
}
impl Node {
fn new() -> Node {
Node {
adj: Vec::new()
}
}
}
impl Graph {
fn
|
() -> Graph {
Graph {
names: HashMap::new(),
nodes: Vec::new()
}
}
fn spawn_if_missing(&mut self, name: String) {
if!self.names.contains_key(&name) {
let index = self.nodes.len();
self.nodes.push(RefCell::new(Node::new()));
self.names.insert(name, index);
}
}
fn add_edge(&mut self, from: String, to: String, dist: i32) {
self.spawn_if_missing(from.clone());
self.spawn_if_missing(to.clone());
let mut node_a = self.nodes[self.names[&from]].borrow_mut();
node_a.adj.push((to.clone(), dist));
}
fn get_tsp_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
dp[1][0] = 0;
for mask in 2..lim {
if mask % 2 == 1 {
for i in 1..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
}
let mut ret = -INFTY;
let neighbours = self.nodes[0].borrow().adj.clone();
for neighbour in neighbours.iter() {
let i = self.names[&neighbour.0];
let weight = neighbour.1;
ret = max(ret, dp[lim - 1][i] + weight);
}
ret
}
fn get_longest_ham_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
for i in 0..n {
dp[1 << i][i] = 0;
}
for mask in 0..lim {
for i in 0..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
let mut ret = -INFTY;
for i in 0..n {
ret = max(ret, dp[lim - 1][i]);
}
ret
}
}
fn main() {
let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
.ok()
.expect("Failed to open the input file!");
let mut input = String::new();
f.read_to_string(&mut input)
.ok()
.expect("Failed to read from the input file!");
let mut graph = Graph::new();
let mut edges: HashMap<(String, String), i32> = HashMap::new();
for line in input.lines() {
let parts: Vec<_> = line.split_whitespace().collect();
let a = parts[0].to_string();
let g = parts[2].to_string();
let d: i32 = parts[3].to_string().parse().ok().expect("Could not parse into an integer!");
let mut b = parts[10].to_string();
b.pop();
let w = if g == "gain" {
d
} else if g == "lose" {
-d
} else {
panic!("Something is wrong, no gain/lose in line!");
};
let key = (min(a.clone(), b.clone()), max(a.clone(), b.clone()));
if edges.contains_key(&key) {
let val = edges[&key];
edges.insert(key, val + w);
} else {
edges.insert(key, w);
}
}
for (key, w) in &edges {
let (a, b) = key.clone();
graph.add_edge(a.clone(), b.clone(), *w);
graph.add_edge(b.clone(), a.clone(), *w);
}
let ret = graph.get_tsp_length();
println!("The longest Hamiltonian cycle length is {}.", ret);
let ret = graph.get_longest_ham_length();
println!("The longest Hamiltonian path length is {}.", ret);
}
|
new
|
identifier_name
|
aor-13.rs
|
use std::cmp::min;
use std::cmp::max;
use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::cell::RefCell;
const INFTY: i32 = 1 << 30;
struct Node {
adj: Vec<(String, i32)>
}
struct Graph {
names: HashMap<String, usize>,
nodes: Vec<RefCell<Node>>
}
impl Node {
fn new() -> Node {
Node {
adj: Vec::new()
}
}
}
impl Graph {
fn new() -> Graph {
Graph {
names: HashMap::new(),
nodes: Vec::new()
}
}
fn spawn_if_missing(&mut self, name: String) {
if!self.names.contains_key(&name) {
let index = self.nodes.len();
self.nodes.push(RefCell::new(Node::new()));
self.names.insert(name, index);
}
}
fn add_edge(&mut self, from: String, to: String, dist: i32) {
self.spawn_if_missing(from.clone());
self.spawn_if_missing(to.clone());
let mut node_a = self.nodes[self.names[&from]].borrow_mut();
node_a.adj.push((to.clone(), dist));
}
fn get_tsp_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
dp[1][0] = 0;
for mask in 2..lim {
if mask % 2 == 1 {
for i in 1..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
}
let mut ret = -INFTY;
let neighbours = self.nodes[0].borrow().adj.clone();
for neighbour in neighbours.iter() {
let i = self.names[&neighbour.0];
let weight = neighbour.1;
ret = max(ret, dp[lim - 1][i] + weight);
}
ret
}
fn get_longest_ham_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
for i in 0..n {
dp[1 << i][i] = 0;
}
for mask in 0..lim {
for i in 0..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
let mut ret = -INFTY;
for i in 0..n {
ret = max(ret, dp[lim - 1][i]);
}
ret
}
}
fn main() {
let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
.ok()
.expect("Failed to open the input file!");
let mut input = String::new();
f.read_to_string(&mut input)
.ok()
.expect("Failed to read from the input file!");
let mut graph = Graph::new();
let mut edges: HashMap<(String, String), i32> = HashMap::new();
for line in input.lines() {
let parts: Vec<_> = line.split_whitespace().collect();
let a = parts[0].to_string();
let g = parts[2].to_string();
let d: i32 = parts[3].to_string().parse().ok().expect("Could not parse into an integer!");
let mut b = parts[10].to_string();
b.pop();
let w = if g == "gain" {
d
} else if g == "lose"
|
else {
panic!("Something is wrong, no gain/lose in line!");
};
let key = (min(a.clone(), b.clone()), max(a.clone(), b.clone()));
if edges.contains_key(&key) {
let val = edges[&key];
edges.insert(key, val + w);
} else {
edges.insert(key, w);
}
}
for (key, w) in &edges {
let (a, b) = key.clone();
graph.add_edge(a.clone(), b.clone(), *w);
graph.add_edge(b.clone(), a.clone(), *w);
}
let ret = graph.get_tsp_length();
println!("The longest Hamiltonian cycle length is {}.", ret);
let ret = graph.get_longest_ham_length();
println!("The longest Hamiltonian path length is {}.", ret);
}
|
{
-d
}
|
conditional_block
|
mod.rs
|
use std::cmp::{min, max};
use std::hash::{Hash, Hasher};
use std::collections::{HashSet, HashMap};
use std::ops::Add;
use std::str::FromStr;
extern crate itertools;
use self::itertools::Itertools;
extern crate permutohedron;
const DATA: &'static str = include_str!("input.txt");
pub fn main() -> Vec<String> {
let map = RouteMap::build(DATA).unwrap();
let s1 = map.find_shortest_route().unwrap();
let s2 = map.find_longest_route().unwrap();
vec![s1.to_string(), s2.to_string()]
}
#[derive(Eq, Debug)]
struct UnorderedPair<T>(T, T);
impl<T: PartialEq> PartialEq for UnorderedPair<T> {
#[inline]
fn eq(&self, other: &UnorderedPair<T>) -> bool {
((self.0 == other.0) && (self.1 == other.1)) || ((self.0 == other.1) && (self.1 == other.0))
}
}
impl<T: Hash + Ord> Hash for UnorderedPair<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
(min(&self.0, &self.1), max(&self.0, &self.1)).hash(state)
}
}
#[cfg(test)]
mod test_unordered_pairs {
use super::UnorderedPair;
#[test]
fn test_unordered_pair() {
assert_eq!(UnorderedPair(0, 1), UnorderedPair(1, 0));
}
}
#[derive(Eq, PartialEq, Debug)]
struct Route {
cities: UnorderedPair<String>,
distance: usize,
}
impl FromStr for Route {
type Err = &'static str;
fn from_str(route: &str) -> Result<Route, &'static str> {
if let (Some(src), Some(dst), Some(distance)) = scan_fmt!(route,
"{} to {} = {d}",
String,
String,
usize) {
Ok(Route {
cities: UnorderedPair(src, dst),
distance: distance,
})
} else {
Err("parse error on route")
}
}
}
struct RouteMap {
cities: HashSet<String>,
routes: HashMap<UnorderedPair<String>, usize>,
}
impl RouteMap {
fn build(input: &str) -> Result<RouteMap, &'static str> {
let mut map = HashMap::new();
let mut cities = HashSet::new();
for line in input.lines() {
match line.parse::<Route>() {
Ok(r) => {
cities.insert(r.cities.0.clone());
cities.insert(r.cities.1.clone());
map.insert(r.cities, r.distance);
}
Err(e) => return Err(e),
}
}
Ok(RouteMap {
cities: cities,
routes: map,
})
}
fn lookup(&self, a: &str, b: &str) -> Option<&usize> {
self.routes.get(&UnorderedPair(a.to_owned(), b.to_owned()))
}
fn get_total_route_distance(&self, stops: &[&String]) -> Option<usize> {
stops.windows(2)
.map(|w| self.lookup(&w[0], &w[1]))
.fold_options(0, Add::add)
}
fn find_shortest_route(&self) -> Option<usize> {
let mut data = self.cities.iter().collect::<Vec<_>>();
let permutations = permutohedron::Heap::new(&mut data);
permutations.filter_map(|p| self.get_total_route_distance(&p[..])).min()
}
fn find_longest_route(&self) -> Option<usize> {
let mut data = self.cities.iter().collect::<Vec<_>>();
let permutations = permutohedron::Heap::new(&mut data);
permutations.filter_map(|p| self.get_total_route_distance(&p[..])).max()
}
}
#[cfg(test)]
mod test {
use super::RouteMap;
const EXAMPLE_DATA: [&'static str; 3] = ["London to Dublin = 464",
"London to Belfast = 518",
"Dublin to Belfast = 141"];
#[test]
fn examples_1() {
let map = RouteMap::build(&EXAMPLE_DATA.join("\n")).unwrap();
let d = map.find_shortest_route();
assert_eq!(d, Some(605));
}
#[test]
fn examples_2() {
let map = RouteMap::build(&EXAMPLE_DATA.join("\n")).unwrap();
|
}
|
let d = map.find_longest_route();
assert_eq!(d, Some(982));
}
|
random_line_split
|
mod.rs
|
use std::cmp::{min, max};
use std::hash::{Hash, Hasher};
use std::collections::{HashSet, HashMap};
use std::ops::Add;
use std::str::FromStr;
extern crate itertools;
use self::itertools::Itertools;
extern crate permutohedron;
const DATA: &'static str = include_str!("input.txt");
pub fn main() -> Vec<String> {
let map = RouteMap::build(DATA).unwrap();
let s1 = map.find_shortest_route().unwrap();
let s2 = map.find_longest_route().unwrap();
vec![s1.to_string(), s2.to_string()]
}
#[derive(Eq, Debug)]
struct UnorderedPair<T>(T, T);
impl<T: PartialEq> PartialEq for UnorderedPair<T> {
#[inline]
fn eq(&self, other: &UnorderedPair<T>) -> bool {
((self.0 == other.0) && (self.1 == other.1)) || ((self.0 == other.1) && (self.1 == other.0))
}
}
impl<T: Hash + Ord> Hash for UnorderedPair<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
(min(&self.0, &self.1), max(&self.0, &self.1)).hash(state)
}
}
#[cfg(test)]
mod test_unordered_pairs {
use super::UnorderedPair;
#[test]
fn test_unordered_pair() {
assert_eq!(UnorderedPair(0, 1), UnorderedPair(1, 0));
}
}
#[derive(Eq, PartialEq, Debug)]
struct Route {
cities: UnorderedPair<String>,
distance: usize,
}
impl FromStr for Route {
type Err = &'static str;
fn from_str(route: &str) -> Result<Route, &'static str> {
if let (Some(src), Some(dst), Some(distance)) = scan_fmt!(route,
"{} to {} = {d}",
String,
String,
usize) {
Ok(Route {
cities: UnorderedPair(src, dst),
distance: distance,
})
} else {
Err("parse error on route")
}
}
}
struct RouteMap {
cities: HashSet<String>,
routes: HashMap<UnorderedPair<String>, usize>,
}
impl RouteMap {
fn build(input: &str) -> Result<RouteMap, &'static str> {
let mut map = HashMap::new();
let mut cities = HashSet::new();
for line in input.lines() {
match line.parse::<Route>() {
Ok(r) => {
cities.insert(r.cities.0.clone());
cities.insert(r.cities.1.clone());
map.insert(r.cities, r.distance);
}
Err(e) => return Err(e),
}
}
Ok(RouteMap {
cities: cities,
routes: map,
})
}
fn lookup(&self, a: &str, b: &str) -> Option<&usize> {
self.routes.get(&UnorderedPair(a.to_owned(), b.to_owned()))
}
fn get_total_route_distance(&self, stops: &[&String]) -> Option<usize> {
stops.windows(2)
.map(|w| self.lookup(&w[0], &w[1]))
.fold_options(0, Add::add)
}
fn find_shortest_route(&self) -> Option<usize> {
let mut data = self.cities.iter().collect::<Vec<_>>();
let permutations = permutohedron::Heap::new(&mut data);
permutations.filter_map(|p| self.get_total_route_distance(&p[..])).min()
}
fn find_longest_route(&self) -> Option<usize> {
let mut data = self.cities.iter().collect::<Vec<_>>();
let permutations = permutohedron::Heap::new(&mut data);
permutations.filter_map(|p| self.get_total_route_distance(&p[..])).max()
}
}
#[cfg(test)]
mod test {
use super::RouteMap;
const EXAMPLE_DATA: [&'static str; 3] = ["London to Dublin = 464",
"London to Belfast = 518",
"Dublin to Belfast = 141"];
#[test]
fn examples_1()
|
#[test]
fn examples_2() {
let map = RouteMap::build(&EXAMPLE_DATA.join("\n")).unwrap();
let d = map.find_longest_route();
assert_eq!(d, Some(982));
}
}
|
{
let map = RouteMap::build(&EXAMPLE_DATA.join("\n")).unwrap();
let d = map.find_shortest_route();
assert_eq!(d, Some(605));
}
|
identifier_body
|
mod.rs
|
use std::cmp::{min, max};
use std::hash::{Hash, Hasher};
use std::collections::{HashSet, HashMap};
use std::ops::Add;
use std::str::FromStr;
extern crate itertools;
use self::itertools::Itertools;
extern crate permutohedron;
const DATA: &'static str = include_str!("input.txt");
pub fn main() -> Vec<String> {
let map = RouteMap::build(DATA).unwrap();
let s1 = map.find_shortest_route().unwrap();
let s2 = map.find_longest_route().unwrap();
vec![s1.to_string(), s2.to_string()]
}
#[derive(Eq, Debug)]
struct UnorderedPair<T>(T, T);
impl<T: PartialEq> PartialEq for UnorderedPair<T> {
#[inline]
fn
|
(&self, other: &UnorderedPair<T>) -> bool {
((self.0 == other.0) && (self.1 == other.1)) || ((self.0 == other.1) && (self.1 == other.0))
}
}
impl<T: Hash + Ord> Hash for UnorderedPair<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
(min(&self.0, &self.1), max(&self.0, &self.1)).hash(state)
}
}
#[cfg(test)]
mod test_unordered_pairs {
use super::UnorderedPair;
#[test]
fn test_unordered_pair() {
assert_eq!(UnorderedPair(0, 1), UnorderedPair(1, 0));
}
}
#[derive(Eq, PartialEq, Debug)]
struct Route {
cities: UnorderedPair<String>,
distance: usize,
}
impl FromStr for Route {
type Err = &'static str;
fn from_str(route: &str) -> Result<Route, &'static str> {
if let (Some(src), Some(dst), Some(distance)) = scan_fmt!(route,
"{} to {} = {d}",
String,
String,
usize) {
Ok(Route {
cities: UnorderedPair(src, dst),
distance: distance,
})
} else {
Err("parse error on route")
}
}
}
struct RouteMap {
cities: HashSet<String>,
routes: HashMap<UnorderedPair<String>, usize>,
}
impl RouteMap {
fn build(input: &str) -> Result<RouteMap, &'static str> {
let mut map = HashMap::new();
let mut cities = HashSet::new();
for line in input.lines() {
match line.parse::<Route>() {
Ok(r) => {
cities.insert(r.cities.0.clone());
cities.insert(r.cities.1.clone());
map.insert(r.cities, r.distance);
}
Err(e) => return Err(e),
}
}
Ok(RouteMap {
cities: cities,
routes: map,
})
}
fn lookup(&self, a: &str, b: &str) -> Option<&usize> {
self.routes.get(&UnorderedPair(a.to_owned(), b.to_owned()))
}
fn get_total_route_distance(&self, stops: &[&String]) -> Option<usize> {
stops.windows(2)
.map(|w| self.lookup(&w[0], &w[1]))
.fold_options(0, Add::add)
}
fn find_shortest_route(&self) -> Option<usize> {
let mut data = self.cities.iter().collect::<Vec<_>>();
let permutations = permutohedron::Heap::new(&mut data);
permutations.filter_map(|p| self.get_total_route_distance(&p[..])).min()
}
fn find_longest_route(&self) -> Option<usize> {
let mut data = self.cities.iter().collect::<Vec<_>>();
let permutations = permutohedron::Heap::new(&mut data);
permutations.filter_map(|p| self.get_total_route_distance(&p[..])).max()
}
}
#[cfg(test)]
mod test {
use super::RouteMap;
const EXAMPLE_DATA: [&'static str; 3] = ["London to Dublin = 464",
"London to Belfast = 518",
"Dublin to Belfast = 141"];
#[test]
fn examples_1() {
let map = RouteMap::build(&EXAMPLE_DATA.join("\n")).unwrap();
let d = map.find_shortest_route();
assert_eq!(d, Some(605));
}
#[test]
fn examples_2() {
let map = RouteMap::build(&EXAMPLE_DATA.join("\n")).unwrap();
let d = map.find_longest_route();
assert_eq!(d, Some(982));
}
}
|
eq
|
identifier_name
|
issue-17904.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Baz<U> where U: Eq(U); //This is parsed as the new Fn* style parenthesis syntax.
struct
|
<U> where U: Eq(U) -> R; // Notice this parses as well.
struct Baz<U>(U) where U: Eq; // This rightfully signals no error as well.
struct Foo<T> where T: Copy, (T); //~ ERROR unexpected token in `where` clause
struct Bar<T> { x: T } where T: Copy //~ ERROR expected item, found `where`
fn main() {}
|
Baz
|
identifier_name
|
issue-17904.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
|
// <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 Baz<U> where U: Eq(U); //This is parsed as the new Fn* style parenthesis syntax.
struct Baz<U> where U: Eq(U) -> R; // Notice this parses as well.
struct Baz<U>(U) where U: Eq; // This rightfully signals no error as well.
struct Foo<T> where T: Copy, (T); //~ ERROR unexpected token in `where` clause
struct Bar<T> { x: T } where T: Copy //~ ERROR expected item, found `where`
fn main() {}
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
random_line_split
|
crate-method-reexport-grrrrrrr.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
// This is a regression test that the metadata for the
// name_pool::methods impl in the other crate is reachable from this
// crate.
// aux-build:crate-method-reexport-grrrrrrr2.rs
extern crate crate_method_reexport_grrrrrrr2;
pub fn
|
() {
use crate_method_reexport_grrrrrrr2::rust::add;
use crate_method_reexport_grrrrrrr2::rust::cx;
let x: Box<_> = box () ();
x.cx();
let y = ();
y.add("hi".to_string());
}
|
main
|
identifier_name
|
crate-method-reexport-grrrrrrr.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
// This is a regression test that the metadata for the
// name_pool::methods impl in the other crate is reachable from this
// crate.
// aux-build:crate-method-reexport-grrrrrrr2.rs
extern crate crate_method_reexport_grrrrrrr2;
pub fn main()
|
{
use crate_method_reexport_grrrrrrr2::rust::add;
use crate_method_reexport_grrrrrrr2::rust::cx;
let x: Box<_> = box () ();
x.cx();
let y = ();
y.add("hi".to_string());
}
|
identifier_body
|
|
crate-method-reexport-grrrrrrr.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
// This is a regression test that the metadata for the
// name_pool::methods impl in the other crate is reachable from this
// crate.
|
use crate_method_reexport_grrrrrrr2::rust::add;
use crate_method_reexport_grrrrrrr2::rust::cx;
let x: Box<_> = box () ();
x.cx();
let y = ();
y.add("hi".to_string());
}
|
// aux-build:crate-method-reexport-grrrrrrr2.rs
extern crate crate_method_reexport_grrrrrrr2;
pub fn main() {
|
random_line_split
|
interop.rs
|
use std::io::Read;
use std::io::Write;
use std::process;
/// Invoke `interop` binary, pass given data as stdin, return stdout.
pub fn interop_command(command: &str, stdin: &[u8]) -> Vec<u8>
|
.unwrap()
.read_to_end(&mut stdout)
.expect("read json");
let exit_status = interop.wait().expect("wait_with_output");
assert!(exit_status.success(), "{}", exit_status);
stdout
}
/// Decode binary protobuf, encode as JSON.
pub fn interop_json_encode(bytes: &[u8]) -> String {
let json = interop_command("json-encode", bytes);
String::from_utf8(json).expect("UTF-8")
}
/// Decode JSON, encode as binary protobuf.
pub fn interop_json_decode(s: &str) -> Vec<u8> {
interop_command("json-decode", s.as_bytes())
}
|
{
let mut interop = process::Command::new("../interop/cxx/interop")
.args(&[command])
.stdin(process::Stdio::piped())
.stdout(process::Stdio::piped())
.stderr(process::Stdio::inherit())
.spawn()
.expect("interop");
interop
.stdin
.take()
.unwrap()
.write_all(stdin)
.expect("write to process");
let mut stdout = Vec::new();
interop
.stdout
.take()
|
identifier_body
|
interop.rs
|
use std::io::Read;
use std::io::Write;
use std::process;
/// Invoke `interop` binary, pass given data as stdin, return stdout.
pub fn
|
(command: &str, stdin: &[u8]) -> Vec<u8> {
let mut interop = process::Command::new("../interop/cxx/interop")
.args(&[command])
.stdin(process::Stdio::piped())
.stdout(process::Stdio::piped())
.stderr(process::Stdio::inherit())
.spawn()
.expect("interop");
interop
.stdin
.take()
.unwrap()
.write_all(stdin)
.expect("write to process");
let mut stdout = Vec::new();
interop
.stdout
.take()
.unwrap()
.read_to_end(&mut stdout)
.expect("read json");
let exit_status = interop.wait().expect("wait_with_output");
assert!(exit_status.success(), "{}", exit_status);
stdout
}
/// Decode binary protobuf, encode as JSON.
pub fn interop_json_encode(bytes: &[u8]) -> String {
let json = interop_command("json-encode", bytes);
String::from_utf8(json).expect("UTF-8")
}
/// Decode JSON, encode as binary protobuf.
pub fn interop_json_decode(s: &str) -> Vec<u8> {
interop_command("json-decode", s.as_bytes())
}
|
interop_command
|
identifier_name
|
interop.rs
|
use std::io::Read;
use std::io::Write;
use std::process;
|
pub fn interop_command(command: &str, stdin: &[u8]) -> Vec<u8> {
let mut interop = process::Command::new("../interop/cxx/interop")
.args(&[command])
.stdin(process::Stdio::piped())
.stdout(process::Stdio::piped())
.stderr(process::Stdio::inherit())
.spawn()
.expect("interop");
interop
.stdin
.take()
.unwrap()
.write_all(stdin)
.expect("write to process");
let mut stdout = Vec::new();
interop
.stdout
.take()
.unwrap()
.read_to_end(&mut stdout)
.expect("read json");
let exit_status = interop.wait().expect("wait_with_output");
assert!(exit_status.success(), "{}", exit_status);
stdout
}
/// Decode binary protobuf, encode as JSON.
pub fn interop_json_encode(bytes: &[u8]) -> String {
let json = interop_command("json-encode", bytes);
String::from_utf8(json).expect("UTF-8")
}
/// Decode JSON, encode as binary protobuf.
pub fn interop_json_decode(s: &str) -> Vec<u8> {
interop_command("json-decode", s.as_bytes())
}
|
/// Invoke `interop` binary, pass given data as stdin, return stdout.
|
random_line_split
|
build.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "gecko")]
extern crate bindgen;
#[cfg(feature = "gecko")]
extern crate log;
#[cfg(feature = "gecko")]
extern crate regex;
#[cfg(feature = "gecko")]
extern crate toml;
extern crate walkdir;
use std::env;
use std::path::Path;
use std::process::{exit, Command};
use walkdir::WalkDir;
#[cfg(feature = "gecko")]
mod build_gecko;
#[cfg(not(feature = "gecko"))]
mod build_gecko {
pub fn generate() {}
}
lazy_static! {
pub static ref PYTHON: String = env::var("PYTHON3").ok().unwrap_or_else(|| {
let candidates = if cfg!(windows) {
["python3.exe"]
} else {
["python3"]
};
for &name in &candidates {
if Command::new(name)
.arg("--version")
.output()
.ok()
.map_or(false, |out| out.status.success())
{
return name.to_owned();
}
}
panic!(
"Can't find python (tried {})! Try fixing PATH or setting the PYTHON3 env var",
candidates.join(", ")
)
});
}
fn
|
(engine: &str) {
for entry in WalkDir::new("properties") {
let entry = entry.unwrap();
match entry.path().extension().and_then(|e| e.to_str()) {
Some("mako") | Some("rs") | Some("py") | Some("zip") => {
println!("cargo:rerun-if-changed={}", entry.path().display());
},
_ => {},
}
}
let script = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("properties")
.join("build.py");
let status = Command::new(&*PYTHON)
.arg(&script)
.arg(engine)
.arg("style-crate")
.status()
.unwrap();
if!status.success() {
exit(1)
}
}
fn main() {
let gecko = cfg!(feature = "gecko");
let servo = cfg!(feature = "servo");
let l2013 = cfg!(feature = "servo-layout-2013");
let l2020 = cfg!(feature = "servo-layout-2020");
let engine = match (gecko, servo, l2013, l2020) {
(true, false, false, false) => "gecko",
(false, true, true, false) => "servo-2013",
(false, true, false, true) => "servo-2020",
_ => panic!(
"\n\n\
The style crate requires enabling one of its'servo' or 'gecko' feature flags \
and, in the'servo' case, one of'servo-layout-2013' or'servo-layout-2020'.\
\n\n"
),
};
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:out_dir={}", env::var("OUT_DIR").unwrap());
generate_properties(engine);
build_gecko::generate();
}
|
generate_properties
|
identifier_name
|
build.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "gecko")]
extern crate bindgen;
#[cfg(feature = "gecko")]
extern crate log;
#[cfg(feature = "gecko")]
extern crate regex;
#[cfg(feature = "gecko")]
extern crate toml;
extern crate walkdir;
use std::env;
use std::path::Path;
use std::process::{exit, Command};
use walkdir::WalkDir;
#[cfg(feature = "gecko")]
mod build_gecko;
#[cfg(not(feature = "gecko"))]
mod build_gecko {
pub fn generate() {}
}
lazy_static! {
pub static ref PYTHON: String = env::var("PYTHON3").ok().unwrap_or_else(|| {
let candidates = if cfg!(windows) {
["python3.exe"]
} else {
["python3"]
};
for &name in &candidates {
if Command::new(name)
.arg("--version")
.output()
.ok()
.map_or(false, |out| out.status.success())
{
return name.to_owned();
}
}
panic!(
"Can't find python (tried {})! Try fixing PATH or setting the PYTHON3 env var",
candidates.join(", ")
)
});
}
fn generate_properties(engine: &str) {
for entry in WalkDir::new("properties") {
let entry = entry.unwrap();
match entry.path().extension().and_then(|e| e.to_str()) {
Some("mako") | Some("rs") | Some("py") | Some("zip") => {
println!("cargo:rerun-if-changed={}", entry.path().display());
},
_ => {},
}
}
let script = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("properties")
.join("build.py");
let status = Command::new(&*PYTHON)
.arg(&script)
.arg(engine)
.arg("style-crate")
.status()
.unwrap();
if!status.success() {
exit(1)
}
}
fn main()
|
}
|
{
let gecko = cfg!(feature = "gecko");
let servo = cfg!(feature = "servo");
let l2013 = cfg!(feature = "servo-layout-2013");
let l2020 = cfg!(feature = "servo-layout-2020");
let engine = match (gecko, servo, l2013, l2020) {
(true, false, false, false) => "gecko",
(false, true, true, false) => "servo-2013",
(false, true, false, true) => "servo-2020",
_ => panic!(
"\n\n\
The style crate requires enabling one of its 'servo' or 'gecko' feature flags \
and, in the 'servo' case, one of 'servo-layout-2013' or 'servo-layout-2020'.\
\n\n"
),
};
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:out_dir={}", env::var("OUT_DIR").unwrap());
generate_properties(engine);
build_gecko::generate();
|
identifier_body
|
build.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "gecko")]
extern crate bindgen;
#[cfg(feature = "gecko")]
extern crate log;
#[cfg(feature = "gecko")]
extern crate regex;
#[cfg(feature = "gecko")]
extern crate toml;
extern crate walkdir;
use std::env;
use std::path::Path;
use std::process::{exit, Command};
use walkdir::WalkDir;
#[cfg(feature = "gecko")]
mod build_gecko;
#[cfg(not(feature = "gecko"))]
mod build_gecko {
pub fn generate() {}
}
lazy_static! {
pub static ref PYTHON: String = env::var("PYTHON3").ok().unwrap_or_else(|| {
let candidates = if cfg!(windows) {
["python3.exe"]
} else {
["python3"]
};
for &name in &candidates {
if Command::new(name)
.arg("--version")
.output()
.ok()
.map_or(false, |out| out.status.success())
{
return name.to_owned();
}
}
panic!(
"Can't find python (tried {})! Try fixing PATH or setting the PYTHON3 env var",
candidates.join(", ")
)
});
}
fn generate_properties(engine: &str) {
for entry in WalkDir::new("properties") {
let entry = entry.unwrap();
match entry.path().extension().and_then(|e| e.to_str()) {
Some("mako") | Some("rs") | Some("py") | Some("zip") =>
|
,
_ => {},
}
}
let script = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("properties")
.join("build.py");
let status = Command::new(&*PYTHON)
.arg(&script)
.arg(engine)
.arg("style-crate")
.status()
.unwrap();
if!status.success() {
exit(1)
}
}
fn main() {
let gecko = cfg!(feature = "gecko");
let servo = cfg!(feature = "servo");
let l2013 = cfg!(feature = "servo-layout-2013");
let l2020 = cfg!(feature = "servo-layout-2020");
let engine = match (gecko, servo, l2013, l2020) {
(true, false, false, false) => "gecko",
(false, true, true, false) => "servo-2013",
(false, true, false, true) => "servo-2020",
_ => panic!(
"\n\n\
The style crate requires enabling one of its'servo' or 'gecko' feature flags \
and, in the'servo' case, one of'servo-layout-2013' or'servo-layout-2020'.\
\n\n"
),
};
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:out_dir={}", env::var("OUT_DIR").unwrap());
generate_properties(engine);
build_gecko::generate();
}
|
{
println!("cargo:rerun-if-changed={}", entry.path().display());
}
|
conditional_block
|
build.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "gecko")]
extern crate bindgen;
#[cfg(feature = "gecko")]
extern crate log;
#[cfg(feature = "gecko")]
extern crate regex;
#[cfg(feature = "gecko")]
extern crate toml;
extern crate walkdir;
use std::env;
use std::path::Path;
use std::process::{exit, Command};
use walkdir::WalkDir;
#[cfg(feature = "gecko")]
mod build_gecko;
#[cfg(not(feature = "gecko"))]
mod build_gecko {
pub fn generate() {}
}
lazy_static! {
pub static ref PYTHON: String = env::var("PYTHON3").ok().unwrap_or_else(|| {
let candidates = if cfg!(windows) {
["python3.exe"]
|
if Command::new(name)
.arg("--version")
.output()
.ok()
.map_or(false, |out| out.status.success())
{
return name.to_owned();
}
}
panic!(
"Can't find python (tried {})! Try fixing PATH or setting the PYTHON3 env var",
candidates.join(", ")
)
});
}
fn generate_properties(engine: &str) {
for entry in WalkDir::new("properties") {
let entry = entry.unwrap();
match entry.path().extension().and_then(|e| e.to_str()) {
Some("mako") | Some("rs") | Some("py") | Some("zip") => {
println!("cargo:rerun-if-changed={}", entry.path().display());
},
_ => {},
}
}
let script = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("properties")
.join("build.py");
let status = Command::new(&*PYTHON)
.arg(&script)
.arg(engine)
.arg("style-crate")
.status()
.unwrap();
if!status.success() {
exit(1)
}
}
fn main() {
let gecko = cfg!(feature = "gecko");
let servo = cfg!(feature = "servo");
let l2013 = cfg!(feature = "servo-layout-2013");
let l2020 = cfg!(feature = "servo-layout-2020");
let engine = match (gecko, servo, l2013, l2020) {
(true, false, false, false) => "gecko",
(false, true, true, false) => "servo-2013",
(false, true, false, true) => "servo-2020",
_ => panic!(
"\n\n\
The style crate requires enabling one of its'servo' or 'gecko' feature flags \
and, in the'servo' case, one of'servo-layout-2013' or'servo-layout-2020'.\
\n\n"
),
};
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:out_dir={}", env::var("OUT_DIR").unwrap());
generate_properties(engine);
build_gecko::generate();
}
|
} else {
["python3"]
};
for &name in &candidates {
|
random_line_split
|
checked_add_mul.rs
|
use num::arithmetic::traits::{CheckedAdd, CheckedAddMul, CheckedMul, UnsignedAbs, WrappingSub};
use num::basic::traits::Zero;
use num::conversion::traits::WrappingFrom;
fn checked_add_mul_unsigned<T: CheckedAdd<T, Output = T> + CheckedMul<T, Output = T>>(
x: T,
y: T,
z: T,
) -> Option<T> {
y.checked_mul(z).and_then(|yz| x.checked_add(yz))
}
macro_rules! impl_checked_add_mul_unsigned {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & xy + z < 2^W \\\\
/// \operatorname{None} & xy + z \geq 2^W,
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_unsigned(self, y, z)
}
}
};
}
apply_to_unsigneds!(impl_checked_add_mul_unsigned);
fn checked_add_mul_signed<
U: CheckedMul<U, Output = U> + Copy + Ord + WrappingSub<U, Output = U>,
T: CheckedAdd<T, Output = T>
+ CheckedMul<T, Output = T>
+ Copy
+ Ord
+ UnsignedAbs<Output = U>
+ WrappingFrom<U>
+ Zero,
>(
x: T,
y: T,
z: T,
) -> Option<T> {
if y == T::ZERO || z == T::ZERO {
return Some(x);
}
let x_sign = x >= T::ZERO;
if x_sign == ((y >= T::ZERO) == (z >= T::ZERO)) {
x.checked_add(y.checked_mul(z)?)
} else {
let x = x.unsigned_abs();
let product = y.unsigned_abs().checked_mul(z.unsigned_abs())?;
let result = T::wrapping_from(if x_sign {
x.wrapping_sub(product)
} else {
product.wrapping_sub(x)
});
if x >= product || (x_sign == (result < T::ZERO))
|
else {
None
}
}
}
macro_rules! impl_checked_add_mul_signed {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & -2^{W-1} \leq xy + z < 2^{W-1} \\\\
/// \operatorname{None} &
/// xy + z < -2^{W-1} \\ \mathrm{or} \\ xy + z \geq 2^{W-1}, \\\\
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_signed(self, y, z)
}
}
};
}
apply_to_signeds!(impl_checked_add_mul_signed);
|
{
Some(result)
}
|
conditional_block
|
checked_add_mul.rs
|
use num::arithmetic::traits::{CheckedAdd, CheckedAddMul, CheckedMul, UnsignedAbs, WrappingSub};
use num::basic::traits::Zero;
use num::conversion::traits::WrappingFrom;
fn
|
<T: CheckedAdd<T, Output = T> + CheckedMul<T, Output = T>>(
x: T,
y: T,
z: T,
) -> Option<T> {
y.checked_mul(z).and_then(|yz| x.checked_add(yz))
}
macro_rules! impl_checked_add_mul_unsigned {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & xy + z < 2^W \\\\
/// \operatorname{None} & xy + z \geq 2^W,
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_unsigned(self, y, z)
}
}
};
}
apply_to_unsigneds!(impl_checked_add_mul_unsigned);
fn checked_add_mul_signed<
U: CheckedMul<U, Output = U> + Copy + Ord + WrappingSub<U, Output = U>,
T: CheckedAdd<T, Output = T>
+ CheckedMul<T, Output = T>
+ Copy
+ Ord
+ UnsignedAbs<Output = U>
+ WrappingFrom<U>
+ Zero,
>(
x: T,
y: T,
z: T,
) -> Option<T> {
if y == T::ZERO || z == T::ZERO {
return Some(x);
}
let x_sign = x >= T::ZERO;
if x_sign == ((y >= T::ZERO) == (z >= T::ZERO)) {
x.checked_add(y.checked_mul(z)?)
} else {
let x = x.unsigned_abs();
let product = y.unsigned_abs().checked_mul(z.unsigned_abs())?;
let result = T::wrapping_from(if x_sign {
x.wrapping_sub(product)
} else {
product.wrapping_sub(x)
});
if x >= product || (x_sign == (result < T::ZERO)) {
Some(result)
} else {
None
}
}
}
macro_rules! impl_checked_add_mul_signed {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & -2^{W-1} \leq xy + z < 2^{W-1} \\\\
/// \operatorname{None} &
/// xy + z < -2^{W-1} \\ \mathrm{or} \\ xy + z \geq 2^{W-1}, \\\\
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_signed(self, y, z)
}
}
};
}
apply_to_signeds!(impl_checked_add_mul_signed);
|
checked_add_mul_unsigned
|
identifier_name
|
checked_add_mul.rs
|
use num::arithmetic::traits::{CheckedAdd, CheckedAddMul, CheckedMul, UnsignedAbs, WrappingSub};
use num::basic::traits::Zero;
use num::conversion::traits::WrappingFrom;
fn checked_add_mul_unsigned<T: CheckedAdd<T, Output = T> + CheckedMul<T, Output = T>>(
x: T,
y: T,
z: T,
) -> Option<T>
|
macro_rules! impl_checked_add_mul_unsigned {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & xy + z < 2^W \\\\
/// \operatorname{None} & xy + z \geq 2^W,
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_unsigned(self, y, z)
}
}
};
}
apply_to_unsigneds!(impl_checked_add_mul_unsigned);
fn checked_add_mul_signed<
U: CheckedMul<U, Output = U> + Copy + Ord + WrappingSub<U, Output = U>,
T: CheckedAdd<T, Output = T>
+ CheckedMul<T, Output = T>
+ Copy
+ Ord
+ UnsignedAbs<Output = U>
+ WrappingFrom<U>
+ Zero,
>(
x: T,
y: T,
z: T,
) -> Option<T> {
if y == T::ZERO || z == T::ZERO {
return Some(x);
}
let x_sign = x >= T::ZERO;
if x_sign == ((y >= T::ZERO) == (z >= T::ZERO)) {
x.checked_add(y.checked_mul(z)?)
} else {
let x = x.unsigned_abs();
let product = y.unsigned_abs().checked_mul(z.unsigned_abs())?;
let result = T::wrapping_from(if x_sign {
x.wrapping_sub(product)
} else {
product.wrapping_sub(x)
});
if x >= product || (x_sign == (result < T::ZERO)) {
Some(result)
} else {
None
}
}
}
macro_rules! impl_checked_add_mul_signed {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & -2^{W-1} \leq xy + z < 2^{W-1} \\\\
/// \operatorname{None} &
/// xy + z < -2^{W-1} \\ \mathrm{or} \\ xy + z \geq 2^{W-1}, \\\\
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_signed(self, y, z)
}
}
};
}
apply_to_signeds!(impl_checked_add_mul_signed);
|
{
y.checked_mul(z).and_then(|yz| x.checked_add(yz))
}
|
identifier_body
|
checked_add_mul.rs
|
use num::arithmetic::traits::{CheckedAdd, CheckedAddMul, CheckedMul, UnsignedAbs, WrappingSub};
use num::basic::traits::Zero;
use num::conversion::traits::WrappingFrom;
fn checked_add_mul_unsigned<T: CheckedAdd<T, Output = T> + CheckedMul<T, Output = T>>(
x: T,
y: T,
z: T,
) -> Option<T> {
y.checked_mul(z).and_then(|yz| x.checked_add(yz))
}
macro_rules! impl_checked_add_mul_unsigned {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & xy + z < 2^W \\\\
/// \operatorname{None} & xy + z \geq 2^W,
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_unsigned(self, y, z)
}
}
};
}
apply_to_unsigneds!(impl_checked_add_mul_unsigned);
fn checked_add_mul_signed<
U: CheckedMul<U, Output = U> + Copy + Ord + WrappingSub<U, Output = U>,
T: CheckedAdd<T, Output = T>
+ CheckedMul<T, Output = T>
+ Copy
+ Ord
+ UnsignedAbs<Output = U>
+ WrappingFrom<U>
+ Zero,
>(
x: T,
y: T,
z: T,
) -> Option<T> {
if y == T::ZERO || z == T::ZERO {
return Some(x);
}
let x_sign = x >= T::ZERO;
if x_sign == ((y >= T::ZERO) == (z >= T::ZERO)) {
x.checked_add(y.checked_mul(z)?)
} else {
let x = x.unsigned_abs();
let product = y.unsigned_abs().checked_mul(z.unsigned_abs())?;
let result = T::wrapping_from(if x_sign {
x.wrapping_sub(product)
} else {
|
Some(result)
} else {
None
}
}
}
macro_rules! impl_checked_add_mul_signed {
($t:ident) => {
impl CheckedAddMul<$t> for $t {
type Output = $t;
/// Computes `self + y * z`, returning `None` if there is no valid result.
///
/// $$
/// f(x, y, z) = \\begin{cases}
/// \operatorname{Some}(xy + z) & -2^{W-1} \leq xy + z < 2^{W-1} \\\\
/// \operatorname{None} &
/// xy + z < -2^{W-1} \\ \mathrm{or} \\ xy + z \geq 2^{W-1}, \\\\
/// \\end{cases}
/// $$
/// where $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::checked_add_mul` module.
#[inline]
fn checked_add_mul(self, y: $t, z: $t) -> Option<$t> {
checked_add_mul_signed(self, y, z)
}
}
};
}
apply_to_signeds!(impl_checked_add_mul_signed);
|
product.wrapping_sub(x)
});
if x >= product || (x_sign == (result < T::ZERO)) {
|
random_line_split
|
texture.rs
|
extern crate gl;
extern crate image;
use self::gl::types::*;
use self::image::GenericImage;
use system::filesystem;
use std::path::Path;
use std::os::raw::c_void;
static VALID_IMG_EXT: [&'static str; 5] = [
"png", "jpeg", "jpg", "gif", "bmp"
];
pub enum TextureFmt {
R8U,
RG8U,
RGB8U,
RGBA8U
}
impl TextureFmt {
pub fn gl_format(&self) -> GLenum {
match self {
&TextureFmt::R8U => gl::RED,
&TextureFmt::RG8U => gl::RG,
&TextureFmt::RGB8U => gl::RGB,
&TextureFmt::RGBA8U => gl::RGBA,
}
}
pub fn gl_type(&self) -> GLenum {
match self {
&TextureFmt::R8U => gl::UNSIGNED_BYTE,
&TextureFmt::RG8U => gl::UNSIGNED_BYTE,
&TextureFmt::RGB8U => gl::UNSIGNED_BYTE,
&TextureFmt::RGBA8U => gl::UNSIGNED_BYTE,
}
}
// pub fn gl_component_count(&self) -> usize {
// match self {
// &R8U => 1,
// &RG8U => 2,
// &RGB8U => 3,
// &RGBA8U => 4,
// }
// }
pub fn gl_bpp(&self) -> usize {
match self {
&TextureFmt::R8U => 1,
&TextureFmt::RG8U => 2,
&TextureFmt::RGB8U => 3,
&TextureFmt::RGBA8U => 4,
}
}
}
fn image_to_gl_fmt(ty: image::ColorType) -> GLenum {
use self::image::ColorType::*;
match ty {
Gray(_) => gl::RED,
RGB(_) => gl::RGB,
GrayA(_) => gl::RG,
RGBA(_) => gl::RGBA,
_ => gl::NONE
}
}
fn image_to_radar_fmt(ty: image::ColorType) -> TextureFmt {
use self::image::ColorType::*;
match ty {
Gray(_) => TextureFmt::R8U,
RGB(_) => TextureFmt::RGB8U,
GrayA(_) => TextureFmt::RG8U,
RGBA(_) => TextureFmt::RGBA8U,
_ => TextureFmt::R8U
}
}
fn get_pixel_ptr(img: &image::DynamicImage) -> *const u8 {
use self::image::ColorType::*;
let ty = img.color();
match ty {
Gray(_) => (*img.as_luma8().unwrap()).as_ptr(),
RGB(_) => (*img.as_rgb8().unwrap()).as_ptr(),
GrayA(_) => (*img.as_luma_alpha8().unwrap()).as_ptr(),
RGBA(_) => (*img.as_rgba8().unwrap()).as_ptr(),
_ => {panic!("Unsupported pixel format.");}
}
}
pub struct Texture {
pub id: GLuint,
pub size: (u32, u32),
pub fmt: TextureFmt
}
impl Drop for Texture {
fn
|
(&mut self) {
unsafe { gl::DeleteTextures(1, &self.id); }
}
}
impl Texture {
pub fn from_image(path_str: &str) -> Texture {
let mut id = 0u32;
let path = Path::new(path_str);
//1. check extension
if!filesystem::check_extension(path, &VALID_IMG_EXT) {
panic!("Invalid image file {}.", path.display());
}
//2. load image
let img = image::open(&path).unwrap();
let fmt = image_to_gl_fmt(img.color());
if fmt == gl::NONE {
panic!("Unsupported texture format for {}.", path.display());
}
let dims = img.dimensions();
let w = dims.0 as i32;
let h = dims.1 as i32;
let bytes = get_pixel_ptr(&img);
//3. convert to gl texture
unsafe {
let mut palign: GLint = 1;
gl::GetIntegerv(gl::UNPACK_ALIGNMENT, &mut palign);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut id);
gl::BindTexture(gl::TEXTURE_2D, id);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR_MIPMAP_LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
// gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAX_ANISOTROPY_EXT, gl::REPEAT);
// ADRIEN TODO - anisotropic level from config file : needs global access to config file somehow
gl::TexImage2D(gl::TEXTURE_2D, 0, fmt as i32, w, h, 0, fmt, gl::UNSIGNED_BYTE, bytes as *const c_void);
gl::GenerateMipmap(gl::TEXTURE_2D);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, palign);
}
Texture {
id: id,
size: (dims.0, dims.1),
fmt: image_to_radar_fmt(img.color())
}
}
// ADRIEN TODO - more generic function to allow textures of any type (f32, int, etc)
pub fn from_empty(size: (u32, u32), fmt: TextureFmt) -> Texture {
let mut id = 0u32;
let gl_bpp = fmt.gl_bpp() as usize;
let gl_fmt = fmt.gl_format();
let gl_type = fmt.gl_type();
let w = size.0 as i32;
let h = size.1 as i32;
let empty_arr = vec![0; gl_bpp * size.0 as usize * size.1 as usize];
unsafe {
let mut palign: GLint = 1;
gl::GetIntegerv(gl::UNPACK_ALIGNMENT, &mut palign);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut id);
gl::BindTexture(gl::TEXTURE_2D, id);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl_fmt as i32, w, h, 0, gl_fmt, gl_type, empty_arr.as_ptr() as *const c_void);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, palign);
}
Texture {
id: id,
size: size,
fmt: fmt
}
}
pub fn bind(&self) {
unsafe { gl::BindTexture(gl::TEXTURE_2D, self.id); }
}
}
|
drop
|
identifier_name
|
texture.rs
|
extern crate gl;
extern crate image;
use self::gl::types::*;
use self::image::GenericImage;
use system::filesystem;
use std::path::Path;
use std::os::raw::c_void;
static VALID_IMG_EXT: [&'static str; 5] = [
"png", "jpeg", "jpg", "gif", "bmp"
];
pub enum TextureFmt {
R8U,
RG8U,
RGB8U,
RGBA8U
}
impl TextureFmt {
pub fn gl_format(&self) -> GLenum {
match self {
&TextureFmt::R8U => gl::RED,
&TextureFmt::RG8U => gl::RG,
&TextureFmt::RGB8U => gl::RGB,
&TextureFmt::RGBA8U => gl::RGBA,
}
}
pub fn gl_type(&self) -> GLenum {
match self {
&TextureFmt::R8U => gl::UNSIGNED_BYTE,
&TextureFmt::RG8U => gl::UNSIGNED_BYTE,
&TextureFmt::RGB8U => gl::UNSIGNED_BYTE,
&TextureFmt::RGBA8U => gl::UNSIGNED_BYTE,
}
}
// pub fn gl_component_count(&self) -> usize {
// match self {
// &R8U => 1,
// &RG8U => 2,
// &RGB8U => 3,
// &RGBA8U => 4,
// }
// }
pub fn gl_bpp(&self) -> usize {
match self {
&TextureFmt::R8U => 1,
&TextureFmt::RG8U => 2,
&TextureFmt::RGB8U => 3,
&TextureFmt::RGBA8U => 4,
}
}
}
fn image_to_gl_fmt(ty: image::ColorType) -> GLenum {
use self::image::ColorType::*;
match ty {
Gray(_) => gl::RED,
RGB(_) => gl::RGB,
GrayA(_) => gl::RG,
RGBA(_) => gl::RGBA,
_ => gl::NONE
}
}
fn image_to_radar_fmt(ty: image::ColorType) -> TextureFmt {
use self::image::ColorType::*;
match ty {
Gray(_) => TextureFmt::R8U,
RGB(_) => TextureFmt::RGB8U,
GrayA(_) => TextureFmt::RG8U,
RGBA(_) => TextureFmt::RGBA8U,
_ => TextureFmt::R8U
}
}
fn get_pixel_ptr(img: &image::DynamicImage) -> *const u8
|
pub struct Texture {
pub id: GLuint,
pub size: (u32, u32),
pub fmt: TextureFmt
}
impl Drop for Texture {
fn drop(&mut self) {
unsafe { gl::DeleteTextures(1, &self.id); }
}
}
impl Texture {
pub fn from_image(path_str: &str) -> Texture {
let mut id = 0u32;
let path = Path::new(path_str);
//1. check extension
if!filesystem::check_extension(path, &VALID_IMG_EXT) {
panic!("Invalid image file {}.", path.display());
}
//2. load image
let img = image::open(&path).unwrap();
let fmt = image_to_gl_fmt(img.color());
if fmt == gl::NONE {
panic!("Unsupported texture format for {}.", path.display());
}
let dims = img.dimensions();
let w = dims.0 as i32;
let h = dims.1 as i32;
let bytes = get_pixel_ptr(&img);
//3. convert to gl texture
unsafe {
let mut palign: GLint = 1;
gl::GetIntegerv(gl::UNPACK_ALIGNMENT, &mut palign);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut id);
gl::BindTexture(gl::TEXTURE_2D, id);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR_MIPMAP_LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
// gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAX_ANISOTROPY_EXT, gl::REPEAT);
// ADRIEN TODO - anisotropic level from config file : needs global access to config file somehow
gl::TexImage2D(gl::TEXTURE_2D, 0, fmt as i32, w, h, 0, fmt, gl::UNSIGNED_BYTE, bytes as *const c_void);
gl::GenerateMipmap(gl::TEXTURE_2D);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, palign);
}
Texture {
id: id,
size: (dims.0, dims.1),
fmt: image_to_radar_fmt(img.color())
}
}
// ADRIEN TODO - more generic function to allow textures of any type (f32, int, etc)
pub fn from_empty(size: (u32, u32), fmt: TextureFmt) -> Texture {
let mut id = 0u32;
let gl_bpp = fmt.gl_bpp() as usize;
let gl_fmt = fmt.gl_format();
let gl_type = fmt.gl_type();
let w = size.0 as i32;
let h = size.1 as i32;
let empty_arr = vec![0; gl_bpp * size.0 as usize * size.1 as usize];
unsafe {
let mut palign: GLint = 1;
gl::GetIntegerv(gl::UNPACK_ALIGNMENT, &mut palign);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut id);
gl::BindTexture(gl::TEXTURE_2D, id);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl_fmt as i32, w, h, 0, gl_fmt, gl_type, empty_arr.as_ptr() as *const c_void);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, palign);
}
Texture {
id: id,
size: size,
fmt: fmt
}
}
pub fn bind(&self) {
unsafe { gl::BindTexture(gl::TEXTURE_2D, self.id); }
}
}
|
{
use self::image::ColorType::*;
let ty = img.color();
match ty {
Gray(_) => (*img.as_luma8().unwrap()).as_ptr(),
RGB(_) => (*img.as_rgb8().unwrap()).as_ptr(),
GrayA(_) => (*img.as_luma_alpha8().unwrap()).as_ptr(),
RGBA(_) => (*img.as_rgba8().unwrap()).as_ptr(),
_ => {panic!("Unsupported pixel format.");}
}
}
|
identifier_body
|
texture.rs
|
extern crate gl;
extern crate image;
use self::gl::types::*;
use self::image::GenericImage;
use system::filesystem;
use std::path::Path;
use std::os::raw::c_void;
static VALID_IMG_EXT: [&'static str; 5] = [
"png", "jpeg", "jpg", "gif", "bmp"
|
RG8U,
RGB8U,
RGBA8U
}
impl TextureFmt {
pub fn gl_format(&self) -> GLenum {
match self {
&TextureFmt::R8U => gl::RED,
&TextureFmt::RG8U => gl::RG,
&TextureFmt::RGB8U => gl::RGB,
&TextureFmt::RGBA8U => gl::RGBA,
}
}
pub fn gl_type(&self) -> GLenum {
match self {
&TextureFmt::R8U => gl::UNSIGNED_BYTE,
&TextureFmt::RG8U => gl::UNSIGNED_BYTE,
&TextureFmt::RGB8U => gl::UNSIGNED_BYTE,
&TextureFmt::RGBA8U => gl::UNSIGNED_BYTE,
}
}
// pub fn gl_component_count(&self) -> usize {
// match self {
// &R8U => 1,
// &RG8U => 2,
// &RGB8U => 3,
// &RGBA8U => 4,
// }
// }
pub fn gl_bpp(&self) -> usize {
match self {
&TextureFmt::R8U => 1,
&TextureFmt::RG8U => 2,
&TextureFmt::RGB8U => 3,
&TextureFmt::RGBA8U => 4,
}
}
}
fn image_to_gl_fmt(ty: image::ColorType) -> GLenum {
use self::image::ColorType::*;
match ty {
Gray(_) => gl::RED,
RGB(_) => gl::RGB,
GrayA(_) => gl::RG,
RGBA(_) => gl::RGBA,
_ => gl::NONE
}
}
fn image_to_radar_fmt(ty: image::ColorType) -> TextureFmt {
use self::image::ColorType::*;
match ty {
Gray(_) => TextureFmt::R8U,
RGB(_) => TextureFmt::RGB8U,
GrayA(_) => TextureFmt::RG8U,
RGBA(_) => TextureFmt::RGBA8U,
_ => TextureFmt::R8U
}
}
fn get_pixel_ptr(img: &image::DynamicImage) -> *const u8 {
use self::image::ColorType::*;
let ty = img.color();
match ty {
Gray(_) => (*img.as_luma8().unwrap()).as_ptr(),
RGB(_) => (*img.as_rgb8().unwrap()).as_ptr(),
GrayA(_) => (*img.as_luma_alpha8().unwrap()).as_ptr(),
RGBA(_) => (*img.as_rgba8().unwrap()).as_ptr(),
_ => {panic!("Unsupported pixel format.");}
}
}
pub struct Texture {
pub id: GLuint,
pub size: (u32, u32),
pub fmt: TextureFmt
}
impl Drop for Texture {
fn drop(&mut self) {
unsafe { gl::DeleteTextures(1, &self.id); }
}
}
impl Texture {
pub fn from_image(path_str: &str) -> Texture {
let mut id = 0u32;
let path = Path::new(path_str);
//1. check extension
if!filesystem::check_extension(path, &VALID_IMG_EXT) {
panic!("Invalid image file {}.", path.display());
}
//2. load image
let img = image::open(&path).unwrap();
let fmt = image_to_gl_fmt(img.color());
if fmt == gl::NONE {
panic!("Unsupported texture format for {}.", path.display());
}
let dims = img.dimensions();
let w = dims.0 as i32;
let h = dims.1 as i32;
let bytes = get_pixel_ptr(&img);
//3. convert to gl texture
unsafe {
let mut palign: GLint = 1;
gl::GetIntegerv(gl::UNPACK_ALIGNMENT, &mut palign);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut id);
gl::BindTexture(gl::TEXTURE_2D, id);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR_MIPMAP_LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
// gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAX_ANISOTROPY_EXT, gl::REPEAT);
// ADRIEN TODO - anisotropic level from config file : needs global access to config file somehow
gl::TexImage2D(gl::TEXTURE_2D, 0, fmt as i32, w, h, 0, fmt, gl::UNSIGNED_BYTE, bytes as *const c_void);
gl::GenerateMipmap(gl::TEXTURE_2D);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, palign);
}
Texture {
id: id,
size: (dims.0, dims.1),
fmt: image_to_radar_fmt(img.color())
}
}
// ADRIEN TODO - more generic function to allow textures of any type (f32, int, etc)
pub fn from_empty(size: (u32, u32), fmt: TextureFmt) -> Texture {
let mut id = 0u32;
let gl_bpp = fmt.gl_bpp() as usize;
let gl_fmt = fmt.gl_format();
let gl_type = fmt.gl_type();
let w = size.0 as i32;
let h = size.1 as i32;
let empty_arr = vec![0; gl_bpp * size.0 as usize * size.1 as usize];
unsafe {
let mut palign: GLint = 1;
gl::GetIntegerv(gl::UNPACK_ALIGNMENT, &mut palign);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut id);
gl::BindTexture(gl::TEXTURE_2D, id);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl_fmt as i32, w, h, 0, gl_fmt, gl_type, empty_arr.as_ptr() as *const c_void);
gl::PixelStorei(gl::UNPACK_ALIGNMENT, palign);
}
Texture {
id: id,
size: size,
fmt: fmt
}
}
pub fn bind(&self) {
unsafe { gl::BindTexture(gl::TEXTURE_2D, self.id); }
}
}
|
];
pub enum TextureFmt {
R8U,
|
random_line_split
|
lexical-scope-in-parameterless-closure.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-android: FIXME(#10381)
// compile-flags:--debuginfo=1
// gdb-command:run
// Nothing to do here really, just make sure it compiles. See issue #8513.
fn
|
() {
let _ = ||();
let _ = range(1u,3).map(|_| 5i);
}
|
main
|
identifier_name
|
lexical-scope-in-parameterless-closure.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-android: FIXME(#10381)
// compile-flags:--debuginfo=1
// gdb-command:run
// Nothing to do here really, just make sure it compiles. See issue #8513.
fn main()
|
{
let _ = ||();
let _ = range(1u,3).map(|_| 5i);
}
|
identifier_body
|
|
extras.rs
|
use std::fmt;
use std::sync::Arc;
#[cfg(feature = "cache")]
use std::time::Duration;
use super::{EventHandler, RawEventHandler};
use crate::client::bridge::gateway::GatewayIntents;
#[cfg(feature = "framework")]
use crate::framework::Framework;
/// A builder to extra things for altering the [`Client`].
///
/// [`Client`]: super::Client
#[derive(Clone)]
pub struct Extras {
pub(crate) event_handler: Option<Arc<dyn EventHandler>>,
pub(crate) raw_event_handler: Option<Arc<dyn RawEventHandler>>,
#[cfg(feature = "framework")]
pub(crate) framework: Arc<Option<Box<dyn Framework + Send + Sync +'static>>>,
#[cfg(feature = "cache")]
pub(crate) timeout: Option<Duration>,
pub(crate) intents: Option<GatewayIntents>,
}
impl Extras {
/// Set the handler for managing discord events.
pub fn event_handler<H>(&mut self, handler: H) -> &mut Self
where
H: EventHandler +'static,
{
self.event_handler = Some(Arc::new(handler));
self
}
/// Set the handler for raw events.
///
/// If you have set the specialised [`Self::event_handler`], all events
/// will be cloned for use to the raw event handler.
pub fn raw_event_handler<H>(&mut self, handler: H) -> &mut Self
where
H: RawEventHandler +'static,
{
self.raw_event_handler = Some(Arc::new(handler));
self
}
/// Set the framework.
#[cfg(feature = "framework")]
pub fn framework<F: Framework + Send + Sync +'static>(&mut self, framework: F) -> &mut Self {
self.framework = Arc::new(Some(Box::new(framework)));
self
}
/// Set the duration the library is permitted to update the cache
/// before giving up acquiring a write-lock.
///
/// This can be useful for avoiding deadlocks, but it also may invalidate your cache.
#[cfg(feature = "cache")]
pub fn cache_update_timeout(&mut self, duration: Duration) -> &mut Self {
self.timeout = Some(duration);
self
}
/// Set what Discord gateway events shall be received.
///
/// By default, no intents are being used and all events are received.
pub fn intents(&mut self, intents: GatewayIntents) -> &mut Self {
self.intents = Some(intents);
self
}
}
impl Default for Extras {
fn default() -> Self {
Extras {
event_handler: None,
raw_event_handler: None,
#[cfg(feature = "framework")]
framework: Arc::new(None),
#[cfg(feature = "cache")]
timeout: None,
intents: None,
}
}
}
impl fmt::Debug for Extras {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[derive(Debug)]
struct EventHandler;
#[derive(Debug)]
struct RawEventHandler;
|
#[cfg(feature = "cache")]
ds.field("cache_update_timeout", &self.timeout);
ds.field("intents", &self.intents);
ds.finish()
}
}
|
let mut ds = f.debug_struct("Extras");
ds.field("event_handler", &EventHandler);
ds.field("raw_event_handler", &RawEventHandler);
|
random_line_split
|
extras.rs
|
use std::fmt;
use std::sync::Arc;
#[cfg(feature = "cache")]
use std::time::Duration;
use super::{EventHandler, RawEventHandler};
use crate::client::bridge::gateway::GatewayIntents;
#[cfg(feature = "framework")]
use crate::framework::Framework;
/// A builder to extra things for altering the [`Client`].
///
/// [`Client`]: super::Client
#[derive(Clone)]
pub struct Extras {
pub(crate) event_handler: Option<Arc<dyn EventHandler>>,
pub(crate) raw_event_handler: Option<Arc<dyn RawEventHandler>>,
#[cfg(feature = "framework")]
pub(crate) framework: Arc<Option<Box<dyn Framework + Send + Sync +'static>>>,
#[cfg(feature = "cache")]
pub(crate) timeout: Option<Duration>,
pub(crate) intents: Option<GatewayIntents>,
}
impl Extras {
/// Set the handler for managing discord events.
pub fn event_handler<H>(&mut self, handler: H) -> &mut Self
where
H: EventHandler +'static,
{
self.event_handler = Some(Arc::new(handler));
self
}
/// Set the handler for raw events.
///
/// If you have set the specialised [`Self::event_handler`], all events
/// will be cloned for use to the raw event handler.
pub fn raw_event_handler<H>(&mut self, handler: H) -> &mut Self
where
H: RawEventHandler +'static,
{
self.raw_event_handler = Some(Arc::new(handler));
self
}
/// Set the framework.
#[cfg(feature = "framework")]
pub fn framework<F: Framework + Send + Sync +'static>(&mut self, framework: F) -> &mut Self {
self.framework = Arc::new(Some(Box::new(framework)));
self
}
/// Set the duration the library is permitted to update the cache
/// before giving up acquiring a write-lock.
///
/// This can be useful for avoiding deadlocks, but it also may invalidate your cache.
#[cfg(feature = "cache")]
pub fn cache_update_timeout(&mut self, duration: Duration) -> &mut Self {
self.timeout = Some(duration);
self
}
/// Set what Discord gateway events shall be received.
///
/// By default, no intents are being used and all events are received.
pub fn intents(&mut self, intents: GatewayIntents) -> &mut Self {
self.intents = Some(intents);
self
}
}
impl Default for Extras {
fn default() -> Self {
Extras {
event_handler: None,
raw_event_handler: None,
#[cfg(feature = "framework")]
framework: Arc::new(None),
#[cfg(feature = "cache")]
timeout: None,
intents: None,
}
}
}
impl fmt::Debug for Extras {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[derive(Debug)]
struct
|
;
#[derive(Debug)]
struct RawEventHandler;
let mut ds = f.debug_struct("Extras");
ds.field("event_handler", &EventHandler);
ds.field("raw_event_handler", &RawEventHandler);
#[cfg(feature = "cache")]
ds.field("cache_update_timeout", &self.timeout);
ds.field("intents", &self.intents);
ds.finish()
}
}
|
EventHandler
|
identifier_name
|
extras.rs
|
use std::fmt;
use std::sync::Arc;
#[cfg(feature = "cache")]
use std::time::Duration;
use super::{EventHandler, RawEventHandler};
use crate::client::bridge::gateway::GatewayIntents;
#[cfg(feature = "framework")]
use crate::framework::Framework;
/// A builder to extra things for altering the [`Client`].
///
/// [`Client`]: super::Client
#[derive(Clone)]
pub struct Extras {
pub(crate) event_handler: Option<Arc<dyn EventHandler>>,
pub(crate) raw_event_handler: Option<Arc<dyn RawEventHandler>>,
#[cfg(feature = "framework")]
pub(crate) framework: Arc<Option<Box<dyn Framework + Send + Sync +'static>>>,
#[cfg(feature = "cache")]
pub(crate) timeout: Option<Duration>,
pub(crate) intents: Option<GatewayIntents>,
}
impl Extras {
/// Set the handler for managing discord events.
pub fn event_handler<H>(&mut self, handler: H) -> &mut Self
where
H: EventHandler +'static,
|
/// Set the handler for raw events.
///
/// If you have set the specialised [`Self::event_handler`], all events
/// will be cloned for use to the raw event handler.
pub fn raw_event_handler<H>(&mut self, handler: H) -> &mut Self
where
H: RawEventHandler +'static,
{
self.raw_event_handler = Some(Arc::new(handler));
self
}
/// Set the framework.
#[cfg(feature = "framework")]
pub fn framework<F: Framework + Send + Sync +'static>(&mut self, framework: F) -> &mut Self {
self.framework = Arc::new(Some(Box::new(framework)));
self
}
/// Set the duration the library is permitted to update the cache
/// before giving up acquiring a write-lock.
///
/// This can be useful for avoiding deadlocks, but it also may invalidate your cache.
#[cfg(feature = "cache")]
pub fn cache_update_timeout(&mut self, duration: Duration) -> &mut Self {
self.timeout = Some(duration);
self
}
/// Set what Discord gateway events shall be received.
///
/// By default, no intents are being used and all events are received.
pub fn intents(&mut self, intents: GatewayIntents) -> &mut Self {
self.intents = Some(intents);
self
}
}
impl Default for Extras {
fn default() -> Self {
Extras {
event_handler: None,
raw_event_handler: None,
#[cfg(feature = "framework")]
framework: Arc::new(None),
#[cfg(feature = "cache")]
timeout: None,
intents: None,
}
}
}
impl fmt::Debug for Extras {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[derive(Debug)]
struct EventHandler;
#[derive(Debug)]
struct RawEventHandler;
let mut ds = f.debug_struct("Extras");
ds.field("event_handler", &EventHandler);
ds.field("raw_event_handler", &RawEventHandler);
#[cfg(feature = "cache")]
ds.field("cache_update_timeout", &self.timeout);
ds.field("intents", &self.intents);
ds.finish()
}
}
|
{
self.event_handler = Some(Arc::new(handler));
self
}
|
identifier_body
|
point.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub struct Point {
pub x: f32,
pub y: f32,
}
fn
|
(this: &Point) -> f32 {
#[cfg(cfail1)]
return this.x + this.y;
#[cfg(cfail2)]
return this.x * this.x + this.y * this.y;
}
impl Point {
pub fn distance_from_origin(&self) -> f32 {
distance_squared(self).sqrt()
}
}
impl Point {
pub fn translate(&mut self, x: f32, y: f32) {
self.x += x;
self.y += y;
}
}
|
distance_squared
|
identifier_name
|
point.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub struct Point {
pub x: f32,
pub y: f32,
}
fn distance_squared(this: &Point) -> f32 {
#[cfg(cfail1)]
return this.x + this.y;
#[cfg(cfail2)]
return this.x * this.x + this.y * this.y;
}
impl Point {
pub fn distance_from_origin(&self) -> f32 {
distance_squared(self).sqrt()
}
}
impl Point {
|
}
|
pub fn translate(&mut self, x: f32, y: f32) {
self.x += x;
self.y += y;
}
|
random_line_split
|
err.rs
|
use std::error::Error;
use std::fmt;
/// The enum `TermiosError` defines the possible errors from constructor Termios.
#[derive(Clone, Copy, Debug)]
pub enum TermiosError {
TcgGet,
TcgSet,
WriteMouseOn,
}
impl fmt::Display for TermiosError {
/// The function `fmt` formats the value using the given formatter.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", ::errno::errno())
}
}
impl Error for TermiosError {
/// The function `description` returns a short description of the error.
fn description(&self) -> &str
|
/// The function `cause` returns the lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> {
None
}
}
|
{
match *self {
TermiosError::TcgGet => "ioctl(2) TCGETS has occured an error.",
TermiosError::TcgSet => "ioctl(2) TCSETS has occured an error.",
TermiosError::WriteMouseOn => "Can't write the MouseOn term.",
}
}
|
identifier_body
|
err.rs
|
use std::error::Error;
use std::fmt;
/// The enum `TermiosError` defines the possible errors from constructor Termios.
#[derive(Clone, Copy, Debug)]
pub enum TermiosError {
TcgGet,
TcgSet,
WriteMouseOn,
}
impl fmt::Display for TermiosError {
/// The function `fmt` formats the value using the given formatter.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", ::errno::errno())
}
}
impl Error for TermiosError {
|
/// The function `description` returns a short description of the error.
fn description(&self) -> &str {
match *self {
TermiosError::TcgGet => "ioctl(2) TCGETS has occured an error.",
TermiosError::TcgSet => "ioctl(2) TCSETS has occured an error.",
TermiosError::WriteMouseOn => "Can't write the MouseOn term.",
}
}
/// The function `cause` returns the lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> {
None
}
}
|
random_line_split
|
|
err.rs
|
use std::error::Error;
use std::fmt;
/// The enum `TermiosError` defines the possible errors from constructor Termios.
#[derive(Clone, Copy, Debug)]
pub enum
|
{
TcgGet,
TcgSet,
WriteMouseOn,
}
impl fmt::Display for TermiosError {
/// The function `fmt` formats the value using the given formatter.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", ::errno::errno())
}
}
impl Error for TermiosError {
/// The function `description` returns a short description of the error.
fn description(&self) -> &str {
match *self {
TermiosError::TcgGet => "ioctl(2) TCGETS has occured an error.",
TermiosError::TcgSet => "ioctl(2) TCSETS has occured an error.",
TermiosError::WriteMouseOn => "Can't write the MouseOn term.",
}
}
/// The function `cause` returns the lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> {
None
}
}
|
TermiosError
|
identifier_name
|
mod.rs
|
#![recursion_limit = "128"]
#![no_std]
#[macro_use]
extern crate generic_array;
use core::cell::Cell;
use core::ops::{Add, Drop};
use generic_array::functional::*;
use generic_array::sequence::*;
use generic_array::typenum::{U0, U3, U4, U97};
use generic_array::GenericArray;
#[test]
fn test() {
let mut list97 = [0; 97];
for i in 0..97 {
list97[i] = i as i32;
}
let l: GenericArray<i32, U97> = GenericArray::clone_from_slice(&list97);
assert_eq!(l[0], 0);
assert_eq!(l[1], 1);
assert_eq!(l[32], 32);
assert_eq!(l[56], 56);
}
#[test]
fn test_drop() {
#[derive(Clone)]
struct TestDrop<'a>(&'a Cell<u32>);
impl<'a> Drop for TestDrop<'a> {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
let drop_counter = Cell::new(0);
{
let _: GenericArray<TestDrop, U3> = arr![TestDrop; TestDrop(&drop_counter),
TestDrop(&drop_counter),
TestDrop(&drop_counter)];
}
assert_eq!(drop_counter.get(), 3);
}
#[test]
fn test_arr() {
let test: GenericArray<u32, U3> = arr![u32; 1, 2, 3];
assert_eq!(test[1], 2);
}
#[test]
fn test_copy() {
let test = arr![u32; 1, 2, 3];
let test2 = test;
// if GenericArray is not copy, this should fail as a use of a moved value
assert_eq!(test[1], 2);
assert_eq!(test2[0], 1);
}
#[derive(Debug, PartialEq, Eq)]
struct NoClone<T>(T);
#[test]
fn test_from_slice() {
let arr = [1, 2, 3, 4];
let gen_arr = GenericArray::<_, U3>::from_slice(&arr[..3]);
assert_eq!(&arr[..3], gen_arr.as_slice());
let arr = [NoClone(1u32), NoClone(2), NoClone(3), NoClone(4)];
let gen_arr = GenericArray::<_, U3>::from_slice(&arr[..3]);
assert_eq!(&arr[..3], gen_arr.as_slice());
}
#[test]
fn test_from_mut_slice() {
let mut arr = [1, 2, 3, 4];
{
let gen_arr = GenericArray::<_, U3>::from_mut_slice(&mut arr[..3]);
|
gen_arr[2] = 10;
}
assert_eq!(arr, [1, 2, 10, 4]);
let mut arr = [NoClone(1u32), NoClone(2), NoClone(3), NoClone(4)];
{
let gen_arr = GenericArray::<_, U3>::from_mut_slice(&mut arr[..3]);
gen_arr[2] = NoClone(10);
}
assert_eq!(arr, [NoClone(1), NoClone(2), NoClone(10), NoClone(4)]);
}
#[test]
fn test_default() {
let arr = GenericArray::<u8, U4>::default();
assert_eq!(arr.as_slice(), &[0, 0, 0, 0]);
}
#[test]
fn test_from() {
let data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)];
let garray: GenericArray<(usize, usize, usize), U3> = data.into();
assert_eq!(&data, garray.as_slice());
}
#[test]
fn test_unit_macro() {
let arr = arr![f32; 3.14];
assert_eq!(arr[0], 3.14);
}
#[test]
fn test_empty_macro() {
let _arr = arr![f32;];
}
#[test]
fn test_cmp() {
let _ = arr![u8; 0x00].cmp(&arr![u8; 0x00]);
}
/// This test should cause a helpful compile error if uncommented.
// #[test]
// fn test_empty_macro2(){
// let arr = arr![];
// }
#[cfg(feature = "serde")]
mod impl_serde {
extern crate serde_json;
use generic_array::typenum::U6;
use generic_array::GenericArray;
#[test]
fn test_serde_implementation() {
let array: GenericArray<f64, U6> = arr![f64; 0.0, 5.0, 3.0, 7.07192, 76.0, -9.0];
let string = serde_json::to_string(&array).unwrap();
assert_eq!(string, "[0.0,5.0,3.0,7.07192,76.0,-9.0]");
let test_array: GenericArray<f64, U6> = serde_json::from_str(&string).unwrap();
assert_eq!(test_array, array);
}
}
#[test]
fn test_map() {
let b: GenericArray<i32, U4> = GenericArray::generate(|i| i as i32 * 4).map(|x| x - 3);
assert_eq!(b, arr![i32; -3, 1, 5, 9]);
}
#[test]
fn test_zip() {
let a: GenericArray<_, U4> = GenericArray::generate(|i| i + 1);
let b: GenericArray<_, U4> = GenericArray::generate(|i| i as i32 * 4);
// Uses reference and non-reference arguments
let c = (&a).zip(b, |r, l| *r as i32 + l);
assert_eq!(c, arr![i32; 1, 6, 11, 16]);
}
#[test]
#[should_panic]
fn test_from_iter_short() {
use core::iter::repeat;
let a: GenericArray<_, U4> = repeat(11).take(3).collect();
assert_eq!(a, arr![i32; 11, 11, 11, 0]);
}
#[test]
fn test_from_iter() {
use core::iter::{once, repeat};
let a: GenericArray<_, U4> = repeat(11).take(3).chain(once(0)).collect();
assert_eq!(a, arr![i32; 11, 11, 11, 0]);
}
#[allow(unused)]
#[derive(Debug, Copy, Clone)]
enum E {
V,
V2(i32),
V3 { h: bool, i: i32 },
}
#[allow(unused)]
#[derive(Debug, Copy, Clone)]
#[repr(C)]
#[repr(packed)]
struct Test {
t: u16,
s: u32,
mm: bool,
r: u16,
f: u16,
p: (),
o: u32,
ff: *const extern "C" fn(*const char) -> *const core::ffi::c_void,
l: *const core::ffi::c_void,
w: bool,
q: bool,
v: E,
}
#[test]
fn test_sizes() {
use core::mem::{size_of, size_of_val};
assert_eq!(size_of::<E>(), 8);
assert_eq!(size_of::<Test>(), 25 + size_of::<usize>() * 2);
assert_eq!(size_of_val(&arr![u8; 1, 2, 3]), size_of::<u8>() * 3);
assert_eq!(size_of_val(&arr![u32; 1]), size_of::<u32>() * 1);
assert_eq!(size_of_val(&arr![u64; 1, 2, 3, 4]), size_of::<u64>() * 4);
assert_eq!(size_of::<GenericArray<Test, U97>>(), size_of::<Test>() * 97);
}
#[test]
fn test_alignment() {
use core::mem::align_of;
assert_eq!(align_of::<GenericArray::<u32, U0>>(), align_of::<[u32; 0]>());
assert_eq!(align_of::<GenericArray::<u32, U3>>(), align_of::<[u32; 3]>());
assert_eq!(align_of::<GenericArray::<Test, U3>>(), align_of::<[Test; 3]>());
}
#[test]
fn test_append() {
let a = arr![i32; 1, 2, 3];
let b = a.append(4);
assert_eq!(b, arr![i32; 1, 2, 3, 4]);
}
#[test]
fn test_prepend() {
let a = arr![i32; 1, 2, 3];
let b = a.prepend(4);
assert_eq!(b, arr![i32; 4, 1, 2, 3]);
}
#[test]
fn test_pop() {
let a = arr![i32; 1, 2, 3, 4];
let (init, last) = a.pop_back();
assert_eq!(init, arr![i32; 1, 2, 3]);
assert_eq!(last, 4);
let (head, tail) = a.pop_front();
assert_eq!(head, 1);
assert_eq!(tail, arr![i32; 2, 3, 4]);
}
#[test]
fn test_split() {
let a = arr![i32; 1, 2, 3, 4];
let (b, c) = a.split();
assert_eq!(b, arr![i32; 1]);
assert_eq!(c, arr![i32; 2, 3, 4]);
let (e, f) = a.split();
assert_eq!(e, arr![i32; 1, 2]);
assert_eq!(f, arr![i32; 3, 4]);
}
#[test]
fn test_split_ref() {
let a = arr![i32; 1, 2, 3, 4];
let a_ref = &a;
let (b_ref, c_ref) = a_ref.split();
assert_eq!(b_ref, &arr![i32; 1]);
assert_eq!(c_ref, &arr![i32; 2, 3, 4]);
let (e_ref, f_ref) = a_ref.split();
assert_eq!(e_ref, &arr![i32; 1, 2]);
assert_eq!(f_ref, &arr![i32; 3, 4]);
}
#[test]
fn test_split_mut() {
let mut a = arr![i32; 1, 2, 3, 4];
let a_ref = &mut a;
let (b_ref, c_ref) = a_ref.split();
assert_eq!(b_ref, &mut arr![i32; 1]);
assert_eq!(c_ref, &mut arr![i32; 2, 3, 4]);
let (e_ref, f_ref) = a_ref.split();
assert_eq!(e_ref, &mut arr![i32; 1, 2]);
assert_eq!(f_ref, &mut arr![i32; 3, 4]);
}
#[test]
fn test_concat() {
let a = arr![i32; 1, 2];
let b = arr![i32; 3, 4, 5];
let c = a.concat(b);
assert_eq!(c, arr![i32; 1, 2, 3, 4, 5]);
let (d, e) = c.split();
assert_eq!(d, arr![i32; 1, 2]);
assert_eq!(e, arr![i32; 3, 4, 5]);
}
#[test]
fn test_fold() {
let a = arr![i32; 1, 2, 3, 4];
assert_eq!(10, a.fold(0, |a, x| a + x));
}
fn sum_generic<S>(s: S) -> i32
where
S: FunctionalSequence<i32>,
S::Item: Add<i32, Output = i32>, // `+`
i32: Add<S::Item, Output = i32>, // reflexive
{
s.fold(0, |a, x| a + x)
}
#[test]
fn test_sum() {
let a = sum_generic(arr![i32; 1, 2, 3, 4]);
assert_eq!(a, 10);
}
#[test]
fn test_as_ref() {
let a = arr![i32; 1, 2, 3, 4];
let a_ref: &[i32; 4] = a.as_ref();
assert_eq!(a_ref, &[1, 2, 3, 4]);
}
#[test]
fn test_as_mut() {
let mut a = arr![i32; 1, 2, 3, 4];
let a_mut: &mut [i32; 4] = a.as_mut();
assert_eq!(a_mut, &mut [1, 2, 3, 4]);
a_mut[2] = 0;
assert_eq!(a_mut, &mut [1, 2, 0, 4]);
assert_eq!(a, arr![i32; 1, 2, 0, 4]);
}
#[test]
fn test_from_array_ref() {
let a = arr![i32; 1, 2, 3, 4];
let a_ref: &[i32; 4] = a.as_ref();
let a_from: &GenericArray<i32, U4> = a_ref.into();
assert_eq!(&a, a_from);
}
#[test]
fn test_from_array_mut() {
let mut a = arr![i32; 1, 2, 3, 4];
let mut a_copy = a;
let a_mut: &mut [i32; 4] = a.as_mut();
let a_from: &mut GenericArray<i32, U4> = a_mut.into();
assert_eq!(&mut a_copy, a_from);
}
|
random_line_split
|
|
mod.rs
|
#![recursion_limit = "128"]
#![no_std]
#[macro_use]
extern crate generic_array;
use core::cell::Cell;
use core::ops::{Add, Drop};
use generic_array::functional::*;
use generic_array::sequence::*;
use generic_array::typenum::{U0, U3, U4, U97};
use generic_array::GenericArray;
#[test]
fn test() {
let mut list97 = [0; 97];
for i in 0..97 {
list97[i] = i as i32;
}
let l: GenericArray<i32, U97> = GenericArray::clone_from_slice(&list97);
assert_eq!(l[0], 0);
assert_eq!(l[1], 1);
assert_eq!(l[32], 32);
assert_eq!(l[56], 56);
}
#[test]
fn test_drop() {
#[derive(Clone)]
struct TestDrop<'a>(&'a Cell<u32>);
impl<'a> Drop for TestDrop<'a> {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
let drop_counter = Cell::new(0);
{
let _: GenericArray<TestDrop, U3> = arr![TestDrop; TestDrop(&drop_counter),
TestDrop(&drop_counter),
TestDrop(&drop_counter)];
}
assert_eq!(drop_counter.get(), 3);
}
#[test]
fn test_arr() {
let test: GenericArray<u32, U3> = arr![u32; 1, 2, 3];
assert_eq!(test[1], 2);
}
#[test]
fn test_copy() {
let test = arr![u32; 1, 2, 3];
let test2 = test;
// if GenericArray is not copy, this should fail as a use of a moved value
assert_eq!(test[1], 2);
assert_eq!(test2[0], 1);
}
#[derive(Debug, PartialEq, Eq)]
struct NoClone<T>(T);
#[test]
fn test_from_slice() {
let arr = [1, 2, 3, 4];
let gen_arr = GenericArray::<_, U3>::from_slice(&arr[..3]);
assert_eq!(&arr[..3], gen_arr.as_slice());
let arr = [NoClone(1u32), NoClone(2), NoClone(3), NoClone(4)];
let gen_arr = GenericArray::<_, U3>::from_slice(&arr[..3]);
assert_eq!(&arr[..3], gen_arr.as_slice());
}
#[test]
fn test_from_mut_slice() {
let mut arr = [1, 2, 3, 4];
{
let gen_arr = GenericArray::<_, U3>::from_mut_slice(&mut arr[..3]);
gen_arr[2] = 10;
}
assert_eq!(arr, [1, 2, 10, 4]);
let mut arr = [NoClone(1u32), NoClone(2), NoClone(3), NoClone(4)];
{
let gen_arr = GenericArray::<_, U3>::from_mut_slice(&mut arr[..3]);
gen_arr[2] = NoClone(10);
}
assert_eq!(arr, [NoClone(1), NoClone(2), NoClone(10), NoClone(4)]);
}
#[test]
fn test_default() {
let arr = GenericArray::<u8, U4>::default();
assert_eq!(arr.as_slice(), &[0, 0, 0, 0]);
}
#[test]
fn test_from() {
let data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)];
let garray: GenericArray<(usize, usize, usize), U3> = data.into();
assert_eq!(&data, garray.as_slice());
}
#[test]
fn test_unit_macro() {
let arr = arr![f32; 3.14];
assert_eq!(arr[0], 3.14);
}
#[test]
fn test_empty_macro() {
let _arr = arr![f32;];
}
#[test]
fn test_cmp() {
let _ = arr![u8; 0x00].cmp(&arr![u8; 0x00]);
}
/// This test should cause a helpful compile error if uncommented.
// #[test]
// fn test_empty_macro2(){
// let arr = arr![];
// }
#[cfg(feature = "serde")]
mod impl_serde {
extern crate serde_json;
use generic_array::typenum::U6;
use generic_array::GenericArray;
#[test]
fn test_serde_implementation() {
let array: GenericArray<f64, U6> = arr![f64; 0.0, 5.0, 3.0, 7.07192, 76.0, -9.0];
let string = serde_json::to_string(&array).unwrap();
assert_eq!(string, "[0.0,5.0,3.0,7.07192,76.0,-9.0]");
let test_array: GenericArray<f64, U6> = serde_json::from_str(&string).unwrap();
assert_eq!(test_array, array);
}
}
#[test]
fn test_map() {
let b: GenericArray<i32, U4> = GenericArray::generate(|i| i as i32 * 4).map(|x| x - 3);
assert_eq!(b, arr![i32; -3, 1, 5, 9]);
}
#[test]
fn test_zip() {
let a: GenericArray<_, U4> = GenericArray::generate(|i| i + 1);
let b: GenericArray<_, U4> = GenericArray::generate(|i| i as i32 * 4);
// Uses reference and non-reference arguments
let c = (&a).zip(b, |r, l| *r as i32 + l);
assert_eq!(c, arr![i32; 1, 6, 11, 16]);
}
#[test]
#[should_panic]
fn test_from_iter_short() {
use core::iter::repeat;
let a: GenericArray<_, U4> = repeat(11).take(3).collect();
assert_eq!(a, arr![i32; 11, 11, 11, 0]);
}
#[test]
fn test_from_iter() {
use core::iter::{once, repeat};
let a: GenericArray<_, U4> = repeat(11).take(3).chain(once(0)).collect();
assert_eq!(a, arr![i32; 11, 11, 11, 0]);
}
#[allow(unused)]
#[derive(Debug, Copy, Clone)]
enum E {
V,
V2(i32),
V3 { h: bool, i: i32 },
}
#[allow(unused)]
#[derive(Debug, Copy, Clone)]
#[repr(C)]
#[repr(packed)]
struct
|
{
t: u16,
s: u32,
mm: bool,
r: u16,
f: u16,
p: (),
o: u32,
ff: *const extern "C" fn(*const char) -> *const core::ffi::c_void,
l: *const core::ffi::c_void,
w: bool,
q: bool,
v: E,
}
#[test]
fn test_sizes() {
use core::mem::{size_of, size_of_val};
assert_eq!(size_of::<E>(), 8);
assert_eq!(size_of::<Test>(), 25 + size_of::<usize>() * 2);
assert_eq!(size_of_val(&arr![u8; 1, 2, 3]), size_of::<u8>() * 3);
assert_eq!(size_of_val(&arr![u32; 1]), size_of::<u32>() * 1);
assert_eq!(size_of_val(&arr![u64; 1, 2, 3, 4]), size_of::<u64>() * 4);
assert_eq!(size_of::<GenericArray<Test, U97>>(), size_of::<Test>() * 97);
}
#[test]
fn test_alignment() {
use core::mem::align_of;
assert_eq!(align_of::<GenericArray::<u32, U0>>(), align_of::<[u32; 0]>());
assert_eq!(align_of::<GenericArray::<u32, U3>>(), align_of::<[u32; 3]>());
assert_eq!(align_of::<GenericArray::<Test, U3>>(), align_of::<[Test; 3]>());
}
#[test]
fn test_append() {
let a = arr![i32; 1, 2, 3];
let b = a.append(4);
assert_eq!(b, arr![i32; 1, 2, 3, 4]);
}
#[test]
fn test_prepend() {
let a = arr![i32; 1, 2, 3];
let b = a.prepend(4);
assert_eq!(b, arr![i32; 4, 1, 2, 3]);
}
#[test]
fn test_pop() {
let a = arr![i32; 1, 2, 3, 4];
let (init, last) = a.pop_back();
assert_eq!(init, arr![i32; 1, 2, 3]);
assert_eq!(last, 4);
let (head, tail) = a.pop_front();
assert_eq!(head, 1);
assert_eq!(tail, arr![i32; 2, 3, 4]);
}
#[test]
fn test_split() {
let a = arr![i32; 1, 2, 3, 4];
let (b, c) = a.split();
assert_eq!(b, arr![i32; 1]);
assert_eq!(c, arr![i32; 2, 3, 4]);
let (e, f) = a.split();
assert_eq!(e, arr![i32; 1, 2]);
assert_eq!(f, arr![i32; 3, 4]);
}
#[test]
fn test_split_ref() {
let a = arr![i32; 1, 2, 3, 4];
let a_ref = &a;
let (b_ref, c_ref) = a_ref.split();
assert_eq!(b_ref, &arr![i32; 1]);
assert_eq!(c_ref, &arr![i32; 2, 3, 4]);
let (e_ref, f_ref) = a_ref.split();
assert_eq!(e_ref, &arr![i32; 1, 2]);
assert_eq!(f_ref, &arr![i32; 3, 4]);
}
#[test]
fn test_split_mut() {
let mut a = arr![i32; 1, 2, 3, 4];
let a_ref = &mut a;
let (b_ref, c_ref) = a_ref.split();
assert_eq!(b_ref, &mut arr![i32; 1]);
assert_eq!(c_ref, &mut arr![i32; 2, 3, 4]);
let (e_ref, f_ref) = a_ref.split();
assert_eq!(e_ref, &mut arr![i32; 1, 2]);
assert_eq!(f_ref, &mut arr![i32; 3, 4]);
}
#[test]
fn test_concat() {
let a = arr![i32; 1, 2];
let b = arr![i32; 3, 4, 5];
let c = a.concat(b);
assert_eq!(c, arr![i32; 1, 2, 3, 4, 5]);
let (d, e) = c.split();
assert_eq!(d, arr![i32; 1, 2]);
assert_eq!(e, arr![i32; 3, 4, 5]);
}
#[test]
fn test_fold() {
let a = arr![i32; 1, 2, 3, 4];
assert_eq!(10, a.fold(0, |a, x| a + x));
}
fn sum_generic<S>(s: S) -> i32
where
S: FunctionalSequence<i32>,
S::Item: Add<i32, Output = i32>, // `+`
i32: Add<S::Item, Output = i32>, // reflexive
{
s.fold(0, |a, x| a + x)
}
#[test]
fn test_sum() {
let a = sum_generic(arr![i32; 1, 2, 3, 4]);
assert_eq!(a, 10);
}
#[test]
fn test_as_ref() {
let a = arr![i32; 1, 2, 3, 4];
let a_ref: &[i32; 4] = a.as_ref();
assert_eq!(a_ref, &[1, 2, 3, 4]);
}
#[test]
fn test_as_mut() {
let mut a = arr![i32; 1, 2, 3, 4];
let a_mut: &mut [i32; 4] = a.as_mut();
assert_eq!(a_mut, &mut [1, 2, 3, 4]);
a_mut[2] = 0;
assert_eq!(a_mut, &mut [1, 2, 0, 4]);
assert_eq!(a, arr![i32; 1, 2, 0, 4]);
}
#[test]
fn test_from_array_ref() {
let a = arr![i32; 1, 2, 3, 4];
let a_ref: &[i32; 4] = a.as_ref();
let a_from: &GenericArray<i32, U4> = a_ref.into();
assert_eq!(&a, a_from);
}
#[test]
fn test_from_array_mut() {
let mut a = arr![i32; 1, 2, 3, 4];
let mut a_copy = a;
let a_mut: &mut [i32; 4] = a.as_mut();
let a_from: &mut GenericArray<i32, U4> = a_mut.into();
assert_eq!(&mut a_copy, a_from);
}
|
Test
|
identifier_name
|
mod.rs
|
// Copyright (C) 2017 Sebastian Dröge <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use glib::prelude::*;
mod imp;
glib::glib_wrapper! {
pub struct ToggleRecord(ObjectSubclass<imp::ToggleRecord>) @extends gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for ToggleRecord {}
unsafe impl Sync for ToggleRecord {}
pub fn r
|
plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"togglerecord",
gst::Rank::None,
ToggleRecord::static_type(),
)
}
|
egister(
|
identifier_name
|
mod.rs
|
// Copyright (C) 2017 Sebastian Dröge <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use glib::prelude::*;
mod imp;
glib::glib_wrapper! {
pub struct ToggleRecord(ObjectSubclass<imp::ToggleRecord>) @extends gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for ToggleRecord {}
unsafe impl Sync for ToggleRecord {}
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"togglerecord",
|
gst::Rank::None,
ToggleRecord::static_type(),
)
}
|
random_line_split
|
|
mod.rs
|
// Copyright (C) 2017 Sebastian Dröge <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use glib::prelude::*;
mod imp;
glib::glib_wrapper! {
pub struct ToggleRecord(ObjectSubclass<imp::ToggleRecord>) @extends gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for ToggleRecord {}
unsafe impl Sync for ToggleRecord {}
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
|
gst::Element::register(
Some(plugin),
"togglerecord",
gst::Rank::None,
ToggleRecord::static_type(),
)
}
|
identifier_body
|
|
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style font-variant font-weight font-stretch
font-size line-height font-family
${'font-size-adjust' if product == 'gecko' else ''}
${'font-kerning' if product == 'gecko' else ''}
${'font-variant-caps' if product == 'gecko' else ''}
${'font-variant-position' if product == 'gecko' else ''}
${'font-language-override' if product == 'none' else ''}"
spec="https://drafts.csswg.org/css-fonts-3/#propdef-font">
use parser::Parse;
use properties::longhands::{font_style, font_variant, font_weight, font_stretch};
use properties::longhands::{font_size, line_height, font_family};
use properties::longhands::font_family::computed_value::FontFamily;
pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let mut nb_normals = 0;
let mut style = None;
let mut variant = None;
let mut weight = None;
let mut stretch = None;
let size;
loop {
// Special-case 'normal' because it is valid in each of
// font-style, font-weight, font-variant and font-stretch.
// Leaves the values to None, 'normal' is the initial value for each of them.
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
nb_normals += 1;
continue;
}
if style.is_none() {
if let Ok(value) = input.try(|input| font_style::parse(context, input)) {
style = Some(value);
continue
}
}
if weight.is_none() {
if let Ok(value) = input.try(|input| font_weight::parse(context, input)) {
weight = Some(value);
continue
}
}
if variant.is_none() {
if let Ok(value) = input.try(|input| font_variant::parse(context, input)) {
variant = Some(value);
continue
}
}
if stretch.is_none() {
if let Ok(value) = input.try(|input| font_stretch::parse(context, input)) {
stretch = Some(value);
continue
}
}
size = Some(try!(font_size::parse(context, input)));
break
}
#[inline]
fn count<T>(opt: &Option<T>) -> u8
|
if size.is_none() || (count(&style) + count(&weight) + count(&variant) + count(&stretch) + nb_normals) > 4 {
return Err(())
}
let line_height = if input.try(|input| input.expect_delim('/')).is_ok() {
Some(try!(line_height::parse(context, input)))
} else {
None
};
let family = Vec::<FontFamily>::parse(context, input)?;
Ok(Longhands {
font_style: style,
font_variant: variant,
font_weight: weight,
font_stretch: stretch,
font_size: size,
line_height: line_height,
font_family: Some(font_family::SpecifiedValue(family)),
% if product == "gecko":
font_size_adjust: None,
font_kerning: None,
font_variant_caps: None,
font_variant_position: None,
% endif
% if product == "none":
font_language_override: None,
% endif
})
}
// This may be a bit off, unsure, possibly needs changes
impl<'a> LonghandsToSerialize<'a> {
fn to_css_declared<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let DeclaredValue::Value(ref style) = *self.font_style {
try!(style.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref variant) = *self.font_variant {
try!(variant.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref weight) = *self.font_weight {
try!(weight.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref stretch) = *self.font_stretch {
try!(stretch.to_css(dest));
try!(write!(dest, " "));
}
try!(self.font_size.to_css(dest));
if let DeclaredValue::Value(ref height) = *self.line_height {
match *height {
line_height::SpecifiedValue::Normal => {},
_ => {
try!(write!(dest, "/"));
try!(height.to_css(dest));
}
}
}
try!(write!(dest, " "));
self.font_family.to_css(dest)
}
}
</%helpers:shorthand>
|
{
if opt.is_some() { 1 } else { 0 }
}
|
identifier_body
|
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style font-variant font-weight font-stretch
font-size line-height font-family
${'font-size-adjust' if product == 'gecko' else ''}
${'font-kerning' if product == 'gecko' else ''}
${'font-variant-caps' if product == 'gecko' else ''}
${'font-variant-position' if product == 'gecko' else ''}
${'font-language-override' if product == 'none' else ''}"
spec="https://drafts.csswg.org/css-fonts-3/#propdef-font">
use parser::Parse;
use properties::longhands::{font_style, font_variant, font_weight, font_stretch};
use properties::longhands::{font_size, line_height, font_family};
use properties::longhands::font_family::computed_value::FontFamily;
pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let mut nb_normals = 0;
let mut style = None;
let mut variant = None;
let mut weight = None;
let mut stretch = None;
|
// Leaves the values to None, 'normal' is the initial value for each of them.
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
nb_normals += 1;
continue;
}
if style.is_none() {
if let Ok(value) = input.try(|input| font_style::parse(context, input)) {
style = Some(value);
continue
}
}
if weight.is_none() {
if let Ok(value) = input.try(|input| font_weight::parse(context, input)) {
weight = Some(value);
continue
}
}
if variant.is_none() {
if let Ok(value) = input.try(|input| font_variant::parse(context, input)) {
variant = Some(value);
continue
}
}
if stretch.is_none() {
if let Ok(value) = input.try(|input| font_stretch::parse(context, input)) {
stretch = Some(value);
continue
}
}
size = Some(try!(font_size::parse(context, input)));
break
}
#[inline]
fn count<T>(opt: &Option<T>) -> u8 {
if opt.is_some() { 1 } else { 0 }
}
if size.is_none() || (count(&style) + count(&weight) + count(&variant) + count(&stretch) + nb_normals) > 4 {
return Err(())
}
let line_height = if input.try(|input| input.expect_delim('/')).is_ok() {
Some(try!(line_height::parse(context, input)))
} else {
None
};
let family = Vec::<FontFamily>::parse(context, input)?;
Ok(Longhands {
font_style: style,
font_variant: variant,
font_weight: weight,
font_stretch: stretch,
font_size: size,
line_height: line_height,
font_family: Some(font_family::SpecifiedValue(family)),
% if product == "gecko":
font_size_adjust: None,
font_kerning: None,
font_variant_caps: None,
font_variant_position: None,
% endif
% if product == "none":
font_language_override: None,
% endif
})
}
// This may be a bit off, unsure, possibly needs changes
impl<'a> LonghandsToSerialize<'a> {
fn to_css_declared<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let DeclaredValue::Value(ref style) = *self.font_style {
try!(style.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref variant) = *self.font_variant {
try!(variant.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref weight) = *self.font_weight {
try!(weight.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref stretch) = *self.font_stretch {
try!(stretch.to_css(dest));
try!(write!(dest, " "));
}
try!(self.font_size.to_css(dest));
if let DeclaredValue::Value(ref height) = *self.line_height {
match *height {
line_height::SpecifiedValue::Normal => {},
_ => {
try!(write!(dest, "/"));
try!(height.to_css(dest));
}
}
}
try!(write!(dest, " "));
self.font_family.to_css(dest)
}
}
</%helpers:shorthand>
|
let size;
loop {
// Special-case 'normal' because it is valid in each of
// font-style, font-weight, font-variant and font-stretch.
|
random_line_split
|
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style font-variant font-weight font-stretch
font-size line-height font-family
${'font-size-adjust' if product == 'gecko' else ''}
${'font-kerning' if product == 'gecko' else ''}
${'font-variant-caps' if product == 'gecko' else ''}
${'font-variant-position' if product == 'gecko' else ''}
${'font-language-override' if product == 'none' else ''}"
spec="https://drafts.csswg.org/css-fonts-3/#propdef-font">
use parser::Parse;
use properties::longhands::{font_style, font_variant, font_weight, font_stretch};
use properties::longhands::{font_size, line_height, font_family};
use properties::longhands::font_family::computed_value::FontFamily;
pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let mut nb_normals = 0;
let mut style = None;
let mut variant = None;
let mut weight = None;
let mut stretch = None;
let size;
loop {
// Special-case 'normal' because it is valid in each of
// font-style, font-weight, font-variant and font-stretch.
// Leaves the values to None, 'normal' is the initial value for each of them.
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
nb_normals += 1;
continue;
}
if style.is_none()
|
if weight.is_none() {
if let Ok(value) = input.try(|input| font_weight::parse(context, input)) {
weight = Some(value);
continue
}
}
if variant.is_none() {
if let Ok(value) = input.try(|input| font_variant::parse(context, input)) {
variant = Some(value);
continue
}
}
if stretch.is_none() {
if let Ok(value) = input.try(|input| font_stretch::parse(context, input)) {
stretch = Some(value);
continue
}
}
size = Some(try!(font_size::parse(context, input)));
break
}
#[inline]
fn count<T>(opt: &Option<T>) -> u8 {
if opt.is_some() { 1 } else { 0 }
}
if size.is_none() || (count(&style) + count(&weight) + count(&variant) + count(&stretch) + nb_normals) > 4 {
return Err(())
}
let line_height = if input.try(|input| input.expect_delim('/')).is_ok() {
Some(try!(line_height::parse(context, input)))
} else {
None
};
let family = Vec::<FontFamily>::parse(context, input)?;
Ok(Longhands {
font_style: style,
font_variant: variant,
font_weight: weight,
font_stretch: stretch,
font_size: size,
line_height: line_height,
font_family: Some(font_family::SpecifiedValue(family)),
% if product == "gecko":
font_size_adjust: None,
font_kerning: None,
font_variant_caps: None,
font_variant_position: None,
% endif
% if product == "none":
font_language_override: None,
% endif
})
}
// This may be a bit off, unsure, possibly needs changes
impl<'a> LonghandsToSerialize<'a> {
fn to_css_declared<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let DeclaredValue::Value(ref style) = *self.font_style {
try!(style.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref variant) = *self.font_variant {
try!(variant.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref weight) = *self.font_weight {
try!(weight.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref stretch) = *self.font_stretch {
try!(stretch.to_css(dest));
try!(write!(dest, " "));
}
try!(self.font_size.to_css(dest));
if let DeclaredValue::Value(ref height) = *self.line_height {
match *height {
line_height::SpecifiedValue::Normal => {},
_ => {
try!(write!(dest, "/"));
try!(height.to_css(dest));
}
}
}
try!(write!(dest, " "));
self.font_family.to_css(dest)
}
}
</%helpers:shorthand>
|
{
if let Ok(value) = input.try(|input| font_style::parse(context, input)) {
style = Some(value);
continue
}
}
|
conditional_block
|
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style font-variant font-weight font-stretch
font-size line-height font-family
${'font-size-adjust' if product == 'gecko' else ''}
${'font-kerning' if product == 'gecko' else ''}
${'font-variant-caps' if product == 'gecko' else ''}
${'font-variant-position' if product == 'gecko' else ''}
${'font-language-override' if product == 'none' else ''}"
spec="https://drafts.csswg.org/css-fonts-3/#propdef-font">
use parser::Parse;
use properties::longhands::{font_style, font_variant, font_weight, font_stretch};
use properties::longhands::{font_size, line_height, font_family};
use properties::longhands::font_family::computed_value::FontFamily;
pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let mut nb_normals = 0;
let mut style = None;
let mut variant = None;
let mut weight = None;
let mut stretch = None;
let size;
loop {
// Special-case 'normal' because it is valid in each of
// font-style, font-weight, font-variant and font-stretch.
// Leaves the values to None, 'normal' is the initial value for each of them.
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
nb_normals += 1;
continue;
}
if style.is_none() {
if let Ok(value) = input.try(|input| font_style::parse(context, input)) {
style = Some(value);
continue
}
}
if weight.is_none() {
if let Ok(value) = input.try(|input| font_weight::parse(context, input)) {
weight = Some(value);
continue
}
}
if variant.is_none() {
if let Ok(value) = input.try(|input| font_variant::parse(context, input)) {
variant = Some(value);
continue
}
}
if stretch.is_none() {
if let Ok(value) = input.try(|input| font_stretch::parse(context, input)) {
stretch = Some(value);
continue
}
}
size = Some(try!(font_size::parse(context, input)));
break
}
#[inline]
fn count<T>(opt: &Option<T>) -> u8 {
if opt.is_some() { 1 } else { 0 }
}
if size.is_none() || (count(&style) + count(&weight) + count(&variant) + count(&stretch) + nb_normals) > 4 {
return Err(())
}
let line_height = if input.try(|input| input.expect_delim('/')).is_ok() {
Some(try!(line_height::parse(context, input)))
} else {
None
};
let family = Vec::<FontFamily>::parse(context, input)?;
Ok(Longhands {
font_style: style,
font_variant: variant,
font_weight: weight,
font_stretch: stretch,
font_size: size,
line_height: line_height,
font_family: Some(font_family::SpecifiedValue(family)),
% if product == "gecko":
font_size_adjust: None,
font_kerning: None,
font_variant_caps: None,
font_variant_position: None,
% endif
% if product == "none":
font_language_override: None,
% endif
})
}
// This may be a bit off, unsure, possibly needs changes
impl<'a> LonghandsToSerialize<'a> {
fn
|
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let DeclaredValue::Value(ref style) = *self.font_style {
try!(style.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref variant) = *self.font_variant {
try!(variant.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref weight) = *self.font_weight {
try!(weight.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref stretch) = *self.font_stretch {
try!(stretch.to_css(dest));
try!(write!(dest, " "));
}
try!(self.font_size.to_css(dest));
if let DeclaredValue::Value(ref height) = *self.line_height {
match *height {
line_height::SpecifiedValue::Normal => {},
_ => {
try!(write!(dest, "/"));
try!(height.to_css(dest));
}
}
}
try!(write!(dest, " "));
self.font_family.to_css(dest)
}
}
</%helpers:shorthand>
|
to_css_declared
|
identifier_name
|
sr_log.rs
|
// SairaDB - A distributed database
// Copyright (C) 2015 by Siyu Wang
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
extern crate time;
extern crate libc;
|
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::io::{stderr, Write};
use std::fs::{create_dir_all, File};
use std::path::Path;
pub fn init(dir: String) -> (Sender<String>, thread::JoinHandle<()>) {
let tm = time::now();
let log_dir = dir + "/slave/log/" + &tm_cat(tm);
let _ = create_dir_all(Path::new(&log_dir));
let (tx, rx) = channel();
let jh = thread::Builder::new().name("log".to_string()).spawn(|| {
log_task(log_dir, rx);
}).unwrap();
(tx, jh)
}
fn tm_cat(tm: time::Tm) -> String {
format!("{}-{}-{}_{}-{}-{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn tm_format(tm: time::Tm) -> String {
format!("{}-{}-{} {}:{}:{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn log_task(log_dir: String, rx: Receiver<String>) {
let mut tm = time::now();
let mut fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
let mut log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
};
let mut size = 0usize;
let mut cache = "".to_string();
//let mut timer = Timer::new().unwrap();
loop {
if cache.len() == 0 {
let new_log = rx.recv().unwrap();
tm = time::now();
cache = tm_format(tm) + " " + &new_log + "\n";
} else {
//let timeout = timer.oneshot(Duration::milliseconds(100));
/*select! {
new_log = rx.recv() => {
cache = cache + &tm_format(tm) + " " + &new_log.unwrap() + "\n";
continue;
}
_ = timeout.recv() => {}
}*/
match log_file.write_all(cache.as_bytes()) {
Ok(_) => {println!("ok");}
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nWrite {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
}
size += cache.len();
cache = "".to_string();
if size > 1000000000 {
tm = time::now();
fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}",
fname, e);
unsafe { libc::exit(4); }
}
};
size = 0;
}
}
}
}
|
random_line_split
|
|
sr_log.rs
|
// SairaDB - A distributed database
// Copyright (C) 2015 by Siyu Wang
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
extern crate time;
extern crate libc;
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::io::{stderr, Write};
use std::fs::{create_dir_all, File};
use std::path::Path;
pub fn init(dir: String) -> (Sender<String>, thread::JoinHandle<()>) {
let tm = time::now();
let log_dir = dir + "/slave/log/" + &tm_cat(tm);
let _ = create_dir_all(Path::new(&log_dir));
let (tx, rx) = channel();
let jh = thread::Builder::new().name("log".to_string()).spawn(|| {
log_task(log_dir, rx);
}).unwrap();
(tx, jh)
}
fn tm_cat(tm: time::Tm) -> String {
format!("{}-{}-{}_{}-{}-{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn tm_format(tm: time::Tm) -> String {
format!("{}-{}-{} {}:{}:{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn log_task(log_dir: String, rx: Receiver<String>) {
let mut tm = time::now();
let mut fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
let mut log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
};
let mut size = 0usize;
let mut cache = "".to_string();
//let mut timer = Timer::new().unwrap();
loop {
if cache.len() == 0 {
let new_log = rx.recv().unwrap();
tm = time::now();
cache = tm_format(tm) + " " + &new_log + "\n";
} else {
//let timeout = timer.oneshot(Duration::milliseconds(100));
/*select! {
new_log = rx.recv() => {
cache = cache + &tm_format(tm) + " " + &new_log.unwrap() + "\n";
continue;
}
_ = timeout.recv() => {}
}*/
match log_file.write_all(cache.as_bytes()) {
Ok(_) => {println!("ok");}
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nWrite {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
}
size += cache.len();
cache = "".to_string();
if size > 1000000000 {
tm = time::now();
fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) =>
|
};
size = 0;
}
}
}
}
|
{
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}",
fname, e);
unsafe { libc::exit(4); }
}
|
conditional_block
|
sr_log.rs
|
// SairaDB - A distributed database
// Copyright (C) 2015 by Siyu Wang
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
extern crate time;
extern crate libc;
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::io::{stderr, Write};
use std::fs::{create_dir_all, File};
use std::path::Path;
pub fn
|
(dir: String) -> (Sender<String>, thread::JoinHandle<()>) {
let tm = time::now();
let log_dir = dir + "/slave/log/" + &tm_cat(tm);
let _ = create_dir_all(Path::new(&log_dir));
let (tx, rx) = channel();
let jh = thread::Builder::new().name("log".to_string()).spawn(|| {
log_task(log_dir, rx);
}).unwrap();
(tx, jh)
}
fn tm_cat(tm: time::Tm) -> String {
format!("{}-{}-{}_{}-{}-{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn tm_format(tm: time::Tm) -> String {
format!("{}-{}-{} {}:{}:{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn log_task(log_dir: String, rx: Receiver<String>) {
let mut tm = time::now();
let mut fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
let mut log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
};
let mut size = 0usize;
let mut cache = "".to_string();
//let mut timer = Timer::new().unwrap();
loop {
if cache.len() == 0 {
let new_log = rx.recv().unwrap();
tm = time::now();
cache = tm_format(tm) + " " + &new_log + "\n";
} else {
//let timeout = timer.oneshot(Duration::milliseconds(100));
/*select! {
new_log = rx.recv() => {
cache = cache + &tm_format(tm) + " " + &new_log.unwrap() + "\n";
continue;
}
_ = timeout.recv() => {}
}*/
match log_file.write_all(cache.as_bytes()) {
Ok(_) => {println!("ok");}
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nWrite {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
}
size += cache.len();
cache = "".to_string();
if size > 1000000000 {
tm = time::now();
fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}",
fname, e);
unsafe { libc::exit(4); }
}
};
size = 0;
}
}
}
}
|
init
|
identifier_name
|
sr_log.rs
|
// SairaDB - A distributed database
// Copyright (C) 2015 by Siyu Wang
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
extern crate time;
extern crate libc;
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::io::{stderr, Write};
use std::fs::{create_dir_all, File};
use std::path::Path;
pub fn init(dir: String) -> (Sender<String>, thread::JoinHandle<()>) {
let tm = time::now();
let log_dir = dir + "/slave/log/" + &tm_cat(tm);
let _ = create_dir_all(Path::new(&log_dir));
let (tx, rx) = channel();
let jh = thread::Builder::new().name("log".to_string()).spawn(|| {
log_task(log_dir, rx);
}).unwrap();
(tx, jh)
}
fn tm_cat(tm: time::Tm) -> String
|
fn tm_format(tm: time::Tm) -> String {
format!("{}-{}-{} {}:{}:{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn log_task(log_dir: String, rx: Receiver<String>) {
let mut tm = time::now();
let mut fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
let mut log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
};
let mut size = 0usize;
let mut cache = "".to_string();
//let mut timer = Timer::new().unwrap();
loop {
if cache.len() == 0 {
let new_log = rx.recv().unwrap();
tm = time::now();
cache = tm_format(tm) + " " + &new_log + "\n";
} else {
//let timeout = timer.oneshot(Duration::milliseconds(100));
/*select! {
new_log = rx.recv() => {
cache = cache + &tm_format(tm) + " " + &new_log.unwrap() + "\n";
continue;
}
_ = timeout.recv() => {}
}*/
match log_file.write_all(cache.as_bytes()) {
Ok(_) => {println!("ok");}
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nWrite {}:\n{}", fname, e);
unsafe { libc::exit(4); }
}
}
size += cache.len();
cache = "".to_string();
if size > 1000000000 {
tm = time::now();
fname = log_dir.to_string() + "/" + &tm_cat(tm) + ".log";
log_file = match File::create(Path::new(&fname)) {
Ok(f) => f,
Err(e) => {
let _ = writeln!(&mut stderr(),
"Error:\nCan not create {}:\n{}",
fname, e);
unsafe { libc::exit(4); }
}
};
size = 0;
}
}
}
}
|
{
format!("{}-{}-{}_{}-{}-{}",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec)
}
|
identifier_body
|
htmlstyleelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLStyleElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Temporary, OptionalRootable};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::{Element, ElementTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;
use layout_interface::{LayoutChan, Msg};
use util::str::DOMString;
use style::stylesheets::{Origin, Stylesheet};
use style::media_queries::parse_media_query_list;
use style::node::TElement;
use cssparser::Parser as CssParser;
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
}
impl HTMLStyleElementDerived for EventTarget {
fn is_htmlstyleelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)))
}
}
impl HTMLStyleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLStyleElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLStyleElement> {
let element = HTMLStyleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLStyleElementBinding::Wrap)
}
}
pub trait StyleElementHelpers {
fn parse_own_css(self);
}
impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> {
fn parse_own_css(self) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let element: JSRef<Element> = ElementCast::from_ref(self);
assert!(node.is_in_doc());
let win = window_from_node(node).root();
let win = win.r();
let url = win.get_url();
let mq_str = element.get_attr(&ns!(""), &atom!("media")).unwrap_or("");
let mut css_parser = CssParser::new(&mq_str);
let media = parse_media_query_list(&mut css_parser);
let data = node.GetTextContent().expect("Element.textContent must be a string");
let sheet = Stylesheet::from_str(data.as_slice(), url, Origin::Author);
let LayoutChan(ref layout_chan) = win.layout_chan();
layout_chan.send(Msg::AddStylesheet(sheet, media)).unwrap();
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLStyleElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn child_inserted(&self, child: JSRef<Node>) {
if let Some(ref s) = self.super_type() {
s.child_inserted(child);
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
|
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
self.parse_own_css();
}
}
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.