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 |
---|---|---|---|---|
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as *mut _,
}
}
}
pub struct Selector {
id: usize,
kq: RawFd,
}
impl Selector {
pub fn new() -> io::Result<Selector> {
// offset by 1 to avoid choosing 0 as the id of a selector
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
let kq = unsafe { try!(cvt(libc::kqueue())) };
drop(set_cloexec(kq));
Ok(Selector {
id: id,
kq: kq,
})
}
pub fn id(&self) -> usize {
self.id
}
pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
let timeout = timeout.map(|to| {
libc::timespec {
tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
tv_nsec: to.subsec_nanos() as libc::c_long,
}
});
let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut());
unsafe {
let cnt = try!(cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
// FIXME: needs a saturating cast here.
evts.sys_events.0.capacity() as c_int,
timeout)));
evts.sys_events.0.set_len(cnt as usize);
Ok(evts.coalesce(awakener))
}
}
pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } |
if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } |
libc::EV_RECEIPT;
unsafe {
let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE };
let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE };
let mut changes = [
kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data!= 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w };
if!(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE!= 0) {
return Err(::std::io::Error::from_raw_os_error(change.data as i32));
}
}
}
Ok(())
}
}
pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
unsafe {
// EV_RECEIPT is a nice way to apply changes and get back per-event results while not
// draining the actual changes.
let filter = libc::EV_DELETE | libc::EV_RECEIPT;
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())).map(|_| ()));
if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
for change in changes.iter() {
debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
if change.data!= 0 && change.data as i32!= libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
}
Ok(())
}
}
}
impl fmt::Debug for Selector {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Selector")
.field("id", &self.id)
.field("kq", &self.kq)
.finish()
}
}
impl Drop for Selector {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.kq);
}
}
}
pub struct Events {
sys_events: KeventList,
events: Vec<Event>,
event_map: HashMap<Token, usize>,
}
struct KeventList(Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
pub fn with_capacity(cap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.events.capacity()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn get(&self, idx: usize) -> Option<Event> {
self.events.get(idx).map(|e| *e)
}
fn coalesce(&mut self, awakener: Token) -> bool {
let mut ret = false;
self.events.clear();
self.event_map.clear();
for e in self.sys_events.0.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
if token == awakener {
// TODO: Should this return an error if event is an error. It
// is not critical as spurious wakeups are permitted.
ret = true;
continue;
}
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(Event::new(Ready::none(), token));
}
if e.flags & libc::EV_ERROR!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
if e.filter == libc::EVFILT_READ {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE {
| if e.flags & libc::EV_EOF!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
}
}
ret
}
pub fn push_event(&mut self, event: Event) {
self.events.push(event);
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
}
}
#[test]
fn does_not_register_rw() {
use ::deprecated::{EventLoopBuilder, Handler};
use ::unix::EventedFd;
struct Nop;
impl Handler for Nop {
type Timeout = ();
type Message = ();
}
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds");
evtloop.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
}
| event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
| conditional_block |
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as *mut _,
}
}
}
pub struct Selector {
id: usize,
kq: RawFd,
}
impl Selector {
pub fn new() -> io::Result<Selector> {
// offset by 1 to avoid choosing 0 as the id of a selector
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
let kq = unsafe { try!(cvt(libc::kqueue())) };
drop(set_cloexec(kq));
Ok(Selector {
id: id,
kq: kq,
})
}
pub fn id(&self) -> usize {
self.id
}
pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
let timeout = timeout.map(|to| {
libc::timespec {
tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
tv_nsec: to.subsec_nanos() as libc::c_long,
}
});
let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut());
unsafe {
let cnt = try!(cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
// FIXME: needs a saturating cast here.
evts.sys_events.0.capacity() as c_int,
timeout)));
evts.sys_events.0.set_len(cnt as usize);
Ok(evts.coalesce(awakener))
}
}
pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } |
if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } |
libc::EV_RECEIPT;
unsafe {
let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE };
let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE };
let mut changes = [
kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data!= 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w };
if!(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE!= 0) {
return Err(::std::io::Error::from_raw_os_error(change.data as i32));
}
}
}
Ok(())
}
}
pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
unsafe {
// EV_RECEIPT is a nice way to apply changes and get back per-event results while not
// draining the actual changes.
let filter = libc::EV_DELETE | libc::EV_RECEIPT;
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())).map(|_| ()));
if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
for change in changes.iter() {
debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
if change.data!= 0 && change.data as i32!= libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
}
Ok(())
}
}
}
impl fmt::Debug for Selector {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Selector")
.field("id", &self.id)
.field("kq", &self.kq)
.finish()
}
}
impl Drop for Selector {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.kq);
}
}
}
pub struct Events {
sys_events: KeventList,
events: Vec<Event>,
event_map: HashMap<Token, usize>,
}
struct KeventList(Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
pub fn wi | ap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.events.capacity()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn get(&self, idx: usize) -> Option<Event> {
self.events.get(idx).map(|e| *e)
}
fn coalesce(&mut self, awakener: Token) -> bool {
let mut ret = false;
self.events.clear();
self.event_map.clear();
for e in self.sys_events.0.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
if token == awakener {
// TODO: Should this return an error if event is an error. It
// is not critical as spurious wakeups are permitted.
ret = true;
continue;
}
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(Event::new(Ready::none(), token));
}
if e.flags & libc::EV_ERROR!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
if e.filter == libc::EVFILT_READ {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE {
event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
if e.flags & libc::EV_EOF!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
}
}
ret
}
pub fn push_event(&mut self, event: Event) {
self.events.push(event);
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
}
}
#[test]
fn does_not_register_rw() {
use ::deprecated::{EventLoopBuilder, Handler};
use ::unix::EventedFd;
struct Nop;
impl Handler for Nop {
type Timeout = ();
type Message = ();
}
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds");
evtloop.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
}
| th_capacity(c | identifier_name |
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as *mut _,
}
}
}
pub struct Selector {
id: usize,
kq: RawFd,
}
impl Selector {
pub fn new() -> io::Result<Selector> {
// offset by 1 to avoid choosing 0 as the id of a selector
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
let kq = unsafe { try!(cvt(libc::kqueue())) };
drop(set_cloexec(kq));
Ok(Selector {
id: id,
kq: kq,
})
}
pub fn id(&self) -> usize {
self.id
}
pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
let timeout = timeout.map(|to| {
libc::timespec {
tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
tv_nsec: to.subsec_nanos() as libc::c_long,
}
});
let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut());
unsafe {
let cnt = try!(cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
// FIXME: needs a saturating cast here.
evts.sys_events.0.capacity() as c_int,
timeout)));
evts.sys_events.0.set_len(cnt as usize);
Ok(evts.coalesce(awakener))
}
}
pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } |
if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } |
libc::EV_RECEIPT;
unsafe {
let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE };
let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE };
let mut changes = [ | ::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data!= 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w };
if!(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE!= 0) {
return Err(::std::io::Error::from_raw_os_error(change.data as i32));
}
}
}
Ok(())
}
}
pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
unsafe {
// EV_RECEIPT is a nice way to apply changes and get back per-event results while not
// draining the actual changes.
let filter = libc::EV_DELETE | libc::EV_RECEIPT;
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())).map(|_| ()));
if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
for change in changes.iter() {
debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
if change.data!= 0 && change.data as i32!= libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
}
Ok(())
}
}
}
impl fmt::Debug for Selector {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Selector")
.field("id", &self.id)
.field("kq", &self.kq)
.finish()
}
}
impl Drop for Selector {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.kq);
}
}
}
pub struct Events {
sys_events: KeventList,
events: Vec<Event>,
event_map: HashMap<Token, usize>,
}
struct KeventList(Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
pub fn with_capacity(cap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.events.capacity()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn get(&self, idx: usize) -> Option<Event> {
self.events.get(idx).map(|e| *e)
}
fn coalesce(&mut self, awakener: Token) -> bool {
let mut ret = false;
self.events.clear();
self.event_map.clear();
for e in self.sys_events.0.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
if token == awakener {
// TODO: Should this return an error if event is an error. It
// is not critical as spurious wakeups are permitted.
ret = true;
continue;
}
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(Event::new(Ready::none(), token));
}
if e.flags & libc::EV_ERROR!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
if e.filter == libc::EVFILT_READ {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE {
event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
if e.flags & libc::EV_EOF!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
}
}
ret
}
pub fn push_event(&mut self, event: Event) {
self.events.push(event);
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
}
}
#[test]
fn does_not_register_rw() {
use ::deprecated::{EventLoopBuilder, Handler};
use ::unix::EventedFd;
struct Nop;
impl Handler for Nop {
type Timeout = ();
type Message = ();
}
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds");
evtloop.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
} | kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int, | random_line_split |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
mod action;
mod background;
mod canvas;
mod element;
mod event;
mod font;
mod loader;
mod resources;
mod sound;
mod sprite;
mod window;
pub use self::action::Action;
pub use self::background::Background;
pub use self::canvas::{Align, Canvas};
pub use self::element::Element; | pub use self::window::Window;
pub use sdl2::rect::{Point, Rect};
pub const FRAME_DELAY_MILLIS: u32 = 40;
// ========================================================================= // | pub use self::event::{Event, KeyMod, Keycode};
pub use self::font::Font;
pub use self::resources::Resources;
pub use self::sound::Sound;
pub use self::sprite::Sprite; | random_line_split |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone(); |
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
},
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_,None) => fail!("Error opening message file: {:s}", share2)
}
}
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
} | let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2); | random_line_split |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else |
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
} ,
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_ ,None) => fail!("Error opening message file: {:s}", share2)
}
} | conditional_block |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
},
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_,None) => fail!("Error opening message file: {:s}", share2)
}
}
}
fn | (a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| xor | identifier_name |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
},
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_,None) => fail!("Error opening message file: {:s}", share2)
}
}
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] | {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
} | identifier_body |
|
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_uppercase_pattern_statics)]
use libc::c_uint;
use std::cmp;
use llvm;
use llvm::{Integer, Pointer, Float, Double, Struct, Array};
use llvm::{StructRetAttribute, ZExtAttribute};
use middle::trans::cabi::{ArgType, FnType};
use middle::trans::context::CrateContext;
use middle::trans::type_::Type;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1u) / a * a;
}
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a);
}
fn ty_align(ty: Type) -> uint | ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
}
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => fail!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::indirect(ty, Some(StructRetAttribute))
}
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType {
let orig_offset = *offset;
let size = ty_size(ty) * 8;
let mut align = ty_align(ty);
align = cmp::min(cmp::max(align, 4), 8);
*offset = align_up_to(*offset, align);
*offset += align_up_to(size, align * 8) / 8;
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::direct(
ty,
Some(struct_ty(ccx, ty)),
padding_ty(ccx, align, orig_offset),
None
)
}
}
fn is_reg_ty(ty: Type) -> bool {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
}
fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
Some(Type::i32(ccx))
} else {
None
}
}
fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
let int_ty = Type::i32(ccx);
let mut args = Vec::new();
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx, r as c_uint)));
}
}
args
}
fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
let sret = ret_ty.is_indirect();
let mut arg_tys = Vec::new();
let mut offset = if sret { 4 } else { 0 };
for aty in atys.iter() {
let ty = classify_arg_ty(ccx, *aty, &mut offset);
arg_tys.push(ty);
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type(); | identifier_body |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_uppercase_pattern_statics)]
use libc::c_uint;
use std::cmp;
use llvm;
use llvm::{Integer, Pointer, Float, Double, Struct, Array};
use llvm::{StructRetAttribute, ZExtAttribute};
use middle::trans::cabi::{ArgType, FnType};
use middle::trans::context::CrateContext;
use middle::trans::type_::Type;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1u) / a * a;
}
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a); | unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
}
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => fail!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::indirect(ty, Some(StructRetAttribute))
}
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType {
let orig_offset = *offset;
let size = ty_size(ty) * 8;
let mut align = ty_align(ty);
align = cmp::min(cmp::max(align, 4), 8);
*offset = align_up_to(*offset, align);
*offset += align_up_to(size, align * 8) / 8;
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::direct(
ty,
Some(struct_ty(ccx, ty)),
padding_ty(ccx, align, orig_offset),
None
)
}
}
fn is_reg_ty(ty: Type) -> bool {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
}
fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
Some(Type::i32(ccx))
} else {
None
}
}
fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
let int_ty = Type::i32(ccx);
let mut args = Vec::new();
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx, r as c_uint)));
}
}
args
}
fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
let sret = ret_ty.is_indirect();
let mut arg_tys = Vec::new();
let mut offset = if sret { 4 } else { 0 };
for aty in atys.iter() {
let ty = classify_arg_ty(ccx, *aty, &mut offset);
arg_tys.push(ty);
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
} | }
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => { | random_line_split |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_uppercase_pattern_statics)]
use libc::c_uint;
use std::cmp;
use llvm;
use llvm::{Integer, Pointer, Float, Double, Struct, Array};
use llvm::{StructRetAttribute, ZExtAttribute};
use middle::trans::cabi::{ArgType, FnType};
use middle::trans::context::CrateContext;
use middle::trans::type_::Type;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1u) / a * a;
}
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a);
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
}
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => fail!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::indirect(ty, Some(StructRetAttribute))
}
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType {
let orig_offset = *offset;
let size = ty_size(ty) * 8;
let mut align = ty_align(ty);
align = cmp::min(cmp::max(align, 4), 8);
*offset = align_up_to(*offset, align);
*offset += align_up_to(size, align * 8) / 8;
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::direct(
ty,
Some(struct_ty(ccx, ty)),
padding_ty(ccx, align, orig_offset),
None
)
}
}
fn is_reg_ty(ty: Type) -> bool {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
}
fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
Some(Type::i32(ccx))
} else {
None
}
}
fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
let int_ty = Type::i32(ccx);
let mut args = Vec::new();
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx, r as c_uint)));
}
}
args
}
fn | (ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
let sret = ret_ty.is_indirect();
let mut arg_tys = Vec::new();
let mut offset = if sret { 4 } else { 0 };
for aty in atys.iter() {
let ty = classify_arg_ty(ccx, *aty, &mut offset);
arg_tys.push(ty);
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| struct_ty | identifier_name |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn sort_array() {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
// We need to make the strings owned to construct the `Options` instance.
let mode = if count {
OutputMode::Count
} else if sort | else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() {
unimplemented!()
}
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.)
| {
OutputMode::SortAndPrint
} | conditional_block |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn sort_array() {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
// We need to make the strings owned to construct the `Options` instance.
let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() |
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.)
| {
unimplemented!()
} | identifier_body |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn sort_array() {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
| let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() {
unimplemented!()
}
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.) | // We need to make the strings owned to construct the `Options` instance. | random_line_split |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn | () {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
// We need to make the strings owned to construct the `Options` instance.
let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() {
unimplemented!()
}
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.)
| sort_array | identifier_name |
regions-trait-1.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.
#![feature(box_syntax)]
struct ctxt { v: uint }
trait get_ctxt {
// Here the `&` is bound in the method definition:
fn get_ctxt(&self) -> &ctxt;
}
struct | <'a> { c: &'a ctxt }
impl<'a> get_ctxt for has_ctxt<'a> {
// Here an error occurs because we used `&self` but
// the definition used `&`:
fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
}
}
fn get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v
}
fn main() {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
assert_eq!(get_v(box hc as Box<get_ctxt>), 22u);
}
| has_ctxt | identifier_name |
regions-trait-1.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.
#![feature(box_syntax)]
struct ctxt { v: uint }
trait get_ctxt {
// Here the `&` is bound in the method definition:
fn get_ctxt(&self) -> &ctxt;
}
struct has_ctxt<'a> { c: &'a ctxt }
impl<'a> get_ctxt for has_ctxt<'a> {
// Here an error occurs because we used `&self` but
// the definition used `&`: |
}
fn get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v
}
fn main() {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
assert_eq!(get_v(box hc as Box<get_ctxt>), 22u);
} | fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
} | random_line_split |
filesearch.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(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
#[derive(Copy)]
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub search_paths: &'a SearchPaths,
pub triple: &'a str,
pub kind: PathKind,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path<F>(&self, mut f: F) where
F: FnMut(&Path) -> FileMatch,
{
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if!visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if!found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if!visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn search<F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p|!is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display()); | FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
search_paths: &'a SearchPaths,
kind: PathKind) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
search_paths: search_paths,
triple: triple,
kind: kind,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if!env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if!env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if!env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if!env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir!= "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
} | rslt = FileMatches;
} | random_line_split |
filesearch.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(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
#[derive(Copy)]
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub search_paths: &'a SearchPaths,
pub triple: &'a str,
pub kind: PathKind,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path<F>(&self, mut f: F) where
F: FnMut(&Path) -> FileMatch,
| }
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if!found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if!visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn search<F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p|!is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display());
rslt = FileMatches;
}
FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
search_paths: &'a SearchPaths,
kind: PathKind) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
search_paths: search_paths,
triple: triple,
kind: kind,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if!env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if!env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if!env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if!env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir!= "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
}
| {
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if !visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
} | identifier_body |
filesearch.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(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
#[derive(Copy)]
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub search_paths: &'a SearchPaths,
pub triple: &'a str,
pub kind: PathKind,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path<F>(&self, mut f: F) where
F: FnMut(&Path) -> FileMatch,
{
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if!visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if!found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if!visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn | <F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p|!is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display());
rslt = FileMatches;
}
FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
search_paths: &'a SearchPaths,
kind: PathKind) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
search_paths: search_paths,
triple: triple,
kind: kind,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if!env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if!env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if!env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if!env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir!= "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
}
| search | identifier_name |
mod.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provide methods to generate, read, write or validate keysets.
mod binary_io;
pub use binary_io::*;
mod handle;
pub use handle::*;
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
mod json_io;
#[cfg(feature = "json")]
pub use json_io::*; | pub use reader::*;
mod validation;
pub use validation::*;
mod writer;
pub use writer::*;
#[cfg(feature = "insecure")]
#[cfg_attr(docsrs, doc(cfg(feature = "insecure")))]
pub mod insecure; | mod manager;
pub use manager::*;
mod mem_io;
pub use mem_io::*;
mod reader; | random_line_split |
os.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.
// FIXME: move various extern bindings from here into liblibc or
// something similar |
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR,..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
}
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0,..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0]!= -1 && fds[0]!= 0);
assert!(fds[1]!= -1 && fds[1]!= 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
} | random_line_split |
|
os.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.
// FIXME: move various extern bindings from here into liblibc or
// something similar
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR,..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
}
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> | {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0, ..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0] != -1 && fds[0] != 0);
assert!(fds[1] != -1 && fds[1] != 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
} | identifier_body |
|
os.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.
// FIXME: move various extern bindings from here into liblibc or
// something similar
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR,..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 |
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0,..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0]!= -1 && fds[0]!= 0);
assert!(fds[1]!= -1 && fds[1]!= 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
}
| {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
} | conditional_block |
os.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.
// FIXME: move various extern bindings from here into liblibc or
// something similar
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn | () -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR,..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
}
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0,..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0]!= -1 && fds[0]!= 0);
assert!(fds[1]!= -1 && fds[1]!= 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
}
| errno | identifier_name |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&se | f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
}
}
#[derive(Debug)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
fn main() {
for city in [
City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
City { name: "Oslo", lat: 59.95, lon: 10.75 },
City { name: "Vancouver", lat: 49.25, lon: -123.1 },
].iter() {
println!("{}", *city);
}
for color in [
Color { red: 128, green: 255, blue: 90 },
Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté
// le trait fmt::Display.
println!("{:?}", *color)
}
} | lf, | identifier_name |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
}
}
#[derive(Debug)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
fn main() {
for city in [
City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
City { name: "Oslo", lat: 59.95, lon: 10.75 },
City { name: "Vancouver", lat: 49.25, lon: -123.1 },
].iter() {
println!("{}", *city);
}
for color in [
Color { red: 128, green: 255, blue: 90 }, | // le trait fmt::Display.
println!("{:?}", *color)
}
} | Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté | random_line_split |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' } | let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
}
}
#[derive(Debug)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
fn main() {
for city in [
City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
City { name: "Oslo", lat: 59.95, lon: 10.75 },
City { name: "Vancouver", lat: 49.25, lon: -123.1 },
].iter() {
println!("{}", *city);
}
for color in [
Color { red: 128, green: 255, blue: 90 },
Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté
// le trait fmt::Display.
println!("{:?}", *color)
}
} | ;
| conditional_block |
gtest_attribute.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
/// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked
/// into a C++ binary that invokes Gtest.
///
/// The `gtest` macro takes two arguments, which are Rust identifiers. The first is the name of the
/// test suite and the second is the name of the test, each of which are converted to a string and
/// given to Gtest. The name of the test function itself does not matter, and need not be unique
/// (it's placed into a unique module based on the Gtest suite + test names.
///
/// The test function must have no arguments. The return value must be either `()` or
/// `std::result::Result<(), E>`. If another return type is found, the test will fail when run. If
/// the return type is a `Result`, then an `Err` is treated as a test failure.
///
/// # Examples
/// ```
/// #[gtest(MathTest, Addition)]
/// fn my_test() {
/// expect_eq!(1 + 1, 2);
/// }
/// ```
///
/// The above adds the function to the Gtest binary as `MathTest.Addtition`:
/// ```
/// [ RUN ] MathTest.Addition
/// [ OK ] MathTest.Addition (0 ms)
/// ```
///
/// A test with a Result return type, and which uses the `?` operator. It will fail if the test
/// returns an `Err`, and print the resulting error string:
/// ```
/// #[gtest(ResultTest, CheckThingWithResult)]
/// fn my_test() -> std::result::Result<(), String> {
/// call_thing_with_result()?;
/// }
/// ```
#[proc_macro_attribute]
pub fn gtest(arg_stream: TokenStream, input: TokenStream) -> TokenStream {
enum GtestAttributeArgument {
TestSuite,
TestName,
}
// Returns a string representation of an identifier argument to the attribute. For example, for
// #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1.
// If the argument is not a Rust identifier or not present, it returns a compiler error as a
// TokenStream to be emitted.
fn get_arg_string(
args: &syn::AttributeArgs,
which: GtestAttributeArgument,
) -> Result<String, TokenStream> {
let pos = match which {
GtestAttributeArgument::TestSuite => 0,
GtestAttributeArgument::TestName => 1,
};
match &args[pos] {
syn::NestedMeta::Meta(syn::Meta::Path(path)) if path.segments.len() == 1 => {
Ok(path.segments[0].ident.to_string())
}
_ => {
let error_stream = match which {
GtestAttributeArgument::TestSuite => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test suite name, written as an identifier."
);
}
}
GtestAttributeArgument::TestName => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test name, written as an identifier."
);
}
}
};
Err(error_stream.into())
}
}
}
let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs);
let input_fn = syn::parse_macro_input!(input as syn::ItemFn);
if let Some(asyncness) = input_fn.sig.asyncness {
// TODO(crbug.com/1288947): We can support async functions once we have block_on() support
// which will run a RunLoop until the async test completes. The run_test_fn just needs to be
// generated to `block_on(|| #test_fn)` instead of calling `#test_fn` synchronously.
return quote_spanned! {
asyncness.span =>
compile_error!("async functions are not supported.");
}
.into();
}
let (test_suite_name, test_name) = match args.len() {
2 => {
let suite = match get_arg_string(&args, GtestAttributeArgument::TestSuite) {
Ok(ok) => ok,
Err(error_stream) => return error_stream,
};
let test = match get_arg_string(&args, GtestAttributeArgument::TestName) {
Ok(ok) => ok,
Err(error_stream) => return error_stream,
};
(suite, test)
}
0 | 1 => {
return quote! {
compile_error!(
"Expected two arguments. For example: #[gtest(TestSuite, TestName)].");
}
.into();
}
x => {
return quote_spanned! {
args[x.min(2)].span() =>
compile_error!(
"Expected two arguments. For example: #[gtest(TestSuite, TestName)].");
}
.into();
}
};
// We put the test function and all the code we generate around it into a submodule which is
// uniquely named for the super module based on the Gtest suite and test names. A result of this
// is that if two tests have the same test suite + name, a compiler error would report the
// conflict.
let test_mod = format_ident!("__test_{}_{}", test_suite_name, test_name);
// The run_test_fn identifier is marked #[no_mangle] to work around a codegen bug where the
// function is seen as dead and the compiler omits it from the object files. Since it's
// #[no_mangle], the identifier must be globally unique or we have an ODR violation. To produce
// a unique identifier, we roll our own name mangling by combining the file name and path from
// the source tree root with the Gtest suite and test names and the function itself.
//
// Note that an adversary could still produce a bug here by placing two equal Gtest suite and
// names in a single.rs file but in separate inline submodules.
//
// TODO(danakj): Build a repro and file upstream bug to refer to.
let mangled_function_name = |f: &syn::ItemFn| -> syn::Ident {
let file_name = file!().replace(|c: char|!c.is_ascii_alphanumeric(), "_"); | let test_fn = &input_fn.sig.ident;
// Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String
// literal. It is represented as an array of type std::os::raw::c_char which can be either
// signed or unsigned depending on the platform, and it can be passed directly to C++. This
// differs from byte strings and CStr which work with `u8`.
//
// TODO(crbug.com/1298175): Would it make sense to write a c_str_literal!() macro that takes a
// Rust string literal and produces a null-terminated array of `c_char`? Then you could write
// `c_str_literal!(file!())` for example, or implement a `file_c_str!()` in this way. Explore
// using https://crates.io/crates/cstr.
//
// TODO(danakj): Write unit tests for this, and consider pulling this out into its own crate,
// if we don't replace it with c_str_literal!() or the "cstr" crate.
struct CStringLiteral<'a>(&'a str);
impl quote::ToTokens for CStringLiteral<'_> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let mut c_chars = self.0.chars().map(|c| c as std::os::raw::c_char).collect::<Vec<_>>();
c_chars.push(0);
// Verify there's no embedded nulls as that would be invalid if the literal were put in
// a std::ffi::CString.
assert_eq!(c_chars.iter().filter(|x| **x == 0).count(), 1);
let comment = format!("\"{}\" as [c_char]", self.0);
tokens.extend(quote! {
{
#[doc=#comment]
&[#(#c_chars as std::os::raw::c_char),*]
}
});
}
}
// C-compatible string literals, that can be inserted into the quote! macro.
let test_suite_name_c_bytes = CStringLiteral(&test_suite_name);
let test_name_c_bytes = CStringLiteral(&test_name);
let file_c_bytes = CStringLiteral(file!());
let output = quote! {
mod #test_mod {
use super::*;
use std::error::Error;
use std::fmt::Display;
use std::result::Result;
#[::rust_gtest_interop::small_ctor::ctor]
unsafe fn register_test() {
let r = ::rust_gtest_interop::__private::TestRegistration {
func: #run_test_fn,
test_suite_name: #test_suite_name_c_bytes,
test_name: #test_name_c_bytes,
file: #file_c_bytes,
line: line!(),
};
::rust_gtest_interop::__private::register_test(r);
}
// The function is extern "C" so `register_test()` can pass this fn as a pointer to C++
// where it's registered with gtest.
//
// TODO(crbug.com/1296284): Removing #[no_mangle] makes rustc drop the symbol for the
// test function in the generated rlib which produces linker errors. If we resolve the
// linked bug and emit real object files from rustc for linking, then all the required
// symbols are present and `#[no_mangle]` should go away along with the custom-mangling
// of `run_test_fn`. We can not use `pub` to resolve this unfortunately. When `#[used]`
// is fixed in https://github.com/rust-lang/rust/issues/47384, this may also be
// resolved as well.
#[no_mangle]
extern "C" fn #run_test_fn() {
let catch_result = std::panic::catch_unwind(|| #test_fn());
use ::rust_gtest_interop::TestResult;
let err_message: Option<String> = match catch_result {
Ok(fn_result) => TestResult::into_error_message(fn_result),
Err(_) => Some("Test panicked".to_string()),
};
if let Some(m) = err_message.as_ref() {
::rust_gtest_interop::__private::add_failure_at(file!(), line!(), &m);
}
}
#input_fn
}
};
output.into()
} | format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident)
};
let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn));
// The identifier of the function which contains the body of the test. | random_line_split |
gtest_attribute.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
/// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked
/// into a C++ binary that invokes Gtest.
///
/// The `gtest` macro takes two arguments, which are Rust identifiers. The first is the name of the
/// test suite and the second is the name of the test, each of which are converted to a string and
/// given to Gtest. The name of the test function itself does not matter, and need not be unique
/// (it's placed into a unique module based on the Gtest suite + test names.
///
/// The test function must have no arguments. The return value must be either `()` or
/// `std::result::Result<(), E>`. If another return type is found, the test will fail when run. If
/// the return type is a `Result`, then an `Err` is treated as a test failure.
///
/// # Examples
/// ```
/// #[gtest(MathTest, Addition)]
/// fn my_test() {
/// expect_eq!(1 + 1, 2);
/// }
/// ```
///
/// The above adds the function to the Gtest binary as `MathTest.Addtition`:
/// ```
/// [ RUN ] MathTest.Addition
/// [ OK ] MathTest.Addition (0 ms)
/// ```
///
/// A test with a Result return type, and which uses the `?` operator. It will fail if the test
/// returns an `Err`, and print the resulting error string:
/// ```
/// #[gtest(ResultTest, CheckThingWithResult)]
/// fn my_test() -> std::result::Result<(), String> {
/// call_thing_with_result()?;
/// }
/// ```
#[proc_macro_attribute]
pub fn gtest(arg_stream: TokenStream, input: TokenStream) -> TokenStream {
enum | {
TestSuite,
TestName,
}
// Returns a string representation of an identifier argument to the attribute. For example, for
// #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1.
// If the argument is not a Rust identifier or not present, it returns a compiler error as a
// TokenStream to be emitted.
fn get_arg_string(
args: &syn::AttributeArgs,
which: GtestAttributeArgument,
) -> Result<String, TokenStream> {
let pos = match which {
GtestAttributeArgument::TestSuite => 0,
GtestAttributeArgument::TestName => 1,
};
match &args[pos] {
syn::NestedMeta::Meta(syn::Meta::Path(path)) if path.segments.len() == 1 => {
Ok(path.segments[0].ident.to_string())
}
_ => {
let error_stream = match which {
GtestAttributeArgument::TestSuite => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test suite name, written as an identifier."
);
}
}
GtestAttributeArgument::TestName => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test name, written as an identifier."
);
}
}
};
Err(error_stream.into())
}
}
}
let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs);
let input_fn = syn::parse_macro_input!(input as syn::ItemFn);
if let Some(asyncness) = input_fn.sig.asyncness {
// TODO(crbug.com/1288947): We can support async functions once we have block_on() support
// which will run a RunLoop until the async test completes. The run_test_fn just needs to be
// generated to `block_on(|| #test_fn)` instead of calling `#test_fn` synchronously.
return quote_spanned! {
asyncness.span =>
compile_error!("async functions are not supported.");
}
.into();
}
let (test_suite_name, test_name) = match args.len() {
2 => {
let suite = match get_arg_string(&args, GtestAttributeArgument::TestSuite) {
Ok(ok) => ok,
Err(error_stream) => return error_stream,
};
let test = match get_arg_string(&args, GtestAttributeArgument::TestName) {
Ok(ok) => ok,
Err(error_stream) => return error_stream,
};
(suite, test)
}
0 | 1 => {
return quote! {
compile_error!(
"Expected two arguments. For example: #[gtest(TestSuite, TestName)].");
}
.into();
}
x => {
return quote_spanned! {
args[x.min(2)].span() =>
compile_error!(
"Expected two arguments. For example: #[gtest(TestSuite, TestName)].");
}
.into();
}
};
// We put the test function and all the code we generate around it into a submodule which is
// uniquely named for the super module based on the Gtest suite and test names. A result of this
// is that if two tests have the same test suite + name, a compiler error would report the
// conflict.
let test_mod = format_ident!("__test_{}_{}", test_suite_name, test_name);
// The run_test_fn identifier is marked #[no_mangle] to work around a codegen bug where the
// function is seen as dead and the compiler omits it from the object files. Since it's
// #[no_mangle], the identifier must be globally unique or we have an ODR violation. To produce
// a unique identifier, we roll our own name mangling by combining the file name and path from
// the source tree root with the Gtest suite and test names and the function itself.
//
// Note that an adversary could still produce a bug here by placing two equal Gtest suite and
// names in a single.rs file but in separate inline submodules.
//
// TODO(danakj): Build a repro and file upstream bug to refer to.
let mangled_function_name = |f: &syn::ItemFn| -> syn::Ident {
let file_name = file!().replace(|c: char|!c.is_ascii_alphanumeric(), "_");
format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident)
};
let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn));
// The identifier of the function which contains the body of the test.
let test_fn = &input_fn.sig.ident;
// Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String
// literal. It is represented as an array of type std::os::raw::c_char which can be either
// signed or unsigned depending on the platform, and it can be passed directly to C++. This
// differs from byte strings and CStr which work with `u8`.
//
// TODO(crbug.com/1298175): Would it make sense to write a c_str_literal!() macro that takes a
// Rust string literal and produces a null-terminated array of `c_char`? Then you could write
// `c_str_literal!(file!())` for example, or implement a `file_c_str!()` in this way. Explore
// using https://crates.io/crates/cstr.
//
// TODO(danakj): Write unit tests for this, and consider pulling this out into its own crate,
// if we don't replace it with c_str_literal!() or the "cstr" crate.
struct CStringLiteral<'a>(&'a str);
impl quote::ToTokens for CStringLiteral<'_> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let mut c_chars = self.0.chars().map(|c| c as std::os::raw::c_char).collect::<Vec<_>>();
c_chars.push(0);
// Verify there's no embedded nulls as that would be invalid if the literal were put in
// a std::ffi::CString.
assert_eq!(c_chars.iter().filter(|x| **x == 0).count(), 1);
let comment = format!("\"{}\" as [c_char]", self.0);
tokens.extend(quote! {
{
#[doc=#comment]
&[#(#c_chars as std::os::raw::c_char),*]
}
});
}
}
// C-compatible string literals, that can be inserted into the quote! macro.
let test_suite_name_c_bytes = CStringLiteral(&test_suite_name);
let test_name_c_bytes = CStringLiteral(&test_name);
let file_c_bytes = CStringLiteral(file!());
let output = quote! {
mod #test_mod {
use super::*;
use std::error::Error;
use std::fmt::Display;
use std::result::Result;
#[::rust_gtest_interop::small_ctor::ctor]
unsafe fn register_test() {
let r = ::rust_gtest_interop::__private::TestRegistration {
func: #run_test_fn,
test_suite_name: #test_suite_name_c_bytes,
test_name: #test_name_c_bytes,
file: #file_c_bytes,
line: line!(),
};
::rust_gtest_interop::__private::register_test(r);
}
// The function is extern "C" so `register_test()` can pass this fn as a pointer to C++
// where it's registered with gtest.
//
// TODO(crbug.com/1296284): Removing #[no_mangle] makes rustc drop the symbol for the
// test function in the generated rlib which produces linker errors. If we resolve the
// linked bug and emit real object files from rustc for linking, then all the required
// symbols are present and `#[no_mangle]` should go away along with the custom-mangling
// of `run_test_fn`. We can not use `pub` to resolve this unfortunately. When `#[used]`
// is fixed in https://github.com/rust-lang/rust/issues/47384, this may also be
// resolved as well.
#[no_mangle]
extern "C" fn #run_test_fn() {
let catch_result = std::panic::catch_unwind(|| #test_fn());
use ::rust_gtest_interop::TestResult;
let err_message: Option<String> = match catch_result {
Ok(fn_result) => TestResult::into_error_message(fn_result),
Err(_) => Some("Test panicked".to_string()),
};
if let Some(m) = err_message.as_ref() {
::rust_gtest_interop::__private::add_failure_at(file!(), line!(), &m);
}
}
#input_fn
}
};
output.into()
}
| GtestAttributeArgument | identifier_name |
gtest_attribute.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
/// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked
/// into a C++ binary that invokes Gtest.
///
/// The `gtest` macro takes two arguments, which are Rust identifiers. The first is the name of the
/// test suite and the second is the name of the test, each of which are converted to a string and
/// given to Gtest. The name of the test function itself does not matter, and need not be unique
/// (it's placed into a unique module based on the Gtest suite + test names.
///
/// The test function must have no arguments. The return value must be either `()` or
/// `std::result::Result<(), E>`. If another return type is found, the test will fail when run. If
/// the return type is a `Result`, then an `Err` is treated as a test failure.
///
/// # Examples
/// ```
/// #[gtest(MathTest, Addition)]
/// fn my_test() {
/// expect_eq!(1 + 1, 2);
/// }
/// ```
///
/// The above adds the function to the Gtest binary as `MathTest.Addtition`:
/// ```
/// [ RUN ] MathTest.Addition
/// [ OK ] MathTest.Addition (0 ms)
/// ```
///
/// A test with a Result return type, and which uses the `?` operator. It will fail if the test
/// returns an `Err`, and print the resulting error string:
/// ```
/// #[gtest(ResultTest, CheckThingWithResult)]
/// fn my_test() -> std::result::Result<(), String> {
/// call_thing_with_result()?;
/// }
/// ```
#[proc_macro_attribute]
pub fn gtest(arg_stream: TokenStream, input: TokenStream) -> TokenStream {
enum GtestAttributeArgument {
TestSuite,
TestName,
}
// Returns a string representation of an identifier argument to the attribute. For example, for
// #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1.
// If the argument is not a Rust identifier or not present, it returns a compiler error as a
// TokenStream to be emitted.
fn get_arg_string(
args: &syn::AttributeArgs,
which: GtestAttributeArgument,
) -> Result<String, TokenStream> {
let pos = match which {
GtestAttributeArgument::TestSuite => 0,
GtestAttributeArgument::TestName => 1,
};
match &args[pos] {
syn::NestedMeta::Meta(syn::Meta::Path(path)) if path.segments.len() == 1 => {
Ok(path.segments[0].ident.to_string())
}
_ => | }
}
}
let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs);
let input_fn = syn::parse_macro_input!(input as syn::ItemFn);
if let Some(asyncness) = input_fn.sig.asyncness {
// TODO(crbug.com/1288947): We can support async functions once we have block_on() support
// which will run a RunLoop until the async test completes. The run_test_fn just needs to be
// generated to `block_on(|| #test_fn)` instead of calling `#test_fn` synchronously.
return quote_spanned! {
asyncness.span =>
compile_error!("async functions are not supported.");
}
.into();
}
let (test_suite_name, test_name) = match args.len() {
2 => {
let suite = match get_arg_string(&args, GtestAttributeArgument::TestSuite) {
Ok(ok) => ok,
Err(error_stream) => return error_stream,
};
let test = match get_arg_string(&args, GtestAttributeArgument::TestName) {
Ok(ok) => ok,
Err(error_stream) => return error_stream,
};
(suite, test)
}
0 | 1 => {
return quote! {
compile_error!(
"Expected two arguments. For example: #[gtest(TestSuite, TestName)].");
}
.into();
}
x => {
return quote_spanned! {
args[x.min(2)].span() =>
compile_error!(
"Expected two arguments. For example: #[gtest(TestSuite, TestName)].");
}
.into();
}
};
// We put the test function and all the code we generate around it into a submodule which is
// uniquely named for the super module based on the Gtest suite and test names. A result of this
// is that if two tests have the same test suite + name, a compiler error would report the
// conflict.
let test_mod = format_ident!("__test_{}_{}", test_suite_name, test_name);
// The run_test_fn identifier is marked #[no_mangle] to work around a codegen bug where the
// function is seen as dead and the compiler omits it from the object files. Since it's
// #[no_mangle], the identifier must be globally unique or we have an ODR violation. To produce
// a unique identifier, we roll our own name mangling by combining the file name and path from
// the source tree root with the Gtest suite and test names and the function itself.
//
// Note that an adversary could still produce a bug here by placing two equal Gtest suite and
// names in a single.rs file but in separate inline submodules.
//
// TODO(danakj): Build a repro and file upstream bug to refer to.
let mangled_function_name = |f: &syn::ItemFn| -> syn::Ident {
let file_name = file!().replace(|c: char|!c.is_ascii_alphanumeric(), "_");
format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident)
};
let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn));
// The identifier of the function which contains the body of the test.
let test_fn = &input_fn.sig.ident;
// Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String
// literal. It is represented as an array of type std::os::raw::c_char which can be either
// signed or unsigned depending on the platform, and it can be passed directly to C++. This
// differs from byte strings and CStr which work with `u8`.
//
// TODO(crbug.com/1298175): Would it make sense to write a c_str_literal!() macro that takes a
// Rust string literal and produces a null-terminated array of `c_char`? Then you could write
// `c_str_literal!(file!())` for example, or implement a `file_c_str!()` in this way. Explore
// using https://crates.io/crates/cstr.
//
// TODO(danakj): Write unit tests for this, and consider pulling this out into its own crate,
// if we don't replace it with c_str_literal!() or the "cstr" crate.
struct CStringLiteral<'a>(&'a str);
impl quote::ToTokens for CStringLiteral<'_> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let mut c_chars = self.0.chars().map(|c| c as std::os::raw::c_char).collect::<Vec<_>>();
c_chars.push(0);
// Verify there's no embedded nulls as that would be invalid if the literal were put in
// a std::ffi::CString.
assert_eq!(c_chars.iter().filter(|x| **x == 0).count(), 1);
let comment = format!("\"{}\" as [c_char]", self.0);
tokens.extend(quote! {
{
#[doc=#comment]
&[#(#c_chars as std::os::raw::c_char),*]
}
});
}
}
// C-compatible string literals, that can be inserted into the quote! macro.
let test_suite_name_c_bytes = CStringLiteral(&test_suite_name);
let test_name_c_bytes = CStringLiteral(&test_name);
let file_c_bytes = CStringLiteral(file!());
let output = quote! {
mod #test_mod {
use super::*;
use std::error::Error;
use std::fmt::Display;
use std::result::Result;
#[::rust_gtest_interop::small_ctor::ctor]
unsafe fn register_test() {
let r = ::rust_gtest_interop::__private::TestRegistration {
func: #run_test_fn,
test_suite_name: #test_suite_name_c_bytes,
test_name: #test_name_c_bytes,
file: #file_c_bytes,
line: line!(),
};
::rust_gtest_interop::__private::register_test(r);
}
// The function is extern "C" so `register_test()` can pass this fn as a pointer to C++
// where it's registered with gtest.
//
// TODO(crbug.com/1296284): Removing #[no_mangle] makes rustc drop the symbol for the
// test function in the generated rlib which produces linker errors. If we resolve the
// linked bug and emit real object files from rustc for linking, then all the required
// symbols are present and `#[no_mangle]` should go away along with the custom-mangling
// of `run_test_fn`. We can not use `pub` to resolve this unfortunately. When `#[used]`
// is fixed in https://github.com/rust-lang/rust/issues/47384, this may also be
// resolved as well.
#[no_mangle]
extern "C" fn #run_test_fn() {
let catch_result = std::panic::catch_unwind(|| #test_fn());
use ::rust_gtest_interop::TestResult;
let err_message: Option<String> = match catch_result {
Ok(fn_result) => TestResult::into_error_message(fn_result),
Err(_) => Some("Test panicked".to_string()),
};
if let Some(m) = err_message.as_ref() {
::rust_gtest_interop::__private::add_failure_at(file!(), line!(), &m);
}
}
#input_fn
}
};
output.into()
}
| {
let error_stream = match which {
GtestAttributeArgument::TestSuite => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test suite name, written as an identifier."
);
}
}
GtestAttributeArgument::TestName => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test name, written as an identifier."
);
}
}
};
Err(error_stream.into()) | conditional_block |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
// 左边没有,只有上面的元素
arr[j] = arr[j] + grid[i][j];
} else {
// 有左边和上边
arr[j] = arr[j].min(arr[j - 1]) + grid[i][j];
}
}
}
arr[n - 1] | }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
} | } | random_line_split |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn | (grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
// 左边没有,只有上面的元素
arr[j] = arr[j] + grid[i][j];
} else {
// 有左边和上边
arr[j] = arr[j].min(arr[j - 1]) + grid[i][j];
}
}
}
arr[n - 1]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
}
| min_path_sum | identifier_name |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 | arr[n - 1]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
}
| {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
// 左边没有,只有上面的元素
arr[j] = arr[j] + grid[i][j];
} else {
// 有左边和上边
arr[j] = arr[j].min(arr[j - 1]) + grid[i][j];
}
}
}
| identifier_body |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() |
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
// 左边没有,只有上面的元素
arr[j] = arr[j] + grid[i][j];
} else {
// 有左边和上边
arr[j] = arr[j].min(arr[j - 1]) + grid[i][j];
}
}
}
arr[n - 1]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
}
| {
return 0;
} | conditional_block |
issue-59494.rs | fn | <A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
move |a: A| -> C { f(g(a)) }
}
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ga)
}
}
fn main() {
let f = |(_, _)| {};
let g = |(a, _)| a;
let t7 = |env| |a| |b| t7p(f, g)(((env, a), b));
let t8 = t8n(t7, t7p(f, g));
//~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)>
}
| t7p | identifier_name |
issue-59494.rs | fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C |
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ga)
}
}
fn main() {
let f = |(_, _)| {};
let g = |(a, _)| a;
let t7 = |env| |a| |b| t7p(f, g)(((env, a), b));
let t8 = t8n(t7, t7p(f, g));
//~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)>
}
| {
move |a: A| -> C { f(g(a)) }
} | identifier_body |
issue-59494.rs | fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
move |a: A| -> C { f(g(a)) }
}
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ga)
}
}
fn main() { | let g = |(a, _)| a;
let t7 = |env| |a| |b| t7p(f, g)(((env, a), b));
let t8 = t8n(t7, t7p(f, g));
//~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)>
} | let f = |(_, _)| {}; | random_line_split |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use log::debug;
#[derive(Debug)]
struct Node<T> {
v: T,
left: NodePtr<T>,
right: NodePtr<T>,
}
type NodePtr<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
pub struct BinarySearchTree<T> {
root: NodePtr<T>,
}
impl<T> Node<T> {
fn new(v: T) -> NodePtr<T> {
Some(Box::new(Self {
v,
left: None,
right: None,
}))
}
}
impl<T> BinarySearchTree<T> {
pub fn new() -> Self {
Self { root: None }
}
fn find_slot(&mut self, v: &T) -> &mut NodePtr<T>
where
T: Ord,
{
let mut current = &mut self.root;
while current.is_some() {
if ¤t.as_ref().unwrap().v == v {
break;
}
use std::cmp::Ordering;
let inner = current.as_mut().unwrap();
match v.cmp(&inner.v) {
Ordering::Less => current = &mut inner.left,
Ordering::Greater => current = &mut inner.right,
Ordering::Equal => unreachable!(),
}
}
current
}
pub fn insert(&mut self, v: T)
where
T: Ord,
{
let slot = self.find_slot(&v);
if slot.is_none() {
*slot = Node::new(v);
}
}
pub fn contains(&self, v: &T) -> bool
where
T: Ord + std::fmt::Debug,
{
let mut current = &self.root;
while let Some(inner) = current {
debug!("Stepping through {:?}", inner.v);
use std::cmp::Ordering;
match v.cmp(&inner.v) {
Ordering::Less => current = &inner.left,
Ordering::Greater => current = &inner.right,
Ordering::Equal => return true,
}
}
false
}
}
impl<T: Ord> std::iter::FromIterator<T> for BinarySearchTree<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut tree = BinarySearchTree::default();
tree.extend(iter);
tree
}
}
impl<T> Default for BinarySearchTree<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Ord> std::iter::Extend<T> for BinarySearchTree<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for i in iter {
self.insert(i);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test] | let mut x = BinarySearchTree::new();
x.insert(5);
x.insert(6);
assert!(x.contains(&5));
assert!(x.contains(&6));
assert!(!x.contains(&7));
}
#[test]
fn test_structure() {
let mut x = BinarySearchTree::new();
x.insert(10);
x.insert(15);
x.insert(17);
x.insert(13);
x.insert(5);
assert!(x.root.as_ref().unwrap().v == 10);
assert!(x.root.as_ref().unwrap().left.as_ref().unwrap().v == 5);
assert!(x.root.as_ref().unwrap().right.as_ref().unwrap().v == 15);
assert!(
x.root
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.left
.as_ref()
.unwrap()
.v
== 13
);
assert!(
x.root
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.v
== 17
);
}
} | fn test_insert_contains() { | random_line_split |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use log::debug;
#[derive(Debug)]
struct | <T> {
v: T,
left: NodePtr<T>,
right: NodePtr<T>,
}
type NodePtr<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
pub struct BinarySearchTree<T> {
root: NodePtr<T>,
}
impl<T> Node<T> {
fn new(v: T) -> NodePtr<T> {
Some(Box::new(Self {
v,
left: None,
right: None,
}))
}
}
impl<T> BinarySearchTree<T> {
pub fn new() -> Self {
Self { root: None }
}
fn find_slot(&mut self, v: &T) -> &mut NodePtr<T>
where
T: Ord,
{
let mut current = &mut self.root;
while current.is_some() {
if ¤t.as_ref().unwrap().v == v {
break;
}
use std::cmp::Ordering;
let inner = current.as_mut().unwrap();
match v.cmp(&inner.v) {
Ordering::Less => current = &mut inner.left,
Ordering::Greater => current = &mut inner.right,
Ordering::Equal => unreachable!(),
}
}
current
}
pub fn insert(&mut self, v: T)
where
T: Ord,
{
let slot = self.find_slot(&v);
if slot.is_none() {
*slot = Node::new(v);
}
}
pub fn contains(&self, v: &T) -> bool
where
T: Ord + std::fmt::Debug,
{
let mut current = &self.root;
while let Some(inner) = current {
debug!("Stepping through {:?}", inner.v);
use std::cmp::Ordering;
match v.cmp(&inner.v) {
Ordering::Less => current = &inner.left,
Ordering::Greater => current = &inner.right,
Ordering::Equal => return true,
}
}
false
}
}
impl<T: Ord> std::iter::FromIterator<T> for BinarySearchTree<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut tree = BinarySearchTree::default();
tree.extend(iter);
tree
}
}
impl<T> Default for BinarySearchTree<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Ord> std::iter::Extend<T> for BinarySearchTree<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for i in iter {
self.insert(i);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_insert_contains() {
let mut x = BinarySearchTree::new();
x.insert(5);
x.insert(6);
assert!(x.contains(&5));
assert!(x.contains(&6));
assert!(!x.contains(&7));
}
#[test]
fn test_structure() {
let mut x = BinarySearchTree::new();
x.insert(10);
x.insert(15);
x.insert(17);
x.insert(13);
x.insert(5);
assert!(x.root.as_ref().unwrap().v == 10);
assert!(x.root.as_ref().unwrap().left.as_ref().unwrap().v == 5);
assert!(x.root.as_ref().unwrap().right.as_ref().unwrap().v == 15);
assert!(
x.root
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.left
.as_ref()
.unwrap()
.v
== 13
);
assert!(
x.root
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.v
== 17
);
}
}
| Node | identifier_name |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use log::debug;
#[derive(Debug)]
struct Node<T> {
v: T,
left: NodePtr<T>,
right: NodePtr<T>,
}
type NodePtr<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
pub struct BinarySearchTree<T> {
root: NodePtr<T>,
}
impl<T> Node<T> {
fn new(v: T) -> NodePtr<T> {
Some(Box::new(Self {
v,
left: None,
right: None,
}))
}
}
impl<T> BinarySearchTree<T> {
pub fn new() -> Self {
Self { root: None }
}
fn find_slot(&mut self, v: &T) -> &mut NodePtr<T>
where
T: Ord,
|
pub fn insert(&mut self, v: T)
where
T: Ord,
{
let slot = self.find_slot(&v);
if slot.is_none() {
*slot = Node::new(v);
}
}
pub fn contains(&self, v: &T) -> bool
where
T: Ord + std::fmt::Debug,
{
let mut current = &self.root;
while let Some(inner) = current {
debug!("Stepping through {:?}", inner.v);
use std::cmp::Ordering;
match v.cmp(&inner.v) {
Ordering::Less => current = &inner.left,
Ordering::Greater => current = &inner.right,
Ordering::Equal => return true,
}
}
false
}
}
impl<T: Ord> std::iter::FromIterator<T> for BinarySearchTree<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut tree = BinarySearchTree::default();
tree.extend(iter);
tree
}
}
impl<T> Default for BinarySearchTree<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Ord> std::iter::Extend<T> for BinarySearchTree<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for i in iter {
self.insert(i);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_insert_contains() {
let mut x = BinarySearchTree::new();
x.insert(5);
x.insert(6);
assert!(x.contains(&5));
assert!(x.contains(&6));
assert!(!x.contains(&7));
}
#[test]
fn test_structure() {
let mut x = BinarySearchTree::new();
x.insert(10);
x.insert(15);
x.insert(17);
x.insert(13);
x.insert(5);
assert!(x.root.as_ref().unwrap().v == 10);
assert!(x.root.as_ref().unwrap().left.as_ref().unwrap().v == 5);
assert!(x.root.as_ref().unwrap().right.as_ref().unwrap().v == 15);
assert!(
x.root
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.left
.as_ref()
.unwrap()
.v
== 13
);
assert!(
x.root
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.right
.as_ref()
.unwrap()
.v
== 17
);
}
}
| {
let mut current = &mut self.root;
while current.is_some() {
if ¤t.as_ref().unwrap().v == v {
break;
}
use std::cmp::Ordering;
let inner = current.as_mut().unwrap();
match v.cmp(&inner.v) {
Ordering::Less => current = &mut inner.left,
Ordering::Greater => current = &mut inner.right,
Ordering::Equal => unreachable!(),
}
}
current
} | identifier_body |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io};
use log::Record;
use crate::stratis::{StratisError, StratisResult};
fn serialize_pairs(pairs: HashMap<String, String>) -> String |
/// Notify systemd that a daemon has started.
#[allow(clippy::implicit_hasher)]
pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> {
let serialized_pairs = serialize_pairs(key_value_pairs);
let cstring = CString::new(serialized_pairs)?;
let ret = unsafe { bindings::sd_notify(libc::c_int::from(unset_variable), cstring.as_ptr()) };
if ret < 0 {
Err(StratisError::Io(io::Error::from_raw_os_error(-ret)))
} else {
Ok(())
}
}
/// Send a message to the system log generated from the Rust log crate Record input.
pub fn syslog(record: &Record<'_>) {
let cstring = match CString::new(record.args().to_string()) {
Ok(s) => s,
Err(_) => return,
};
unsafe { bindings::syslog(record.level() as libc::c_int, cstring.as_ptr()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_key_value_pair_serialization() {
let mut hash_map = HashMap::new();
hash_map.insert("READY".to_string(), "1".to_string());
assert_eq!("READY=1\n".to_string(), serialize_pairs(hash_map));
}
}
| {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();
string += "\n";
string
})
} | identifier_body |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io}; | use log::Record;
use crate::stratis::{StratisError, StratisResult};
fn serialize_pairs(pairs: HashMap<String, String>) -> String {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();
string += "\n";
string
})
}
/// Notify systemd that a daemon has started.
#[allow(clippy::implicit_hasher)]
pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> {
let serialized_pairs = serialize_pairs(key_value_pairs);
let cstring = CString::new(serialized_pairs)?;
let ret = unsafe { bindings::sd_notify(libc::c_int::from(unset_variable), cstring.as_ptr()) };
if ret < 0 {
Err(StratisError::Io(io::Error::from_raw_os_error(-ret)))
} else {
Ok(())
}
}
/// Send a message to the system log generated from the Rust log crate Record input.
pub fn syslog(record: &Record<'_>) {
let cstring = match CString::new(record.args().to_string()) {
Ok(s) => s,
Err(_) => return,
};
unsafe { bindings::syslog(record.level() as libc::c_int, cstring.as_ptr()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_key_value_pair_serialization() {
let mut hash_map = HashMap::new();
hash_map.insert("READY".to_string(), "1".to_string());
assert_eq!("READY=1\n".to_string(), serialize_pairs(hash_map));
}
} | random_line_split |
|
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io};
use log::Record;
use crate::stratis::{StratisError, StratisResult};
fn | (pairs: HashMap<String, String>) -> String {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();
string += "\n";
string
})
}
/// Notify systemd that a daemon has started.
#[allow(clippy::implicit_hasher)]
pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> {
let serialized_pairs = serialize_pairs(key_value_pairs);
let cstring = CString::new(serialized_pairs)?;
let ret = unsafe { bindings::sd_notify(libc::c_int::from(unset_variable), cstring.as_ptr()) };
if ret < 0 {
Err(StratisError::Io(io::Error::from_raw_os_error(-ret)))
} else {
Ok(())
}
}
/// Send a message to the system log generated from the Rust log crate Record input.
pub fn syslog(record: &Record<'_>) {
let cstring = match CString::new(record.args().to_string()) {
Ok(s) => s,
Err(_) => return,
};
unsafe { bindings::syslog(record.level() as libc::c_int, cstring.as_ptr()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_key_value_pair_serialization() {
let mut hash_map = HashMap::new();
hash_map.insert("READY".to_string(), "1".to_string());
assert_eq!("READY=1\n".to_string(), serialize_pairs(hash_map));
}
}
| serialize_pairs | identifier_name |
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::ImageCache;
use profile_traits::mem::ReportsChan;
use rpc::LayoutRPC;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg};
use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use script_traits::Painter;
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;
use servo_channel::{Receiver, Sender};
use servo_url::ServoUrl;
use std::sync::Arc;
use style::context::QuirksMode;
use style::properties::PropertyId;
use style::selector_parser::PseudoElement;
use style::stylesheets::Stylesheet;
/// Asynchronous messages that script can send to layout.
pub enum Msg {
/// Adds the given stylesheet to the document. The second stylesheet is the
/// insertion point (if it exists, the sheet needs to be inserted before
/// it).
AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>),
/// Removes a stylesheet from the document.
RemoveStylesheet(ServoArc<Stylesheet>),
/// Change the quirks mode.
SetQuirksMode(QuirksMode),
/// Requests a reflow.
Reflow(ScriptReflow),
/// Get an RPC interface.
GetRPC(Sender<Box<LayoutRPC + Send>>),
/// Requests that the layout thread render the next frame of all animations.
TickAnimations,
/// Updates layout's timer for animation testing from script.
///
/// The inner field is the number of *milliseconds* to advance, and the bool
/// field is whether animations should be force-ticked.
AdvanceClockMs(i32, bool),
/// Destroys layout data associated with a DOM node.
///
/// TODO(pcwalton): Maybe think about batching to avoid message traffic.
ReapStyleAndLayoutData(OpaqueStyleAndLayoutData),
/// Requests that the layout thread measure its memory usage. The resulting reports are sent back
/// via the supplied channel.
CollectReports(ReportsChan),
/// Requests that the layout thread enter a quiescent state in which no more messages are
/// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
/// this happens.
PrepareToExit(Sender<()>),
/// Requests that the layout thread immediately shut down. There must be no more nodes left after
/// this, or layout will crash.
ExitNow,
/// Get the last epoch counter for this layout thread.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending;
/// false otherwise).
GetWebFontLoadState(IpcSender<bool>),
/// Creates a new layout thread.
///
/// This basically exists to keep the script-layout dependency one-way.
CreateLayoutThread(NewLayoutThreadInfo),
/// Set the final Url.
SetFinalUrl(ServoUrl),
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Tells layout about a single new scrolling offset from the script. The rest will
/// remain untouched and layout won't forward this back to script.
UpdateScrollStateFromScript(ScrollState),
/// Tells layout that script has added some paint worklet modules.
RegisterPaint(Atom, Vec<Atom>, Box<Painter>),
/// Send to layout the precise time when the navigation started.
SetNavigationStart(u64),
}
#[derive(Debug, PartialEq)]
pub enum NodesFromPointQueryType {
All,
Topmost,
}
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(TrustedNodeAddress),
ContentBoxesQuery(TrustedNodeAddress),
NodeScrollIdQuery(TrustedNodeAddress),
NodeGeometryQuery(TrustedNodeAddress),
NodeScrollGeometryQuery(TrustedNodeAddress),
ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId),
OffsetParentQuery(TrustedNodeAddress),
StyleQuery(TrustedNodeAddress),
TextIndexQuery(TrustedNodeAddress, Point2D<f32>),
NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType),
ElementInnerTextQuery(TrustedNodeAddress),
}
/// Any query to perform with this reflow.
#[derive(Debug, PartialEq)]
pub enum ReflowGoal {
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
pub fn needs_display_list(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => true,
&QueryMsg::ContentBoxQuery(_) |
&QueryMsg::ContentBoxesQuery(_) |
&QueryMsg::NodeGeometryQuery(_) |
&QueryMsg::NodeScrollGeometryQuery(_) |
&QueryMsg::NodeScrollIdQuery(_) |
&QueryMsg::ResolvedStyleQuery(..) |
&QueryMsg::OffsetParentQuery(_) |
&QueryMsg::StyleQuery(_) => false,
},
}
}
/// Returns true if the given ReflowQuery needs its display list send to WebRender or
/// false if a layout_thread display list is sufficient.
pub fn needs_display(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => true,
&QueryMsg::ContentBoxQuery(_) |
&QueryMsg::ContentBoxesQuery(_) |
&QueryMsg::NodeGeometryQuery(_) |
&QueryMsg::NodeScrollGeometryQuery(_) |
&QueryMsg::NodeScrollIdQuery(_) |
&QueryMsg::ResolvedStyleQuery(..) |
&QueryMsg::OffsetParentQuery(_) |
&QueryMsg::StyleQuery(_) => false,
},
}
}
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComplete {
/// The list of images that were encountered that are in progress.
pub pending_images: Vec<PendingImage>,
/// The list of nodes that initiated a CSS transition.
pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>,
}
/// Information needed for a script-initiated reflow.
pub struct ScriptReflow {
/// General reflow data.
pub reflow_info: Reflow,
/// The document node.
pub document: TrustedNodeAddress,
/// Whether the document's stylesheets have changed since the last script reflow.
pub stylesheets_changed: bool,
/// The current window size.
pub window_size: WindowSizeData,
/// The channel that we send a notification to.
pub script_join_chan: Sender<ReflowComplete>,
/// The goal of this reflow.
pub reflow_goal: ReflowGoal,
/// The number of objects in the dom #10110
pub dom_count: u32,
}
pub struct | {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<ImageCache>,
pub content_process_shutdown_chan: Option<IpcSender<()>>,
pub layout_threads: usize,
pub paint_time_metrics: PaintTimeMetrics,
}
| NewLayoutThreadInfo | identifier_name |
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::ImageCache;
use profile_traits::mem::ReportsChan;
use rpc::LayoutRPC;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; | use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use script_traits::Painter;
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;
use servo_channel::{Receiver, Sender};
use servo_url::ServoUrl;
use std::sync::Arc;
use style::context::QuirksMode;
use style::properties::PropertyId;
use style::selector_parser::PseudoElement;
use style::stylesheets::Stylesheet;
/// Asynchronous messages that script can send to layout.
pub enum Msg {
/// Adds the given stylesheet to the document. The second stylesheet is the
/// insertion point (if it exists, the sheet needs to be inserted before
/// it).
AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>),
/// Removes a stylesheet from the document.
RemoveStylesheet(ServoArc<Stylesheet>),
/// Change the quirks mode.
SetQuirksMode(QuirksMode),
/// Requests a reflow.
Reflow(ScriptReflow),
/// Get an RPC interface.
GetRPC(Sender<Box<LayoutRPC + Send>>),
/// Requests that the layout thread render the next frame of all animations.
TickAnimations,
/// Updates layout's timer for animation testing from script.
///
/// The inner field is the number of *milliseconds* to advance, and the bool
/// field is whether animations should be force-ticked.
AdvanceClockMs(i32, bool),
/// Destroys layout data associated with a DOM node.
///
/// TODO(pcwalton): Maybe think about batching to avoid message traffic.
ReapStyleAndLayoutData(OpaqueStyleAndLayoutData),
/// Requests that the layout thread measure its memory usage. The resulting reports are sent back
/// via the supplied channel.
CollectReports(ReportsChan),
/// Requests that the layout thread enter a quiescent state in which no more messages are
/// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
/// this happens.
PrepareToExit(Sender<()>),
/// Requests that the layout thread immediately shut down. There must be no more nodes left after
/// this, or layout will crash.
ExitNow,
/// Get the last epoch counter for this layout thread.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending;
/// false otherwise).
GetWebFontLoadState(IpcSender<bool>),
/// Creates a new layout thread.
///
/// This basically exists to keep the script-layout dependency one-way.
CreateLayoutThread(NewLayoutThreadInfo),
/// Set the final Url.
SetFinalUrl(ServoUrl),
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Tells layout about a single new scrolling offset from the script. The rest will
/// remain untouched and layout won't forward this back to script.
UpdateScrollStateFromScript(ScrollState),
/// Tells layout that script has added some paint worklet modules.
RegisterPaint(Atom, Vec<Atom>, Box<Painter>),
/// Send to layout the precise time when the navigation started.
SetNavigationStart(u64),
}
#[derive(Debug, PartialEq)]
pub enum NodesFromPointQueryType {
All,
Topmost,
}
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(TrustedNodeAddress),
ContentBoxesQuery(TrustedNodeAddress),
NodeScrollIdQuery(TrustedNodeAddress),
NodeGeometryQuery(TrustedNodeAddress),
NodeScrollGeometryQuery(TrustedNodeAddress),
ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId),
OffsetParentQuery(TrustedNodeAddress),
StyleQuery(TrustedNodeAddress),
TextIndexQuery(TrustedNodeAddress, Point2D<f32>),
NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType),
ElementInnerTextQuery(TrustedNodeAddress),
}
/// Any query to perform with this reflow.
#[derive(Debug, PartialEq)]
pub enum ReflowGoal {
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
pub fn needs_display_list(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => true,
&QueryMsg::ContentBoxQuery(_) |
&QueryMsg::ContentBoxesQuery(_) |
&QueryMsg::NodeGeometryQuery(_) |
&QueryMsg::NodeScrollGeometryQuery(_) |
&QueryMsg::NodeScrollIdQuery(_) |
&QueryMsg::ResolvedStyleQuery(..) |
&QueryMsg::OffsetParentQuery(_) |
&QueryMsg::StyleQuery(_) => false,
},
}
}
/// Returns true if the given ReflowQuery needs its display list send to WebRender or
/// false if a layout_thread display list is sufficient.
pub fn needs_display(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => true,
&QueryMsg::ContentBoxQuery(_) |
&QueryMsg::ContentBoxesQuery(_) |
&QueryMsg::NodeGeometryQuery(_) |
&QueryMsg::NodeScrollGeometryQuery(_) |
&QueryMsg::NodeScrollIdQuery(_) |
&QueryMsg::ResolvedStyleQuery(..) |
&QueryMsg::OffsetParentQuery(_) |
&QueryMsg::StyleQuery(_) => false,
},
}
}
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComplete {
/// The list of images that were encountered that are in progress.
pub pending_images: Vec<PendingImage>,
/// The list of nodes that initiated a CSS transition.
pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>,
}
/// Information needed for a script-initiated reflow.
pub struct ScriptReflow {
/// General reflow data.
pub reflow_info: Reflow,
/// The document node.
pub document: TrustedNodeAddress,
/// Whether the document's stylesheets have changed since the last script reflow.
pub stylesheets_changed: bool,
/// The current window size.
pub window_size: WindowSizeData,
/// The channel that we send a notification to.
pub script_join_chan: Sender<ReflowComplete>,
/// The goal of this reflow.
pub reflow_goal: ReflowGoal,
/// The number of objects in the dom #10110
pub dom_count: u32,
}
pub struct NewLayoutThreadInfo {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<ImageCache>,
pub content_process_shutdown_chan: Option<IpcSender<()>>,
pub layout_threads: usize,
pub paint_time_metrics: PaintTimeMetrics,
} | random_line_split |
|
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::ImageCache;
use profile_traits::mem::ReportsChan;
use rpc::LayoutRPC;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg};
use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use script_traits::Painter;
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;
use servo_channel::{Receiver, Sender};
use servo_url::ServoUrl;
use std::sync::Arc;
use style::context::QuirksMode;
use style::properties::PropertyId;
use style::selector_parser::PseudoElement;
use style::stylesheets::Stylesheet;
/// Asynchronous messages that script can send to layout.
pub enum Msg {
/// Adds the given stylesheet to the document. The second stylesheet is the
/// insertion point (if it exists, the sheet needs to be inserted before
/// it).
AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>),
/// Removes a stylesheet from the document.
RemoveStylesheet(ServoArc<Stylesheet>),
/// Change the quirks mode.
SetQuirksMode(QuirksMode),
/// Requests a reflow.
Reflow(ScriptReflow),
/// Get an RPC interface.
GetRPC(Sender<Box<LayoutRPC + Send>>),
/// Requests that the layout thread render the next frame of all animations.
TickAnimations,
/// Updates layout's timer for animation testing from script.
///
/// The inner field is the number of *milliseconds* to advance, and the bool
/// field is whether animations should be force-ticked.
AdvanceClockMs(i32, bool),
/// Destroys layout data associated with a DOM node.
///
/// TODO(pcwalton): Maybe think about batching to avoid message traffic.
ReapStyleAndLayoutData(OpaqueStyleAndLayoutData),
/// Requests that the layout thread measure its memory usage. The resulting reports are sent back
/// via the supplied channel.
CollectReports(ReportsChan),
/// Requests that the layout thread enter a quiescent state in which no more messages are
/// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
/// this happens.
PrepareToExit(Sender<()>),
/// Requests that the layout thread immediately shut down. There must be no more nodes left after
/// this, or layout will crash.
ExitNow,
/// Get the last epoch counter for this layout thread.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending;
/// false otherwise).
GetWebFontLoadState(IpcSender<bool>),
/// Creates a new layout thread.
///
/// This basically exists to keep the script-layout dependency one-way.
CreateLayoutThread(NewLayoutThreadInfo),
/// Set the final Url.
SetFinalUrl(ServoUrl),
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Tells layout about a single new scrolling offset from the script. The rest will
/// remain untouched and layout won't forward this back to script.
UpdateScrollStateFromScript(ScrollState),
/// Tells layout that script has added some paint worklet modules.
RegisterPaint(Atom, Vec<Atom>, Box<Painter>),
/// Send to layout the precise time when the navigation started.
SetNavigationStart(u64),
}
#[derive(Debug, PartialEq)]
pub enum NodesFromPointQueryType {
All,
Topmost,
}
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(TrustedNodeAddress),
ContentBoxesQuery(TrustedNodeAddress),
NodeScrollIdQuery(TrustedNodeAddress),
NodeGeometryQuery(TrustedNodeAddress),
NodeScrollGeometryQuery(TrustedNodeAddress),
ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId),
OffsetParentQuery(TrustedNodeAddress),
StyleQuery(TrustedNodeAddress),
TextIndexQuery(TrustedNodeAddress, Point2D<f32>),
NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType),
ElementInnerTextQuery(TrustedNodeAddress),
}
/// Any query to perform with this reflow.
#[derive(Debug, PartialEq)]
pub enum ReflowGoal {
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
pub fn needs_display_list(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => true,
&QueryMsg::ContentBoxQuery(_) |
&QueryMsg::ContentBoxesQuery(_) |
&QueryMsg::NodeGeometryQuery(_) |
&QueryMsg::NodeScrollGeometryQuery(_) |
&QueryMsg::NodeScrollIdQuery(_) |
&QueryMsg::ResolvedStyleQuery(..) |
&QueryMsg::OffsetParentQuery(_) |
&QueryMsg::StyleQuery(_) => false,
},
}
}
/// Returns true if the given ReflowQuery needs its display list send to WebRender or
/// false if a layout_thread display list is sufficient.
pub fn needs_display(&self) -> bool |
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComplete {
/// The list of images that were encountered that are in progress.
pub pending_images: Vec<PendingImage>,
/// The list of nodes that initiated a CSS transition.
pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>,
}
/// Information needed for a script-initiated reflow.
pub struct ScriptReflow {
/// General reflow data.
pub reflow_info: Reflow,
/// The document node.
pub document: TrustedNodeAddress,
/// Whether the document's stylesheets have changed since the last script reflow.
pub stylesheets_changed: bool,
/// The current window size.
pub window_size: WindowSizeData,
/// The channel that we send a notification to.
pub script_join_chan: Sender<ReflowComplete>,
/// The goal of this reflow.
pub reflow_goal: ReflowGoal,
/// The number of objects in the dom #10110
pub dom_count: u32,
}
pub struct NewLayoutThreadInfo {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<ImageCache>,
pub content_process_shutdown_chan: Option<IpcSender<()>>,
pub layout_threads: usize,
pub paint_time_metrics: PaintTimeMetrics,
}
| {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => true,
&QueryMsg::ContentBoxQuery(_) |
&QueryMsg::ContentBoxesQuery(_) |
&QueryMsg::NodeGeometryQuery(_) |
&QueryMsg::NodeScrollGeometryQuery(_) |
&QueryMsg::NodeScrollIdQuery(_) |
&QueryMsg::ResolvedStyleQuery(..) |
&QueryMsg::OffsetParentQuery(_) |
&QueryMsg::StyleQuery(_) => false,
},
}
} | identifier_body |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;
use builder::{Builder, TokenString, add_node_dependency};
use node;
use super::pinmap;
pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
for port_node in node.subnodes().iter() {
port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(&node, port_node);
for pin_node in port_node.subnodes().iter() {
pin_node.materializer.set(Some(build_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(port_node, pin_node);
super::add_node_dependency_on_clock(builder, pin_node);
}
}
}
pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
node.expect_no_attributes(cx);
}
fn build_pin(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
let port_node = node.parent.clone().unwrap().upgrade().unwrap();
let ref port_path = port_node.path;
let port_str = format!("Port{}", match port_path.as_str().parse::<usize>().unwrap() {
0...4 => port_path,
other => {
cx.parse_sess().span_diagnostic.span_err(port_node.path_span,
format!("unknown port `{}`, allowed values: 0...4",
other).as_str());
return;
}
});
let port = TokenString(port_str);
if node.name.is_none() {
cx.parse_sess().span_diagnostic.span_err(node.name_span,
"pin node must have a name");
return;
}
let direction_str = if node.get_string_attr("function").is_some() {
"core::option::Option::None"
} else {
match node.get_string_attr("direction").unwrap().as_str() {
"out" => "core::option::Option::Some(zinc::hal::pin::Out)",
"in" => "core::option::Option::Some(zinc::hal::pin::In)",
other => {
let attr = node.get_attr("direction");
cx.parse_sess().span_diagnostic.span_err(attr.value_span,
format!("unknown direction `{}`, allowed values: `in`, `out`",
other).as_str());
return;
}
}
};
let direction = TokenString(direction_str.to_string());
let pin_str = match node.path.as_str().parse::<usize>().unwrap() {
0...31 => &node.path,
other => {
cx.parse_sess().span_diagnostic.span_err(node.path_span,
format!("unknown pin `{}`, allowed values: 0...31",
other).as_str());
return;
}
};
let port_def = pinmap::port_def();
let function_str = match node.get_string_attr("function") {
None => "Gpio".to_string(),
Some(fun) => {
let pins = &port_def[port_path];
let maybe_pin_index: usize = node.path.as_str().parse().unwrap();
let maybe_pin: &Option<pinmap::PinDef> = pins.get(maybe_pin_index).unwrap();
match maybe_pin {
&None => {
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span,
format!("unknown pin function `{}`, only GPIO avaliable on this pin",
fun).as_str());
return;
}
&Some(ref pin_funcs) => {
let maybe_func = pin_funcs.get(&fun); | format!("unknown pin function `{}`, allowed functions: {}",
fun, avaliable.join(", ")).as_str());
return;
},
Some(func_idx) => {
format!("AltFunction{}", func_idx)
}
}
}
}
}
};
let function = TokenString(function_str);
let pin = TokenString(format!("{}u8", pin_str));
let pin_name = TokenString(node.name.clone().unwrap());
node.set_type_name("zinc::hal::lpc43xx::pin::Pin".to_string());
let st = quote_stmt!(&*cx,
let $pin_name = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::$port,
$pin,
zinc::hal::lpc43xx::pin::Function::$function,
$direction);
).unwrap();
builder.add_main_statement(st);
}
#[cfg(test)]
mod test {
use builder::Builder;
use test_helpers::{assert_equal_source, with_parsed};
#[test]
fn builds_input_gpio() {
with_parsed("
gpio {
0 {
p1@1 { direction = \"in\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p1").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p1 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
1u8,
zinc::hal::lpc43xx::pin::Function::Gpio,
core::option::Option::Some(zinc::hal::pin::In));");
});
}
#[test]
fn builds_output_gpio() {
with_parsed("
gpio {
0 {
p2@2 { direction = \"out\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p2 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
2u8,
zinc::hal::lpc43xx::pin::Function::Gpio,
core::option::Option::Some(zinc::hal::pin::Out));");
});
}
#[test]
fn builds_altfn_gpio() {
with_parsed("
gpio {
0 {
p3@3 { direction = \"out\"; function = \"ad0_6\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p3 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
3u8,
zinc::hal::lpc43xx::pin::Function::AltFunction2,
core::option::Option::None);");
});
}
} | match maybe_func {
None => {
let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect();
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span, | random_line_split |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;
use builder::{Builder, TokenString, add_node_dependency};
use node;
use super::pinmap;
pub fn | (builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
for port_node in node.subnodes().iter() {
port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(&node, port_node);
for pin_node in port_node.subnodes().iter() {
pin_node.materializer.set(Some(build_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(port_node, pin_node);
super::add_node_dependency_on_clock(builder, pin_node);
}
}
}
pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
node.expect_no_attributes(cx);
}
fn build_pin(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
let port_node = node.parent.clone().unwrap().upgrade().unwrap();
let ref port_path = port_node.path;
let port_str = format!("Port{}", match port_path.as_str().parse::<usize>().unwrap() {
0...4 => port_path,
other => {
cx.parse_sess().span_diagnostic.span_err(port_node.path_span,
format!("unknown port `{}`, allowed values: 0...4",
other).as_str());
return;
}
});
let port = TokenString(port_str);
if node.name.is_none() {
cx.parse_sess().span_diagnostic.span_err(node.name_span,
"pin node must have a name");
return;
}
let direction_str = if node.get_string_attr("function").is_some() {
"core::option::Option::None"
} else {
match node.get_string_attr("direction").unwrap().as_str() {
"out" => "core::option::Option::Some(zinc::hal::pin::Out)",
"in" => "core::option::Option::Some(zinc::hal::pin::In)",
other => {
let attr = node.get_attr("direction");
cx.parse_sess().span_diagnostic.span_err(attr.value_span,
format!("unknown direction `{}`, allowed values: `in`, `out`",
other).as_str());
return;
}
}
};
let direction = TokenString(direction_str.to_string());
let pin_str = match node.path.as_str().parse::<usize>().unwrap() {
0...31 => &node.path,
other => {
cx.parse_sess().span_diagnostic.span_err(node.path_span,
format!("unknown pin `{}`, allowed values: 0...31",
other).as_str());
return;
}
};
let port_def = pinmap::port_def();
let function_str = match node.get_string_attr("function") {
None => "Gpio".to_string(),
Some(fun) => {
let pins = &port_def[port_path];
let maybe_pin_index: usize = node.path.as_str().parse().unwrap();
let maybe_pin: &Option<pinmap::PinDef> = pins.get(maybe_pin_index).unwrap();
match maybe_pin {
&None => {
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span,
format!("unknown pin function `{}`, only GPIO avaliable on this pin",
fun).as_str());
return;
}
&Some(ref pin_funcs) => {
let maybe_func = pin_funcs.get(&fun);
match maybe_func {
None => {
let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect();
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span,
format!("unknown pin function `{}`, allowed functions: {}",
fun, avaliable.join(", ")).as_str());
return;
},
Some(func_idx) => {
format!("AltFunction{}", func_idx)
}
}
}
}
}
};
let function = TokenString(function_str);
let pin = TokenString(format!("{}u8", pin_str));
let pin_name = TokenString(node.name.clone().unwrap());
node.set_type_name("zinc::hal::lpc43xx::pin::Pin".to_string());
let st = quote_stmt!(&*cx,
let $pin_name = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::$port,
$pin,
zinc::hal::lpc43xx::pin::Function::$function,
$direction);
).unwrap();
builder.add_main_statement(st);
}
#[cfg(test)]
mod test {
use builder::Builder;
use test_helpers::{assert_equal_source, with_parsed};
#[test]
fn builds_input_gpio() {
with_parsed("
gpio {
0 {
p1@1 { direction = \"in\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p1").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p1 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
1u8,
zinc::hal::lpc43xx::pin::Function::Gpio,
core::option::Option::Some(zinc::hal::pin::In));");
});
}
#[test]
fn builds_output_gpio() {
with_parsed("
gpio {
0 {
p2@2 { direction = \"out\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p2 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
2u8,
zinc::hal::lpc43xx::pin::Function::Gpio,
core::option::Option::Some(zinc::hal::pin::Out));");
});
}
#[test]
fn builds_altfn_gpio() {
with_parsed("
gpio {
0 {
p3@3 { direction = \"out\"; function = \"ad0_6\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p3 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
3u8,
zinc::hal::lpc43xx::pin::Function::AltFunction2,
core::option::Option::None);");
});
}
}
| attach | identifier_name |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;
use builder::{Builder, TokenString, add_node_dependency};
use node;
use super::pinmap;
pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
for port_node in node.subnodes().iter() {
port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(&node, port_node);
for pin_node in port_node.subnodes().iter() {
pin_node.materializer.set(Some(build_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(port_node, pin_node);
super::add_node_dependency_on_clock(builder, pin_node);
}
}
}
pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
node.expect_no_attributes(cx);
}
fn build_pin(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
let port_node = node.parent.clone().unwrap().upgrade().unwrap();
let ref port_path = port_node.path;
let port_str = format!("Port{}", match port_path.as_str().parse::<usize>().unwrap() {
0...4 => port_path,
other => {
cx.parse_sess().span_diagnostic.span_err(port_node.path_span,
format!("unknown port `{}`, allowed values: 0...4",
other).as_str());
return;
}
});
let port = TokenString(port_str);
if node.name.is_none() {
cx.parse_sess().span_diagnostic.span_err(node.name_span,
"pin node must have a name");
return;
}
let direction_str = if node.get_string_attr("function").is_some() {
"core::option::Option::None"
} else {
match node.get_string_attr("direction").unwrap().as_str() {
"out" => "core::option::Option::Some(zinc::hal::pin::Out)",
"in" => "core::option::Option::Some(zinc::hal::pin::In)",
other => {
let attr = node.get_attr("direction");
cx.parse_sess().span_diagnostic.span_err(attr.value_span,
format!("unknown direction `{}`, allowed values: `in`, `out`",
other).as_str());
return;
}
}
};
let direction = TokenString(direction_str.to_string());
let pin_str = match node.path.as_str().parse::<usize>().unwrap() {
0...31 => &node.path,
other => {
cx.parse_sess().span_diagnostic.span_err(node.path_span,
format!("unknown pin `{}`, allowed values: 0...31",
other).as_str());
return;
}
};
let port_def = pinmap::port_def();
let function_str = match node.get_string_attr("function") {
None => "Gpio".to_string(),
Some(fun) => {
let pins = &port_def[port_path];
let maybe_pin_index: usize = node.path.as_str().parse().unwrap();
let maybe_pin: &Option<pinmap::PinDef> = pins.get(maybe_pin_index).unwrap();
match maybe_pin {
&None => {
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span,
format!("unknown pin function `{}`, only GPIO avaliable on this pin",
fun).as_str());
return;
}
&Some(ref pin_funcs) => {
let maybe_func = pin_funcs.get(&fun);
match maybe_func {
None => {
let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect();
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span,
format!("unknown pin function `{}`, allowed functions: {}",
fun, avaliable.join(", ")).as_str());
return;
},
Some(func_idx) => {
format!("AltFunction{}", func_idx)
}
}
}
}
}
};
let function = TokenString(function_str);
let pin = TokenString(format!("{}u8", pin_str));
let pin_name = TokenString(node.name.clone().unwrap());
node.set_type_name("zinc::hal::lpc43xx::pin::Pin".to_string());
let st = quote_stmt!(&*cx,
let $pin_name = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::$port,
$pin,
zinc::hal::lpc43xx::pin::Function::$function,
$direction);
).unwrap();
builder.add_main_statement(st);
}
#[cfg(test)]
mod test {
use builder::Builder;
use test_helpers::{assert_equal_source, with_parsed};
#[test]
fn builds_input_gpio() {
with_parsed("
gpio {
0 {
p1@1 { direction = \"in\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p1").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p1 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
1u8,
zinc::hal::lpc43xx::pin::Function::Gpio,
core::option::Option::Some(zinc::hal::pin::In));");
});
}
#[test]
fn builds_output_gpio() |
#[test]
fn builds_altfn_gpio() {
with_parsed("
gpio {
0 {
p3@3 { direction = \"out\"; function = \"ad0_6\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p3 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
3u8,
zinc::hal::lpc43xx::pin::Function::AltFunction2,
core::option::Option::None);");
});
}
}
| {
with_parsed("
gpio {
0 {
p2@2 { direction = \"out\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(&builder.main_stmts()[0],
"let p2 = zinc::hal::lpc43xx::pin::Pin::new(
zinc::hal::lpc43xx::pin::Port::Port0,
2u8,
zinc::hal::lpc43xx::pin::Function::Gpio,
core::option::Option::Some(zinc::hal::pin::Out));");
});
} | identifier_body |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! View onto transaction rlp
use util::{U256, Bytes, Hashable, H256};
use rlp::{Rlp, View};
/// View onto transaction rlp.
pub struct TransactionView<'a> {
rlp: Rlp<'a>
}
impl<'a> TransactionView<'a> {
/// Creates new view onto block from raw bytes.
pub fn new(bytes: &'a [u8]) -> TransactionView<'a> |
/// Creates new view onto block from rlp.
pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> {
TransactionView {
rlp: rlp
}
}
/// Return reference to underlaying rlp.
pub fn rlp(&self) -> &Rlp<'a> {
&self.rlp
}
/// Get the nonce field of the transaction.
pub fn nonce(&self) -> U256 { self.rlp.val_at(0) }
/// Get the gas_price field of the transaction.
pub fn gas_price(&self) -> U256 { self.rlp.val_at(1) }
/// Get the gas field of the transaction.
pub fn gas(&self) -> U256 { self.rlp.val_at(2) }
/// Get the value field of the transaction.
pub fn value(&self) -> U256 { self.rlp.val_at(4) }
/// Get the data field of the transaction.
pub fn data(&self) -> Bytes { self.rlp.val_at(5) }
/// Get the v field of the transaction.
pub fn v(&self) -> u8 { let r: u16 = self.rlp.val_at(6); r as u8 }
/// Get the r field of the transaction.
pub fn r(&self) -> U256 { self.rlp.val_at(7) }
/// Get the s field of the transaction.
pub fn s(&self) -> U256 { self.rlp.val_at(8) }
}
impl<'a> Hashable for TransactionView<'a> {
fn sha3(&self) -> H256 {
self.rlp.as_raw().sha3()
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use util::U256;
use super::TransactionView;
#[test]
fn test_transaction_view() {
let rlp = "f87c80018261a894095e7baea6a6c7c4c2dfeb977efac326af552d870a9d00000000000000000000000000000000000000000000000000000000001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804".from_hex().unwrap();
let view = TransactionView::new(&rlp);
assert_eq!(view.nonce(), U256::from(0));
assert_eq!(view.gas_price(), U256::from(1));
assert_eq!(view.gas(), U256::from(0x61a8));
assert_eq!(view.value(), U256::from(0xa));
assert_eq!(view.data(), "0000000000000000000000000000000000000000000000000000000000".from_hex().unwrap());
assert_eq!(view.r(), U256::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353").unwrap());
assert_eq!(view.s(), U256::from_str("efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap());
assert_eq!(view.v(), 0x1b);
}
}
| {
TransactionView {
rlp: Rlp::new(bytes)
}
} | identifier_body |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
| // 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/>.
//! View onto transaction rlp
use util::{U256, Bytes, Hashable, H256};
use rlp::{Rlp, View};
/// View onto transaction rlp.
pub struct TransactionView<'a> {
rlp: Rlp<'a>
}
impl<'a> TransactionView<'a> {
/// Creates new view onto block from raw bytes.
pub fn new(bytes: &'a [u8]) -> TransactionView<'a> {
TransactionView {
rlp: Rlp::new(bytes)
}
}
/// Creates new view onto block from rlp.
pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> {
TransactionView {
rlp: rlp
}
}
/// Return reference to underlaying rlp.
pub fn rlp(&self) -> &Rlp<'a> {
&self.rlp
}
/// Get the nonce field of the transaction.
pub fn nonce(&self) -> U256 { self.rlp.val_at(0) }
/// Get the gas_price field of the transaction.
pub fn gas_price(&self) -> U256 { self.rlp.val_at(1) }
/// Get the gas field of the transaction.
pub fn gas(&self) -> U256 { self.rlp.val_at(2) }
/// Get the value field of the transaction.
pub fn value(&self) -> U256 { self.rlp.val_at(4) }
/// Get the data field of the transaction.
pub fn data(&self) -> Bytes { self.rlp.val_at(5) }
/// Get the v field of the transaction.
pub fn v(&self) -> u8 { let r: u16 = self.rlp.val_at(6); r as u8 }
/// Get the r field of the transaction.
pub fn r(&self) -> U256 { self.rlp.val_at(7) }
/// Get the s field of the transaction.
pub fn s(&self) -> U256 { self.rlp.val_at(8) }
}
impl<'a> Hashable for TransactionView<'a> {
fn sha3(&self) -> H256 {
self.rlp.as_raw().sha3()
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use util::U256;
use super::TransactionView;
#[test]
fn test_transaction_view() {
let rlp = "f87c80018261a894095e7baea6a6c7c4c2dfeb977efac326af552d870a9d00000000000000000000000000000000000000000000000000000000001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804".from_hex().unwrap();
let view = TransactionView::new(&rlp);
assert_eq!(view.nonce(), U256::from(0));
assert_eq!(view.gas_price(), U256::from(1));
assert_eq!(view.gas(), U256::from(0x61a8));
assert_eq!(view.value(), U256::from(0xa));
assert_eq!(view.data(), "0000000000000000000000000000000000000000000000000000000000".from_hex().unwrap());
assert_eq!(view.r(), U256::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353").unwrap());
assert_eq!(view.s(), U256::from_str("efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap());
assert_eq!(view.v(), 0x1b);
}
} | // 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 | random_line_split |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! View onto transaction rlp
use util::{U256, Bytes, Hashable, H256};
use rlp::{Rlp, View};
/// View onto transaction rlp.
pub struct TransactionView<'a> {
rlp: Rlp<'a>
}
impl<'a> TransactionView<'a> {
/// Creates new view onto block from raw bytes.
pub fn | (bytes: &'a [u8]) -> TransactionView<'a> {
TransactionView {
rlp: Rlp::new(bytes)
}
}
/// Creates new view onto block from rlp.
pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> {
TransactionView {
rlp: rlp
}
}
/// Return reference to underlaying rlp.
pub fn rlp(&self) -> &Rlp<'a> {
&self.rlp
}
/// Get the nonce field of the transaction.
pub fn nonce(&self) -> U256 { self.rlp.val_at(0) }
/// Get the gas_price field of the transaction.
pub fn gas_price(&self) -> U256 { self.rlp.val_at(1) }
/// Get the gas field of the transaction.
pub fn gas(&self) -> U256 { self.rlp.val_at(2) }
/// Get the value field of the transaction.
pub fn value(&self) -> U256 { self.rlp.val_at(4) }
/// Get the data field of the transaction.
pub fn data(&self) -> Bytes { self.rlp.val_at(5) }
/// Get the v field of the transaction.
pub fn v(&self) -> u8 { let r: u16 = self.rlp.val_at(6); r as u8 }
/// Get the r field of the transaction.
pub fn r(&self) -> U256 { self.rlp.val_at(7) }
/// Get the s field of the transaction.
pub fn s(&self) -> U256 { self.rlp.val_at(8) }
}
impl<'a> Hashable for TransactionView<'a> {
fn sha3(&self) -> H256 {
self.rlp.as_raw().sha3()
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use util::U256;
use super::TransactionView;
#[test]
fn test_transaction_view() {
let rlp = "f87c80018261a894095e7baea6a6c7c4c2dfeb977efac326af552d870a9d00000000000000000000000000000000000000000000000000000000001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804".from_hex().unwrap();
let view = TransactionView::new(&rlp);
assert_eq!(view.nonce(), U256::from(0));
assert_eq!(view.gas_price(), U256::from(1));
assert_eq!(view.gas(), U256::from(0x61a8));
assert_eq!(view.value(), U256::from(0xa));
assert_eq!(view.data(), "0000000000000000000000000000000000000000000000000000000000".from_hex().unwrap());
assert_eq!(view.r(), U256::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353").unwrap());
assert_eq!(view.s(), U256::from_str("efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap());
assert_eq!(view.v(), 0x1b);
}
}
| new | identifier_name |
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct | {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10;
Some(ret)
}
}
}
}
#[derive(Copy, Clone)]
enum LuhnState { Even, Odd, }
fn digits(n: u64) -> Digits {
Digits{m: n}
}
fn luhn_test(n: u64) -> bool {
let odd_even = [LuhnState::Odd, LuhnState::Even];
let numbers = digits(n).zip(odd_even.iter().cycle().map(|&s| s));
let sum =
numbers.fold(0u64, |s, n| {
s +
match n {
(n, LuhnState::Odd) => n,
(n, LuhnState::Even) =>
digits(n * 2).fold(0, |s, n| s + n),
} });
sum % 10 == 0
}
#[cfg(not(test))]
fn main() {
let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670];
for n in &nos {
if luhn_test(*n) {
println!("{} passes.", n);
} else { println!("{} fails.", n); }
}
}
#[test]
fn test_inputs() {
assert!(luhn_test(49927398716));
assert!(!luhn_test(49927398717));
assert!(!luhn_test(1234567812345678));
assert!(luhn_test(1234567812345670));
}
| Digits | identifier_name |
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct Digits {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10;
Some(ret)
}
}
}
}
#[derive(Copy, Clone)]
enum LuhnState { Even, Odd, }
fn digits(n: u64) -> Digits {
Digits{m: n}
}
fn luhn_test(n: u64) -> bool {
let odd_even = [LuhnState::Odd, LuhnState::Even];
let numbers = digits(n).zip(odd_even.iter().cycle().map(|&s| s));
let sum =
numbers.fold(0u64, |s, n| {
s +
match n {
(n, LuhnState::Odd) => n,
(n, LuhnState::Even) =>
digits(n * 2).fold(0, |s, n| s + n),
} });
sum % 10 == 0
}
#[cfg(not(test))]
fn main() {
let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670];
for n in &nos {
if luhn_test(*n) {
println!("{} passes.", n);
} else { println!("{} fails.", n); }
}
}
#[test]
fn test_inputs() | {
assert!(luhn_test(49927398716));
assert!(!luhn_test(49927398717));
assert!(!luhn_test(1234567812345678));
assert!(luhn_test(1234567812345670));
} | identifier_body |
|
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct Digits {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10;
Some(ret)
}
}
}
}
#[derive(Copy, Clone)]
enum LuhnState { Even, Odd, }
fn digits(n: u64) -> Digits {
Digits{m: n}
}
fn luhn_test(n: u64) -> bool {
let odd_even = [LuhnState::Odd, LuhnState::Even];
let numbers = digits(n).zip(odd_even.iter().cycle().map(|&s| s));
let sum =
numbers.fold(0u64, |s, n| {
s +
match n {
(n, LuhnState::Odd) => n,
(n, LuhnState::Even) =>
digits(n * 2).fold(0, |s, n| s + n),
} });
sum % 10 == 0
}
#[cfg(not(test))]
fn main() {
let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670];
for n in &nos {
if luhn_test(*n) {
println!("{} passes.", n);
} else { println!("{} fails.", n); }
}
}
#[test] | assert!(!luhn_test(49927398717));
assert!(!luhn_test(1234567812345678));
assert!(luhn_test(1234567812345670));
} | fn test_inputs() {
assert!(luhn_test(49927398716)); | random_line_split |
mod.rs | //! Collectors will receive events from the contextual shard, check if the
//! filter lets them pass, and collects if the receive, collect, or time limits
//! are not reached yet.
use std::sync::Arc;
mod error;
pub use error::Error as CollectorError;
#[cfg(feature = "unstable_discord_api")]
pub mod component_interaction_collector;
pub mod event_collector;
pub mod message_collector;
pub mod reaction_collector;
#[cfg(feature = "unstable_discord_api")]
pub use component_interaction_collector::*;
pub use event_collector::*;
pub use message_collector::*;
pub use reaction_collector::*;
/// Wraps a &T and clones the value into an Arc<T> lazily. Used with collectors to allow inspecting | pub(crate) struct LazyArc<'a, T> {
value: &'a T,
arc: Option<Arc<T>>,
}
impl<'a, T: Clone> LazyArc<'a, T> {
pub fn new(value: &'a T) -> Self {
LazyArc {
value,
arc: None,
}
}
pub fn as_arc(&mut self) -> Arc<T> {
let value = self.value;
self.arc.get_or_insert_with(|| Arc::new(value.clone())).clone()
}
}
impl<'a, T> std::ops::Deref for LazyArc<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.value
}
} | /// the value in filters while only cloning values that actually match.
#[derive(Debug)] | random_line_split |
mod.rs | //! Collectors will receive events from the contextual shard, check if the
//! filter lets them pass, and collects if the receive, collect, or time limits
//! are not reached yet.
use std::sync::Arc;
mod error;
pub use error::Error as CollectorError;
#[cfg(feature = "unstable_discord_api")]
pub mod component_interaction_collector;
pub mod event_collector;
pub mod message_collector;
pub mod reaction_collector;
#[cfg(feature = "unstable_discord_api")]
pub use component_interaction_collector::*;
pub use event_collector::*;
pub use message_collector::*;
pub use reaction_collector::*;
/// Wraps a &T and clones the value into an Arc<T> lazily. Used with collectors to allow inspecting
/// the value in filters while only cloning values that actually match.
#[derive(Debug)]
pub(crate) struct LazyArc<'a, T> {
value: &'a T,
arc: Option<Arc<T>>,
}
impl<'a, T: Clone> LazyArc<'a, T> {
pub fn new(value: &'a T) -> Self {
LazyArc {
value,
arc: None,
}
}
pub fn as_arc(&mut self) -> Arc<T> {
let value = self.value;
self.arc.get_or_insert_with(|| Arc::new(value.clone())).clone()
}
}
impl<'a, T> std::ops::Deref for LazyArc<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target |
}
| {
self.value
} | identifier_body |
mod.rs | //! Collectors will receive events from the contextual shard, check if the
//! filter lets them pass, and collects if the receive, collect, or time limits
//! are not reached yet.
use std::sync::Arc;
mod error;
pub use error::Error as CollectorError;
#[cfg(feature = "unstable_discord_api")]
pub mod component_interaction_collector;
pub mod event_collector;
pub mod message_collector;
pub mod reaction_collector;
#[cfg(feature = "unstable_discord_api")]
pub use component_interaction_collector::*;
pub use event_collector::*;
pub use message_collector::*;
pub use reaction_collector::*;
/// Wraps a &T and clones the value into an Arc<T> lazily. Used with collectors to allow inspecting
/// the value in filters while only cloning values that actually match.
#[derive(Debug)]
pub(crate) struct LazyArc<'a, T> {
value: &'a T,
arc: Option<Arc<T>>,
}
impl<'a, T: Clone> LazyArc<'a, T> {
pub fn new(value: &'a T) -> Self {
LazyArc {
value,
arc: None,
}
}
pub fn | (&mut self) -> Arc<T> {
let value = self.value;
self.arc.get_or_insert_with(|| Arc::new(value.clone())).clone()
}
}
impl<'a, T> std::ops::Deref for LazyArc<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.value
}
}
| as_arc | identifier_name |
window_event.rs | #![allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Serialize, Deserialize)]
pub enum WindowEvent {
Pos(i32, i32),
Size(u32, u32),
Close,
Refresh,
Focus(bool),
Iconify(bool),
FramebufferSize(u32, u32),
MouseButton(MouseButton, Action, Modifiers),
CursorPos(f64, f64, Modifiers),
CursorEnter(bool),
Scroll(f64, f64, Modifiers),
Key(Key, Action, Modifiers),
Char(char),
CharModifiers(char, Modifiers),
Touch(u64, f64, f64, TouchAction, Modifiers),
}
use WindowEvent::*;
impl WindowEvent {
/// Tests if this event is related to the keyboard.
pub fn is_keyboard_event(&self) -> bool {
matches!(self, Key(..) | Char(..) | CharModifiers(..))
}
/// Tests if this event is related to the mouse.
pub fn | (&self) -> bool {
matches!(
self,
MouseButton(..) | CursorPos(..) | CursorEnter(..) | Scroll(..)
)
}
/// Tests if this event is related to the touch.
pub fn is_touch_event(&self) -> bool {
matches!(self, Touch(..))
}
}
// NOTE: list of keys inspired from glutin.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum Key {
Key1,
Key2,
Key3,
Key4,
Key5,
Key6,
Key7,
Key8,
Key9,
Key0,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
Escape,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
Snapshot,
Scroll,
Pause,
Insert,
Home,
Delete,
End,
PageDown,
PageUp,
Left,
Up,
Right,
Down,
Back,
Return,
Space,
Compose,
Caret,
Numlock,
Numpad0,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
AbntC1,
AbntC2,
Add,
Apostrophe,
Apps,
At,
Ax,
Backslash,
Calculator,
Capital,
Colon,
Comma,
Convert,
Decimal,
Divide,
Equals,
Grave,
Kana,
Kanji,
LAlt,
LBracket,
LControl,
LShift,
LWin,
Mail,
MediaSelect,
MediaStop,
Minus,
Multiply,
Mute,
MyComputer,
NavigateForward,
NavigateBackward,
NextTrack,
NoConvert,
NumpadComma,
NumpadEnter,
NumpadEquals,
OEM102,
Period,
PlayPause,
Power,
PrevTrack,
RAlt,
RBracket,
RControl,
RShift,
RWin,
Semicolon,
Slash,
Sleep,
Stop,
Subtract,
Sysrq,
Tab,
Underline,
Unlabeled,
VolumeDown,
VolumeUp,
Wake,
WebBack,
WebFavorites,
WebForward,
WebHome,
WebRefresh,
WebSearch,
WebStop,
Yen,
Copy,
Paste,
Cut,
Unknown,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum MouseButton {
Button1,
Button2,
Button3,
Button4,
Button5,
Button6,
Button7,
Button8,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum Action {
Release,
Press,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum TouchAction {
Start,
End,
Move,
Cancel,
}
bitflags! {
#[doc = "Key modifiers"]
#[derive(Serialize, Deserialize)]
pub struct Modifiers: i32 {
const Shift = 0b0001;
const Control = 0b0010;
const Alt = 0b0100;
const Super = 0b1000;
}
}
| is_mouse_event | identifier_name |
window_event.rs | #![allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Serialize, Deserialize)]
pub enum WindowEvent {
Pos(i32, i32),
Size(u32, u32),
Close,
Refresh,
Focus(bool),
Iconify(bool),
FramebufferSize(u32, u32),
MouseButton(MouseButton, Action, Modifiers),
CursorPos(f64, f64, Modifiers),
CursorEnter(bool),
Scroll(f64, f64, Modifiers),
Key(Key, Action, Modifiers),
Char(char), | }
use WindowEvent::*;
impl WindowEvent {
/// Tests if this event is related to the keyboard.
pub fn is_keyboard_event(&self) -> bool {
matches!(self, Key(..) | Char(..) | CharModifiers(..))
}
/// Tests if this event is related to the mouse.
pub fn is_mouse_event(&self) -> bool {
matches!(
self,
MouseButton(..) | CursorPos(..) | CursorEnter(..) | Scroll(..)
)
}
/// Tests if this event is related to the touch.
pub fn is_touch_event(&self) -> bool {
matches!(self, Touch(..))
}
}
// NOTE: list of keys inspired from glutin.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum Key {
Key1,
Key2,
Key3,
Key4,
Key5,
Key6,
Key7,
Key8,
Key9,
Key0,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
Escape,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
Snapshot,
Scroll,
Pause,
Insert,
Home,
Delete,
End,
PageDown,
PageUp,
Left,
Up,
Right,
Down,
Back,
Return,
Space,
Compose,
Caret,
Numlock,
Numpad0,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
AbntC1,
AbntC2,
Add,
Apostrophe,
Apps,
At,
Ax,
Backslash,
Calculator,
Capital,
Colon,
Comma,
Convert,
Decimal,
Divide,
Equals,
Grave,
Kana,
Kanji,
LAlt,
LBracket,
LControl,
LShift,
LWin,
Mail,
MediaSelect,
MediaStop,
Minus,
Multiply,
Mute,
MyComputer,
NavigateForward,
NavigateBackward,
NextTrack,
NoConvert,
NumpadComma,
NumpadEnter,
NumpadEquals,
OEM102,
Period,
PlayPause,
Power,
PrevTrack,
RAlt,
RBracket,
RControl,
RShift,
RWin,
Semicolon,
Slash,
Sleep,
Stop,
Subtract,
Sysrq,
Tab,
Underline,
Unlabeled,
VolumeDown,
VolumeUp,
Wake,
WebBack,
WebFavorites,
WebForward,
WebHome,
WebRefresh,
WebSearch,
WebStop,
Yen,
Copy,
Paste,
Cut,
Unknown,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum MouseButton {
Button1,
Button2,
Button3,
Button4,
Button5,
Button6,
Button7,
Button8,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum Action {
Release,
Press,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum TouchAction {
Start,
End,
Move,
Cancel,
}
bitflags! {
#[doc = "Key modifiers"]
#[derive(Serialize, Deserialize)]
pub struct Modifiers: i32 {
const Shift = 0b0001;
const Control = 0b0010;
const Alt = 0b0100;
const Super = 0b1000;
}
} | CharModifiers(char, Modifiers),
Touch(u64, f64, f64, TouchAction, Modifiers), | random_line_split |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::DocumentSource;
use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
use crate::dom::servoparser::ServoParser;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use script_traits::DocumentActivity;
#[dom_struct]
pub struct DOMParser {
reflector_: Reflector,
window: Dom<Window>, // XXXjdm Document instead?
}
impl DOMParser {
fn new_inherited(window: &Window) -> DOMParser {
DOMParser {
reflector_: Reflector::new(),
window: Dom::from_ref(window),
}
}
pub fn new(window: &Window) -> DomRoot<DOMParser> {
reflect_dom_object(
Box::new(DOMParser::new_inherited(window)),
window,
DOMParserBinding::Wrap,
)
}
pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>> {
Ok(DOMParser::new(window))
}
}
impl DOMParserMethods for DOMParser {
// https://w3c.github.io/DOM-Parsing/#the-domparser-interface
fn ParseFromString(
&self,
s: DOMString,
ty: DOMParserBinding::SupportedType,
) -> Fallible<DomRoot<Document>> {
let url = self.window.get_url();
let content_type = ty
.as_str()
.parse()
.expect("Supported type is not a MIME type");
let doc = self.window.Document();
let loader = DocumentLoader::new(&*doc.loader());
match ty {
Text_html => {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::HTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_html_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
},
Text_xml | Application_xml | Application_xhtml_xml => | ,
}
}
}
| {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_xml_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
} | conditional_block |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::DocumentSource;
use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
use crate::dom::servoparser::ServoParser;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use script_traits::DocumentActivity;
#[dom_struct]
pub struct DOMParser {
reflector_: Reflector,
window: Dom<Window>, // XXXjdm Document instead?
}
impl DOMParser {
fn new_inherited(window: &Window) -> DOMParser {
DOMParser {
reflector_: Reflector::new(),
window: Dom::from_ref(window),
}
}
pub fn new(window: &Window) -> DomRoot<DOMParser> {
reflect_dom_object(
Box::new(DOMParser::new_inherited(window)),
window,
DOMParserBinding::Wrap,
)
}
pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>> {
Ok(DOMParser::new(window))
}
}
impl DOMParserMethods for DOMParser {
// https://w3c.github.io/DOM-Parsing/#the-domparser-interface
fn ParseFromString(
&self,
s: DOMString,
ty: DOMParserBinding::SupportedType,
) -> Fallible<DomRoot<Document>> {
let url = self.window.get_url();
let content_type = ty
.as_str()
.parse()
.expect("Supported type is not a MIME type");
let doc = self.window.Document();
let loader = DocumentLoader::new(&*doc.loader());
match ty {
Text_html => {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::HTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_html_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
}, | &self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_xml_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
},
}
}
} | Text_xml | Application_xml | Application_xhtml_xml => {
let document = Document::new( | random_line_split |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::DocumentSource;
use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
use crate::dom::servoparser::ServoParser;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use script_traits::DocumentActivity;
#[dom_struct]
pub struct DOMParser {
reflector_: Reflector,
window: Dom<Window>, // XXXjdm Document instead?
}
impl DOMParser {
fn new_inherited(window: &Window) -> DOMParser {
DOMParser {
reflector_: Reflector::new(),
window: Dom::from_ref(window),
}
}
pub fn new(window: &Window) -> DomRoot<DOMParser> {
reflect_dom_object(
Box::new(DOMParser::new_inherited(window)),
window,
DOMParserBinding::Wrap,
)
}
pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>> |
}
impl DOMParserMethods for DOMParser {
// https://w3c.github.io/DOM-Parsing/#the-domparser-interface
fn ParseFromString(
&self,
s: DOMString,
ty: DOMParserBinding::SupportedType,
) -> Fallible<DomRoot<Document>> {
let url = self.window.get_url();
let content_type = ty
.as_str()
.parse()
.expect("Supported type is not a MIME type");
let doc = self.window.Document();
let loader = DocumentLoader::new(&*doc.loader());
match ty {
Text_html => {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::HTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_html_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
},
Text_xml | Application_xml | Application_xhtml_xml => {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_xml_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
},
}
}
}
| {
Ok(DOMParser::new(window))
} | identifier_body |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::DocumentSource;
use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
use crate::dom::servoparser::ServoParser;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use script_traits::DocumentActivity;
#[dom_struct]
pub struct DOMParser {
reflector_: Reflector,
window: Dom<Window>, // XXXjdm Document instead?
}
impl DOMParser {
fn new_inherited(window: &Window) -> DOMParser {
DOMParser {
reflector_: Reflector::new(),
window: Dom::from_ref(window),
}
}
pub fn new(window: &Window) -> DomRoot<DOMParser> {
reflect_dom_object(
Box::new(DOMParser::new_inherited(window)),
window,
DOMParserBinding::Wrap,
)
}
pub fn | (window: &Window) -> Fallible<DomRoot<DOMParser>> {
Ok(DOMParser::new(window))
}
}
impl DOMParserMethods for DOMParser {
// https://w3c.github.io/DOM-Parsing/#the-domparser-interface
fn ParseFromString(
&self,
s: DOMString,
ty: DOMParserBinding::SupportedType,
) -> Fallible<DomRoot<Document>> {
let url = self.window.get_url();
let content_type = ty
.as_str()
.parse()
.expect("Supported type is not a MIME type");
let doc = self.window.Document();
let loader = DocumentLoader::new(&*doc.loader());
match ty {
Text_html => {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::HTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_html_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
},
Text_xml | Application_xml | Application_xhtml_xml => {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
Some(content_type),
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
loader,
None,
None,
Default::default(),
);
ServoParser::parse_xml_document(&document, s, url);
document.set_ready_state(DocumentReadyState::Complete);
Ok(document)
},
}
}
}
| Constructor | identifier_name |
builtins.rs | use crate::state::InterpState;
use enum_iterator::IntoEnumIterator;
/// Represents a builtin function
#[derive(Debug, Clone, PartialEq, IntoEnumIterator)]
pub enum Builtin {
Dot,
Plus,
Minus,
Star,
Slash,
Abs,
And,
Or,
Xor,
LShift,
RShift,
Equals,
NotEquals,
LessThan,
GreaterThan,
LessEqual,
GreaterEqual,
Emit,
Dup,
Swap,
Over,
Rot,
Tuck,
Drop,
Fetch,
Store,
Here,
Comma,
Depth,
Allot,
}
impl Builtin {
pub fn | (&self) -> &'static str {
match *self {
Builtin::Dot => ".",
Builtin::Plus => "+",
Builtin::Minus => "-",
Builtin::Star => "*",
Builtin::Slash => "/",
Builtin::Abs => "abs",
Builtin::And => "and",
Builtin::Or => "or",
Builtin::Xor => "xor",
Builtin::LShift => "lshift",
Builtin::RShift => "rshift",
Builtin::Equals => "=",
Builtin::NotEquals => "<>",
Builtin::LessThan => "<",
Builtin::GreaterThan => ">",
Builtin::LessEqual => "<=",
Builtin::GreaterEqual => ">=",
Builtin::Emit => "emit",
Builtin::Dup => "dup",
Builtin::Swap => "swap",
Builtin::Over => "over",
Builtin::Rot => "rot",
Builtin::Tuck => "tuck",
Builtin::Drop => "drop",
Builtin::Here => "here",
Builtin::Fetch => "@",
Builtin::Store => "!",
Builtin::Comma => ",",
Builtin::Depth => "depth",
Builtin::Allot => "allot",
}
}
pub fn call(&self, state: &mut InterpState) {
let stack = &mut state.stack;
/// Allows defining a builtin using closure-like syntax. Note that the
/// arguments are in reverse order, as that is how the stack is laid out.
macro_rules! stackexpr {
( | $($aname:ident : $atype:ty),+ | $($value:expr),+ ) => {
{
$(
let $aname: $atype = stack.pop();
)+
$(
stack.push($value);
)+
}
}
}
use self::Builtin::*;
match *self {
Dot => print!("{}", stack.pop::<i32>()),
Plus => stackexpr!(|n2: i32, n1: i32| n1 + n2),
Minus => stackexpr!(|n2: i32, n1: i32| n1 - n2),
Star => stackexpr!(|n2: i32, n1: i32| n1 * n2),
Slash => stackexpr!(|n2: i32, n1: i32| n1 / n2),
Abs => stackexpr!(|n: i32| n.abs()),
And => stackexpr!(|n2: i32, n1: i32| n1 & n2),
Or => stackexpr!(|n2: i32, n1: i32| n1 | n2),
Xor => stackexpr!(|n2: i32, n1: i32| n1 ^ n2),
LShift => stackexpr!(|u: i32, n: i32| n << u),
RShift => stackexpr!(|u: i32, n: i32| n >> u),
Equals => stackexpr!(|n2: i32, n1: i32| n1 == n2),
NotEquals => stackexpr!(|n2: i32, n1: i32| n1!= n2),
LessThan => stackexpr!(|n2: i32, n1: i32| n1 < n2),
GreaterThan => stackexpr!(|n2: i32, n1: i32| n1 > n2),
LessEqual => stackexpr!(|n2: i32, n1: i32| n1 <= n2),
GreaterEqual => stackexpr!(|n2: i32, n1: i32| n1 >= n2),
Emit => print!("{}", stack.pop::<char>()),
Dup => {
let n: i32 = stack.peak();
stack.push(n);
}
Swap => stackexpr!(|n2: i32, n1: i32| n2, n1),
Over => stackexpr!(|n2: i32, n1: i32| n1, n2, n1),
Rot => stackexpr!(|n3: i32, n2: i32, n1: i32| n2, n3, n1),
Tuck => stackexpr!(|n2: i32, n1: i32| n2, n1, n2),
Drop => {
stack.pop::<i32>();
}
Fetch => stackexpr!(|addr: i32| state.memory.get::<i32>(addr)),
Store => {
let addr: i32 = stack.pop();
let n: i32 = stack.pop();
state.memory.set(addr, n);
}
Here => stack.push(state.memory.here()),
Comma => {
state.memory.new(stack.pop::<i32>());
}
Depth => {
let len = stack.len();
stack.push(len);
}
Allot => {
let n = stack.pop();
if n < 0 {
// TODO Free memory
} else {
for _ in 0..n {
state.memory.new(0);
}
}
}
}
}
}
| word | identifier_name |
builtins.rs | use crate::state::InterpState;
use enum_iterator::IntoEnumIterator;
/// Represents a builtin function
#[derive(Debug, Clone, PartialEq, IntoEnumIterator)]
pub enum Builtin {
Dot,
Plus,
Minus,
Star,
Slash,
Abs,
And,
Or,
Xor,
LShift,
RShift,
Equals,
NotEquals,
LessThan,
GreaterThan,
LessEqual,
GreaterEqual,
Emit,
Dup,
Swap,
Over,
Rot,
Tuck,
Drop,
Fetch,
Store,
Here,
Comma,
Depth,
Allot,
}
impl Builtin {
pub fn word(&self) -> &'static str {
match *self {
Builtin::Dot => ".",
Builtin::Plus => "+",
Builtin::Minus => "-",
Builtin::Star => "*",
Builtin::Slash => "/",
Builtin::Abs => "abs",
Builtin::And => "and",
Builtin::Or => "or",
Builtin::Xor => "xor",
Builtin::LShift => "lshift",
Builtin::RShift => "rshift",
Builtin::Equals => "=",
Builtin::NotEquals => "<>",
Builtin::LessThan => "<",
Builtin::GreaterThan => ">",
Builtin::LessEqual => "<=",
Builtin::GreaterEqual => ">=",
Builtin::Emit => "emit",
Builtin::Dup => "dup",
Builtin::Swap => "swap",
Builtin::Over => "over",
Builtin::Rot => "rot",
Builtin::Tuck => "tuck",
Builtin::Drop => "drop",
Builtin::Here => "here",
Builtin::Fetch => "@",
Builtin::Store => "!",
Builtin::Comma => ",",
Builtin::Depth => "depth",
Builtin::Allot => "allot",
}
}
pub fn call(&self, state: &mut InterpState) {
let stack = &mut state.stack;
/// Allows defining a builtin using closure-like syntax. Note that the
/// arguments are in reverse order, as that is how the stack is laid out.
macro_rules! stackexpr {
( | $($aname:ident : $atype:ty),+ | $($value:expr),+ ) => {
{
$(
let $aname: $atype = stack.pop();
)+
$(
stack.push($value);
)+
}
}
}
use self::Builtin::*;
match *self {
Dot => print!("{}", stack.pop::<i32>()),
Plus => stackexpr!(|n2: i32, n1: i32| n1 + n2),
Minus => stackexpr!(|n2: i32, n1: i32| n1 - n2),
Star => stackexpr!(|n2: i32, n1: i32| n1 * n2),
Slash => stackexpr!(|n2: i32, n1: i32| n1 / n2),
Abs => stackexpr!(|n: i32| n.abs()),
And => stackexpr!(|n2: i32, n1: i32| n1 & n2),
Or => stackexpr!(|n2: i32, n1: i32| n1 | n2),
Xor => stackexpr!(|n2: i32, n1: i32| n1 ^ n2),
LShift => stackexpr!(|u: i32, n: i32| n << u), | LessEqual => stackexpr!(|n2: i32, n1: i32| n1 <= n2),
GreaterEqual => stackexpr!(|n2: i32, n1: i32| n1 >= n2),
Emit => print!("{}", stack.pop::<char>()),
Dup => {
let n: i32 = stack.peak();
stack.push(n);
}
Swap => stackexpr!(|n2: i32, n1: i32| n2, n1),
Over => stackexpr!(|n2: i32, n1: i32| n1, n2, n1),
Rot => stackexpr!(|n3: i32, n2: i32, n1: i32| n2, n3, n1),
Tuck => stackexpr!(|n2: i32, n1: i32| n2, n1, n2),
Drop => {
stack.pop::<i32>();
}
Fetch => stackexpr!(|addr: i32| state.memory.get::<i32>(addr)),
Store => {
let addr: i32 = stack.pop();
let n: i32 = stack.pop();
state.memory.set(addr, n);
}
Here => stack.push(state.memory.here()),
Comma => {
state.memory.new(stack.pop::<i32>());
}
Depth => {
let len = stack.len();
stack.push(len);
}
Allot => {
let n = stack.pop();
if n < 0 {
// TODO Free memory
} else {
for _ in 0..n {
state.memory.new(0);
}
}
}
}
}
} | RShift => stackexpr!(|u: i32, n: i32| n >> u),
Equals => stackexpr!(|n2: i32, n1: i32| n1 == n2),
NotEquals => stackexpr!(|n2: i32, n1: i32| n1 != n2),
LessThan => stackexpr!(|n2: i32, n1: i32| n1 < n2),
GreaterThan => stackexpr!(|n2: i32, n1: i32| n1 > n2), | random_line_split |
builtins.rs | use crate::state::InterpState;
use enum_iterator::IntoEnumIterator;
/// Represents a builtin function
#[derive(Debug, Clone, PartialEq, IntoEnumIterator)]
pub enum Builtin {
Dot,
Plus,
Minus,
Star,
Slash,
Abs,
And,
Or,
Xor,
LShift,
RShift,
Equals,
NotEquals,
LessThan,
GreaterThan,
LessEqual,
GreaterEqual,
Emit,
Dup,
Swap,
Over,
Rot,
Tuck,
Drop,
Fetch,
Store,
Here,
Comma,
Depth,
Allot,
}
impl Builtin {
pub fn word(&self) -> &'static str {
match *self {
Builtin::Dot => ".",
Builtin::Plus => "+",
Builtin::Minus => "-",
Builtin::Star => "*",
Builtin::Slash => "/",
Builtin::Abs => "abs",
Builtin::And => "and",
Builtin::Or => "or",
Builtin::Xor => "xor",
Builtin::LShift => "lshift",
Builtin::RShift => "rshift",
Builtin::Equals => "=",
Builtin::NotEquals => "<>",
Builtin::LessThan => "<",
Builtin::GreaterThan => ">",
Builtin::LessEqual => "<=",
Builtin::GreaterEqual => ">=",
Builtin::Emit => "emit",
Builtin::Dup => "dup",
Builtin::Swap => "swap",
Builtin::Over => "over",
Builtin::Rot => "rot",
Builtin::Tuck => "tuck",
Builtin::Drop => "drop",
Builtin::Here => "here",
Builtin::Fetch => "@",
Builtin::Store => "!",
Builtin::Comma => ",",
Builtin::Depth => "depth",
Builtin::Allot => "allot",
}
}
pub fn call(&self, state: &mut InterpState) | Dot => print!("{}", stack.pop::<i32>()),
Plus => stackexpr!(|n2: i32, n1: i32| n1 + n2),
Minus => stackexpr!(|n2: i32, n1: i32| n1 - n2),
Star => stackexpr!(|n2: i32, n1: i32| n1 * n2),
Slash => stackexpr!(|n2: i32, n1: i32| n1 / n2),
Abs => stackexpr!(|n: i32| n.abs()),
And => stackexpr!(|n2: i32, n1: i32| n1 & n2),
Or => stackexpr!(|n2: i32, n1: i32| n1 | n2),
Xor => stackexpr!(|n2: i32, n1: i32| n1 ^ n2),
LShift => stackexpr!(|u: i32, n: i32| n << u),
RShift => stackexpr!(|u: i32, n: i32| n >> u),
Equals => stackexpr!(|n2: i32, n1: i32| n1 == n2),
NotEquals => stackexpr!(|n2: i32, n1: i32| n1!= n2),
LessThan => stackexpr!(|n2: i32, n1: i32| n1 < n2),
GreaterThan => stackexpr!(|n2: i32, n1: i32| n1 > n2),
LessEqual => stackexpr!(|n2: i32, n1: i32| n1 <= n2),
GreaterEqual => stackexpr!(|n2: i32, n1: i32| n1 >= n2),
Emit => print!("{}", stack.pop::<char>()),
Dup => {
let n: i32 = stack.peak();
stack.push(n);
}
Swap => stackexpr!(|n2: i32, n1: i32| n2, n1),
Over => stackexpr!(|n2: i32, n1: i32| n1, n2, n1),
Rot => stackexpr!(|n3: i32, n2: i32, n1: i32| n2, n3, n1),
Tuck => stackexpr!(|n2: i32, n1: i32| n2, n1, n2),
Drop => {
stack.pop::<i32>();
}
Fetch => stackexpr!(|addr: i32| state.memory.get::<i32>(addr)),
Store => {
let addr: i32 = stack.pop();
let n: i32 = stack.pop();
state.memory.set(addr, n);
}
Here => stack.push(state.memory.here()),
Comma => {
state.memory.new(stack.pop::<i32>());
}
Depth => {
let len = stack.len();
stack.push(len);
}
Allot => {
let n = stack.pop();
if n < 0 {
// TODO Free memory
} else {
for _ in 0..n {
state.memory.new(0);
}
}
}
}
}
}
| {
let stack = &mut state.stack;
/// Allows defining a builtin using closure-like syntax. Note that the
/// arguments are in reverse order, as that is how the stack is laid out.
macro_rules! stackexpr {
( | $($aname:ident : $atype:ty),+ | $($value:expr),+ ) => {
{
$(
let $aname: $atype = stack.pop();
)+
$(
stack.push($value);
)+
}
}
}
use self::Builtin::*;
match *self { | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "js"]
#![crate_type = "rlib"]
#![feature(core_intrinsics)]
#![feature(link_args)]
#![feature(str_utf16)]
#![feature(unsafe_no_drop_flag)]
#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, improper_ctypes, raw_pointer_derive)]
extern crate libc;
#[macro_use]
extern crate log; |
pub mod jsapi;
pub mod linkhack;
pub mod rust;
pub mod glue;
pub mod jsval;
use jsapi::{JSContext, JSProtoKey, Heap};
use jsval::JSVal;
use rust::GCMethods;
use libc::c_uint;
use heapsize::HeapSizeOf;
pub const default_heapsize: u32 = 32_u32 * 1024_u32 * 1024_u32;
pub const default_stacksize: usize = 8192;
pub const JSID_TYPE_STRING: i64 = 0;
pub const JSID_TYPE_INT: i64 = 1;
pub const JSID_TYPE_VOID: i64 = 2;
pub const JSID_TYPE_OBJECT: i64 = 4;
pub const JSID_TYPE_DEFAULT_XML_NAMESPACE: i64 = 6;
pub const JSID_TYPE_MASK: i64 = 7;
pub const JSFUN_CONSTRUCTOR: u32 = 0x400; /* native that can be called as a ctor */
pub const JSPROP_ENUMERATE: c_uint = 0x01;
pub const JSPROP_READONLY: c_uint = 0x02;
pub const JSPROP_PERMANENT: c_uint = 0x04;
pub const JSPROP_GETTER: c_uint = 0x10;
pub const JSPROP_SETTER: c_uint = 0x20;
pub const JSPROP_SHARED: c_uint = 0x40;
pub const JSPROP_NATIVE_ACCESSORS: c_uint = 0x08;
pub const JSCLASS_RESERVED_SLOTS_SHIFT: c_uint = 8;
pub const JSCLASS_RESERVED_SLOTS_WIDTH: c_uint = 8;
pub const JSCLASS_RESERVED_SLOTS_MASK: c_uint = ((1 << JSCLASS_RESERVED_SLOTS_WIDTH) - 1) as c_uint;
pub const JSCLASS_HIGH_FLAGS_SHIFT: c_uint =
JSCLASS_RESERVED_SLOTS_SHIFT + JSCLASS_RESERVED_SLOTS_WIDTH;
pub const JSCLASS_IS_GLOBAL: c_uint = 1 << (JSCLASS_HIGH_FLAGS_SHIFT + 1);
pub const JSCLASS_GLOBAL_APPLICATION_SLOTS: c_uint = 4;
pub const JSCLASS_GLOBAL_SLOT_COUNT: c_uint = JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProtoKey::JSProto_LIMIT as u32 * 3 + 31;
pub const JSCLASS_IS_DOMJSCLASS: u32 = 1 << 4;
pub const JSCLASS_IMPLEMENTS_BARRIERS: u32 = 1 << 5;
pub const JSCLASS_USERBIT1: u32 = 1 << 7;
pub const JSCLASS_IS_PROXY: u32 = 1 << (JSCLASS_HIGH_FLAGS_SHIFT+4);
pub const JSSLOT_PROXY_PRIVATE: u32 = 1;
pub const JS_DEFAULT_ZEAL_FREQ: u32 = 100;
pub const JSTrue: u8 = 1;
pub const JSFalse: u8 = 0;
#[link(name = "jsglue")]
extern { }
#[cfg(target_os = "android")]
#[link(name = "stdc++")]
extern { }
#[cfg(target_os = "android")]
#[link(name = "gcc")]
extern { }
#[inline(always)]
pub unsafe fn JS_ARGV(_cx: *mut JSContext, vp: *mut JSVal) -> *mut JSVal {
vp.offset(2)
}
#[inline(always)]
pub unsafe fn JS_CALLEE(_cx: *mut JSContext, vp: *mut JSVal) -> JSVal {
*vp
}
// This is measured properly by the heap measurement implemented in SpiderMonkey.
impl<T: Copy + GCMethods<T>> HeapSizeOf for Heap<T> {
fn heap_size_of_children(&self) -> usize {
0
}
}
known_heap_size!(0, JSVal); | #[macro_use]
extern crate heapsize;
extern crate rustc_serialize as serialize; | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "js"]
#![crate_type = "rlib"]
#![feature(core_intrinsics)]
#![feature(link_args)]
#![feature(str_utf16)]
#![feature(unsafe_no_drop_flag)]
#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, improper_ctypes, raw_pointer_derive)]
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate heapsize;
extern crate rustc_serialize as serialize;
pub mod jsapi;
pub mod linkhack;
pub mod rust;
pub mod glue;
pub mod jsval;
use jsapi::{JSContext, JSProtoKey, Heap};
use jsval::JSVal;
use rust::GCMethods;
use libc::c_uint;
use heapsize::HeapSizeOf;
pub const default_heapsize: u32 = 32_u32 * 1024_u32 * 1024_u32;
pub const default_stacksize: usize = 8192;
pub const JSID_TYPE_STRING: i64 = 0;
pub const JSID_TYPE_INT: i64 = 1;
pub const JSID_TYPE_VOID: i64 = 2;
pub const JSID_TYPE_OBJECT: i64 = 4;
pub const JSID_TYPE_DEFAULT_XML_NAMESPACE: i64 = 6;
pub const JSID_TYPE_MASK: i64 = 7;
pub const JSFUN_CONSTRUCTOR: u32 = 0x400; /* native that can be called as a ctor */
pub const JSPROP_ENUMERATE: c_uint = 0x01;
pub const JSPROP_READONLY: c_uint = 0x02;
pub const JSPROP_PERMANENT: c_uint = 0x04;
pub const JSPROP_GETTER: c_uint = 0x10;
pub const JSPROP_SETTER: c_uint = 0x20;
pub const JSPROP_SHARED: c_uint = 0x40;
pub const JSPROP_NATIVE_ACCESSORS: c_uint = 0x08;
pub const JSCLASS_RESERVED_SLOTS_SHIFT: c_uint = 8;
pub const JSCLASS_RESERVED_SLOTS_WIDTH: c_uint = 8;
pub const JSCLASS_RESERVED_SLOTS_MASK: c_uint = ((1 << JSCLASS_RESERVED_SLOTS_WIDTH) - 1) as c_uint;
pub const JSCLASS_HIGH_FLAGS_SHIFT: c_uint =
JSCLASS_RESERVED_SLOTS_SHIFT + JSCLASS_RESERVED_SLOTS_WIDTH;
pub const JSCLASS_IS_GLOBAL: c_uint = 1 << (JSCLASS_HIGH_FLAGS_SHIFT + 1);
pub const JSCLASS_GLOBAL_APPLICATION_SLOTS: c_uint = 4;
pub const JSCLASS_GLOBAL_SLOT_COUNT: c_uint = JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProtoKey::JSProto_LIMIT as u32 * 3 + 31;
pub const JSCLASS_IS_DOMJSCLASS: u32 = 1 << 4;
pub const JSCLASS_IMPLEMENTS_BARRIERS: u32 = 1 << 5;
pub const JSCLASS_USERBIT1: u32 = 1 << 7;
pub const JSCLASS_IS_PROXY: u32 = 1 << (JSCLASS_HIGH_FLAGS_SHIFT+4);
pub const JSSLOT_PROXY_PRIVATE: u32 = 1;
pub const JS_DEFAULT_ZEAL_FREQ: u32 = 100;
pub const JSTrue: u8 = 1;
pub const JSFalse: u8 = 0;
#[link(name = "jsglue")]
extern { }
#[cfg(target_os = "android")]
#[link(name = "stdc++")]
extern { }
#[cfg(target_os = "android")]
#[link(name = "gcc")]
extern { }
#[inline(always)]
pub unsafe fn JS_ARGV(_cx: *mut JSContext, vp: *mut JSVal) -> *mut JSVal {
vp.offset(2)
}
#[inline(always)]
pub unsafe fn JS_CALLEE(_cx: *mut JSContext, vp: *mut JSVal) -> JSVal |
// This is measured properly by the heap measurement implemented in SpiderMonkey.
impl<T: Copy + GCMethods<T>> HeapSizeOf for Heap<T> {
fn heap_size_of_children(&self) -> usize {
0
}
}
known_heap_size!(0, JSVal);
| {
*vp
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "js"]
#![crate_type = "rlib"]
#![feature(core_intrinsics)]
#![feature(link_args)]
#![feature(str_utf16)]
#![feature(unsafe_no_drop_flag)]
#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, improper_ctypes, raw_pointer_derive)]
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate heapsize;
extern crate rustc_serialize as serialize;
pub mod jsapi;
pub mod linkhack;
pub mod rust;
pub mod glue;
pub mod jsval;
use jsapi::{JSContext, JSProtoKey, Heap};
use jsval::JSVal;
use rust::GCMethods;
use libc::c_uint;
use heapsize::HeapSizeOf;
pub const default_heapsize: u32 = 32_u32 * 1024_u32 * 1024_u32;
pub const default_stacksize: usize = 8192;
pub const JSID_TYPE_STRING: i64 = 0;
pub const JSID_TYPE_INT: i64 = 1;
pub const JSID_TYPE_VOID: i64 = 2;
pub const JSID_TYPE_OBJECT: i64 = 4;
pub const JSID_TYPE_DEFAULT_XML_NAMESPACE: i64 = 6;
pub const JSID_TYPE_MASK: i64 = 7;
pub const JSFUN_CONSTRUCTOR: u32 = 0x400; /* native that can be called as a ctor */
pub const JSPROP_ENUMERATE: c_uint = 0x01;
pub const JSPROP_READONLY: c_uint = 0x02;
pub const JSPROP_PERMANENT: c_uint = 0x04;
pub const JSPROP_GETTER: c_uint = 0x10;
pub const JSPROP_SETTER: c_uint = 0x20;
pub const JSPROP_SHARED: c_uint = 0x40;
pub const JSPROP_NATIVE_ACCESSORS: c_uint = 0x08;
pub const JSCLASS_RESERVED_SLOTS_SHIFT: c_uint = 8;
pub const JSCLASS_RESERVED_SLOTS_WIDTH: c_uint = 8;
pub const JSCLASS_RESERVED_SLOTS_MASK: c_uint = ((1 << JSCLASS_RESERVED_SLOTS_WIDTH) - 1) as c_uint;
pub const JSCLASS_HIGH_FLAGS_SHIFT: c_uint =
JSCLASS_RESERVED_SLOTS_SHIFT + JSCLASS_RESERVED_SLOTS_WIDTH;
pub const JSCLASS_IS_GLOBAL: c_uint = 1 << (JSCLASS_HIGH_FLAGS_SHIFT + 1);
pub const JSCLASS_GLOBAL_APPLICATION_SLOTS: c_uint = 4;
pub const JSCLASS_GLOBAL_SLOT_COUNT: c_uint = JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProtoKey::JSProto_LIMIT as u32 * 3 + 31;
pub const JSCLASS_IS_DOMJSCLASS: u32 = 1 << 4;
pub const JSCLASS_IMPLEMENTS_BARRIERS: u32 = 1 << 5;
pub const JSCLASS_USERBIT1: u32 = 1 << 7;
pub const JSCLASS_IS_PROXY: u32 = 1 << (JSCLASS_HIGH_FLAGS_SHIFT+4);
pub const JSSLOT_PROXY_PRIVATE: u32 = 1;
pub const JS_DEFAULT_ZEAL_FREQ: u32 = 100;
pub const JSTrue: u8 = 1;
pub const JSFalse: u8 = 0;
#[link(name = "jsglue")]
extern { }
#[cfg(target_os = "android")]
#[link(name = "stdc++")]
extern { }
#[cfg(target_os = "android")]
#[link(name = "gcc")]
extern { }
#[inline(always)]
pub unsafe fn JS_ARGV(_cx: *mut JSContext, vp: *mut JSVal) -> *mut JSVal {
vp.offset(2)
}
#[inline(always)]
pub unsafe fn JS_CALLEE(_cx: *mut JSContext, vp: *mut JSVal) -> JSVal {
*vp
}
// This is measured properly by the heap measurement implemented in SpiderMonkey.
impl<T: Copy + GCMethods<T>> HeapSizeOf for Heap<T> {
fn | (&self) -> usize {
0
}
}
known_heap_size!(0, JSVal);
| heap_size_of_children | identifier_name |
window.rs | -> &mut glfw::Window {
&mut self.window
}
/// The window width.
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The size of the window.
#[inline]
pub fn size(&self) -> Vec2<f32> {
let (w, h) = self.window.get_size();
Vec2::new(w as f32, h as f32)
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
#[inline]
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f!= 0); 1000 / f })
}
/// Set window title
pub fn set_title(&mut self, title: &str) {
self.window.set_title(title)
}
/// Closes the window.
#[inline]
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
#[inline]
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
#[inline]
pub fn show(&mut self) {
self.window.show()
}
/// Sets the background color.
#[inline]
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a point to be drawn during the next frame.
#[inline]
pub fn draw_point(&mut self, pt: &Pnt3<f32>, color: &Pnt3<f32>) {
self.point_renderer.draw_point(pt.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a string to be drawn during the next frame.
#[inline]
pub fn draw_text(&mut self, text: &str, pos: &Pnt2<f32>, font: &Rc<Font>, color: &Pnt3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, sn: &mut SceneNode) {
sn.unlink()
}
/// Adds a group to the scene.
///
/// A group is a node not containing any object.
pub fn add_group(&mut self) -> SceneNode {
self.scene.add_group()
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: Vec3<f32>) -> SceneNode {
self.scene.add_obj(path, mtl_dir, scale)
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Rc<RefCell<Mesh>>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_mesh(mesh, scale)
}
/// Creates and adds a new object using the geometry generated by a given procedural generator.
/// Creates and adds a new object using a mesh descriptor.
pub fn add_trimesh(&mut self, descr: TriMesh3<f32>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_trimesh(descr, scale)
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> SceneNode {
self.scene.add_cube(wx, wy, wz)
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cone(r, h)
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cylinder(r, h)
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_capsule(r, h)
}
/// Adds a double-sided quad to the scene. The quad is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width.
/// * `h` - the quad height.
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`.
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`.
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, usubdivs: usize, vsubdivs: usize) -> SceneNode {
self.scene.add_quad(w, h, usubdivs, vsubdivs)
}
/// Adds a double-sided quad with the specified vertices.
pub fn add_quad_with_vertices(&mut self,
vertices: &[Pnt3<f32>],
nhpoints: usize,
nvpoints: usize)
-> SceneNode {
self.scene.add_quad_with_vertices(vertices, nhpoints, nvpoints)
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Returns whether this window is closed or not.
pub fn is_closed(&self) -> bool {
false // FIXME
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title.
/// * `width` - the window width.
/// * `height` - the window height.
pub fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height)
}
// FIXME: make this pub?
fn do_new(title: &str, hide: bool, width: u32, height: u32) -> Window {
// FIXME: glfw::set_error_callback(~ErrorCallback);
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
let (mut window, events) = glfw.create_window(width, height, title, WindowMode::Windowed).expect("Unable to open a glfw window.");
window.make_current();
verify!(gl::load_with(|name| window.get_proc_address(name) as *const _));
init_gl();
let mut usr_window = Window {
max_ms_per_frame: None,
glfw: glfw,
window: window,
events: Rc::new(events),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
scene: SceneNode::new_empty(),
light_mode: Light::Absolute(Pnt3::new(0.0, 10.0, 0.0)),
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
point_renderer: PointRenderer::new(),
text_renderer: TextRenderer::new(),
post_process_render_target: FramebufferManager::new_render_target(width as usize, height as usize),
framebuffer_manager: FramebufferManager::new(),
curr_time: time::precise_time_ns(),
camera: Rc::new(RefCell::new(ArcBall::new(Pnt3::new(0.0f32, 0.0, -1.0), na::orig())))
};
// setup callbacks
usr_window.window.set_framebuffer_size_polling(true);
usr_window.window.set_key_polling(true);
usr_window.window.set_mouse_button_polling(true);
usr_window.window.set_cursor_pos_polling(true);
usr_window.window.set_scroll_polling(true);
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
let light = usr_window.light_mode.clone();
usr_window.set_light(light);
usr_window
}
/// Reference to the scene associated with this window.
#[inline]
pub fn scene<'a>(&'a self) -> &'a SceneNode {
&self.scene
}
/// Mutable reference to the scene associated with this window.
#[inline]
pub fn scene_mut<'a>(&'a mut self) -> &'a mut SceneNode {
&mut self.scene
}
// FIXME: give more options for the snap size and offset.
/// Read the pixels currently displayed to the screen.
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized.
pub fn snap(&self, out: &mut Vec<u8>) {
let (width, height) = self.window.get_size();
self.snap_rect(out, 0, 0, width as usize, height as usize)
}
/// Read a section of pixels from the screen
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized
/// * `x, y, width, height` - the rectangle to capture
pub fn snap_rect(&self, out: &mut Vec<u8>, x: usize, y: usize, width: usize, height: usize) {
let size = (width * height * 3) as usize;
if out.len() < size {
let diff = size - out.len();
out.extend(repeat(0).take(diff));
}
else {
out.truncate(size)
}
// FIXME: this is _not_ the fastest way of doing this.
unsafe {
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::ReadPixels(x as i32, y as i32,
width as i32, height as i32,
gl::RGB,
gl::UNSIGNED_BYTE,
mem::transmute(&mut out[0]));
}
}
/// Get the current screen as an image
pub fn snap_image(&self) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = self.window.get_size();
let mut buf = Vec::new();
self.snap(&mut buf);
let img_opt = ImageBuffer::from_vec(width as u32, height as u32, buf);
let img = img_opt.expect("Buffer created from window was not big enough for image.");
imageops::flip_vertical(&img)
}
/// Gets the events manager that gives access to an event iterator.
pub fn events(&self) -> EventManager {
EventManager::new(self.events.clone(), self.unhandled_events.clone())
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline]
fn handle_events(&mut self, camera: &mut Option<&mut Camera>) {
let unhandled_events = self.unhandled_events.clone(); // FIXME: this is very ugly.
let events = self.events.clone(); // FIXME: this is very ugly
for event in unhandled_events.borrow().iter() {
self.handle_event(camera, event)
}
for event in glfw::flush_messages(&*events) {
self.handle_event(camera, &event.1)
}
unhandled_events.borrow_mut().clear();
self.glfw.poll_events();
}
fn handle_event(&mut self, camera: &mut Option<&mut Camera>, event: &WindowEvent) {
match *event {
WindowEvent::Key(Key::Escape, _, Action::Release, _) => {
self.close();
},
WindowEvent::FramebufferSize(w, h) => {
self.update_viewport(w as f32, h as f32);
},
_ => { }
}
match *camera {
Some(ref mut cam) => cam.handle_event(&self.window, event),
None => self.camera.borrow_mut().handle_event(&self.window, event)
}
}
/// Renders the scene using the default camera.
///
/// Returns `false` if the window should be closed.
pub fn render(&mut self) -> bool {
self.render_with(None, None)
}
/// Render using a specific post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_effect(&mut self, effect: &mut PostProcessingEffect) -> bool {
self.render_with(None, Some(effect))
}
/// Render using a specific camera.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera(&mut self, camera: &mut Camera) -> bool {
self.render_with(Some(camera), None)
}
/// Render using a specific camera and post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera_and_effect(&mut self, camera: &mut Camera, effect: &mut PostProcessingEffect) -> bool {
self.render_with(Some(camera), Some(effect))
}
/// Draws the scene with the given camera and post-processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with(&mut self,
camera: Option<&mut Camera>,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let mut camera = camera;
self.handle_events(&mut camera);
match camera {
Some(cam) => self.do_render_with(cam, post_processing),
None => {
let self_cam = self.camera.clone(); // FIXME: this is ugly.
let mut bself_cam = self_cam.borrow_mut();
self.do_render_with(&mut *bself_cam, post_processing)
}
}
}
fn do_render_with(&mut self,
camera: &mut Camera,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
// XXX: too bad we have to do this at each frame…
let w = self.width();
let h = self.height();
camera.handle_event(&self.window, &WindowEvent::FramebufferSize(w as i32, h as i32));
camera.update(&self.window);
match self.light_mode {
Light::StickToCamera => self.set_light(Light::StickToCamera),
_ => { }
}
let mut post_processing = post_processing;
if post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in 0usize.. camera.num_passes() {
camera.start_pass(pass, &self.window);
self.render_scene(camera, pass);
}
camera.render_complete(&self.window);
let (znear, zfar) = camera.clip_planes();
// FIXME: remove this completely?
// swatch off the wireframe mode for post processing and text rendering.
// if self.wireframe_mode {
// verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
// }
match post_processing {
Some(ref mut p) => {
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - self.curr_time) / 1000000;
if elapsed < ms {
thread::sleep(Duration::from_millis(ms - elapsed));
}
}
}
self.curr_time = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
!self.should_close()
}
fn render_scene(&mut self, camera: &mut Camera, pass: usize) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, camera);
}
if self.point_renderer.needs_rendering() {
self.point_renderer.render(pass, camera);
}
self.scene.data_mut().render(pass, camera, &self.light_mode);
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0, 0, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/ | verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST)); | random_line_split |
|
window.rs |
/// This is the main interface with the 3d engine.
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_ms_per_frame: Option<u64>,
scene: SceneNode,
light_mode: Light, // FIXME: move that to the scene graph
background: Vec3<GLfloat>,
line_renderer: LineRenderer,
point_renderer: PointRenderer,
text_renderer: TextRenderer,
framebuffer_manager: FramebufferManager,
post_process_render_target: RenderTarget,
curr_time: u64,
camera: Rc<RefCell<ArcBall>>
}
impl Window {
/// Indicates whether this window should be closed.
#[inline]
pub fn should_close(&self) -> bool {
self.window.should_close()
}
/// Access the glfw context.
#[inline]
pub fn context<'r>(&'r self) -> &'r glfw::Glfw {
&self.glfw
}
/// Access the glfw window.
#[inline]
pub fn glfw_window(&self) -> &glfw::Window {
&self.window
}
/// Mutably access the glfw window.
#[inline]
pub fn glfw_window_mut(&mut self) -> &mut glfw::Window {
&mut self.window
}
/// The window width.
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The size of the window.
#[inline]
pub fn size(&self) -> Vec2<f32> {
let (w, h) = self.window.get_size();
Vec2::new(w as f32, h as f32)
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
#[inline]
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f!= 0); 1000 / f })
}
/// Set window title
pub fn set_title(&mut self, title: &str) {
self.window.set_title(title)
}
/// Closes the window.
#[inline]
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
#[inline]
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
#[inline]
pub fn show(&mut self) {
self.window.show()
}
/// Sets the background color.
#[inline]
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a point to be drawn during the next frame.
#[inline]
pub fn draw_point(&mut self, pt: &Pnt3<f32>, color: &Pnt3<f32>) {
self.point_renderer.draw_point(pt.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a string to be drawn during the next frame.
#[inline]
pub fn draw_text(&mut self, text: &str, pos: &Pnt2<f32>, font: &Rc<Font>, color: &Pnt3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, sn: &mut SceneNode) {
sn.unlink()
}
/// Adds a group to the scene.
///
/// A group is a node not containing any object.
pub fn add_group(&mut self) -> SceneNode {
self.scene.add_group()
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: Vec3<f32>) -> SceneNode {
self.scene.add_obj(path, mtl_dir, scale)
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Rc<RefCell<Mesh>>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_mesh(mesh, scale)
}
/// Creates and adds a new object using the geometry generated by a given procedural generator.
/// Creates and adds a new object using a mesh descriptor.
pub fn add_trimesh(&mut self, descr: TriMesh3<f32>, scale: Vec3<f32>) -> SceneNode |
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> SceneNode {
self.scene.add_cube(wx, wy, wz)
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cone(r, h)
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cylinder(r, h)
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_capsule(r, h)
}
/// Adds a double-sided quad to the scene. The quad is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width.
/// * `h` - the quad height.
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`.
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`.
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, usubdivs: usize, vsubdivs: usize) -> SceneNode {
self.scene.add_quad(w, h, usubdivs, vsubdivs)
}
/// Adds a double-sided quad with the specified vertices.
pub fn add_quad_with_vertices(&mut self,
vertices: &[Pnt3<f32>],
nhpoints: usize,
nvpoints: usize)
-> SceneNode {
self.scene.add_quad_with_vertices(vertices, nhpoints, nvpoints)
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Returns whether this window is closed or not.
pub fn is_closed(&self) -> bool {
false // FIXME
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title.
/// * `width` - the window width.
/// * `height` - the window height.
pub fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height)
}
// FIXME: make this pub?
fn do_new(title: &str, hide: bool, width: u32, height: u32) -> Window {
// FIXME: glfw::set_error_callback(~ErrorCallback);
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
let (mut window, events) = glfw.create_window(width, height, title, WindowMode::Windowed).expect("Unable to open a glfw window.");
window.make_current();
verify!(gl::load_with(|name| window.get_proc_address(name) as *const _));
init_gl();
let mut usr_window = Window {
max_ms_per_frame: None,
glfw: glfw,
window: window,
events: Rc::new(events),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
scene: SceneNode::new_empty(),
light_mode: Light::Absolute(Pnt3::new(0.0, 10.0, 0.0)),
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
point_renderer: PointRenderer::new(),
text_renderer: TextRenderer::new(),
post_process_render_target: FramebufferManager::new_render_target(width as usize, height as usize),
framebuffer_manager: FramebufferManager::new(),
curr_time: time::precise_time_ns(),
camera: Rc::new(RefCell::new(ArcBall::new(Pnt3::new(0.0f32, 0.0, -1.0), na::orig())))
};
// setup callbacks
usr_window.window.set_framebuffer_size_polling(true);
usr_window.window.set_key_polling(true);
usr_window.window.set_mouse_button_polling(true);
usr_window.window.set_cursor_pos_polling(true);
usr_window.window.set_scroll_polling(true);
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
let light = usr_window.light_mode.clone();
usr_window.set_light(light);
usr_window
}
/// Reference to the scene associated with this window.
#[inline]
pub fn scene<'a>(&'a self) -> &'a SceneNode {
&self.scene
}
/// Mutable reference to the scene associated with this window.
#[inline]
pub fn scene_mut<'a>(&'a mut self) -> &'a mut SceneNode {
&mut self.scene
}
// FIXME: give more options for the snap size and offset.
/// Read the pixels currently displayed to the screen.
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized.
pub fn snap(&self, out: &mut Vec<u8>) {
let (width, height) = self.window.get_size();
self.snap_rect(out, 0, 0, width as usize, height as usize)
}
/// Read a section of pixels from the screen
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized
/// * `x, y, width, height` - the rectangle to capture
pub fn snap_rect(&self, out: &mut Vec<u8>, x: usize, y: usize, width: usize, height: usize) {
let size = (width * height * 3) as usize;
if out.len() < size {
let diff = size - out.len();
out.extend(repeat(0).take(diff));
}
else {
out.truncate(size)
}
// FIXME: this is _not_ the fastest way of doing this.
unsafe {
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::ReadPixels(x as i32, y as i32,
width as i32, height as i32,
gl::RGB,
gl::UNSIGNED_BYTE,
mem::transmute(&mut out[0]));
}
}
/// Get the current screen as an image
pub fn snap_image(&self) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = self.window.get_size();
let mut buf = Vec::new();
self.snap(&mut buf);
let img_opt = ImageBuffer::from_vec(width as u32, height as u32, buf);
let img = img_opt.expect("Buffer created from window was not big enough for image.");
imageops::flip_vertical(&img)
}
/// Gets the events manager that gives access to an event iterator.
pub fn events(&self) -> EventManager {
EventManager::new(self.events.clone(), self.unhandled_events.clone())
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline]
fn handle_events(&mut self, camera: &mut Option<&mut Camera>) {
let unhandled_events = self.unhandled_events.clone(); // FIXME: this is very ugly.
let events = self.events.clone(); // FIXME: this is very ugly
for event in unhandled_events.borrow().iter() {
self.handle_event(camera, event)
}
for event in glfw::flush_messages(&*events) {
self.handle_event(camera, &event.1)
}
unhandled_events.borrow_mut().clear();
self.glfw.poll_events();
}
fn handle_event(&mut self, camera: &mut Option<&mut Camera>, event: &WindowEvent) {
match *event {
WindowEvent::Key(Key::Escape, _, Action::Release, _) => {
self.close();
},
WindowEvent::FramebufferSize(w, h) => {
self.update_viewport(w as f32, h as f32);
},
_ => { }
}
match *camera {
Some(ref mut cam) => cam.handle_event(&self.window, event),
None => self.camera.borrow_mut().handle_event(&self.window, event)
}
}
/// Renders the scene using the default camera.
///
/// Returns `false` if the window should be closed.
pub fn render(&mut self) -> bool {
self.render_with(None, None)
}
/// Render using a specific post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_effect(&mut self, effect: &mut PostProcessingEffect) -> bool {
self.render_with(None, Some(effect))
}
/// Render using a specific camera.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera(&mut self, camera: &mut Camera) -> bool {
self.render_with(Some(camera), None)
}
/// Render using a specific camera and post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera_and_effect(&mut self, camera: &mut Camera, effect: &mut PostProcessingEffect) -> bool {
self.render_with(Some(camera), Some(effect))
}
/// Draws the scene with the given camera and post-processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with(&mut self,
camera: Option<&mut Camera>,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let mut camera = camera;
self.handle_events(&mut camera);
match camera {
Some(cam) => self.do_render_with(cam, post_processing),
None => {
let self_cam = self.camera.clone(); // FIXME: this is ugly.
let mut bself_cam = self_cam.borrow_mut();
self.do_render_with(&mut *bself_cam, post_processing)
}
}
}
fn do_render_with(&mut self,
camera: &mut Camera,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
// XXX: too bad we have to do this at each frame…
let w = self.width();
let h = self.height();
camera.handle_event(&self.window, &WindowEvent::FramebufferSize(w as i32, h as i32));
camera.update(&self.window);
match self.light_mode {
Light::StickToCamera => self.set_light(Light::StickToCamera),
_ => { }
}
let mut post_processing = post_processing;
if post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in 0usize.. camera.num_passes() {
camera.start_pass(pass, &self.window);
self.render_scene(camera, pass);
}
camera.render_complete(&self.window);
let (znear, zfar) = camera.clip_planes();
// FIXME: remove this completely?
// swatch off the wireframe mode for post processing and text rendering.
// if self.wireframe_mode {
// verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
// }
match post_processing {
Some(ref mut p) => {
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - self.curr_time) / 1000000; | {
self.scene.add_trimesh(descr, scale)
} | identifier_body |
window.rs |
/// This is the main interface with the 3d engine.
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_ms_per_frame: Option<u64>,
scene: SceneNode,
light_mode: Light, // FIXME: move that to the scene graph
background: Vec3<GLfloat>,
line_renderer: LineRenderer,
point_renderer: PointRenderer,
text_renderer: TextRenderer,
framebuffer_manager: FramebufferManager,
post_process_render_target: RenderTarget,
curr_time: u64,
camera: Rc<RefCell<ArcBall>>
}
impl Window {
/// Indicates whether this window should be closed.
#[inline]
pub fn should_close(&self) -> bool {
self.window.should_close()
}
/// Access the glfw context.
#[inline]
pub fn context<'r>(&'r self) -> &'r glfw::Glfw {
&self.glfw
}
/// Access the glfw window.
#[inline]
pub fn glfw_window(&self) -> &glfw::Window {
&self.window
}
/// Mutably access the glfw window.
#[inline]
pub fn glfw_window_mut(&mut self) -> &mut glfw::Window {
&mut self.window
}
/// The window width.
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The size of the window.
#[inline]
pub fn size(&self) -> Vec2<f32> {
let (w, h) = self.window.get_size();
Vec2::new(w as f32, h as f32)
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
#[inline]
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f!= 0); 1000 / f })
}
/// Set window title
pub fn set_title(&mut self, title: &str) {
self.window.set_title(title)
}
/// Closes the window.
#[inline]
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
#[inline]
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
#[inline]
pub fn show(&mut self) {
self.window.show()
}
/// Sets the background color.
#[inline]
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a point to be drawn during the next frame.
#[inline]
pub fn draw_point(&mut self, pt: &Pnt3<f32>, color: &Pnt3<f32>) {
self.point_renderer.draw_point(pt.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a string to be drawn during the next frame.
#[inline]
pub fn draw_text(&mut self, text: &str, pos: &Pnt2<f32>, font: &Rc<Font>, color: &Pnt3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, sn: &mut SceneNode) {
sn.unlink()
}
/// Adds a group to the scene.
///
/// A group is a node not containing any object.
pub fn add_group(&mut self) -> SceneNode {
self.scene.add_group()
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: Vec3<f32>) -> SceneNode {
self.scene.add_obj(path, mtl_dir, scale)
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Rc<RefCell<Mesh>>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_mesh(mesh, scale)
}
/// Creates and adds a new object using the geometry generated by a given procedural generator.
/// Creates and adds a new object using a mesh descriptor.
pub fn add_trimesh(&mut self, descr: TriMesh3<f32>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_trimesh(descr, scale)
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> SceneNode {
self.scene.add_cube(wx, wy, wz)
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn | (&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cone(r, h)
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cylinder(r, h)
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_capsule(r, h)
}
/// Adds a double-sided quad to the scene. The quad is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width.
/// * `h` - the quad height.
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`.
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`.
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, usubdivs: usize, vsubdivs: usize) -> SceneNode {
self.scene.add_quad(w, h, usubdivs, vsubdivs)
}
/// Adds a double-sided quad with the specified vertices.
pub fn add_quad_with_vertices(&mut self,
vertices: &[Pnt3<f32>],
nhpoints: usize,
nvpoints: usize)
-> SceneNode {
self.scene.add_quad_with_vertices(vertices, nhpoints, nvpoints)
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Returns whether this window is closed or not.
pub fn is_closed(&self) -> bool {
false // FIXME
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title.
/// * `width` - the window width.
/// * `height` - the window height.
pub fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height)
}
// FIXME: make this pub?
fn do_new(title: &str, hide: bool, width: u32, height: u32) -> Window {
// FIXME: glfw::set_error_callback(~ErrorCallback);
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
let (mut window, events) = glfw.create_window(width, height, title, WindowMode::Windowed).expect("Unable to open a glfw window.");
window.make_current();
verify!(gl::load_with(|name| window.get_proc_address(name) as *const _));
init_gl();
let mut usr_window = Window {
max_ms_per_frame: None,
glfw: glfw,
window: window,
events: Rc::new(events),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
scene: SceneNode::new_empty(),
light_mode: Light::Absolute(Pnt3::new(0.0, 10.0, 0.0)),
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
point_renderer: PointRenderer::new(),
text_renderer: TextRenderer::new(),
post_process_render_target: FramebufferManager::new_render_target(width as usize, height as usize),
framebuffer_manager: FramebufferManager::new(),
curr_time: time::precise_time_ns(),
camera: Rc::new(RefCell::new(ArcBall::new(Pnt3::new(0.0f32, 0.0, -1.0), na::orig())))
};
// setup callbacks
usr_window.window.set_framebuffer_size_polling(true);
usr_window.window.set_key_polling(true);
usr_window.window.set_mouse_button_polling(true);
usr_window.window.set_cursor_pos_polling(true);
usr_window.window.set_scroll_polling(true);
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
let light = usr_window.light_mode.clone();
usr_window.set_light(light);
usr_window
}
/// Reference to the scene associated with this window.
#[inline]
pub fn scene<'a>(&'a self) -> &'a SceneNode {
&self.scene
}
/// Mutable reference to the scene associated with this window.
#[inline]
pub fn scene_mut<'a>(&'a mut self) -> &'a mut SceneNode {
&mut self.scene
}
// FIXME: give more options for the snap size and offset.
/// Read the pixels currently displayed to the screen.
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized.
pub fn snap(&self, out: &mut Vec<u8>) {
let (width, height) = self.window.get_size();
self.snap_rect(out, 0, 0, width as usize, height as usize)
}
/// Read a section of pixels from the screen
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized
/// * `x, y, width, height` - the rectangle to capture
pub fn snap_rect(&self, out: &mut Vec<u8>, x: usize, y: usize, width: usize, height: usize) {
let size = (width * height * 3) as usize;
if out.len() < size {
let diff = size - out.len();
out.extend(repeat(0).take(diff));
}
else {
out.truncate(size)
}
// FIXME: this is _not_ the fastest way of doing this.
unsafe {
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::ReadPixels(x as i32, y as i32,
width as i32, height as i32,
gl::RGB,
gl::UNSIGNED_BYTE,
mem::transmute(&mut out[0]));
}
}
/// Get the current screen as an image
pub fn snap_image(&self) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = self.window.get_size();
let mut buf = Vec::new();
self.snap(&mut buf);
let img_opt = ImageBuffer::from_vec(width as u32, height as u32, buf);
let img = img_opt.expect("Buffer created from window was not big enough for image.");
imageops::flip_vertical(&img)
}
/// Gets the events manager that gives access to an event iterator.
pub fn events(&self) -> EventManager {
EventManager::new(self.events.clone(), self.unhandled_events.clone())
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline]
fn handle_events(&mut self, camera: &mut Option<&mut Camera>) {
let unhandled_events = self.unhandled_events.clone(); // FIXME: this is very ugly.
let events = self.events.clone(); // FIXME: this is very ugly
for event in unhandled_events.borrow().iter() {
self.handle_event(camera, event)
}
for event in glfw::flush_messages(&*events) {
self.handle_event(camera, &event.1)
}
unhandled_events.borrow_mut().clear();
self.glfw.poll_events();
}
fn handle_event(&mut self, camera: &mut Option<&mut Camera>, event: &WindowEvent) {
match *event {
WindowEvent::Key(Key::Escape, _, Action::Release, _) => {
self.close();
},
WindowEvent::FramebufferSize(w, h) => {
self.update_viewport(w as f32, h as f32);
},
_ => { }
}
match *camera {
Some(ref mut cam) => cam.handle_event(&self.window, event),
None => self.camera.borrow_mut().handle_event(&self.window, event)
}
}
/// Renders the scene using the default camera.
///
/// Returns `false` if the window should be closed.
pub fn render(&mut self) -> bool {
self.render_with(None, None)
}
/// Render using a specific post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_effect(&mut self, effect: &mut PostProcessingEffect) -> bool {
self.render_with(None, Some(effect))
}
/// Render using a specific camera.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera(&mut self, camera: &mut Camera) -> bool {
self.render_with(Some(camera), None)
}
/// Render using a specific camera and post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera_and_effect(&mut self, camera: &mut Camera, effect: &mut PostProcessingEffect) -> bool {
self.render_with(Some(camera), Some(effect))
}
/// Draws the scene with the given camera and post-processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with(&mut self,
camera: Option<&mut Camera>,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let mut camera = camera;
self.handle_events(&mut camera);
match camera {
Some(cam) => self.do_render_with(cam, post_processing),
None => {
let self_cam = self.camera.clone(); // FIXME: this is ugly.
let mut bself_cam = self_cam.borrow_mut();
self.do_render_with(&mut *bself_cam, post_processing)
}
}
}
fn do_render_with(&mut self,
camera: &mut Camera,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
// XXX: too bad we have to do this at each frame…
let w = self.width();
let h = self.height();
camera.handle_event(&self.window, &WindowEvent::FramebufferSize(w as i32, h as i32));
camera.update(&self.window);
match self.light_mode {
Light::StickToCamera => self.set_light(Light::StickToCamera),
_ => { }
}
let mut post_processing = post_processing;
if post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in 0usize.. camera.num_passes() {
camera.start_pass(pass, &self.window);
self.render_scene(camera, pass);
}
camera.render_complete(&self.window);
let (znear, zfar) = camera.clip_planes();
// FIXME: remove this completely?
// swatch off the wireframe mode for post processing and text rendering.
// if self.wireframe_mode {
// verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
// }
match post_processing {
Some(ref mut p) => {
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - self.curr_time) / 1000000; | add_sphere | identifier_name |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
use dataflow::channels::pushers::{Tee, Counter as PushCounter};
use dataflow::channels::pushers::buffer::{Buffer as PushBuffer, AutoflushSession};
use dataflow::operators::Capability;
use dataflow::operators::capability::mint as mint_capability;
use dataflow::{Stream, Scope};
/// Create a new `Stream` and `Handle` through which to supply input.
pub trait UnorderedInput<G: Scope> {
/// Create a new capability-based `Stream` and `Handle` through which to supply input. This
/// input supports multiple open epochs (timestamps) at the same time.
///
/// The `new_unordered_input` method returns `((Handle, Capability), Stream)` where the `Stream` can be used
/// immediately for timely dataflow construction, `Handle` and `Capability` are later used to introduce
/// data into the timely dataflow computation.
///
/// The `Capability` returned is for the default value of the timestamp type in use. The
/// capability can be dropped to inform the system that the input has advanced beyond the
/// capability's timestamp. To retain the ability to send, a new capability at a later timestamp
/// should be obtained first, via the `delayed` function for `Capability`.
///
/// To communicate the end-of-input drop all available capabilities.
///
/// #Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
///
/// use timely::*;
/// use timely::dataflow::operators::*;
/// use timely::dataflow::operators::capture::Extract;
/// use timely::dataflow::{Stream, Scope};
/// use timely::progress::timestamp::RootTimestamp;
///
/// // get send and recv endpoints, wrap send to share
/// let (send, recv) = ::std::sync::mpsc::channel();
/// let send = Arc::new(Mutex::new(send));
///
/// timely::execute(Configuration::Thread, move |root| {
///
/// // this is only to validate the output.
/// let send = send.lock().unwrap().clone();
///
/// // create and capture the unordered input.
/// let (mut input, mut cap) = root.scoped(|scope| {
/// let (input, stream) = scope.new_unordered_input();
/// stream.capture_into(send);
/// input
/// });
///
/// // feed values 0..10 at times 0..10.
/// for round in 0..10 {
/// input.session(cap.clone()).give(round);
/// cap = cap.delayed(&RootTimestamp::new(round + 1));
/// root.step();
/// }
/// }).unwrap();
///
/// let extract = recv.extract();
/// for i in 0..10 {
/// assert_eq!(extract[i], (RootTimestamp::new(i), vec![i]));
/// }
/// ```
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>);
}
impl<G: Scope> UnorderedInput<G> for G {
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>) {
let (output, registrar) = Tee::<G::Timestamp, D>::new();
let internal = Rc::new(RefCell::new(CountMap::new()));
let produced = Rc::new(RefCell::new(CountMap::new()));
let cap = mint_capability(Default::default(), internal.clone());
let helper = UnorderedHandle::new(PushCounter::new(output, produced.clone()));
let peers = self.peers();
let index = self.add_operator(UnorderedOperator {
internal: internal.clone(),
produced: produced.clone(),
peers: peers,
});
return ((helper, cap), Stream::new(Source { index: index, port: 0 }, registrar, self.clone()));
}
}
struct UnorderedOperator<T:Timestamp> {
internal: Rc<RefCell<CountMap<T>>>,
produced: Rc<RefCell<CountMap<T>>>,
peers: usize,
}
impl<T:Timestamp> Operate<T> for UnorderedOperator<T> {
fn name(&self) -> String { "Input".to_owned() }
fn inputs(&self) -> usize { 0 }
fn outputs(&self) -> usize { 1 }
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().iter() {
internal.update(time, count * (self.peers as i64 - 1));
}
// drain the changes to empty out, and complete the counts for internal.
self.internal.borrow_mut().drain_into(&mut internal);
(Vec::new(), vec![internal])
}
fn pull_internal_progress(&mut self,_consumed: &mut [CountMap<T>],
internal: &mut [CountMap<T>],
produced: &mut [CountMap<T>]) -> bool
{
self.produced.borrow_mut().drain_into(&mut produced[0]);
self.internal.borrow_mut().drain_into(&mut internal[0]);
return false;
}
fn notify_me(&self) -> bool { false }
}
/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct | <T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
/// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
}
}
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
}
| UnorderedHandle | identifier_name |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
use dataflow::channels::pushers::{Tee, Counter as PushCounter};
use dataflow::channels::pushers::buffer::{Buffer as PushBuffer, AutoflushSession};
use dataflow::operators::Capability;
use dataflow::operators::capability::mint as mint_capability;
use dataflow::{Stream, Scope};
/// Create a new `Stream` and `Handle` through which to supply input.
pub trait UnorderedInput<G: Scope> {
/// Create a new capability-based `Stream` and `Handle` through which to supply input. This
/// input supports multiple open epochs (timestamps) at the same time.
///
/// The `new_unordered_input` method returns `((Handle, Capability), Stream)` where the `Stream` can be used
/// immediately for timely dataflow construction, `Handle` and `Capability` are later used to introduce
/// data into the timely dataflow computation.
///
/// The `Capability` returned is for the default value of the timestamp type in use. The
/// capability can be dropped to inform the system that the input has advanced beyond the
/// capability's timestamp. To retain the ability to send, a new capability at a later timestamp
/// should be obtained first, via the `delayed` function for `Capability`.
///
/// To communicate the end-of-input drop all available capabilities.
///
/// #Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
///
/// use timely::*;
/// use timely::dataflow::operators::*;
/// use timely::dataflow::operators::capture::Extract;
/// use timely::dataflow::{Stream, Scope};
/// use timely::progress::timestamp::RootTimestamp;
///
/// // get send and recv endpoints, wrap send to share
/// let (send, recv) = ::std::sync::mpsc::channel();
/// let send = Arc::new(Mutex::new(send));
///
/// timely::execute(Configuration::Thread, move |root| {
///
/// // this is only to validate the output.
/// let send = send.lock().unwrap().clone();
///
/// // create and capture the unordered input.
/// let (mut input, mut cap) = root.scoped(|scope| {
/// let (input, stream) = scope.new_unordered_input();
/// stream.capture_into(send);
/// input
/// });
///
/// // feed values 0..10 at times 0..10.
/// for round in 0..10 {
/// input.session(cap.clone()).give(round);
/// cap = cap.delayed(&RootTimestamp::new(round + 1));
/// root.step();
/// }
/// }).unwrap();
///
/// let extract = recv.extract();
/// for i in 0..10 {
/// assert_eq!(extract[i], (RootTimestamp::new(i), vec![i]));
/// }
/// ```
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>);
}
impl<G: Scope> UnorderedInput<G> for G {
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>) {
let (output, registrar) = Tee::<G::Timestamp, D>::new();
let internal = Rc::new(RefCell::new(CountMap::new()));
let produced = Rc::new(RefCell::new(CountMap::new()));
let cap = mint_capability(Default::default(), internal.clone());
let helper = UnorderedHandle::new(PushCounter::new(output, produced.clone()));
let peers = self.peers();
let index = self.add_operator(UnorderedOperator {
internal: internal.clone(),
produced: produced.clone(),
peers: peers,
});
return ((helper, cap), Stream::new(Source { index: index, port: 0 }, registrar, self.clone()));
}
}
struct UnorderedOperator<T:Timestamp> {
internal: Rc<RefCell<CountMap<T>>>,
produced: Rc<RefCell<CountMap<T>>>,
peers: usize,
}
impl<T:Timestamp> Operate<T> for UnorderedOperator<T> {
fn name(&self) -> String { "Input".to_owned() }
fn inputs(&self) -> usize { 0 }
fn outputs(&self) -> usize |
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().iter() {
internal.update(time, count * (self.peers as i64 - 1));
}
// drain the changes to empty out, and complete the counts for internal.
self.internal.borrow_mut().drain_into(&mut internal);
(Vec::new(), vec![internal])
}
fn pull_internal_progress(&mut self,_consumed: &mut [CountMap<T>],
internal: &mut [CountMap<T>],
produced: &mut [CountMap<T>]) -> bool
{
self.produced.borrow_mut().drain_into(&mut produced[0]);
self.internal.borrow_mut().drain_into(&mut internal[0]);
return false;
}
fn notify_me(&self) -> bool { false }
}
/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct UnorderedHandle<T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
/// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
}
}
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
}
| { 1 } | identifier_body |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
use dataflow::channels::pushers::{Tee, Counter as PushCounter};
use dataflow::channels::pushers::buffer::{Buffer as PushBuffer, AutoflushSession};
use dataflow::operators::Capability;
use dataflow::operators::capability::mint as mint_capability;
use dataflow::{Stream, Scope};
/// Create a new `Stream` and `Handle` through which to supply input.
pub trait UnorderedInput<G: Scope> {
/// Create a new capability-based `Stream` and `Handle` through which to supply input. This
/// input supports multiple open epochs (timestamps) at the same time.
///
/// The `new_unordered_input` method returns `((Handle, Capability), Stream)` where the `Stream` can be used
/// immediately for timely dataflow construction, `Handle` and `Capability` are later used to introduce
/// data into the timely dataflow computation.
///
/// The `Capability` returned is for the default value of the timestamp type in use. The
/// capability can be dropped to inform the system that the input has advanced beyond the
/// capability's timestamp. To retain the ability to send, a new capability at a later timestamp
/// should be obtained first, via the `delayed` function for `Capability`.
///
/// To communicate the end-of-input drop all available capabilities.
///
/// #Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
///
/// use timely::*;
/// use timely::dataflow::operators::*;
/// use timely::dataflow::operators::capture::Extract;
/// use timely::dataflow::{Stream, Scope};
/// use timely::progress::timestamp::RootTimestamp;
///
/// // get send and recv endpoints, wrap send to share
/// let (send, recv) = ::std::sync::mpsc::channel();
/// let send = Arc::new(Mutex::new(send));
///
/// timely::execute(Configuration::Thread, move |root| {
///
/// // this is only to validate the output.
/// let send = send.lock().unwrap().clone();
///
/// // create and capture the unordered input.
/// let (mut input, mut cap) = root.scoped(|scope| {
/// let (input, stream) = scope.new_unordered_input();
/// stream.capture_into(send);
/// input
/// });
///
/// // feed values 0..10 at times 0..10.
/// for round in 0..10 {
/// input.session(cap.clone()).give(round);
/// cap = cap.delayed(&RootTimestamp::new(round + 1));
/// root.step();
/// }
/// }).unwrap();
///
/// let extract = recv.extract();
/// for i in 0..10 {
/// assert_eq!(extract[i], (RootTimestamp::new(i), vec![i]));
/// }
/// ```
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>);
}
impl<G: Scope> UnorderedInput<G> for G {
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>) {
let (output, registrar) = Tee::<G::Timestamp, D>::new();
let internal = Rc::new(RefCell::new(CountMap::new()));
let produced = Rc::new(RefCell::new(CountMap::new()));
let cap = mint_capability(Default::default(), internal.clone());
let helper = UnorderedHandle::new(PushCounter::new(output, produced.clone()));
let peers = self.peers();
let index = self.add_operator(UnorderedOperator {
internal: internal.clone(),
produced: produced.clone(),
peers: peers,
});
return ((helper, cap), Stream::new(Source { index: index, port: 0 }, registrar, self.clone()));
}
}
struct UnorderedOperator<T:Timestamp> {
internal: Rc<RefCell<CountMap<T>>>,
produced: Rc<RefCell<CountMap<T>>>,
peers: usize,
}
impl<T:Timestamp> Operate<T> for UnorderedOperator<T> {
fn name(&self) -> String { "Input".to_owned() }
fn inputs(&self) -> usize { 0 }
fn outputs(&self) -> usize { 1 }
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().iter() {
internal.update(time, count * (self.peers as i64 - 1));
}
// drain the changes to empty out, and complete the counts for internal.
self.internal.borrow_mut().drain_into(&mut internal);
(Vec::new(), vec![internal])
}
fn pull_internal_progress(&mut self,_consumed: &mut [CountMap<T>],
internal: &mut [CountMap<T>],
produced: &mut [CountMap<T>]) -> bool
{
self.produced.borrow_mut().drain_into(&mut produced[0]);
self.internal.borrow_mut().drain_into(&mut internal[0]);
return false;
}
fn notify_me(&self) -> bool { false }
}
/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct UnorderedHandle<T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
| }
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
} | /// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
} | random_line_split |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct Package {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> |
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>,
sources: RefCell<SourceMap<'cfg>>,
}
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() {
return Ok(pkg)
}
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
}
| {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
} | identifier_body |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct Package {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
}
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>, | }
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() {
return Ok(pkg)
}
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
} | sources: RefCell<SourceMap<'cfg>>, | random_line_split |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct | {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
}
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>,
sources: RefCell<SourceMap<'cfg>>,
}
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() {
return Ok(pkg)
}
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
}
| Package | identifier_name |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct Package {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
}
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>,
sources: RefCell<SourceMap<'cfg>>,
}
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() |
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
}
| {
return Ok(pkg)
} | conditional_block |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a non-threadsafe
// fn. To mitigate the race condition, wrap it in a Once struct.
pub fn init() {
INIT_ZSYS.call_once(|| {
unsafe { czmq_sys::zsys_init() };
});
}
/// Create a pipe, which consists of two PAIR sockets connected
/// over inproc.
pub fn create_pipe() -> Result<(ZSock, ZSock)> {
let mut backend_raw: *mut czmq_sys::zsock_t = ptr::null_mut();
let frontend_raw = unsafe { czmq_sys::zsys_create_pipe(&mut backend_raw) };
if frontend_raw == ptr::null_mut() {
Err(Error::new(ErrorKind::NullPtr, ZSysError::CreatePipe))
} else {
Ok(unsafe { (ZSock::from_raw(frontend_raw as *mut c_void, true), ZSock::from_raw(backend_raw as *mut c_void, true)) })
}
}
pub fn is_interrupted() -> bool {
unsafe { czmq_sys::zsys_interrupted == 1 }
}
}
#[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&self) -> &str {
match *self {
ZSysError::CreatePipe => "Could not create pipe",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_pipe() {
ZSys::init();
let (frontend, backend) = ZSys::create_pipe().unwrap();
frontend.send_str("I changed my iPod’s name to Titanic...now it’s syncing.").unwrap();
assert_eq!(backend.recv_str().unwrap().unwrap(), "I changed my iPod’s name to Titanic...now it’s syncing.");
backend.send_str("My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!").unwrap();
assert_eq!(frontend.recv_str().unwrap().unwrap(), "My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!");
}
#[test]
fn test_is_ | // This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
}
| interrupted() {
| identifier_name |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a non-threadsafe
// fn. To mitigate the race condition, wrap it in a Once struct.
pub fn init() {
INIT_ZSYS.call_once(|| {
unsafe { czmq_sys::zsys_init() };
});
}
/// Create a pipe, which consists of two PAIR sockets connected
/// over inproc.
pub fn create_pipe() -> Result<(ZSock, ZSock)> {
let mut backend_raw: *mut czmq_sys::zsock_t = ptr::null_mut();
let frontend_raw = unsafe { czmq_sys::zsys_create_pipe(&mut backend_raw) };
if frontend_raw == ptr::null_mut() {
Err(Error::new(ErrorKind::NullPtr, ZSysError::CreatePipe))
} else {
Ok(unsafe { (ZSock::from_raw(frontend_raw as *mut c_void, true), ZSock::from_raw(backend_raw as *mut c_void, true)) })
}
}
pub fn is_interrupted() -> bool { | #[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&self) -> &str {
match *self {
ZSysError::CreatePipe => "Could not create pipe",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_pipe() {
ZSys::init();
let (frontend, backend) = ZSys::create_pipe().unwrap();
frontend.send_str("I changed my iPod’s name to Titanic...now it’s syncing.").unwrap();
assert_eq!(backend.recv_str().unwrap().unwrap(), "I changed my iPod’s name to Titanic...now it’s syncing.");
backend.send_str("My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!").unwrap();
assert_eq!(frontend.recv_str().unwrap().unwrap(), "My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!");
}
#[test]
fn test_is_interrupted() {
// This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
} | unsafe { czmq_sys::zsys_interrupted == 1 }
}
}
| random_line_split |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a non-threadsafe
// fn. To mitigate the race condition, wrap it in a Once struct.
pub fn init() {
INIT_ZSYS.call_once(|| {
unsafe { czmq_sys::zsys_init() };
});
}
/// Create a pipe, which consists of two PAIR sockets connected
/// over inproc.
pub fn create_pipe() -> Result<(ZSock, ZSock)> {
let mut backend_raw: *mut czmq_sys::zsock_t = ptr::null_mut();
let frontend_raw = unsafe { czmq_sys::zsys_create_pipe(&mut backend_raw) };
if frontend_raw == ptr::null_mut() {
Err(Error::new(ErrorKind::NullPtr, ZSysError::CreatePipe))
} else {
Ok(unsafe { (ZSock::from_raw(frontend_raw as *mut c_void, true), ZSock::from_raw(backend_raw as *mut c_void, true)) })
}
}
pub fn is_interrupted() -> bool |
}
#[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&self) -> &str {
match *self {
ZSysError::CreatePipe => "Could not create pipe",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_pipe() {
ZSys::init();
let (frontend, backend) = ZSys::create_pipe().unwrap();
frontend.send_str("I changed my iPod’s name to Titanic...now it’s syncing.").unwrap();
assert_eq!(backend.recv_str().unwrap().unwrap(), "I changed my iPod’s name to Titanic...now it’s syncing.");
backend.send_str("My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!").unwrap();
assert_eq!(frontend.recv_str().unwrap().unwrap(), "My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!");
}
#[test]
fn test_is_interrupted() {
// This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
}
| {
unsafe { czmq_sys::zsys_interrupted == 1 }
} | identifier_body |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library.
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn main() | {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", hasher.result_str(), fname);
}
} | identifier_body |
|
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library.
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn | () {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", hasher.result_str(), fname);
}
}
| main | identifier_name |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
|
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn main() {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", hasher.result_str(), fname);
}
} | // This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library. | random_line_split |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use ast;
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) | // #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("u64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("u64", c, s, sub)
}),
})
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
let n = match substr.nonself_args {
[n] => n,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(FromPrimitive)`")
};
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in enum_def.variants.iter() {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let variant = cx.expr_ident(span, variant.node.name);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant, ty);
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n, arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in deriving(FromPrimitive)")
}
}
| {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)), | identifier_body |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use ast;
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn | (cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("u64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("u64", c, s, sub)
}),
})
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
let n = match substr.nonself_args {
[n] => n,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(FromPrimitive)`")
};
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in enum_def.variants.iter() {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let variant = cx.expr_ident(span, variant.node.name);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant, ty);
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n, arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in deriving(FromPrimitive)")
}
}
| expand_deriving_from_primitive | identifier_name |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use ast;
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(), | MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("u64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("u64", c, s, sub)
}),
})
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
let n = match substr.nonself_args {
[n] => n,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(FromPrimitive)`")
};
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in enum_def.variants.iter() {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let variant = cx.expr_ident(span, variant.node.name);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant, ty);
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n, arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in deriving(FromPrimitive)")
}
} | methods: vec!( | random_line_split |
sync.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.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if!guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 &&!waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn drop_port(&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap!= 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else {
Vec::new()
};
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> |
}
| {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
} | identifier_body |
sync.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.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if!guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 &&!waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn drop_port(&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap!= 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else {
Vec::new()
};
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else { | BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
}
} | match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(), | random_line_split |
sync.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.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if!guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 &&!waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn drop_port(&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap!= 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else | ;
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
}
}
| {
Vec::new()
} | conditional_block |
sync.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.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if!guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 &&!waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn | (&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap!= 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else {
Vec::new()
};
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
}
}
| drop_port | identifier_name |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune
Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR,
vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag;
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn | <'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 { return None }
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
}
| shift_mut_ref | identifier_name |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune
Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR,
vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) |
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn shift_mut_ref<'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 { return None }
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
}
| {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag; | identifier_body |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune | vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag;
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn shift_mut_ref<'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 { return None }
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
} | Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR, | random_line_split |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune
Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR,
vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag;
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn shift_mut_ref<'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 |
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
}
| { return None } | conditional_block |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn new(ip: String, date: String, req: String, code: i32, size: i32, referer: String, agent: String) -> Weblog {
Weblog { ip: ip, date: date, req: req, code: code, size: size, referer: referer, agent: agent }
}
}
impl Eq for Weblog {}
impl PartialEq for Weblog {
fn eq(&self, other: &Self) -> bool {
self.ip == other.ip && self.date == other.date
}
}
impl fmt::Display for Weblog {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
| {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
} | identifier_body |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn | (ip: String, date: String, req: String, code: i32, size: i32, referer: String, agent: String) -> Weblog {
Weblog { ip: ip, date: date, req: req, code: code, size: size, referer: referer, agent: agent }
}
}
impl Eq for Weblog {}
impl PartialEq for Weblog {
fn eq(&self, other: &Self) -> bool {
self.ip == other.ip && self.date == other.date
}
}
impl fmt::Display for Weblog {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
}
}
| new | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.