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};
#[cfg(not(target_os = "netbsd"))]
use std::os::raw::{c_int, c_short};
use std::os::unix::io::AsRawFd;
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_imp::{self as event, Event};
use sys::unix::{cvt, UnixReady};
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;
#[cfg(not(target_os = "netbsd"))]
type Filter = c_short;
#[cfg(not(target_os = "netbsd"))]
type UData = *mut ::libc::c_void;
#[cfg(not(target_os = "netbsd"))]
type Count = c_int;
#[cfg(target_os = "netbsd")]
type Filter = u32;
#[cfg(target_os = "netbsd")]
type UData = ::libc::intptr_t;
#[cfg(target_os = "netbsd")]
type Count = usize;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter as Filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as UData,
}
}
}
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 { 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 = cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
evts.sys_events.0.capacity() as Count,
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)),
];
cvt(libc::kevent(self.kq,
changes.as_ptr(),
changes.len() as Count,
changes.as_mut_ptr(),
changes.len() as Count,
::std::ptr::null()))?;
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
// Test to see if an error happened
if change.data == 0 {
continue
}
// Older versions of OSX (10.11 and 10.10 have been witnessed)
// can return EPIPE when registering a pipe file descriptor
// where the other end has already disappeared. For example code
// that creates a pipe, closes a file descriptor, and then
// registers the other end will see an EPIPE returned from
// `register`.
//
// It also turns out that kevent will still report events on the
// file descriptor, telling us that it's readable/hup at least
// after we've done this registration. As a result we just
// ignore `EPIPE` here instead of propagating it.
//
// More info can be found at carllerche/mio#582
if change.data as i32 == libc::EPIPE &&
change.filter == libc::EVFILT_WRITE as Filter {
continue
}
// ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ as Filter { r } else { w };
if change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE!= 0 {
continue
}
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;
#[cfg(not(target_os = "netbsd"))]
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
#[cfg(target_os = "netbsd")]
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, 0),
kevent!(fd, libc::EVFILT_WRITE, filter, 0),
];
cvt(libc::kevent(self.kq,
changes.as_ptr(),
changes.len() as Count,
changes.as_mut_ptr(),
changes.len() as Count,
::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 AsRawFd for Selector {
fn as_raw_fd(&self) -> RawFd {
self.kq
}
|
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::empty(), token));
}
if e.flags & libc::EV_ERROR!= 0 {
event::kind_mut(&mut self.events[idx]).insert(*UnixReady::error());
}
if e.filter == libc::EVFILT_READ as Filter {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE as Filter {
event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
#[cfg(any(target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos"))]
{
if e.filter == libc::EVFILT_AIO {
event::kind_mut(&mut self.events[idx]).insert(UnixReady::aio());
}
}
if e.flags & libc::EV_EOF!= 0 {
event::kind_mut(&mut self.events[idx]).insert(UnixReady::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(UnixReady::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 {
fmt.debug_struct("Events")
.field("len", &self.sys_events.0.len())
.finish()
}
}
#[test]
fn does_not_register_rw() {
use {Poll, Ready, PollOpt, Token};
use unix::EventedFd;
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let poll = Poll::new().unwrap();
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
poll.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
}
#[cfg(any(target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos"))]
#[test]
fn test_coalesce_aio() {
let mut events = Events::with_capacity(1);
events.sys_events.0.push(kevent!(0x1234, libc::EVFILT_AIO, 0, 42));
events.coalesce(Token(0));
assert!(events.events[0].readiness() == UnixReady::aio().into());
assert!(events.events[0].token() == Token(42));
}
|
}
impl Drop for Selector {
fn drop(&mut self) {
|
random_line_split
|
kqueue.rs
|
use std::{cmp, fmt, ptr};
#[cfg(not(target_os = "netbsd"))]
use std::os::raw::{c_int, c_short};
use std::os::unix::io::AsRawFd;
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_imp::{self as event, Event};
use sys::unix::{cvt, UnixReady};
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;
#[cfg(not(target_os = "netbsd"))]
type Filter = c_short;
#[cfg(not(target_os = "netbsd"))]
type UData = *mut ::libc::c_void;
#[cfg(not(target_os = "netbsd"))]
type Count = c_int;
#[cfg(target_os = "netbsd")]
type Filter = u32;
#[cfg(target_os = "netbsd")]
type UData = ::libc::intptr_t;
#[cfg(target_os = "netbsd")]
type Count = usize;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter as Filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as UData,
}
}
}
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 { 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 = cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
evts.sys_events.0.capacity() as Count,
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)),
];
cvt(libc::kevent(self.kq,
changes.as_ptr(),
changes.len() as Count,
changes.as_mut_ptr(),
changes.len() as Count,
::std::ptr::null()))?;
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
// Test to see if an error happened
if change.data == 0 {
continue
}
// Older versions of OSX (10.11 and 10.10 have been witnessed)
// can return EPIPE when registering a pipe file descriptor
// where the other end has already disappeared. For example code
// that creates a pipe, closes a file descriptor, and then
// registers the other end will see an EPIPE returned from
// `register`.
//
// It also turns out that kevent will still report events on the
// file descriptor, telling us that it's readable/hup at least
// after we've done this registration. As a result we just
// ignore `EPIPE` here instead of propagating it.
//
// More info can be found at carllerche/mio#582
if change.data as i32 == libc::EPIPE &&
change.filter == libc::EVFILT_WRITE as Filter {
continue
}
// ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ as Filter { r } else { w };
if change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE!= 0 {
continue
}
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;
#[cfg(not(target_os = "netbsd"))]
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
#[cfg(target_os = "netbsd")]
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, 0),
kevent!(fd, libc::EVFILT_WRITE, filter, 0),
];
cvt(libc::kevent(self.kq,
changes.as_ptr(),
changes.len() as Count,
changes.as_mut_ptr(),
changes.len() as Count,
::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 AsRawFd for Selector {
fn as_raw_fd(&self) -> RawFd {
self.kq
}
}
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
|
(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::empty(), token));
}
if e.flags & libc::EV_ERROR!= 0 {
event::kind_mut(&mut self.events[idx]).insert(*UnixReady::error());
}
if e.filter == libc::EVFILT_READ as Filter {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE as Filter {
event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
#[cfg(any(target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos"))]
{
if e.filter == libc::EVFILT_AIO {
event::kind_mut(&mut self.events[idx]).insert(UnixReady::aio());
}
}
if e.flags & libc::EV_EOF!= 0 {
event::kind_mut(&mut self.events[idx]).insert(UnixReady::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(UnixReady::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 {
fmt.debug_struct("Events")
.field("len", &self.sys_events.0.len())
.finish()
}
}
#[test]
fn does_not_register_rw() {
use {Poll, Ready, PollOpt, Token};
use unix::EventedFd;
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let poll = Poll::new().unwrap();
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
poll.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
}
#[cfg(any(target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos"))]
#[test]
fn test_coalesce_aio() {
let mut events = Events::with_capacity(1);
events.sys_events.0.push(kevent!(0x1234, libc::EVFILT_AIO, 0, 42));
events.coalesce(Token(0));
assert!(events.events[0].readiness() == UnixReady::aio().into());
assert!(events.events[0].token() == Token(42));
}
|
KeventList
|
identifier_name
|
snoop.rs
|
//! Snoop plugin that exposes metrics on a local socket.
use errors::*;
use plugin::*;
use metric::*;
use std::collections::HashMap;
use std::sync::{Mutex, Arc};
use std::net::SocketAddr;
use tokio_io::{io, AsyncRead};
use tokio_core::net;
use futures::{sync, Future};
use futures::stream::Stream;
use std::convert::AsRef;
use std::fmt;
use serde_json;
#[derive(Deserialize, Debug)]
struct SnoopInputConfig {
bind: Option<SocketAddr>,
}
#[derive(Debug)]
struct SnoopOutput {}
fn report_and_discard<E: fmt::Display>(e: E) -> () {
info!("An error occured: {}", e);
}
type Sender = sync::mpsc::UnboundedSender<Message>;
impl Output for SnoopOutput {
fn setup(&self, ctx: PluginContext) -> Result<Box<OutputInstance>> {
let config: SnoopInputConfig = ctx.decode_config()?;
let ref mut core = ctx.core.try_borrow_mut()?;
let default_addr = "127.0.0.1:8080".parse::<SocketAddr>().map_err(|e| {
ErrorKind::Message(e.to_string())
})?;
let addr = config.bind.unwrap_or(default_addr);
let handle = core.handle();
let socket = net::TcpListener::bind(&addr, &handle)?;
let connections: Arc<Mutex<HashMap<SocketAddr, Sender>>> =
Arc::new(Mutex::new(HashMap::new()));
let hello_connections = connections.clone();
let accept = socket.incoming().map_err(report_and_discard).for_each(
move |(socket, addr)| {
info!("connect: {}", addr);
let (tx, rx) = sync::mpsc::unbounded();
let (reader, writer) = socket.split();
hello_connections
.lock()
.map_err(report_and_discard)?
.insert(addr, tx);
let socket_writer = rx.fold(writer, |writer, msg| {
let amt = io::write_all(writer, msg);
amt.map(|(writer, _m)| writer).map_err(report_and_discard)
}).map(|_| ());
let bye_connections = hello_connections.clone();
// read one byte, bur more importantly the future will be notified on disconnects.
// TODO: this has the side-effect that anything written by the client will cause it
// to be immediately disconnected.
let reader = io::read_exact(reader, vec![0; 1]).map(|_| ()).map_err(
report_and_discard,
);
let conn = reader.select(socket_writer);
handle.spawn(conn.then(move |_| {
info!("disconnect: {}", addr);
bye_connections.lock().map_err(report_and_discard)?.remove(
&addr,
);
Ok(())
}));
Ok(())
},
);
core.handle().spawn(accept);
Ok(Box::new(SnoopOutputInstance {
id: ctx.id.clone(),
connections: connections.clone(),
}))
}
}
struct SnoopOutputInstance {
id: String,
connections: Arc<Mutex<HashMap<SocketAddr, Sender>>>,
}
#[derive(Serialize)]
struct SerializedOutput<'a> {
plugin_id: &'a String,
metric_id: &'a MetricId,
value: &'a f64,
}
impl OutputInstance for SnoopOutputInstance {
fn feed(&self, sample: &Sample) -> Result<()> {
let mut c = self.connections.lock()?;
// serialize a single output message
let bytes = {
let serialized = SerializedOutput {
plugin_id: &self.id,
metric_id: &sample.metric_id,
value: &sample.value,
};
let mut bytes: Vec<u8> = serde_json::to_string(&serialized)?.into_bytes();
bytes.push('\n' as u8);
bytes
};
// put in ref-counted data structure to avoid copying to all connections.
let out = Message(Arc::new(bytes.into_boxed_slice()));
for (_addr, tx) in c.iter_mut() {
let _r = tx.unbounded_send(out.clone()).map_err(|_| {
ErrorKind::Message("failed to feed".to_owned())
})?;
}
Ok(())
}
}
pub fn
|
() -> Result<Box<Output>> {
Ok(Box::new(SnoopOutput {}))
}
#[derive(Clone)]
pub struct Message(Arc<Box<[u8]>>);
impl AsRef<[u8]> for Message {
fn as_ref(&self) -> &[u8] {
let &Message(ref a) = self;
&a
}
}
|
output
|
identifier_name
|
snoop.rs
|
//! Snoop plugin that exposes metrics on a local socket.
use errors::*;
use plugin::*;
use metric::*;
use std::collections::HashMap;
|
use futures::stream::Stream;
use std::convert::AsRef;
use std::fmt;
use serde_json;
#[derive(Deserialize, Debug)]
struct SnoopInputConfig {
bind: Option<SocketAddr>,
}
#[derive(Debug)]
struct SnoopOutput {}
fn report_and_discard<E: fmt::Display>(e: E) -> () {
info!("An error occured: {}", e);
}
type Sender = sync::mpsc::UnboundedSender<Message>;
impl Output for SnoopOutput {
fn setup(&self, ctx: PluginContext) -> Result<Box<OutputInstance>> {
let config: SnoopInputConfig = ctx.decode_config()?;
let ref mut core = ctx.core.try_borrow_mut()?;
let default_addr = "127.0.0.1:8080".parse::<SocketAddr>().map_err(|e| {
ErrorKind::Message(e.to_string())
})?;
let addr = config.bind.unwrap_or(default_addr);
let handle = core.handle();
let socket = net::TcpListener::bind(&addr, &handle)?;
let connections: Arc<Mutex<HashMap<SocketAddr, Sender>>> =
Arc::new(Mutex::new(HashMap::new()));
let hello_connections = connections.clone();
let accept = socket.incoming().map_err(report_and_discard).for_each(
move |(socket, addr)| {
info!("connect: {}", addr);
let (tx, rx) = sync::mpsc::unbounded();
let (reader, writer) = socket.split();
hello_connections
.lock()
.map_err(report_and_discard)?
.insert(addr, tx);
let socket_writer = rx.fold(writer, |writer, msg| {
let amt = io::write_all(writer, msg);
amt.map(|(writer, _m)| writer).map_err(report_and_discard)
}).map(|_| ());
let bye_connections = hello_connections.clone();
// read one byte, bur more importantly the future will be notified on disconnects.
// TODO: this has the side-effect that anything written by the client will cause it
// to be immediately disconnected.
let reader = io::read_exact(reader, vec![0; 1]).map(|_| ()).map_err(
report_and_discard,
);
let conn = reader.select(socket_writer);
handle.spawn(conn.then(move |_| {
info!("disconnect: {}", addr);
bye_connections.lock().map_err(report_and_discard)?.remove(
&addr,
);
Ok(())
}));
Ok(())
},
);
core.handle().spawn(accept);
Ok(Box::new(SnoopOutputInstance {
id: ctx.id.clone(),
connections: connections.clone(),
}))
}
}
struct SnoopOutputInstance {
id: String,
connections: Arc<Mutex<HashMap<SocketAddr, Sender>>>,
}
#[derive(Serialize)]
struct SerializedOutput<'a> {
plugin_id: &'a String,
metric_id: &'a MetricId,
value: &'a f64,
}
impl OutputInstance for SnoopOutputInstance {
fn feed(&self, sample: &Sample) -> Result<()> {
let mut c = self.connections.lock()?;
// serialize a single output message
let bytes = {
let serialized = SerializedOutput {
plugin_id: &self.id,
metric_id: &sample.metric_id,
value: &sample.value,
};
let mut bytes: Vec<u8> = serde_json::to_string(&serialized)?.into_bytes();
bytes.push('\n' as u8);
bytes
};
// put in ref-counted data structure to avoid copying to all connections.
let out = Message(Arc::new(bytes.into_boxed_slice()));
for (_addr, tx) in c.iter_mut() {
let _r = tx.unbounded_send(out.clone()).map_err(|_| {
ErrorKind::Message("failed to feed".to_owned())
})?;
}
Ok(())
}
}
pub fn output() -> Result<Box<Output>> {
Ok(Box::new(SnoopOutput {}))
}
#[derive(Clone)]
pub struct Message(Arc<Box<[u8]>>);
impl AsRef<[u8]> for Message {
fn as_ref(&self) -> &[u8] {
let &Message(ref a) = self;
&a
}
}
|
use std::sync::{Mutex, Arc};
use std::net::SocketAddr;
use tokio_io::{io, AsyncRead};
use tokio_core::net;
use futures::{sync, Future};
|
random_line_split
|
runtime.rs
|
#[cfg(windows)]
mod os
{
#[cfg(windows)]
#[link(name = "ole32")]
extern "system" {
#[doc(hidden)]
pub fn CoInitializeEx(
reserved: *const ::std::os::raw::c_void,
init: u32,
) -> crate::raw::HRESULT;
#[doc(hidden)]
pub fn CoUninitialize();
}
pub fn initialize() -> crate::raw::HRESULT
{
unsafe {
let hr = CoInitializeEx(::std::ptr::null(), 2 /* APARTMENTTHREADED */);
match hr {
crate::raw::S_FALSE => crate::raw::S_OK,
other => other,
}
}
}
pub fn uninitialize()
{
unsafe {
CoUninitialize();
}
}
}
#[cfg(not(windows))]
mod os
{
pub fn initialize() -> crate::raw::HRESULT
{
crate::raw::S_OK
}
pub fn uninitialize()
|
}
pub fn initialize() -> crate::RawComResult<()>
{
match os::initialize() {
crate::raw::S_OK => Ok(()),
e => Err(e),
}
}
pub fn uninitialize()
{
os::uninitialize();
}
|
{}
|
identifier_body
|
runtime.rs
|
#[cfg(windows)]
mod os
{
#[cfg(windows)]
#[link(name = "ole32")]
extern "system" {
#[doc(hidden)]
pub fn CoInitializeEx(
reserved: *const ::std::os::raw::c_void,
init: u32,
) -> crate::raw::HRESULT;
#[doc(hidden)]
pub fn CoUninitialize();
}
pub fn initialize() -> crate::raw::HRESULT
{
unsafe {
let hr = CoInitializeEx(::std::ptr::null(), 2 /* APARTMENTTHREADED */);
match hr {
crate::raw::S_FALSE => crate::raw::S_OK,
other => other,
}
}
}
pub fn uninitialize()
{
unsafe {
CoUninitialize();
}
}
}
#[cfg(not(windows))]
mod os
{
pub fn initialize() -> crate::raw::HRESULT
{
crate::raw::S_OK
}
pub fn
|
() {}
}
pub fn initialize() -> crate::RawComResult<()>
{
match os::initialize() {
crate::raw::S_OK => Ok(()),
e => Err(e),
}
}
pub fn uninitialize()
{
os::uninitialize();
}
|
uninitialize
|
identifier_name
|
runtime.rs
|
#[cfg(windows)]
mod os
{
#[cfg(windows)]
#[link(name = "ole32")]
extern "system" {
#[doc(hidden)]
pub fn CoInitializeEx(
reserved: *const ::std::os::raw::c_void,
init: u32,
) -> crate::raw::HRESULT;
#[doc(hidden)]
pub fn CoUninitialize();
}
pub fn initialize() -> crate::raw::HRESULT
{
unsafe {
let hr = CoInitializeEx(::std::ptr::null(), 2 /* APARTMENTTHREADED */);
match hr {
crate::raw::S_FALSE => crate::raw::S_OK,
other => other,
}
}
}
pub fn uninitialize()
{
unsafe {
CoUninitialize();
}
}
}
#[cfg(not(windows))]
mod os
{
pub fn initialize() -> crate::raw::HRESULT
{
crate::raw::S_OK
|
}
pub fn uninitialize() {}
}
pub fn initialize() -> crate::RawComResult<()>
{
match os::initialize() {
crate::raw::S_OK => Ok(()),
e => Err(e),
}
}
pub fn uninitialize()
{
os::uninitialize();
}
|
random_line_split
|
|
lib.rs
|
#[macro_use]
extern crate error_chain;
// We'll put our errors in an `errors` module, and other modules in
// this crate will `use errors::*;` to get access to everything
// `error_chain!` creates.
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain!{}
}
use errors::*;
pub fn
|
<T: AsRef<str>>(digits: T, length: usize) -> Result<u64> {
let digits = digits.as_ref();
if digits.len() < length {
bail!("The digits string must at least be {} characters in size but was only {}",
length,
digits.len());
}
let mut new_digits = Vec::with_capacity(digits.len());
for c in digits.chars() {
new_digits.push(char_to_digit(c).chain_err(|| "Cannot convert string to int array")? as u64)
}
let mut max_value = 0;
for start_index in 0..(new_digits.len() - length + 1) {
let tmp_value = new_digits[start_index..(start_index + length)].iter().product();
if tmp_value > max_value {
max_value = tmp_value
};
}
Ok(max_value)
}
fn char_to_digit(c: char) -> Result<u8> {
match c {
'0'...'9' => Ok(c as u8 - '0' as u8),
_ => bail!("'{}' is not a digit"),
}
}
|
lsp
|
identifier_name
|
lib.rs
|
#[macro_use]
extern crate error_chain;
// We'll put our errors in an `errors` module, and other modules in
// this crate will `use errors::*;` to get access to everything
// `error_chain!` creates.
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain!{}
}
use errors::*;
pub fn lsp<T: AsRef<str>>(digits: T, length: usize) -> Result<u64> {
let digits = digits.as_ref();
if digits.len() < length {
bail!("The digits string must at least be {} characters in size but was only {}",
length,
digits.len());
}
let mut new_digits = Vec::with_capacity(digits.len());
for c in digits.chars() {
new_digits.push(char_to_digit(c).chain_err(|| "Cannot convert string to int array")? as u64)
}
let mut max_value = 0;
for start_index in 0..(new_digits.len() - length + 1) {
let tmp_value = new_digits[start_index..(start_index + length)].iter().product();
if tmp_value > max_value {
max_value = tmp_value
};
}
Ok(max_value)
}
fn char_to_digit(c: char) -> Result<u8>
|
{
match c {
'0'...'9' => Ok(c as u8 - '0' as u8),
_ => bail!("'{}' is not a digit"),
}
}
|
identifier_body
|
|
lib.rs
|
#[macro_use]
extern crate error_chain;
// We'll put our errors in an `errors` module, and other modules in
// this crate will `use errors::*;` to get access to everything
// `error_chain!` creates.
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain!{}
}
use errors::*;
pub fn lsp<T: AsRef<str>>(digits: T, length: usize) -> Result<u64> {
let digits = digits.as_ref();
if digits.len() < length {
bail!("The digits string must at least be {} characters in size but was only {}",
length,
digits.len());
}
let mut new_digits = Vec::with_capacity(digits.len());
for c in digits.chars() {
new_digits.push(char_to_digit(c).chain_err(|| "Cannot convert string to int array")? as u64)
}
let mut max_value = 0;
for start_index in 0..(new_digits.len() - length + 1) {
let tmp_value = new_digits[start_index..(start_index + length)].iter().product();
if tmp_value > max_value {
max_value = tmp_value
};
}
Ok(max_value)
}
|
_ => bail!("'{}' is not a digit"),
}
}
|
fn char_to_digit(c: char) -> Result<u8> {
match c {
'0'...'9' => Ok(c as u8 - '0' as u8),
|
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/. */
//! The implementation of the DOM.
//!
//! The DOM is comprised of interfaces (defined by specifications using
//! [WebIDL](https://heycam.github.io/webidl/)) that are implemented as Rust
//! structs in submodules of this module. Its implementation is documented
//! below.
//!
//! A DOM object and its reflector
//! ==============================
//!
//! The implementation of an interface `Foo` in Servo's DOM involves two
//! related but distinct objects:
//!
//! * the **DOM object**: an instance of the Rust struct `dom::foo::Foo`
//! (marked with the `#[dom_struct]` attribute) on the Rust heap;
//! * the **reflector**: a `JSObject` allocated by SpiderMonkey, that owns the
//! DOM object.
//!
//! Memory management
//! =================
//!
//! Reflectors of DOM objects, and thus the DOM objects themselves, are managed
//! by the SpiderMonkey Garbage Collector. Thus, keeping alive a DOM object
//! is done through its reflector.
//!
//! For more information, see:
//!
//! * rooting pointers on the stack:
//! the [`Root`](bindings/root/struct.Root.html) smart pointer;
//! * tracing pointers in member fields: the [`Dom`](bindings/root/struct.Dom.html),
//! [`MutNullableDom`](bindings/root/struct.MutNullableDom.html) and
//! [`MutDom`](bindings/root/struct.MutDom.html) smart pointers and
//! [the tracing implementation](bindings/trace/index.html);
//! * rooting pointers from across thread boundaries or in channels: the
//! [`Trusted`](bindings/refcounted/struct.Trusted.html) smart pointer;
//!
//! Inheritance
//! ===========
//!
//! Rust does not support struct inheritance, as would be used for the
//! object-oriented DOM APIs. To work around this issue, Servo stores an
//! instance of the superclass in the first field of its subclasses. (Note that
//! it is stored by value, rather than in a smart pointer such as `Dom<T>`.)
//!
//! This implies that a pointer to an object can safely be cast to a pointer
//! to all its classes.
//!
//! This invariant is enforced by the lint in
//! `plugins::lints::inheritance_integrity`.
//!
//! Interfaces which either derive from or are derived by other interfaces
|
//! and check whether a given instance is of a given type.
//!
//! ```ignore
//! use dom::bindings::inheritance::Castable;
//! use dom::element::Element;
//! use dom::htmlelement::HTMLElement;
//! use dom::htmlinputelement::HTMLInputElement;
//!
//! if let Some(elem) = node.downcast::<Element> {
//! if elem.is::<HTMLInputElement>() {
//! return elem.upcast::<HTMLElement>();
//! }
//! }
//! ```
//!
//! Furthermore, when discriminating a given instance against multiple
//! interface types, code generation provides a convenient TypeId enum
//! which can be used to write `match` expressions instead of multiple
//! calls to `Castable::is::<T>`. The `type_id()` method of an instance is
//! provided by the farthest interface it derives from, e.g. `EventTarget`
//! for `HTMLMediaElement`. For convenience, that method is also provided
//! on the `Node` interface to avoid unnecessary upcasts to `EventTarget`.
//!
//! ```ignore
//! use dom::bindings::inheritance::{EventTargetTypeId, NodeTypeId};
//!
//! match *node.type_id() {
//! EventTargetTypeId::Node(NodeTypeId::CharacterData(_)) =>...,
//! EventTargetTypeId::Node(NodeTypeId::Element(_)) =>...,
//! ...,
//! }
//! ```
//!
//! Construction
//! ============
//!
//! DOM objects of type `T` in Servo have two constructors:
//!
//! * a `T::new_inherited` static method that returns a plain `T`, and
//! * a `T::new` static method that returns `DomRoot<T>`.
//!
//! (The result of either method can be wrapped in `Result`, if that is
//! appropriate for the type in question.)
//!
//! The latter calls the former, boxes the result, and creates a reflector
//! corresponding to it by calling `dom::bindings::utils::reflect_dom_object`
//! (which yields ownership of the object to the SpiderMonkey Garbage Collector).
//! This is the API to use when creating a DOM object.
//!
//! The former should only be called by the latter, and by subclasses'
//! `new_inherited` methods.
//!
//! DOM object constructors in JavaScript correspond to a `T::Constructor`
//! static method. This method is always fallible.
//!
//! Destruction
//! ===========
//!
//! When the SpiderMonkey Garbage Collector discovers that the reflector of a
//! DOM object is garbage, it calls the reflector's finalization hook. This
//! function deletes the reflector's DOM object, calling its destructor in the
//! process.
//!
//! Mutability and aliasing
//! =======================
//!
//! Reflectors are JavaScript objects, and as such can be freely aliased. As
//! Rust does not allow mutable aliasing, mutable borrows of DOM objects are
//! not allowed. In particular, any mutable fields use `Cell` or `DomRefCell`
//! to manage their mutability.
//!
//! `Reflector` and `DomObject`
//! =============================
//!
//! Every DOM object has a `Reflector` as its first (transitive) member field.
//! This contains a `*mut JSObject` that points to its reflector.
//!
//! The `FooBinding::Wrap` function creates the reflector, stores a pointer to
//! the DOM object in the reflector, and initializes the pointer to the reflector
//! in the `Reflector` field.
//!
//! The `DomObject` trait provides a `reflector()` method that returns the
//! DOM object's `Reflector`. It is implemented automatically for DOM structs
//! through the `#[dom_struct]` attribute.
//!
//! Implementing methods for a DOM object
//! =====================================
//!
//! * `dom::bindings::codegen::Bindings::FooBindings::FooMethods` for methods
//! defined through IDL;
//! * `&self` public methods for public helpers;
//! * `&self` methods for private helpers.
//!
//! Accessing fields of a DOM object
//! ================================
//!
//! All fields of DOM objects are private; accessing them from outside their
//! module is done through explicit getter or setter methods.
//!
//! Inheritance and casting
//! =======================
//!
//! All DOM interfaces part of an inheritance chain (i.e. interfaces
//! that derive others or are derived from) implement the trait `Castable`
//! which provides both downcast and upcasts.
//!
//! ```ignore
//! # use script::dom::bindings::inheritance::Castable;
//! # use script::dom::element::Element;
//! # use script::dom::node::Node;
//! # use script::dom::htmlelement::HTMLElement;
//! fn f(element: &Element) {
//! let base = element.upcast::<Node>();
//! let derived = element.downcast::<HTMLElement>().unwrap();
//! }
//! ```
//!
//! Adding a new DOM interface
//! ==========================
//!
//! Adding a new interface `Foo` requires at least the following:
//!
//! * adding the new IDL file at `components/script/dom/webidls/Foo.webidl`;
//! * creating `components/script/dom/foo.rs`;
//! * listing `foo.rs` in `components/script/dom/mod.rs`;
//! * defining the DOM struct `Foo` with a `#[dom_struct]` attribute, a
//! superclass or `Reflector` member, and other members as appropriate;
//! * implementing the
//! `dom::bindings::codegen::Bindings::FooBindings::FooMethods` trait for
//! `Foo`;
//! * adding/updating the match arm in create_element in
//! `components/script/dom/create.rs` (only applicable to new types inheriting
//! from `HTMLElement`)
//!
//! More information is available in the [bindings module](bindings/index.html).
//!
//! Accessing DOM objects from layout
//! =================================
//!
//! Layout code can access the DOM through the
//! [`LayoutDom`](bindings/root/struct.LayoutDom.html) smart pointer. This does not
//! keep the DOM object alive; we ensure that no DOM code (Garbage Collection
//! in particular) runs while the layout thread is accessing the DOM.
//!
//! Methods accessible to layout are implemented on `LayoutDom<Foo>` using
//! `LayoutFooHelpers` traits.
#[macro_use]
pub mod macros;
pub mod types {
#[cfg(not(target_env = "msvc"))]
include!(concat!(env!("OUT_DIR"), "/InterfaceTypes.rs"));
#[cfg(target_env = "msvc")]
include!(concat!(env!("OUT_DIR"), "/build/InterfaceTypes.rs"));
}
pub mod abstractworker;
pub mod abstractworkerglobalscope;
pub mod activation;
pub mod attr;
pub mod beforeunloadevent;
pub mod bindings;
pub mod blob;
pub mod bluetooth;
pub mod bluetoothadvertisingevent;
pub mod bluetoothcharacteristicproperties;
pub mod bluetoothdevice;
pub mod bluetoothpermissionresult;
pub mod bluetoothremotegattcharacteristic;
pub mod bluetoothremotegattdescriptor;
pub mod bluetoothremotegattserver;
pub mod bluetoothremotegattservice;
pub mod bluetoothuuid;
pub mod canvasgradient;
pub mod canvaspattern;
pub mod canvasrenderingcontext2d;
pub mod characterdata;
pub mod client;
pub mod closeevent;
pub mod comment;
pub mod compositionevent;
pub mod console;
mod create;
pub mod crypto;
pub mod css;
pub mod cssconditionrule;
pub mod cssfontfacerule;
pub mod cssgroupingrule;
pub mod cssimportrule;
pub mod csskeyframerule;
pub mod csskeyframesrule;
pub mod cssmediarule;
pub mod cssnamespacerule;
pub mod cssrule;
pub mod cssrulelist;
pub mod cssstyledeclaration;
pub mod cssstylerule;
pub mod cssstylesheet;
pub mod cssstylevalue;
pub mod csssupportsrule;
pub mod cssviewportrule;
pub mod customelementregistry;
pub mod customevent;
pub mod dedicatedworkerglobalscope;
pub mod dissimilaroriginlocation;
pub mod dissimilaroriginwindow;
pub mod document;
pub mod documentfragment;
pub mod documenttype;
pub mod domexception;
pub mod domimplementation;
pub mod dommatrix;
pub mod dommatrixreadonly;
pub mod domparser;
pub mod dompoint;
pub mod dompointreadonly;
pub mod domquad;
pub mod domrect;
pub mod domrectreadonly;
pub mod domstringmap;
pub mod domtokenlist;
pub mod element;
pub mod errorevent;
pub mod event;
pub mod eventsource;
pub mod eventtarget;
pub mod extendableevent;
pub mod extendablemessageevent;
pub mod file;
pub mod filelist;
pub mod filereader;
pub mod filereadersync;
pub mod focusevent;
pub mod formdata;
pub mod gamepad;
pub mod gamepadbutton;
pub mod gamepadbuttonlist;
pub mod gamepadevent;
pub mod gamepadlist;
pub mod globalscope;
pub mod hashchangeevent;
pub mod headers;
pub mod history;
pub mod htmlanchorelement;
pub mod htmlareaelement;
pub mod htmlaudioelement;
pub mod htmlbaseelement;
pub mod htmlbodyelement;
pub mod htmlbrelement;
pub mod htmlbuttonelement;
pub mod htmlcanvaselement;
pub mod htmlcollection;
pub mod htmldataelement;
pub mod htmldatalistelement;
pub mod htmldetailselement;
pub mod htmldialogelement;
pub mod htmldirectoryelement;
pub mod htmldivelement;
pub mod htmldlistelement;
pub mod htmlelement;
pub mod htmlembedelement;
pub mod htmlfieldsetelement;
pub mod htmlfontelement;
pub mod htmlformcontrolscollection;
pub mod htmlformelement;
pub mod htmlframeelement;
pub mod htmlframesetelement;
pub mod htmlheadelement;
pub mod htmlheadingelement;
pub mod htmlhrelement;
pub mod htmlhtmlelement;
pub mod htmliframeelement;
pub mod htmlimageelement;
pub mod htmlinputelement;
pub mod htmllabelelement;
pub mod htmllegendelement;
pub mod htmllielement;
pub mod htmllinkelement;
pub mod htmlmapelement;
pub mod htmlmediaelement;
pub mod htmlmetaelement;
pub mod htmlmeterelement;
pub mod htmlmodelement;
pub mod htmlobjectelement;
pub mod htmlolistelement;
pub mod htmloptgroupelement;
pub mod htmloptionelement;
pub mod htmloptionscollection;
pub mod htmloutputelement;
pub mod htmlparagraphelement;
pub mod htmlparamelement;
pub mod htmlpictureelement;
pub mod htmlpreelement;
pub mod htmlprogresselement;
pub mod htmlquoteelement;
pub mod htmlscriptelement;
pub mod htmlselectelement;
pub mod htmlsourceelement;
pub mod htmlspanelement;
pub mod htmlstyleelement;
pub mod htmltablecaptionelement;
pub mod htmltablecellelement;
pub mod htmltablecolelement;
pub mod htmltabledatacellelement;
pub mod htmltableelement;
pub mod htmltableheadercellelement;
pub mod htmltablerowelement;
pub mod htmltablesectionelement;
pub mod htmltemplateelement;
pub mod htmltextareaelement;
pub mod htmltimeelement;
pub mod htmltitleelement;
pub mod htmltrackelement;
pub mod htmlulistelement;
pub mod htmlunknownelement;
pub mod htmlvideoelement;
pub mod imagedata;
pub mod inputevent;
pub mod keyboardevent;
pub mod location;
pub mod mediaerror;
pub mod medialist;
pub mod mediaquerylist;
pub mod mediaquerylistevent;
pub mod messageevent;
pub mod mimetype;
pub mod mimetypearray;
pub mod mouseevent;
pub mod mutationobserver;
pub mod mutationrecord;
pub mod namednodemap;
pub mod navigator;
pub mod navigatorinfo;
pub mod node;
pub mod nodeiterator;
pub mod nodelist;
pub mod pagetransitionevent;
pub mod paintrenderingcontext2d;
pub mod paintsize;
pub mod paintworkletglobalscope;
pub mod performance;
pub mod performanceentry;
pub mod performancemark;
pub mod performancemeasure;
pub mod performanceobserver;
pub mod performanceobserverentrylist;
pub mod performancepainttiming;
pub mod performancetiming;
pub mod permissions;
pub mod permissionstatus;
pub mod plugin;
pub mod pluginarray;
pub mod popstateevent;
pub mod processinginstruction;
pub mod progressevent;
pub mod promise;
pub mod promisenativehandler;
pub mod radionodelist;
pub mod range;
pub mod request;
pub mod response;
pub mod screen;
pub mod serviceworker;
pub mod serviceworkercontainer;
pub mod serviceworkerglobalscope;
pub mod serviceworkerregistration;
pub mod servoparser;
pub mod storage;
pub mod storageevent;
pub mod stylepropertymapreadonly;
pub mod stylesheet;
pub mod stylesheetlist;
pub mod svgelement;
pub mod svggraphicselement;
pub mod svgsvgelement;
pub mod testbinding;
pub mod testbindingiterable;
pub mod testbindingpairiterable;
pub mod testbindingproxy;
pub mod testrunner;
pub mod testworklet;
pub mod testworkletglobalscope;
pub mod text;
pub mod textcontrol;
pub mod textdecoder;
pub mod textencoder;
pub mod touch;
pub mod touchevent;
pub mod touchlist;
pub mod transitionevent;
pub mod treewalker;
pub mod uievent;
pub mod url;
pub mod urlhelper;
pub mod urlsearchparams;
pub mod userscripts;
pub mod validation;
pub mod validitystate;
pub mod values;
pub mod virtualmethods;
pub mod vr;
pub mod vrdisplay;
pub mod vrdisplaycapabilities;
pub mod vrdisplayevent;
pub mod vreyeparameters;
pub mod vrfieldofview;
pub mod vrframedata;
pub mod vrpose;
pub mod vrstageparameters;
pub mod webgl_extensions;
pub use self::webgl_extensions::ext::*;
pub mod webgl2renderingcontext;
pub mod webgl_validations;
pub mod webglactiveinfo;
pub mod webglbuffer;
pub mod webglcontextevent;
pub mod webglframebuffer;
pub mod webglobject;
pub mod webglprogram;
pub mod webglrenderbuffer;
pub mod webglrenderingcontext;
pub mod webglshader;
pub mod webglshaderprecisionformat;
pub mod webgltexture;
pub mod webgluniformlocation;
pub mod websocket;
pub mod window;
pub mod windowproxy;
pub mod worker;
pub mod workerglobalscope;
pub mod workerlocation;
pub mod workernavigator;
pub mod worklet;
pub mod workletglobalscope;
pub mod xmldocument;
pub mod xmlhttprequest;
pub mod xmlhttprequesteventtarget;
pub mod xmlhttprequestupload;
|
//! implement the `Castable` trait, which provides three methods `is::<T>()`,
//! `downcast::<T>()` and `upcast::<T>()` to cast across the type hierarchy
|
random_line_split
|
mod.rs
|
mod address;
mod entry;
mod table;
mod huge;
mod page;
use alloc::boxed::Box;
use alloc::vec::Vec;
use sys::volatile::prelude::*;
use pi::common::IO_BASE as _IO_BASE;
use core::fmt;
use aarch64;
pub use self::entry::Entry;
pub use self::table::{Table, Level, L0, L1, L2, L3};
pub use self::address::{PhysicalAddr, VirtualAddr};
pub use self::huge::{Huge, HUGESZ};
pub use self::page::{Page, PAGESZ};
pub const UPPER_SPACE_MASK: usize = 0xFFFFFF80_00000000;
pub const LOWER_SPACE_MASK: usize = 0x0000007F_FFFFFFFF;
const IO_BASE: usize = _IO_BASE & LOWER_SPACE_MASK;
use allocator::util::{align_up, align_down};
use allocator::safe_box;
// get addresses from linker
extern "C" {
static mut _start: u8;
static mut _data: u8;
static mut _end: u8;
}
pub fn kernel_start() -> PhysicalAddr {
let p = unsafe { &mut _start as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_data() -> PhysicalAddr {
let p = unsafe { &mut _data as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_end() -> PhysicalAddr {
let p = unsafe { &mut _end as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
#[inline(always)]
pub fn v2p(v: VirtualAddr) -> Option<PhysicalAddr> {
v.as_usize().checked_sub(UPPER_SPACE_MASK).map(Into::into)
}
#[inline(always)]
pub fn p2v(p: PhysicalAddr) -> VirtualAddr {
((p.as_usize() | UPPER_SPACE_MASK) as *mut u8).into()
}
pub struct Memory {
root: L1,
areas: Vec<Area>,
}
unsafe impl Send for Memory {}
unsafe impl Sync for Memory {}
impl fmt::Debug for Memory {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Memory{:?}", self.areas)
}
}
impl Memory {
pub fn new() -> Option<Box<Self>> {
Some(safe_box(Self {
root: Page::new_zeroed()?.into(),
areas: Vec::new(),
})?)
}
pub fn ttbr(&mut self) -> PhysicalAddr {
self.root.physical()
}
#[must_use]
pub fn area_rx(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RX))
}
#[must_use]
pub fn area_rw(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RW))
}
#[must_use]
pub fn area_ro(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RO))
}
#[must_use]
pub fn area_dev(&mut self, area: Area) -> Option<()> {
self.area(area.entry(Entry::USER_DEV))
}
#[must_use]
pub fn area(&mut self, area: Area) -> Option<()> {
/*
use console::kprintln;
match area.physical {
Some(p) => kprintln!("area: {}-{} to {}", area.start, area.end, p),
None => kprintln!("area: {}-{}", area.start, area.end),
}
*/
let mut addr = align_down(area.start.as_usize(), PAGESZ);
let end = align_up(area.end.as_usize(), PAGESZ);
let entry = area.entry;
let p = area.physical;
self.areas.try_reserve(1).ok()?;
self.areas.push(area);
if let Some(p) = p {
let mut p = align_down(p.as_usize(), PAGESZ);
while addr < end {
let v = (addr as *mut u8).into();
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
if addr % HUGESZ == 0 && (end - addr) >= HUGESZ {
l2[v].write(Entry::block(p.into()) | entry);
addr += HUGESZ;
p += HUGESZ;
} else {
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
addr += PAGESZ;
p += PAGESZ;
}
}
}
Some(())
}
pub fn find_area_mut(&mut self, addr: VirtualAddr) -> Option<&mut Area> {
self.areas.iter_mut().find(|area| area.contains(addr))
}
pub fn find_area(&self, addr: VirtualAddr) -> Option<&Area> {
self.areas.iter().find(|area| area.contains(addr))
}
pub fn has_addr(&self, addr: VirtualAddr) -> bool {
self.areas.iter().any(|area| area.contains(addr))
}
pub fn page_fault(&mut self, addr: u64) {
let addr = VirtualAddr::from((addr as usize) as *mut u8);
let page = Page::new().expect("allocate page");
unsafe { self.add_page(addr, page).expect("add page") };
}
unsafe fn add_page(&mut self, v: VirtualAddr, p: Page) -> Option<()> {
let entry = self.find_area(v)?.entry;
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
Some(())
}
}
bitflags! {
pub struct Prot: u8 {
const READ = 1 << 0;
const WRITE = 1 << 1;
const EXEC = 1 << 2;
const RO = Self::READ.bits;
const RW = Self::READ.bits | Self::WRITE.bits;
const RX = Self::READ.bits | Self::EXEC.bits;
}
}
bitflags! {
pub struct Map: u8 {
const EXEC = 1 << 0;
const WRITE = 1 << 1;
const READ = 1 << 2;
const CAN_EXEC = 1 << 4;
const CAN_WRITE = 1 << 5;
const CAN_READ = 1 << 6;
const ANON = 1 << 10;
const FIXED = 1 << 11;
const PRIVATE = 1 << 12;
const SHARED = 1 << 13;
const STACK = 1 << 14;
}
}
#[derive(Debug)]
pub struct Area {
pub start: VirtualAddr,
pub end: VirtualAddr,
pub entry: Entry,
pub physical: Option<PhysicalAddr>,
}
impl Area {
pub fn new(start: usize, end: usize) -> Self {
let start = VirtualAddr::from(start as *mut u8);
let end = VirtualAddr::from(end as *mut u8);
Self {
start, end,
entry: Entry::INVALID,
physical: None,
}
}
pub fn entry(mut self, entry: Entry) -> Self {
self.entry = entry;
self
}
pub fn prot(mut self, p: Prot) -> Self {
self.entry = match p {
Prot::RO => Entry::USER_RO,
Prot::RW => Entry::USER_RW,
Prot::RX => Entry::USER_RX,
_ => unimplemented!(),
};
self
}
pub fn map_to(mut self, p: PhysicalAddr) -> Self {
self.physical = Some(p);
self
}
pub fn is_empty(&self) -> bool
|
pub fn contains(&self, addr: VirtualAddr) -> bool {
self.start <= addr && addr < self.end
}
pub fn intersects(&self, other: Self) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}
/// Set up page translation tables and enable virtual memory
pub fn initialize() {
#![allow(non_snake_case)]
static mut L1: Table<L1> = Table::empty();
static mut L2: Table<L2> = Table::empty();
static mut L3: Table<L3> = Table::empty();
let NORMAL: Entry = Entry::AF | Entry::ISH;
let DATA: Entry = NORMAL | Entry::XN | Entry::PXN;
let CODE: Entry = NORMAL | Entry::AP_RO;
let DEV: Entry = Entry::AF | Entry::OSH | Entry::XN | Entry::ATTR_1;
let start = kernel_start().as_usize();
let data = kernel_data().as_usize();
let ttbr = unsafe {
L1.get_mut(0).write(Entry::table((&mut L2 as *mut Table<L2>).into()) | NORMAL);
L2.get_mut(0).write(Entry::table((&mut L3 as *mut Table<L3>).into()) | NORMAL);
for n in 1..512usize {
let addr = n * HUGESZ;
L2.get_mut(n).write(Entry::block(addr.into()) | if addr < IO_BASE { DATA } else { DEV });
}
for n in 0..512usize {
let addr = n * PAGESZ;
L3.get_mut(n).write(Entry::page(addr.into()) | if addr < start || addr >= data { DATA } else { CODE });
}
&mut L1 as *mut _ as u64
};
aarch64::set_ttbr0_el1(0, ttbr, true);
aarch64::set_ttbr1_el1(1, ttbr, true);
// okay, now we have to set system registers to enable MMU
// check for 4k granule and at least 36 bits physical address bus
let mmfr = aarch64::MMFR::new();
let par = mmfr.physical_address_range();
assert!(mmfr.support_4kb_granulate(), "4k granulate not supported");
assert!(par >= aarch64::PhysicalAddressRange::R36, "36 bit address space not supported");
let ips = par.raw() as u64;
// first, set Memory Attributes array,
// indexed by PT_MEM, PT_DEV, PT_NC in our example
let mair: u64 =
(0xFF << 0) | // AttrIdx=0: normal, IWBWA, OWBWA, NTR
(0x04 << 8) | // AttrIdx=1: device, nGnRE (must be OSH too)
(0x44 <<16); // AttrIdx=2: non cacheable
// next, specify mapping characteristics in translate control register
let tcr: u64 =
(0b00 << 37) | // TBI=0, no tagging
(ips << 32) | // IPS=autodetected
(0b10 << 30) | // TG1=4k
(0b11 << 28) | // SH1=3 inner
(0b01 << 26) | // ORGN1=1 write back
(0b01 << 24) | // IRGN1=1 write back
(0b0 << 23) | // EPD1 enable higher half
(25 << 16) | // T1SZ=25, 3 levels (512G)
(0b00 << 14) | // TG0=4k
(0b11 << 12) | // SH0=3 inner
(0b01 << 10) | // ORGN0=1 write back
(0b01 << 8) | // IRGN0=1 write back
(0b0 << 7) | // EPD0 enable lower half
(25 << 0); // T0SZ=25, 3 levels (512G)
unsafe {
asm!("
msr mair_el1, $0
msr tcr_el1, $1
isb
"
:: "r"(mair), "r"(tcr)
:: "volatile");
}
// finally, toggle some bits in system control register to enable page translation
unsafe {
let mut r: u64;
asm!("dsb ish; isb; mrs $0, sctlr_el1" : "=r"(r) : : : "volatile");
r |= 0xC00800; // set mandatory reserved bits
r &=!((1<<25) | // clear EE, little endian translation tables
(1<<24) | // clear E0E
(1<<19) | // clear WXN
(1<<12) | // clear I, no instruction cache
(1<< 4) | // clear SA0
(1<< 3) | // clear SA
(1<< 2) | // clear C, no cache at all
(1<< 1)); // clear A, no aligment check
r |= 1<< 0; // set M, enable MMU
asm!("msr sctlr_el1, $0; isb" :: "r"(r) :: "volatile");
}
}
|
{
self.start >= self.end
}
|
identifier_body
|
mod.rs
|
mod address;
mod entry;
mod table;
mod huge;
mod page;
use alloc::boxed::Box;
use alloc::vec::Vec;
use sys::volatile::prelude::*;
use pi::common::IO_BASE as _IO_BASE;
use core::fmt;
use aarch64;
pub use self::entry::Entry;
pub use self::table::{Table, Level, L0, L1, L2, L3};
pub use self::address::{PhysicalAddr, VirtualAddr};
pub use self::huge::{Huge, HUGESZ};
pub use self::page::{Page, PAGESZ};
pub const UPPER_SPACE_MASK: usize = 0xFFFFFF80_00000000;
pub const LOWER_SPACE_MASK: usize = 0x0000007F_FFFFFFFF;
const IO_BASE: usize = _IO_BASE & LOWER_SPACE_MASK;
use allocator::util::{align_up, align_down};
use allocator::safe_box;
// get addresses from linker
extern "C" {
static mut _start: u8;
static mut _data: u8;
static mut _end: u8;
}
pub fn kernel_start() -> PhysicalAddr {
let p = unsafe { &mut _start as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_data() -> PhysicalAddr {
let p = unsafe { &mut _data as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_end() -> PhysicalAddr {
let p = unsafe { &mut _end as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
#[inline(always)]
pub fn v2p(v: VirtualAddr) -> Option<PhysicalAddr> {
v.as_usize().checked_sub(UPPER_SPACE_MASK).map(Into::into)
}
#[inline(always)]
pub fn p2v(p: PhysicalAddr) -> VirtualAddr {
((p.as_usize() | UPPER_SPACE_MASK) as *mut u8).into()
}
pub struct Memory {
root: L1,
areas: Vec<Area>,
}
unsafe impl Send for Memory {}
unsafe impl Sync for Memory {}
impl fmt::Debug for Memory {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Memory{:?}", self.areas)
}
}
impl Memory {
pub fn new() -> Option<Box<Self>> {
Some(safe_box(Self {
root: Page::new_zeroed()?.into(),
areas: Vec::new(),
})?)
}
pub fn ttbr(&mut self) -> PhysicalAddr {
self.root.physical()
}
#[must_use]
pub fn
|
(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RX))
}
#[must_use]
pub fn area_rw(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RW))
}
#[must_use]
pub fn area_ro(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RO))
}
#[must_use]
pub fn area_dev(&mut self, area: Area) -> Option<()> {
self.area(area.entry(Entry::USER_DEV))
}
#[must_use]
pub fn area(&mut self, area: Area) -> Option<()> {
/*
use console::kprintln;
match area.physical {
Some(p) => kprintln!("area: {}-{} to {}", area.start, area.end, p),
None => kprintln!("area: {}-{}", area.start, area.end),
}
*/
let mut addr = align_down(area.start.as_usize(), PAGESZ);
let end = align_up(area.end.as_usize(), PAGESZ);
let entry = area.entry;
let p = area.physical;
self.areas.try_reserve(1).ok()?;
self.areas.push(area);
if let Some(p) = p {
let mut p = align_down(p.as_usize(), PAGESZ);
while addr < end {
let v = (addr as *mut u8).into();
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
if addr % HUGESZ == 0 && (end - addr) >= HUGESZ {
l2[v].write(Entry::block(p.into()) | entry);
addr += HUGESZ;
p += HUGESZ;
} else {
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
addr += PAGESZ;
p += PAGESZ;
}
}
}
Some(())
}
pub fn find_area_mut(&mut self, addr: VirtualAddr) -> Option<&mut Area> {
self.areas.iter_mut().find(|area| area.contains(addr))
}
pub fn find_area(&self, addr: VirtualAddr) -> Option<&Area> {
self.areas.iter().find(|area| area.contains(addr))
}
pub fn has_addr(&self, addr: VirtualAddr) -> bool {
self.areas.iter().any(|area| area.contains(addr))
}
pub fn page_fault(&mut self, addr: u64) {
let addr = VirtualAddr::from((addr as usize) as *mut u8);
let page = Page::new().expect("allocate page");
unsafe { self.add_page(addr, page).expect("add page") };
}
unsafe fn add_page(&mut self, v: VirtualAddr, p: Page) -> Option<()> {
let entry = self.find_area(v)?.entry;
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
Some(())
}
}
bitflags! {
pub struct Prot: u8 {
const READ = 1 << 0;
const WRITE = 1 << 1;
const EXEC = 1 << 2;
const RO = Self::READ.bits;
const RW = Self::READ.bits | Self::WRITE.bits;
const RX = Self::READ.bits | Self::EXEC.bits;
}
}
bitflags! {
pub struct Map: u8 {
const EXEC = 1 << 0;
const WRITE = 1 << 1;
const READ = 1 << 2;
const CAN_EXEC = 1 << 4;
const CAN_WRITE = 1 << 5;
const CAN_READ = 1 << 6;
const ANON = 1 << 10;
const FIXED = 1 << 11;
const PRIVATE = 1 << 12;
const SHARED = 1 << 13;
const STACK = 1 << 14;
}
}
#[derive(Debug)]
pub struct Area {
pub start: VirtualAddr,
pub end: VirtualAddr,
pub entry: Entry,
pub physical: Option<PhysicalAddr>,
}
impl Area {
pub fn new(start: usize, end: usize) -> Self {
let start = VirtualAddr::from(start as *mut u8);
let end = VirtualAddr::from(end as *mut u8);
Self {
start, end,
entry: Entry::INVALID,
physical: None,
}
}
pub fn entry(mut self, entry: Entry) -> Self {
self.entry = entry;
self
}
pub fn prot(mut self, p: Prot) -> Self {
self.entry = match p {
Prot::RO => Entry::USER_RO,
Prot::RW => Entry::USER_RW,
Prot::RX => Entry::USER_RX,
_ => unimplemented!(),
};
self
}
pub fn map_to(mut self, p: PhysicalAddr) -> Self {
self.physical = Some(p);
self
}
pub fn is_empty(&self) -> bool {
self.start >= self.end
}
pub fn contains(&self, addr: VirtualAddr) -> bool {
self.start <= addr && addr < self.end
}
pub fn intersects(&self, other: Self) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}
/// Set up page translation tables and enable virtual memory
pub fn initialize() {
#![allow(non_snake_case)]
static mut L1: Table<L1> = Table::empty();
static mut L2: Table<L2> = Table::empty();
static mut L3: Table<L3> = Table::empty();
let NORMAL: Entry = Entry::AF | Entry::ISH;
let DATA: Entry = NORMAL | Entry::XN | Entry::PXN;
let CODE: Entry = NORMAL | Entry::AP_RO;
let DEV: Entry = Entry::AF | Entry::OSH | Entry::XN | Entry::ATTR_1;
let start = kernel_start().as_usize();
let data = kernel_data().as_usize();
let ttbr = unsafe {
L1.get_mut(0).write(Entry::table((&mut L2 as *mut Table<L2>).into()) | NORMAL);
L2.get_mut(0).write(Entry::table((&mut L3 as *mut Table<L3>).into()) | NORMAL);
for n in 1..512usize {
let addr = n * HUGESZ;
L2.get_mut(n).write(Entry::block(addr.into()) | if addr < IO_BASE { DATA } else { DEV });
}
for n in 0..512usize {
let addr = n * PAGESZ;
L3.get_mut(n).write(Entry::page(addr.into()) | if addr < start || addr >= data { DATA } else { CODE });
}
&mut L1 as *mut _ as u64
};
aarch64::set_ttbr0_el1(0, ttbr, true);
aarch64::set_ttbr1_el1(1, ttbr, true);
// okay, now we have to set system registers to enable MMU
// check for 4k granule and at least 36 bits physical address bus
let mmfr = aarch64::MMFR::new();
let par = mmfr.physical_address_range();
assert!(mmfr.support_4kb_granulate(), "4k granulate not supported");
assert!(par >= aarch64::PhysicalAddressRange::R36, "36 bit address space not supported");
let ips = par.raw() as u64;
// first, set Memory Attributes array,
// indexed by PT_MEM, PT_DEV, PT_NC in our example
let mair: u64 =
(0xFF << 0) | // AttrIdx=0: normal, IWBWA, OWBWA, NTR
(0x04 << 8) | // AttrIdx=1: device, nGnRE (must be OSH too)
(0x44 <<16); // AttrIdx=2: non cacheable
// next, specify mapping characteristics in translate control register
let tcr: u64 =
(0b00 << 37) | // TBI=0, no tagging
(ips << 32) | // IPS=autodetected
(0b10 << 30) | // TG1=4k
(0b11 << 28) | // SH1=3 inner
(0b01 << 26) | // ORGN1=1 write back
(0b01 << 24) | // IRGN1=1 write back
(0b0 << 23) | // EPD1 enable higher half
(25 << 16) | // T1SZ=25, 3 levels (512G)
(0b00 << 14) | // TG0=4k
(0b11 << 12) | // SH0=3 inner
(0b01 << 10) | // ORGN0=1 write back
(0b01 << 8) | // IRGN0=1 write back
(0b0 << 7) | // EPD0 enable lower half
(25 << 0); // T0SZ=25, 3 levels (512G)
unsafe {
asm!("
msr mair_el1, $0
msr tcr_el1, $1
isb
"
:: "r"(mair), "r"(tcr)
:: "volatile");
}
// finally, toggle some bits in system control register to enable page translation
unsafe {
let mut r: u64;
asm!("dsb ish; isb; mrs $0, sctlr_el1" : "=r"(r) : : : "volatile");
r |= 0xC00800; // set mandatory reserved bits
r &=!((1<<25) | // clear EE, little endian translation tables
(1<<24) | // clear E0E
(1<<19) | // clear WXN
(1<<12) | // clear I, no instruction cache
(1<< 4) | // clear SA0
(1<< 3) | // clear SA
(1<< 2) | // clear C, no cache at all
(1<< 1)); // clear A, no aligment check
r |= 1<< 0; // set M, enable MMU
asm!("msr sctlr_el1, $0; isb" :: "r"(r) :: "volatile");
}
}
|
area_rx
|
identifier_name
|
mod.rs
|
mod address;
mod entry;
mod table;
mod huge;
mod page;
use alloc::boxed::Box;
use alloc::vec::Vec;
use sys::volatile::prelude::*;
use pi::common::IO_BASE as _IO_BASE;
use core::fmt;
use aarch64;
pub use self::entry::Entry;
pub use self::table::{Table, Level, L0, L1, L2, L3};
pub use self::address::{PhysicalAddr, VirtualAddr};
pub use self::huge::{Huge, HUGESZ};
pub use self::page::{Page, PAGESZ};
pub const UPPER_SPACE_MASK: usize = 0xFFFFFF80_00000000;
pub const LOWER_SPACE_MASK: usize = 0x0000007F_FFFFFFFF;
const IO_BASE: usize = _IO_BASE & LOWER_SPACE_MASK;
use allocator::util::{align_up, align_down};
use allocator::safe_box;
// get addresses from linker
extern "C" {
static mut _start: u8;
static mut _data: u8;
static mut _end: u8;
}
pub fn kernel_start() -> PhysicalAddr {
let p = unsafe { &mut _start as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_data() -> PhysicalAddr {
let p = unsafe { &mut _data as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_end() -> PhysicalAddr {
let p = unsafe { &mut _end as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
#[inline(always)]
pub fn v2p(v: VirtualAddr) -> Option<PhysicalAddr> {
v.as_usize().checked_sub(UPPER_SPACE_MASK).map(Into::into)
}
#[inline(always)]
pub fn p2v(p: PhysicalAddr) -> VirtualAddr {
((p.as_usize() | UPPER_SPACE_MASK) as *mut u8).into()
}
pub struct Memory {
root: L1,
areas: Vec<Area>,
}
unsafe impl Send for Memory {}
unsafe impl Sync for Memory {}
impl fmt::Debug for Memory {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Memory{:?}", self.areas)
}
}
impl Memory {
pub fn new() -> Option<Box<Self>> {
Some(safe_box(Self {
root: Page::new_zeroed()?.into(),
areas: Vec::new(),
})?)
}
pub fn ttbr(&mut self) -> PhysicalAddr {
self.root.physical()
}
#[must_use]
pub fn area_rx(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RX))
}
#[must_use]
pub fn area_rw(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RW))
}
#[must_use]
pub fn area_ro(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RO))
}
#[must_use]
pub fn area_dev(&mut self, area: Area) -> Option<()> {
self.area(area.entry(Entry::USER_DEV))
}
#[must_use]
pub fn area(&mut self, area: Area) -> Option<()> {
/*
use console::kprintln;
match area.physical {
Some(p) => kprintln!("area: {}-{} to {}", area.start, area.end, p),
None => kprintln!("area: {}-{}", area.start, area.end),
}
*/
let mut addr = align_down(area.start.as_usize(), PAGESZ);
let end = align_up(area.end.as_usize(), PAGESZ);
let entry = area.entry;
let p = area.physical;
self.areas.try_reserve(1).ok()?;
self.areas.push(area);
if let Some(p) = p {
let mut p = align_down(p.as_usize(), PAGESZ);
while addr < end {
let v = (addr as *mut u8).into();
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
if addr % HUGESZ == 0 && (end - addr) >= HUGESZ {
l2[v].write(Entry::block(p.into()) | entry);
addr += HUGESZ;
p += HUGESZ;
} else {
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
addr += PAGESZ;
p += PAGESZ;
}
}
}
Some(())
}
pub fn find_area_mut(&mut self, addr: VirtualAddr) -> Option<&mut Area> {
self.areas.iter_mut().find(|area| area.contains(addr))
}
pub fn find_area(&self, addr: VirtualAddr) -> Option<&Area> {
self.areas.iter().find(|area| area.contains(addr))
}
pub fn has_addr(&self, addr: VirtualAddr) -> bool {
self.areas.iter().any(|area| area.contains(addr))
}
pub fn page_fault(&mut self, addr: u64) {
let addr = VirtualAddr::from((addr as usize) as *mut u8);
let page = Page::new().expect("allocate page");
unsafe { self.add_page(addr, page).expect("add page") };
}
unsafe fn add_page(&mut self, v: VirtualAddr, p: Page) -> Option<()> {
let entry = self.find_area(v)?.entry;
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
Some(())
}
}
bitflags! {
pub struct Prot: u8 {
const READ = 1 << 0;
const WRITE = 1 << 1;
const EXEC = 1 << 2;
const RO = Self::READ.bits;
const RW = Self::READ.bits | Self::WRITE.bits;
const RX = Self::READ.bits | Self::EXEC.bits;
}
}
bitflags! {
pub struct Map: u8 {
const EXEC = 1 << 0;
const WRITE = 1 << 1;
const READ = 1 << 2;
const CAN_EXEC = 1 << 4;
const CAN_WRITE = 1 << 5;
const CAN_READ = 1 << 6;
const ANON = 1 << 10;
const FIXED = 1 << 11;
const PRIVATE = 1 << 12;
const SHARED = 1 << 13;
const STACK = 1 << 14;
}
}
#[derive(Debug)]
pub struct Area {
pub start: VirtualAddr,
pub end: VirtualAddr,
pub entry: Entry,
pub physical: Option<PhysicalAddr>,
}
impl Area {
pub fn new(start: usize, end: usize) -> Self {
let start = VirtualAddr::from(start as *mut u8);
let end = VirtualAddr::from(end as *mut u8);
Self {
start, end,
entry: Entry::INVALID,
physical: None,
}
}
pub fn entry(mut self, entry: Entry) -> Self {
self.entry = entry;
self
}
pub fn prot(mut self, p: Prot) -> Self {
self.entry = match p {
Prot::RO => Entry::USER_RO,
Prot::RW => Entry::USER_RW,
Prot::RX => Entry::USER_RX,
_ => unimplemented!(),
};
self
}
pub fn map_to(mut self, p: PhysicalAddr) -> Self {
self.physical = Some(p);
self
}
pub fn is_empty(&self) -> bool {
self.start >= self.end
}
pub fn contains(&self, addr: VirtualAddr) -> bool {
self.start <= addr && addr < self.end
}
pub fn intersects(&self, other: Self) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}
/// Set up page translation tables and enable virtual memory
pub fn initialize() {
#![allow(non_snake_case)]
static mut L1: Table<L1> = Table::empty();
static mut L2: Table<L2> = Table::empty();
static mut L3: Table<L3> = Table::empty();
let NORMAL: Entry = Entry::AF | Entry::ISH;
let DATA: Entry = NORMAL | Entry::XN | Entry::PXN;
let CODE: Entry = NORMAL | Entry::AP_RO;
let DEV: Entry = Entry::AF | Entry::OSH | Entry::XN | Entry::ATTR_1;
let start = kernel_start().as_usize();
let data = kernel_data().as_usize();
let ttbr = unsafe {
L1.get_mut(0).write(Entry::table((&mut L2 as *mut Table<L2>).into()) | NORMAL);
L2.get_mut(0).write(Entry::table((&mut L3 as *mut Table<L3>).into()) | NORMAL);
for n in 1..512usize {
let addr = n * HUGESZ;
L2.get_mut(n).write(Entry::block(addr.into()) | if addr < IO_BASE { DATA } else { DEV });
}
for n in 0..512usize {
let addr = n * PAGESZ;
L3.get_mut(n).write(Entry::page(addr.into()) | if addr < start || addr >= data { DATA } else { CODE });
}
&mut L1 as *mut _ as u64
};
aarch64::set_ttbr0_el1(0, ttbr, true);
aarch64::set_ttbr1_el1(1, ttbr, true);
// okay, now we have to set system registers to enable MMU
// check for 4k granule and at least 36 bits physical address bus
let mmfr = aarch64::MMFR::new();
let par = mmfr.physical_address_range();
assert!(mmfr.support_4kb_granulate(), "4k granulate not supported");
assert!(par >= aarch64::PhysicalAddressRange::R36, "36 bit address space not supported");
let ips = par.raw() as u64;
// first, set Memory Attributes array,
// indexed by PT_MEM, PT_DEV, PT_NC in our example
let mair: u64 =
(0xFF << 0) | // AttrIdx=0: normal, IWBWA, OWBWA, NTR
(0x04 << 8) | // AttrIdx=1: device, nGnRE (must be OSH too)
(0x44 <<16); // AttrIdx=2: non cacheable
// next, specify mapping characteristics in translate control register
let tcr: u64 =
(0b00 << 37) | // TBI=0, no tagging
(ips << 32) | // IPS=autodetected
(0b10 << 30) | // TG1=4k
(0b11 << 28) | // SH1=3 inner
(0b01 << 26) | // ORGN1=1 write back
(0b01 << 24) | // IRGN1=1 write back
(0b0 << 23) | // EPD1 enable higher half
(25 << 16) | // T1SZ=25, 3 levels (512G)
(0b00 << 14) | // TG0=4k
(0b11 << 12) | // SH0=3 inner
(0b01 << 10) | // ORGN0=1 write back
(0b01 << 8) | // IRGN0=1 write back
(0b0 << 7) | // EPD0 enable lower half
(25 << 0); // T0SZ=25, 3 levels (512G)
unsafe {
asm!("
msr mair_el1, $0
msr tcr_el1, $1
isb
"
:: "r"(mair), "r"(tcr)
:: "volatile");
}
// finally, toggle some bits in system control register to enable page translation
|
let mut r: u64;
asm!("dsb ish; isb; mrs $0, sctlr_el1" : "=r"(r) : : : "volatile");
r |= 0xC00800; // set mandatory reserved bits
r &=!((1<<25) | // clear EE, little endian translation tables
(1<<24) | // clear E0E
(1<<19) | // clear WXN
(1<<12) | // clear I, no instruction cache
(1<< 4) | // clear SA0
(1<< 3) | // clear SA
(1<< 2) | // clear C, no cache at all
(1<< 1)); // clear A, no aligment check
r |= 1<< 0; // set M, enable MMU
asm!("msr sctlr_el1, $0; isb" :: "r"(r) :: "volatile");
}
}
|
unsafe {
|
random_line_split
|
mod.rs
|
mod address;
mod entry;
mod table;
mod huge;
mod page;
use alloc::boxed::Box;
use alloc::vec::Vec;
use sys::volatile::prelude::*;
use pi::common::IO_BASE as _IO_BASE;
use core::fmt;
use aarch64;
pub use self::entry::Entry;
pub use self::table::{Table, Level, L0, L1, L2, L3};
pub use self::address::{PhysicalAddr, VirtualAddr};
pub use self::huge::{Huge, HUGESZ};
pub use self::page::{Page, PAGESZ};
pub const UPPER_SPACE_MASK: usize = 0xFFFFFF80_00000000;
pub const LOWER_SPACE_MASK: usize = 0x0000007F_FFFFFFFF;
const IO_BASE: usize = _IO_BASE & LOWER_SPACE_MASK;
use allocator::util::{align_up, align_down};
use allocator::safe_box;
// get addresses from linker
extern "C" {
static mut _start: u8;
static mut _data: u8;
static mut _end: u8;
}
pub fn kernel_start() -> PhysicalAddr {
let p = unsafe { &mut _start as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_data() -> PhysicalAddr {
let p = unsafe { &mut _data as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
pub fn kernel_end() -> PhysicalAddr {
let p = unsafe { &mut _end as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
#[inline(always)]
pub fn v2p(v: VirtualAddr) -> Option<PhysicalAddr> {
v.as_usize().checked_sub(UPPER_SPACE_MASK).map(Into::into)
}
#[inline(always)]
pub fn p2v(p: PhysicalAddr) -> VirtualAddr {
((p.as_usize() | UPPER_SPACE_MASK) as *mut u8).into()
}
pub struct Memory {
root: L1,
areas: Vec<Area>,
}
unsafe impl Send for Memory {}
unsafe impl Sync for Memory {}
impl fmt::Debug for Memory {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Memory{:?}", self.areas)
}
}
impl Memory {
pub fn new() -> Option<Box<Self>> {
Some(safe_box(Self {
root: Page::new_zeroed()?.into(),
areas: Vec::new(),
})?)
}
pub fn ttbr(&mut self) -> PhysicalAddr {
self.root.physical()
}
#[must_use]
pub fn area_rx(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RX))
}
#[must_use]
pub fn area_rw(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RW))
}
#[must_use]
pub fn area_ro(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RO))
}
#[must_use]
pub fn area_dev(&mut self, area: Area) -> Option<()> {
self.area(area.entry(Entry::USER_DEV))
}
#[must_use]
pub fn area(&mut self, area: Area) -> Option<()> {
/*
use console::kprintln;
match area.physical {
Some(p) => kprintln!("area: {}-{} to {}", area.start, area.end, p),
None => kprintln!("area: {}-{}", area.start, area.end),
}
*/
let mut addr = align_down(area.start.as_usize(), PAGESZ);
let end = align_up(area.end.as_usize(), PAGESZ);
let entry = area.entry;
let p = area.physical;
self.areas.try_reserve(1).ok()?;
self.areas.push(area);
if let Some(p) = p
|
Some(())
}
pub fn find_area_mut(&mut self, addr: VirtualAddr) -> Option<&mut Area> {
self.areas.iter_mut().find(|area| area.contains(addr))
}
pub fn find_area(&self, addr: VirtualAddr) -> Option<&Area> {
self.areas.iter().find(|area| area.contains(addr))
}
pub fn has_addr(&self, addr: VirtualAddr) -> bool {
self.areas.iter().any(|area| area.contains(addr))
}
pub fn page_fault(&mut self, addr: u64) {
let addr = VirtualAddr::from((addr as usize) as *mut u8);
let page = Page::new().expect("allocate page");
unsafe { self.add_page(addr, page).expect("add page") };
}
unsafe fn add_page(&mut self, v: VirtualAddr, p: Page) -> Option<()> {
let entry = self.find_area(v)?.entry;
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
Some(())
}
}
bitflags! {
pub struct Prot: u8 {
const READ = 1 << 0;
const WRITE = 1 << 1;
const EXEC = 1 << 2;
const RO = Self::READ.bits;
const RW = Self::READ.bits | Self::WRITE.bits;
const RX = Self::READ.bits | Self::EXEC.bits;
}
}
bitflags! {
pub struct Map: u8 {
const EXEC = 1 << 0;
const WRITE = 1 << 1;
const READ = 1 << 2;
const CAN_EXEC = 1 << 4;
const CAN_WRITE = 1 << 5;
const CAN_READ = 1 << 6;
const ANON = 1 << 10;
const FIXED = 1 << 11;
const PRIVATE = 1 << 12;
const SHARED = 1 << 13;
const STACK = 1 << 14;
}
}
#[derive(Debug)]
pub struct Area {
pub start: VirtualAddr,
pub end: VirtualAddr,
pub entry: Entry,
pub physical: Option<PhysicalAddr>,
}
impl Area {
pub fn new(start: usize, end: usize) -> Self {
let start = VirtualAddr::from(start as *mut u8);
let end = VirtualAddr::from(end as *mut u8);
Self {
start, end,
entry: Entry::INVALID,
physical: None,
}
}
pub fn entry(mut self, entry: Entry) -> Self {
self.entry = entry;
self
}
pub fn prot(mut self, p: Prot) -> Self {
self.entry = match p {
Prot::RO => Entry::USER_RO,
Prot::RW => Entry::USER_RW,
Prot::RX => Entry::USER_RX,
_ => unimplemented!(),
};
self
}
pub fn map_to(mut self, p: PhysicalAddr) -> Self {
self.physical = Some(p);
self
}
pub fn is_empty(&self) -> bool {
self.start >= self.end
}
pub fn contains(&self, addr: VirtualAddr) -> bool {
self.start <= addr && addr < self.end
}
pub fn intersects(&self, other: Self) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}
/// Set up page translation tables and enable virtual memory
pub fn initialize() {
#![allow(non_snake_case)]
static mut L1: Table<L1> = Table::empty();
static mut L2: Table<L2> = Table::empty();
static mut L3: Table<L3> = Table::empty();
let NORMAL: Entry = Entry::AF | Entry::ISH;
let DATA: Entry = NORMAL | Entry::XN | Entry::PXN;
let CODE: Entry = NORMAL | Entry::AP_RO;
let DEV: Entry = Entry::AF | Entry::OSH | Entry::XN | Entry::ATTR_1;
let start = kernel_start().as_usize();
let data = kernel_data().as_usize();
let ttbr = unsafe {
L1.get_mut(0).write(Entry::table((&mut L2 as *mut Table<L2>).into()) | NORMAL);
L2.get_mut(0).write(Entry::table((&mut L3 as *mut Table<L3>).into()) | NORMAL);
for n in 1..512usize {
let addr = n * HUGESZ;
L2.get_mut(n).write(Entry::block(addr.into()) | if addr < IO_BASE { DATA } else { DEV });
}
for n in 0..512usize {
let addr = n * PAGESZ;
L3.get_mut(n).write(Entry::page(addr.into()) | if addr < start || addr >= data { DATA } else { CODE });
}
&mut L1 as *mut _ as u64
};
aarch64::set_ttbr0_el1(0, ttbr, true);
aarch64::set_ttbr1_el1(1, ttbr, true);
// okay, now we have to set system registers to enable MMU
// check for 4k granule and at least 36 bits physical address bus
let mmfr = aarch64::MMFR::new();
let par = mmfr.physical_address_range();
assert!(mmfr.support_4kb_granulate(), "4k granulate not supported");
assert!(par >= aarch64::PhysicalAddressRange::R36, "36 bit address space not supported");
let ips = par.raw() as u64;
// first, set Memory Attributes array,
// indexed by PT_MEM, PT_DEV, PT_NC in our example
let mair: u64 =
(0xFF << 0) | // AttrIdx=0: normal, IWBWA, OWBWA, NTR
(0x04 << 8) | // AttrIdx=1: device, nGnRE (must be OSH too)
(0x44 <<16); // AttrIdx=2: non cacheable
// next, specify mapping characteristics in translate control register
let tcr: u64 =
(0b00 << 37) | // TBI=0, no tagging
(ips << 32) | // IPS=autodetected
(0b10 << 30) | // TG1=4k
(0b11 << 28) | // SH1=3 inner
(0b01 << 26) | // ORGN1=1 write back
(0b01 << 24) | // IRGN1=1 write back
(0b0 << 23) | // EPD1 enable higher half
(25 << 16) | // T1SZ=25, 3 levels (512G)
(0b00 << 14) | // TG0=4k
(0b11 << 12) | // SH0=3 inner
(0b01 << 10) | // ORGN0=1 write back
(0b01 << 8) | // IRGN0=1 write back
(0b0 << 7) | // EPD0 enable lower half
(25 << 0); // T0SZ=25, 3 levels (512G)
unsafe {
asm!("
msr mair_el1, $0
msr tcr_el1, $1
isb
"
:: "r"(mair), "r"(tcr)
:: "volatile");
}
// finally, toggle some bits in system control register to enable page translation
unsafe {
let mut r: u64;
asm!("dsb ish; isb; mrs $0, sctlr_el1" : "=r"(r) : : : "volatile");
r |= 0xC00800; // set mandatory reserved bits
r &=!((1<<25) | // clear EE, little endian translation tables
(1<<24) | // clear E0E
(1<<19) | // clear WXN
(1<<12) | // clear I, no instruction cache
(1<< 4) | // clear SA0
(1<< 3) | // clear SA
(1<< 2) | // clear C, no cache at all
(1<< 1)); // clear A, no aligment check
r |= 1<< 0; // set M, enable MMU
asm!("msr sctlr_el1, $0; isb" :: "r"(r) :: "volatile");
}
}
|
{
let mut p = align_down(p.as_usize(), PAGESZ);
while addr < end {
let v = (addr as *mut u8).into();
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
if addr % HUGESZ == 0 && (end - addr) >= HUGESZ {
l2[v].write(Entry::block(p.into()) | entry);
addr += HUGESZ;
p += HUGESZ;
} else {
let l3 = l2.next_table_or(v, Entry::USER_BASE)?;
l3[v].write(Entry::page(p.into()) | entry);
addr += PAGESZ;
p += PAGESZ;
}
}
}
|
conditional_block
|
parser_tests.rs
|
#[cfg(test)]
mod tests {
use model::{Model, TemplateParameter};
use std::fs::File;
use std::io::Write;
use clang::{Clang, Index};
use tempdir::TempDir;
use serde_json;
use std::fmt::Debug;
use response_file::ExtendWithResponseFile;
const INTERFACE: &'static str = r#"
namespace foo { namespace sample {
struct Interface {
virtual ~Interface() = default;
virtual void method(int foo) = 0;
virtual int foo(double bar) = 0;
virtual bool baz() {return true};
};
}}
"#;
const TEMPLATE_INTERFACE: &'static str = r#"
namespace foo { namespace bar {
template <typename T, typename U, class V>
class Baz {
virtual ~Baz() = default;
Baz(const Baz&) = delete;
virtual bool boo() = 0;
};
}}
"#;
fn create_model(input: &str) -> Model {
create_model_with_args(input, &[&"-x", &"c++", &"-std=c++14"])
}
fn create_model_with_args<S: AsRef<str> + Debug>(input: &str, args: &[S]) -> Model {
println!("input: {:?} args: {:?}", input, args);
let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir");
let file_path = tmp_dir.path().join("interface.h");
let mut tmp_file = File::create(&file_path).expect("create temp file");
tmp_file.write(input.as_bytes()).expect("write file");
let clang = Clang::new().expect("instantiate clang");
let index = Index::new(&clang, false, false);
let tu = index.parser(&file_path)
.arguments(args)
.parse()
.expect("parse interface");
Model::new(&tu)
}
#[test]
fn should_parse() {
create_model(INTERFACE);
}
#[test]
fn should_list_namespaces() {
let model = create_model(INTERFACE);
assert!(model.interfaces[0].namespaces == vec!["foo".to_string(), "sample".to_string()]);
}
#[test]
fn should_not_include_destructors() {
let model = create_model(INTERFACE);
assert!(!model.interfaces[0]
.clone()
.methods
.into_iter()
.any(|x| x.name == "~Interface"));
}
#[test]
fn should_parse_template_class()
|
#[test]
fn should_list_template_parameters() {
let model = create_model(TEMPLATE_INTERFACE);
assert!(model.interfaces.len() > 0);
assert_eq!(model.interfaces[0]
.clone()
.template_parameters
.unwrap(),
vec![TemplateParameter { type_name: "T".to_string() },
TemplateParameter { type_name: "U".to_string() },
TemplateParameter { type_name: "V".to_string() }]);
}
#[test]
fn should_generate_random_names_for_anonymous_method_arguments() {
const INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS: &'static str = r#"
struct Foo {
virtual void noArgumentName(double) = 0;
};
"#;
let model = create_model(INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS);
assert!(serde_json::ser::to_string(&model.interfaces[0].methods[0].arguments[0].name)
.unwrap()
.len() > 0)
}
#[test]
fn should_parse_template_methods() {
const INTERFACE_WITH_TEMPLATE_METHODS: &'static str = r#"
struct Foo {
template <typename T> void foo(T bar);
};
"#;
let model = create_model(INTERFACE_WITH_TEMPLATE_METHODS);
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.template_arguments
.unwrap(),
vec![TemplateParameter { type_name: "T".to_string() }])
}
#[test]
fn should_parse_arguments_with_namespaced_types() {
const INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS: &'static str = r#"
namespace a { namespace b {
using c = int;
}}
struct A {
virtual void method(a::b::c abc);
};
"#;
let model = create_model(INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS);
println!("{:?}", model);
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.arguments[0]
.argument_type,
"a::b::c".to_string());
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.arguments[0]
.name,
Some("abc".to_string()));
}
#[test]
fn should_support_response_file() {
const INTERFACE_WITH_RESPONSE_FILE_DEFINE: &'static str = r#"
#ifdef FLAG
struct A {
virtual void method(int abc);
};
#endif
"#;
const RESPONSE_FILE: &'static str = "-x;c++;-std=c++14;-DFLAG";
let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir");
let response_file_path = tmp_dir.path().join("interface.rsp");
let mut response_file = File::create(&response_file_path).expect("create temp file");
response_file.write(RESPONSE_FILE.as_bytes()).expect("write file");
let model = create_model_with_args(INTERFACE_WITH_RESPONSE_FILE_DEFINE,
&vec!["@".to_string() +
&response_file_path.to_string_lossy()]
.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>());
assert_eq!(model.interfaces[0].name, "A".to_string());
}
}
|
{
create_model(TEMPLATE_INTERFACE);
}
|
identifier_body
|
parser_tests.rs
|
#[cfg(test)]
mod tests {
use model::{Model, TemplateParameter};
use std::fs::File;
use std::io::Write;
use clang::{Clang, Index};
use tempdir::TempDir;
use serde_json;
use std::fmt::Debug;
use response_file::ExtendWithResponseFile;
const INTERFACE: &'static str = r#"
namespace foo { namespace sample {
struct Interface {
virtual ~Interface() = default;
virtual void method(int foo) = 0;
virtual int foo(double bar) = 0;
virtual bool baz() {return true};
};
}}
"#;
const TEMPLATE_INTERFACE: &'static str = r#"
namespace foo { namespace bar {
template <typename T, typename U, class V>
class Baz {
virtual ~Baz() = default;
Baz(const Baz&) = delete;
virtual bool boo() = 0;
};
}}
"#;
fn create_model(input: &str) -> Model {
create_model_with_args(input, &[&"-x", &"c++", &"-std=c++14"])
}
fn create_model_with_args<S: AsRef<str> + Debug>(input: &str, args: &[S]) -> Model {
println!("input: {:?} args: {:?}", input, args);
let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir");
let file_path = tmp_dir.path().join("interface.h");
let mut tmp_file = File::create(&file_path).expect("create temp file");
tmp_file.write(input.as_bytes()).expect("write file");
let clang = Clang::new().expect("instantiate clang");
let index = Index::new(&clang, false, false);
let tu = index.parser(&file_path)
.arguments(args)
.parse()
.expect("parse interface");
Model::new(&tu)
}
#[test]
fn should_parse() {
create_model(INTERFACE);
}
#[test]
fn should_list_namespaces() {
let model = create_model(INTERFACE);
assert!(model.interfaces[0].namespaces == vec!["foo".to_string(), "sample".to_string()]);
}
#[test]
fn should_not_include_destructors() {
let model = create_model(INTERFACE);
assert!(!model.interfaces[0]
.clone()
.methods
.into_iter()
.any(|x| x.name == "~Interface"));
}
#[test]
fn
|
() {
create_model(TEMPLATE_INTERFACE);
}
#[test]
fn should_list_template_parameters() {
let model = create_model(TEMPLATE_INTERFACE);
assert!(model.interfaces.len() > 0);
assert_eq!(model.interfaces[0]
.clone()
.template_parameters
.unwrap(),
vec![TemplateParameter { type_name: "T".to_string() },
TemplateParameter { type_name: "U".to_string() },
TemplateParameter { type_name: "V".to_string() }]);
}
#[test]
fn should_generate_random_names_for_anonymous_method_arguments() {
const INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS: &'static str = r#"
struct Foo {
virtual void noArgumentName(double) = 0;
};
"#;
let model = create_model(INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS);
assert!(serde_json::ser::to_string(&model.interfaces[0].methods[0].arguments[0].name)
.unwrap()
.len() > 0)
}
#[test]
fn should_parse_template_methods() {
const INTERFACE_WITH_TEMPLATE_METHODS: &'static str = r#"
struct Foo {
template <typename T> void foo(T bar);
};
"#;
let model = create_model(INTERFACE_WITH_TEMPLATE_METHODS);
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.template_arguments
.unwrap(),
vec![TemplateParameter { type_name: "T".to_string() }])
}
#[test]
fn should_parse_arguments_with_namespaced_types() {
const INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS: &'static str = r#"
namespace a { namespace b {
using c = int;
}}
struct A {
virtual void method(a::b::c abc);
};
"#;
let model = create_model(INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS);
println!("{:?}", model);
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.arguments[0]
.argument_type,
"a::b::c".to_string());
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.arguments[0]
.name,
Some("abc".to_string()));
}
#[test]
fn should_support_response_file() {
const INTERFACE_WITH_RESPONSE_FILE_DEFINE: &'static str = r#"
#ifdef FLAG
struct A {
virtual void method(int abc);
};
#endif
"#;
const RESPONSE_FILE: &'static str = "-x;c++;-std=c++14;-DFLAG";
let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir");
let response_file_path = tmp_dir.path().join("interface.rsp");
let mut response_file = File::create(&response_file_path).expect("create temp file");
response_file.write(RESPONSE_FILE.as_bytes()).expect("write file");
let model = create_model_with_args(INTERFACE_WITH_RESPONSE_FILE_DEFINE,
&vec!["@".to_string() +
&response_file_path.to_string_lossy()]
.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>());
assert_eq!(model.interfaces[0].name, "A".to_string());
}
}
|
should_parse_template_class
|
identifier_name
|
parser_tests.rs
|
#[cfg(test)]
|
use model::{Model, TemplateParameter};
use std::fs::File;
use std::io::Write;
use clang::{Clang, Index};
use tempdir::TempDir;
use serde_json;
use std::fmt::Debug;
use response_file::ExtendWithResponseFile;
const INTERFACE: &'static str = r#"
namespace foo { namespace sample {
struct Interface {
virtual ~Interface() = default;
virtual void method(int foo) = 0;
virtual int foo(double bar) = 0;
virtual bool baz() {return true};
};
}}
"#;
const TEMPLATE_INTERFACE: &'static str = r#"
namespace foo { namespace bar {
template <typename T, typename U, class V>
class Baz {
virtual ~Baz() = default;
Baz(const Baz&) = delete;
virtual bool boo() = 0;
};
}}
"#;
fn create_model(input: &str) -> Model {
create_model_with_args(input, &[&"-x", &"c++", &"-std=c++14"])
}
fn create_model_with_args<S: AsRef<str> + Debug>(input: &str, args: &[S]) -> Model {
println!("input: {:?} args: {:?}", input, args);
let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir");
let file_path = tmp_dir.path().join("interface.h");
let mut tmp_file = File::create(&file_path).expect("create temp file");
tmp_file.write(input.as_bytes()).expect("write file");
let clang = Clang::new().expect("instantiate clang");
let index = Index::new(&clang, false, false);
let tu = index.parser(&file_path)
.arguments(args)
.parse()
.expect("parse interface");
Model::new(&tu)
}
#[test]
fn should_parse() {
create_model(INTERFACE);
}
#[test]
fn should_list_namespaces() {
let model = create_model(INTERFACE);
assert!(model.interfaces[0].namespaces == vec!["foo".to_string(), "sample".to_string()]);
}
#[test]
fn should_not_include_destructors() {
let model = create_model(INTERFACE);
assert!(!model.interfaces[0]
.clone()
.methods
.into_iter()
.any(|x| x.name == "~Interface"));
}
#[test]
fn should_parse_template_class() {
create_model(TEMPLATE_INTERFACE);
}
#[test]
fn should_list_template_parameters() {
let model = create_model(TEMPLATE_INTERFACE);
assert!(model.interfaces.len() > 0);
assert_eq!(model.interfaces[0]
.clone()
.template_parameters
.unwrap(),
vec![TemplateParameter { type_name: "T".to_string() },
TemplateParameter { type_name: "U".to_string() },
TemplateParameter { type_name: "V".to_string() }]);
}
#[test]
fn should_generate_random_names_for_anonymous_method_arguments() {
const INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS: &'static str = r#"
struct Foo {
virtual void noArgumentName(double) = 0;
};
"#;
let model = create_model(INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS);
assert!(serde_json::ser::to_string(&model.interfaces[0].methods[0].arguments[0].name)
.unwrap()
.len() > 0)
}
#[test]
fn should_parse_template_methods() {
const INTERFACE_WITH_TEMPLATE_METHODS: &'static str = r#"
struct Foo {
template <typename T> void foo(T bar);
};
"#;
let model = create_model(INTERFACE_WITH_TEMPLATE_METHODS);
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.template_arguments
.unwrap(),
vec![TemplateParameter { type_name: "T".to_string() }])
}
#[test]
fn should_parse_arguments_with_namespaced_types() {
const INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS: &'static str = r#"
namespace a { namespace b {
using c = int;
}}
struct A {
virtual void method(a::b::c abc);
};
"#;
let model = create_model(INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS);
println!("{:?}", model);
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.arguments[0]
.argument_type,
"a::b::c".to_string());
assert_eq!(model.interfaces[0]
.clone()
.methods[0]
.clone()
.arguments[0]
.name,
Some("abc".to_string()));
}
#[test]
fn should_support_response_file() {
const INTERFACE_WITH_RESPONSE_FILE_DEFINE: &'static str = r#"
#ifdef FLAG
struct A {
virtual void method(int abc);
};
#endif
"#;
const RESPONSE_FILE: &'static str = "-x;c++;-std=c++14;-DFLAG";
let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir");
let response_file_path = tmp_dir.path().join("interface.rsp");
let mut response_file = File::create(&response_file_path).expect("create temp file");
response_file.write(RESPONSE_FILE.as_bytes()).expect("write file");
let model = create_model_with_args(INTERFACE_WITH_RESPONSE_FILE_DEFINE,
&vec!["@".to_string() +
&response_file_path.to_string_lossy()]
.into_iter()
.extend_with_response_file()
.collect::<Vec<_>>());
assert_eq!(model.interfaces[0].name, "A".to_string());
}
}
|
mod tests {
|
random_line_split
|
cci_no_inline_lib.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.
|
// same as cci_iter_lib, more-or-less, but not marked inline
pub fn iter<F>(v: Vec<uint>, mut f: F) where F: FnMut(uint) {
let mut i = 0_usize;
let n = v.len();
while i < n {
f(v[i]);
i += 1_usize;
}
}
|
#![crate_name="cci_no_inline_lib"]
|
random_line_split
|
cci_no_inline_lib.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.
#![crate_name="cci_no_inline_lib"]
// same as cci_iter_lib, more-or-less, but not marked inline
pub fn
|
<F>(v: Vec<uint>, mut f: F) where F: FnMut(uint) {
let mut i = 0_usize;
let n = v.len();
while i < n {
f(v[i]);
i += 1_usize;
}
}
|
iter
|
identifier_name
|
cci_no_inline_lib.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.
#![crate_name="cci_no_inline_lib"]
// same as cci_iter_lib, more-or-less, but not marked inline
pub fn iter<F>(v: Vec<uint>, mut f: F) where F: FnMut(uint)
|
{
let mut i = 0_usize;
let n = v.len();
while i < n {
f(v[i]);
i += 1_usize;
}
}
|
identifier_body
|
|
test.rs
|
use intern::intern;
use grammar::repr::*;
use lr1::Lookahead;
use lr1::Lookahead::EOF;
use test_util::{normalized_grammar};
use super::FirstSets;
pub fn nt(t: &str) -> Symbol {
Symbol::Nonterminal(NonterminalString(intern(t)))
}
pub fn term(t: &str) -> Symbol {
Symbol::Terminal(TerminalString::Quoted(intern(t)))
}
fn la(t: &str) -> Lookahead {
Lookahead::Terminal(TerminalString::Quoted(intern(t)))
}
fn first(first: &FirstSets, symbols: &[Symbol], lookahead: Lookahead) -> Vec<Lookahead> {
let mut v = first.first(symbols, lookahead);
v.sort();
v
}
#[test]
fn basic() {
|
"D" => Some(1);
=> None;
};
"#);
let first_sets = FirstSets::new(&grammar);
assert_eq!(
first(&first_sets, &[nt("A")], EOF),
vec![la("C"), la("D")]);
assert_eq!(
first(&first_sets, &[nt("B")], EOF),
vec![EOF, la("D")]);
assert_eq!(
first(&first_sets, &[nt("B"), term("E")], EOF),
vec![la("D"), la("E")]);
}
|
let grammar = normalized_grammar(r#"
grammar;
extern { enum Tok { } }
A = B "C";
B: Option<u32> = {
|
random_line_split
|
test.rs
|
use intern::intern;
use grammar::repr::*;
use lr1::Lookahead;
use lr1::Lookahead::EOF;
use test_util::{normalized_grammar};
use super::FirstSets;
pub fn nt(t: &str) -> Symbol {
Symbol::Nonterminal(NonterminalString(intern(t)))
}
pub fn
|
(t: &str) -> Symbol {
Symbol::Terminal(TerminalString::Quoted(intern(t)))
}
fn la(t: &str) -> Lookahead {
Lookahead::Terminal(TerminalString::Quoted(intern(t)))
}
fn first(first: &FirstSets, symbols: &[Symbol], lookahead: Lookahead) -> Vec<Lookahead> {
let mut v = first.first(symbols, lookahead);
v.sort();
v
}
#[test]
fn basic() {
let grammar = normalized_grammar(r#"
grammar;
extern { enum Tok { } }
A = B "C";
B: Option<u32> = {
"D" => Some(1);
=> None;
};
"#);
let first_sets = FirstSets::new(&grammar);
assert_eq!(
first(&first_sets, &[nt("A")], EOF),
vec![la("C"), la("D")]);
assert_eq!(
first(&first_sets, &[nt("B")], EOF),
vec![EOF, la("D")]);
assert_eq!(
first(&first_sets, &[nt("B"), term("E")], EOF),
vec![la("D"), la("E")]);
}
|
term
|
identifier_name
|
test.rs
|
use intern::intern;
use grammar::repr::*;
use lr1::Lookahead;
use lr1::Lookahead::EOF;
use test_util::{normalized_grammar};
use super::FirstSets;
pub fn nt(t: &str) -> Symbol {
Symbol::Nonterminal(NonterminalString(intern(t)))
}
pub fn term(t: &str) -> Symbol
|
fn la(t: &str) -> Lookahead {
Lookahead::Terminal(TerminalString::Quoted(intern(t)))
}
fn first(first: &FirstSets, symbols: &[Symbol], lookahead: Lookahead) -> Vec<Lookahead> {
let mut v = first.first(symbols, lookahead);
v.sort();
v
}
#[test]
fn basic() {
let grammar = normalized_grammar(r#"
grammar;
extern { enum Tok { } }
A = B "C";
B: Option<u32> = {
"D" => Some(1);
=> None;
};
"#);
let first_sets = FirstSets::new(&grammar);
assert_eq!(
first(&first_sets, &[nt("A")], EOF),
vec![la("C"), la("D")]);
assert_eq!(
first(&first_sets, &[nt("B")], EOF),
vec![EOF, la("D")]);
assert_eq!(
first(&first_sets, &[nt("B"), term("E")], EOF),
vec![la("D"), la("E")]);
}
|
{
Symbol::Terminal(TerminalString::Quoted(intern(t)))
}
|
identifier_body
|
compile.rs
|
use basm;
use beast;
use core::error::*;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::str::FromStr;
const BAKERVM_IMAGE_EXTENSION: &str = "img";
pub const DEFAULT_LANG: Lang = Lang::Beast;
#[derive(Debug)]
pub enum
|
{
Beast,
Basm,
}
impl FromStr for Lang {
type Err = &'static str;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
match s {
"basm" => Ok(Lang::Basm),
"beast" | "bst" => Ok(Lang::Beast),
_ => bail!("unknown language. Language must be one of [beast, bst, basm]"),
}
}
}
pub fn compile(lang: Option<Lang>, input: PathBuf, output: Option<PathBuf>) -> Result<()> {
let input = input
.canonicalize()
.chain_err(|| "unable to canonicalize input path")?;
// We don't want to fail at recognizing the language, so we just default to
// Beast
let lang = lang.unwrap_or_else(|| {
if let Some(extension) = input.extension() {
if let Some(extension) = extension.to_str() {
extension.parse().unwrap_or(DEFAULT_LANG)
} else {
DEFAULT_LANG
}
} else {
DEFAULT_LANG
}
});
let mut fallback_output = input.clone();
ensure!(
fallback_output.set_extension(BAKERVM_IMAGE_EXTENSION),
"unable to set file extension"
);
let output = output.unwrap_or(fallback_output);
let start_dir = env::current_dir().chain_err(|| "unable to get current directory")?;
let program = match lang {
Lang::Basm => basm::compile(input).chain_err(|| "unable to compile basm file")?,
Lang::Beast => beast::compile(input).chain_err(|| "unable to compile Beast file")?,
};
env::set_current_dir(start_dir).chain_err(|| "unable to switch directories")?;
let mut file = File::create(output).chain_err(|| "unable to create file")?;
file.write_all(&program[..])
.chain_err(|| "unable to write program data")?;
file.sync_all()
.chain_err(|| "unable to sync output file to file system")?;
Ok(())
}
|
Lang
|
identifier_name
|
compile.rs
|
use basm;
use beast;
use core::error::*;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::str::FromStr;
const BAKERVM_IMAGE_EXTENSION: &str = "img";
pub const DEFAULT_LANG: Lang = Lang::Beast;
#[derive(Debug)]
pub enum Lang {
Beast,
Basm,
}
impl FromStr for Lang {
type Err = &'static str;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
match s {
"basm" => Ok(Lang::Basm),
"beast" | "bst" => Ok(Lang::Beast),
_ => bail!("unknown language. Language must be one of [beast, bst, basm]"),
}
}
}
|
pub fn compile(lang: Option<Lang>, input: PathBuf, output: Option<PathBuf>) -> Result<()> {
let input = input
.canonicalize()
.chain_err(|| "unable to canonicalize input path")?;
// We don't want to fail at recognizing the language, so we just default to
// Beast
let lang = lang.unwrap_or_else(|| {
if let Some(extension) = input.extension() {
if let Some(extension) = extension.to_str() {
extension.parse().unwrap_or(DEFAULT_LANG)
} else {
DEFAULT_LANG
}
} else {
DEFAULT_LANG
}
});
let mut fallback_output = input.clone();
ensure!(
fallback_output.set_extension(BAKERVM_IMAGE_EXTENSION),
"unable to set file extension"
);
let output = output.unwrap_or(fallback_output);
let start_dir = env::current_dir().chain_err(|| "unable to get current directory")?;
let program = match lang {
Lang::Basm => basm::compile(input).chain_err(|| "unable to compile basm file")?,
Lang::Beast => beast::compile(input).chain_err(|| "unable to compile Beast file")?,
};
env::set_current_dir(start_dir).chain_err(|| "unable to switch directories")?;
let mut file = File::create(output).chain_err(|| "unable to create file")?;
file.write_all(&program[..])
.chain_err(|| "unable to write program data")?;
file.sync_all()
.chain_err(|| "unable to sync output file to file system")?;
Ok(())
}
|
random_line_split
|
|
compile.rs
|
use basm;
use beast;
use core::error::*;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::str::FromStr;
const BAKERVM_IMAGE_EXTENSION: &str = "img";
pub const DEFAULT_LANG: Lang = Lang::Beast;
#[derive(Debug)]
pub enum Lang {
Beast,
Basm,
}
impl FromStr for Lang {
type Err = &'static str;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
match s {
"basm" => Ok(Lang::Basm),
"beast" | "bst" => Ok(Lang::Beast),
_ => bail!("unknown language. Language must be one of [beast, bst, basm]"),
}
}
}
pub fn compile(lang: Option<Lang>, input: PathBuf, output: Option<PathBuf>) -> Result<()>
|
ensure!(
fallback_output.set_extension(BAKERVM_IMAGE_EXTENSION),
"unable to set file extension"
);
let output = output.unwrap_or(fallback_output);
let start_dir = env::current_dir().chain_err(|| "unable to get current directory")?;
let program = match lang {
Lang::Basm => basm::compile(input).chain_err(|| "unable to compile basm file")?,
Lang::Beast => beast::compile(input).chain_err(|| "unable to compile Beast file")?,
};
env::set_current_dir(start_dir).chain_err(|| "unable to switch directories")?;
let mut file = File::create(output).chain_err(|| "unable to create file")?;
file.write_all(&program[..])
.chain_err(|| "unable to write program data")?;
file.sync_all()
.chain_err(|| "unable to sync output file to file system")?;
Ok(())
}
|
{
let input = input
.canonicalize()
.chain_err(|| "unable to canonicalize input path")?;
// We don't want to fail at recognizing the language, so we just default to
// Beast
let lang = lang.unwrap_or_else(|| {
if let Some(extension) = input.extension() {
if let Some(extension) = extension.to_str() {
extension.parse().unwrap_or(DEFAULT_LANG)
} else {
DEFAULT_LANG
}
} else {
DEFAULT_LANG
}
});
let mut fallback_output = input.clone();
|
identifier_body
|
eh.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Parsing of GCC-style Language-Specific Data Area (LSDA)
//! For details see:
//! http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA/ehframechpt.html
//! http://mentorembedded.github.io/cxx-abi/exceptions.pdf
//! http://www.airs.com/blog/archives/460
//! http://www.airs.com/blog/archives/464
//!
//! A reference implementation may be found in the GCC source tree
//! (<root>/libgcc/unwind-c.c as of this writing)
#![allow(non_upper_case_globals)]
#![allow(unused)]
use prelude::v1::*;
use rt::dwarf::DwarfReader;
use core::mem;
pub const DW_EH_PE_omit : u8 = 0xFF;
pub const DW_EH_PE_absptr : u8 = 0x00;
pub const DW_EH_PE_uleb128 : u8 = 0x01;
pub const DW_EH_PE_udata2 : u8 = 0x02;
pub const DW_EH_PE_udata4 : u8 = 0x03;
pub const DW_EH_PE_udata8 : u8 = 0x04;
pub const DW_EH_PE_sleb128 : u8 = 0x09;
pub const DW_EH_PE_sdata2 : u8 = 0x0A;
pub const DW_EH_PE_sdata4 : u8 = 0x0B;
pub const DW_EH_PE_sdata8 : u8 = 0x0C;
pub const DW_EH_PE_pcrel : u8 = 0x10;
pub const DW_EH_PE_textrel : u8 = 0x20;
pub const DW_EH_PE_datarel : u8 = 0x30;
pub const DW_EH_PE_funcrel : u8 = 0x40;
pub const DW_EH_PE_aligned : u8 = 0x50;
pub const DW_EH_PE_indirect : u8 = 0x80;
#[derive(Copy, Clone)]
pub struct EHContext {
pub ip: usize, // Current instruction pointer
pub func_start: usize, // Address of the current function
pub text_start: usize, // Address of the code section
pub data_start: usize, // Address of the data section
}
pub unsafe fn find_landing_pad(lsda: *const u8, context: &EHContext)
-> Option<usize> {
if lsda.is_null() {
return None;
}
let func_start = context.func_start;
let mut reader = DwarfReader::new(lsda);
let start_encoding = reader.read::<u8>();
// base address for landing pad offsets
let lpad_base = if start_encoding!= DW_EH_PE_omit {
read_encoded_pointer(&mut reader, context, start_encoding)
} else {
func_start
};
let ttype_encoding = reader.read::<u8>();
if ttype_encoding!= DW_EH_PE_omit {
// Rust doesn't analyze exception types, so we don't care about the type table
reader.read_uleb128();
}
let call_site_encoding = reader.read::<u8>();
let call_site_table_length = reader.read_uleb128();
let action_table = reader.ptr.offset(call_site_table_length as isize);
// Return addresses point 1 byte past the call instruction, which could
// be in the next IP range.
let ip = context.ip-1;
while reader.ptr < action_table {
let cs_start = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_len = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_lpad = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_action = reader.read_uleb128();
// Callsite table is sorted by cs_start, so if we've passed the ip, we
// may stop searching.
if ip < func_start + cs_start {
break
}
if ip < func_start + cs_start + cs_len {
if cs_lpad!= 0 {
return Some(lpad_base + cs_lpad);
} else {
return None;
}
}
}
// IP range not found: gcc's C++ personality calls terminate() here,
// however the rest of the languages treat this the same as cs_lpad == 0.
// We follow this suit.
return None;
}
#[inline]
fn round_up(unrounded: usize, align: usize) -> usize {
assert!(align.is_power_of_two());
(unrounded + align - 1) &!(align - 1)
}
unsafe fn read_encoded_pointer(reader: &mut DwarfReader,
context: &EHContext,
encoding: u8) -> usize {
assert!(encoding!= DW_EH_PE_omit);
|
return reader.read::<usize>();
}
let mut result = match encoding & 0x0F {
DW_EH_PE_absptr => reader.read::<usize>(),
DW_EH_PE_uleb128 => reader.read_uleb128() as usize,
DW_EH_PE_udata2 => reader.read::<u16>() as usize,
DW_EH_PE_udata4 => reader.read::<u32>() as usize,
DW_EH_PE_udata8 => reader.read::<u64>() as usize,
DW_EH_PE_sleb128 => reader.read_sleb128() as usize,
DW_EH_PE_sdata2 => reader.read::<i16>() as usize,
DW_EH_PE_sdata4 => reader.read::<i32>() as usize,
DW_EH_PE_sdata8 => reader.read::<i64>() as usize,
_ => panic!()
};
result += match encoding & 0x70 {
DW_EH_PE_absptr => 0,
// relative to address of the encoded value, despite the name
DW_EH_PE_pcrel => reader.ptr as usize,
DW_EH_PE_textrel => { assert!(context.text_start!= 0);
context.text_start },
DW_EH_PE_datarel => { assert!(context.data_start!= 0);
context.data_start },
DW_EH_PE_funcrel => { assert!(context.func_start!= 0);
context.func_start },
_ => panic!()
};
if encoding & DW_EH_PE_indirect!= 0 {
result = *(result as *const usize);
}
result
}
|
// DW_EH_PE_aligned implies it's an absolute pointer value
if encoding == DW_EH_PE_aligned {
reader.ptr = round_up(reader.ptr as usize,
mem::size_of::<usize>()) as *const u8;
|
random_line_split
|
eh.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Parsing of GCC-style Language-Specific Data Area (LSDA)
//! For details see:
//! http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA/ehframechpt.html
//! http://mentorembedded.github.io/cxx-abi/exceptions.pdf
//! http://www.airs.com/blog/archives/460
//! http://www.airs.com/blog/archives/464
//!
//! A reference implementation may be found in the GCC source tree
//! (<root>/libgcc/unwind-c.c as of this writing)
#![allow(non_upper_case_globals)]
#![allow(unused)]
use prelude::v1::*;
use rt::dwarf::DwarfReader;
use core::mem;
pub const DW_EH_PE_omit : u8 = 0xFF;
pub const DW_EH_PE_absptr : u8 = 0x00;
pub const DW_EH_PE_uleb128 : u8 = 0x01;
pub const DW_EH_PE_udata2 : u8 = 0x02;
pub const DW_EH_PE_udata4 : u8 = 0x03;
pub const DW_EH_PE_udata8 : u8 = 0x04;
pub const DW_EH_PE_sleb128 : u8 = 0x09;
pub const DW_EH_PE_sdata2 : u8 = 0x0A;
pub const DW_EH_PE_sdata4 : u8 = 0x0B;
pub const DW_EH_PE_sdata8 : u8 = 0x0C;
pub const DW_EH_PE_pcrel : u8 = 0x10;
pub const DW_EH_PE_textrel : u8 = 0x20;
pub const DW_EH_PE_datarel : u8 = 0x30;
pub const DW_EH_PE_funcrel : u8 = 0x40;
pub const DW_EH_PE_aligned : u8 = 0x50;
pub const DW_EH_PE_indirect : u8 = 0x80;
#[derive(Copy, Clone)]
pub struct EHContext {
pub ip: usize, // Current instruction pointer
pub func_start: usize, // Address of the current function
pub text_start: usize, // Address of the code section
pub data_start: usize, // Address of the data section
}
pub unsafe fn
|
(lsda: *const u8, context: &EHContext)
-> Option<usize> {
if lsda.is_null() {
return None;
}
let func_start = context.func_start;
let mut reader = DwarfReader::new(lsda);
let start_encoding = reader.read::<u8>();
// base address for landing pad offsets
let lpad_base = if start_encoding!= DW_EH_PE_omit {
read_encoded_pointer(&mut reader, context, start_encoding)
} else {
func_start
};
let ttype_encoding = reader.read::<u8>();
if ttype_encoding!= DW_EH_PE_omit {
// Rust doesn't analyze exception types, so we don't care about the type table
reader.read_uleb128();
}
let call_site_encoding = reader.read::<u8>();
let call_site_table_length = reader.read_uleb128();
let action_table = reader.ptr.offset(call_site_table_length as isize);
// Return addresses point 1 byte past the call instruction, which could
// be in the next IP range.
let ip = context.ip-1;
while reader.ptr < action_table {
let cs_start = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_len = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_lpad = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_action = reader.read_uleb128();
// Callsite table is sorted by cs_start, so if we've passed the ip, we
// may stop searching.
if ip < func_start + cs_start {
break
}
if ip < func_start + cs_start + cs_len {
if cs_lpad!= 0 {
return Some(lpad_base + cs_lpad);
} else {
return None;
}
}
}
// IP range not found: gcc's C++ personality calls terminate() here,
// however the rest of the languages treat this the same as cs_lpad == 0.
// We follow this suit.
return None;
}
#[inline]
fn round_up(unrounded: usize, align: usize) -> usize {
assert!(align.is_power_of_two());
(unrounded + align - 1) &!(align - 1)
}
unsafe fn read_encoded_pointer(reader: &mut DwarfReader,
context: &EHContext,
encoding: u8) -> usize {
assert!(encoding!= DW_EH_PE_omit);
// DW_EH_PE_aligned implies it's an absolute pointer value
if encoding == DW_EH_PE_aligned {
reader.ptr = round_up(reader.ptr as usize,
mem::size_of::<usize>()) as *const u8;
return reader.read::<usize>();
}
let mut result = match encoding & 0x0F {
DW_EH_PE_absptr => reader.read::<usize>(),
DW_EH_PE_uleb128 => reader.read_uleb128() as usize,
DW_EH_PE_udata2 => reader.read::<u16>() as usize,
DW_EH_PE_udata4 => reader.read::<u32>() as usize,
DW_EH_PE_udata8 => reader.read::<u64>() as usize,
DW_EH_PE_sleb128 => reader.read_sleb128() as usize,
DW_EH_PE_sdata2 => reader.read::<i16>() as usize,
DW_EH_PE_sdata4 => reader.read::<i32>() as usize,
DW_EH_PE_sdata8 => reader.read::<i64>() as usize,
_ => panic!()
};
result += match encoding & 0x70 {
DW_EH_PE_absptr => 0,
// relative to address of the encoded value, despite the name
DW_EH_PE_pcrel => reader.ptr as usize,
DW_EH_PE_textrel => { assert!(context.text_start!= 0);
context.text_start },
DW_EH_PE_datarel => { assert!(context.data_start!= 0);
context.data_start },
DW_EH_PE_funcrel => { assert!(context.func_start!= 0);
context.func_start },
_ => panic!()
};
if encoding & DW_EH_PE_indirect!= 0 {
result = *(result as *const usize);
}
result
}
|
find_landing_pad
|
identifier_name
|
eh.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Parsing of GCC-style Language-Specific Data Area (LSDA)
//! For details see:
//! http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA/ehframechpt.html
//! http://mentorembedded.github.io/cxx-abi/exceptions.pdf
//! http://www.airs.com/blog/archives/460
//! http://www.airs.com/blog/archives/464
//!
//! A reference implementation may be found in the GCC source tree
//! (<root>/libgcc/unwind-c.c as of this writing)
#![allow(non_upper_case_globals)]
#![allow(unused)]
use prelude::v1::*;
use rt::dwarf::DwarfReader;
use core::mem;
pub const DW_EH_PE_omit : u8 = 0xFF;
pub const DW_EH_PE_absptr : u8 = 0x00;
pub const DW_EH_PE_uleb128 : u8 = 0x01;
pub const DW_EH_PE_udata2 : u8 = 0x02;
pub const DW_EH_PE_udata4 : u8 = 0x03;
pub const DW_EH_PE_udata8 : u8 = 0x04;
pub const DW_EH_PE_sleb128 : u8 = 0x09;
pub const DW_EH_PE_sdata2 : u8 = 0x0A;
pub const DW_EH_PE_sdata4 : u8 = 0x0B;
pub const DW_EH_PE_sdata8 : u8 = 0x0C;
pub const DW_EH_PE_pcrel : u8 = 0x10;
pub const DW_EH_PE_textrel : u8 = 0x20;
pub const DW_EH_PE_datarel : u8 = 0x30;
pub const DW_EH_PE_funcrel : u8 = 0x40;
pub const DW_EH_PE_aligned : u8 = 0x50;
pub const DW_EH_PE_indirect : u8 = 0x80;
#[derive(Copy, Clone)]
pub struct EHContext {
pub ip: usize, // Current instruction pointer
pub func_start: usize, // Address of the current function
pub text_start: usize, // Address of the code section
pub data_start: usize, // Address of the data section
}
pub unsafe fn find_landing_pad(lsda: *const u8, context: &EHContext)
-> Option<usize>
|
}
let call_site_encoding = reader.read::<u8>();
let call_site_table_length = reader.read_uleb128();
let action_table = reader.ptr.offset(call_site_table_length as isize);
// Return addresses point 1 byte past the call instruction, which could
// be in the next IP range.
let ip = context.ip-1;
while reader.ptr < action_table {
let cs_start = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_len = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_lpad = read_encoded_pointer(&mut reader, context, call_site_encoding);
let cs_action = reader.read_uleb128();
// Callsite table is sorted by cs_start, so if we've passed the ip, we
// may stop searching.
if ip < func_start + cs_start {
break
}
if ip < func_start + cs_start + cs_len {
if cs_lpad!= 0 {
return Some(lpad_base + cs_lpad);
} else {
return None;
}
}
}
// IP range not found: gcc's C++ personality calls terminate() here,
// however the rest of the languages treat this the same as cs_lpad == 0.
// We follow this suit.
return None;
}
#[inline]
fn round_up(unrounded: usize, align: usize) -> usize {
assert!(align.is_power_of_two());
(unrounded + align - 1) &!(align - 1)
}
unsafe fn read_encoded_pointer(reader: &mut DwarfReader,
context: &EHContext,
encoding: u8) -> usize {
assert!(encoding!= DW_EH_PE_omit);
// DW_EH_PE_aligned implies it's an absolute pointer value
if encoding == DW_EH_PE_aligned {
reader.ptr = round_up(reader.ptr as usize,
mem::size_of::<usize>()) as *const u8;
return reader.read::<usize>();
}
let mut result = match encoding & 0x0F {
DW_EH_PE_absptr => reader.read::<usize>(),
DW_EH_PE_uleb128 => reader.read_uleb128() as usize,
DW_EH_PE_udata2 => reader.read::<u16>() as usize,
DW_EH_PE_udata4 => reader.read::<u32>() as usize,
DW_EH_PE_udata8 => reader.read::<u64>() as usize,
DW_EH_PE_sleb128 => reader.read_sleb128() as usize,
DW_EH_PE_sdata2 => reader.read::<i16>() as usize,
DW_EH_PE_sdata4 => reader.read::<i32>() as usize,
DW_EH_PE_sdata8 => reader.read::<i64>() as usize,
_ => panic!()
};
result += match encoding & 0x70 {
DW_EH_PE_absptr => 0,
// relative to address of the encoded value, despite the name
DW_EH_PE_pcrel => reader.ptr as usize,
DW_EH_PE_textrel => { assert!(context.text_start!= 0);
context.text_start },
DW_EH_PE_datarel => { assert!(context.data_start!= 0);
context.data_start },
DW_EH_PE_funcrel => { assert!(context.func_start!= 0);
context.func_start },
_ => panic!()
};
if encoding & DW_EH_PE_indirect!= 0 {
result = *(result as *const usize);
}
result
}
|
{
if lsda.is_null() {
return None;
}
let func_start = context.func_start;
let mut reader = DwarfReader::new(lsda);
let start_encoding = reader.read::<u8>();
// base address for landing pad offsets
let lpad_base = if start_encoding != DW_EH_PE_omit {
read_encoded_pointer(&mut reader, context, start_encoding)
} else {
func_start
};
let ttype_encoding = reader.read::<u8>();
if ttype_encoding != DW_EH_PE_omit {
// Rust doesn't analyze exception types, so we don't care about the type table
reader.read_uleb128();
|
identifier_body
|
selection_sort.rs
|
/*
* Implementation of selection_sort in Rust
*/
fn selection_sort(mut list: Vec<i32>) -> Vec<i32> {
let n = list.len();
for j in 0..n-1 {
let mut cur_min = j;
for i in j+1..n {
if list[i] < list[cur_min] {
cur_min = i;
}
}
if cur_min!= j {
list.swap(j, cur_min);
}
}
return list;
}
fn main()
|
{
let mut mylist = Vec::new();
mylist.push(5);
mylist.push(4);
mylist.push(8);
mylist.push(9);
mylist.push(20);
mylist.push(14);
mylist.push(3);
mylist.push(1);
mylist.push(2);
mylist.push(2);
println!("{:?}", mylist);
let selection_sorted = selection_sort(mylist);
println!("{:?}", selection_sorted);
}
|
identifier_body
|
|
selection_sort.rs
|
/*
* Implementation of selection_sort in Rust
*/
fn selection_sort(mut list: Vec<i32>) -> Vec<i32> {
let n = list.len();
for j in 0..n-1 {
let mut cur_min = j;
for i in j+1..n {
if list[i] < list[cur_min] {
cur_min = i;
}
}
if cur_min!= j
|
}
return list;
}
fn main() {
let mut mylist = Vec::new();
mylist.push(5);
mylist.push(4);
mylist.push(8);
mylist.push(9);
mylist.push(20);
mylist.push(14);
mylist.push(3);
mylist.push(1);
mylist.push(2);
mylist.push(2);
println!("{:?}", mylist);
let selection_sorted = selection_sort(mylist);
println!("{:?}", selection_sorted);
}
|
{
list.swap(j, cur_min);
}
|
conditional_block
|
selection_sort.rs
|
/*
* Implementation of selection_sort in Rust
*/
fn selection_sort(mut list: Vec<i32>) -> Vec<i32> {
let n = list.len();
|
if list[i] < list[cur_min] {
cur_min = i;
}
}
if cur_min!= j {
list.swap(j, cur_min);
}
}
return list;
}
fn main() {
let mut mylist = Vec::new();
mylist.push(5);
mylist.push(4);
mylist.push(8);
mylist.push(9);
mylist.push(20);
mylist.push(14);
mylist.push(3);
mylist.push(1);
mylist.push(2);
mylist.push(2);
println!("{:?}", mylist);
let selection_sorted = selection_sort(mylist);
println!("{:?}", selection_sorted);
}
|
for j in 0..n-1 {
let mut cur_min = j;
for i in j+1..n {
|
random_line_split
|
selection_sort.rs
|
/*
* Implementation of selection_sort in Rust
*/
fn
|
(mut list: Vec<i32>) -> Vec<i32> {
let n = list.len();
for j in 0..n-1 {
let mut cur_min = j;
for i in j+1..n {
if list[i] < list[cur_min] {
cur_min = i;
}
}
if cur_min!= j {
list.swap(j, cur_min);
}
}
return list;
}
fn main() {
let mut mylist = Vec::new();
mylist.push(5);
mylist.push(4);
mylist.push(8);
mylist.push(9);
mylist.push(20);
mylist.push(14);
mylist.push(3);
mylist.push(1);
mylist.push(2);
mylist.push(2);
println!("{:?}", mylist);
let selection_sorted = selection_sort(mylist);
println!("{:?}", selection_sorted);
}
|
selection_sort
|
identifier_name
|
serialization.rs
|
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use serde_json::map::Map;
use serde_json::{from_str, to_string, Value};
use crate::errors::Result;
pub(crate) fn b64_encode(input: &[u8]) -> String {
base64::encode_config(input, base64::URL_SAFE_NO_PAD)
}
pub(crate) fn b64_decode(input: &str) -> Result<Vec<u8>> {
base64::decode_config(input, base64::URL_SAFE_NO_PAD).map_err(|e| e.into())
}
/// Serializes a struct to JSON and encodes it in base64
pub(crate) fn b64_encode_part<T: Serialize>(input: &T) -> Result<String> {
|
}
/// Decodes from base64 and deserializes from JSON to a struct AND a hashmap of Value so we can
/// run validation on it
pub(crate) fn from_jwt_part_claims<B: AsRef<str>, T: DeserializeOwned>(
encoded: B,
) -> Result<(T, Map<String, Value>)> {
let s = String::from_utf8(b64_decode(encoded.as_ref())?)?;
let claims: T = from_str(&s)?;
let validation_map: Map<_, _> = from_str(&s)?;
Ok((claims, validation_map))
}
|
let json = to_string(input)?;
Ok(b64_encode(json.as_bytes()))
|
random_line_split
|
serialization.rs
|
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use serde_json::map::Map;
use serde_json::{from_str, to_string, Value};
use crate::errors::Result;
pub(crate) fn b64_encode(input: &[u8]) -> String {
base64::encode_config(input, base64::URL_SAFE_NO_PAD)
}
pub(crate) fn b64_decode(input: &str) -> Result<Vec<u8>> {
base64::decode_config(input, base64::URL_SAFE_NO_PAD).map_err(|e| e.into())
}
/// Serializes a struct to JSON and encodes it in base64
pub(crate) fn
|
<T: Serialize>(input: &T) -> Result<String> {
let json = to_string(input)?;
Ok(b64_encode(json.as_bytes()))
}
/// Decodes from base64 and deserializes from JSON to a struct AND a hashmap of Value so we can
/// run validation on it
pub(crate) fn from_jwt_part_claims<B: AsRef<str>, T: DeserializeOwned>(
encoded: B,
) -> Result<(T, Map<String, Value>)> {
let s = String::from_utf8(b64_decode(encoded.as_ref())?)?;
let claims: T = from_str(&s)?;
let validation_map: Map<_, _> = from_str(&s)?;
Ok((claims, validation_map))
}
|
b64_encode_part
|
identifier_name
|
serialization.rs
|
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use serde_json::map::Map;
use serde_json::{from_str, to_string, Value};
use crate::errors::Result;
pub(crate) fn b64_encode(input: &[u8]) -> String
|
pub(crate) fn b64_decode(input: &str) -> Result<Vec<u8>> {
base64::decode_config(input, base64::URL_SAFE_NO_PAD).map_err(|e| e.into())
}
/// Serializes a struct to JSON and encodes it in base64
pub(crate) fn b64_encode_part<T: Serialize>(input: &T) -> Result<String> {
let json = to_string(input)?;
Ok(b64_encode(json.as_bytes()))
}
/// Decodes from base64 and deserializes from JSON to a struct AND a hashmap of Value so we can
/// run validation on it
pub(crate) fn from_jwt_part_claims<B: AsRef<str>, T: DeserializeOwned>(
encoded: B,
) -> Result<(T, Map<String, Value>)> {
let s = String::from_utf8(b64_decode(encoded.as_ref())?)?;
let claims: T = from_str(&s)?;
let validation_map: Map<_, _> = from_str(&s)?;
Ok((claims, validation_map))
}
|
{
base64::encode_config(input, base64::URL_SAFE_NO_PAD)
}
|
identifier_body
|
static-reference-to-fn-2.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.
fn id<T>(x: T) -> T { x }
struct StateMachineIter<'a> {
statefn: &'a StateMachineFunc<'a>
}
|
impl<'a> Iterator for StateMachineIter<'a> {
type Item = &'static str;
fn next(&mut self) -> Option<&'static str> {
return (*self.statefn)(self);
}
}
fn state1(self_: &mut StateMachineIter) -> Option<&'static str> {
self_.statefn = &id(state2 as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state1");
}
fn state2(self_: &mut StateMachineIter) -> Option<(&'static str)> {
self_.statefn = &id(state3 as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state2");
}
fn state3(self_: &mut StateMachineIter) -> Option<(&'static str)> {
self_.statefn = &id(finished as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state3");
}
fn finished(_: &mut StateMachineIter) -> Option<(&'static str)> {
return None;
}
fn state_iter() -> StateMachineIter<'static> {
StateMachineIter {
statefn: &id(state1 as StateMachineFunc)
//~^ ERROR borrowed value does not live long enough
}
}
fn main() {
let mut it = state_iter();
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
}
|
type StateMachineFunc<'a> = fn(&mut StateMachineIter<'a>) -> Option<&'static str>;
|
random_line_split
|
static-reference-to-fn-2.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.
fn id<T>(x: T) -> T { x }
struct StateMachineIter<'a> {
statefn: &'a StateMachineFunc<'a>
}
type StateMachineFunc<'a> = fn(&mut StateMachineIter<'a>) -> Option<&'static str>;
impl<'a> Iterator for StateMachineIter<'a> {
type Item = &'static str;
fn next(&mut self) -> Option<&'static str>
|
}
fn state1(self_: &mut StateMachineIter) -> Option<&'static str> {
self_.statefn = &id(state2 as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state1");
}
fn state2(self_: &mut StateMachineIter) -> Option<(&'static str)> {
self_.statefn = &id(state3 as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state2");
}
fn state3(self_: &mut StateMachineIter) -> Option<(&'static str)> {
self_.statefn = &id(finished as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state3");
}
fn finished(_: &mut StateMachineIter) -> Option<(&'static str)> {
return None;
}
fn state_iter() -> StateMachineIter<'static> {
StateMachineIter {
statefn: &id(state1 as StateMachineFunc)
//~^ ERROR borrowed value does not live long enough
}
}
fn main() {
let mut it = state_iter();
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
}
|
{
return (*self.statefn)(self);
}
|
identifier_body
|
static-reference-to-fn-2.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.
fn id<T>(x: T) -> T { x }
struct StateMachineIter<'a> {
statefn: &'a StateMachineFunc<'a>
}
type StateMachineFunc<'a> = fn(&mut StateMachineIter<'a>) -> Option<&'static str>;
impl<'a> Iterator for StateMachineIter<'a> {
type Item = &'static str;
fn next(&mut self) -> Option<&'static str> {
return (*self.statefn)(self);
}
}
fn
|
(self_: &mut StateMachineIter) -> Option<&'static str> {
self_.statefn = &id(state2 as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state1");
}
fn state2(self_: &mut StateMachineIter) -> Option<(&'static str)> {
self_.statefn = &id(state3 as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state2");
}
fn state3(self_: &mut StateMachineIter) -> Option<(&'static str)> {
self_.statefn = &id(finished as StateMachineFunc);
//~^ ERROR borrowed value does not live long enough
return Some("state3");
}
fn finished(_: &mut StateMachineIter) -> Option<(&'static str)> {
return None;
}
fn state_iter() -> StateMachineIter<'static> {
StateMachineIter {
statefn: &id(state1 as StateMachineFunc)
//~^ ERROR borrowed value does not live long enough
}
}
fn main() {
let mut it = state_iter();
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
println!("{:?}",it.next());
}
|
state1
|
identifier_name
|
main.rs
|
#![feature(core_intrinsics, asm)]
#![feature(start, lang_items)]
#![allow(clippy::missing_safety_doc, unused_imports, dead_code)]
use core::intrinsics::likely;
use faf::const_concat_bytes;
use faf::const_http::*;
use faf::util::{const_len, memcmp};
const ROUTE_PLAINTEXT: &[u8] = b"/plaintext";
const ROUTE_PLAINTEXT_LEN: usize = const_len(ROUTE_PLAINTEXT);
const TEXT_PLAIN_CONTENT_TYPE: &[u8] = b"Content-Type: text/plain";
const CONTENT_LENGTH: &[u8] = b"Content-Length: ";
const PLAINTEXT_BODY: &[u8] = b"Hello, World!";
const PLAINTEXT_BODY_LEN: usize = const_len(PLAINTEXT_BODY);
const PLAINTEXT_BODY_SIZE: &[u8] = b"13";
const PLAINTEXT_BASE: &[u8] = const_concat_bytes!(
HTTP_200_OK,
CRLF,
SERVER,
CRLF,
TEXT_PLAIN_CONTENT_TYPE,
CRLF,
CONTENT_LENGTH,
PLAINTEXT_BODY_SIZE,
CRLF
);
const PLAINTEXT_BASE_LEN: usize = const_len(PLAINTEXT_BASE);
const PLAINTEXT_TEST: &[u8] = b"HTTP/1.1 200 OK\r\nServer: F\r\nContent-Type: text/plain\r\nContent-Length: 13\r\nDate: Thu, 18 Nov 2021 23:15:07 GMT\r\n\r\nHello, World!";
const PLAINTEXT_TEST_LEN: usize = const_len(PLAINTEXT_TEST);
#[inline]
fn cb(
method: *const u8,
method_len: usize,
path: *const u8,
path_len: usize,
response_buffer: *mut u8,
date_buff: *const u8,
) -> usize {
unsafe {
if likely(method_len >= GET_LEN && path_len >= ROUTE_PLAINTEXT_LEN) {
if likely(memcmp(GET.as_ptr(), method, GET_LEN) == 0) {
if likely(memcmp(ROUTE_PLAINTEXT.as_ptr(), path, ROUTE_PLAINTEXT_LEN) == 0) {
core::ptr::copy_nonoverlapping(PLAINTEXT_BASE.as_ptr(), response_buffer, PLAINTEXT_BASE_LEN);
core::ptr::copy_nonoverlapping(date_buff, response_buffer.add(PLAINTEXT_BASE_LEN), DATE_LEN);
core::ptr::copy_nonoverlapping(
CRLFCRLF.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN),
CRLFCRLF_LEN,
);
core::ptr::copy_nonoverlapping(
PLAINTEXT_BODY.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN),
PLAINTEXT_BODY_LEN,
);
PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN + PLAINTEXT_BODY_LEN
} else {
core::ptr::copy_nonoverlapping(HTTP_404_NOTFOUND.as_ptr(), response_buffer, HTTP_404_NOTFOUND_LEN);
HTTP_404_NOTFOUND_LEN
}
} else {
core::ptr::copy_nonoverlapping(HTTP_405_NOTALLOWED.as_ptr(), response_buffer, HTTP_405_NOTALLOWED_LEN);
HTTP_405_NOTALLOWED_LEN
}
} else {
0
}
}
}
pub fn main()
|
{
faf::epoll::go(8089, cb);
}
|
identifier_body
|
|
main.rs
|
#![feature(core_intrinsics, asm)]
#![feature(start, lang_items)]
#![allow(clippy::missing_safety_doc, unused_imports, dead_code)]
use core::intrinsics::likely;
use faf::const_concat_bytes;
use faf::const_http::*;
use faf::util::{const_len, memcmp};
const ROUTE_PLAINTEXT: &[u8] = b"/plaintext";
const ROUTE_PLAINTEXT_LEN: usize = const_len(ROUTE_PLAINTEXT);
const TEXT_PLAIN_CONTENT_TYPE: &[u8] = b"Content-Type: text/plain";
const CONTENT_LENGTH: &[u8] = b"Content-Length: ";
const PLAINTEXT_BODY: &[u8] = b"Hello, World!";
const PLAINTEXT_BODY_LEN: usize = const_len(PLAINTEXT_BODY);
const PLAINTEXT_BODY_SIZE: &[u8] = b"13";
const PLAINTEXT_BASE: &[u8] = const_concat_bytes!(
HTTP_200_OK,
CRLF,
SERVER,
CRLF,
TEXT_PLAIN_CONTENT_TYPE,
CRLF,
CONTENT_LENGTH,
PLAINTEXT_BODY_SIZE,
CRLF
);
const PLAINTEXT_BASE_LEN: usize = const_len(PLAINTEXT_BASE);
const PLAINTEXT_TEST: &[u8] = b"HTTP/1.1 200 OK\r\nServer: F\r\nContent-Type: text/plain\r\nContent-Length: 13\r\nDate: Thu, 18 Nov 2021 23:15:07 GMT\r\n\r\nHello, World!";
const PLAINTEXT_TEST_LEN: usize = const_len(PLAINTEXT_TEST);
#[inline]
fn cb(
method: *const u8,
method_len: usize,
path: *const u8,
path_len: usize,
response_buffer: *mut u8,
date_buff: *const u8,
) -> usize {
unsafe {
if likely(method_len >= GET_LEN && path_len >= ROUTE_PLAINTEXT_LEN) {
if likely(memcmp(GET.as_ptr(), method, GET_LEN) == 0) {
if likely(memcmp(ROUTE_PLAINTEXT.as_ptr(), path, ROUTE_PLAINTEXT_LEN) == 0) {
core::ptr::copy_nonoverlapping(PLAINTEXT_BASE.as_ptr(), response_buffer, PLAINTEXT_BASE_LEN);
core::ptr::copy_nonoverlapping(date_buff, response_buffer.add(PLAINTEXT_BASE_LEN), DATE_LEN);
core::ptr::copy_nonoverlapping(
CRLFCRLF.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN),
CRLFCRLF_LEN,
);
core::ptr::copy_nonoverlapping(
PLAINTEXT_BODY.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN),
PLAINTEXT_BODY_LEN,
);
PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN + PLAINTEXT_BODY_LEN
} else {
core::ptr::copy_nonoverlapping(HTTP_404_NOTFOUND.as_ptr(), response_buffer, HTTP_404_NOTFOUND_LEN);
HTTP_404_NOTFOUND_LEN
}
} else {
core::ptr::copy_nonoverlapping(HTTP_405_NOTALLOWED.as_ptr(), response_buffer, HTTP_405_NOTALLOWED_LEN);
HTTP_405_NOTALLOWED_LEN
}
} else {
0
}
}
}
pub fn
|
() {
faf::epoll::go(8089, cb);
}
|
main
|
identifier_name
|
main.rs
|
#![feature(core_intrinsics, asm)]
#![feature(start, lang_items)]
#![allow(clippy::missing_safety_doc, unused_imports, dead_code)]
use core::intrinsics::likely;
use faf::const_concat_bytes;
use faf::const_http::*;
use faf::util::{const_len, memcmp};
const ROUTE_PLAINTEXT: &[u8] = b"/plaintext";
const ROUTE_PLAINTEXT_LEN: usize = const_len(ROUTE_PLAINTEXT);
const TEXT_PLAIN_CONTENT_TYPE: &[u8] = b"Content-Type: text/plain";
const CONTENT_LENGTH: &[u8] = b"Content-Length: ";
const PLAINTEXT_BODY: &[u8] = b"Hello, World!";
const PLAINTEXT_BODY_LEN: usize = const_len(PLAINTEXT_BODY);
const PLAINTEXT_BODY_SIZE: &[u8] = b"13";
const PLAINTEXT_BASE: &[u8] = const_concat_bytes!(
HTTP_200_OK,
CRLF,
SERVER,
CRLF,
TEXT_PLAIN_CONTENT_TYPE,
CRLF,
CONTENT_LENGTH,
PLAINTEXT_BODY_SIZE,
CRLF
);
const PLAINTEXT_BASE_LEN: usize = const_len(PLAINTEXT_BASE);
const PLAINTEXT_TEST: &[u8] = b"HTTP/1.1 200 OK\r\nServer: F\r\nContent-Type: text/plain\r\nContent-Length: 13\r\nDate: Thu, 18 Nov 2021 23:15:07 GMT\r\n\r\nHello, World!";
const PLAINTEXT_TEST_LEN: usize = const_len(PLAINTEXT_TEST);
#[inline]
fn cb(
method: *const u8,
method_len: usize,
path: *const u8,
path_len: usize,
response_buffer: *mut u8,
date_buff: *const u8,
) -> usize {
unsafe {
if likely(method_len >= GET_LEN && path_len >= ROUTE_PLAINTEXT_LEN) {
if likely(memcmp(GET.as_ptr(), method, GET_LEN) == 0) {
if likely(memcmp(ROUTE_PLAINTEXT.as_ptr(), path, ROUTE_PLAINTEXT_LEN) == 0) {
core::ptr::copy_nonoverlapping(PLAINTEXT_BASE.as_ptr(), response_buffer, PLAINTEXT_BASE_LEN);
core::ptr::copy_nonoverlapping(date_buff, response_buffer.add(PLAINTEXT_BASE_LEN), DATE_LEN);
core::ptr::copy_nonoverlapping(
CRLFCRLF.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN),
CRLFCRLF_LEN,
);
core::ptr::copy_nonoverlapping(
PLAINTEXT_BODY.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN),
PLAINTEXT_BODY_LEN,
);
PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN + PLAINTEXT_BODY_LEN
} else {
core::ptr::copy_nonoverlapping(HTTP_404_NOTFOUND.as_ptr(), response_buffer, HTTP_404_NOTFOUND_LEN);
HTTP_404_NOTFOUND_LEN
}
} else
|
} else {
0
}
}
}
pub fn main() {
faf::epoll::go(8089, cb);
}
|
{
core::ptr::copy_nonoverlapping(HTTP_405_NOTALLOWED.as_ptr(), response_buffer, HTTP_405_NOTALLOWED_LEN);
HTTP_405_NOTALLOWED_LEN
}
|
conditional_block
|
main.rs
|
#![feature(core_intrinsics, asm)]
#![feature(start, lang_items)]
#![allow(clippy::missing_safety_doc, unused_imports, dead_code)]
use core::intrinsics::likely;
use faf::const_concat_bytes;
use faf::const_http::*;
use faf::util::{const_len, memcmp};
const ROUTE_PLAINTEXT: &[u8] = b"/plaintext";
const ROUTE_PLAINTEXT_LEN: usize = const_len(ROUTE_PLAINTEXT);
const TEXT_PLAIN_CONTENT_TYPE: &[u8] = b"Content-Type: text/plain";
const CONTENT_LENGTH: &[u8] = b"Content-Length: ";
const PLAINTEXT_BODY: &[u8] = b"Hello, World!";
const PLAINTEXT_BODY_LEN: usize = const_len(PLAINTEXT_BODY);
const PLAINTEXT_BODY_SIZE: &[u8] = b"13";
const PLAINTEXT_BASE: &[u8] = const_concat_bytes!(
HTTP_200_OK,
CRLF,
SERVER,
CRLF,
TEXT_PLAIN_CONTENT_TYPE,
CRLF,
CONTENT_LENGTH,
PLAINTEXT_BODY_SIZE,
|
const PLAINTEXT_BASE_LEN: usize = const_len(PLAINTEXT_BASE);
const PLAINTEXT_TEST: &[u8] = b"HTTP/1.1 200 OK\r\nServer: F\r\nContent-Type: text/plain\r\nContent-Length: 13\r\nDate: Thu, 18 Nov 2021 23:15:07 GMT\r\n\r\nHello, World!";
const PLAINTEXT_TEST_LEN: usize = const_len(PLAINTEXT_TEST);
#[inline]
fn cb(
method: *const u8,
method_len: usize,
path: *const u8,
path_len: usize,
response_buffer: *mut u8,
date_buff: *const u8,
) -> usize {
unsafe {
if likely(method_len >= GET_LEN && path_len >= ROUTE_PLAINTEXT_LEN) {
if likely(memcmp(GET.as_ptr(), method, GET_LEN) == 0) {
if likely(memcmp(ROUTE_PLAINTEXT.as_ptr(), path, ROUTE_PLAINTEXT_LEN) == 0) {
core::ptr::copy_nonoverlapping(PLAINTEXT_BASE.as_ptr(), response_buffer, PLAINTEXT_BASE_LEN);
core::ptr::copy_nonoverlapping(date_buff, response_buffer.add(PLAINTEXT_BASE_LEN), DATE_LEN);
core::ptr::copy_nonoverlapping(
CRLFCRLF.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN),
CRLFCRLF_LEN,
);
core::ptr::copy_nonoverlapping(
PLAINTEXT_BODY.as_ptr(),
response_buffer.add(PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN),
PLAINTEXT_BODY_LEN,
);
PLAINTEXT_BASE_LEN + DATE_LEN + CRLFCRLF_LEN + PLAINTEXT_BODY_LEN
} else {
core::ptr::copy_nonoverlapping(HTTP_404_NOTFOUND.as_ptr(), response_buffer, HTTP_404_NOTFOUND_LEN);
HTTP_404_NOTFOUND_LEN
}
} else {
core::ptr::copy_nonoverlapping(HTTP_405_NOTALLOWED.as_ptr(), response_buffer, HTTP_405_NOTALLOWED_LEN);
HTTP_405_NOTALLOWED_LEN
}
} else {
0
}
}
}
pub fn main() {
faf::epoll::go(8089, cb);
}
|
CRLF
);
|
random_line_split
|
lib.rs
|
extern crate bigtable as bt;
#[macro_use]
extern crate error_chain;
extern crate libc;
extern crate goauth;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate protobuf;
extern crate rustc_serialize;
mod fdw_error {
error_chain! {
foreign_links {
FromUtf8(::std::string::FromUtf8Error);
Utf8(::std::str::Utf8Error);
Io(::std::io::Error);
Base64(::rustc_serialize::base64::FromBase64Error);
Auth(::goauth::error::GOErr);
Ffi(::std::ffi::NulError);
Bt(::bt::error::BTErr);
Json(::serde_json::Error);
}
}
}
mod fdw;
#[allow(unused_variables)]
pub mod ffi;
#[allow(dead_code)]
|
#[allow(non_snake_case)]
#[allow(non_upper_case_globals)]
mod pg; // Generated PG bindings
mod structs;
static mut LIMIT: Option<i64> = Some(0);
|
#[allow(non_camel_case_types)]
#[allow(improper_ctypes)]
|
random_line_split
|
mod.rs
|
#![cfg_attr(test, allow(dead_code))]
use ::scene::{Camera, Scene};
pub mod bunny;
pub mod cornell;
pub mod cow;
pub mod easing;
pub mod fresnel;
pub mod heptoroid;
pub mod lucy;
pub mod sibenik;
pub mod sphere;
pub mod sponza;
pub mod tachikoma;
pub mod teapot;
pub trait SceneConfig {
fn get_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera;
fn get_animation_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera {
self.get_camera(image_width, image_height, fov)
}
fn get_scene(&self) -> Scene;
}
|
pub fn scene_by_name(name: &str) -> Option<Box<SceneConfig>> {
Some(match name {
"bunny" => Box::new(bunny::BunnyConfig),
"cornell" => Box::new(cornell::CornelConfig),
"cow" => Box::new(cow::CowConfig),
"easing" => Box::new(easing::EasingConfig),
"fresnel" => Box::new(fresnel::FresnelConfig),
"heptoroid-shiny" => Box::new(heptoroid::HeptoroidConfig::shiny()),
"heptoroid-white" => Box::new(heptoroid::HeptoroidConfig::white()),
"heptoroid-refractive" => Box::new(heptoroid::HeptoroidConfig::refractive()),
"lucy" => Box::new(lucy::LucyConfig),
"sibenik" => Box::new(sibenik::SibenikConfig),
"sphere" => Box::new(sphere::SphereConfig),
"sponza" => Box::new(sponza::SponzaConfig),
"tachikoma" => Box::new(tachikoma::TachikomaConfig),
"teapot" => Box::new(teapot::TeapotConfig),
_ => return None,
})
}
|
random_line_split
|
|
mod.rs
|
#![cfg_attr(test, allow(dead_code))]
use ::scene::{Camera, Scene};
pub mod bunny;
pub mod cornell;
pub mod cow;
pub mod easing;
pub mod fresnel;
pub mod heptoroid;
pub mod lucy;
pub mod sibenik;
pub mod sphere;
pub mod sponza;
pub mod tachikoma;
pub mod teapot;
pub trait SceneConfig {
fn get_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera;
fn get_animation_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera
|
fn get_scene(&self) -> Scene;
}
pub fn scene_by_name(name: &str) -> Option<Box<SceneConfig>> {
Some(match name {
"bunny" => Box::new(bunny::BunnyConfig),
"cornell" => Box::new(cornell::CornelConfig),
"cow" => Box::new(cow::CowConfig),
"easing" => Box::new(easing::EasingConfig),
"fresnel" => Box::new(fresnel::FresnelConfig),
"heptoroid-shiny" => Box::new(heptoroid::HeptoroidConfig::shiny()),
"heptoroid-white" => Box::new(heptoroid::HeptoroidConfig::white()),
"heptoroid-refractive" => Box::new(heptoroid::HeptoroidConfig::refractive()),
"lucy" => Box::new(lucy::LucyConfig),
"sibenik" => Box::new(sibenik::SibenikConfig),
"sphere" => Box::new(sphere::SphereConfig),
"sponza" => Box::new(sponza::SponzaConfig),
"tachikoma" => Box::new(tachikoma::TachikomaConfig),
"teapot" => Box::new(teapot::TeapotConfig),
_ => return None,
})
}
|
{
self.get_camera(image_width, image_height, fov)
}
|
identifier_body
|
mod.rs
|
#![cfg_attr(test, allow(dead_code))]
use ::scene::{Camera, Scene};
pub mod bunny;
pub mod cornell;
pub mod cow;
pub mod easing;
pub mod fresnel;
pub mod heptoroid;
pub mod lucy;
pub mod sibenik;
pub mod sphere;
pub mod sponza;
pub mod tachikoma;
pub mod teapot;
pub trait SceneConfig {
fn get_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera;
fn get_animation_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera {
self.get_camera(image_width, image_height, fov)
}
fn get_scene(&self) -> Scene;
}
pub fn
|
(name: &str) -> Option<Box<SceneConfig>> {
Some(match name {
"bunny" => Box::new(bunny::BunnyConfig),
"cornell" => Box::new(cornell::CornelConfig),
"cow" => Box::new(cow::CowConfig),
"easing" => Box::new(easing::EasingConfig),
"fresnel" => Box::new(fresnel::FresnelConfig),
"heptoroid-shiny" => Box::new(heptoroid::HeptoroidConfig::shiny()),
"heptoroid-white" => Box::new(heptoroid::HeptoroidConfig::white()),
"heptoroid-refractive" => Box::new(heptoroid::HeptoroidConfig::refractive()),
"lucy" => Box::new(lucy::LucyConfig),
"sibenik" => Box::new(sibenik::SibenikConfig),
"sphere" => Box::new(sphere::SphereConfig),
"sponza" => Box::new(sponza::SponzaConfig),
"tachikoma" => Box::new(tachikoma::TachikomaConfig),
"teapot" => Box::new(teapot::TeapotConfig),
_ => return None,
})
}
|
scene_by_name
|
identifier_name
|
image.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-values
use crate::custom_properties;
use crate::values::serialize_atom_identifier;
use crate::Atom;
use servo_arc::Arc;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// An [image].
///
/// [image]: https://drafts.csswg.org/css-images/#image-values
#[derive(Clone, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub enum Image<Gradient, MozImageRect, ImageUrl> {
/// A `<url()>` image.
Url(ImageUrl),
/// A `<gradient>` image. Gradients are rather large, and not nearly as
/// common as urls, so we box them here to keep the size of this enum sane.
Gradient(Box<Gradient>),
/// A `-moz-image-rect` image. Also fairly large and rare.
Rect(Box<MozImageRect>),
/// A `-moz-element(# <element-id>)`
#[css(function = "-moz-element")]
Element(Atom),
/// A paint worklet image.
/// <https://drafts.css-houdini.org/css-paint-api/>
#[cfg(feature = "servo")]
PaintWorklet(PaintWorklet),
}
/// A CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct Gradient<LineDirection, Length, LengthOrPercentage, Position, Color, Angle> {
/// Gradients can be linear or radial.
pub kind: GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle>,
/// The color stops and interpolation hints.
pub items: Vec<GradientItem<Color, LengthOrPercentage>>,
/// True if this is a repeating gradient.
pub repeating: bool,
/// Compatibility mode.
pub compat_mode: CompatMode,
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
/// Whether we used the modern notation or the compatibility `-webkit`, `-moz` prefixes.
pub enum CompatMode {
/// Modern syntax.
Modern,
/// `-webkit` prefix.
WebKit,
/// `-moz` prefix
Moz,
}
/// A gradient kind.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum
|
<LineDirection, Length, LengthOrPercentage, Position, Angle> {
/// A linear gradient.
Linear(LineDirection),
/// A radial gradient.
Radial(
EndingShape<Length, LengthOrPercentage>,
Position,
Option<Angle>,
),
}
/// A radial gradient's ending shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum EndingShape<Length, LengthOrPercentage> {
/// A circular gradient.
Circle(Circle<Length>),
/// An elliptic gradient.
Ellipse(Ellipse<LengthOrPercentage>),
}
/// A circle shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum Circle<Length> {
/// A circle radius.
Radius(Length),
/// A circle extent.
Extent(ShapeExtent),
}
/// An ellipse shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum Ellipse<LengthOrPercentage> {
/// An ellipse pair of radii.
Radii(LengthOrPercentage, LengthOrPercentage),
/// An ellipse extent.
Extent(ShapeExtent),
}
/// <https://drafts.csswg.org/css-images/#typedef-extent-keyword>
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)]
pub enum ShapeExtent {
ClosestSide,
FarthestSide,
ClosestCorner,
FarthestCorner,
Contain,
Cover,
}
/// A gradient item.
/// <https://drafts.csswg.org/css-images-4/#color-stop-syntax>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum GradientItem<Color, LengthOrPercentage> {
/// A color stop.
ColorStop(ColorStop<Color, LengthOrPercentage>),
/// An interpolation hint.
InterpolationHint(LengthOrPercentage),
}
/// A color stop.
/// <https://drafts.csswg.org/css-images/#typedef-color-stop-list>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub struct ColorStop<Color, LengthOrPercentage> {
/// The color of this stop.
pub color: Color,
/// The position of this stop.
pub position: Option<LengthOrPercentage>,
}
/// Specified values for a paint worklet.
/// <https://drafts.css-houdini.org/css-paint-api/>
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
#[derive(Clone, Debug, PartialEq, ToComputedValue)]
pub struct PaintWorklet {
/// The name the worklet was registered with.
pub name: Atom,
/// The arguments for the worklet.
/// TODO: store a parsed representation of the arguments.
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
pub arguments: Vec<Arc<custom_properties::SpecifiedValue>>,
}
impl ::style_traits::SpecifiedValueInfo for PaintWorklet {}
impl ToCss for PaintWorklet {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("paint(")?;
serialize_atom_identifier(&self.name, dest)?;
for argument in &self.arguments {
dest.write_str(", ")?;
argument.to_css(dest)?;
}
dest.write_str(")")
}
}
/// Values for `moz-image-rect`.
///
/// `-moz-image-rect(<uri>, top, right, bottom, left);`
#[allow(missing_docs)]
#[css(comma, function)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> {
pub url: MozImageRectUrl,
pub top: NumberOrPercentage,
pub right: NumberOrPercentage,
pub bottom: NumberOrPercentage,
pub left: NumberOrPercentage,
}
impl<G, R, U> fmt::Debug for Image<G, R, U>
where
G: ToCss,
R: ToCss,
U: ToCss,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_css(&mut CssWriter::new(f))
}
}
impl<G, R, U> ToCss for Image<G, R, U>
where
G: ToCss,
R: ToCss,
U: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self {
Image::Url(ref url) => url.to_css(dest),
Image::Gradient(ref gradient) => gradient.to_css(dest),
Image::Rect(ref rect) => rect.to_css(dest),
#[cfg(feature = "servo")]
Image::PaintWorklet(ref paint_worklet) => paint_worklet.to_css(dest),
Image::Element(ref selector) => {
dest.write_str("-moz-element(#")?;
serialize_atom_identifier(selector, dest)?;
dest.write_str(")")
},
}
}
}
impl<D, L, LoP, P, C, A> ToCss for Gradient<D, L, LoP, P, C, A>
where
D: LineDirection,
L: ToCss,
LoP: ToCss,
P: ToCss,
C: ToCss,
A: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match self.compat_mode {
CompatMode::WebKit => dest.write_str("-webkit-")?,
CompatMode::Moz => dest.write_str("-moz-")?,
_ => {},
}
if self.repeating {
dest.write_str("repeating-")?;
}
dest.write_str(self.kind.label())?;
dest.write_str("-gradient(")?;
let mut skip_comma = match self.kind {
GradientKind::Linear(ref direction) if direction.points_downwards(self.compat_mode) => {
true
},
GradientKind::Linear(ref direction) => {
direction.to_css(dest, self.compat_mode)?;
false
},
GradientKind::Radial(ref shape, ref position, ref angle) => {
let omit_shape = match *shape {
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::Cover)) |
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner)) => true,
_ => false,
};
if self.compat_mode == CompatMode::Modern {
if!omit_shape {
shape.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
position.to_css(dest)?;
} else {
position.to_css(dest)?;
if let Some(ref a) = *angle {
dest.write_str(" ")?;
a.to_css(dest)?;
}
if!omit_shape {
dest.write_str(", ")?;
shape.to_css(dest)?;
}
}
false
},
};
for item in &self.items {
if!skip_comma {
dest.write_str(", ")?;
}
skip_comma = false;
item.to_css(dest)?;
}
dest.write_str(")")
}
}
impl<D, L, LoP, P, A> GradientKind<D, L, LoP, P, A> {
fn label(&self) -> &str {
match *self {
GradientKind::Linear(..) => "linear",
GradientKind::Radial(..) => "radial",
}
}
}
/// The direction of a linear gradient.
pub trait LineDirection {
/// Whether this direction points towards, and thus can be omitted.
fn points_downwards(&self, compat_mode: CompatMode) -> bool;
/// Serialises this direction according to the compatibility mode.
fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: CompatMode) -> fmt::Result
where
W: Write;
}
impl<L> ToCss for Circle<L>
where
L: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self {
Circle::Extent(ShapeExtent::FarthestCorner) | Circle::Extent(ShapeExtent::Cover) => {
dest.write_str("circle")
},
Circle::Extent(keyword) => {
dest.write_str("circle ")?;
keyword.to_css(dest)
},
Circle::Radius(ref length) => length.to_css(dest),
}
}
}
|
GradientKind
|
identifier_name
|
image.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-values
use crate::custom_properties;
use crate::values::serialize_atom_identifier;
use crate::Atom;
use servo_arc::Arc;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// An [image].
///
/// [image]: https://drafts.csswg.org/css-images/#image-values
#[derive(Clone, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub enum Image<Gradient, MozImageRect, ImageUrl> {
/// A `<url()>` image.
Url(ImageUrl),
/// A `<gradient>` image. Gradients are rather large, and not nearly as
/// common as urls, so we box them here to keep the size of this enum sane.
Gradient(Box<Gradient>),
/// A `-moz-image-rect` image. Also fairly large and rare.
Rect(Box<MozImageRect>),
/// A `-moz-element(# <element-id>)`
#[css(function = "-moz-element")]
Element(Atom),
/// A paint worklet image.
/// <https://drafts.css-houdini.org/css-paint-api/>
#[cfg(feature = "servo")]
PaintWorklet(PaintWorklet),
}
/// A CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct Gradient<LineDirection, Length, LengthOrPercentage, Position, Color, Angle> {
/// Gradients can be linear or radial.
pub kind: GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle>,
/// The color stops and interpolation hints.
pub items: Vec<GradientItem<Color, LengthOrPercentage>>,
/// True if this is a repeating gradient.
pub repeating: bool,
/// Compatibility mode.
pub compat_mode: CompatMode,
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
/// Whether we used the modern notation or the compatibility `-webkit`, `-moz` prefixes.
pub enum CompatMode {
/// Modern syntax.
Modern,
/// `-webkit` prefix.
WebKit,
/// `-moz` prefix
Moz,
}
/// A gradient kind.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle> {
/// A linear gradient.
Linear(LineDirection),
/// A radial gradient.
Radial(
EndingShape<Length, LengthOrPercentage>,
Position,
Option<Angle>,
),
}
/// A radial gradient's ending shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum EndingShape<Length, LengthOrPercentage> {
/// A circular gradient.
Circle(Circle<Length>),
/// An elliptic gradient.
Ellipse(Ellipse<LengthOrPercentage>),
}
/// A circle shape.
|
Extent(ShapeExtent),
}
/// An ellipse shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum Ellipse<LengthOrPercentage> {
/// An ellipse pair of radii.
Radii(LengthOrPercentage, LengthOrPercentage),
/// An ellipse extent.
Extent(ShapeExtent),
}
/// <https://drafts.csswg.org/css-images/#typedef-extent-keyword>
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)]
pub enum ShapeExtent {
ClosestSide,
FarthestSide,
ClosestCorner,
FarthestCorner,
Contain,
Cover,
}
/// A gradient item.
/// <https://drafts.csswg.org/css-images-4/#color-stop-syntax>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum GradientItem<Color, LengthOrPercentage> {
/// A color stop.
ColorStop(ColorStop<Color, LengthOrPercentage>),
/// An interpolation hint.
InterpolationHint(LengthOrPercentage),
}
/// A color stop.
/// <https://drafts.csswg.org/css-images/#typedef-color-stop-list>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub struct ColorStop<Color, LengthOrPercentage> {
/// The color of this stop.
pub color: Color,
/// The position of this stop.
pub position: Option<LengthOrPercentage>,
}
/// Specified values for a paint worklet.
/// <https://drafts.css-houdini.org/css-paint-api/>
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
#[derive(Clone, Debug, PartialEq, ToComputedValue)]
pub struct PaintWorklet {
/// The name the worklet was registered with.
pub name: Atom,
/// The arguments for the worklet.
/// TODO: store a parsed representation of the arguments.
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
pub arguments: Vec<Arc<custom_properties::SpecifiedValue>>,
}
impl ::style_traits::SpecifiedValueInfo for PaintWorklet {}
impl ToCss for PaintWorklet {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("paint(")?;
serialize_atom_identifier(&self.name, dest)?;
for argument in &self.arguments {
dest.write_str(", ")?;
argument.to_css(dest)?;
}
dest.write_str(")")
}
}
/// Values for `moz-image-rect`.
///
/// `-moz-image-rect(<uri>, top, right, bottom, left);`
#[allow(missing_docs)]
#[css(comma, function)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> {
pub url: MozImageRectUrl,
pub top: NumberOrPercentage,
pub right: NumberOrPercentage,
pub bottom: NumberOrPercentage,
pub left: NumberOrPercentage,
}
impl<G, R, U> fmt::Debug for Image<G, R, U>
where
G: ToCss,
R: ToCss,
U: ToCss,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_css(&mut CssWriter::new(f))
}
}
impl<G, R, U> ToCss for Image<G, R, U>
where
G: ToCss,
R: ToCss,
U: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self {
Image::Url(ref url) => url.to_css(dest),
Image::Gradient(ref gradient) => gradient.to_css(dest),
Image::Rect(ref rect) => rect.to_css(dest),
#[cfg(feature = "servo")]
Image::PaintWorklet(ref paint_worklet) => paint_worklet.to_css(dest),
Image::Element(ref selector) => {
dest.write_str("-moz-element(#")?;
serialize_atom_identifier(selector, dest)?;
dest.write_str(")")
},
}
}
}
impl<D, L, LoP, P, C, A> ToCss for Gradient<D, L, LoP, P, C, A>
where
D: LineDirection,
L: ToCss,
LoP: ToCss,
P: ToCss,
C: ToCss,
A: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match self.compat_mode {
CompatMode::WebKit => dest.write_str("-webkit-")?,
CompatMode::Moz => dest.write_str("-moz-")?,
_ => {},
}
if self.repeating {
dest.write_str("repeating-")?;
}
dest.write_str(self.kind.label())?;
dest.write_str("-gradient(")?;
let mut skip_comma = match self.kind {
GradientKind::Linear(ref direction) if direction.points_downwards(self.compat_mode) => {
true
},
GradientKind::Linear(ref direction) => {
direction.to_css(dest, self.compat_mode)?;
false
},
GradientKind::Radial(ref shape, ref position, ref angle) => {
let omit_shape = match *shape {
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::Cover)) |
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner)) => true,
_ => false,
};
if self.compat_mode == CompatMode::Modern {
if!omit_shape {
shape.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
position.to_css(dest)?;
} else {
position.to_css(dest)?;
if let Some(ref a) = *angle {
dest.write_str(" ")?;
a.to_css(dest)?;
}
if!omit_shape {
dest.write_str(", ")?;
shape.to_css(dest)?;
}
}
false
},
};
for item in &self.items {
if!skip_comma {
dest.write_str(", ")?;
}
skip_comma = false;
item.to_css(dest)?;
}
dest.write_str(")")
}
}
impl<D, L, LoP, P, A> GradientKind<D, L, LoP, P, A> {
fn label(&self) -> &str {
match *self {
GradientKind::Linear(..) => "linear",
GradientKind::Radial(..) => "radial",
}
}
}
/// The direction of a linear gradient.
pub trait LineDirection {
/// Whether this direction points towards, and thus can be omitted.
fn points_downwards(&self, compat_mode: CompatMode) -> bool;
/// Serialises this direction according to the compatibility mode.
fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: CompatMode) -> fmt::Result
where
W: Write;
}
impl<L> ToCss for Circle<L>
where
L: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self {
Circle::Extent(ShapeExtent::FarthestCorner) | Circle::Extent(ShapeExtent::Cover) => {
dest.write_str("circle")
},
Circle::Extent(keyword) => {
dest.write_str("circle ")?;
keyword.to_css(dest)
},
Circle::Radius(ref length) => length.to_css(dest),
}
}
}
|
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum Circle<Length> {
/// A circle radius.
Radius(Length),
/// A circle extent.
|
random_line_split
|
image.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-values
use crate::custom_properties;
use crate::values::serialize_atom_identifier;
use crate::Atom;
use servo_arc::Arc;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// An [image].
///
/// [image]: https://drafts.csswg.org/css-images/#image-values
#[derive(Clone, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub enum Image<Gradient, MozImageRect, ImageUrl> {
/// A `<url()>` image.
Url(ImageUrl),
/// A `<gradient>` image. Gradients are rather large, and not nearly as
/// common as urls, so we box them here to keep the size of this enum sane.
Gradient(Box<Gradient>),
/// A `-moz-image-rect` image. Also fairly large and rare.
Rect(Box<MozImageRect>),
/// A `-moz-element(# <element-id>)`
#[css(function = "-moz-element")]
Element(Atom),
/// A paint worklet image.
/// <https://drafts.css-houdini.org/css-paint-api/>
#[cfg(feature = "servo")]
PaintWorklet(PaintWorklet),
}
/// A CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct Gradient<LineDirection, Length, LengthOrPercentage, Position, Color, Angle> {
/// Gradients can be linear or radial.
pub kind: GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle>,
/// The color stops and interpolation hints.
pub items: Vec<GradientItem<Color, LengthOrPercentage>>,
/// True if this is a repeating gradient.
pub repeating: bool,
/// Compatibility mode.
pub compat_mode: CompatMode,
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
/// Whether we used the modern notation or the compatibility `-webkit`, `-moz` prefixes.
pub enum CompatMode {
/// Modern syntax.
Modern,
/// `-webkit` prefix.
WebKit,
/// `-moz` prefix
Moz,
}
/// A gradient kind.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle> {
/// A linear gradient.
Linear(LineDirection),
/// A radial gradient.
Radial(
EndingShape<Length, LengthOrPercentage>,
Position,
Option<Angle>,
),
}
/// A radial gradient's ending shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum EndingShape<Length, LengthOrPercentage> {
/// A circular gradient.
Circle(Circle<Length>),
/// An elliptic gradient.
Ellipse(Ellipse<LengthOrPercentage>),
}
/// A circle shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum Circle<Length> {
/// A circle radius.
Radius(Length),
/// A circle extent.
Extent(ShapeExtent),
}
/// An ellipse shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum Ellipse<LengthOrPercentage> {
/// An ellipse pair of radii.
Radii(LengthOrPercentage, LengthOrPercentage),
/// An ellipse extent.
Extent(ShapeExtent),
}
/// <https://drafts.csswg.org/css-images/#typedef-extent-keyword>
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)]
pub enum ShapeExtent {
ClosestSide,
FarthestSide,
ClosestCorner,
FarthestCorner,
Contain,
Cover,
}
/// A gradient item.
/// <https://drafts.csswg.org/css-images-4/#color-stop-syntax>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum GradientItem<Color, LengthOrPercentage> {
/// A color stop.
ColorStop(ColorStop<Color, LengthOrPercentage>),
/// An interpolation hint.
InterpolationHint(LengthOrPercentage),
}
/// A color stop.
/// <https://drafts.csswg.org/css-images/#typedef-color-stop-list>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub struct ColorStop<Color, LengthOrPercentage> {
/// The color of this stop.
pub color: Color,
/// The position of this stop.
pub position: Option<LengthOrPercentage>,
}
/// Specified values for a paint worklet.
/// <https://drafts.css-houdini.org/css-paint-api/>
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
#[derive(Clone, Debug, PartialEq, ToComputedValue)]
pub struct PaintWorklet {
/// The name the worklet was registered with.
pub name: Atom,
/// The arguments for the worklet.
/// TODO: store a parsed representation of the arguments.
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
pub arguments: Vec<Arc<custom_properties::SpecifiedValue>>,
}
impl ::style_traits::SpecifiedValueInfo for PaintWorklet {}
impl ToCss for PaintWorklet {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str("paint(")?;
serialize_atom_identifier(&self.name, dest)?;
for argument in &self.arguments {
dest.write_str(", ")?;
argument.to_css(dest)?;
}
dest.write_str(")")
}
}
/// Values for `moz-image-rect`.
///
/// `-moz-image-rect(<uri>, top, right, bottom, left);`
#[allow(missing_docs)]
#[css(comma, function)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> {
pub url: MozImageRectUrl,
pub top: NumberOrPercentage,
pub right: NumberOrPercentage,
pub bottom: NumberOrPercentage,
pub left: NumberOrPercentage,
}
impl<G, R, U> fmt::Debug for Image<G, R, U>
where
G: ToCss,
R: ToCss,
U: ToCss,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_css(&mut CssWriter::new(f))
}
}
impl<G, R, U> ToCss for Image<G, R, U>
where
G: ToCss,
R: ToCss,
U: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self {
Image::Url(ref url) => url.to_css(dest),
Image::Gradient(ref gradient) => gradient.to_css(dest),
Image::Rect(ref rect) => rect.to_css(dest),
#[cfg(feature = "servo")]
Image::PaintWorklet(ref paint_worklet) => paint_worklet.to_css(dest),
Image::Element(ref selector) => {
dest.write_str("-moz-element(#")?;
serialize_atom_identifier(selector, dest)?;
dest.write_str(")")
},
}
}
}
impl<D, L, LoP, P, C, A> ToCss for Gradient<D, L, LoP, P, C, A>
where
D: LineDirection,
L: ToCss,
LoP: ToCss,
P: ToCss,
C: ToCss,
A: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match self.compat_mode {
CompatMode::WebKit => dest.write_str("-webkit-")?,
CompatMode::Moz => dest.write_str("-moz-")?,
_ => {},
}
if self.repeating {
dest.write_str("repeating-")?;
}
dest.write_str(self.kind.label())?;
dest.write_str("-gradient(")?;
let mut skip_comma = match self.kind {
GradientKind::Linear(ref direction) if direction.points_downwards(self.compat_mode) => {
true
},
GradientKind::Linear(ref direction) =>
|
,
GradientKind::Radial(ref shape, ref position, ref angle) => {
let omit_shape = match *shape {
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::Cover)) |
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner)) => true,
_ => false,
};
if self.compat_mode == CompatMode::Modern {
if!omit_shape {
shape.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
position.to_css(dest)?;
} else {
position.to_css(dest)?;
if let Some(ref a) = *angle {
dest.write_str(" ")?;
a.to_css(dest)?;
}
if!omit_shape {
dest.write_str(", ")?;
shape.to_css(dest)?;
}
}
false
},
};
for item in &self.items {
if!skip_comma {
dest.write_str(", ")?;
}
skip_comma = false;
item.to_css(dest)?;
}
dest.write_str(")")
}
}
impl<D, L, LoP, P, A> GradientKind<D, L, LoP, P, A> {
fn label(&self) -> &str {
match *self {
GradientKind::Linear(..) => "linear",
GradientKind::Radial(..) => "radial",
}
}
}
/// The direction of a linear gradient.
pub trait LineDirection {
/// Whether this direction points towards, and thus can be omitted.
fn points_downwards(&self, compat_mode: CompatMode) -> bool;
/// Serialises this direction according to the compatibility mode.
fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: CompatMode) -> fmt::Result
where
W: Write;
}
impl<L> ToCss for Circle<L>
where
L: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self {
Circle::Extent(ShapeExtent::FarthestCorner) | Circle::Extent(ShapeExtent::Cover) => {
dest.write_str("circle")
},
Circle::Extent(keyword) => {
dest.write_str("circle ")?;
keyword.to_css(dest)
},
Circle::Radius(ref length) => length.to_css(dest),
}
}
}
|
{
direction.to_css(dest, self.compat_mode)?;
false
}
|
conditional_block
|
nutation.rs
|
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#![allow(non_snake_case)]
extern crate astro;
use astro::*;
#[test]
fn nutation()
|
#[test]
fn nutation_in_eq_coords() {
let eq_point = coords::EqPoint {
asc: 41.5555635_f64.to_radians(),
dec: 49.3503415_f64.to_radians()
};
let (a, b) = nutation::nutation_in_eq_coords(
&eq_point,
angle::deg_frm_dms(0, 0, 14.861).to_radians(),
angle::deg_frm_dms(0, 0, 2.705).to_radians(),
23.436_f64.to_radians()
);
assert_eq!(util::round_upto_digits(a.to_degrees(), 7), 0.0044011);
assert_eq!(util::round_upto_digits(b.to_degrees(), 7), 0.001727);
}
|
{
let (nut_in_long, nut_in_oblq) = nutation::nutation(2446895.5);
let (d1, m1, s1) = angle::dms_frm_deg(nut_in_long.to_degrees());
assert_eq!((d1, m1, util::round_upto_digits(s1, 3)), (0, 0, -3.788));
let (d2, m2, s2) = angle::dms_frm_deg(nut_in_oblq.to_degrees());
assert_eq!((d2, m2, util::round_upto_digits(s2, 3)), (0, 0, 9.443));
}
|
identifier_body
|
nutation.rs
|
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#![allow(non_snake_case)]
extern crate astro;
use astro::*;
#[test]
fn nutation() {
let (nut_in_long, nut_in_oblq) = nutation::nutation(2446895.5);
let (d1, m1, s1) = angle::dms_frm_deg(nut_in_long.to_degrees());
assert_eq!((d1, m1, util::round_upto_digits(s1, 3)), (0, 0, -3.788));
let (d2, m2, s2) = angle::dms_frm_deg(nut_in_oblq.to_degrees());
assert_eq!((d2, m2, util::round_upto_digits(s2, 3)), (0, 0, 9.443));
}
#[test]
fn
|
() {
let eq_point = coords::EqPoint {
asc: 41.5555635_f64.to_radians(),
dec: 49.3503415_f64.to_radians()
};
let (a, b) = nutation::nutation_in_eq_coords(
&eq_point,
angle::deg_frm_dms(0, 0, 14.861).to_radians(),
angle::deg_frm_dms(0, 0, 2.705).to_radians(),
23.436_f64.to_radians()
);
assert_eq!(util::round_upto_digits(a.to_degrees(), 7), 0.0044011);
assert_eq!(util::round_upto_digits(b.to_degrees(), 7), 0.001727);
}
|
nutation_in_eq_coords
|
identifier_name
|
nutation.rs
|
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
#![allow(non_snake_case)]
extern crate astro;
use astro::*;
#[test]
fn nutation() {
let (nut_in_long, nut_in_oblq) = nutation::nutation(2446895.5);
let (d1, m1, s1) = angle::dms_frm_deg(nut_in_long.to_degrees());
assert_eq!((d1, m1, util::round_upto_digits(s1, 3)), (0, 0, -3.788));
let (d2, m2, s2) = angle::dms_frm_deg(nut_in_oblq.to_degrees());
assert_eq!((d2, m2, util::round_upto_digits(s2, 3)), (0, 0, 9.443));
}
#[test]
fn nutation_in_eq_coords() {
let eq_point = coords::EqPoint {
asc: 41.5555635_f64.to_radians(),
dec: 49.3503415_f64.to_radians()
};
let (a, b) = nutation::nutation_in_eq_coords(
&eq_point,
angle::deg_frm_dms(0, 0, 14.861).to_radians(),
angle::deg_frm_dms(0, 0, 2.705).to_radians(),
23.436_f64.to_radians()
);
assert_eq!(util::round_upto_digits(a.to_degrees(), 7), 0.0044011);
assert_eq!(util::round_upto_digits(b.to_degrees(), 7), 0.001727);
}
|
*/
|
random_line_split
|
oneshot.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.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic usize variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: usize = 0; // initial state: no data, no blocked receiver
const DATA: usize = 1; // data ready for receiver to take
const DISCONNECTED: usize = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T>
|
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_usize(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_usize() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst)!= EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_usize(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_usize(ptr) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_usize(ptr).signal();
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// 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(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_usize() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_usize(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// 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(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_usize(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
|
{
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED => {
Err(self.data.take().unwrap())
}
|
identifier_body
|
oneshot.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.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic usize variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: usize = 0; // initial state: no data, no blocked receiver
const DATA: usize = 1; // data ready for receiver to take
const DISCONNECTED: usize = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
|
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED => {
Err(self.data.take().unwrap())
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_usize(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_usize() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst)!= EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_usize(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_usize(ptr) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_usize(ptr).signal();
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// 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(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_usize() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_usize(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// 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(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_usize(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
|
pub enum SelectionResult<T> {
|
random_line_split
|
oneshot.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.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic usize variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: usize = 0; // initial state: no data, no blocked receiver
const DATA: usize = 1; // data ready for receiver to take
const DISCONNECTED: usize = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED => {
Err(self.data.take().unwrap())
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_usize(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_usize() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst)!= EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_usize(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_usize(ptr) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_usize(ptr).signal();
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// 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(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_usize() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_usize(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_usize(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// 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
|
(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_usize(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
|
abort_selection
|
identifier_name
|
page.rs
|
use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn new(utils: Utils, admin_template: View) -> Index {
Index {
utils: utils,
template: admin_template,
}
}
}
impl Handler for Index {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
|
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
"child_user": "Pages"
});
let mut response = Response::with((status::Ok, self.template.render("home.html", model)));
response.headers.set(ContentType::html());
Ok(response)
}
}
|
let model = json!({
"title": "Testing",
|
random_line_split
|
page.rs
|
use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn new(utils: Utils, admin_template: View) -> Index
|
}
impl Handler for Index {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
"child_user": "Pages"
});
let mut response = Response::with((status::Ok, self.template.render("home.html", model)));
response.headers.set(ContentType::html());
Ok(response)
}
}
|
{
Index {
utils: utils,
template: admin_template,
}
}
|
identifier_body
|
page.rs
|
use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct
|
{
utils: Utils,
template: View,
}
impl Index {
pub fn new(utils: Utils, admin_template: View) -> Index {
Index {
utils: utils,
template: admin_template,
}
}
}
impl Handler for Index {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
"child_user": "Pages"
});
let mut response = Response::with((status::Ok, self.template.render("home.html", model)));
response.headers.set(ContentType::html());
Ok(response)
}
}
|
Index
|
identifier_name
|
lib.rs
|
//! Provides a Cursor abstraction for use with the `postgres` crate.
//!
//! # Examples
//!
//! ```no_run
//! extern crate postgres;
//! extern crate postgres_cursor;
//!
//! use postgres::{Connection, TlsMode};
//! use postgres_cursor::Cursor;
//!
//! # fn main() {
//!
//! // First, establish a connection with postgres
//! let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
//! .expect("connect");
//!
//! // Build the cursor
//! let mut cursor = Cursor::build(&conn)
//! // Batch size determines rows returned in each FETCH call
//! .batch_size(10)
//! // Query is the statement to build a cursor for
//! .query("SELECT id FROM products")
//! // Finalize turns this builder into a cursor
//! .finalize()
//! .expect("cursor creation succeeded");
//!
//! // Iterate over batches of rows
//! for result in &mut cursor {
//! // Each item returned from the iterator is a Result<Rows>.
//! // This is because each call to `next()` makes a query
//! // to the database.
//! let rows = result.unwrap();
//!
//! // After handling errors, rows returned in this iteration
//! // can be iterated over.
//! for row in &rows {
//! println!("{:?}", row);
//! }
//! }
//!
//! # }
//! ```
extern crate postgres;
extern crate rand;
#[macro_use]
#[cfg(test)]
extern crate lazy_static;
use std::{fmt, mem};
use std::iter::IntoIterator;
use postgres::Connection;
use postgres::types::ToSql;
use postgres::rows::{Rows};
use rand::{thread_rng, Rng};
struct Hex<'a>(&'a [u8]);
impl<'a> fmt::Display for Hex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in self.0 {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
/// Represents a PostgreSQL cursor.
///
/// The actual cursor in the database is only created and active _while_
/// `Iter` is in scope and calls to `next()` return `Some`.
pub struct Cursor<'conn> {
conn: &'conn Connection,
closed: bool,
cursor_name: String,
fetch_query: String,
batch_size: u32
}
impl<'conn> Cursor<'conn> {
fn new<'c, 'a, D>(builder: Builder<'c, 'a, D>) -> postgres::Result<Cursor<'c>>
where D: fmt::Display +?Sized
{
let mut bytes: [u8; 8] = unsafe { mem::uninitialized() };
thread_rng().fill_bytes(&mut bytes[..]);
let cursor_name = format!("cursor:{}:{}", builder.tag, Hex(&bytes));
let query = format!("DECLARE \"{}\" CURSOR FOR {}", cursor_name, builder.query);
let fetch_query = format!("FETCH {} FROM \"{}\"", builder.batch_size, cursor_name);
builder.conn.execute("BEGIN", &[])?;
builder.conn.execute(&query[..], builder.params)?;
Ok(Cursor {
closed: false,
conn: builder.conn,
cursor_name,
fetch_query,
batch_size: builder.batch_size,
})
}
pub fn build<'b>(conn: &'b Connection) -> Builder<'b,'static, str> {
Builder::<str>::new(conn)
}
}
/// Iterator returning `Rows` for every call to `next()`.
pub struct Iter<'b, 'a: 'b> {
cursor: &'b mut Cursor<'a>,
}
impl<'b, 'a: 'b> Iterator for Iter<'b, 'a> {
type Item = postgres::Result<Rows>;
fn next(&mut self) -> Option<postgres::Result<Rows>> {
if self.cursor.closed {
None
} else {
Some(self.cursor.next_batch())
}
}
}
impl<'a, 'conn> IntoIterator for &'a mut Cursor<'conn> {
type Item = postgres::Result<Rows>;
type IntoIter = Iter<'a, 'conn>;
fn into_iter(self) -> Iter<'a, 'conn> {
self.iter()
}
}
impl<'a> Cursor<'a> {
pub fn iter<'b>(&'b mut self) -> Iter<'b, 'a> {
Iter {
cursor: self,
}
}
fn next_batch(&mut self) -> postgres::Result<Rows> {
let rows = self.conn.query(&self.fetch_query[..], &[])?;
if rows.len() < (self.batch_size as usize) {
self.close()?;
}
Ok(rows)
}
fn close(&mut self) -> postgres::Result<()> {
if!self.closed {
let close_query = format!("CLOSE \"{}\"", self.cursor_name);
self.conn.execute(&close_query[..], &[])?;
self.conn.execute("COMMIT", &[])?;
self.closed = true;
}
Ok(())
}
}
impl<'a> Drop for Cursor<'a> {
fn drop(&mut self) {
let _ = self.close();
}
}
/// Builds a Cursor
///
/// This type is constructed by calling `Cursor::build`.
pub struct Builder<'conn, 'builder, D:?Sized + 'builder> {
batch_size: u32,
query: &'builder str,
conn: &'conn Connection,
tag: &'builder D,
params: &'builder [&'builder ToSql],
}
impl<'conn, 'builder, D: fmt::Display +?Sized + 'builder> Builder<'conn, 'builder, D> {
fn new<'c>(conn: &'c Connection) -> Builder<'c,'static, str> {
Builder {
conn,
batch_size: 5_000,
query: "SELECT 1 as one",
tag: "default",
params: &[],
}
}
/// Set query params for cursor creation
pub fn query_params(mut self, params: &'builder [&'builder ToSql]) -> Self {
self.params = params;
self
}
/// Set the batch size passed to `FETCH` on each iteration.
///
/// Default is 5,000.
pub fn batch_size(mut self, batch_size: u32) -> Self
|
/// Set the tag for cursor name.
///
/// Adding a tag to the cursor name can be helpful for identifying where
/// cursors originate when viewing `pg_stat_activity`.
///
/// Default is `default`.
///
/// # Examples
///
/// Any type that implements `fmt::Display` may be provided as a tag. For example, a simple
/// string literal is one option.
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// let mut cursor = Cursor::build(&conn)
/// .tag("custom-cursor-tag")
/// .finalize();
/// # }
/// ```
///
/// Or maybe you want to build a tag at run-time without incurring an extra allocation:
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// use std::fmt;
///
/// struct Pid(i32);
/// impl fmt::Display for Pid {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "pid-{}", self.0)
/// }
/// }
///
/// let tag = Pid(8123);
/// let mut cursor = Cursor::build(&conn)
/// .tag(&tag)
/// .finalize();
/// # }
/// ```
pub fn tag<D2: fmt::Display +?Sized>(self, tag: &'builder D2) -> Builder<'conn, 'builder, D2> {
Builder {
batch_size: self.batch_size,
query: self.query,
conn: self.conn,
tag: tag,
params: self.params
}
}
/// Set the query to create a cursor for.
///
/// Default is `SELECT 1`.
pub fn query(mut self, query: &'builder str) -> Self {
self.query = query;
self
}
/// Turn the builder into a `Cursor`.
pub fn finalize(self) -> postgres::Result<Cursor<'conn>> {
Cursor::new(self)
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use postgres::{Connection, TlsMode};
use super::Cursor;
lazy_static! {
static ref LOCK: Mutex<u8> = {
Mutex::new(0)
};
}
fn synchronized<F: FnOnce() -> T, T>(func: F) -> T {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
func()
}
fn with_items<F: FnOnce(&Connection) -> T, T>(items: i32, func: F) -> T {
synchronized(|| {
let conn = get_connection();
conn.execute("TRUNCATE TABLE products", &[]).expect("truncate");
// Highly inefficient; should optimize.
for i in 0..items {
conn.execute("INSERT INTO products (id) VALUES ($1)", &[&i]).expect("insert");
}
func(&conn)
})
}
fn get_connection() -> Connection {
Connection::connect("postgres://[email protected]/postgresql_cursor_test", TlsMode::None)
.expect("connect")
}
#[test]
fn test_framework_works() {
let count = 183;
with_items(count, |conn| {
for row in &conn.query("SELECT COUNT(*) FROM products", &[]).unwrap() {
let got: i64 = row.get(0);
assert_eq!(got, count as i64);
}
});
}
#[test]
fn cursor_iter_works_when_batch_size_divisible() {
with_items(200, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 200);
});
}
#[test]
fn cursor_iter_works_when_batch_size_remainder() {
with_items(197, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 197);
});
}
#[test]
fn build_cursor_with_tag() {
with_items(1, |conn| {
{
let cursor = Cursor::build(conn)
.tag("foobar")
.finalize().unwrap();
assert!(cursor.cursor_name.starts_with("cursor:foobar"));
}
struct Foo;
use std::fmt;
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "foo-{}", 1)
}
}
{
let foo = Foo;
let cursor = Cursor::build(conn)
.tag(&foo)
.finalize().unwrap();
println!("{}", cursor.cursor_name);
assert!(cursor.cursor_name.starts_with("cursor:foo-1"));
}
});
}
#[test]
fn cursor_with_long_tag() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.tag("really-long-tag-damn-that-was-only-three-words-foo-bar-baz")
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 100);
});
}
#[test]
fn cursor_with_params() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.query("SELECT id FROM products WHERE id > $1 AND id < $2")
.query_params(&[&1, &10])
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 8);
});
}
}
|
{
self.batch_size = batch_size;
self
}
|
identifier_body
|
lib.rs
|
//! Provides a Cursor abstraction for use with the `postgres` crate.
//!
//! # Examples
//!
//! ```no_run
//! extern crate postgres;
//! extern crate postgres_cursor;
//!
//! use postgres::{Connection, TlsMode};
//! use postgres_cursor::Cursor;
//!
//! # fn main() {
//!
//! // First, establish a connection with postgres
//! let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
//! .expect("connect");
//!
//! // Build the cursor
//! let mut cursor = Cursor::build(&conn)
//! // Batch size determines rows returned in each FETCH call
//! .batch_size(10)
//! // Query is the statement to build a cursor for
//! .query("SELECT id FROM products")
//! // Finalize turns this builder into a cursor
//! .finalize()
//! .expect("cursor creation succeeded");
//!
//! // Iterate over batches of rows
//! for result in &mut cursor {
//! // Each item returned from the iterator is a Result<Rows>.
//! // This is because each call to `next()` makes a query
//! // to the database.
//! let rows = result.unwrap();
//!
//! // After handling errors, rows returned in this iteration
//! // can be iterated over.
//! for row in &rows {
//! println!("{:?}", row);
//! }
//! }
//!
//! # }
//! ```
extern crate postgres;
extern crate rand;
#[macro_use]
#[cfg(test)]
extern crate lazy_static;
use std::{fmt, mem};
use std::iter::IntoIterator;
use postgres::Connection;
use postgres::types::ToSql;
use postgres::rows::{Rows};
use rand::{thread_rng, Rng};
struct Hex<'a>(&'a [u8]);
impl<'a> fmt::Display for Hex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in self.0 {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
/// Represents a PostgreSQL cursor.
///
/// The actual cursor in the database is only created and active _while_
/// `Iter` is in scope and calls to `next()` return `Some`.
pub struct Cursor<'conn> {
conn: &'conn Connection,
closed: bool,
cursor_name: String,
fetch_query: String,
batch_size: u32
}
impl<'conn> Cursor<'conn> {
fn
|
<'c, 'a, D>(builder: Builder<'c, 'a, D>) -> postgres::Result<Cursor<'c>>
where D: fmt::Display +?Sized
{
let mut bytes: [u8; 8] = unsafe { mem::uninitialized() };
thread_rng().fill_bytes(&mut bytes[..]);
let cursor_name = format!("cursor:{}:{}", builder.tag, Hex(&bytes));
let query = format!("DECLARE \"{}\" CURSOR FOR {}", cursor_name, builder.query);
let fetch_query = format!("FETCH {} FROM \"{}\"", builder.batch_size, cursor_name);
builder.conn.execute("BEGIN", &[])?;
builder.conn.execute(&query[..], builder.params)?;
Ok(Cursor {
closed: false,
conn: builder.conn,
cursor_name,
fetch_query,
batch_size: builder.batch_size,
})
}
pub fn build<'b>(conn: &'b Connection) -> Builder<'b,'static, str> {
Builder::<str>::new(conn)
}
}
/// Iterator returning `Rows` for every call to `next()`.
pub struct Iter<'b, 'a: 'b> {
cursor: &'b mut Cursor<'a>,
}
impl<'b, 'a: 'b> Iterator for Iter<'b, 'a> {
type Item = postgres::Result<Rows>;
fn next(&mut self) -> Option<postgres::Result<Rows>> {
if self.cursor.closed {
None
} else {
Some(self.cursor.next_batch())
}
}
}
impl<'a, 'conn> IntoIterator for &'a mut Cursor<'conn> {
type Item = postgres::Result<Rows>;
type IntoIter = Iter<'a, 'conn>;
fn into_iter(self) -> Iter<'a, 'conn> {
self.iter()
}
}
impl<'a> Cursor<'a> {
pub fn iter<'b>(&'b mut self) -> Iter<'b, 'a> {
Iter {
cursor: self,
}
}
fn next_batch(&mut self) -> postgres::Result<Rows> {
let rows = self.conn.query(&self.fetch_query[..], &[])?;
if rows.len() < (self.batch_size as usize) {
self.close()?;
}
Ok(rows)
}
fn close(&mut self) -> postgres::Result<()> {
if!self.closed {
let close_query = format!("CLOSE \"{}\"", self.cursor_name);
self.conn.execute(&close_query[..], &[])?;
self.conn.execute("COMMIT", &[])?;
self.closed = true;
}
Ok(())
}
}
impl<'a> Drop for Cursor<'a> {
fn drop(&mut self) {
let _ = self.close();
}
}
/// Builds a Cursor
///
/// This type is constructed by calling `Cursor::build`.
pub struct Builder<'conn, 'builder, D:?Sized + 'builder> {
batch_size: u32,
query: &'builder str,
conn: &'conn Connection,
tag: &'builder D,
params: &'builder [&'builder ToSql],
}
impl<'conn, 'builder, D: fmt::Display +?Sized + 'builder> Builder<'conn, 'builder, D> {
fn new<'c>(conn: &'c Connection) -> Builder<'c,'static, str> {
Builder {
conn,
batch_size: 5_000,
query: "SELECT 1 as one",
tag: "default",
params: &[],
}
}
/// Set query params for cursor creation
pub fn query_params(mut self, params: &'builder [&'builder ToSql]) -> Self {
self.params = params;
self
}
/// Set the batch size passed to `FETCH` on each iteration.
///
/// Default is 5,000.
pub fn batch_size(mut self, batch_size: u32) -> Self {
self.batch_size = batch_size;
self
}
/// Set the tag for cursor name.
///
/// Adding a tag to the cursor name can be helpful for identifying where
/// cursors originate when viewing `pg_stat_activity`.
///
/// Default is `default`.
///
/// # Examples
///
/// Any type that implements `fmt::Display` may be provided as a tag. For example, a simple
/// string literal is one option.
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// let mut cursor = Cursor::build(&conn)
/// .tag("custom-cursor-tag")
/// .finalize();
/// # }
/// ```
///
/// Or maybe you want to build a tag at run-time without incurring an extra allocation:
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// use std::fmt;
///
/// struct Pid(i32);
/// impl fmt::Display for Pid {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "pid-{}", self.0)
/// }
/// }
///
/// let tag = Pid(8123);
/// let mut cursor = Cursor::build(&conn)
/// .tag(&tag)
/// .finalize();
/// # }
/// ```
pub fn tag<D2: fmt::Display +?Sized>(self, tag: &'builder D2) -> Builder<'conn, 'builder, D2> {
Builder {
batch_size: self.batch_size,
query: self.query,
conn: self.conn,
tag: tag,
params: self.params
}
}
/// Set the query to create a cursor for.
///
/// Default is `SELECT 1`.
pub fn query(mut self, query: &'builder str) -> Self {
self.query = query;
self
}
/// Turn the builder into a `Cursor`.
pub fn finalize(self) -> postgres::Result<Cursor<'conn>> {
Cursor::new(self)
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use postgres::{Connection, TlsMode};
use super::Cursor;
lazy_static! {
static ref LOCK: Mutex<u8> = {
Mutex::new(0)
};
}
fn synchronized<F: FnOnce() -> T, T>(func: F) -> T {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
func()
}
fn with_items<F: FnOnce(&Connection) -> T, T>(items: i32, func: F) -> T {
synchronized(|| {
let conn = get_connection();
conn.execute("TRUNCATE TABLE products", &[]).expect("truncate");
// Highly inefficient; should optimize.
for i in 0..items {
conn.execute("INSERT INTO products (id) VALUES ($1)", &[&i]).expect("insert");
}
func(&conn)
})
}
fn get_connection() -> Connection {
Connection::connect("postgres://[email protected]/postgresql_cursor_test", TlsMode::None)
.expect("connect")
}
#[test]
fn test_framework_works() {
let count = 183;
with_items(count, |conn| {
for row in &conn.query("SELECT COUNT(*) FROM products", &[]).unwrap() {
let got: i64 = row.get(0);
assert_eq!(got, count as i64);
}
});
}
#[test]
fn cursor_iter_works_when_batch_size_divisible() {
with_items(200, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 200);
});
}
#[test]
fn cursor_iter_works_when_batch_size_remainder() {
with_items(197, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 197);
});
}
#[test]
fn build_cursor_with_tag() {
with_items(1, |conn| {
{
let cursor = Cursor::build(conn)
.tag("foobar")
.finalize().unwrap();
assert!(cursor.cursor_name.starts_with("cursor:foobar"));
}
struct Foo;
use std::fmt;
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "foo-{}", 1)
}
}
{
let foo = Foo;
let cursor = Cursor::build(conn)
.tag(&foo)
.finalize().unwrap();
println!("{}", cursor.cursor_name);
assert!(cursor.cursor_name.starts_with("cursor:foo-1"));
}
});
}
#[test]
fn cursor_with_long_tag() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.tag("really-long-tag-damn-that-was-only-three-words-foo-bar-baz")
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 100);
});
}
#[test]
fn cursor_with_params() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.query("SELECT id FROM products WHERE id > $1 AND id < $2")
.query_params(&[&1, &10])
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 8);
});
}
}
|
new
|
identifier_name
|
lib.rs
|
//! Provides a Cursor abstraction for use with the `postgres` crate.
//!
//! # Examples
//!
//! ```no_run
//! extern crate postgres;
//! extern crate postgres_cursor;
//!
//! use postgres::{Connection, TlsMode};
//! use postgres_cursor::Cursor;
//!
//! # fn main() {
//!
//! // First, establish a connection with postgres
//! let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
//! .expect("connect");
//!
//! // Build the cursor
//! let mut cursor = Cursor::build(&conn)
//! // Batch size determines rows returned in each FETCH call
//! .batch_size(10)
//! // Query is the statement to build a cursor for
//! .query("SELECT id FROM products")
//! // Finalize turns this builder into a cursor
//! .finalize()
//! .expect("cursor creation succeeded");
//!
//! // Iterate over batches of rows
//! for result in &mut cursor {
//! // Each item returned from the iterator is a Result<Rows>.
//! // This is because each call to `next()` makes a query
//! // to the database.
//! let rows = result.unwrap();
//!
//! // After handling errors, rows returned in this iteration
//! // can be iterated over.
//! for row in &rows {
//! println!("{:?}", row);
//! }
//! }
//!
//! # }
//! ```
extern crate postgres;
extern crate rand;
#[macro_use]
#[cfg(test)]
extern crate lazy_static;
use std::{fmt, mem};
use std::iter::IntoIterator;
use postgres::Connection;
use postgres::types::ToSql;
use postgres::rows::{Rows};
use rand::{thread_rng, Rng};
struct Hex<'a>(&'a [u8]);
impl<'a> fmt::Display for Hex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in self.0 {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
/// Represents a PostgreSQL cursor.
///
/// The actual cursor in the database is only created and active _while_
/// `Iter` is in scope and calls to `next()` return `Some`.
pub struct Cursor<'conn> {
conn: &'conn Connection,
closed: bool,
cursor_name: String,
fetch_query: String,
batch_size: u32
}
impl<'conn> Cursor<'conn> {
fn new<'c, 'a, D>(builder: Builder<'c, 'a, D>) -> postgres::Result<Cursor<'c>>
where D: fmt::Display +?Sized
{
let mut bytes: [u8; 8] = unsafe { mem::uninitialized() };
thread_rng().fill_bytes(&mut bytes[..]);
let cursor_name = format!("cursor:{}:{}", builder.tag, Hex(&bytes));
let query = format!("DECLARE \"{}\" CURSOR FOR {}", cursor_name, builder.query);
let fetch_query = format!("FETCH {} FROM \"{}\"", builder.batch_size, cursor_name);
builder.conn.execute("BEGIN", &[])?;
builder.conn.execute(&query[..], builder.params)?;
Ok(Cursor {
closed: false,
conn: builder.conn,
cursor_name,
fetch_query,
batch_size: builder.batch_size,
})
}
pub fn build<'b>(conn: &'b Connection) -> Builder<'b,'static, str> {
Builder::<str>::new(conn)
}
}
/// Iterator returning `Rows` for every call to `next()`.
pub struct Iter<'b, 'a: 'b> {
cursor: &'b mut Cursor<'a>,
}
impl<'b, 'a: 'b> Iterator for Iter<'b, 'a> {
type Item = postgres::Result<Rows>;
fn next(&mut self) -> Option<postgres::Result<Rows>> {
if self.cursor.closed {
None
} else {
Some(self.cursor.next_batch())
}
}
}
impl<'a, 'conn> IntoIterator for &'a mut Cursor<'conn> {
type Item = postgres::Result<Rows>;
type IntoIter = Iter<'a, 'conn>;
fn into_iter(self) -> Iter<'a, 'conn> {
self.iter()
}
}
impl<'a> Cursor<'a> {
pub fn iter<'b>(&'b mut self) -> Iter<'b, 'a> {
Iter {
cursor: self,
}
}
fn next_batch(&mut self) -> postgres::Result<Rows> {
let rows = self.conn.query(&self.fetch_query[..], &[])?;
if rows.len() < (self.batch_size as usize) {
self.close()?;
}
Ok(rows)
}
fn close(&mut self) -> postgres::Result<()> {
if!self.closed
|
Ok(())
}
}
impl<'a> Drop for Cursor<'a> {
fn drop(&mut self) {
let _ = self.close();
}
}
/// Builds a Cursor
///
/// This type is constructed by calling `Cursor::build`.
pub struct Builder<'conn, 'builder, D:?Sized + 'builder> {
batch_size: u32,
query: &'builder str,
conn: &'conn Connection,
tag: &'builder D,
params: &'builder [&'builder ToSql],
}
impl<'conn, 'builder, D: fmt::Display +?Sized + 'builder> Builder<'conn, 'builder, D> {
fn new<'c>(conn: &'c Connection) -> Builder<'c,'static, str> {
Builder {
conn,
batch_size: 5_000,
query: "SELECT 1 as one",
tag: "default",
params: &[],
}
}
/// Set query params for cursor creation
pub fn query_params(mut self, params: &'builder [&'builder ToSql]) -> Self {
self.params = params;
self
}
/// Set the batch size passed to `FETCH` on each iteration.
///
/// Default is 5,000.
pub fn batch_size(mut self, batch_size: u32) -> Self {
self.batch_size = batch_size;
self
}
/// Set the tag for cursor name.
///
/// Adding a tag to the cursor name can be helpful for identifying where
/// cursors originate when viewing `pg_stat_activity`.
///
/// Default is `default`.
///
/// # Examples
///
/// Any type that implements `fmt::Display` may be provided as a tag. For example, a simple
/// string literal is one option.
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// let mut cursor = Cursor::build(&conn)
/// .tag("custom-cursor-tag")
/// .finalize();
/// # }
/// ```
///
/// Or maybe you want to build a tag at run-time without incurring an extra allocation:
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// use std::fmt;
///
/// struct Pid(i32);
/// impl fmt::Display for Pid {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "pid-{}", self.0)
/// }
/// }
///
/// let tag = Pid(8123);
/// let mut cursor = Cursor::build(&conn)
/// .tag(&tag)
/// .finalize();
/// # }
/// ```
pub fn tag<D2: fmt::Display +?Sized>(self, tag: &'builder D2) -> Builder<'conn, 'builder, D2> {
Builder {
batch_size: self.batch_size,
query: self.query,
conn: self.conn,
tag: tag,
params: self.params
}
}
/// Set the query to create a cursor for.
///
/// Default is `SELECT 1`.
pub fn query(mut self, query: &'builder str) -> Self {
self.query = query;
self
}
/// Turn the builder into a `Cursor`.
pub fn finalize(self) -> postgres::Result<Cursor<'conn>> {
Cursor::new(self)
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use postgres::{Connection, TlsMode};
use super::Cursor;
lazy_static! {
static ref LOCK: Mutex<u8> = {
Mutex::new(0)
};
}
fn synchronized<F: FnOnce() -> T, T>(func: F) -> T {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
func()
}
fn with_items<F: FnOnce(&Connection) -> T, T>(items: i32, func: F) -> T {
synchronized(|| {
let conn = get_connection();
conn.execute("TRUNCATE TABLE products", &[]).expect("truncate");
// Highly inefficient; should optimize.
for i in 0..items {
conn.execute("INSERT INTO products (id) VALUES ($1)", &[&i]).expect("insert");
}
func(&conn)
})
}
fn get_connection() -> Connection {
Connection::connect("postgres://[email protected]/postgresql_cursor_test", TlsMode::None)
.expect("connect")
}
#[test]
fn test_framework_works() {
let count = 183;
with_items(count, |conn| {
for row in &conn.query("SELECT COUNT(*) FROM products", &[]).unwrap() {
let got: i64 = row.get(0);
assert_eq!(got, count as i64);
}
});
}
#[test]
fn cursor_iter_works_when_batch_size_divisible() {
with_items(200, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 200);
});
}
#[test]
fn cursor_iter_works_when_batch_size_remainder() {
with_items(197, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 197);
});
}
#[test]
fn build_cursor_with_tag() {
with_items(1, |conn| {
{
let cursor = Cursor::build(conn)
.tag("foobar")
.finalize().unwrap();
assert!(cursor.cursor_name.starts_with("cursor:foobar"));
}
struct Foo;
use std::fmt;
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "foo-{}", 1)
}
}
{
let foo = Foo;
let cursor = Cursor::build(conn)
.tag(&foo)
.finalize().unwrap();
println!("{}", cursor.cursor_name);
assert!(cursor.cursor_name.starts_with("cursor:foo-1"));
}
});
}
#[test]
fn cursor_with_long_tag() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.tag("really-long-tag-damn-that-was-only-three-words-foo-bar-baz")
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 100);
});
}
#[test]
fn cursor_with_params() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.query("SELECT id FROM products WHERE id > $1 AND id < $2")
.query_params(&[&1, &10])
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 8);
});
}
}
|
{
let close_query = format!("CLOSE \"{}\"", self.cursor_name);
self.conn.execute(&close_query[..], &[])?;
self.conn.execute("COMMIT", &[])?;
self.closed = true;
}
|
conditional_block
|
lib.rs
|
//! Provides a Cursor abstraction for use with the `postgres` crate.
//!
//! # Examples
//!
//! ```no_run
//! extern crate postgres;
//! extern crate postgres_cursor;
//!
//! use postgres::{Connection, TlsMode};
//! use postgres_cursor::Cursor;
//!
//! # fn main() {
//!
//! // First, establish a connection with postgres
//! let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
//! .expect("connect");
//!
//! // Build the cursor
//! let mut cursor = Cursor::build(&conn)
//! // Batch size determines rows returned in each FETCH call
//! .batch_size(10)
//! // Query is the statement to build a cursor for
//! .query("SELECT id FROM products")
//! // Finalize turns this builder into a cursor
//! .finalize()
//! .expect("cursor creation succeeded");
//!
//! // Iterate over batches of rows
//! for result in &mut cursor {
//! // Each item returned from the iterator is a Result<Rows>.
//! // This is because each call to `next()` makes a query
//! // to the database.
//! let rows = result.unwrap();
//!
//! // After handling errors, rows returned in this iteration
//! // can be iterated over.
//! for row in &rows {
//! println!("{:?}", row);
//! }
//! }
//!
//! # }
//! ```
extern crate postgres;
extern crate rand;
#[macro_use]
#[cfg(test)]
extern crate lazy_static;
use std::{fmt, mem};
use std::iter::IntoIterator;
use postgres::Connection;
use postgres::types::ToSql;
use postgres::rows::{Rows};
use rand::{thread_rng, Rng};
struct Hex<'a>(&'a [u8]);
impl<'a> fmt::Display for Hex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in self.0 {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
/// Represents a PostgreSQL cursor.
///
/// The actual cursor in the database is only created and active _while_
/// `Iter` is in scope and calls to `next()` return `Some`.
pub struct Cursor<'conn> {
conn: &'conn Connection,
closed: bool,
cursor_name: String,
fetch_query: String,
batch_size: u32
}
impl<'conn> Cursor<'conn> {
fn new<'c, 'a, D>(builder: Builder<'c, 'a, D>) -> postgres::Result<Cursor<'c>>
where D: fmt::Display +?Sized
{
let mut bytes: [u8; 8] = unsafe { mem::uninitialized() };
thread_rng().fill_bytes(&mut bytes[..]);
let cursor_name = format!("cursor:{}:{}", builder.tag, Hex(&bytes));
let query = format!("DECLARE \"{}\" CURSOR FOR {}", cursor_name, builder.query);
let fetch_query = format!("FETCH {} FROM \"{}\"", builder.batch_size, cursor_name);
builder.conn.execute("BEGIN", &[])?;
builder.conn.execute(&query[..], builder.params)?;
Ok(Cursor {
closed: false,
conn: builder.conn,
cursor_name,
fetch_query,
batch_size: builder.batch_size,
})
}
pub fn build<'b>(conn: &'b Connection) -> Builder<'b,'static, str> {
Builder::<str>::new(conn)
}
}
/// Iterator returning `Rows` for every call to `next()`.
pub struct Iter<'b, 'a: 'b> {
cursor: &'b mut Cursor<'a>,
}
impl<'b, 'a: 'b> Iterator for Iter<'b, 'a> {
type Item = postgres::Result<Rows>;
fn next(&mut self) -> Option<postgres::Result<Rows>> {
if self.cursor.closed {
None
} else {
Some(self.cursor.next_batch())
}
}
}
impl<'a, 'conn> IntoIterator for &'a mut Cursor<'conn> {
type Item = postgres::Result<Rows>;
type IntoIter = Iter<'a, 'conn>;
fn into_iter(self) -> Iter<'a, 'conn> {
self.iter()
}
}
impl<'a> Cursor<'a> {
pub fn iter<'b>(&'b mut self) -> Iter<'b, 'a> {
Iter {
cursor: self,
}
}
fn next_batch(&mut self) -> postgres::Result<Rows> {
let rows = self.conn.query(&self.fetch_query[..], &[])?;
if rows.len() < (self.batch_size as usize) {
self.close()?;
}
Ok(rows)
}
fn close(&mut self) -> postgres::Result<()> {
if!self.closed {
let close_query = format!("CLOSE \"{}\"", self.cursor_name);
self.conn.execute(&close_query[..], &[])?;
self.conn.execute("COMMIT", &[])?;
self.closed = true;
}
Ok(())
}
}
impl<'a> Drop for Cursor<'a> {
fn drop(&mut self) {
let _ = self.close();
}
|
/// Builds a Cursor
///
/// This type is constructed by calling `Cursor::build`.
pub struct Builder<'conn, 'builder, D:?Sized + 'builder> {
batch_size: u32,
query: &'builder str,
conn: &'conn Connection,
tag: &'builder D,
params: &'builder [&'builder ToSql],
}
impl<'conn, 'builder, D: fmt::Display +?Sized + 'builder> Builder<'conn, 'builder, D> {
fn new<'c>(conn: &'c Connection) -> Builder<'c,'static, str> {
Builder {
conn,
batch_size: 5_000,
query: "SELECT 1 as one",
tag: "default",
params: &[],
}
}
/// Set query params for cursor creation
pub fn query_params(mut self, params: &'builder [&'builder ToSql]) -> Self {
self.params = params;
self
}
/// Set the batch size passed to `FETCH` on each iteration.
///
/// Default is 5,000.
pub fn batch_size(mut self, batch_size: u32) -> Self {
self.batch_size = batch_size;
self
}
/// Set the tag for cursor name.
///
/// Adding a tag to the cursor name can be helpful for identifying where
/// cursors originate when viewing `pg_stat_activity`.
///
/// Default is `default`.
///
/// # Examples
///
/// Any type that implements `fmt::Display` may be provided as a tag. For example, a simple
/// string literal is one option.
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// let mut cursor = Cursor::build(&conn)
/// .tag("custom-cursor-tag")
/// .finalize();
/// # }
/// ```
///
/// Or maybe you want to build a tag at run-time without incurring an extra allocation:
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate postgres_cursor;
/// # use postgres::{Connection, TlsMode};
/// # use postgres_cursor::Cursor;
/// # fn main() {
/// # let conn = Connection::connect("postgres://[email protected]/foo", TlsMode::None)
/// # .expect("connect");
/// use std::fmt;
///
/// struct Pid(i32);
/// impl fmt::Display for Pid {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "pid-{}", self.0)
/// }
/// }
///
/// let tag = Pid(8123);
/// let mut cursor = Cursor::build(&conn)
/// .tag(&tag)
/// .finalize();
/// # }
/// ```
pub fn tag<D2: fmt::Display +?Sized>(self, tag: &'builder D2) -> Builder<'conn, 'builder, D2> {
Builder {
batch_size: self.batch_size,
query: self.query,
conn: self.conn,
tag: tag,
params: self.params
}
}
/// Set the query to create a cursor for.
///
/// Default is `SELECT 1`.
pub fn query(mut self, query: &'builder str) -> Self {
self.query = query;
self
}
/// Turn the builder into a `Cursor`.
pub fn finalize(self) -> postgres::Result<Cursor<'conn>> {
Cursor::new(self)
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use postgres::{Connection, TlsMode};
use super::Cursor;
lazy_static! {
static ref LOCK: Mutex<u8> = {
Mutex::new(0)
};
}
fn synchronized<F: FnOnce() -> T, T>(func: F) -> T {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
func()
}
fn with_items<F: FnOnce(&Connection) -> T, T>(items: i32, func: F) -> T {
synchronized(|| {
let conn = get_connection();
conn.execute("TRUNCATE TABLE products", &[]).expect("truncate");
// Highly inefficient; should optimize.
for i in 0..items {
conn.execute("INSERT INTO products (id) VALUES ($1)", &[&i]).expect("insert");
}
func(&conn)
})
}
fn get_connection() -> Connection {
Connection::connect("postgres://[email protected]/postgresql_cursor_test", TlsMode::None)
.expect("connect")
}
#[test]
fn test_framework_works() {
let count = 183;
with_items(count, |conn| {
for row in &conn.query("SELECT COUNT(*) FROM products", &[]).unwrap() {
let got: i64 = row.get(0);
assert_eq!(got, count as i64);
}
});
}
#[test]
fn cursor_iter_works_when_batch_size_divisible() {
with_items(200, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 200);
});
}
#[test]
fn cursor_iter_works_when_batch_size_remainder() {
with_items(197, |conn| {
let mut cursor = Cursor::build(conn)
.batch_size(10)
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 197);
});
}
#[test]
fn build_cursor_with_tag() {
with_items(1, |conn| {
{
let cursor = Cursor::build(conn)
.tag("foobar")
.finalize().unwrap();
assert!(cursor.cursor_name.starts_with("cursor:foobar"));
}
struct Foo;
use std::fmt;
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "foo-{}", 1)
}
}
{
let foo = Foo;
let cursor = Cursor::build(conn)
.tag(&foo)
.finalize().unwrap();
println!("{}", cursor.cursor_name);
assert!(cursor.cursor_name.starts_with("cursor:foo-1"));
}
});
}
#[test]
fn cursor_with_long_tag() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.tag("really-long-tag-damn-that-was-only-three-words-foo-bar-baz")
.query("SELECT id FROM products")
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 100);
});
}
#[test]
fn cursor_with_params() {
with_items(100, |conn| {
let mut cursor = Cursor::build(conn)
.query("SELECT id FROM products WHERE id > $1 AND id < $2")
.query_params(&[&1, &10])
.finalize().unwrap();
let mut got = 0;
for batch in &mut cursor {
let batch = batch.unwrap();
got += batch.len();
}
assert_eq!(got, 8);
});
}
}
|
}
|
random_line_split
|
read.rs
|
use crate::io::AsyncRead;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use std::io;
use std::pin::Pin;
/// Future for the [`read`](super::AsyncReadExt::read) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Read<'a, R:?Sized> {
reader: &'a mut R,
|
impl<R:?Sized + Unpin> Unpin for Read<'_, R> {}
impl<'a, R: AsyncRead +?Sized + Unpin> Read<'a, R> {
pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self {
Read { reader, buf }
}
}
impl<R: AsyncRead +?Sized + Unpin> Future for Read<'_, R> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
Pin::new(&mut this.reader).poll_read(cx, this.buf)
}
}
|
buf: &'a mut [u8],
}
|
random_line_split
|
read.rs
|
use crate::io::AsyncRead;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use std::io;
use std::pin::Pin;
/// Future for the [`read`](super::AsyncReadExt::read) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct
|
<'a, R:?Sized> {
reader: &'a mut R,
buf: &'a mut [u8],
}
impl<R:?Sized + Unpin> Unpin for Read<'_, R> {}
impl<'a, R: AsyncRead +?Sized + Unpin> Read<'a, R> {
pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self {
Read { reader, buf }
}
}
impl<R: AsyncRead +?Sized + Unpin> Future for Read<'_, R> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
Pin::new(&mut this.reader).poll_read(cx, this.buf)
}
}
|
Read
|
identifier_name
|
read.rs
|
use crate::io::AsyncRead;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use std::io;
use std::pin::Pin;
/// Future for the [`read`](super::AsyncReadExt::read) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Read<'a, R:?Sized> {
reader: &'a mut R,
buf: &'a mut [u8],
}
impl<R:?Sized + Unpin> Unpin for Read<'_, R> {}
impl<'a, R: AsyncRead +?Sized + Unpin> Read<'a, R> {
pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self
|
}
impl<R: AsyncRead +?Sized + Unpin> Future for Read<'_, R> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
Pin::new(&mut this.reader).poll_read(cx, this.buf)
}
}
|
{
Read { reader, buf }
}
|
identifier_body
|
mod.rs
|
// This Source Code Form is subject to the terms of the GNU General Public
// License, version 3. If a copy of the GPL was not distributed with this file,
// You can obtain one at https://www.gnu.org/licenses/gpl.txt.
pub(super) mod tostr;
use crate::{path::ConcretePath, tree::Tree, value::Value};
use failure::Fallible;
use std::fmt;
pub trait NativeFunc {
fn compute(&self, value: Value, tree: &Tree) -> Fallible<Value>;
fn find_all_possible_inputs(
&self,
value_type: (),
tree: &Tree,
out: &mut Vec<ConcretePath>,
) -> Fallible<()>;
fn box_clone(&self) -> Box<dyn NativeFunc + Send + Sync>;
}
impl Clone for Box<dyn NativeFunc + Send + Sync> {
fn clone(&self) -> Box<dyn NativeFunc + Send + Sync>
|
}
impl fmt::Debug for Box<dyn NativeFunc + Send + Sync> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<Unknown NativeFunc>")
}
}
|
{
self.box_clone()
}
|
identifier_body
|
mod.rs
|
// This Source Code Form is subject to the terms of the GNU General Public
// License, version 3. If a copy of the GPL was not distributed with this file,
// You can obtain one at https://www.gnu.org/licenses/gpl.txt.
pub(super) mod tostr;
use crate::{path::ConcretePath, tree::Tree, value::Value};
use failure::Fallible;
use std::fmt;
pub trait NativeFunc {
fn compute(&self, value: Value, tree: &Tree) -> Fallible<Value>;
fn find_all_possible_inputs(
&self,
value_type: (),
tree: &Tree,
out: &mut Vec<ConcretePath>,
) -> Fallible<()>;
fn box_clone(&self) -> Box<dyn NativeFunc + Send + Sync>;
}
impl Clone for Box<dyn NativeFunc + Send + Sync> {
fn
|
(&self) -> Box<dyn NativeFunc + Send + Sync> {
self.box_clone()
}
}
impl fmt::Debug for Box<dyn NativeFunc + Send + Sync> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<Unknown NativeFunc>")
}
}
|
clone
|
identifier_name
|
mod.rs
|
// This Source Code Form is subject to the terms of the GNU General Public
// License, version 3. If a copy of the GPL was not distributed with this file,
// You can obtain one at https://www.gnu.org/licenses/gpl.txt.
pub(super) mod tostr;
use crate::{path::ConcretePath, tree::Tree, value::Value};
use failure::Fallible;
use std::fmt;
pub trait NativeFunc {
fn compute(&self, value: Value, tree: &Tree) -> Fallible<Value>;
fn find_all_possible_inputs(
&self,
value_type: (),
tree: &Tree,
out: &mut Vec<ConcretePath>,
) -> Fallible<()>;
fn box_clone(&self) -> Box<dyn NativeFunc + Send + Sync>;
}
impl Clone for Box<dyn NativeFunc + Send + Sync> {
fn clone(&self) -> Box<dyn NativeFunc + Send + Sync> {
self.box_clone()
}
}
|
}
}
|
impl fmt::Debug for Box<dyn NativeFunc + Send + Sync> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<Unknown NativeFunc>")
|
random_line_split
|
comm_adapters.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use clone::Clone;
use cmp;
use sync::mpsc::{Sender, Receiver};
use old_io;
use option::Option::{None, Some};
use result::Result::{Ok, Err};
use slice::{bytes, SliceExt};
use super::{Buffer, Reader, Writer, IoResult};
use vec::Vec;
/// Allows reading from a rx.
///
/// # Example
///
/// ```
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanReader;
///
/// let (tx, rx) = channel();
/// # drop(tx);
/// let mut reader = ChanReader::new(rx);
///
/// let mut buf = [0u8; 100];
/// match reader.read(&mut buf) {
/// Ok(nread) => println!("Read {} bytes", nread),
/// Err(e) => println!("read error: {}", e),
/// }
/// ```
pub struct ChanReader {
buf: Vec<u8>, // A buffer of bytes received but not consumed.
pos: uint, // How many of the buffered bytes have already be consumed.
rx: Receiver<Vec<u8>>, // The Receiver to pull data from.
closed: bool, // Whether the channel this Receiver connects to has been closed.
}
impl ChanReader {
/// Wraps a `Port` in a `ChanReader` structure
pub fn new(rx: Receiver<Vec<u8>>) -> ChanReader {
ChanReader {
buf: Vec::new(),
pos: 0,
rx: rx,
closed: false,
}
}
}
impl Buffer for ChanReader {
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos >= self.buf.len() {
self.pos = 0;
match self.rx.recv() {
Ok(bytes) => {
self.buf = bytes;
},
Err(..) => {
self.closed = true;
self.buf = Vec::new();
}
}
}
if self.closed {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(&self.buf[self.pos..])
}
}
fn consume(&mut self, amt: uint) {
self.pos += amt;
assert!(self.pos <= self.buf.len());
}
}
impl Reader for ChanReader {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let mut num_read = 0;
loop {
let count = match self.fill_buf().ok() {
Some(src) => {
let dst = &mut buf[num_read..];
let count = cmp::min(src.len(), dst.len());
bytes::copy_memory(dst, &src[..count]);
count
},
None => 0,
};
self.consume(count);
num_read += count;
if num_read == buf.len() || self.closed {
break;
}
}
if self.closed && num_read == 0 {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(num_read)
}
}
}
/// Allows writing to a tx.
///
/// # Example
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanWriter;
///
/// let (tx, rx) = channel();
/// # drop(rx);
/// let mut writer = ChanWriter::new(tx);
/// writer.write("hello, world".as_bytes());
/// ```
pub struct ChanWriter {
tx: Sender<Vec<u8>>,
}
impl ChanWriter {
/// Wraps a channel in a `ChanWriter` structure
pub fn new(tx: Sender<Vec<u8>>) -> ChanWriter {
ChanWriter { tx: tx }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for ChanWriter {
fn clone(&self) -> ChanWriter {
ChanWriter { tx: self.tx.clone() }
}
}
impl Writer for ChanWriter {
fn write_all(&mut self, buf: &[u8]) -> IoResult<()>
|
}
#[cfg(test)]
mod test {
use prelude::v1::*;
use sync::mpsc::channel;
use super::*;
use old_io;
use thread::Thread;
#[test]
fn test_rx_reader() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(vec![1u8, 2u8]).unwrap();
tx.send(vec![]).unwrap();
tx.send(vec![3u8, 4u8]).unwrap();
tx.send(vec![5u8, 6u8]).unwrap();
tx.send(vec![7u8, 8u8]).unwrap();
});
let mut reader = ChanReader::new(rx);
let mut buf = [0u8; 3];
assert_eq!(Ok(0), reader.read(&mut []));
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[1,2,3];
assert_eq!(a, buf);
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[4,5,6];
assert_eq!(a, buf);
assert_eq!(Ok(2), reader.read(&mut buf));
let a: &[u8] = &[7,8,6];
assert_eq!(a, buf);
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
// Ensure it continues to panic in the same way.
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
}
#[test]
fn test_rx_buffer() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(b"he".to_vec()).unwrap();
tx.send(b"llo wo".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
tx.send(b"rld\nhow ".to_vec()).unwrap();
tx.send(b"are you?".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
});
let mut reader = ChanReader::new(rx);
assert_eq!(Ok("hello world\n".to_string()), reader.read_line());
assert_eq!(Ok("how are you?".to_string()), reader.read_line());
match reader.read_line() {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
}
#[test]
fn test_chan_writer() {
let (tx, rx) = channel();
let mut writer = ChanWriter::new(tx);
writer.write_be_u32(42).unwrap();
let wanted = vec![0u8, 0u8, 0u8, 42u8];
let got = match Thread::scoped(move|| { rx.recv().unwrap() }).join() {
Ok(got) => got,
Err(_) => panic!(),
};
assert_eq!(wanted, got);
match writer.write_u8(1) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::BrokenPipe),
}
}
}
|
{
self.tx.send(buf.to_vec()).map_err(|_| {
old_io::IoError {
kind: old_io::BrokenPipe,
desc: "Pipe closed",
detail: None
}
})
}
|
identifier_body
|
comm_adapters.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use clone::Clone;
use cmp;
use sync::mpsc::{Sender, Receiver};
use old_io;
use option::Option::{None, Some};
use result::Result::{Ok, Err};
use slice::{bytes, SliceExt};
use super::{Buffer, Reader, Writer, IoResult};
use vec::Vec;
/// Allows reading from a rx.
///
/// # Example
///
/// ```
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanReader;
///
/// let (tx, rx) = channel();
/// # drop(tx);
/// let mut reader = ChanReader::new(rx);
///
/// let mut buf = [0u8; 100];
/// match reader.read(&mut buf) {
/// Ok(nread) => println!("Read {} bytes", nread),
/// Err(e) => println!("read error: {}", e),
/// }
/// ```
pub struct ChanReader {
buf: Vec<u8>, // A buffer of bytes received but not consumed.
pos: uint, // How many of the buffered bytes have already be consumed.
rx: Receiver<Vec<u8>>, // The Receiver to pull data from.
closed: bool, // Whether the channel this Receiver connects to has been closed.
}
impl ChanReader {
/// Wraps a `Port` in a `ChanReader` structure
pub fn new(rx: Receiver<Vec<u8>>) -> ChanReader {
ChanReader {
buf: Vec::new(),
pos: 0,
rx: rx,
closed: false,
}
}
}
impl Buffer for ChanReader {
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos >= self.buf.len() {
self.pos = 0;
match self.rx.recv() {
Ok(bytes) => {
self.buf = bytes;
},
Err(..) => {
self.closed = true;
self.buf = Vec::new();
}
}
}
if self.closed {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(&self.buf[self.pos..])
}
}
fn consume(&mut self, amt: uint) {
self.pos += amt;
assert!(self.pos <= self.buf.len());
}
}
impl Reader for ChanReader {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let mut num_read = 0;
loop {
let count = match self.fill_buf().ok() {
Some(src) => {
let dst = &mut buf[num_read..];
let count = cmp::min(src.len(), dst.len());
bytes::copy_memory(dst, &src[..count]);
count
},
None => 0,
};
|
if num_read == buf.len() || self.closed {
break;
}
}
if self.closed && num_read == 0 {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(num_read)
}
}
}
/// Allows writing to a tx.
///
/// # Example
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanWriter;
///
/// let (tx, rx) = channel();
/// # drop(rx);
/// let mut writer = ChanWriter::new(tx);
/// writer.write("hello, world".as_bytes());
/// ```
pub struct ChanWriter {
tx: Sender<Vec<u8>>,
}
impl ChanWriter {
/// Wraps a channel in a `ChanWriter` structure
pub fn new(tx: Sender<Vec<u8>>) -> ChanWriter {
ChanWriter { tx: tx }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for ChanWriter {
fn clone(&self) -> ChanWriter {
ChanWriter { tx: self.tx.clone() }
}
}
impl Writer for ChanWriter {
fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
self.tx.send(buf.to_vec()).map_err(|_| {
old_io::IoError {
kind: old_io::BrokenPipe,
desc: "Pipe closed",
detail: None
}
})
}
}
#[cfg(test)]
mod test {
use prelude::v1::*;
use sync::mpsc::channel;
use super::*;
use old_io;
use thread::Thread;
#[test]
fn test_rx_reader() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(vec![1u8, 2u8]).unwrap();
tx.send(vec![]).unwrap();
tx.send(vec![3u8, 4u8]).unwrap();
tx.send(vec![5u8, 6u8]).unwrap();
tx.send(vec![7u8, 8u8]).unwrap();
});
let mut reader = ChanReader::new(rx);
let mut buf = [0u8; 3];
assert_eq!(Ok(0), reader.read(&mut []));
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[1,2,3];
assert_eq!(a, buf);
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[4,5,6];
assert_eq!(a, buf);
assert_eq!(Ok(2), reader.read(&mut buf));
let a: &[u8] = &[7,8,6];
assert_eq!(a, buf);
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
// Ensure it continues to panic in the same way.
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
}
#[test]
fn test_rx_buffer() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(b"he".to_vec()).unwrap();
tx.send(b"llo wo".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
tx.send(b"rld\nhow ".to_vec()).unwrap();
tx.send(b"are you?".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
});
let mut reader = ChanReader::new(rx);
assert_eq!(Ok("hello world\n".to_string()), reader.read_line());
assert_eq!(Ok("how are you?".to_string()), reader.read_line());
match reader.read_line() {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
}
#[test]
fn test_chan_writer() {
let (tx, rx) = channel();
let mut writer = ChanWriter::new(tx);
writer.write_be_u32(42).unwrap();
let wanted = vec![0u8, 0u8, 0u8, 42u8];
let got = match Thread::scoped(move|| { rx.recv().unwrap() }).join() {
Ok(got) => got,
Err(_) => panic!(),
};
assert_eq!(wanted, got);
match writer.write_u8(1) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::BrokenPipe),
}
}
}
|
self.consume(count);
num_read += count;
|
random_line_split
|
comm_adapters.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use clone::Clone;
use cmp;
use sync::mpsc::{Sender, Receiver};
use old_io;
use option::Option::{None, Some};
use result::Result::{Ok, Err};
use slice::{bytes, SliceExt};
use super::{Buffer, Reader, Writer, IoResult};
use vec::Vec;
/// Allows reading from a rx.
///
/// # Example
///
/// ```
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanReader;
///
/// let (tx, rx) = channel();
/// # drop(tx);
/// let mut reader = ChanReader::new(rx);
///
/// let mut buf = [0u8; 100];
/// match reader.read(&mut buf) {
/// Ok(nread) => println!("Read {} bytes", nread),
/// Err(e) => println!("read error: {}", e),
/// }
/// ```
pub struct ChanReader {
buf: Vec<u8>, // A buffer of bytes received but not consumed.
pos: uint, // How many of the buffered bytes have already be consumed.
rx: Receiver<Vec<u8>>, // The Receiver to pull data from.
closed: bool, // Whether the channel this Receiver connects to has been closed.
}
impl ChanReader {
/// Wraps a `Port` in a `ChanReader` structure
pub fn new(rx: Receiver<Vec<u8>>) -> ChanReader {
ChanReader {
buf: Vec::new(),
pos: 0,
rx: rx,
closed: false,
}
}
}
impl Buffer for ChanReader {
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos >= self.buf.len() {
self.pos = 0;
match self.rx.recv() {
Ok(bytes) => {
self.buf = bytes;
},
Err(..) =>
|
}
}
if self.closed {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(&self.buf[self.pos..])
}
}
fn consume(&mut self, amt: uint) {
self.pos += amt;
assert!(self.pos <= self.buf.len());
}
}
impl Reader for ChanReader {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let mut num_read = 0;
loop {
let count = match self.fill_buf().ok() {
Some(src) => {
let dst = &mut buf[num_read..];
let count = cmp::min(src.len(), dst.len());
bytes::copy_memory(dst, &src[..count]);
count
},
None => 0,
};
self.consume(count);
num_read += count;
if num_read == buf.len() || self.closed {
break;
}
}
if self.closed && num_read == 0 {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(num_read)
}
}
}
/// Allows writing to a tx.
///
/// # Example
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanWriter;
///
/// let (tx, rx) = channel();
/// # drop(rx);
/// let mut writer = ChanWriter::new(tx);
/// writer.write("hello, world".as_bytes());
/// ```
pub struct ChanWriter {
tx: Sender<Vec<u8>>,
}
impl ChanWriter {
/// Wraps a channel in a `ChanWriter` structure
pub fn new(tx: Sender<Vec<u8>>) -> ChanWriter {
ChanWriter { tx: tx }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for ChanWriter {
fn clone(&self) -> ChanWriter {
ChanWriter { tx: self.tx.clone() }
}
}
impl Writer for ChanWriter {
fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
self.tx.send(buf.to_vec()).map_err(|_| {
old_io::IoError {
kind: old_io::BrokenPipe,
desc: "Pipe closed",
detail: None
}
})
}
}
#[cfg(test)]
mod test {
use prelude::v1::*;
use sync::mpsc::channel;
use super::*;
use old_io;
use thread::Thread;
#[test]
fn test_rx_reader() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(vec![1u8, 2u8]).unwrap();
tx.send(vec![]).unwrap();
tx.send(vec![3u8, 4u8]).unwrap();
tx.send(vec![5u8, 6u8]).unwrap();
tx.send(vec![7u8, 8u8]).unwrap();
});
let mut reader = ChanReader::new(rx);
let mut buf = [0u8; 3];
assert_eq!(Ok(0), reader.read(&mut []));
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[1,2,3];
assert_eq!(a, buf);
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[4,5,6];
assert_eq!(a, buf);
assert_eq!(Ok(2), reader.read(&mut buf));
let a: &[u8] = &[7,8,6];
assert_eq!(a, buf);
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
// Ensure it continues to panic in the same way.
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
}
#[test]
fn test_rx_buffer() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(b"he".to_vec()).unwrap();
tx.send(b"llo wo".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
tx.send(b"rld\nhow ".to_vec()).unwrap();
tx.send(b"are you?".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
});
let mut reader = ChanReader::new(rx);
assert_eq!(Ok("hello world\n".to_string()), reader.read_line());
assert_eq!(Ok("how are you?".to_string()), reader.read_line());
match reader.read_line() {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
}
#[test]
fn test_chan_writer() {
let (tx, rx) = channel();
let mut writer = ChanWriter::new(tx);
writer.write_be_u32(42).unwrap();
let wanted = vec![0u8, 0u8, 0u8, 42u8];
let got = match Thread::scoped(move|| { rx.recv().unwrap() }).join() {
Ok(got) => got,
Err(_) => panic!(),
};
assert_eq!(wanted, got);
match writer.write_u8(1) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::BrokenPipe),
}
}
}
|
{
self.closed = true;
self.buf = Vec::new();
}
|
conditional_block
|
comm_adapters.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use clone::Clone;
use cmp;
use sync::mpsc::{Sender, Receiver};
use old_io;
use option::Option::{None, Some};
use result::Result::{Ok, Err};
use slice::{bytes, SliceExt};
use super::{Buffer, Reader, Writer, IoResult};
use vec::Vec;
/// Allows reading from a rx.
///
/// # Example
///
/// ```
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanReader;
///
/// let (tx, rx) = channel();
/// # drop(tx);
/// let mut reader = ChanReader::new(rx);
///
/// let mut buf = [0u8; 100];
/// match reader.read(&mut buf) {
/// Ok(nread) => println!("Read {} bytes", nread),
/// Err(e) => println!("read error: {}", e),
/// }
/// ```
pub struct ChanReader {
buf: Vec<u8>, // A buffer of bytes received but not consumed.
pos: uint, // How many of the buffered bytes have already be consumed.
rx: Receiver<Vec<u8>>, // The Receiver to pull data from.
closed: bool, // Whether the channel this Receiver connects to has been closed.
}
impl ChanReader {
/// Wraps a `Port` in a `ChanReader` structure
pub fn new(rx: Receiver<Vec<u8>>) -> ChanReader {
ChanReader {
buf: Vec::new(),
pos: 0,
rx: rx,
closed: false,
}
}
}
impl Buffer for ChanReader {
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos >= self.buf.len() {
self.pos = 0;
match self.rx.recv() {
Ok(bytes) => {
self.buf = bytes;
},
Err(..) => {
self.closed = true;
self.buf = Vec::new();
}
}
}
if self.closed {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(&self.buf[self.pos..])
}
}
fn consume(&mut self, amt: uint) {
self.pos += amt;
assert!(self.pos <= self.buf.len());
}
}
impl Reader for ChanReader {
fn
|
(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let mut num_read = 0;
loop {
let count = match self.fill_buf().ok() {
Some(src) => {
let dst = &mut buf[num_read..];
let count = cmp::min(src.len(), dst.len());
bytes::copy_memory(dst, &src[..count]);
count
},
None => 0,
};
self.consume(count);
num_read += count;
if num_read == buf.len() || self.closed {
break;
}
}
if self.closed && num_read == 0 {
Err(old_io::standard_error(old_io::EndOfFile))
} else {
Ok(num_read)
}
}
}
/// Allows writing to a tx.
///
/// # Example
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::sync::mpsc::channel;
/// use std::old_io::ChanWriter;
///
/// let (tx, rx) = channel();
/// # drop(rx);
/// let mut writer = ChanWriter::new(tx);
/// writer.write("hello, world".as_bytes());
/// ```
pub struct ChanWriter {
tx: Sender<Vec<u8>>,
}
impl ChanWriter {
/// Wraps a channel in a `ChanWriter` structure
pub fn new(tx: Sender<Vec<u8>>) -> ChanWriter {
ChanWriter { tx: tx }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for ChanWriter {
fn clone(&self) -> ChanWriter {
ChanWriter { tx: self.tx.clone() }
}
}
impl Writer for ChanWriter {
fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
self.tx.send(buf.to_vec()).map_err(|_| {
old_io::IoError {
kind: old_io::BrokenPipe,
desc: "Pipe closed",
detail: None
}
})
}
}
#[cfg(test)]
mod test {
use prelude::v1::*;
use sync::mpsc::channel;
use super::*;
use old_io;
use thread::Thread;
#[test]
fn test_rx_reader() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(vec![1u8, 2u8]).unwrap();
tx.send(vec![]).unwrap();
tx.send(vec![3u8, 4u8]).unwrap();
tx.send(vec![5u8, 6u8]).unwrap();
tx.send(vec![7u8, 8u8]).unwrap();
});
let mut reader = ChanReader::new(rx);
let mut buf = [0u8; 3];
assert_eq!(Ok(0), reader.read(&mut []));
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[1,2,3];
assert_eq!(a, buf);
assert_eq!(Ok(3), reader.read(&mut buf));
let a: &[u8] = &[4,5,6];
assert_eq!(a, buf);
assert_eq!(Ok(2), reader.read(&mut buf));
let a: &[u8] = &[7,8,6];
assert_eq!(a, buf);
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
// Ensure it continues to panic in the same way.
match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
}
#[test]
fn test_rx_buffer() {
let (tx, rx) = channel();
Thread::spawn(move|| {
tx.send(b"he".to_vec()).unwrap();
tx.send(b"llo wo".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
tx.send(b"rld\nhow ".to_vec()).unwrap();
tx.send(b"are you?".to_vec()).unwrap();
tx.send(b"".to_vec()).unwrap();
});
let mut reader = ChanReader::new(rx);
assert_eq!(Ok("hello world\n".to_string()), reader.read_line());
assert_eq!(Ok("how are you?".to_string()), reader.read_line());
match reader.read_line() {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
}
#[test]
fn test_chan_writer() {
let (tx, rx) = channel();
let mut writer = ChanWriter::new(tx);
writer.write_be_u32(42).unwrap();
let wanted = vec![0u8, 0u8, 0u8, 42u8];
let got = match Thread::scoped(move|| { rx.recv().unwrap() }).join() {
Ok(got) => got,
Err(_) => panic!(),
};
assert_eq!(wanted, got);
match writer.write_u8(1) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::BrokenPipe),
}
}
}
|
read
|
identifier_name
|
lib.rs
|
//! An asynchronous implementation of [STUN][RFC 5389] server and client.
//!
//! # Examples
//!
//! An example that issues a `BINDING` request:
//!
//! ```
//! # extern crate fibers_global;
//! # extern crate fibers_transport;
//! # extern crate futures;
//! # extern crate rustun;
//! # extern crate stun_codec;
//! # extern crate trackable;
//! use fibers_transport::UdpTransporter;
//! use futures::Future;
//! use rustun::channel::Channel;
//! use rustun::client::Client;
//! use rustun::message::Request;
//! use rustun::server::{BindingHandler, UdpServer};
//! use rustun::transport::StunUdpTransporter;
//! use rustun::Error;
//! use stun_codec::{rfc5389, MessageDecoder, MessageEncoder};
//!
//! # fn main() -> Result<(), trackable::error::MainError> {
//! let addr = "127.0.0.1:0".parse().unwrap();
//!
//! // Starts UDP server
//! let server = fibers_global::execute(UdpServer::start(fibers_global::handle(), addr, BindingHandler))?;
//! let server_addr = server.local_addr();
//! fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
//!
//! // Sents BINDING request
//! let response = UdpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::bind(addr)
//! .map_err(Error::from)
//! .map(StunUdpTransporter::new)
//! .map(Channel::new)
//! .and_then(move |channel| {
//! let client = Client::new(&fibers_global::handle(), channel);
//! let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
//! client.call(server_addr, request)
//! });
//!
//! // Waits BINDING response
//! let response = fibers_global::execute(response)?;
//! assert!(response.is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! You can run example server and client that handle `BINDING` method as follows:
//!
//! ```console
//! // Starts the STUN server in a shell.
//! $ cargo run --example binding_srv
//!
//! // Executes a STUN client in another shell.
//! $ cargo run --example binding_cli -- 127.0.0.1
//! Ok(SuccessResponse(Message {
//! class: SuccessResponse,
//! method: Method(1),
//! transaction_id: TransactionId(0x344A403694972F5E53B69465),
//! attributes: [Known { inner: XorMappedAddress(XorMappedAddress(V4(127.0.0.1:54754))),
//! padding: Some(Padding([])) }]
//! }))
//! ```
//!
//! # References
//!
//! - [RFC 5389 - Session Traversal Utilities for NAT (STUN)][RFC 5389]
//!
//! [RFC 5389]: https://tools.ietf.org/html/rfc5389
#![warn(missing_docs)]
extern crate bytecodec;
extern crate factory;
extern crate fibers;
#[cfg(test)]
extern crate fibers_global;
extern crate fibers_timeout_queue;
extern crate fibers_transport;
extern crate futures;
extern crate rand;
extern crate stun_codec;
#[macro_use]
extern crate trackable;
pub use error::{Error, ErrorKind};
pub mod channel;
pub mod client;
pub mod message;
pub mod server;
pub mod transport;
mod error;
/// A specialized `Result` type for this crate.
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use crate::channel::Channel;
use crate::client::Client;
use crate::message::Request;
use crate::server::{BindingHandler, TcpServer, UdpServer};
use crate::transport::{StunTcpTransporter, StunUdpTransporter};
use crate::Error;
use factory::DefaultFactory;
use fibers_global;
use fibers_transport::{TcpTransporter, UdpTransporter};
use futures::Future;
use std::thread;
use std::time::Duration;
use stun_codec::rfc5389;
use stun_codec::{MessageDecoder, MessageEncoder};
use trackable::error::MainError;
#[test]
fn
|
() -> Result<(), MainError> {
let server = fibers_global::execute(UdpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
BindingHandler,
))?;
let server_addr = server.local_addr();
fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
let client_addr = "127.0.0.1:0".parse().unwrap();
let response = UdpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::bind(client_addr)
.map_err(Error::from)
.map(StunUdpTransporter::new)
.map(Channel::new)
.and_then(move |channel| {
let client = Client::new(&fibers_global::handle(), channel);
let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
client.call(server_addr, request)
});
let response = track!(fibers_global::execute(response))?;
assert!(response.is_ok());
Ok(())
}
#[test]
fn basic_tcp_test() -> Result<(), MainError> {
let server = fibers_global::execute(TcpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
DefaultFactory::<BindingHandler>::new(),
))?;
let server_addr = server.local_addr();
fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
thread::sleep(Duration::from_millis(50));
let response = TcpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::connect(server_addr)
.map_err(Error::from)
.map(StunTcpTransporter::new)
.map(Channel::new)
.and_then(move |channel| {
let client = Client::new(&fibers_global::handle(), channel);
let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
client.call((), request)
});
let response = track!(fibers_global::execute(response))?;
assert!(response.is_ok());
Ok(())
}
}
|
basic_udp_test
|
identifier_name
|
lib.rs
|
//! An asynchronous implementation of [STUN][RFC 5389] server and client.
//!
//! # Examples
//!
//! An example that issues a `BINDING` request:
//!
//! ```
//! # extern crate fibers_global;
//! # extern crate fibers_transport;
//! # extern crate futures;
//! # extern crate rustun;
//! # extern crate stun_codec;
//! # extern crate trackable;
//! use fibers_transport::UdpTransporter;
//! use futures::Future;
//! use rustun::channel::Channel;
//! use rustun::client::Client;
//! use rustun::message::Request;
//! use rustun::server::{BindingHandler, UdpServer};
//! use rustun::transport::StunUdpTransporter;
//! use rustun::Error;
//! use stun_codec::{rfc5389, MessageDecoder, MessageEncoder};
//!
//! # fn main() -> Result<(), trackable::error::MainError> {
//! let addr = "127.0.0.1:0".parse().unwrap();
//!
//! // Starts UDP server
//! let server = fibers_global::execute(UdpServer::start(fibers_global::handle(), addr, BindingHandler))?;
//! let server_addr = server.local_addr();
//! fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
//!
//! // Sents BINDING request
//! let response = UdpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::bind(addr)
//! .map_err(Error::from)
//! .map(StunUdpTransporter::new)
//! .map(Channel::new)
//! .and_then(move |channel| {
//! let client = Client::new(&fibers_global::handle(), channel);
//! let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
//! client.call(server_addr, request)
//! });
//!
//! // Waits BINDING response
//! let response = fibers_global::execute(response)?;
//! assert!(response.is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! You can run example server and client that handle `BINDING` method as follows:
//!
//! ```console
//! // Starts the STUN server in a shell.
//! $ cargo run --example binding_srv
//!
//! // Executes a STUN client in another shell.
//! $ cargo run --example binding_cli -- 127.0.0.1
//! Ok(SuccessResponse(Message {
//! class: SuccessResponse,
//! method: Method(1),
//! transaction_id: TransactionId(0x344A403694972F5E53B69465),
//! attributes: [Known { inner: XorMappedAddress(XorMappedAddress(V4(127.0.0.1:54754))),
//! padding: Some(Padding([])) }]
//! }))
//! ```
//!
//! # References
//!
//! - [RFC 5389 - Session Traversal Utilities for NAT (STUN)][RFC 5389]
//!
//! [RFC 5389]: https://tools.ietf.org/html/rfc5389
#![warn(missing_docs)]
extern crate bytecodec;
extern crate factory;
extern crate fibers;
#[cfg(test)]
extern crate fibers_global;
extern crate fibers_timeout_queue;
extern crate fibers_transport;
extern crate futures;
extern crate rand;
extern crate stun_codec;
#[macro_use]
extern crate trackable;
pub use error::{Error, ErrorKind};
pub mod channel;
pub mod client;
pub mod message;
pub mod server;
pub mod transport;
mod error;
/// A specialized `Result` type for this crate.
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use crate::channel::Channel;
use crate::client::Client;
use crate::message::Request;
use crate::server::{BindingHandler, TcpServer, UdpServer};
use crate::transport::{StunTcpTransporter, StunUdpTransporter};
use crate::Error;
use factory::DefaultFactory;
use fibers_global;
use fibers_transport::{TcpTransporter, UdpTransporter};
use futures::Future;
use std::thread;
use std::time::Duration;
use stun_codec::rfc5389;
use stun_codec::{MessageDecoder, MessageEncoder};
use trackable::error::MainError;
#[test]
fn basic_udp_test() -> Result<(), MainError> {
let server = fibers_global::execute(UdpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
BindingHandler,
))?;
let server_addr = server.local_addr();
fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
let client_addr = "127.0.0.1:0".parse().unwrap();
let response = UdpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::bind(client_addr)
.map_err(Error::from)
.map(StunUdpTransporter::new)
.map(Channel::new)
.and_then(move |channel| {
let client = Client::new(&fibers_global::handle(), channel);
let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
client.call(server_addr, request)
});
let response = track!(fibers_global::execute(response))?;
assert!(response.is_ok());
Ok(())
}
#[test]
fn basic_tcp_test() -> Result<(), MainError>
|
let response = track!(fibers_global::execute(response))?;
assert!(response.is_ok());
Ok(())
}
}
|
{
let server = fibers_global::execute(TcpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
DefaultFactory::<BindingHandler>::new(),
))?;
let server_addr = server.local_addr();
fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
thread::sleep(Duration::from_millis(50));
let response = TcpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::connect(server_addr)
.map_err(Error::from)
.map(StunTcpTransporter::new)
.map(Channel::new)
.and_then(move |channel| {
let client = Client::new(&fibers_global::handle(), channel);
let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
client.call((), request)
});
|
identifier_body
|
lib.rs
|
//! An asynchronous implementation of [STUN][RFC 5389] server and client.
//!
//! # Examples
//!
//! An example that issues a `BINDING` request:
//!
//! ```
//! # extern crate fibers_global;
//! # extern crate fibers_transport;
//! # extern crate futures;
//! # extern crate rustun;
//! # extern crate stun_codec;
//! # extern crate trackable;
//! use fibers_transport::UdpTransporter;
//! use futures::Future;
//! use rustun::channel::Channel;
//! use rustun::client::Client;
//! use rustun::message::Request;
//! use rustun::server::{BindingHandler, UdpServer};
//! use rustun::transport::StunUdpTransporter;
//! use rustun::Error;
//! use stun_codec::{rfc5389, MessageDecoder, MessageEncoder};
//!
//! # fn main() -> Result<(), trackable::error::MainError> {
//! let addr = "127.0.0.1:0".parse().unwrap();
//!
//! // Starts UDP server
//! let server = fibers_global::execute(UdpServer::start(fibers_global::handle(), addr, BindingHandler))?;
//! let server_addr = server.local_addr();
//! fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
//!
//! // Sents BINDING request
//! let response = UdpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::bind(addr)
//! .map_err(Error::from)
//! .map(StunUdpTransporter::new)
//! .map(Channel::new)
//! .and_then(move |channel| {
//! let client = Client::new(&fibers_global::handle(), channel);
//! let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
//! client.call(server_addr, request)
//! });
//!
//! // Waits BINDING response
//! let response = fibers_global::execute(response)?;
//! assert!(response.is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! You can run example server and client that handle `BINDING` method as follows:
//!
//! ```console
//! // Starts the STUN server in a shell.
//! $ cargo run --example binding_srv
//!
//! // Executes a STUN client in another shell.
//! $ cargo run --example binding_cli -- 127.0.0.1
//! Ok(SuccessResponse(Message {
//! class: SuccessResponse,
//! method: Method(1),
//! transaction_id: TransactionId(0x344A403694972F5E53B69465),
//! attributes: [Known { inner: XorMappedAddress(XorMappedAddress(V4(127.0.0.1:54754))),
//! padding: Some(Padding([])) }]
//! }))
//! ```
//!
//! # References
//!
//! - [RFC 5389 - Session Traversal Utilities for NAT (STUN)][RFC 5389]
//!
//! [RFC 5389]: https://tools.ietf.org/html/rfc5389
#![warn(missing_docs)]
extern crate bytecodec;
extern crate factory;
extern crate fibers;
#[cfg(test)]
extern crate fibers_global;
extern crate fibers_timeout_queue;
extern crate fibers_transport;
extern crate futures;
extern crate rand;
extern crate stun_codec;
#[macro_use]
extern crate trackable;
pub use error::{Error, ErrorKind};
pub mod channel;
pub mod client;
pub mod message;
pub mod server;
pub mod transport;
mod error;
/// A specialized `Result` type for this crate.
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use crate::channel::Channel;
use crate::client::Client;
use crate::message::Request;
use crate::server::{BindingHandler, TcpServer, UdpServer};
use crate::transport::{StunTcpTransporter, StunUdpTransporter};
use crate::Error;
use factory::DefaultFactory;
use fibers_global;
use fibers_transport::{TcpTransporter, UdpTransporter};
use futures::Future;
use std::thread;
use std::time::Duration;
use stun_codec::rfc5389;
use stun_codec::{MessageDecoder, MessageEncoder};
use trackable::error::MainError;
#[test]
fn basic_udp_test() -> Result<(), MainError> {
let server = fibers_global::execute(UdpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
BindingHandler,
))?;
let server_addr = server.local_addr();
fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
let client_addr = "127.0.0.1:0".parse().unwrap();
let response = UdpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::bind(client_addr)
.map_err(Error::from)
.map(StunUdpTransporter::new)
.map(Channel::new)
.and_then(move |channel| {
let client = Client::new(&fibers_global::handle(), channel);
let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
client.call(server_addr, request)
});
let response = track!(fibers_global::execute(response))?;
assert!(response.is_ok());
Ok(())
}
#[test]
fn basic_tcp_test() -> Result<(), MainError> {
let server = fibers_global::execute(TcpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
DefaultFactory::<BindingHandler>::new(),
))?;
let server_addr = server.local_addr();
|
fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
thread::sleep(Duration::from_millis(50));
let response = TcpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::connect(server_addr)
.map_err(Error::from)
.map(StunTcpTransporter::new)
.map(Channel::new)
.and_then(move |channel| {
let client = Client::new(&fibers_global::handle(), channel);
let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
client.call((), request)
});
let response = track!(fibers_global::execute(response))?;
assert!(response.is_ok());
Ok(())
}
}
|
random_line_split
|
|
popups.rs
|
use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static mut flag: Flag = Flag(0, 0);
pub fn get_flag_str(f: Flag) -> Option<&'static str> {
for &(text, known_flag) in FLAGS.iter() {
if known_flag == f {
return Some(text);
}
}
None
}
pub fn check_global_flags() {
if unsafe { visible } && get_frame_count() > unsafe { end_frame } {
unsafe {
visible = false;
}
let console = Console::get();
console.visible = false;
console.background_color.a = 150;
console.lines[1].visible = true;
}
if unsafe { visible } {
let console = Console::get();
console.visible = true;
console.background_color.a = 0;
console.lines[1].visible = false;
let Flag(addr, bit) = unsafe { flag };
if let Some(text) = get_flag_str(Flag(addr, 1 << bit))
|
else {
let _ = write!(
console.lines[0].begin(),
"Flag {:02X} {} has been set",
0xFF & addr,
bit
);
}
}
for (index, cached_value) in unsafe { global_flags_cache.iter_mut().enumerate() } {
let addr = 0x803B872C + index;
let current_value = read::<u8>(addr);
let diff = current_value & (0xFF ^ *cached_value);
if diff!= 0 {
for bit in 0..8 {
if diff & (1 << bit)!= 0 {
show_popup(addr, bit);
}
}
*cached_value |= diff;
}
}
}
fn show_popup(addr: Addr, bit: u8) {
unsafe {
end_frame = get_frame_count() + 200;
visible = true;
flag = Flag(addr, bit);
}
}
|
{
let text = if text.len() > 50 { &text[..50] } else { text };
let _ = write!(console.lines[0].begin(), "{}", text);
}
|
conditional_block
|
popups.rs
|
use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static mut flag: Flag = Flag(0, 0);
pub fn get_flag_str(f: Flag) -> Option<&'static str> {
for &(text, known_flag) in FLAGS.iter() {
if known_flag == f {
return Some(text);
}
}
None
}
pub fn check_global_flags() {
if unsafe { visible } && get_frame_count() > unsafe { end_frame } {
unsafe {
visible = false;
}
let console = Console::get();
console.visible = false;
console.background_color.a = 150;
console.lines[1].visible = true;
}
if unsafe { visible } {
let console = Console::get();
console.visible = true;
console.background_color.a = 0;
console.lines[1].visible = false;
let Flag(addr, bit) = unsafe { flag };
if let Some(text) = get_flag_str(Flag(addr, 1 << bit)) {
let text = if text.len() > 50 { &text[..50] } else { text };
let _ = write!(console.lines[0].begin(), "{}", text);
} else {
let _ = write!(
console.lines[0].begin(),
"Flag {:02X} {} has been set",
0xFF & addr,
bit
);
}
}
for (index, cached_value) in unsafe { global_flags_cache.iter_mut().enumerate() } {
let addr = 0x803B872C + index;
let current_value = read::<u8>(addr);
let diff = current_value & (0xFF ^ *cached_value);
if diff!= 0 {
for bit in 0..8 {
if diff & (1 << bit)!= 0 {
show_popup(addr, bit);
}
}
*cached_value |= diff;
}
}
}
fn show_popup(addr: Addr, bit: u8)
|
{
unsafe {
end_frame = get_frame_count() + 200;
visible = true;
flag = Flag(addr, bit);
}
}
|
identifier_body
|
|
popups.rs
|
use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static mut flag: Flag = Flag(0, 0);
pub fn
|
(f: Flag) -> Option<&'static str> {
for &(text, known_flag) in FLAGS.iter() {
if known_flag == f {
return Some(text);
}
}
None
}
pub fn check_global_flags() {
if unsafe { visible } && get_frame_count() > unsafe { end_frame } {
unsafe {
visible = false;
}
let console = Console::get();
console.visible = false;
console.background_color.a = 150;
console.lines[1].visible = true;
}
if unsafe { visible } {
let console = Console::get();
console.visible = true;
console.background_color.a = 0;
console.lines[1].visible = false;
let Flag(addr, bit) = unsafe { flag };
if let Some(text) = get_flag_str(Flag(addr, 1 << bit)) {
let text = if text.len() > 50 { &text[..50] } else { text };
let _ = write!(console.lines[0].begin(), "{}", text);
} else {
let _ = write!(
console.lines[0].begin(),
"Flag {:02X} {} has been set",
0xFF & addr,
bit
);
}
}
for (index, cached_value) in unsafe { global_flags_cache.iter_mut().enumerate() } {
let addr = 0x803B872C + index;
let current_value = read::<u8>(addr);
let diff = current_value & (0xFF ^ *cached_value);
if diff!= 0 {
for bit in 0..8 {
if diff & (1 << bit)!= 0 {
show_popup(addr, bit);
}
}
*cached_value |= diff;
}
}
}
fn show_popup(addr: Addr, bit: u8) {
unsafe {
end_frame = get_frame_count() + 200;
visible = true;
flag = Flag(addr, bit);
}
}
|
get_flag_str
|
identifier_name
|
popups.rs
|
use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static mut flag: Flag = Flag(0, 0);
pub fn get_flag_str(f: Flag) -> Option<&'static str> {
for &(text, known_flag) in FLAGS.iter() {
if known_flag == f {
return Some(text);
}
}
None
}
pub fn check_global_flags() {
if unsafe { visible } && get_frame_count() > unsafe { end_frame } {
unsafe {
visible = false;
}
let console = Console::get();
console.visible = false;
console.background_color.a = 150;
console.lines[1].visible = true;
}
if unsafe { visible } {
let console = Console::get();
console.visible = true;
console.background_color.a = 0;
console.lines[1].visible = false;
let Flag(addr, bit) = unsafe { flag };
if let Some(text) = get_flag_str(Flag(addr, 1 << bit)) {
let text = if text.len() > 50 { &text[..50] } else { text };
let _ = write!(console.lines[0].begin(), "{}", text);
} else {
let _ = write!(
console.lines[0].begin(),
"Flag {:02X} {} has been set",
0xFF & addr,
bit
);
}
}
|
let current_value = read::<u8>(addr);
let diff = current_value & (0xFF ^ *cached_value);
if diff!= 0 {
for bit in 0..8 {
if diff & (1 << bit)!= 0 {
show_popup(addr, bit);
}
}
*cached_value |= diff;
}
}
}
fn show_popup(addr: Addr, bit: u8) {
unsafe {
end_frame = get_frame_count() + 200;
visible = true;
flag = Flag(addr, bit);
}
}
|
for (index, cached_value) in unsafe { global_flags_cache.iter_mut().enumerate() } {
let addr = 0x803B872C + index;
|
random_line_split
|
entry.rs
|
use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn is_unused(&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::containing_address(
self.0 as usize & 0x000fffff_fffff000
))
} else {
None
}
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() &! 0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
pub flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = 1 << 1,
const USER_ACCESSIBLE = 1 << 2,
|
const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
}
|
const WRITE_THROUGH = 1 << 3,
|
random_line_split
|
entry.rs
|
use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn is_unused(&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::containing_address(
self.0 as usize & 0x000fffff_fffff000
))
} else
|
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() &! 0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
pub flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = 1 << 1,
const USER_ACCESSIBLE = 1 << 2,
const WRITE_THROUGH = 1 << 3,
const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
}
|
{
None
}
|
conditional_block
|
entry.rs
|
use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn
|
(&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::containing_address(
self.0 as usize & 0x000fffff_fffff000
))
} else {
None
}
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() &! 0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
pub flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = 1 << 1,
const USER_ACCESSIBLE = 1 << 2,
const WRITE_THROUGH = 1 << 3,
const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
}
|
is_unused
|
identifier_name
|
mod.rs
|
// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#[cfg(feature = "libvda")]
pub mod vda;
use base::AsRawDescriptor;
use crate::virtio::video::error::VideoResult;
use crate::virtio::video::{
format::Bitrate,
resource::{GuestResource, GuestResourceHandle},
};
use super::encoder::{
EncoderCapabilities, EncoderEvent, InputBufferId, OutputBufferId, SessionConfig,
};
pub trait EncoderSession {
/// Encodes the frame provided by `resource`.
/// `force_keyframe` forces the frame to be encoded as a keyframe.
/// When the buffer has been successfully processed, a `ProcessedInputBuffer` event will
/// be readable from the event pipe, with the same `InputBufferId` as returned by this
/// function.
/// When the corresponding encoded data is ready, `ProcessedOutputBuffer` events will be
/// readable from the event pipe, with the same timestamp as provided `timestamp`.
fn encode(
&mut self,
resource: GuestResource,
timestamp: u64,
force_keyframe: bool,
) -> VideoResult<InputBufferId>;
/// Provides an output `resource` to store encoded output, where `offset` and `size` define the
/// region of memory to use.
/// When the buffer has been filled with encoded output, a `ProcessedOutputBuffer` event will be
/// readable from the event pipe, with the same `OutputBufferId` as returned by this function.
fn use_output_buffer(
|
/// Requests the encoder to flush. When completed, an `EncoderEvent::FlushResponse` event will
/// be readable from the event pipe.
fn flush(&mut self) -> VideoResult<()>;
/// Requests the encoder to use new encoding parameters provided by `bitrate` and `framerate`.
fn request_encoding_params_change(
&mut self,
bitrate: Bitrate,
framerate: u32,
) -> VideoResult<()>;
/// Returns the event pipe on which the availability of events will be signaled. Note that the
/// returned value is borrowed and only valid as long as the session is alive.
fn event_pipe(&self) -> &dyn AsRawDescriptor;
/// Performs a blocking read for an encoder event. This function should only be called when
/// the file descriptor returned by `event_pipe` is readable.
fn read_event(&mut self) -> VideoResult<EncoderEvent>;
}
pub trait Encoder {
type Session: EncoderSession;
fn query_capabilities(&self) -> VideoResult<EncoderCapabilities>;
fn start_session(&mut self, config: SessionConfig) -> VideoResult<Self::Session>;
fn stop_session(&mut self, session: Self::Session) -> VideoResult<()>;
}
|
&mut self,
resource: GuestResourceHandle,
offset: u32,
size: u32,
) -> VideoResult<OutputBufferId>;
|
random_line_split
|
generic-type-params-name-repr.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(default_type_params)]
struct A;
struct B;
struct C;
struct Foo<T = A, U = B, V = C>;
struct Hash<T>;
struct HashMap<K, V, H = Hash<K>>;
fn main() {
// Ensure that the printed type doesn't include the default type params...
let _: Foo<int> = ();
//~^ ERROR mismatched types: expected `Foo<int>` but found `()`
//...even when they're present, but the same types as the defaults.
let _: Foo<int, B, C> = ();
//~^ ERROR mismatched types: expected `Foo<int>` but found `()`
|
let _: HashMap<String, int> = ();
//~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
let _: HashMap<String, int, Hash<String>> = ();
//~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
// But not when there's a different type in between.
let _: Foo<A, int, C> = ();
//~^ ERROR mismatched types: expected `Foo<A,int>` but found `()`
// And don't print <> at all when there's just defaults.
let _: Foo<A, B, C> = ();
//~^ ERROR mismatched types: expected `Foo` but found `()`
}
|
// Including cases where the default is using previous type params.
|
random_line_split
|
generic-type-params-name-repr.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(default_type_params)]
struct A;
struct
|
;
struct C;
struct Foo<T = A, U = B, V = C>;
struct Hash<T>;
struct HashMap<K, V, H = Hash<K>>;
fn main() {
// Ensure that the printed type doesn't include the default type params...
let _: Foo<int> = ();
//~^ ERROR mismatched types: expected `Foo<int>` but found `()`
//...even when they're present, but the same types as the defaults.
let _: Foo<int, B, C> = ();
//~^ ERROR mismatched types: expected `Foo<int>` but found `()`
// Including cases where the default is using previous type params.
let _: HashMap<String, int> = ();
//~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
let _: HashMap<String, int, Hash<String>> = ();
//~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
// But not when there's a different type in between.
let _: Foo<A, int, C> = ();
//~^ ERROR mismatched types: expected `Foo<A,int>` but found `()`
// And don't print <> at all when there's just defaults.
let _: Foo<A, B, C> = ();
//~^ ERROR mismatched types: expected `Foo` but found `()`
}
|
B
|
identifier_name
|
download.rs
|
use async_trait::async_trait;
use cucumber::given;
use snafu::ResultExt;
use crate::error;
use crate::error::Error;
use crate::state::{GlobalState, State, Step, StepStatus};
use tests::download;
// Download OSM
#[given(regex = r"osm file has been downloaded for (\S+)$")]
pub async fn download_osm(state: &mut GlobalState, region: String) {
state
.execute_once(DownloadOsm(region))
.await
.expect("failed to download OSM file");
}
#[derive(PartialEq)]
pub struct DownloadOsm(pub String);
#[async_trait(?Send)]
impl Step for DownloadOsm {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self(region) = self;
download::osm(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
// Download bano
#[given(regex = r"bano files have been downloaded for (.+) into (\S+)$")]
pub async fn download_bano(state: &mut GlobalState, departments: String, region: String) {
let departments = departments
.split(',')
.map(str::trim)
.map(str::to_string)
.collect();
state
.execute_once(DownloadBano {
departments,
region,
})
.await
.expect("failed to download OSM file");
}
#[derive(PartialEq)]
pub struct DownloadBano {
pub departments: Vec<String>,
pub region: String,
}
#[async_trait(?Send)]
impl Step for DownloadBano {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self {
departments,
region,
} = self;
download::bano(region, departments)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
// Download NTFS
#[given(regex = r"ntfs file has been downloaded for (\S+)$")]
pub async fn download_ntfs(state: &mut GlobalState, region: String) {
state
.execute_once(DownloadNTFS { region })
.await
.expect("failed to download NTFS file");
}
#[derive(Debug, PartialEq)]
pub struct DownloadNTFS {
pub region: String,
}
#[async_trait(?Send)]
impl Step for DownloadNTFS {
async fn
|
(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self { region } = self;
download::ntfs(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
|
execute
|
identifier_name
|
download.rs
|
use async_trait::async_trait;
use cucumber::given;
use snafu::ResultExt;
use crate::error;
use crate::error::Error;
use crate::state::{GlobalState, State, Step, StepStatus};
use tests::download;
// Download OSM
#[given(regex = r"osm file has been downloaded for (\S+)$")]
pub async fn download_osm(state: &mut GlobalState, region: String) {
state
.execute_once(DownloadOsm(region))
.await
.expect("failed to download OSM file");
}
#[derive(PartialEq)]
pub struct DownloadOsm(pub String);
#[async_trait(?Send)]
impl Step for DownloadOsm {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self(region) = self;
download::osm(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
// Download bano
#[given(regex = r"bano files have been downloaded for (.+) into (\S+)$")]
pub async fn download_bano(state: &mut GlobalState, departments: String, region: String) {
let departments = departments
.split(',')
.map(str::trim)
.map(str::to_string)
.collect();
state
.execute_once(DownloadBano {
departments,
region,
})
.await
.expect("failed to download OSM file");
}
#[derive(PartialEq)]
pub struct DownloadBano {
pub departments: Vec<String>,
pub region: String,
}
#[async_trait(?Send)]
impl Step for DownloadBano {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self {
departments,
region,
} = self;
download::bano(region, departments)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
// Download NTFS
#[given(regex = r"ntfs file has been downloaded for (\S+)$")]
pub async fn download_ntfs(state: &mut GlobalState, region: String) {
state
.execute_once(DownloadNTFS { region })
.await
.expect("failed to download NTFS file");
}
#[derive(Debug, PartialEq)]
pub struct DownloadNTFS {
pub region: String,
}
#[async_trait(?Send)]
impl Step for DownloadNTFS {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error>
|
}
|
{
let Self { region } = self;
download::ntfs(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
|
identifier_body
|
download.rs
|
use async_trait::async_trait;
use cucumber::given;
use snafu::ResultExt;
use crate::error;
use crate::error::Error;
use crate::state::{GlobalState, State, Step, StepStatus};
use tests::download;
// Download OSM
#[given(regex = r"osm file has been downloaded for (\S+)$")]
pub async fn download_osm(state: &mut GlobalState, region: String) {
state
.execute_once(DownloadOsm(region))
.await
.expect("failed to download OSM file");
}
#[derive(PartialEq)]
pub struct DownloadOsm(pub String);
#[async_trait(?Send)]
impl Step for DownloadOsm {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self(region) = self;
download::osm(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
// Download bano
#[given(regex = r"bano files have been downloaded for (.+) into (\S+)$")]
pub async fn download_bano(state: &mut GlobalState, departments: String, region: String) {
let departments = departments
.split(',')
.map(str::trim)
.map(str::to_string)
.collect();
|
state
.execute_once(DownloadBano {
departments,
region,
})
.await
.expect("failed to download OSM file");
}
#[derive(PartialEq)]
pub struct DownloadBano {
pub departments: Vec<String>,
pub region: String,
}
#[async_trait(?Send)]
impl Step for DownloadBano {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self {
departments,
region,
} = self;
download::bano(region, departments)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
// Download NTFS
#[given(regex = r"ntfs file has been downloaded for (\S+)$")]
pub async fn download_ntfs(state: &mut GlobalState, region: String) {
state
.execute_once(DownloadNTFS { region })
.await
.expect("failed to download NTFS file");
}
#[derive(Debug, PartialEq)]
pub struct DownloadNTFS {
pub region: String,
}
#[async_trait(?Send)]
impl Step for DownloadNTFS {
async fn execute(&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self { region } = self;
download::ntfs(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
|
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/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![plugin(plugins)]
#![deny(unsafe_code)]
#![plugin(serde_macros)]
extern crate canvas;
extern crate canvas_traits;
extern crate clipboard;
extern crate compositing;
extern crate devtools_traits;
extern crate euclid;
#[cfg(not(target_os = "windows"))]
extern crate gaol;
extern crate gfx;
extern crate gfx_traits;
extern crate ipc_channel;
extern crate layers;
extern crate layout_traits;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate script_traits;
extern crate serde;
extern crate style_traits;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender_traits;
mod constellation;
mod pipeline;
#[cfg(not(target_os = "windows"))]
mod sandboxing;
mod timer_scheduler;
|
pub use pipeline::UnprivilegedPipelineContent;
#[cfg(not(target_os = "windows"))]
pub use sandboxing::content_process_sandbox_profile;
|
pub use constellation::{Constellation, InitialConstellationState};
|
random_line_split
|
issue13507.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.
pub mod testtypes {
use std::intrinsics::TypeId;
pub fn type_ids() -> Vec<TypeId> {
let mut ids = vec!();
ids.push(TypeId::of::<FooNil>());
ids.push(TypeId::of::<FooBool>());
ids.push(TypeId::of::<FooInt>());
ids.push(TypeId::of::<FooUint>());
ids.push(TypeId::of::<FooFloat>());
ids.push(TypeId::of::<FooEnum>());
ids.push(TypeId::of::<FooUniq>());
ids.push(TypeId::of::<FooPtr>());
ids.push(TypeId::of::<FooClosure>());
ids.push(TypeId::of::<&'static FooTrait>());
ids.push(TypeId::of::<FooStruct>());
ids.push(TypeId::of::<FooTuple>());
ids
}
// Tests ty_nil
pub type FooNil = ();
// Skipping ty_bot
// Tests ty_bool
pub type FooBool = bool;
// Tests ty_char
pub type FooChar = char;
// Tests ty_int (does not test all variants of IntTy)
pub type FooInt = int;
// Tests ty_uint (does not test all variants of UintTy)
pub type FooUint = uint;
// Tests ty_float (does not test all variants of FloatTy)
pub type FooFloat = f64;
// For ty_str, what kind of string should I use? &'static str? ~str? Raw str?
// Tests ty_enum
pub enum FooEnum {
VarA(uint),
VarB(uint, uint)
}
// Skipping ty_box
// Tests ty_uniq (of u8)
pub type FooUniq = ~u8;
// As with ty_str, what type should be used for ty_vec?
// Tests ty_ptr
pub type FooPtr = *u8;
// Skipping ty_rptr
// Skipping ty_bare_fn (how do you get a bare function type, rather than proc or closure?)
// Tests ty_closure (does not test all types of closures)
pub type FooClosure = |arg: u8|:'static -> u8;
// Tests ty_trait
pub trait FooTrait {
fn foo_method(&self) -> uint;
fn foo_static_method() -> uint;
}
// Tests ty_struct
pub struct
|
{
pub pub_foo_field: uint,
foo_field: uint
}
// Tests ty_tup
pub type FooTuple = (u8, i8, bool);
// Skipping ty_param
// Skipping ty_self
// Skipping ty_self
// Skipping ty_infer
// Skipping ty_err
}
|
FooStruct
|
identifier_name
|
issue13507.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.
pub mod testtypes {
use std::intrinsics::TypeId;
pub fn type_ids() -> Vec<TypeId>
|
// Tests ty_nil
pub type FooNil = ();
// Skipping ty_bot
// Tests ty_bool
pub type FooBool = bool;
// Tests ty_char
pub type FooChar = char;
// Tests ty_int (does not test all variants of IntTy)
pub type FooInt = int;
// Tests ty_uint (does not test all variants of UintTy)
pub type FooUint = uint;
// Tests ty_float (does not test all variants of FloatTy)
pub type FooFloat = f64;
// For ty_str, what kind of string should I use? &'static str? ~str? Raw str?
// Tests ty_enum
pub enum FooEnum {
VarA(uint),
VarB(uint, uint)
}
// Skipping ty_box
// Tests ty_uniq (of u8)
pub type FooUniq = ~u8;
// As with ty_str, what type should be used for ty_vec?
// Tests ty_ptr
pub type FooPtr = *u8;
// Skipping ty_rptr
// Skipping ty_bare_fn (how do you get a bare function type, rather than proc or closure?)
// Tests ty_closure (does not test all types of closures)
pub type FooClosure = |arg: u8|:'static -> u8;
// Tests ty_trait
pub trait FooTrait {
fn foo_method(&self) -> uint;
fn foo_static_method() -> uint;
}
// Tests ty_struct
pub struct FooStruct {
pub pub_foo_field: uint,
foo_field: uint
}
// Tests ty_tup
pub type FooTuple = (u8, i8, bool);
// Skipping ty_param
// Skipping ty_self
// Skipping ty_self
// Skipping ty_infer
// Skipping ty_err
}
|
{
let mut ids = vec!();
ids.push(TypeId::of::<FooNil>());
ids.push(TypeId::of::<FooBool>());
ids.push(TypeId::of::<FooInt>());
ids.push(TypeId::of::<FooUint>());
ids.push(TypeId::of::<FooFloat>());
ids.push(TypeId::of::<FooEnum>());
ids.push(TypeId::of::<FooUniq>());
ids.push(TypeId::of::<FooPtr>());
ids.push(TypeId::of::<FooClosure>());
ids.push(TypeId::of::<&'static FooTrait>());
ids.push(TypeId::of::<FooStruct>());
ids.push(TypeId::of::<FooTuple>());
ids
}
|
identifier_body
|
issue13507.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.
pub mod testtypes {
use std::intrinsics::TypeId;
pub fn type_ids() -> Vec<TypeId> {
let mut ids = vec!();
ids.push(TypeId::of::<FooNil>());
ids.push(TypeId::of::<FooBool>());
ids.push(TypeId::of::<FooInt>());
ids.push(TypeId::of::<FooUint>());
ids.push(TypeId::of::<FooFloat>());
ids.push(TypeId::of::<FooEnum>());
ids.push(TypeId::of::<FooUniq>());
ids.push(TypeId::of::<FooPtr>());
ids.push(TypeId::of::<FooClosure>());
ids.push(TypeId::of::<&'static FooTrait>());
ids.push(TypeId::of::<FooStruct>());
|
}
// Tests ty_nil
pub type FooNil = ();
// Skipping ty_bot
// Tests ty_bool
pub type FooBool = bool;
// Tests ty_char
pub type FooChar = char;
// Tests ty_int (does not test all variants of IntTy)
pub type FooInt = int;
// Tests ty_uint (does not test all variants of UintTy)
pub type FooUint = uint;
// Tests ty_float (does not test all variants of FloatTy)
pub type FooFloat = f64;
// For ty_str, what kind of string should I use? &'static str? ~str? Raw str?
// Tests ty_enum
pub enum FooEnum {
VarA(uint),
VarB(uint, uint)
}
// Skipping ty_box
// Tests ty_uniq (of u8)
pub type FooUniq = ~u8;
// As with ty_str, what type should be used for ty_vec?
// Tests ty_ptr
pub type FooPtr = *u8;
// Skipping ty_rptr
// Skipping ty_bare_fn (how do you get a bare function type, rather than proc or closure?)
// Tests ty_closure (does not test all types of closures)
pub type FooClosure = |arg: u8|:'static -> u8;
// Tests ty_trait
pub trait FooTrait {
fn foo_method(&self) -> uint;
fn foo_static_method() -> uint;
}
// Tests ty_struct
pub struct FooStruct {
pub pub_foo_field: uint,
foo_field: uint
}
// Tests ty_tup
pub type FooTuple = (u8, i8, bool);
// Skipping ty_param
// Skipping ty_self
// Skipping ty_self
// Skipping ty_infer
// Skipping ty_err
}
|
ids.push(TypeId::of::<FooTuple>());
ids
|
random_line_split
|
payments.rs
|
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use api::ErrorCode;
use errors::ToErrorCode;
use errors::prelude::*;
#[derive(Debug)]
pub enum PaymentsError {
PluggedMethodError(ErrorCode),
UnknownType(String),
CommonError(CommonError),
IncompatiblePaymentError(String),
}
impl Error for PaymentsError {
fn description(&self) -> &str {
match *self {
PaymentsError::CommonError(ref err) => err.description(),
PaymentsError::UnknownType(ref msg) => msg.as_str(),
PaymentsError::PluggedMethodError(_error_code) => "Plugged method error. Consider the error code.",
PaymentsError::IncompatiblePaymentError(ref msg) => msg.as_str(),
}
}
}
impl Display for PaymentsError {
fn fmt(&self, _f: &mut Formatter) -> fmt::Result {
match *self {
PaymentsError::CommonError(ref err) => err.fmt(_f),
PaymentsError::PluggedMethodError(_err_code) => write!(_f, "Plugged method error. Consider the error code."),
PaymentsError::UnknownType(ref msg) => write!(_f, "Unknown Type Error: {}", msg),
PaymentsError::IncompatiblePaymentError(ref msg) => write!(_f, "Incompatible Payment Method Error: {}", msg),
}
}
}
impl ToErrorCode for PaymentsError {
fn
|
(&self) -> ErrorCode {
match *self {
PaymentsError::PluggedMethodError(e) => e,
PaymentsError::CommonError(ref err) => err.to_error_code(),
PaymentsError::UnknownType(ref _str) => ErrorCode::PaymentUnknownMethodError,
PaymentsError::IncompatiblePaymentError(ref _str) => ErrorCode::PaymentIncompatibleMethodsError,
}
}
}
|
to_error_code
|
identifier_name
|
payments.rs
|
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use api::ErrorCode;
use errors::ToErrorCode;
use errors::prelude::*;
#[derive(Debug)]
pub enum PaymentsError {
PluggedMethodError(ErrorCode),
UnknownType(String),
CommonError(CommonError),
IncompatiblePaymentError(String),
}
impl Error for PaymentsError {
fn description(&self) -> &str
|
}
impl Display for PaymentsError {
fn fmt(&self, _f: &mut Formatter) -> fmt::Result {
match *self {
PaymentsError::CommonError(ref err) => err.fmt(_f),
PaymentsError::PluggedMethodError(_err_code) => write!(_f, "Plugged method error. Consider the error code."),
PaymentsError::UnknownType(ref msg) => write!(_f, "Unknown Type Error: {}", msg),
PaymentsError::IncompatiblePaymentError(ref msg) => write!(_f, "Incompatible Payment Method Error: {}", msg),
}
}
}
impl ToErrorCode for PaymentsError {
fn to_error_code(&self) -> ErrorCode {
match *self {
PaymentsError::PluggedMethodError(e) => e,
PaymentsError::CommonError(ref err) => err.to_error_code(),
PaymentsError::UnknownType(ref _str) => ErrorCode::PaymentUnknownMethodError,
PaymentsError::IncompatiblePaymentError(ref _str) => ErrorCode::PaymentIncompatibleMethodsError,
}
}
}
|
{
match *self {
PaymentsError::CommonError(ref err) => err.description(),
PaymentsError::UnknownType(ref msg) => msg.as_str(),
PaymentsError::PluggedMethodError(_error_code) => "Plugged method error. Consider the error code.",
PaymentsError::IncompatiblePaymentError(ref msg) => msg.as_str(),
}
}
|
identifier_body
|
payments.rs
|
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use api::ErrorCode;
use errors::ToErrorCode;
use errors::prelude::*;
#[derive(Debug)]
pub enum PaymentsError {
PluggedMethodError(ErrorCode),
UnknownType(String),
CommonError(CommonError),
IncompatiblePaymentError(String),
}
impl Error for PaymentsError {
fn description(&self) -> &str {
match *self {
PaymentsError::CommonError(ref err) => err.description(),
PaymentsError::UnknownType(ref msg) => msg.as_str(),
|
}
}
impl Display for PaymentsError {
fn fmt(&self, _f: &mut Formatter) -> fmt::Result {
match *self {
PaymentsError::CommonError(ref err) => err.fmt(_f),
PaymentsError::PluggedMethodError(_err_code) => write!(_f, "Plugged method error. Consider the error code."),
PaymentsError::UnknownType(ref msg) => write!(_f, "Unknown Type Error: {}", msg),
PaymentsError::IncompatiblePaymentError(ref msg) => write!(_f, "Incompatible Payment Method Error: {}", msg),
}
}
}
impl ToErrorCode for PaymentsError {
fn to_error_code(&self) -> ErrorCode {
match *self {
PaymentsError::PluggedMethodError(e) => e,
PaymentsError::CommonError(ref err) => err.to_error_code(),
PaymentsError::UnknownType(ref _str) => ErrorCode::PaymentUnknownMethodError,
PaymentsError::IncompatiblePaymentError(ref _str) => ErrorCode::PaymentIncompatibleMethodsError,
}
}
}
|
PaymentsError::PluggedMethodError(_error_code) => "Plugged method error. Consider the error code.",
PaymentsError::IncompatiblePaymentError(ref msg) => msg.as_str(),
}
|
random_line_split
|
gamepadbuttonlist.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding;
use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, DomSlice};
use crate::dom::gamepadbutton::GamepadButton;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use webvr_traits::WebVRGamepadButton;
// https://w3c.github.io/gamepad/#gamepadbutton-interface
#[dom_struct]
pub struct GamepadButtonList {
reflector_: Reflector,
list: Vec<Dom<GamepadButton>>,
}
impl GamepadButtonList {
#[allow(unrooted_must_root)]
fn new_inherited(list: &[&GamepadButton]) -> GamepadButtonList {
GamepadButtonList {
reflector_: Reflector::new(),
list: list.iter().map(|button| Dom::from_ref(*button)).collect(),
}
}
pub fn new_from_vr(
global: &GlobalScope,
buttons: &[WebVRGamepadButton],
) -> DomRoot<GamepadButtonList> {
rooted_vec!(let list <- buttons.iter()
.map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched)));
reflect_dom_object(
Box::new(GamepadButtonList::new_inherited(list.r())),
global,
GamepadButtonListBinding::Wrap,
)
}
pub fn sync_from_vr(&self, vr_buttons: &[WebVRGamepadButton]) {
for (gp_btn, btn) in self.list.iter().zip(vr_buttons.iter()) {
gp_btn.update(btn.pressed, btn.touched);
}
}
}
impl GamepadButtonListMethods for GamepadButtonList {
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Length(&self) -> u32 {
self.list.len() as u32
}
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> {
self.list
.get(index as usize)
.map(|button| DomRoot::from_ref(&**button))
}
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<GamepadButton>>
|
}
|
{
self.Item(index)
}
|
identifier_body
|
gamepadbuttonlist.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding;
use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, DomSlice};
use crate::dom::gamepadbutton::GamepadButton;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use webvr_traits::WebVRGamepadButton;
// https://w3c.github.io/gamepad/#gamepadbutton-interface
#[dom_struct]
pub struct GamepadButtonList {
reflector_: Reflector,
list: Vec<Dom<GamepadButton>>,
}
impl GamepadButtonList {
#[allow(unrooted_must_root)]
fn new_inherited(list: &[&GamepadButton]) -> GamepadButtonList {
GamepadButtonList {
reflector_: Reflector::new(),
list: list.iter().map(|button| Dom::from_ref(*button)).collect(),
}
}
pub fn new_from_vr(
global: &GlobalScope,
buttons: &[WebVRGamepadButton],
) -> DomRoot<GamepadButtonList> {
rooted_vec!(let list <- buttons.iter()
.map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched)));
reflect_dom_object(
Box::new(GamepadButtonList::new_inherited(list.r())),
global,
GamepadButtonListBinding::Wrap,
)
}
pub fn sync_from_vr(&self, vr_buttons: &[WebVRGamepadButton]) {
for (gp_btn, btn) in self.list.iter().zip(vr_buttons.iter()) {
gp_btn.update(btn.pressed, btn.touched);
}
}
}
|
self.list.len() as u32
}
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> {
self.list
.get(index as usize)
.map(|button| DomRoot::from_ref(&**button))
}
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<GamepadButton>> {
self.Item(index)
}
}
|
impl GamepadButtonListMethods for GamepadButtonList {
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Length(&self) -> u32 {
|
random_line_split
|
gamepadbuttonlist.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding;
use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, DomSlice};
use crate::dom::gamepadbutton::GamepadButton;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use webvr_traits::WebVRGamepadButton;
// https://w3c.github.io/gamepad/#gamepadbutton-interface
#[dom_struct]
pub struct GamepadButtonList {
reflector_: Reflector,
list: Vec<Dom<GamepadButton>>,
}
impl GamepadButtonList {
#[allow(unrooted_must_root)]
fn new_inherited(list: &[&GamepadButton]) -> GamepadButtonList {
GamepadButtonList {
reflector_: Reflector::new(),
list: list.iter().map(|button| Dom::from_ref(*button)).collect(),
}
}
pub fn new_from_vr(
global: &GlobalScope,
buttons: &[WebVRGamepadButton],
) -> DomRoot<GamepadButtonList> {
rooted_vec!(let list <- buttons.iter()
.map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched)));
reflect_dom_object(
Box::new(GamepadButtonList::new_inherited(list.r())),
global,
GamepadButtonListBinding::Wrap,
)
}
pub fn sync_from_vr(&self, vr_buttons: &[WebVRGamepadButton]) {
for (gp_btn, btn) in self.list.iter().zip(vr_buttons.iter()) {
gp_btn.update(btn.pressed, btn.touched);
}
}
}
impl GamepadButtonListMethods for GamepadButtonList {
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Length(&self) -> u32 {
self.list.len() as u32
}
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> {
self.list
.get(index as usize)
.map(|button| DomRoot::from_ref(&**button))
}
// https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn
|
(&self, index: u32) -> Option<DomRoot<GamepadButton>> {
self.Item(index)
}
}
|
IndexedGetter
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.