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 |
---|---|---|---|---|
utf8_chars.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
use std::str;
pub fn main()
|
assert!((!str::is_utf8([0xe0_u8])));
assert!((!str::is_utf8([0xe0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xe0_u8, 0xff_u8, 0x10_u8])));
// invalid 4 byte prefix
assert!((!str::is_utf8([0xf0_u8])));
assert!((!str::is_utf8([0xf0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xf0_u8, 0xff_u8, 0x10_u8])));
assert!((!str::is_utf8([0xf0_u8, 0xff_u8, 0xff_u8, 0x10_u8])));
let mut stack = ~"a×c€";
assert_eq!(stack.pop_char(), '€');
assert_eq!(stack.pop_char(), 'c');
stack.push_char('u');
assert!(stack == ~"a×u");
assert_eq!(stack.shift_char(), 'a');
assert_eq!(stack.shift_char(), '×');
stack.unshift_char('ß');
assert!(stack == ~"ßu");
}
|
{
// Chars of 1, 2, 3, and 4 bytes
let chs: ~[char] = ~['e', 'é', '€', '\U00010000'];
let s: ~str = str::from_chars(chs);
let schs: ~[char] = s.chars().collect();
assert!(s.len() == 10u);
assert!(s.char_len() == 4u);
assert!(schs.len() == 4u);
assert!(str::from_chars(schs) == s);
assert!(s.char_at(0u) == 'e');
assert!(s.char_at(1u) == 'é');
assert!((str::is_utf8(s.as_bytes())));
// invalid prefix
assert!((!str::is_utf8([0x80_u8])));
// invalid 2 byte prefix
assert!((!str::is_utf8([0xc0_u8])));
assert!((!str::is_utf8([0xc0_u8, 0x10_u8])));
// invalid 3 byte prefix
|
identifier_body
|
utf8_chars.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
use std::str;
pub fn main() {
// Chars of 1, 2, 3, and 4 bytes
let chs: ~[char] = ~['e', 'é', '€', '\U00010000'];
let s: ~str = str::from_chars(chs);
let schs: ~[char] = s.chars().collect();
assert!(s.len() == 10u);
assert!(s.char_len() == 4u);
|
assert!((str::is_utf8(s.as_bytes())));
// invalid prefix
assert!((!str::is_utf8([0x80_u8])));
// invalid 2 byte prefix
assert!((!str::is_utf8([0xc0_u8])));
assert!((!str::is_utf8([0xc0_u8, 0x10_u8])));
// invalid 3 byte prefix
assert!((!str::is_utf8([0xe0_u8])));
assert!((!str::is_utf8([0xe0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xe0_u8, 0xff_u8, 0x10_u8])));
// invalid 4 byte prefix
assert!((!str::is_utf8([0xf0_u8])));
assert!((!str::is_utf8([0xf0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xf0_u8, 0xff_u8, 0x10_u8])));
assert!((!str::is_utf8([0xf0_u8, 0xff_u8, 0xff_u8, 0x10_u8])));
let mut stack = ~"a×c€";
assert_eq!(stack.pop_char(), '€');
assert_eq!(stack.pop_char(), 'c');
stack.push_char('u');
assert!(stack == ~"a×u");
assert_eq!(stack.shift_char(), 'a');
assert_eq!(stack.shift_char(), '×');
stack.unshift_char('ß');
assert!(stack == ~"ßu");
}
|
assert!(schs.len() == 4u);
assert!(str::from_chars(schs) == s);
assert!(s.char_at(0u) == 'e');
assert!(s.char_at(1u) == 'é');
|
random_line_split
|
utf8_chars.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
use std::str;
pub fn
|
() {
// Chars of 1, 2, 3, and 4 bytes
let chs: ~[char] = ~['e', 'é', '€', '\U00010000'];
let s: ~str = str::from_chars(chs);
let schs: ~[char] = s.chars().collect();
assert!(s.len() == 10u);
assert!(s.char_len() == 4u);
assert!(schs.len() == 4u);
assert!(str::from_chars(schs) == s);
assert!(s.char_at(0u) == 'e');
assert!(s.char_at(1u) == 'é');
assert!((str::is_utf8(s.as_bytes())));
// invalid prefix
assert!((!str::is_utf8([0x80_u8])));
// invalid 2 byte prefix
assert!((!str::is_utf8([0xc0_u8])));
assert!((!str::is_utf8([0xc0_u8, 0x10_u8])));
// invalid 3 byte prefix
assert!((!str::is_utf8([0xe0_u8])));
assert!((!str::is_utf8([0xe0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xe0_u8, 0xff_u8, 0x10_u8])));
// invalid 4 byte prefix
assert!((!str::is_utf8([0xf0_u8])));
assert!((!str::is_utf8([0xf0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xf0_u8, 0xff_u8, 0x10_u8])));
assert!((!str::is_utf8([0xf0_u8, 0xff_u8, 0xff_u8, 0x10_u8])));
let mut stack = ~"a×c€";
assert_eq!(stack.pop_char(), '€');
assert_eq!(stack.pop_char(), 'c');
stack.push_char('u');
assert!(stack == ~"a×u");
assert_eq!(stack.shift_char(), 'a');
assert_eq!(stack.shift_char(), '×');
stack.unshift_char('ß');
assert!(stack == ~"ßu");
}
|
main
|
identifier_name
|
mod.rs
|
`send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` instances are easily constructed using *combinators*.
//!
//! ## Example
//!
//! Here we create a `SendDesc` instance that just sends a GET request and waits for a response:
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # use async_coap::null::NullLocalEndpoint;
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! #
//! let mut remote_endpoint = local_endpoint
//! .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! .expect("Remote endpoint lookup failed");
//!
//! let future = remote_endpoint.send(CoapRequest::get());
//!
//! assert_eq!(future.await, Ok(()));
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! That `SendDesc` was perhaps a little *too* simple: it doesn't even interpret the results,
//! returning `Ok(())` for any message responding with a `2.05 Content` message!
//!
//! By using the combinator `.emit_successful_response()`, we can have our `SendDesc` return
//! an owned copy of the message it received ([`OwnedImmutableMessage`](crate::message::OwnedImmutableMessage)):
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! # use async_coap::message::OwnedImmutableMessage;
//! # let mut remote_endpoint = local_endpoint
//! # .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! # .expect("Remote endpoint lookup failed");
//! #
//! #
//! let send_desc = CoapRequest::get().emit_successful_response();
//!
//! let future = remote_endpoint.send(send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! What if we wanted the response in JSON? What if it was really large and we
//! knew we would need to do a block2 transfer? We can do that easily:
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response();
//!
//! // Here we are specifying that we want to send the request to a specific
//! // path on the remote endpoint, `/large` in this case.
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! But if this is a large amount of data, we won't get any indication about the transfer
//! until it is done. What if we wanted to add some printouts about the status?
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response()
//! .inspect(|context| {
//! let addr = context.remote_address();
//! let msg = context.message();
//!
//! // Print out each individual block message received.
//! println!("Got {:?} from {}", msg, addr);
//! });
//!
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! There are [many more combinators][SendDescExt] for doing all sorts of things, such as
//! adding additional options and [block2 message aggregation](SendDescUnicast::block2).
use super::*;
mod request;
pub use request::*;
mod observe;
pub use observe::*;
mod unicast_block2;
pub use unicast_block2::*;
mod handler;
pub use handler::*;
mod inspect;
pub use inspect::*;
mod payload;
pub use payload::*;
mod ping;
pub use ping::Ping;
mod add_option;
pub use add_option::*;
mod nonconfirmable;
pub use nonconfirmable::*;
mod multicast;
pub use multicast::*;
mod emit;
pub use emit::*;
mod include_socket_addr;
pub use include_socket_addr::*;
mod uri_host_path;
pub use uri_host_path::UriHostPath;
use std::iter::{once, Once};
use std::marker::PhantomData;
use std::ops::Bound;
use std::time::Duration;
/// # Send Descriptor Trait
///
/// Types implementing this trait can be passed to the `send*` methods of [`LocalEndpoint`]
/// and [`RemoteEndpoint`], and can define almost every aspect of how a message transaction
/// is handled.
///
/// See the [module level documentation](index.html) for more information on typical usage
/// patterns.
///
/// ## Internals
///
/// There are several methods in this trait, but three of them are critical:
///
/// * [`write_options`](SendDesc::write_options)\: Defines which options are going to be
/// included in the outbound message.
/// * [`write_payload`](SendDesc::write_payload)\: Defines the contents of the payload for the
/// outbound message.
/// * [`handler`](SendDesc::handler)\: Handles inbound reply messages, as well as error conditions.
///
pub trait SendDesc<IC, R = (), TP = StandardCoapConstants>: Send
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// **Experimental**: Gets custom transmission parameters.
fn trans_params(&self) -> Option<TP> {
None
}
/// **Experimental**: Used for determining if the given option seen in the reply message
/// is supported or not.
///
/// Response messages with any options that cause this
/// method to return false will be rejected.
///
fn supports_option(&self, option: OptionNumber) -> bool {
!option.is_critical()
}
/// Calculates the duration of the delay to wait before sending the next retransmission.
///
/// If `None` is returned, then no further retransmissions will be attempted.
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<Duration> {
if retransmits_sent > TP::COAP_MAX_RETRANSMIT
|
let ret = (TP::COAP_ACK_TIMEOUT.as_millis() as u64) << retransmits_sent as u64;
const JDIV: u64 = 512u64;
let rmod: u64 = (JDIV as f32 * (TP::COAP_ACK_RANDOM_FACTOR - 1.0)) as u64;
let jmul = JDIV + rand::random::<u64>() % rmod;
Some(Duration::from_millis(ret * jmul / JDIV))
}
/// The delay to wait between when we have received a successful response and when
/// we should send out another request.
///
/// The new request will have a new msg_id, but
/// the same token. The retransmission counter will be reset to zero.
///
/// This mechanism is currently used exclusively for CoAP observing.
///
/// The default return value is `None`, indicating that there are to be no message
/// restarts.
fn delay_to_restart(&self) -> Option<Duration> {
None
}
/// The maximum time to wait for an asynchronous response after having received an ACK.
fn max_rtt(&self) -> Duration {
TP::COAP_MAX_RTT
}
/// the maximum time from the first transmission of a Confirmable message to the time when
/// the sender gives up on receiving an acknowledgement or reset.
fn transmit_wait_duration(&self) -> Duration {
TP::COAP_MAX_TRANSMIT_WAIT
}
/// Defines which options are going to be included in the outbound message.
///
/// Writes all options in the given range to `msg`.
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error>;
/// Generates the outbound message by making calls into `msg`.
fn write_payload(
&self,
msg: &mut dyn MessageWrite,
socket_addr: &IC::SocketAddr,
) -> Result<(), Error>;
/// Handles the response to the outbound message.
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<R>, Error>;
}
/// Marker trait for identifying that this `SendDesc` is for *unicast* requests.
/// Also contains unicast-specific combinators, such as [`block2()`][SendDescUnicast::block2].
pub trait SendDescUnicast {
/// Returns a send descriptor that will perform Block2 processing.
///
/// Note that just adding this to your send descriptor chain alone is unlikely to do what
/// you want. You've got three options:
///
/// * Add a call to [`emit_successful_collected_response`][UnicastBlock2::emit_successful_collected_response]
/// immediately after the call to this method. This will cause the message to be reconstructed from the blocks
/// and returned as a value from the future from `send`. You can optionally add an
/// [`inspect`][SendDescExt::inspect] combinator to get some feedback as the message is being
/// reconstructed from all of the individual block messages.
/// * Add a call to [`emit_successful_response`][SendDescExt::emit_successful_response] along
/// with using `send_to_stream` instead of `send`. This will give you a `Stream` that will
/// contain all of the individual block messages in the stream.
/// * [Add your own handler][SendDescExt::use_handler] to do whatever you need to do, returning
/// `ResponseStatus::SendNext` until all of the blocks have been received. This is
/// useful if you want to avoid memory allocation.
///
/// There may be other valid combinations of combinators, depending on what you are trying
/// to do.
fn block2<IC, R, TP>(self, block2: Option<BlockInfo>) -> UnicastBlock2<Self, IC>
where
IC: InboundContext,
R: Send,
TP: TransParams,
Self: SendDesc<IC, R, TP> + Sized,
{
UnicastBlock2::new(self, block2)
}
}
/// Marker trait for identifying that this `SendDesc` is for *multicast* requests.
/// Also contains multicast-specific extensions.
pub trait SendDescMulticast {}
/// Combinator extension trait for Send Descriptors.
pub trait SendDescExt<IC, R, TP>: SendDesc<IC, R, TP> + Sized
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// Adds zero or more instances of the option `key`, using values coming from `viter`.
///
/// This method allows you to conditionally add options to a send descriptor. For example,
/// you could convert an `Option` to an iterator (using `into_iterator()`) and pass it to
/// this method: if the `Option` is `None` then no coap option will be added.
fn add_option_iter<K, I>(self, key: OptionKey<K>, viter: I) -> AddOption<Self, K, I, IC>
where
I: IntoIterator<Item = K> + Send + Clone,
K: Send + Clone,
{
AddOption {
inner: self,
key,
viter,
phantom: PhantomData,
}
}
/// Adds one instance of the option `key` with a value of `value`.
fn add_option<K>(self, key: OptionKey<K>, value: K) -> AddOption<Self, K, Once<K>, IC>
where
K: Send + Clone,
{
self.add_option_iter(key, once(value))
}
/// Adds an Accept option with the given `ContentFormat`.
fn accept(
self,
accept: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC> {
self.add_option(option::ACCEPT, accept)
}
/// Adds an Content-Format option with the given `ContentFormat`.
fn content_format(
self,
content_format: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC> {
self.add_option(option::CONTENT_FORMAT, content_format)
}
/// Adds a handler function to be called when a response message has been received (or when
/// an error has occurred).
fn use_handler<F, FR>(self, handler: F) -> Handler<Self, F>
where
F: FnMut(
Result<&dyn InboundContext<SocketAddr = IC::SocketAddr>, Error>,
) -> Result<ResponseStatus<FR>, Error>
+ Send,
FR: Send,
{
Handler {
inner: self,
handler,
}
}
/// Updates the send descriptor chain to emit any received message as a result, even
/// if that message has a message code that indicates an error.
fn emit_any_response(self) -> EmitAnyResponse<Self> {
EmitAnyResponse::new(self)
}
/// Updates the send descriptor chain to emit received message as a result, but only
/// if that message has a message code that indicates success.
fn emit_successful_response(self) -> EmitSuccessfulResponse<Self> {
EmitSuccessfulResponse::new(self)
}
/// Updates the send descriptor chain to emit only the message code of the received
/// response.
fn emit_msg_code(self) -> EmitMsgCode<Self> {
EmitMsgCode::new(self)
}
/// Updates the send descriptor chain to also emit the SocketAddr of the sender
/// of the response, resulting in tuple return type.
///
/// This is useful for handling responses to a multicast request.
fn include_socket_addr(self) -> IncludeSocketAddr<Self> {
IncludeSocketAddr::new(self)
}
/// Adds an inspection closure that will be called for each received response message.
///
/// The inspector closure will not be called if no responses are received, and it cannot
/// change the behavior of the send descriptor chain. If you need either of those
/// behaviors, see [`SendDescExt::use_handler`].
fn inspect<F>(self, inspect: F) -> Inspect<Self, F>
where
F: FnMut(&dyn InboundContext<SocketAddr = IC::SocketAddr>) + Send,
{
Inspect {
inner: self,
inspect,
}
}
/// Adds a closure that writes to the payload of the outbound message.
fn payload_writer<F>(self, writer: F) -> PayloadWriter<Self, F>
where
F: Fn(&mut dyn MessageWrite) -> Result<(), Error> + Send,
{
PayloadWriter {
inner: self,
writer,
}
}
/// Allows you to specify the URI_HOST, URI_PATH, and URI_QUERY option values
/// in a more convenient way than using `add_option_iter` manually.
fn uri_host_path<T: Into<RelRefBuf>>(
self,
host: Option<String>,
uri_path: T,
) -> UriHostPath<Self, IC> {
UriHostPath {
inner: self,
host,
path_and_query: uri_path.into(),
phantom: PhantomData,
}
}
}
/// Blanket implementation of `SendDescExt` for all types implementing `SendDesc`.
impl<T, IC, R, TP> SendDescExt<IC, R, TP> for T
where
T: SendDesc<IC, R, TP>,
IC: InboundContext,
R: Send,
TP: TransParams,
{
}
/// Helper macro that assists with writing correct implementations of [`SendDesc::write_options`].
///
/// ## Example
///
/// ```
/// # use async_coap::uri::RelRefBuf;
/// # use std::marker::PhantomData;
/// # use async_coap::send_desc::SendDesc;
/// # use async_coap::prelude::*;
/// # use async_coap::write_options;
/// # use async_coap::{InboundContext, Error, message::MessageWrite};
/// # use std::ops::Bound;
/// # pub struct WriteOptionsExample<IC>(PhantomData<IC>);
/// # impl<IC: InboundContext> SendDesc<IC, ()> for WriteOptionsExample<IC> {
/// #
/// fn write_options(
/// &self,
/// msg: &mut dyn OptionInsert,
/// socket_addr: &IC::SocketAddr,
/// start: Bound<OptionNumber>,
/// end: Bound<OptionNumber>,
/// ) -> Result<(), Error> {
/// write_options!((msg, socket_addr, start, end) {
/// // Note that the options **MUST** be listed **in numerical order**,
/// // otherwise the behavior will be undefined!
/// URI_HOST => Some("example.com").into_iter(),
/// URI_PORT => Some(1234).into_iter(),
/// URI_PATH => vec!["a","b","c"].into_iter(),
/// })
/// }
/// #
/// # fn write_payload(&self,msg: &mut dyn MessageWrite, socket_addr: &IC::SocketAddr) -> Result<(), Error> {
/// # Ok(())
/// # }
/// # fn handler(&mut self,context: Result<&IC, Error>) -> Result<ResponseStatus<()>, Error> {
/// # context.map(|_| ResponseStatus::Done(()))
/// # }
/// # }
/// ```
#[macro_export]
macro_rules! write_options {
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr, $inner:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let inner = &$inner;
let msg = $msg;
let socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr, inner); )*
inner.write_options(msg, socket_addr, start, end)
}};
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let msg = $msg;
let _socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr); )*
let _ = start;
Ok(())
}};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident, $inner:expr) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end,$inner){$($key=>$viter),*})
};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end){$($key=>$viter),*})
};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident, $inner:expr) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
$inner.write_options($msg, $socket_addr, $start, Bound::Included(key.0))?;
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
}
/// Helper macro that provides pass-thru implementations of the timing-related methods
/// of a [`SendDesc`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_timing {
($inner:tt) => {
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<::core::time::Duration> {
self.$inner.delay_to_retransmit(retransmits_sent)
}
fn delay_to_restart(&self) -> Option<::core::time::Duration> {
self.$inner.delay_to_restart()
}
fn max_rtt(&self) -> ::core::time::Duration {
self.$inner.max_rtt()
}
fn transmit_wait_duration(&self) -> ::core::time::Duration {
self.$inner.transmit_wait_duration()
}
}
}
/// Helper macro that provides pass-thru implementation of [`SendDesc::write_options`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_options {
($inner:tt) => {
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error> {
self.$inner.write_options(msg, socket_addr, start, end)
}
}
}
/// Helper macro that provides pass-thru implementations of [`SendDesc::handler`] and
/// [`SendDesc::supports_option`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_handler {
($inner:tt, $rt:ty) => {
fn supports_option(&self, option: OptionNumber) -> bool {
self.$inner.supports_option(option)
}
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<$rt>, Error> {
self.$inner.handler(context)
}
};
|
{
return None;
}
|
conditional_block
|
mod.rs
|
to the `send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` instances are easily constructed using *combinators*.
//!
//! ## Example
//!
//! Here we create a `SendDesc` instance that just sends a GET request and waits for a response:
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # use async_coap::null::NullLocalEndpoint;
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! #
//! let mut remote_endpoint = local_endpoint
//! .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! .expect("Remote endpoint lookup failed");
//!
//! let future = remote_endpoint.send(CoapRequest::get());
//!
//! assert_eq!(future.await, Ok(()));
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! That `SendDesc` was perhaps a little *too* simple: it doesn't even interpret the results,
//! returning `Ok(())` for any message responding with a `2.05 Content` message!
//!
//! By using the combinator `.emit_successful_response()`, we can have our `SendDesc` return
//! an owned copy of the message it received ([`OwnedImmutableMessage`](crate::message::OwnedImmutableMessage)):
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! # use async_coap::message::OwnedImmutableMessage;
//! # let mut remote_endpoint = local_endpoint
//! # .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! # .expect("Remote endpoint lookup failed");
//! #
//! #
//! let send_desc = CoapRequest::get().emit_successful_response();
//!
//! let future = remote_endpoint.send(send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! What if we wanted the response in JSON? What if it was really large and we
//! knew we would need to do a block2 transfer? We can do that easily:
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response();
//!
//! // Here we are specifying that we want to send the request to a specific
//! // path on the remote endpoint, `/large` in this case.
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! But if this is a large amount of data, we won't get any indication about the transfer
//! until it is done. What if we wanted to add some printouts about the status?
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response()
//! .inspect(|context| {
//! let addr = context.remote_address();
//! let msg = context.message();
//!
//! // Print out each individual block message received.
//! println!("Got {:?} from {}", msg, addr);
//! });
//!
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! There are [many more combinators][SendDescExt] for doing all sorts of things, such as
//! adding additional options and [block2 message aggregation](SendDescUnicast::block2).
use super::*;
mod request;
pub use request::*;
mod observe;
pub use observe::*;
mod unicast_block2;
pub use unicast_block2::*;
mod handler;
pub use handler::*;
mod inspect;
pub use inspect::*;
mod payload;
pub use payload::*;
mod ping;
pub use ping::Ping;
mod add_option;
pub use add_option::*;
mod nonconfirmable;
pub use nonconfirmable::*;
mod multicast;
pub use multicast::*;
mod emit;
pub use emit::*;
mod include_socket_addr;
pub use include_socket_addr::*;
mod uri_host_path;
pub use uri_host_path::UriHostPath;
use std::iter::{once, Once};
use std::marker::PhantomData;
use std::ops::Bound;
use std::time::Duration;
/// # Send Descriptor Trait
///
/// Types implementing this trait can be passed to the `send*` methods of [`LocalEndpoint`]
/// and [`RemoteEndpoint`], and can define almost every aspect of how a message transaction
/// is handled.
///
/// See the [module level documentation](index.html) for more information on typical usage
/// patterns.
///
/// ## Internals
///
/// There are several methods in this trait, but three of them are critical:
///
/// * [`write_options`](SendDesc::write_options)\: Defines which options are going to be
/// included in the outbound message.
/// * [`write_payload`](SendDesc::write_payload)\: Defines the contents of the payload for the
/// outbound message.
/// * [`handler`](SendDesc::handler)\: Handles inbound reply messages, as well as error conditions.
///
pub trait SendDesc<IC, R = (), TP = StandardCoapConstants>: Send
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// **Experimental**: Gets custom transmission parameters.
fn trans_params(&self) -> Option<TP> {
None
}
/// **Experimental**: Used for determining if the given option seen in the reply message
/// is supported or not.
///
/// Response messages with any options that cause this
/// method to return false will be rejected.
///
fn supports_option(&self, option: OptionNumber) -> bool {
!option.is_critical()
}
/// Calculates the duration of the delay to wait before sending the next retransmission.
///
/// If `None` is returned, then no further retransmissions will be attempted.
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<Duration> {
if retransmits_sent > TP::COAP_MAX_RETRANSMIT {
return None;
}
let ret = (TP::COAP_ACK_TIMEOUT.as_millis() as u64) << retransmits_sent as u64;
const JDIV: u64 = 512u64;
let rmod: u64 = (JDIV as f32 * (TP::COAP_ACK_RANDOM_FACTOR - 1.0)) as u64;
let jmul = JDIV + rand::random::<u64>() % rmod;
Some(Duration::from_millis(ret * jmul / JDIV))
}
/// The delay to wait between when we have received a successful response and when
/// we should send out another request.
///
/// The new request will have a new msg_id, but
/// the same token. The retransmission counter will be reset to zero.
///
/// This mechanism is currently used exclusively for CoAP observing.
///
/// The default return value is `None`, indicating that there are to be no message
/// restarts.
fn delay_to_restart(&self) -> Option<Duration> {
None
}
/// The maximum time to wait for an asynchronous response after having received an ACK.
fn max_rtt(&self) -> Duration {
TP::COAP_MAX_RTT
}
/// the maximum time from the first transmission of a Confirmable message to the time when
/// the sender gives up on receiving an acknowledgement or reset.
fn transmit_wait_duration(&self) -> Duration {
TP::COAP_MAX_TRANSMIT_WAIT
}
/// Defines which options are going to be included in the outbound message.
///
/// Writes all options in the given range to `msg`.
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error>;
/// Generates the outbound message by making calls into `msg`.
fn write_payload(
&self,
msg: &mut dyn MessageWrite,
socket_addr: &IC::SocketAddr,
) -> Result<(), Error>;
/// Handles the response to the outbound message.
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<R>, Error>;
}
/// Marker trait for identifying that this `SendDesc` is for *unicast* requests.
/// Also contains unicast-specific combinators, such as [`block2()`][SendDescUnicast::block2].
pub trait SendDescUnicast {
/// Returns a send descriptor that will perform Block2 processing.
///
/// Note that just adding this to your send descriptor chain alone is unlikely to do what
/// you want. You've got three options:
///
/// * Add a call to [`emit_successful_collected_response`][UnicastBlock2::emit_successful_collected_response]
/// immediately after the call to this method. This will cause the message to be reconstructed from the blocks
/// and returned as a value from the future from `send`. You can optionally add an
/// [`inspect`][SendDescExt::inspect] combinator to get some feedback as the message is being
/// reconstructed from all of the individual block messages.
/// * Add a call to [`emit_successful_response`][SendDescExt::emit_successful_response] along
/// with using `send_to_stream` instead of `send`. This will give you a `Stream` that will
/// contain all of the individual block messages in the stream.
/// * [Add your own handler][SendDescExt::use_handler] to do whatever you need to do, returning
/// `ResponseStatus::SendNext` until all of the blocks have been received. This is
/// useful if you want to avoid memory allocation.
///
/// There may be other valid combinations of combinators, depending on what you are trying
/// to do.
fn block2<IC, R, TP>(self, block2: Option<BlockInfo>) -> UnicastBlock2<Self, IC>
where
IC: InboundContext,
R: Send,
TP: TransParams,
Self: SendDesc<IC, R, TP> + Sized,
{
UnicastBlock2::new(self, block2)
}
}
/// Marker trait for identifying that this `SendDesc` is for *multicast* requests.
/// Also contains multicast-specific extensions.
pub trait SendDescMulticast {}
/// Combinator extension trait for Send Descriptors.
pub trait SendDescExt<IC, R, TP>: SendDesc<IC, R, TP> + Sized
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// Adds zero or more instances of the option `key`, using values coming from `viter`.
///
/// This method allows you to conditionally add options to a send descriptor. For example,
/// you could convert an `Option` to an iterator (using `into_iterator()`) and pass it to
/// this method: if the `Option` is `None` then no coap option will be added.
fn add_option_iter<K, I>(self, key: OptionKey<K>, viter: I) -> AddOption<Self, K, I, IC>
where
I: IntoIterator<Item = K> + Send + Clone,
K: Send + Clone,
{
AddOption {
inner: self,
key,
|
/// Adds one instance of the option `key` with a value of `value`.
fn add_option<K>(self, key: OptionKey<K>, value: K) -> AddOption<Self, K, Once<K>, IC>
where
K: Send + Clone,
{
self.add_option_iter(key, once(value))
}
/// Adds an Accept option with the given `ContentFormat`.
fn accept(
self,
accept: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC> {
self.add_option(option::ACCEPT, accept)
}
/// Adds an Content-Format option with the given `ContentFormat`.
fn content_format(
self,
content_format: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC> {
self.add_option(option::CONTENT_FORMAT, content_format)
}
/// Adds a handler function to be called when a response message has been received (or when
/// an error has occurred).
fn use_handler<F, FR>(self, handler: F) -> Handler<Self, F>
where
F: FnMut(
Result<&dyn InboundContext<SocketAddr = IC::SocketAddr>, Error>,
) -> Result<ResponseStatus<FR>, Error>
+ Send,
FR: Send,
{
Handler {
inner: self,
handler,
}
}
/// Updates the send descriptor chain to emit any received message as a result, even
/// if that message has a message code that indicates an error.
fn emit_any_response(self) -> EmitAnyResponse<Self> {
EmitAnyResponse::new(self)
}
/// Updates the send descriptor chain to emit received message as a result, but only
/// if that message has a message code that indicates success.
fn emit_successful_response(self) -> EmitSuccessfulResponse<Self> {
EmitSuccessfulResponse::new(self)
}
/// Updates the send descriptor chain to emit only the message code of the received
/// response.
fn emit_msg_code(self) -> EmitMsgCode<Self> {
EmitMsgCode::new(self)
}
/// Updates the send descriptor chain to also emit the SocketAddr of the sender
/// of the response, resulting in tuple return type.
///
/// This is useful for handling responses to a multicast request.
fn include_socket_addr(self) -> IncludeSocketAddr<Self> {
IncludeSocketAddr::new(self)
}
/// Adds an inspection closure that will be called for each received response message.
///
/// The inspector closure will not be called if no responses are received, and it cannot
/// change the behavior of the send descriptor chain. If you need either of those
/// behaviors, see [`SendDescExt::use_handler`].
fn inspect<F>(self, inspect: F) -> Inspect<Self, F>
where
F: FnMut(&dyn InboundContext<SocketAddr = IC::SocketAddr>) + Send,
{
Inspect {
inner: self,
inspect,
}
}
/// Adds a closure that writes to the payload of the outbound message.
fn payload_writer<F>(self, writer: F) -> PayloadWriter<Self, F>
where
F: Fn(&mut dyn MessageWrite) -> Result<(), Error> + Send,
{
PayloadWriter {
inner: self,
writer,
}
}
/// Allows you to specify the URI_HOST, URI_PATH, and URI_QUERY option values
/// in a more convenient way than using `add_option_iter` manually.
fn uri_host_path<T: Into<RelRefBuf>>(
self,
host: Option<String>,
uri_path: T,
) -> UriHostPath<Self, IC> {
UriHostPath {
inner: self,
host,
path_and_query: uri_path.into(),
phantom: PhantomData,
}
}
}
/// Blanket implementation of `SendDescExt` for all types implementing `SendDesc`.
impl<T, IC, R, TP> SendDescExt<IC, R, TP> for T
where
T: SendDesc<IC, R, TP>,
IC: InboundContext,
R: Send,
TP: TransParams,
{
}
/// Helper macro that assists with writing correct implementations of [`SendDesc::write_options`].
///
/// ## Example
///
/// ```
/// # use async_coap::uri::RelRefBuf;
/// # use std::marker::PhantomData;
/// # use async_coap::send_desc::SendDesc;
/// # use async_coap::prelude::*;
/// # use async_coap::write_options;
/// # use async_coap::{InboundContext, Error, message::MessageWrite};
/// # use std::ops::Bound;
/// # pub struct WriteOptionsExample<IC>(PhantomData<IC>);
/// # impl<IC: InboundContext> SendDesc<IC, ()> for WriteOptionsExample<IC> {
/// #
/// fn write_options(
/// &self,
/// msg: &mut dyn OptionInsert,
/// socket_addr: &IC::SocketAddr,
/// start: Bound<OptionNumber>,
/// end: Bound<OptionNumber>,
/// ) -> Result<(), Error> {
/// write_options!((msg, socket_addr, start, end) {
/// // Note that the options **MUST** be listed **in numerical order**,
/// // otherwise the behavior will be undefined!
/// URI_HOST => Some("example.com").into_iter(),
/// URI_PORT => Some(1234).into_iter(),
/// URI_PATH => vec!["a","b","c"].into_iter(),
/// })
/// }
/// #
/// # fn write_payload(&self,msg: &mut dyn MessageWrite, socket_addr: &IC::SocketAddr) -> Result<(), Error> {
/// # Ok(())
/// # }
/// # fn handler(&mut self,context: Result<&IC, Error>) -> Result<ResponseStatus<()>, Error> {
/// # context.map(|_| ResponseStatus::Done(()))
/// # }
/// # }
/// ```
#[macro_export]
macro_rules! write_options {
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr, $inner:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let inner = &$inner;
let msg = $msg;
let socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr, inner); )*
inner.write_options(msg, socket_addr, start, end)
}};
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let msg = $msg;
let _socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr); )*
let _ = start;
Ok(())
}};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident, $inner:expr) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end,$inner){$($key=>$viter),*})
};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end){$($key=>$viter),*})
};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident, $inner:expr) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
$inner.write_options($msg, $socket_addr, $start, Bound::Included(key.0))?;
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
}
/// Helper macro that provides pass-thru implementations of the timing-related methods
/// of a [`SendDesc`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_timing {
($inner:tt) => {
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<::core::time::Duration> {
self.$inner.delay_to_retransmit(retransmits_sent)
}
fn delay_to_restart(&self) -> Option<::core::time::Duration> {
self.$inner.delay_to_restart()
}
fn max_rtt(&self) -> ::core::time::Duration {
self.$inner.max_rtt()
}
fn transmit_wait_duration(&self) -> ::core::time::Duration {
self.$inner.transmit_wait_duration()
}
}
}
/// Helper macro that provides pass-thru implementation of [`SendDesc::write_options`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_options {
($inner:tt) => {
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error> {
self.$inner.write_options(msg, socket_addr, start, end)
}
}
}
/// Helper macro that provides pass-thru implementations of [`SendDesc::handler`] and
/// [`SendDesc::supports_option`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_handler {
($inner:tt, $rt:ty) => {
fn supports_option(&self, option: OptionNumber) -> bool {
self.$inner.supports_option(option)
}
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<$rt>, Error> {
self.$inner.handler(context)
}
};
|
viter,
phantom: PhantomData,
}
}
|
random_line_split
|
mod.rs
|
`send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` instances are easily constructed using *combinators*.
//!
//! ## Example
//!
//! Here we create a `SendDesc` instance that just sends a GET request and waits for a response:
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # use async_coap::null::NullLocalEndpoint;
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! #
//! let mut remote_endpoint = local_endpoint
//! .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! .expect("Remote endpoint lookup failed");
//!
//! let future = remote_endpoint.send(CoapRequest::get());
//!
//! assert_eq!(future.await, Ok(()));
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! That `SendDesc` was perhaps a little *too* simple: it doesn't even interpret the results,
//! returning `Ok(())` for any message responding with a `2.05 Content` message!
//!
//! By using the combinator `.emit_successful_response()`, we can have our `SendDesc` return
//! an owned copy of the message it received ([`OwnedImmutableMessage`](crate::message::OwnedImmutableMessage)):
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! # use async_coap::message::OwnedImmutableMessage;
//! # let mut remote_endpoint = local_endpoint
//! # .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! # .expect("Remote endpoint lookup failed");
//! #
//! #
//! let send_desc = CoapRequest::get().emit_successful_response();
//!
//! let future = remote_endpoint.send(send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! What if we wanted the response in JSON? What if it was really large and we
//! knew we would need to do a block2 transfer? We can do that easily:
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response();
//!
//! // Here we are specifying that we want to send the request to a specific
//! // path on the remote endpoint, `/large` in this case.
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! But if this is a large amount of data, we won't get any indication about the transfer
//! until it is done. What if we wanted to add some printouts about the status?
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response()
//! .inspect(|context| {
//! let addr = context.remote_address();
//! let msg = context.message();
//!
//! // Print out each individual block message received.
//! println!("Got {:?} from {}", msg, addr);
//! });
//!
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! There are [many more combinators][SendDescExt] for doing all sorts of things, such as
//! adding additional options and [block2 message aggregation](SendDescUnicast::block2).
use super::*;
mod request;
pub use request::*;
mod observe;
pub use observe::*;
mod unicast_block2;
pub use unicast_block2::*;
mod handler;
pub use handler::*;
mod inspect;
pub use inspect::*;
mod payload;
pub use payload::*;
mod ping;
pub use ping::Ping;
mod add_option;
pub use add_option::*;
mod nonconfirmable;
pub use nonconfirmable::*;
mod multicast;
pub use multicast::*;
mod emit;
pub use emit::*;
mod include_socket_addr;
pub use include_socket_addr::*;
mod uri_host_path;
pub use uri_host_path::UriHostPath;
use std::iter::{once, Once};
use std::marker::PhantomData;
use std::ops::Bound;
use std::time::Duration;
/// # Send Descriptor Trait
///
/// Types implementing this trait can be passed to the `send*` methods of [`LocalEndpoint`]
/// and [`RemoteEndpoint`], and can define almost every aspect of how a message transaction
/// is handled.
///
/// See the [module level documentation](index.html) for more information on typical usage
/// patterns.
///
/// ## Internals
///
/// There are several methods in this trait, but three of them are critical:
///
/// * [`write_options`](SendDesc::write_options)\: Defines which options are going to be
/// included in the outbound message.
/// * [`write_payload`](SendDesc::write_payload)\: Defines the contents of the payload for the
/// outbound message.
/// * [`handler`](SendDesc::handler)\: Handles inbound reply messages, as well as error conditions.
///
pub trait SendDesc<IC, R = (), TP = StandardCoapConstants>: Send
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// **Experimental**: Gets custom transmission parameters.
fn trans_params(&self) -> Option<TP> {
None
}
/// **Experimental**: Used for determining if the given option seen in the reply message
/// is supported or not.
///
/// Response messages with any options that cause this
/// method to return false will be rejected.
///
fn supports_option(&self, option: OptionNumber) -> bool {
!option.is_critical()
}
/// Calculates the duration of the delay to wait before sending the next retransmission.
///
/// If `None` is returned, then no further retransmissions will be attempted.
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<Duration> {
if retransmits_sent > TP::COAP_MAX_RETRANSMIT {
return None;
}
let ret = (TP::COAP_ACK_TIMEOUT.as_millis() as u64) << retransmits_sent as u64;
const JDIV: u64 = 512u64;
let rmod: u64 = (JDIV as f32 * (TP::COAP_ACK_RANDOM_FACTOR - 1.0)) as u64;
let jmul = JDIV + rand::random::<u64>() % rmod;
Some(Duration::from_millis(ret * jmul / JDIV))
}
/// The delay to wait between when we have received a successful response and when
/// we should send out another request.
///
/// The new request will have a new msg_id, but
/// the same token. The retransmission counter will be reset to zero.
///
/// This mechanism is currently used exclusively for CoAP observing.
///
/// The default return value is `None`, indicating that there are to be no message
/// restarts.
fn delay_to_restart(&self) -> Option<Duration> {
None
}
/// The maximum time to wait for an asynchronous response after having received an ACK.
fn max_rtt(&self) -> Duration {
TP::COAP_MAX_RTT
}
/// the maximum time from the first transmission of a Confirmable message to the time when
/// the sender gives up on receiving an acknowledgement or reset.
fn transmit_wait_duration(&self) -> Duration {
TP::COAP_MAX_TRANSMIT_WAIT
}
/// Defines which options are going to be included in the outbound message.
///
/// Writes all options in the given range to `msg`.
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error>;
/// Generates the outbound message by making calls into `msg`.
fn write_payload(
&self,
msg: &mut dyn MessageWrite,
socket_addr: &IC::SocketAddr,
) -> Result<(), Error>;
/// Handles the response to the outbound message.
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<R>, Error>;
}
/// Marker trait for identifying that this `SendDesc` is for *unicast* requests.
/// Also contains unicast-specific combinators, such as [`block2()`][SendDescUnicast::block2].
pub trait SendDescUnicast {
/// Returns a send descriptor that will perform Block2 processing.
///
/// Note that just adding this to your send descriptor chain alone is unlikely to do what
/// you want. You've got three options:
///
/// * Add a call to [`emit_successful_collected_response`][UnicastBlock2::emit_successful_collected_response]
/// immediately after the call to this method. This will cause the message to be reconstructed from the blocks
/// and returned as a value from the future from `send`. You can optionally add an
/// [`inspect`][SendDescExt::inspect] combinator to get some feedback as the message is being
/// reconstructed from all of the individual block messages.
/// * Add a call to [`emit_successful_response`][SendDescExt::emit_successful_response] along
/// with using `send_to_stream` instead of `send`. This will give you a `Stream` that will
/// contain all of the individual block messages in the stream.
/// * [Add your own handler][SendDescExt::use_handler] to do whatever you need to do, returning
/// `ResponseStatus::SendNext` until all of the blocks have been received. This is
/// useful if you want to avoid memory allocation.
///
/// There may be other valid combinations of combinators, depending on what you are trying
/// to do.
fn block2<IC, R, TP>(self, block2: Option<BlockInfo>) -> UnicastBlock2<Self, IC>
where
IC: InboundContext,
R: Send,
TP: TransParams,
Self: SendDesc<IC, R, TP> + Sized,
{
UnicastBlock2::new(self, block2)
}
}
/// Marker trait for identifying that this `SendDesc` is for *multicast* requests.
/// Also contains multicast-specific extensions.
pub trait SendDescMulticast {}
/// Combinator extension trait for Send Descriptors.
pub trait SendDescExt<IC, R, TP>: SendDesc<IC, R, TP> + Sized
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// Adds zero or more instances of the option `key`, using values coming from `viter`.
///
/// This method allows you to conditionally add options to a send descriptor. For example,
/// you could convert an `Option` to an iterator (using `into_iterator()`) and pass it to
/// this method: if the `Option` is `None` then no coap option will be added.
fn add_option_iter<K, I>(self, key: OptionKey<K>, viter: I) -> AddOption<Self, K, I, IC>
where
I: IntoIterator<Item = K> + Send + Clone,
K: Send + Clone,
{
AddOption {
inner: self,
key,
viter,
phantom: PhantomData,
}
}
/// Adds one instance of the option `key` with a value of `value`.
fn add_option<K>(self, key: OptionKey<K>, value: K) -> AddOption<Self, K, Once<K>, IC>
where
K: Send + Clone,
{
self.add_option_iter(key, once(value))
}
/// Adds an Accept option with the given `ContentFormat`.
fn accept(
self,
accept: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC> {
self.add_option(option::ACCEPT, accept)
}
/// Adds an Content-Format option with the given `ContentFormat`.
fn content_format(
self,
content_format: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC>
|
/// Adds a handler function to be called when a response message has been received (or when
/// an error has occurred).
fn use_handler<F, FR>(self, handler: F) -> Handler<Self, F>
where
F: FnMut(
Result<&dyn InboundContext<SocketAddr = IC::SocketAddr>, Error>,
) -> Result<ResponseStatus<FR>, Error>
+ Send,
FR: Send,
{
Handler {
inner: self,
handler,
}
}
/// Updates the send descriptor chain to emit any received message as a result, even
/// if that message has a message code that indicates an error.
fn emit_any_response(self) -> EmitAnyResponse<Self> {
EmitAnyResponse::new(self)
}
/// Updates the send descriptor chain to emit received message as a result, but only
/// if that message has a message code that indicates success.
fn emit_successful_response(self) -> EmitSuccessfulResponse<Self> {
EmitSuccessfulResponse::new(self)
}
/// Updates the send descriptor chain to emit only the message code of the received
/// response.
fn emit_msg_code(self) -> EmitMsgCode<Self> {
EmitMsgCode::new(self)
}
/// Updates the send descriptor chain to also emit the SocketAddr of the sender
/// of the response, resulting in tuple return type.
///
/// This is useful for handling responses to a multicast request.
fn include_socket_addr(self) -> IncludeSocketAddr<Self> {
IncludeSocketAddr::new(self)
}
/// Adds an inspection closure that will be called for each received response message.
///
/// The inspector closure will not be called if no responses are received, and it cannot
/// change the behavior of the send descriptor chain. If you need either of those
/// behaviors, see [`SendDescExt::use_handler`].
fn inspect<F>(self, inspect: F) -> Inspect<Self, F>
where
F: FnMut(&dyn InboundContext<SocketAddr = IC::SocketAddr>) + Send,
{
Inspect {
inner: self,
inspect,
}
}
/// Adds a closure that writes to the payload of the outbound message.
fn payload_writer<F>(self, writer: F) -> PayloadWriter<Self, F>
where
F: Fn(&mut dyn MessageWrite) -> Result<(), Error> + Send,
{
PayloadWriter {
inner: self,
writer,
}
}
/// Allows you to specify the URI_HOST, URI_PATH, and URI_QUERY option values
/// in a more convenient way than using `add_option_iter` manually.
fn uri_host_path<T: Into<RelRefBuf>>(
self,
host: Option<String>,
uri_path: T,
) -> UriHostPath<Self, IC> {
UriHostPath {
inner: self,
host,
path_and_query: uri_path.into(),
phantom: PhantomData,
}
}
}
/// Blanket implementation of `SendDescExt` for all types implementing `SendDesc`.
impl<T, IC, R, TP> SendDescExt<IC, R, TP> for T
where
T: SendDesc<IC, R, TP>,
IC: InboundContext,
R: Send,
TP: TransParams,
{
}
/// Helper macro that assists with writing correct implementations of [`SendDesc::write_options`].
///
/// ## Example
///
/// ```
/// # use async_coap::uri::RelRefBuf;
/// # use std::marker::PhantomData;
/// # use async_coap::send_desc::SendDesc;
/// # use async_coap::prelude::*;
/// # use async_coap::write_options;
/// # use async_coap::{InboundContext, Error, message::MessageWrite};
/// # use std::ops::Bound;
/// # pub struct WriteOptionsExample<IC>(PhantomData<IC>);
/// # impl<IC: InboundContext> SendDesc<IC, ()> for WriteOptionsExample<IC> {
/// #
/// fn write_options(
/// &self,
/// msg: &mut dyn OptionInsert,
/// socket_addr: &IC::SocketAddr,
/// start: Bound<OptionNumber>,
/// end: Bound<OptionNumber>,
/// ) -> Result<(), Error> {
/// write_options!((msg, socket_addr, start, end) {
/// // Note that the options **MUST** be listed **in numerical order**,
/// // otherwise the behavior will be undefined!
/// URI_HOST => Some("example.com").into_iter(),
/// URI_PORT => Some(1234).into_iter(),
/// URI_PATH => vec!["a","b","c"].into_iter(),
/// })
/// }
/// #
/// # fn write_payload(&self,msg: &mut dyn MessageWrite, socket_addr: &IC::SocketAddr) -> Result<(), Error> {
/// # Ok(())
/// # }
/// # fn handler(&mut self,context: Result<&IC, Error>) -> Result<ResponseStatus<()>, Error> {
/// # context.map(|_| ResponseStatus::Done(()))
/// # }
/// # }
/// ```
#[macro_export]
macro_rules! write_options {
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr, $inner:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let inner = &$inner;
let msg = $msg;
let socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr, inner); )*
inner.write_options(msg, socket_addr, start, end)
}};
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let msg = $msg;
let _socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr); )*
let _ = start;
Ok(())
}};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident, $inner:expr) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end,$inner){$($key=>$viter),*})
};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end){$($key=>$viter),*})
};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident, $inner:expr) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
$inner.write_options($msg, $socket_addr, $start, Bound::Included(key.0))?;
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
}
/// Helper macro that provides pass-thru implementations of the timing-related methods
/// of a [`SendDesc`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_timing {
($inner:tt) => {
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<::core::time::Duration> {
self.$inner.delay_to_retransmit(retransmits_sent)
}
fn delay_to_restart(&self) -> Option<::core::time::Duration> {
self.$inner.delay_to_restart()
}
fn max_rtt(&self) -> ::core::time::Duration {
self.$inner.max_rtt()
}
fn transmit_wait_duration(&self) -> ::core::time::Duration {
self.$inner.transmit_wait_duration()
}
}
}
/// Helper macro that provides pass-thru implementation of [`SendDesc::write_options`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_options {
($inner:tt) => {
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error> {
self.$inner.write_options(msg, socket_addr, start, end)
}
}
}
/// Helper macro that provides pass-thru implementations of [`SendDesc::handler`] and
/// [`SendDesc::supports_option`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_handler {
($inner:tt, $rt:ty) => {
fn supports_option(&self, option: OptionNumber) -> bool {
self.$inner.supports_option(option)
}
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<$rt>, Error> {
self.$inner.handler(context)
}
};
|
{
self.add_option(option::CONTENT_FORMAT, content_format)
}
|
identifier_body
|
mod.rs
|
`send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` instances are easily constructed using *combinators*.
//!
//! ## Example
//!
//! Here we create a `SendDesc` instance that just sends a GET request and waits for a response:
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # use async_coap::null::NullLocalEndpoint;
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! #
//! let mut remote_endpoint = local_endpoint
//! .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! .expect("Remote endpoint lookup failed");
//!
//! let future = remote_endpoint.send(CoapRequest::get());
//!
//! assert_eq!(future.await, Ok(()));
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! That `SendDesc` was perhaps a little *too* simple: it doesn't even interpret the results,
//! returning `Ok(())` for any message responding with a `2.05 Content` message!
//!
//! By using the combinator `.emit_successful_response()`, we can have our `SendDesc` return
//! an owned copy of the message it received ([`OwnedImmutableMessage`](crate::message::OwnedImmutableMessage)):
//!
//! ```
//! # use std::sync::Arc;
//! # use futures::{prelude::*,executor::LocalPool,task::LocalSpawnExt};
//! # use async_coap::prelude::*;
//! # use async_coap::datagram::{DatagramLocalEndpoint, AllowStdUdpSocket, LoopbackSocket};
//! # let socket = AllowStdUdpSocket::bind("[::]:0").expect("UDP bind failed");
//! # let local_endpoint = Arc::new(DatagramLocalEndpoint::new(socket));
//! # let mut pool = LocalPool::new();
//! # pool.spawner().spawn_local(local_endpoint.clone().receive_loop_arc(null_receiver!()).map(|_|unreachable!()));
//! # let future = async move {
//! # use async_coap::message::OwnedImmutableMessage;
//! # let mut remote_endpoint = local_endpoint
//! # .remote_endpoint_from_uri(uri!("coap://coap.me:5683/test"))
//! # .expect("Remote endpoint lookup failed");
//! #
//! #
//! let send_desc = CoapRequest::get().emit_successful_response();
//!
//! let future = remote_endpoint.send(send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! #
//! #
//! # };
//! # pool.run_until(future);
//! ```
//!
//! What if we wanted the response in JSON? What if it was really large and we
//! knew we would need to do a block2 transfer? We can do that easily:
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response();
//!
//! // Here we are specifying that we want to send the request to a specific
//! // path on the remote endpoint, `/large` in this case.
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! But if this is a large amount of data, we won't get any indication about the transfer
//! until it is done. What if we wanted to add some printouts about the status?
//!
//! ```ignore
//! let send_desc = CoapRequest::get()
//! .accept(ContentFormat::APPLICATION_JSON)
//! .block2(None)
//! .emit_successful_collected_response()
//! .inspect(|context| {
//! let addr = context.remote_address();
//! let msg = context.message();
//!
//! // Print out each individual block message received.
//! println!("Got {:?} from {}", msg, addr);
//! });
//!
//! let future = remote_endpoint.send_to(rel_ref!("/large"), send_desc);
//!
//! let message = future.await.expect("Request failed");
//!
//! println!("Got reply: {:?}", message);
//! ```
//!
//! There are [many more combinators][SendDescExt] for doing all sorts of things, such as
//! adding additional options and [block2 message aggregation](SendDescUnicast::block2).
use super::*;
mod request;
pub use request::*;
mod observe;
pub use observe::*;
mod unicast_block2;
pub use unicast_block2::*;
mod handler;
pub use handler::*;
mod inspect;
pub use inspect::*;
mod payload;
pub use payload::*;
mod ping;
pub use ping::Ping;
mod add_option;
pub use add_option::*;
mod nonconfirmable;
pub use nonconfirmable::*;
mod multicast;
pub use multicast::*;
mod emit;
pub use emit::*;
mod include_socket_addr;
pub use include_socket_addr::*;
mod uri_host_path;
pub use uri_host_path::UriHostPath;
use std::iter::{once, Once};
use std::marker::PhantomData;
use std::ops::Bound;
use std::time::Duration;
/// # Send Descriptor Trait
///
/// Types implementing this trait can be passed to the `send*` methods of [`LocalEndpoint`]
/// and [`RemoteEndpoint`], and can define almost every aspect of how a message transaction
/// is handled.
///
/// See the [module level documentation](index.html) for more information on typical usage
/// patterns.
///
/// ## Internals
///
/// There are several methods in this trait, but three of them are critical:
///
/// * [`write_options`](SendDesc::write_options)\: Defines which options are going to be
/// included in the outbound message.
/// * [`write_payload`](SendDesc::write_payload)\: Defines the contents of the payload for the
/// outbound message.
/// * [`handler`](SendDesc::handler)\: Handles inbound reply messages, as well as error conditions.
///
pub trait SendDesc<IC, R = (), TP = StandardCoapConstants>: Send
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// **Experimental**: Gets custom transmission parameters.
fn trans_params(&self) -> Option<TP> {
None
}
/// **Experimental**: Used for determining if the given option seen in the reply message
/// is supported or not.
///
/// Response messages with any options that cause this
/// method to return false will be rejected.
///
fn supports_option(&self, option: OptionNumber) -> bool {
!option.is_critical()
}
/// Calculates the duration of the delay to wait before sending the next retransmission.
///
/// If `None` is returned, then no further retransmissions will be attempted.
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<Duration> {
if retransmits_sent > TP::COAP_MAX_RETRANSMIT {
return None;
}
let ret = (TP::COAP_ACK_TIMEOUT.as_millis() as u64) << retransmits_sent as u64;
const JDIV: u64 = 512u64;
let rmod: u64 = (JDIV as f32 * (TP::COAP_ACK_RANDOM_FACTOR - 1.0)) as u64;
let jmul = JDIV + rand::random::<u64>() % rmod;
Some(Duration::from_millis(ret * jmul / JDIV))
}
/// The delay to wait between when we have received a successful response and when
/// we should send out another request.
///
/// The new request will have a new msg_id, but
/// the same token. The retransmission counter will be reset to zero.
///
/// This mechanism is currently used exclusively for CoAP observing.
///
/// The default return value is `None`, indicating that there are to be no message
/// restarts.
fn delay_to_restart(&self) -> Option<Duration> {
None
}
/// The maximum time to wait for an asynchronous response after having received an ACK.
fn max_rtt(&self) -> Duration {
TP::COAP_MAX_RTT
}
/// the maximum time from the first transmission of a Confirmable message to the time when
/// the sender gives up on receiving an acknowledgement or reset.
fn transmit_wait_duration(&self) -> Duration {
TP::COAP_MAX_TRANSMIT_WAIT
}
/// Defines which options are going to be included in the outbound message.
///
/// Writes all options in the given range to `msg`.
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error>;
/// Generates the outbound message by making calls into `msg`.
fn write_payload(
&self,
msg: &mut dyn MessageWrite,
socket_addr: &IC::SocketAddr,
) -> Result<(), Error>;
/// Handles the response to the outbound message.
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<R>, Error>;
}
/// Marker trait for identifying that this `SendDesc` is for *unicast* requests.
/// Also contains unicast-specific combinators, such as [`block2()`][SendDescUnicast::block2].
pub trait SendDescUnicast {
/// Returns a send descriptor that will perform Block2 processing.
///
/// Note that just adding this to your send descriptor chain alone is unlikely to do what
/// you want. You've got three options:
///
/// * Add a call to [`emit_successful_collected_response`][UnicastBlock2::emit_successful_collected_response]
/// immediately after the call to this method. This will cause the message to be reconstructed from the blocks
/// and returned as a value from the future from `send`. You can optionally add an
/// [`inspect`][SendDescExt::inspect] combinator to get some feedback as the message is being
/// reconstructed from all of the individual block messages.
/// * Add a call to [`emit_successful_response`][SendDescExt::emit_successful_response] along
/// with using `send_to_stream` instead of `send`. This will give you a `Stream` that will
/// contain all of the individual block messages in the stream.
/// * [Add your own handler][SendDescExt::use_handler] to do whatever you need to do, returning
/// `ResponseStatus::SendNext` until all of the blocks have been received. This is
/// useful if you want to avoid memory allocation.
///
/// There may be other valid combinations of combinators, depending on what you are trying
/// to do.
fn block2<IC, R, TP>(self, block2: Option<BlockInfo>) -> UnicastBlock2<Self, IC>
where
IC: InboundContext,
R: Send,
TP: TransParams,
Self: SendDesc<IC, R, TP> + Sized,
{
UnicastBlock2::new(self, block2)
}
}
/// Marker trait for identifying that this `SendDesc` is for *multicast* requests.
/// Also contains multicast-specific extensions.
pub trait SendDescMulticast {}
/// Combinator extension trait for Send Descriptors.
pub trait SendDescExt<IC, R, TP>: SendDesc<IC, R, TP> + Sized
where
IC: InboundContext,
R: Send,
TP: TransParams,
{
/// Adds zero or more instances of the option `key`, using values coming from `viter`.
///
/// This method allows you to conditionally add options to a send descriptor. For example,
/// you could convert an `Option` to an iterator (using `into_iterator()`) and pass it to
/// this method: if the `Option` is `None` then no coap option will be added.
fn add_option_iter<K, I>(self, key: OptionKey<K>, viter: I) -> AddOption<Self, K, I, IC>
where
I: IntoIterator<Item = K> + Send + Clone,
K: Send + Clone,
{
AddOption {
inner: self,
key,
viter,
phantom: PhantomData,
}
}
/// Adds one instance of the option `key` with a value of `value`.
fn add_option<K>(self, key: OptionKey<K>, value: K) -> AddOption<Self, K, Once<K>, IC>
where
K: Send + Clone,
{
self.add_option_iter(key, once(value))
}
/// Adds an Accept option with the given `ContentFormat`.
fn accept(
self,
accept: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC> {
self.add_option(option::ACCEPT, accept)
}
/// Adds an Content-Format option with the given `ContentFormat`.
fn content_format(
self,
content_format: ContentFormat,
) -> AddOption<Self, ContentFormat, Once<ContentFormat>, IC> {
self.add_option(option::CONTENT_FORMAT, content_format)
}
/// Adds a handler function to be called when a response message has been received (or when
/// an error has occurred).
fn use_handler<F, FR>(self, handler: F) -> Handler<Self, F>
where
F: FnMut(
Result<&dyn InboundContext<SocketAddr = IC::SocketAddr>, Error>,
) -> Result<ResponseStatus<FR>, Error>
+ Send,
FR: Send,
{
Handler {
inner: self,
handler,
}
}
/// Updates the send descriptor chain to emit any received message as a result, even
/// if that message has a message code that indicates an error.
fn emit_any_response(self) -> EmitAnyResponse<Self> {
EmitAnyResponse::new(self)
}
/// Updates the send descriptor chain to emit received message as a result, but only
/// if that message has a message code that indicates success.
fn emit_successful_response(self) -> EmitSuccessfulResponse<Self> {
EmitSuccessfulResponse::new(self)
}
/// Updates the send descriptor chain to emit only the message code of the received
/// response.
fn emit_msg_code(self) -> EmitMsgCode<Self> {
EmitMsgCode::new(self)
}
/// Updates the send descriptor chain to also emit the SocketAddr of the sender
/// of the response, resulting in tuple return type.
///
/// This is useful for handling responses to a multicast request.
fn
|
(self) -> IncludeSocketAddr<Self> {
IncludeSocketAddr::new(self)
}
/// Adds an inspection closure that will be called for each received response message.
///
/// The inspector closure will not be called if no responses are received, and it cannot
/// change the behavior of the send descriptor chain. If you need either of those
/// behaviors, see [`SendDescExt::use_handler`].
fn inspect<F>(self, inspect: F) -> Inspect<Self, F>
where
F: FnMut(&dyn InboundContext<SocketAddr = IC::SocketAddr>) + Send,
{
Inspect {
inner: self,
inspect,
}
}
/// Adds a closure that writes to the payload of the outbound message.
fn payload_writer<F>(self, writer: F) -> PayloadWriter<Self, F>
where
F: Fn(&mut dyn MessageWrite) -> Result<(), Error> + Send,
{
PayloadWriter {
inner: self,
writer,
}
}
/// Allows you to specify the URI_HOST, URI_PATH, and URI_QUERY option values
/// in a more convenient way than using `add_option_iter` manually.
fn uri_host_path<T: Into<RelRefBuf>>(
self,
host: Option<String>,
uri_path: T,
) -> UriHostPath<Self, IC> {
UriHostPath {
inner: self,
host,
path_and_query: uri_path.into(),
phantom: PhantomData,
}
}
}
/// Blanket implementation of `SendDescExt` for all types implementing `SendDesc`.
impl<T, IC, R, TP> SendDescExt<IC, R, TP> for T
where
T: SendDesc<IC, R, TP>,
IC: InboundContext,
R: Send,
TP: TransParams,
{
}
/// Helper macro that assists with writing correct implementations of [`SendDesc::write_options`].
///
/// ## Example
///
/// ```
/// # use async_coap::uri::RelRefBuf;
/// # use std::marker::PhantomData;
/// # use async_coap::send_desc::SendDesc;
/// # use async_coap::prelude::*;
/// # use async_coap::write_options;
/// # use async_coap::{InboundContext, Error, message::MessageWrite};
/// # use std::ops::Bound;
/// # pub struct WriteOptionsExample<IC>(PhantomData<IC>);
/// # impl<IC: InboundContext> SendDesc<IC, ()> for WriteOptionsExample<IC> {
/// #
/// fn write_options(
/// &self,
/// msg: &mut dyn OptionInsert,
/// socket_addr: &IC::SocketAddr,
/// start: Bound<OptionNumber>,
/// end: Bound<OptionNumber>,
/// ) -> Result<(), Error> {
/// write_options!((msg, socket_addr, start, end) {
/// // Note that the options **MUST** be listed **in numerical order**,
/// // otherwise the behavior will be undefined!
/// URI_HOST => Some("example.com").into_iter(),
/// URI_PORT => Some(1234).into_iter(),
/// URI_PATH => vec!["a","b","c"].into_iter(),
/// })
/// }
/// #
/// # fn write_payload(&self,msg: &mut dyn MessageWrite, socket_addr: &IC::SocketAddr) -> Result<(), Error> {
/// # Ok(())
/// # }
/// # fn handler(&mut self,context: Result<&IC, Error>) -> Result<ResponseStatus<()>, Error> {
/// # context.map(|_| ResponseStatus::Done(()))
/// # }
/// # }
/// ```
#[macro_export]
macro_rules! write_options {
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr, $inner:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let inner = &$inner;
let msg = $msg;
let socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr, inner); )*
inner.write_options(msg, socket_addr, start, end)
}};
(($msg:expr, $socket_addr:expr, $start:expr, $end:expr) { $($key:expr => $viter:expr),* }) => {{
let mut start = $start;
let end = $end;
let msg = $msg;
let _socket_addr = $socket_addr;
#[allow(unused)]
use $crate::option::*;
#[allow(unused)]
use std::iter::once;
$( write_options!(_internal $key, $viter, start, end, msg, socket_addr); )*
let _ = start;
Ok(())
}};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident, $inner:expr) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end,$inner){$($key=>$viter),*})
};
(($msg:ident, $socket_addr:ident, $start:ident, $end:ident) { $($key:expr => $viter:expr),*,}) => {
write_options!(($msg,$socket_addr,$start,$end){$($key=>$viter),*})
};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident, $inner:expr) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
$inner.write_options($msg, $socket_addr, $start, Bound::Included(key.0))?;
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
( _internal $key:expr, $viter:expr, $start:ident, $end:ident, $msg:ident, $socket_addr:ident) => {{
let key = $key;
let mut value_iter = $viter.into_iter().peekable();
if value_iter.peek().is_some()
&& match $start {
Bound::Included(b) => b <= key.0,
Bound::Excluded(b) => b < key.0,
Bound::Unbounded => true,
}
{
if match $end {
Bound::Included(b) => key.0 <= b,
Bound::Excluded(b) => key.0 < b,
Bound::Unbounded => true,
} {
for value in value_iter {
$msg.insert_option(key, value)?;
}
$start = Bound::Excluded(key.0)
}
}
}};
}
/// Helper macro that provides pass-thru implementations of the timing-related methods
/// of a [`SendDesc`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_timing {
($inner:tt) => {
fn delay_to_retransmit(&self, retransmits_sent: u32) -> Option<::core::time::Duration> {
self.$inner.delay_to_retransmit(retransmits_sent)
}
fn delay_to_restart(&self) -> Option<::core::time::Duration> {
self.$inner.delay_to_restart()
}
fn max_rtt(&self) -> ::core::time::Duration {
self.$inner.max_rtt()
}
fn transmit_wait_duration(&self) -> ::core::time::Duration {
self.$inner.transmit_wait_duration()
}
}
}
/// Helper macro that provides pass-thru implementation of [`SendDesc::write_options`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_options {
($inner:tt) => {
fn write_options(
&self,
msg: &mut dyn OptionInsert,
socket_addr: &IC::SocketAddr,
start: Bound<OptionNumber>,
end: Bound<OptionNumber>,
) -> Result<(), Error> {
self.$inner.write_options(msg, socket_addr, start, end)
}
}
}
/// Helper macro that provides pass-thru implementations of [`SendDesc::handler`] and
/// [`SendDesc::supports_option`].
///
/// This macro takes a single argument: the name of the member variable to pass along
/// the call to.
#[doc(hidden)]
#[macro_export]
macro_rules! send_desc_passthru_handler {
($inner:tt, $rt:ty) => {
fn supports_option(&self, option: OptionNumber) -> bool {
self.$inner.supports_option(option)
}
fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<$rt>, Error> {
self.$inner.handler(context)
}
};
|
include_socket_addr
|
identifier_name
|
diff.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! A simple binary that computes the diff between two files.
use std::fs;
#[cfg(target_family = "unix")]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use structopt::StructOpt;
use xdiff::diff_unified;
use xdiff::CopyInfo;
use xdiff::DiffFile;
use xdiff::DiffOpts;
use xdiff::FileType;
const EXEC_BIT: u32 = 0o0000100;
#[derive(Debug, StructOpt)]
#[structopt(name = "diff", about = "A showcase binary for xdiff diff library.")]
struct Opt {
/// Input file
#[structopt(parse(from_os_str))]
file_a: PathBuf,
/// Output file, stdout if not present
#[structopt(parse(from_os_str))]
file_b: PathBuf,
/// Treat the <file-b> as a copy of the <file-a>
|
#[structopt(short, long)]
copy: bool,
/// Treat the <file-b> as a move of the <file-a>
#[structopt(short, long)]
move_: bool,
/// Do not follow symlinks - compare them instead (POSIX-only)
#[structopt(short, long)]
symlink: bool,
/// Number of lines of unified context (default: 3)
#[structopt(short = "U", long, default_value = "3")]
unified: usize,
}
fn main() -> Result<(), std::io::Error> {
let opt = Opt::from_args();
#[cfg(target_family = "unix")]
fn file_mode_and_contents(
opt: &Opt,
path: &Path,
) -> Result<(FileType, Vec<u8>), std::io::Error> {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
if opt.symlink && path.symlink_metadata()?.file_type().is_symlink() {
let dest = path.read_link()?;
let dest: &OsStr = dest.as_ref();
Ok((FileType::Symlink, dest.as_bytes().to_owned()))
} else if (path.metadata()?.permissions().mode() & EXEC_BIT) > 0 {
Ok((FileType::Executable, fs::read(path)?))
} else {
Ok((FileType::Regular, fs::read(path)?))
}
}
#[cfg(target_family = "windows")]
fn file_mode_and_contents(
_opt: &Opt,
path: &Path,
) -> Result<(FileType, Vec<u8>), std::io::Error> {
Ok((FileType::Regular, fs::read(path)?))
}
let copy_info = match (opt.copy, opt.move_) {
(true, false) => CopyInfo::Copy,
(false, true) => CopyInfo::Move,
(false, false) => CopyInfo::None,
(true, true) => panic!("file can't be marked as both copy and move"),
};
let a_path_str = opt.file_a.to_string_lossy();
let a = if opt.file_a.is_file() {
let (mode, contents) = file_mode_and_contents(&opt, &opt.file_a)?;
Some(DiffFile::new(a_path_str.as_bytes(), contents, mode))
} else {
None
};
let b_path_str = opt.file_b.to_string_lossy();
let b = if opt.file_b.is_file() {
let (mode, contents) = file_mode_and_contents(&opt, &opt.file_b)?;
Some(DiffFile::new(b_path_str.as_bytes(), contents, mode))
} else {
None
};
let diff = diff_unified(
a,
b,
DiffOpts {
context: opt.unified,
copy_info,
},
);
print!("{}", String::from_utf8_lossy(&diff));
Ok(())
}
|
random_line_split
|
|
diff.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! A simple binary that computes the diff between two files.
use std::fs;
#[cfg(target_family = "unix")]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use structopt::StructOpt;
use xdiff::diff_unified;
use xdiff::CopyInfo;
use xdiff::DiffFile;
use xdiff::DiffOpts;
use xdiff::FileType;
const EXEC_BIT: u32 = 0o0000100;
#[derive(Debug, StructOpt)]
#[structopt(name = "diff", about = "A showcase binary for xdiff diff library.")]
struct Opt {
/// Input file
#[structopt(parse(from_os_str))]
file_a: PathBuf,
/// Output file, stdout if not present
#[structopt(parse(from_os_str))]
file_b: PathBuf,
/// Treat the <file-b> as a copy of the <file-a>
#[structopt(short, long)]
copy: bool,
/// Treat the <file-b> as a move of the <file-a>
#[structopt(short, long)]
move_: bool,
/// Do not follow symlinks - compare them instead (POSIX-only)
#[structopt(short, long)]
symlink: bool,
/// Number of lines of unified context (default: 3)
#[structopt(short = "U", long, default_value = "3")]
unified: usize,
}
fn main() -> Result<(), std::io::Error> {
let opt = Opt::from_args();
#[cfg(target_family = "unix")]
fn file_mode_and_contents(
opt: &Opt,
path: &Path,
) -> Result<(FileType, Vec<u8>), std::io::Error> {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
if opt.symlink && path.symlink_metadata()?.file_type().is_symlink() {
let dest = path.read_link()?;
let dest: &OsStr = dest.as_ref();
Ok((FileType::Symlink, dest.as_bytes().to_owned()))
} else if (path.metadata()?.permissions().mode() & EXEC_BIT) > 0 {
Ok((FileType::Executable, fs::read(path)?))
} else {
Ok((FileType::Regular, fs::read(path)?))
}
}
#[cfg(target_family = "windows")]
fn file_mode_and_contents(
_opt: &Opt,
path: &Path,
) -> Result<(FileType, Vec<u8>), std::io::Error>
|
let copy_info = match (opt.copy, opt.move_) {
(true, false) => CopyInfo::Copy,
(false, true) => CopyInfo::Move,
(false, false) => CopyInfo::None,
(true, true) => panic!("file can't be marked as both copy and move"),
};
let a_path_str = opt.file_a.to_string_lossy();
let a = if opt.file_a.is_file() {
let (mode, contents) = file_mode_and_contents(&opt, &opt.file_a)?;
Some(DiffFile::new(a_path_str.as_bytes(), contents, mode))
} else {
None
};
let b_path_str = opt.file_b.to_string_lossy();
let b = if opt.file_b.is_file() {
let (mode, contents) = file_mode_and_contents(&opt, &opt.file_b)?;
Some(DiffFile::new(b_path_str.as_bytes(), contents, mode))
} else {
None
};
let diff = diff_unified(
a,
b,
DiffOpts {
context: opt.unified,
copy_info,
},
);
print!("{}", String::from_utf8_lossy(&diff));
Ok(())
}
|
{
Ok((FileType::Regular, fs::read(path)?))
}
|
identifier_body
|
diff.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! A simple binary that computes the diff between two files.
use std::fs;
#[cfg(target_family = "unix")]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use structopt::StructOpt;
use xdiff::diff_unified;
use xdiff::CopyInfo;
use xdiff::DiffFile;
use xdiff::DiffOpts;
use xdiff::FileType;
const EXEC_BIT: u32 = 0o0000100;
#[derive(Debug, StructOpt)]
#[structopt(name = "diff", about = "A showcase binary for xdiff diff library.")]
struct
|
{
/// Input file
#[structopt(parse(from_os_str))]
file_a: PathBuf,
/// Output file, stdout if not present
#[structopt(parse(from_os_str))]
file_b: PathBuf,
/// Treat the <file-b> as a copy of the <file-a>
#[structopt(short, long)]
copy: bool,
/// Treat the <file-b> as a move of the <file-a>
#[structopt(short, long)]
move_: bool,
/// Do not follow symlinks - compare them instead (POSIX-only)
#[structopt(short, long)]
symlink: bool,
/// Number of lines of unified context (default: 3)
#[structopt(short = "U", long, default_value = "3")]
unified: usize,
}
fn main() -> Result<(), std::io::Error> {
let opt = Opt::from_args();
#[cfg(target_family = "unix")]
fn file_mode_and_contents(
opt: &Opt,
path: &Path,
) -> Result<(FileType, Vec<u8>), std::io::Error> {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
if opt.symlink && path.symlink_metadata()?.file_type().is_symlink() {
let dest = path.read_link()?;
let dest: &OsStr = dest.as_ref();
Ok((FileType::Symlink, dest.as_bytes().to_owned()))
} else if (path.metadata()?.permissions().mode() & EXEC_BIT) > 0 {
Ok((FileType::Executable, fs::read(path)?))
} else {
Ok((FileType::Regular, fs::read(path)?))
}
}
#[cfg(target_family = "windows")]
fn file_mode_and_contents(
_opt: &Opt,
path: &Path,
) -> Result<(FileType, Vec<u8>), std::io::Error> {
Ok((FileType::Regular, fs::read(path)?))
}
let copy_info = match (opt.copy, opt.move_) {
(true, false) => CopyInfo::Copy,
(false, true) => CopyInfo::Move,
(false, false) => CopyInfo::None,
(true, true) => panic!("file can't be marked as both copy and move"),
};
let a_path_str = opt.file_a.to_string_lossy();
let a = if opt.file_a.is_file() {
let (mode, contents) = file_mode_and_contents(&opt, &opt.file_a)?;
Some(DiffFile::new(a_path_str.as_bytes(), contents, mode))
} else {
None
};
let b_path_str = opt.file_b.to_string_lossy();
let b = if opt.file_b.is_file() {
let (mode, contents) = file_mode_and_contents(&opt, &opt.file_b)?;
Some(DiffFile::new(b_path_str.as_bytes(), contents, mode))
} else {
None
};
let diff = diff_unified(
a,
b,
DiffOpts {
context: opt.unified,
copy_info,
},
);
print!("{}", String::from_utf8_lossy(&diff));
Ok(())
}
|
Opt
|
identifier_name
|
unused-attr.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.
#![deny(unused_attributes)]
#![allow(dead_code, unused_imports)]
#![feature(core)]
#![foo] //~ ERROR unused attribute
#[foo] //~ ERROR unused attribute
extern crate core;
#[foo] //~ ERROR unused attribute
use std::collections;
#[foo] //~ ERROR unused attribute
extern "C" {
#[foo] //~ ERROR unused attribute
fn foo();
}
#[foo] //~ ERROR unused attribute
mod foo {
#[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo)
|
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
|
{
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
}
|
identifier_body
|
unused-attr.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.
#![deny(unused_attributes)]
#![allow(dead_code, unused_imports)]
#![feature(core)]
#![foo] //~ ERROR unused attribute
#[foo] //~ ERROR unused attribute
extern crate core;
#[foo] //~ ERROR unused attribute
use std::collections;
#[foo] //~ ERROR unused attribute
extern "C" {
#[foo] //~ ERROR unused attribute
fn foo();
}
#[foo] //~ ERROR unused attribute
mod foo {
|
#[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo) {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
}
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
|
random_line_split
|
|
unused-attr.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.
#![deny(unused_attributes)]
#![allow(dead_code, unused_imports)]
#![feature(core)]
#![foo] //~ ERROR unused attribute
#[foo] //~ ERROR unused attribute
extern crate core;
#[foo] //~ ERROR unused attribute
use std::collections;
#[foo] //~ ERROR unused attribute
extern "C" {
#[foo] //~ ERROR unused attribute
fn foo();
}
#[foo] //~ ERROR unused attribute
mod foo {
#[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo) {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
}
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn
|
() {}
}
fn main() {}
|
blah2
|
identifier_name
|
move-3-unique.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
#[deriving(Clone)]
struct Triple {
x: int,
y: int,
z: int,
}
fn test(x: bool, foo: ~Triple) -> int {
let bar = foo;
let mut y: ~Triple;
if x { y = bar; } else { y = ~Triple {x: 4, y: 5, z: 6}; }
return y.y;
}
pub fn main()
|
{
let x = ~Triple{x: 1, y: 2, z: 3};
for _ in range(0u, 10000u) {
assert_eq!(test(true, x.clone()), 2);
}
assert_eq!(test(false, x), 5);
}
|
identifier_body
|
|
move-3-unique.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
#[deriving(Clone)]
struct Triple {
x: int,
y: int,
z: int,
}
fn
|
(x: bool, foo: ~Triple) -> int {
let bar = foo;
let mut y: ~Triple;
if x { y = bar; } else { y = ~Triple {x: 4, y: 5, z: 6}; }
return y.y;
}
pub fn main() {
let x = ~Triple{x: 1, y: 2, z: 3};
for _ in range(0u, 10000u) {
assert_eq!(test(true, x.clone()), 2);
}
assert_eq!(test(false, x), 5);
}
|
test
|
identifier_name
|
move-3-unique.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
#[deriving(Clone)]
struct Triple {
x: int,
y: int,
z: int,
}
fn test(x: bool, foo: ~Triple) -> int {
let bar = foo;
let mut y: ~Triple;
if x { y = bar; } else { y = ~Triple {x: 4, y: 5, z: 6}; }
return y.y;
}
pub fn main() {
let x = ~Triple{x: 1, y: 2, z: 3};
for _ in range(0u, 10000u) {
assert_eq!(test(true, x.clone()), 2);
|
}
assert_eq!(test(false, x), 5);
}
|
random_line_split
|
|
move-3-unique.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
#[deriving(Clone)]
struct Triple {
x: int,
y: int,
z: int,
}
fn test(x: bool, foo: ~Triple) -> int {
let bar = foo;
let mut y: ~Triple;
if x { y = bar; } else
|
return y.y;
}
pub fn main() {
let x = ~Triple{x: 1, y: 2, z: 3};
for _ in range(0u, 10000u) {
assert_eq!(test(true, x.clone()), 2);
}
assert_eq!(test(false, x), 5);
}
|
{ y = ~Triple {x: 4, y: 5, z: 6}; }
|
conditional_block
|
live.rs
|
/// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek_offset_usize, Scheme};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, Page, PageFlags, PhysicalAddress, TableKind, VirtualAddress};
use crate::paging::mapper::PageFlushAll;
static mut LIST: [u8; 2] = [b'0', b'\n'];
struct Handle {
path: &'static [u8],
data: Arc<RwLock<&'static mut [u8]>>,
mode: u16,
seek: usize
}
|
}
impl DiskScheme {
pub fn new() -> Option<DiskScheme> {
let mut phys = 0;
let mut size = 0;
for line in str::from_utf8(unsafe { crate::INIT_ENV }).unwrap_or("").lines() {
let mut parts = line.splitn(2, '=');
let name = parts.next().unwrap_or("");
let value = parts.next().unwrap_or("");
if name == "DISK_LIVE_ADDR" {
phys = usize::from_str_radix(value, 16).unwrap_or(0);
}
if name == "DISK_LIVE_SIZE" {
size = usize::from_str_radix(value, 16).unwrap_or(0);
}
}
if phys > 0 && size > 0 {
// Map live disk pages
let virt = phys + crate::PHYS_OFFSET;
unsafe {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let flush_all = PageFlushAll::new();
let start_page = Page::containing_address(VirtualAddress::new(virt));
let end_page = Page::containing_address(VirtualAddress::new(virt + size - 1));
for page in Page::range_inclusive(start_page, end_page) {
let frame = Frame::containing_address(PhysicalAddress::new(page.start_address().data() - crate::PHYS_OFFSET));
let flags = PageFlags::new().write(true);
let result = active_table.map_to(page, frame, flags);
flush_all.consume(result);
}
flush_all.flush();
}
Some(DiskScheme {
next_id: AtomicUsize::new(0),
list: Arc::new(RwLock::new(unsafe { &mut LIST })),
data: Arc::new(RwLock::new(unsafe {
slice::from_raw_parts_mut(virt as *mut u8, size)
})),
handles: RwLock::new(BTreeMap::new())
})
} else {
None
}
}
}
impl Scheme for DiskScheme {
fn open(&self, path: &str, _flags: usize, _uid: u32, _gid: u32) -> Result<usize> {
let path_trimmed = path.trim_matches('/');
match path_trimmed {
"" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"",
data: self.list.clone(),
mode: MODE_DIR | 0o755,
seek: 0
});
Ok(id)
},
"0" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"0",
data: self.data.clone(),
mode: MODE_FILE | 0o644,
seek: 0
});
Ok(id)
}
_ => Err(Error::new(ENOENT))
}
}
fn read(&self, id: usize, buffer: &mut [u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
buffer[i] = data[handle.seek];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn write(&self, id: usize, buffer: &[u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let mut data = handle.data.write();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
data[handle.seek] = buffer[i];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn seek(&self, id: usize, pos: isize, whence: usize) -> Result<isize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let new_offset = calc_seek_offset_usize(handle.seek, pos, whence, data.len())?;
handle.seek = new_offset as usize;
Ok(new_offset)
}
fn fcntl(&self, id: usize, _cmd: usize, _arg: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
//TODO: Copy scheme part in kernel
let mut i = 0;
let scheme_path = b"disk/live:";
while i < buf.len() && i < scheme_path.len() {
buf[i] = scheme_path[i];
i += 1;
}
let mut j = 0;
while i < buf.len() && j < handle.path.len() {
buf[i] = handle.path[j];
i += 1;
j += 1;
}
Ok(i)
}
fn fstat(&self, id: usize, stat: &mut Stat) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
stat.st_mode = handle.mode;
stat.st_uid = 0;
stat.st_gid = 0;
stat.st_size = data.len() as u64;
Ok(0)
}
fn fsync(&self, id: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn close(&self, id: usize) -> Result<usize> {
self.handles.write().remove(&id).ok_or(Error::new(EBADF)).and(Ok(0))
}
}
|
pub struct DiskScheme {
next_id: AtomicUsize,
list: Arc<RwLock<&'static mut [u8]>>,
data: Arc<RwLock<&'static mut [u8]>>,
handles: RwLock<BTreeMap<usize, Handle>>
|
random_line_split
|
live.rs
|
/// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek_offset_usize, Scheme};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, Page, PageFlags, PhysicalAddress, TableKind, VirtualAddress};
use crate::paging::mapper::PageFlushAll;
static mut LIST: [u8; 2] = [b'0', b'\n'];
struct
|
{
path: &'static [u8],
data: Arc<RwLock<&'static mut [u8]>>,
mode: u16,
seek: usize
}
pub struct DiskScheme {
next_id: AtomicUsize,
list: Arc<RwLock<&'static mut [u8]>>,
data: Arc<RwLock<&'static mut [u8]>>,
handles: RwLock<BTreeMap<usize, Handle>>
}
impl DiskScheme {
pub fn new() -> Option<DiskScheme> {
let mut phys = 0;
let mut size = 0;
for line in str::from_utf8(unsafe { crate::INIT_ENV }).unwrap_or("").lines() {
let mut parts = line.splitn(2, '=');
let name = parts.next().unwrap_or("");
let value = parts.next().unwrap_or("");
if name == "DISK_LIVE_ADDR" {
phys = usize::from_str_radix(value, 16).unwrap_or(0);
}
if name == "DISK_LIVE_SIZE" {
size = usize::from_str_radix(value, 16).unwrap_or(0);
}
}
if phys > 0 && size > 0 {
// Map live disk pages
let virt = phys + crate::PHYS_OFFSET;
unsafe {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let flush_all = PageFlushAll::new();
let start_page = Page::containing_address(VirtualAddress::new(virt));
let end_page = Page::containing_address(VirtualAddress::new(virt + size - 1));
for page in Page::range_inclusive(start_page, end_page) {
let frame = Frame::containing_address(PhysicalAddress::new(page.start_address().data() - crate::PHYS_OFFSET));
let flags = PageFlags::new().write(true);
let result = active_table.map_to(page, frame, flags);
flush_all.consume(result);
}
flush_all.flush();
}
Some(DiskScheme {
next_id: AtomicUsize::new(0),
list: Arc::new(RwLock::new(unsafe { &mut LIST })),
data: Arc::new(RwLock::new(unsafe {
slice::from_raw_parts_mut(virt as *mut u8, size)
})),
handles: RwLock::new(BTreeMap::new())
})
} else {
None
}
}
}
impl Scheme for DiskScheme {
fn open(&self, path: &str, _flags: usize, _uid: u32, _gid: u32) -> Result<usize> {
let path_trimmed = path.trim_matches('/');
match path_trimmed {
"" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"",
data: self.list.clone(),
mode: MODE_DIR | 0o755,
seek: 0
});
Ok(id)
},
"0" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"0",
data: self.data.clone(),
mode: MODE_FILE | 0o644,
seek: 0
});
Ok(id)
}
_ => Err(Error::new(ENOENT))
}
}
fn read(&self, id: usize, buffer: &mut [u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
buffer[i] = data[handle.seek];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn write(&self, id: usize, buffer: &[u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let mut data = handle.data.write();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
data[handle.seek] = buffer[i];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn seek(&self, id: usize, pos: isize, whence: usize) -> Result<isize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let new_offset = calc_seek_offset_usize(handle.seek, pos, whence, data.len())?;
handle.seek = new_offset as usize;
Ok(new_offset)
}
fn fcntl(&self, id: usize, _cmd: usize, _arg: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
//TODO: Copy scheme part in kernel
let mut i = 0;
let scheme_path = b"disk/live:";
while i < buf.len() && i < scheme_path.len() {
buf[i] = scheme_path[i];
i += 1;
}
let mut j = 0;
while i < buf.len() && j < handle.path.len() {
buf[i] = handle.path[j];
i += 1;
j += 1;
}
Ok(i)
}
fn fstat(&self, id: usize, stat: &mut Stat) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
stat.st_mode = handle.mode;
stat.st_uid = 0;
stat.st_gid = 0;
stat.st_size = data.len() as u64;
Ok(0)
}
fn fsync(&self, id: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn close(&self, id: usize) -> Result<usize> {
self.handles.write().remove(&id).ok_or(Error::new(EBADF)).and(Ok(0))
}
}
|
Handle
|
identifier_name
|
live.rs
|
/// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek_offset_usize, Scheme};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, Page, PageFlags, PhysicalAddress, TableKind, VirtualAddress};
use crate::paging::mapper::PageFlushAll;
static mut LIST: [u8; 2] = [b'0', b'\n'];
struct Handle {
path: &'static [u8],
data: Arc<RwLock<&'static mut [u8]>>,
mode: u16,
seek: usize
}
pub struct DiskScheme {
next_id: AtomicUsize,
list: Arc<RwLock<&'static mut [u8]>>,
data: Arc<RwLock<&'static mut [u8]>>,
handles: RwLock<BTreeMap<usize, Handle>>
}
impl DiskScheme {
pub fn new() -> Option<DiskScheme> {
let mut phys = 0;
let mut size = 0;
for line in str::from_utf8(unsafe { crate::INIT_ENV }).unwrap_or("").lines() {
let mut parts = line.splitn(2, '=');
let name = parts.next().unwrap_or("");
let value = parts.next().unwrap_or("");
if name == "DISK_LIVE_ADDR" {
phys = usize::from_str_radix(value, 16).unwrap_or(0);
}
if name == "DISK_LIVE_SIZE" {
size = usize::from_str_radix(value, 16).unwrap_or(0);
}
}
if phys > 0 && size > 0 {
// Map live disk pages
let virt = phys + crate::PHYS_OFFSET;
unsafe {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let flush_all = PageFlushAll::new();
let start_page = Page::containing_address(VirtualAddress::new(virt));
let end_page = Page::containing_address(VirtualAddress::new(virt + size - 1));
for page in Page::range_inclusive(start_page, end_page) {
let frame = Frame::containing_address(PhysicalAddress::new(page.start_address().data() - crate::PHYS_OFFSET));
let flags = PageFlags::new().write(true);
let result = active_table.map_to(page, frame, flags);
flush_all.consume(result);
}
flush_all.flush();
}
Some(DiskScheme {
next_id: AtomicUsize::new(0),
list: Arc::new(RwLock::new(unsafe { &mut LIST })),
data: Arc::new(RwLock::new(unsafe {
slice::from_raw_parts_mut(virt as *mut u8, size)
})),
handles: RwLock::new(BTreeMap::new())
})
} else
|
}
}
impl Scheme for DiskScheme {
fn open(&self, path: &str, _flags: usize, _uid: u32, _gid: u32) -> Result<usize> {
let path_trimmed = path.trim_matches('/');
match path_trimmed {
"" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"",
data: self.list.clone(),
mode: MODE_DIR | 0o755,
seek: 0
});
Ok(id)
},
"0" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"0",
data: self.data.clone(),
mode: MODE_FILE | 0o644,
seek: 0
});
Ok(id)
}
_ => Err(Error::new(ENOENT))
}
}
fn read(&self, id: usize, buffer: &mut [u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
buffer[i] = data[handle.seek];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn write(&self, id: usize, buffer: &[u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let mut data = handle.data.write();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
data[handle.seek] = buffer[i];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn seek(&self, id: usize, pos: isize, whence: usize) -> Result<isize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let new_offset = calc_seek_offset_usize(handle.seek, pos, whence, data.len())?;
handle.seek = new_offset as usize;
Ok(new_offset)
}
fn fcntl(&self, id: usize, _cmd: usize, _arg: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
//TODO: Copy scheme part in kernel
let mut i = 0;
let scheme_path = b"disk/live:";
while i < buf.len() && i < scheme_path.len() {
buf[i] = scheme_path[i];
i += 1;
}
let mut j = 0;
while i < buf.len() && j < handle.path.len() {
buf[i] = handle.path[j];
i += 1;
j += 1;
}
Ok(i)
}
fn fstat(&self, id: usize, stat: &mut Stat) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
stat.st_mode = handle.mode;
stat.st_uid = 0;
stat.st_gid = 0;
stat.st_size = data.len() as u64;
Ok(0)
}
fn fsync(&self, id: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn close(&self, id: usize) -> Result<usize> {
self.handles.write().remove(&id).ok_or(Error::new(EBADF)).and(Ok(0))
}
}
|
{
None
}
|
conditional_block
|
live.rs
|
/// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek_offset_usize, Scheme};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, Page, PageFlags, PhysicalAddress, TableKind, VirtualAddress};
use crate::paging::mapper::PageFlushAll;
static mut LIST: [u8; 2] = [b'0', b'\n'];
struct Handle {
path: &'static [u8],
data: Arc<RwLock<&'static mut [u8]>>,
mode: u16,
seek: usize
}
pub struct DiskScheme {
next_id: AtomicUsize,
list: Arc<RwLock<&'static mut [u8]>>,
data: Arc<RwLock<&'static mut [u8]>>,
handles: RwLock<BTreeMap<usize, Handle>>
}
impl DiskScheme {
pub fn new() -> Option<DiskScheme> {
let mut phys = 0;
let mut size = 0;
for line in str::from_utf8(unsafe { crate::INIT_ENV }).unwrap_or("").lines() {
let mut parts = line.splitn(2, '=');
let name = parts.next().unwrap_or("");
let value = parts.next().unwrap_or("");
if name == "DISK_LIVE_ADDR" {
phys = usize::from_str_radix(value, 16).unwrap_or(0);
}
if name == "DISK_LIVE_SIZE" {
size = usize::from_str_radix(value, 16).unwrap_or(0);
}
}
if phys > 0 && size > 0 {
// Map live disk pages
let virt = phys + crate::PHYS_OFFSET;
unsafe {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let flush_all = PageFlushAll::new();
let start_page = Page::containing_address(VirtualAddress::new(virt));
let end_page = Page::containing_address(VirtualAddress::new(virt + size - 1));
for page in Page::range_inclusive(start_page, end_page) {
let frame = Frame::containing_address(PhysicalAddress::new(page.start_address().data() - crate::PHYS_OFFSET));
let flags = PageFlags::new().write(true);
let result = active_table.map_to(page, frame, flags);
flush_all.consume(result);
}
flush_all.flush();
}
Some(DiskScheme {
next_id: AtomicUsize::new(0),
list: Arc::new(RwLock::new(unsafe { &mut LIST })),
data: Arc::new(RwLock::new(unsafe {
slice::from_raw_parts_mut(virt as *mut u8, size)
})),
handles: RwLock::new(BTreeMap::new())
})
} else {
None
}
}
}
impl Scheme for DiskScheme {
fn open(&self, path: &str, _flags: usize, _uid: u32, _gid: u32) -> Result<usize> {
let path_trimmed = path.trim_matches('/');
match path_trimmed {
"" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"",
data: self.list.clone(),
mode: MODE_DIR | 0o755,
seek: 0
});
Ok(id)
},
"0" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.handles.write().insert(id, Handle {
path: b"0",
data: self.data.clone(),
mode: MODE_FILE | 0o644,
seek: 0
});
Ok(id)
}
_ => Err(Error::new(ENOENT))
}
}
fn read(&self, id: usize, buffer: &mut [u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
buffer[i] = data[handle.seek];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn write(&self, id: usize, buffer: &[u8]) -> Result<usize> {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let mut data = handle.data.write();
let mut i = 0;
while i < buffer.len() && handle.seek < data.len() {
data[handle.seek] = buffer[i];
i += 1;
handle.seek += 1;
}
Ok(i)
}
fn seek(&self, id: usize, pos: isize, whence: usize) -> Result<isize>
|
fn fcntl(&self, id: usize, _cmd: usize, _arg: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
//TODO: Copy scheme part in kernel
let mut i = 0;
let scheme_path = b"disk/live:";
while i < buf.len() && i < scheme_path.len() {
buf[i] = scheme_path[i];
i += 1;
}
let mut j = 0;
while i < buf.len() && j < handle.path.len() {
buf[i] = handle.path[j];
i += 1;
j += 1;
}
Ok(i)
}
fn fstat(&self, id: usize, stat: &mut Stat) -> Result<usize> {
let handles = self.handles.read();
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
stat.st_mode = handle.mode;
stat.st_uid = 0;
stat.st_gid = 0;
stat.st_size = data.len() as u64;
Ok(0)
}
fn fsync(&self, id: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn close(&self, id: usize) -> Result<usize> {
self.handles.write().remove(&id).ok_or(Error::new(EBADF)).and(Ok(0))
}
}
|
{
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let new_offset = calc_seek_offset_usize(handle.seek, pos, whence, data.len())?;
handle.seek = new_offset as usize;
Ok(new_offset)
}
|
identifier_body
|
windowproxy.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{CacheableWrapper, WrapperCache, BindingObject};
use script_task::page_from_context;
use js::jsapi::{JSContext, JSObject};
pub struct WindowProxy {
wrapper: WrapperCache
}
impl WindowProxy {
pub fn new() -> @mut WindowProxy {
@mut WindowProxy {
wrapper: WrapperCache::new()
}
}
pub fn init_wrapper(@mut self, cx: *JSContext, scope: *JSObject) {
self.wrap_object_shared(cx, scope);
}
}
impl BindingObject for WindowProxy {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
let page = page_from_context(cx);
unsafe {
Some((*page).frame.get_ref().window as @mut CacheableWrapper)
}
}
}
impl CacheableWrapper for WindowProxy {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
return self.get_wrappercache()
}
fn
|
(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!("not yet implemented")
}
}
|
wrap_object_shared
|
identifier_name
|
windowproxy.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{CacheableWrapper, WrapperCache, BindingObject};
use script_task::page_from_context;
use js::jsapi::{JSContext, JSObject};
pub struct WindowProxy {
wrapper: WrapperCache
}
impl WindowProxy {
pub fn new() -> @mut WindowProxy {
@mut WindowProxy {
wrapper: WrapperCache::new()
}
}
pub fn init_wrapper(@mut self, cx: *JSContext, scope: *JSObject) {
self.wrap_object_shared(cx, scope);
}
}
impl BindingObject for WindowProxy {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
let page = page_from_context(cx);
unsafe {
Some((*page).frame.get_ref().window as @mut CacheableWrapper)
}
}
}
impl CacheableWrapper for WindowProxy {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
return self.get_wrappercache()
|
}
|
}
fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!("not yet implemented")
}
|
random_line_split
|
solver014.rs
|
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::long::is_even;
use euler::Solver;
// The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)
//
// Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
// It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
// Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
//
// Which starting number, under one million, produces the longest chain?
//
// NOTE: Once the chain starts the terms are allowed to go above one million.
pub struct Solver014 {
pub n: isize
}
impl Default for Solver014 {
fn default() -> Self {
Solver014 { n: 1_000_000 }
}
}
impl Solver for Solver014 {
fn solve(&self) -> isize {
// floor i is an odd number 2/3 of self.n
let (mut collatz, floor) = (collatz_memoize(self.n), self.n * 2 / 3 - (self.n * 2 / 3) % 2 - 1);
(floor..self.n).step_by(2).max_by_key(|&x| collatz.length(x)).unwrap()
}
}
// --- //
struct CollatzMemoize {
cache: Vec<isize>
}
fn collatz_memoize(size: isize) -> CollatzMemoize {
let mut cache = vec![0; size as _];
cache[1] = 1;
CollatzMemoize { cache }
}
impl CollatzMemoize {
fn length(&mut self, value: isize) -> isize {
let (v, size) = (value as usize, self.cache.len());
if v < size && self.cache[v]!= 0 {
return self.cache[v];
}
|
}
collatz
}
}
|
let collatz = if is_even(value) { 1 + self.length(value >> 1) } else { 2 + self.length((value * 3 + 1) >> 1) };
if v < size {
self.cache[v] = collatz;
|
random_line_split
|
solver014.rs
|
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::long::is_even;
use euler::Solver;
// The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)
//
// Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
// It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
// Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
//
// Which starting number, under one million, produces the longest chain?
//
// NOTE: Once the chain starts the terms are allowed to go above one million.
pub struct Solver014 {
pub n: isize
}
impl Default for Solver014 {
fn default() -> Self {
Solver014 { n: 1_000_000 }
}
}
impl Solver for Solver014 {
fn solve(&self) -> isize {
// floor i is an odd number 2/3 of self.n
let (mut collatz, floor) = (collatz_memoize(self.n), self.n * 2 / 3 - (self.n * 2 / 3) % 2 - 1);
(floor..self.n).step_by(2).max_by_key(|&x| collatz.length(x)).unwrap()
}
}
// --- //
struct CollatzMemoize {
c
|
e>
}
fn collatz_memoize(size: isize) -> CollatzMemoize {
let mut cache = vec![0; size as _];
cache[1] = 1;
CollatzMemoize { cache }
}
impl CollatzMemoize {
fn length(&mut self, value: isize) -> isize {
let (v, size) = (value as usize, self.cache.len());
if v < size && self.cache[v]!= 0 {
return self.cache[v];
}
let collatz = if is_even(value) { 1 + self.length(value >> 1) } else { 2 + self.length((value * 3 + 1) >> 1) };
if v < size {
self.cache[v] = collatz;
}
collatz
}
}
|
ache: Vec<isiz
|
identifier_name
|
solver014.rs
|
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::long::is_even;
use euler::Solver;
// The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)
//
// Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
// It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
// Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
//
// Which starting number, under one million, produces the longest chain?
//
// NOTE: Once the chain starts the terms are allowed to go above one million.
pub struct Solver014 {
pub n: isize
}
impl Default for Solver014 {
fn default() -> Self {
Solver014 { n: 1_000_000 }
}
}
impl Solver for Solver014 {
fn solve(&self) -> isize {
// floor i is an odd number 2/3 of self.n
let (mut collatz, floor) = (collatz_memoize(self.n), self.n * 2 / 3 - (self.n * 2 / 3) % 2 - 1);
(floor..self.n).step_by(2).max_by_key(|&x| collatz.length(x)).unwrap()
}
}
// --- //
struct CollatzMemoize {
cache: Vec<isize>
}
fn collatz_memoize(size: isize) -> CollatzMemoize {
let mut cache = vec![0; size as _];
cache[1] = 1;
CollatzMemoize { cache }
}
impl CollatzMemoize {
fn length(&mut self, value: isize) -> isize {
let (v, size) = (value as usize, self.cache.len());
if v < size && self.cache[v]!= 0 {
return self.cache[v];
}
let collatz = if is_even(value) { 1 + self.length(value >> 1) } else { 2 + self.length((value * 3 + 1) >> 1) };
if v < size {
self.cac
|
}
|
he[v] = collatz;
}
collatz
}
|
conditional_block
|
lib.rs
|
use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()>
|
}
}
}
}
}
None => {
println!("no cookie in headers");
}
}
session_value.and_then(|val| {
req.ext_mut().insert::<SessionVal>(val);
Some(())
});
Ok(())
}
// library function
pub fn set_cookie(
res: &mut Response,
ckey: String,
val: String,
domain: Option<String>,
path: Option<String>,
secure: Option<bool>,
max_age: Option<i64>,
) -> Result<()> {
let mut cookie = Cookie_M::new(ckey, val);
if domain.is_some() {
cookie.set_domain(domain.unwrap());
}
if path.is_some() {
cookie.set_path(path.unwrap());
}
if secure.is_some() {
cookie.set_secure(secure.unwrap());
}
if max_age.is_some() {
cookie.set_max_age(time::Duration::seconds(max_age.unwrap()))
}
res.headers_mut().set(SetCookie(vec![cookie.to_string()]));
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
}
|
{
if ckey.is_none() {
return Ok(());
}
let mut session_value: Option<String> = None;
match req.headers().get::<Cookie>() {
Some(cookie_headers) => {
//let mut cookie_jar = CookieJar::new();
for header in cookie_headers.iter() {
let raw_str = match ::std::str::from_utf8(&header.as_bytes()) {
Ok(string) => string,
Err(_) => continue,
};
for cookie_str in raw_str.split(";").map(|s| s.trim()) {
if let Ok(cookie) = Cookie_M::parse(cookie_str) {
if cookie.name() == ckey.unwrap() {
session_value = Some(cookie.value().to_owned());
break;
|
identifier_body
|
lib.rs
|
use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()> {
if ckey.is_none() {
return Ok(());
}
let mut session_value: Option<String> = None;
match req.headers().get::<Cookie>() {
Some(cookie_headers) => {
//let mut cookie_jar = CookieJar::new();
for header in cookie_headers.iter() {
let raw_str = match ::std::str::from_utf8(&header.as_bytes()) {
Ok(string) => string,
Err(_) => continue,
};
for cookie_str in raw_str.split(";").map(|s| s.trim()) {
if let Ok(cookie) = Cookie_M::parse(cookie_str) {
if cookie.name() == ckey.unwrap()
|
}
}
}
}
None => {
println!("no cookie in headers");
}
}
session_value.and_then(|val| {
req.ext_mut().insert::<SessionVal>(val);
Some(())
});
Ok(())
}
// library function
pub fn set_cookie(
res: &mut Response,
ckey: String,
val: String,
domain: Option<String>,
path: Option<String>,
secure: Option<bool>,
max_age: Option<i64>,
) -> Result<()> {
let mut cookie = Cookie_M::new(ckey, val);
if domain.is_some() {
cookie.set_domain(domain.unwrap());
}
if path.is_some() {
cookie.set_path(path.unwrap());
}
if secure.is_some() {
cookie.set_secure(secure.unwrap());
}
if max_age.is_some() {
cookie.set_max_age(time::Duration::seconds(max_age.unwrap()))
}
res.headers_mut().set(SetCookie(vec![cookie.to_string()]));
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
}
|
{
session_value = Some(cookie.value().to_owned());
break;
}
|
conditional_block
|
lib.rs
|
use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()> {
if ckey.is_none() {
return Ok(());
}
let mut session_value: Option<String> = None;
match req.headers().get::<Cookie>() {
Some(cookie_headers) => {
//let mut cookie_jar = CookieJar::new();
for header in cookie_headers.iter() {
let raw_str = match ::std::str::from_utf8(&header.as_bytes()) {
Ok(string) => string,
Err(_) => continue,
};
for cookie_str in raw_str.split(";").map(|s| s.trim()) {
if let Ok(cookie) = Cookie_M::parse(cookie_str) {
if cookie.name() == ckey.unwrap() {
session_value = Some(cookie.value().to_owned());
break;
}
}
}
}
}
None => {
println!("no cookie in headers");
}
}
session_value.and_then(|val| {
req.ext_mut().insert::<SessionVal>(val);
Some(())
});
Ok(())
}
// library function
pub fn
|
(
res: &mut Response,
ckey: String,
val: String,
domain: Option<String>,
path: Option<String>,
secure: Option<bool>,
max_age: Option<i64>,
) -> Result<()> {
let mut cookie = Cookie_M::new(ckey, val);
if domain.is_some() {
cookie.set_domain(domain.unwrap());
}
if path.is_some() {
cookie.set_path(path.unwrap());
}
if secure.is_some() {
cookie.set_secure(secure.unwrap());
}
if max_age.is_some() {
cookie.set_max_age(time::Duration::seconds(max_age.unwrap()))
}
res.headers_mut().set(SetCookie(vec![cookie.to_string()]));
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
}
|
set_cookie
|
identifier_name
|
lib.rs
|
use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()> {
if ckey.is_none() {
return Ok(());
}
let mut session_value: Option<String> = None;
match req.headers().get::<Cookie>() {
Some(cookie_headers) => {
//let mut cookie_jar = CookieJar::new();
for header in cookie_headers.iter() {
let raw_str = match ::std::str::from_utf8(&header.as_bytes()) {
Ok(string) => string,
Err(_) => continue,
};
for cookie_str in raw_str.split(";").map(|s| s.trim()) {
if let Ok(cookie) = Cookie_M::parse(cookie_str) {
if cookie.name() == ckey.unwrap() {
session_value = Some(cookie.value().to_owned());
break;
}
}
}
}
}
None => {
println!("no cookie in headers");
}
}
session_value.and_then(|val| {
req.ext_mut().insert::<SessionVal>(val);
Some(())
});
Ok(())
}
// library function
pub fn set_cookie(
res: &mut Response,
ckey: String,
val: String,
domain: Option<String>,
path: Option<String>,
secure: Option<bool>,
max_age: Option<i64>,
) -> Result<()> {
let mut cookie = Cookie_M::new(ckey, val);
if domain.is_some() {
cookie.set_domain(domain.unwrap());
}
if path.is_some() {
cookie.set_path(path.unwrap());
}
if secure.is_some() {
cookie.set_secure(secure.unwrap());
}
if max_age.is_some() {
cookie.set_max_age(time::Duration::seconds(max_age.unwrap()))
}
res.headers_mut().set(SetCookie(vec![cookie.to_string()]));
|
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
}
|
random_line_split
|
|
mode.rs
|
// When starting program, start at state "Init"
// Always allow commands "debug" and "isready"
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum
|
{
// * `uci`
// send all "id" and "option" messages
// send one "uciok" message
// go to mode "Wait"
Init,
// * `setoption`
// maybe initialize stuff
// set the option
// stay in mode Wait
// * `ucinewgame`
// reset status
// take note that GUI supports the ucinewgame command
// go to NewGame mode
// * `position`
// if GUI does not support ucinewgame, then:
// simulate `ucinewgame` command
// reprocess `position` command
// set up position for same game
// go to Ready mode
Wait,
// * `position`
// set up position for new game
// go to Ready mode
NewGame,
// * `go`
// process the arguments
// start searching
// go to mode Search
Ready,
// * `ponderhit`
// Execute the ponder move
// stay in mode Search
// * `stop`
// * OR
// * engine decides on best move
// stop searching
// send all "info" data/messages
// send one "bestmove" message
// stop search
// go to mode Wait
// * engine runs for a while
// send all "info" data/messages
Search,
// For any mode:
//
// * `debug`
// set debug as on or off
// * `isready`
// if mode is not Search, then: wait for everything to finish
// send one "readyok" message
}
impl Mode {
pub fn new() -> Mode {
Mode::Init
}
}
|
Mode
|
identifier_name
|
mode.rs
|
// When starting program, start at state "Init"
// Always allow commands "debug" and "isready"
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Mode {
// * `uci`
// send all "id" and "option" messages
// send one "uciok" message
// go to mode "Wait"
Init,
// * `setoption`
// maybe initialize stuff
// set the option
// stay in mode Wait
// * `ucinewgame`
// reset status
// take note that GUI supports the ucinewgame command
// go to NewGame mode
// * `position`
// if GUI does not support ucinewgame, then:
// simulate `ucinewgame` command
// reprocess `position` command
// set up position for same game
// go to Ready mode
Wait,
// * `position`
// set up position for new game
|
NewGame,
// * `go`
// process the arguments
// start searching
// go to mode Search
Ready,
// * `ponderhit`
// Execute the ponder move
// stay in mode Search
// * `stop`
// * OR
// * engine decides on best move
// stop searching
// send all "info" data/messages
// send one "bestmove" message
// stop search
// go to mode Wait
// * engine runs for a while
// send all "info" data/messages
Search,
// For any mode:
//
// * `debug`
// set debug as on or off
// * `isready`
// if mode is not Search, then: wait for everything to finish
// send one "readyok" message
}
impl Mode {
pub fn new() -> Mode {
Mode::Init
}
}
|
// go to Ready mode
|
random_line_split
|
mode.rs
|
// When starting program, start at state "Init"
// Always allow commands "debug" and "isready"
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Mode {
// * `uci`
// send all "id" and "option" messages
// send one "uciok" message
// go to mode "Wait"
Init,
// * `setoption`
// maybe initialize stuff
// set the option
// stay in mode Wait
// * `ucinewgame`
// reset status
// take note that GUI supports the ucinewgame command
// go to NewGame mode
// * `position`
// if GUI does not support ucinewgame, then:
// simulate `ucinewgame` command
// reprocess `position` command
// set up position for same game
// go to Ready mode
Wait,
// * `position`
// set up position for new game
// go to Ready mode
NewGame,
// * `go`
// process the arguments
// start searching
// go to mode Search
Ready,
// * `ponderhit`
// Execute the ponder move
// stay in mode Search
// * `stop`
// * OR
// * engine decides on best move
// stop searching
// send all "info" data/messages
// send one "bestmove" message
// stop search
// go to mode Wait
// * engine runs for a while
// send all "info" data/messages
Search,
// For any mode:
//
// * `debug`
// set debug as on or off
// * `isready`
// if mode is not Search, then: wait for everything to finish
// send one "readyok" message
}
impl Mode {
pub fn new() -> Mode
|
}
|
{
Mode::Init
}
|
identifier_body
|
rlperrors.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::fmt;
use std::error::Error as StdError;
use rlp::bytes::FromBytesError;
#[derive(Debug, PartialEq, Eq)]
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// Couldn't convert given bytes to an instance of required type.
FromBytesError(FromBytesError),
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else.
RlpExpectedToBeList,
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// Expected a different size list.
RlpIncorrectListLen,
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// List length number has a prefixed zero byte, invalid for numbers.
RlpListLenWithZeroPrefix,
/// Non-canonical (longer than necessary) representation used for data or list.
RlpInvalidIndirection,
/// Declared length is inconsistent with data specified after.
RlpInconsistentLengthAndData,
}
impl StdError for DecoderError {
fn description(&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<FromBytesError> for DecoderError {
fn from(err: FromBytesError) -> DecoderError {
DecoderError::FromBytesError(err)
}
}
|
fmt
|
identifier_name
|
rlperrors.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::fmt;
use std::error::Error as StdError;
use rlp::bytes::FromBytesError;
#[derive(Debug, PartialEq, Eq)]
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// Couldn't convert given bytes to an instance of required type.
FromBytesError(FromBytesError),
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
|
RlpExpectedToBeList,
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// Expected a different size list.
RlpIncorrectListLen,
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// List length number has a prefixed zero byte, invalid for numbers.
RlpListLenWithZeroPrefix,
/// Non-canonical (longer than necessary) representation used for data or list.
RlpInvalidIndirection,
/// Declared length is inconsistent with data specified after.
RlpInconsistentLengthAndData,
}
impl StdError for DecoderError {
fn description(&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<FromBytesError> for DecoderError {
fn from(err: FromBytesError) -> DecoderError {
DecoderError::FromBytesError(err)
}
}
|
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else.
|
random_line_split
|
gaussian.rs
|
extern crate rand;
use crate::distribs::distribution::*;
use crate::util::math::*;
use std::f64::consts;
#[allow(dead_code)]
pub struct Gaussian {
mu: f64,
sigma: f64,
}
impl Gaussian {
pub fn new(avg: f64, variance: f64) -> Gaussian {
Gaussian {
mu: avg,
sigma: variance.sqrt(),
}
}
}
impl Distribution<f64> for Gaussian {
//Using the Box–Muller transform (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform)
fn sample(&self) -> RandomVariable<f64> {
let u_1 = rand::random::<f64>();
let u_2 = rand::random::<f64>();
let u_1_term = (-2.0f64 * (u_1.ln())).sqrt();
let u_2_term = (2.0f64 * consts::PI * u_2).cos();
RandomVariable { value: Cell::new(self.sigma * (u_1_term * u_2_term) + self.mu) }
}
fn mu(&self) -> f64 {
self.mu
}
fn sigma(&self) -> f64 {
self.sigma
}
fn pdf(&self, x: f64) -> f64 {
let factor = (2.0f64 * self.sigma * self.sigma * consts::PI)
.sqrt()
.recip();
let exp_num = -((x - self.mu).powi(2));
let exp_denom = 2.0f64 * self.sigma * self.sigma;
factor * (exp_num / exp_denom).exp()
}
fn cd
|
self, x: f64) -> f64 {
phi((x - self.mu) / self.sigma)
}
}
|
f(&
|
identifier_name
|
gaussian.rs
|
extern crate rand;
use crate::distribs::distribution::*;
use crate::util::math::*;
use std::f64::consts;
#[allow(dead_code)]
pub struct Gaussian {
mu: f64,
sigma: f64,
}
impl Gaussian {
pub fn new(avg: f64, variance: f64) -> Gaussian {
Gaussian {
mu: avg,
sigma: variance.sqrt(),
}
}
}
impl Distribution<f64> for Gaussian {
//Using the Box–Muller transform (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform)
fn sample(&self) -> RandomVariable<f64> {
let u_1 = rand::random::<f64>();
let u_2 = rand::random::<f64>();
let u_1_term = (-2.0f64 * (u_1.ln())).sqrt();
let u_2_term = (2.0f64 * consts::PI * u_2).cos();
RandomVariable { value: Cell::new(self.sigma * (u_1_term * u_2_term) + self.mu) }
}
fn mu(&self) -> f64 {
self.mu
}
fn sigma(&self) -> f64 {
|
fn pdf(&self, x: f64) -> f64 {
let factor = (2.0f64 * self.sigma * self.sigma * consts::PI)
.sqrt()
.recip();
let exp_num = -((x - self.mu).powi(2));
let exp_denom = 2.0f64 * self.sigma * self.sigma;
factor * (exp_num / exp_denom).exp()
}
fn cdf(&self, x: f64) -> f64 {
phi((x - self.mu) / self.sigma)
}
}
|
self.sigma
}
|
identifier_body
|
gaussian.rs
|
extern crate rand;
use crate::distribs::distribution::*;
use crate::util::math::*;
use std::f64::consts;
#[allow(dead_code)]
pub struct Gaussian {
mu: f64,
|
pub fn new(avg: f64, variance: f64) -> Gaussian {
Gaussian {
mu: avg,
sigma: variance.sqrt(),
}
}
}
impl Distribution<f64> for Gaussian {
//Using the Box–Muller transform (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform)
fn sample(&self) -> RandomVariable<f64> {
let u_1 = rand::random::<f64>();
let u_2 = rand::random::<f64>();
let u_1_term = (-2.0f64 * (u_1.ln())).sqrt();
let u_2_term = (2.0f64 * consts::PI * u_2).cos();
RandomVariable { value: Cell::new(self.sigma * (u_1_term * u_2_term) + self.mu) }
}
fn mu(&self) -> f64 {
self.mu
}
fn sigma(&self) -> f64 {
self.sigma
}
fn pdf(&self, x: f64) -> f64 {
let factor = (2.0f64 * self.sigma * self.sigma * consts::PI)
.sqrt()
.recip();
let exp_num = -((x - self.mu).powi(2));
let exp_denom = 2.0f64 * self.sigma * self.sigma;
factor * (exp_num / exp_denom).exp()
}
fn cdf(&self, x: f64) -> f64 {
phi((x - self.mu) / self.sigma)
}
}
|
sigma: f64,
}
impl Gaussian {
|
random_line_split
|
select.rs
|
// Copyright 2015 Colin Sherratt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use {Signal, ArmedSignal, Pulse, Waiting, Barrier, Signals};
pub struct Inner {
pub ready: Vec<usize>,
pub trigger: Option<Pulse>,
}
pub struct Handle(pub Arc<Mutex<Inner>>);
/// A `Select` listens to 1 or more signals. It will wait until
/// any signal becomes available before Pulsing. `Select` will then
/// return the `Signal` that has been `Pulsed`. `Select` has no defined
/// ordering of events for `Signal`s when there are more then one `Signals`
/// pending.
pub struct Select {
inner: Arc<Mutex<Inner>>,
signals: HashMap<usize, ArmedSignal>,
}
impl Select {
/// Create a new empty `Select`
pub fn new() -> Select {
Select {
inner: Arc::new(Mutex::new(Inner {
ready: Vec::new(),
trigger: None,
})),
signals: HashMap::new(),
}
}
/// Add a signal to the `Select`, a unique id that is associated
/// With the signal is returned. This can be used to remove the
/// signal from the `Select` or to lookup the `Pulse` when it fires.
pub fn add(&mut self, pulse: Signal) -> usize {
let id = pulse.id();
let p = pulse.arm(Waiting::select(Handle(self.inner.clone())));
self.signals.insert(id, p);
id
}
/// Remove a `Signal1 from the `Select` using it's unique id.
pub fn remove(&mut self, id: usize) -> Option<Signal> {
self.signals
.remove(&id)
.map(|x| x.disarm())
}
/// Convert all the signals present in the `Select` into a `Barrier`
pub fn into_barrier(self) -> Barrier {
let vec: Vec<Signal> = self.signals
.into_iter()
.map(|(_, p)| p.disarm())
.collect();
Barrier::new(&vec)
}
/// This is a non-blocking attempt to get a `Signal` from a `Select`
/// this will return a `Some(Signal)` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<Signal> {
let mut guard = self.inner.lock().unwrap();
if let Some(x) = guard.ready.pop() {
return Some(self.signals.remove(&x).map(|x| x.disarm()).unwrap());
}
None
}
/// Get the number of Signals being watched
pub fn len(&self) -> usize {
self.signals.len()
}
}
impl Iterator for Select {
type Item = Signal;
fn next(&mut self) -> Option<Signal>
|
}
impl Signals for Select {
fn signal(&self) -> Signal {
let (pulse, t) = Signal::new();
let mut guard = self.inner.lock().unwrap();
if guard.ready.len() == 0 {
guard.trigger = Some(t);
} else {
t.pulse();
}
pulse
}
}
/// `SelectMap` is a wrapper around a `Select` rather then use
/// a unique id to find out what signal has been asserts, `SelectMap`
/// will return an supplied object.
pub struct SelectMap<T> {
select: Select,
items: HashMap<usize, T>,
}
impl<T> SelectMap<T> {
/// Create a new empty `SelectMap`
pub fn new() -> SelectMap<T> {
SelectMap {
select: Select::new(),
items: HashMap::new(),
}
}
/// Add a `Signal` and an associated value into the `SelectMap`
pub fn add(&mut self, signal: Signal, value: T) {
let id = self.select.add(signal);
self.items.insert(id, value);
}
/// This is a non-blocking attempt to get a `Signal` from a `SelectMap`
/// this will return a `Some((Signal, T))` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<(Signal, T)> {
self.select.try_next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
/// Get the number of items in the `SelectMap`
pub fn len(&self) -> usize {
self.items.len()
}
}
impl<T> Iterator for SelectMap<T> {
type Item = (Signal, T);
fn next(&mut self) -> Option<(Signal, T)> {
self.select.next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
}
impl<T> Signals for SelectMap<T> {
fn signal(&self) -> Signal {
self.select.signal()
}
}
|
{
loop {
if self.signals.len() == 0 {
return None;
}
let pulse = {
let mut guard = self.inner.lock().unwrap();
while let Some(x) = guard.ready.pop() {
if let Some(x) = self.signals.remove(&x) {
return Some(x.disarm());
}
}
let (pulse, t) = Signal::new();
guard.trigger = Some(t);
pulse
};
pulse.wait().unwrap();
}
}
|
identifier_body
|
select.rs
|
// Copyright 2015 Colin Sherratt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use {Signal, ArmedSignal, Pulse, Waiting, Barrier, Signals};
pub struct Inner {
pub ready: Vec<usize>,
pub trigger: Option<Pulse>,
}
pub struct Handle(pub Arc<Mutex<Inner>>);
/// A `Select` listens to 1 or more signals. It will wait until
/// any signal becomes available before Pulsing. `Select` will then
/// return the `Signal` that has been `Pulsed`. `Select` has no defined
/// ordering of events for `Signal`s when there are more then one `Signals`
/// pending.
pub struct Select {
inner: Arc<Mutex<Inner>>,
signals: HashMap<usize, ArmedSignal>,
}
impl Select {
/// Create a new empty `Select`
pub fn new() -> Select {
Select {
inner: Arc::new(Mutex::new(Inner {
ready: Vec::new(),
trigger: None,
})),
signals: HashMap::new(),
}
}
/// Add a signal to the `Select`, a unique id that is associated
/// With the signal is returned. This can be used to remove the
/// signal from the `Select` or to lookup the `Pulse` when it fires.
pub fn add(&mut self, pulse: Signal) -> usize {
let id = pulse.id();
let p = pulse.arm(Waiting::select(Handle(self.inner.clone())));
self.signals.insert(id, p);
id
}
/// Remove a `Signal1 from the `Select` using it's unique id.
pub fn remove(&mut self, id: usize) -> Option<Signal> {
self.signals
.remove(&id)
.map(|x| x.disarm())
}
/// Convert all the signals present in the `Select` into a `Barrier`
pub fn into_barrier(self) -> Barrier {
let vec: Vec<Signal> = self.signals
.into_iter()
.map(|(_, p)| p.disarm())
.collect();
Barrier::new(&vec)
}
/// This is a non-blocking attempt to get a `Signal` from a `Select`
/// this will return a `Some(Signal)` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<Signal> {
let mut guard = self.inner.lock().unwrap();
if let Some(x) = guard.ready.pop() {
return Some(self.signals.remove(&x).map(|x| x.disarm()).unwrap());
}
None
}
/// Get the number of Signals being watched
pub fn len(&self) -> usize {
self.signals.len()
}
}
impl Iterator for Select {
type Item = Signal;
fn next(&mut self) -> Option<Signal> {
loop {
if self.signals.len() == 0 {
return None;
}
let pulse = {
let mut guard = self.inner.lock().unwrap();
while let Some(x) = guard.ready.pop() {
if let Some(x) = self.signals.remove(&x) {
return Some(x.disarm());
}
}
let (pulse, t) = Signal::new();
guard.trigger = Some(t);
pulse
};
pulse.wait().unwrap();
}
}
}
impl Signals for Select {
fn signal(&self) -> Signal {
let (pulse, t) = Signal::new();
let mut guard = self.inner.lock().unwrap();
if guard.ready.len() == 0 {
guard.trigger = Some(t);
} else {
t.pulse();
}
pulse
}
}
/// `SelectMap` is a wrapper around a `Select` rather then use
/// a unique id to find out what signal has been asserts, `SelectMap`
/// will return an supplied object.
pub struct
|
<T> {
select: Select,
items: HashMap<usize, T>,
}
impl<T> SelectMap<T> {
/// Create a new empty `SelectMap`
pub fn new() -> SelectMap<T> {
SelectMap {
select: Select::new(),
items: HashMap::new(),
}
}
/// Add a `Signal` and an associated value into the `SelectMap`
pub fn add(&mut self, signal: Signal, value: T) {
let id = self.select.add(signal);
self.items.insert(id, value);
}
/// This is a non-blocking attempt to get a `Signal` from a `SelectMap`
/// this will return a `Some((Signal, T))` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<(Signal, T)> {
self.select.try_next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
/// Get the number of items in the `SelectMap`
pub fn len(&self) -> usize {
self.items.len()
}
}
impl<T> Iterator for SelectMap<T> {
type Item = (Signal, T);
fn next(&mut self) -> Option<(Signal, T)> {
self.select.next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
}
impl<T> Signals for SelectMap<T> {
fn signal(&self) -> Signal {
self.select.signal()
}
}
|
SelectMap
|
identifier_name
|
select.rs
|
// Copyright 2015 Colin Sherratt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use {Signal, ArmedSignal, Pulse, Waiting, Barrier, Signals};
pub struct Inner {
pub ready: Vec<usize>,
pub trigger: Option<Pulse>,
}
pub struct Handle(pub Arc<Mutex<Inner>>);
/// A `Select` listens to 1 or more signals. It will wait until
/// any signal becomes available before Pulsing. `Select` will then
/// return the `Signal` that has been `Pulsed`. `Select` has no defined
/// ordering of events for `Signal`s when there are more then one `Signals`
/// pending.
pub struct Select {
inner: Arc<Mutex<Inner>>,
signals: HashMap<usize, ArmedSignal>,
}
impl Select {
/// Create a new empty `Select`
pub fn new() -> Select {
Select {
inner: Arc::new(Mutex::new(Inner {
ready: Vec::new(),
trigger: None,
})),
signals: HashMap::new(),
}
}
/// Add a signal to the `Select`, a unique id that is associated
/// With the signal is returned. This can be used to remove the
/// signal from the `Select` or to lookup the `Pulse` when it fires.
pub fn add(&mut self, pulse: Signal) -> usize {
let id = pulse.id();
let p = pulse.arm(Waiting::select(Handle(self.inner.clone())));
self.signals.insert(id, p);
id
}
/// Remove a `Signal1 from the `Select` using it's unique id.
pub fn remove(&mut self, id: usize) -> Option<Signal> {
self.signals
.remove(&id)
.map(|x| x.disarm())
}
/// Convert all the signals present in the `Select` into a `Barrier`
pub fn into_barrier(self) -> Barrier {
let vec: Vec<Signal> = self.signals
.into_iter()
.map(|(_, p)| p.disarm())
.collect();
Barrier::new(&vec)
}
/// This is a non-blocking attempt to get a `Signal` from a `Select`
/// this will return a `Some(Signal)` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<Signal> {
let mut guard = self.inner.lock().unwrap();
if let Some(x) = guard.ready.pop() {
return Some(self.signals.remove(&x).map(|x| x.disarm()).unwrap());
}
None
}
/// Get the number of Signals being watched
pub fn len(&self) -> usize {
self.signals.len()
}
}
impl Iterator for Select {
type Item = Signal;
fn next(&mut self) -> Option<Signal> {
loop {
if self.signals.len() == 0 {
return None;
}
let pulse = {
let mut guard = self.inner.lock().unwrap();
while let Some(x) = guard.ready.pop() {
if let Some(x) = self.signals.remove(&x)
|
}
let (pulse, t) = Signal::new();
guard.trigger = Some(t);
pulse
};
pulse.wait().unwrap();
}
}
}
impl Signals for Select {
fn signal(&self) -> Signal {
let (pulse, t) = Signal::new();
let mut guard = self.inner.lock().unwrap();
if guard.ready.len() == 0 {
guard.trigger = Some(t);
} else {
t.pulse();
}
pulse
}
}
/// `SelectMap` is a wrapper around a `Select` rather then use
/// a unique id to find out what signal has been asserts, `SelectMap`
/// will return an supplied object.
pub struct SelectMap<T> {
select: Select,
items: HashMap<usize, T>,
}
impl<T> SelectMap<T> {
/// Create a new empty `SelectMap`
pub fn new() -> SelectMap<T> {
SelectMap {
select: Select::new(),
items: HashMap::new(),
}
}
/// Add a `Signal` and an associated value into the `SelectMap`
pub fn add(&mut self, signal: Signal, value: T) {
let id = self.select.add(signal);
self.items.insert(id, value);
}
/// This is a non-blocking attempt to get a `Signal` from a `SelectMap`
/// this will return a `Some((Signal, T))` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<(Signal, T)> {
self.select.try_next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
/// Get the number of items in the `SelectMap`
pub fn len(&self) -> usize {
self.items.len()
}
}
impl<T> Iterator for SelectMap<T> {
type Item = (Signal, T);
fn next(&mut self) -> Option<(Signal, T)> {
self.select.next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
}
impl<T> Signals for SelectMap<T> {
fn signal(&self) -> Signal {
self.select.signal()
}
}
|
{
return Some(x.disarm());
}
|
conditional_block
|
select.rs
|
// Copyright 2015 Colin Sherratt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
|
use std::collections::HashMap;
use {Signal, ArmedSignal, Pulse, Waiting, Barrier, Signals};
pub struct Inner {
pub ready: Vec<usize>,
pub trigger: Option<Pulse>,
}
pub struct Handle(pub Arc<Mutex<Inner>>);
/// A `Select` listens to 1 or more signals. It will wait until
/// any signal becomes available before Pulsing. `Select` will then
/// return the `Signal` that has been `Pulsed`. `Select` has no defined
/// ordering of events for `Signal`s when there are more then one `Signals`
/// pending.
pub struct Select {
inner: Arc<Mutex<Inner>>,
signals: HashMap<usize, ArmedSignal>,
}
impl Select {
/// Create a new empty `Select`
pub fn new() -> Select {
Select {
inner: Arc::new(Mutex::new(Inner {
ready: Vec::new(),
trigger: None,
})),
signals: HashMap::new(),
}
}
/// Add a signal to the `Select`, a unique id that is associated
/// With the signal is returned. This can be used to remove the
/// signal from the `Select` or to lookup the `Pulse` when it fires.
pub fn add(&mut self, pulse: Signal) -> usize {
let id = pulse.id();
let p = pulse.arm(Waiting::select(Handle(self.inner.clone())));
self.signals.insert(id, p);
id
}
/// Remove a `Signal1 from the `Select` using it's unique id.
pub fn remove(&mut self, id: usize) -> Option<Signal> {
self.signals
.remove(&id)
.map(|x| x.disarm())
}
/// Convert all the signals present in the `Select` into a `Barrier`
pub fn into_barrier(self) -> Barrier {
let vec: Vec<Signal> = self.signals
.into_iter()
.map(|(_, p)| p.disarm())
.collect();
Barrier::new(&vec)
}
/// This is a non-blocking attempt to get a `Signal` from a `Select`
/// this will return a `Some(Signal)` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<Signal> {
let mut guard = self.inner.lock().unwrap();
if let Some(x) = guard.ready.pop() {
return Some(self.signals.remove(&x).map(|x| x.disarm()).unwrap());
}
None
}
/// Get the number of Signals being watched
pub fn len(&self) -> usize {
self.signals.len()
}
}
impl Iterator for Select {
type Item = Signal;
fn next(&mut self) -> Option<Signal> {
loop {
if self.signals.len() == 0 {
return None;
}
let pulse = {
let mut guard = self.inner.lock().unwrap();
while let Some(x) = guard.ready.pop() {
if let Some(x) = self.signals.remove(&x) {
return Some(x.disarm());
}
}
let (pulse, t) = Signal::new();
guard.trigger = Some(t);
pulse
};
pulse.wait().unwrap();
}
}
}
impl Signals for Select {
fn signal(&self) -> Signal {
let (pulse, t) = Signal::new();
let mut guard = self.inner.lock().unwrap();
if guard.ready.len() == 0 {
guard.trigger = Some(t);
} else {
t.pulse();
}
pulse
}
}
/// `SelectMap` is a wrapper around a `Select` rather then use
/// a unique id to find out what signal has been asserts, `SelectMap`
/// will return an supplied object.
pub struct SelectMap<T> {
select: Select,
items: HashMap<usize, T>,
}
impl<T> SelectMap<T> {
/// Create a new empty `SelectMap`
pub fn new() -> SelectMap<T> {
SelectMap {
select: Select::new(),
items: HashMap::new(),
}
}
/// Add a `Signal` and an associated value into the `SelectMap`
pub fn add(&mut self, signal: Signal, value: T) {
let id = self.select.add(signal);
self.items.insert(id, value);
}
/// This is a non-blocking attempt to get a `Signal` from a `SelectMap`
/// this will return a `Some((Signal, T))` if there is a pending `Signal`
/// in the select. Otherwise it will return `None`
pub fn try_next(&mut self) -> Option<(Signal, T)> {
self.select.try_next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
/// Get the number of items in the `SelectMap`
pub fn len(&self) -> usize {
self.items.len()
}
}
impl<T> Iterator for SelectMap<T> {
type Item = (Signal, T);
fn next(&mut self) -> Option<(Signal, T)> {
self.select.next().map(|x| {
let id = x.id();
(x, self.items.remove(&id).unwrap())
})
}
}
impl<T> Signals for SelectMap<T> {
fn signal(&self) -> Signal {
self.select.signal()
}
}
|
use std::sync::{Arc, Mutex};
|
random_line_split
|
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this type should be upstreamed to the Rust standard library.
use std::cast;
use std::util;
#[unsafe_no_drop_flag]
#[no_freeze]
pub struct Slot<T> {
// NB: Must be priv, or else someone could borrow it.
priv value: T,
priv immutable_borrow_count: u8,
priv mutably_borrowed: bool,
}
impl<T:Clone> Clone for Slot<T> {
#[inline]
fn clone(&self) -> Slot<T> {
Slot {
value: self.value.clone(),
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
}
#[unsafe_destructor]
impl<T> Drop for Slot<T> {
fn drop(&mut self) {
// Noncopyable.
}
}
pub struct SlotRef<'self,T> {
ptr: &'self T,
priv immutable_borrow_count: *mut u8,
}
#[unsafe_destructor]
impl<'self,T> Drop for SlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.immutable_borrow_count -= 1
}
}
}
pub struct MutSlotRef<'self,T> {
ptr: &'self mut T,
priv mutably_borrowed: *mut bool,
}
#[unsafe_destructor]
impl<'self,T> Drop for MutSlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.mutably_borrowed = false
}
}
}
impl<T> Slot<T> {
#[inline]
pub fn init(value: T) -> Slot<T> {
Slot {
value: value,
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
/// Borrows the data immutably. This function is thread-safe, but *bad things will happen if
/// you try to mutate the data while one of these pointers is held*.
#[inline]
pub unsafe fn borrow_unchecked<'a>(&'a self) -> &'a T {
&self.value
}
#[inline]
pub fn borrow<'a>(&'a self) -> SlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count == 255 || self.mutably_borrowed
|
let immutable_borrow_count = cast::transmute_mut(&self.immutable_borrow_count);
*immutable_borrow_count += 1;
SlotRef {
ptr: &self.value,
immutable_borrow_count: immutable_borrow_count,
}
}
}
#[inline]
pub fn mutate<'a>(&'a self) -> MutSlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count > 0 || self.mutably_borrowed {
self.fail()
}
let mutably_borrowed = cast::transmute_mut(&self.mutably_borrowed);
*mutably_borrowed = true;
MutSlotRef {
ptr: cast::transmute_mut(&self.value),
mutably_borrowed: mutably_borrowed,
}
}
}
#[inline]
pub fn set(&self, value: T) {
*self.mutate().ptr = value
}
/// Replaces the slot's value with the given value and returns the old value.
#[inline]
pub fn replace(&self, value: T) -> T {
util::replace(self.mutate().ptr, value)
}
#[inline(never)]
pub fn fail(&self) ->! {
fail!("slot is borrowed")
}
}
impl<T:Clone> Slot<T> {
#[inline]
pub fn get(&self) -> T {
self.value.clone()
}
}
|
{
self.fail()
}
|
conditional_block
|
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this type should be upstreamed to the Rust standard library.
use std::cast;
use std::util;
#[unsafe_no_drop_flag]
#[no_freeze]
pub struct Slot<T> {
// NB: Must be priv, or else someone could borrow it.
priv value: T,
priv immutable_borrow_count: u8,
priv mutably_borrowed: bool,
}
impl<T:Clone> Clone for Slot<T> {
#[inline]
fn clone(&self) -> Slot<T> {
Slot {
value: self.value.clone(),
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
}
#[unsafe_destructor]
impl<T> Drop for Slot<T> {
fn drop(&mut self) {
// Noncopyable.
}
}
pub struct SlotRef<'self,T> {
ptr: &'self T,
priv immutable_borrow_count: *mut u8,
}
#[unsafe_destructor]
impl<'self,T> Drop for SlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.immutable_borrow_count -= 1
}
}
}
pub struct MutSlotRef<'self,T> {
ptr: &'self mut T,
priv mutably_borrowed: *mut bool,
}
#[unsafe_destructor]
impl<'self,T> Drop for MutSlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.mutably_borrowed = false
}
}
}
impl<T> Slot<T> {
#[inline]
pub fn init(value: T) -> Slot<T> {
Slot {
value: value,
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
/// Borrows the data immutably. This function is thread-safe, but *bad things will happen if
/// you try to mutate the data while one of these pointers is held*.
#[inline]
pub unsafe fn borrow_unchecked<'a>(&'a self) -> &'a T {
&self.value
}
#[inline]
pub fn borrow<'a>(&'a self) -> SlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count == 255 || self.mutably_borrowed {
self.fail()
}
let immutable_borrow_count = cast::transmute_mut(&self.immutable_borrow_count);
*immutable_borrow_count += 1;
SlotRef {
ptr: &self.value,
immutable_borrow_count: immutable_borrow_count,
}
}
}
#[inline]
pub fn mutate<'a>(&'a self) -> MutSlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count > 0 || self.mutably_borrowed {
self.fail()
}
let mutably_borrowed = cast::transmute_mut(&self.mutably_borrowed);
*mutably_borrowed = true;
MutSlotRef {
ptr: cast::transmute_mut(&self.value),
mutably_borrowed: mutably_borrowed,
}
}
}
#[inline]
pub fn set(&self, value: T) {
|
/// Replaces the slot's value with the given value and returns the old value.
#[inline]
pub fn replace(&self, value: T) -> T {
util::replace(self.mutate().ptr, value)
}
#[inline(never)]
pub fn fail(&self) ->! {
fail!("slot is borrowed")
}
}
impl<T:Clone> Slot<T> {
#[inline]
pub fn get(&self) -> T {
self.value.clone()
}
}
|
*self.mutate().ptr = value
}
|
random_line_split
|
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this type should be upstreamed to the Rust standard library.
use std::cast;
use std::util;
#[unsafe_no_drop_flag]
#[no_freeze]
pub struct Slot<T> {
// NB: Must be priv, or else someone could borrow it.
priv value: T,
priv immutable_borrow_count: u8,
priv mutably_borrowed: bool,
}
impl<T:Clone> Clone for Slot<T> {
#[inline]
fn clone(&self) -> Slot<T> {
Slot {
value: self.value.clone(),
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
}
#[unsafe_destructor]
impl<T> Drop for Slot<T> {
fn drop(&mut self) {
// Noncopyable.
}
}
pub struct SlotRef<'self,T> {
ptr: &'self T,
priv immutable_borrow_count: *mut u8,
}
#[unsafe_destructor]
impl<'self,T> Drop for SlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.immutable_borrow_count -= 1
}
}
}
pub struct MutSlotRef<'self,T> {
ptr: &'self mut T,
priv mutably_borrowed: *mut bool,
}
#[unsafe_destructor]
impl<'self,T> Drop for MutSlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.mutably_borrowed = false
}
}
}
impl<T> Slot<T> {
#[inline]
pub fn init(value: T) -> Slot<T> {
Slot {
value: value,
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
/// Borrows the data immutably. This function is thread-safe, but *bad things will happen if
/// you try to mutate the data while one of these pointers is held*.
#[inline]
pub unsafe fn borrow_unchecked<'a>(&'a self) -> &'a T
|
#[inline]
pub fn borrow<'a>(&'a self) -> SlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count == 255 || self.mutably_borrowed {
self.fail()
}
let immutable_borrow_count = cast::transmute_mut(&self.immutable_borrow_count);
*immutable_borrow_count += 1;
SlotRef {
ptr: &self.value,
immutable_borrow_count: immutable_borrow_count,
}
}
}
#[inline]
pub fn mutate<'a>(&'a self) -> MutSlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count > 0 || self.mutably_borrowed {
self.fail()
}
let mutably_borrowed = cast::transmute_mut(&self.mutably_borrowed);
*mutably_borrowed = true;
MutSlotRef {
ptr: cast::transmute_mut(&self.value),
mutably_borrowed: mutably_borrowed,
}
}
}
#[inline]
pub fn set(&self, value: T) {
*self.mutate().ptr = value
}
/// Replaces the slot's value with the given value and returns the old value.
#[inline]
pub fn replace(&self, value: T) -> T {
util::replace(self.mutate().ptr, value)
}
#[inline(never)]
pub fn fail(&self) ->! {
fail!("slot is borrowed")
}
}
impl<T:Clone> Slot<T> {
#[inline]
pub fn get(&self) -> T {
self.value.clone()
}
}
|
{
&self.value
}
|
identifier_body
|
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this type should be upstreamed to the Rust standard library.
use std::cast;
use std::util;
#[unsafe_no_drop_flag]
#[no_freeze]
pub struct Slot<T> {
// NB: Must be priv, or else someone could borrow it.
priv value: T,
priv immutable_borrow_count: u8,
priv mutably_borrowed: bool,
}
impl<T:Clone> Clone for Slot<T> {
#[inline]
fn clone(&self) -> Slot<T> {
Slot {
value: self.value.clone(),
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
}
#[unsafe_destructor]
impl<T> Drop for Slot<T> {
fn
|
(&mut self) {
// Noncopyable.
}
}
pub struct SlotRef<'self,T> {
ptr: &'self T,
priv immutable_borrow_count: *mut u8,
}
#[unsafe_destructor]
impl<'self,T> Drop for SlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.immutable_borrow_count -= 1
}
}
}
pub struct MutSlotRef<'self,T> {
ptr: &'self mut T,
priv mutably_borrowed: *mut bool,
}
#[unsafe_destructor]
impl<'self,T> Drop for MutSlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.mutably_borrowed = false
}
}
}
impl<T> Slot<T> {
#[inline]
pub fn init(value: T) -> Slot<T> {
Slot {
value: value,
immutable_borrow_count: 0,
mutably_borrowed: false,
}
}
/// Borrows the data immutably. This function is thread-safe, but *bad things will happen if
/// you try to mutate the data while one of these pointers is held*.
#[inline]
pub unsafe fn borrow_unchecked<'a>(&'a self) -> &'a T {
&self.value
}
#[inline]
pub fn borrow<'a>(&'a self) -> SlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count == 255 || self.mutably_borrowed {
self.fail()
}
let immutable_borrow_count = cast::transmute_mut(&self.immutable_borrow_count);
*immutable_borrow_count += 1;
SlotRef {
ptr: &self.value,
immutable_borrow_count: immutable_borrow_count,
}
}
}
#[inline]
pub fn mutate<'a>(&'a self) -> MutSlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count > 0 || self.mutably_borrowed {
self.fail()
}
let mutably_borrowed = cast::transmute_mut(&self.mutably_borrowed);
*mutably_borrowed = true;
MutSlotRef {
ptr: cast::transmute_mut(&self.value),
mutably_borrowed: mutably_borrowed,
}
}
}
#[inline]
pub fn set(&self, value: T) {
*self.mutate().ptr = value
}
/// Replaces the slot's value with the given value and returns the old value.
#[inline]
pub fn replace(&self, value: T) -> T {
util::replace(self.mutate().ptr, value)
}
#[inline(never)]
pub fn fail(&self) ->! {
fail!("slot is borrowed")
}
}
impl<T:Clone> Slot<T> {
#[inline]
pub fn get(&self) -> T {
self.value.clone()
}
}
|
drop
|
identifier_name
|
read_manifest.rs
|
use std::env;
use std::error::Error;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct
|
{
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH Path to the manifest to compile
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>> {
debug!("executing; cmd=cargo-read-manifest; args={:?}",
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let mut source = try!(PathSource::for_path(root.parent().unwrap(), config).map_err(|e| {
CliError::new(e.description(), 1)
}));
try!(source.update().map_err(|err| CliError::new(err.description(), 1)));
source.root_package()
.map(|pkg| Some(pkg))
.map_err(|err| CliError::from_boxed(err, 1))
}
|
Options
|
identifier_name
|
read_manifest.rs
|
use std::env;
use std::error::Error;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH Path to the manifest to compile
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>> {
debug!("executing; cmd=cargo-read-manifest; args={:?}",
|
let mut source = try!(PathSource::for_path(root.parent().unwrap(), config).map_err(|e| {
CliError::new(e.description(), 1)
}));
try!(source.update().map_err(|err| CliError::new(err.description(), 1)));
source.root_package()
.map(|pkg| Some(pkg))
.map_err(|err| CliError::from_boxed(err, 1))
}
|
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
|
random_line_split
|
read_manifest.rs
|
use std::env;
use std::error::Error;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH Path to the manifest to compile
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>>
|
{
debug!("executing; cmd=cargo-read-manifest; args={:?}",
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let mut source = try!(PathSource::for_path(root.parent().unwrap(), config).map_err(|e| {
CliError::new(e.description(), 1)
}));
try!(source.update().map_err(|err| CliError::new(err.description(), 1)));
source.root_package()
.map(|pkg| Some(pkg))
.map_err(|err| CliError::from_boxed(err, 1))
}
|
identifier_body
|
|
type-ascription-soundness.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.
// Type ascription doesn't lead to unsoundness
#![feature(type_ascription)]
fn main() {
|
ref x => {}
}
let _len = (arr: &[u8]).len(); //~ ERROR mismatched types
}
|
let arr = &[1u8, 2, 3];
let ref x = arr: &[u8]; //~ ERROR mismatched types
let ref mut x = arr: &[u8]; //~ ERROR mismatched types
match arr: &[u8] { //~ ERROR mismatched types
|
random_line_split
|
type-ascription-soundness.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.
// Type ascription doesn't lead to unsoundness
#![feature(type_ascription)]
fn main()
|
{
let arr = &[1u8, 2, 3];
let ref x = arr: &[u8]; //~ ERROR mismatched types
let ref mut x = arr: &[u8]; //~ ERROR mismatched types
match arr: &[u8] { //~ ERROR mismatched types
ref x => {}
}
let _len = (arr: &[u8]).len(); //~ ERROR mismatched types
}
|
identifier_body
|
|
type-ascription-soundness.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.
// Type ascription doesn't lead to unsoundness
#![feature(type_ascription)]
fn
|
() {
let arr = &[1u8, 2, 3];
let ref x = arr: &[u8]; //~ ERROR mismatched types
let ref mut x = arr: &[u8]; //~ ERROR mismatched types
match arr: &[u8] { //~ ERROR mismatched types
ref x => {}
}
let _len = (arr: &[u8]).len(); //~ ERROR mismatched types
}
|
main
|
identifier_name
|
models.rs
|
use rocket::http::RawStr;
use rocket::request::FromParam;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Integer;
use super::schema::{measurements, sensors};
use super::MeteoError;
use crate::db::models::Node;
use crate::utils::DateTimeUtc;
use std::convert::TryFrom;
use std::io::Write;
#[derive(Identifiable, Queryable, Associations, Debug, Clone)]
#[belongs_to(Node)]
pub struct Sensor {
pub id: i32,
|
#[derive(Identifiable, Queryable, Associations, Debug, Clone)]
#[belongs_to(Sensor)]
pub(super) struct Measurement {
pub id: i32,
pub sensor_id: i32,
pub value: f32,
pub measured_at: DateTimeUtc,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromSqlRow, AsExpression)]
#[sql_type = "Integer"]
#[repr(i32)]
pub enum SensorTypeEnum {
Pressure = 0,
Temperature = 1,
Humidity = 2,
LightLevel = 3,
}
impl AsRef<str> for SensorTypeEnum {
fn as_ref(&self) -> &'static str {
match self {
SensorTypeEnum::Pressure => "pressure",
SensorTypeEnum::Temperature => "temperature",
SensorTypeEnum::Humidity => "humidity",
SensorTypeEnum::LightLevel => "light_level",
}
}
}
impl<'a> TryFrom<&'a str> for SensorTypeEnum {
type Error = MeteoError;
fn try_from(sensor_type_str: &'a str) -> Result<Self, Self::Error> {
match sensor_type_str {
"pressure" => Ok(SensorTypeEnum::Pressure),
"temperature" => Ok(SensorTypeEnum::Temperature),
"humidity" => Ok(SensorTypeEnum::Humidity),
"light_level" => Ok(SensorTypeEnum::LightLevel),
_ => Err(MeteoError),
}
}
}
impl<DB> FromSql<Integer, DB> for SensorTypeEnum
where
DB: Backend,
i32: FromSql<Integer, DB>,
{
fn from_sql(bytes: Option<&<DB as Backend>::RawValue>) -> deserialize::Result<Self> {
let raw_val = i32::from_sql(bytes)?;
match raw_val {
x if x == SensorTypeEnum::Pressure as i32 => Ok(SensorTypeEnum::Pressure),
x if x == SensorTypeEnum::Temperature as i32 => Ok(SensorTypeEnum::Temperature),
x if x == SensorTypeEnum::Humidity as i32 => Ok(SensorTypeEnum::Humidity),
x if x == SensorTypeEnum::LightLevel as i32 => Ok(SensorTypeEnum::LightLevel),
_ => Err(Box::new(MeteoError)),
}
}
}
impl<DB> ToSql<Integer, DB> for SensorTypeEnum
where
DB: Backend,
i32: ToSql<Integer, DB>,
{
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
(*self as i32).to_sql(out)
}
}
impl<'req> FromParam<'req> for SensorTypeEnum {
type Error = MeteoError;
fn from_param(param: &'req RawStr) -> Result<Self, Self::Error> {
SensorTypeEnum::try_from(param.as_str())
}
}
|
pub public_id: i32,
pub node_id: i32,
pub sensor_type: SensorTypeEnum,
pub name: String,
}
|
random_line_split
|
models.rs
|
use rocket::http::RawStr;
use rocket::request::FromParam;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Integer;
use super::schema::{measurements, sensors};
use super::MeteoError;
use crate::db::models::Node;
use crate::utils::DateTimeUtc;
use std::convert::TryFrom;
use std::io::Write;
#[derive(Identifiable, Queryable, Associations, Debug, Clone)]
#[belongs_to(Node)]
pub struct Sensor {
pub id: i32,
pub public_id: i32,
pub node_id: i32,
pub sensor_type: SensorTypeEnum,
pub name: String,
}
#[derive(Identifiable, Queryable, Associations, Debug, Clone)]
#[belongs_to(Sensor)]
pub(super) struct Measurement {
pub id: i32,
pub sensor_id: i32,
pub value: f32,
pub measured_at: DateTimeUtc,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromSqlRow, AsExpression)]
#[sql_type = "Integer"]
#[repr(i32)]
pub enum SensorTypeEnum {
Pressure = 0,
Temperature = 1,
Humidity = 2,
LightLevel = 3,
}
impl AsRef<str> for SensorTypeEnum {
fn as_ref(&self) -> &'static str {
match self {
SensorTypeEnum::Pressure => "pressure",
SensorTypeEnum::Temperature => "temperature",
SensorTypeEnum::Humidity => "humidity",
SensorTypeEnum::LightLevel => "light_level",
}
}
}
impl<'a> TryFrom<&'a str> for SensorTypeEnum {
type Error = MeteoError;
fn try_from(sensor_type_str: &'a str) -> Result<Self, Self::Error>
|
}
impl<DB> FromSql<Integer, DB> for SensorTypeEnum
where
DB: Backend,
i32: FromSql<Integer, DB>,
{
fn from_sql(bytes: Option<&<DB as Backend>::RawValue>) -> deserialize::Result<Self> {
let raw_val = i32::from_sql(bytes)?;
match raw_val {
x if x == SensorTypeEnum::Pressure as i32 => Ok(SensorTypeEnum::Pressure),
x if x == SensorTypeEnum::Temperature as i32 => Ok(SensorTypeEnum::Temperature),
x if x == SensorTypeEnum::Humidity as i32 => Ok(SensorTypeEnum::Humidity),
x if x == SensorTypeEnum::LightLevel as i32 => Ok(SensorTypeEnum::LightLevel),
_ => Err(Box::new(MeteoError)),
}
}
}
impl<DB> ToSql<Integer, DB> for SensorTypeEnum
where
DB: Backend,
i32: ToSql<Integer, DB>,
{
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
(*self as i32).to_sql(out)
}
}
impl<'req> FromParam<'req> for SensorTypeEnum {
type Error = MeteoError;
fn from_param(param: &'req RawStr) -> Result<Self, Self::Error> {
SensorTypeEnum::try_from(param.as_str())
}
}
|
{
match sensor_type_str {
"pressure" => Ok(SensorTypeEnum::Pressure),
"temperature" => Ok(SensorTypeEnum::Temperature),
"humidity" => Ok(SensorTypeEnum::Humidity),
"light_level" => Ok(SensorTypeEnum::LightLevel),
_ => Err(MeteoError),
}
}
|
identifier_body
|
models.rs
|
use rocket::http::RawStr;
use rocket::request::FromParam;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Integer;
use super::schema::{measurements, sensors};
use super::MeteoError;
use crate::db::models::Node;
use crate::utils::DateTimeUtc;
use std::convert::TryFrom;
use std::io::Write;
#[derive(Identifiable, Queryable, Associations, Debug, Clone)]
#[belongs_to(Node)]
pub struct Sensor {
pub id: i32,
pub public_id: i32,
pub node_id: i32,
pub sensor_type: SensorTypeEnum,
pub name: String,
}
#[derive(Identifiable, Queryable, Associations, Debug, Clone)]
#[belongs_to(Sensor)]
pub(super) struct
|
{
pub id: i32,
pub sensor_id: i32,
pub value: f32,
pub measured_at: DateTimeUtc,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromSqlRow, AsExpression)]
#[sql_type = "Integer"]
#[repr(i32)]
pub enum SensorTypeEnum {
Pressure = 0,
Temperature = 1,
Humidity = 2,
LightLevel = 3,
}
impl AsRef<str> for SensorTypeEnum {
fn as_ref(&self) -> &'static str {
match self {
SensorTypeEnum::Pressure => "pressure",
SensorTypeEnum::Temperature => "temperature",
SensorTypeEnum::Humidity => "humidity",
SensorTypeEnum::LightLevel => "light_level",
}
}
}
impl<'a> TryFrom<&'a str> for SensorTypeEnum {
type Error = MeteoError;
fn try_from(sensor_type_str: &'a str) -> Result<Self, Self::Error> {
match sensor_type_str {
"pressure" => Ok(SensorTypeEnum::Pressure),
"temperature" => Ok(SensorTypeEnum::Temperature),
"humidity" => Ok(SensorTypeEnum::Humidity),
"light_level" => Ok(SensorTypeEnum::LightLevel),
_ => Err(MeteoError),
}
}
}
impl<DB> FromSql<Integer, DB> for SensorTypeEnum
where
DB: Backend,
i32: FromSql<Integer, DB>,
{
fn from_sql(bytes: Option<&<DB as Backend>::RawValue>) -> deserialize::Result<Self> {
let raw_val = i32::from_sql(bytes)?;
match raw_val {
x if x == SensorTypeEnum::Pressure as i32 => Ok(SensorTypeEnum::Pressure),
x if x == SensorTypeEnum::Temperature as i32 => Ok(SensorTypeEnum::Temperature),
x if x == SensorTypeEnum::Humidity as i32 => Ok(SensorTypeEnum::Humidity),
x if x == SensorTypeEnum::LightLevel as i32 => Ok(SensorTypeEnum::LightLevel),
_ => Err(Box::new(MeteoError)),
}
}
}
impl<DB> ToSql<Integer, DB> for SensorTypeEnum
where
DB: Backend,
i32: ToSql<Integer, DB>,
{
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
(*self as i32).to_sql(out)
}
}
impl<'req> FromParam<'req> for SensorTypeEnum {
type Error = MeteoError;
fn from_param(param: &'req RawStr) -> Result<Self, Self::Error> {
SensorTypeEnum::try_from(param.as_str())
}
}
|
Measurement
|
identifier_name
|
lib.rs
|
#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serializable types for the [Matrix Client-Server API][client-api].
//! These types can be shared by client and server code.
//!
//! [client-api]: https://spec.matrix.org/v1.2/client-server-api/
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
pub mod account;
pub mod alias;
pub mod appservice;
pub mod backup;
pub mod capabilities;
pub mod config;
pub mod context;
pub mod device;
pub mod directory;
pub mod discover;
pub mod error;
pub mod filter;
pub mod keys;
pub mod knock;
pub mod media;
pub mod membership;
pub mod message;
pub mod presence;
pub mod profile;
pub mod push;
pub mod read_marker;
pub mod receipt;
pub mod redact;
pub mod room;
pub mod search;
pub mod server;
pub mod session;
pub mod space;
pub mod state;
pub mod sync;
pub mod tag;
pub mod thirdparty;
pub mod to_device;
pub mod typing;
pub mod uiaa;
pub mod user_directory;
pub mod voip;
use std::fmt;
pub use error::Error;
// Wrapper around `Box<str>` that cannot be used in a meaningful way outside of
// this crate. Used for string enums because their `_Custom` variant can't be
// truly private (only `#[doc(hidden)]`).
#[doc(hidden)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct
|
(Box<str>);
impl fmt::Debug for PrivOwnedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
|
PrivOwnedStr
|
identifier_name
|
lib.rs
|
#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serializable types for the [Matrix Client-Server API][client-api].
//! These types can be shared by client and server code.
//!
//! [client-api]: https://spec.matrix.org/v1.2/client-server-api/
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
pub mod account;
pub mod alias;
pub mod appservice;
pub mod backup;
pub mod capabilities;
pub mod config;
pub mod context;
pub mod device;
pub mod directory;
pub mod discover;
pub mod error;
|
pub mod filter;
pub mod keys;
pub mod knock;
pub mod media;
pub mod membership;
pub mod message;
pub mod presence;
pub mod profile;
pub mod push;
pub mod read_marker;
pub mod receipt;
pub mod redact;
pub mod room;
pub mod search;
pub mod server;
pub mod session;
pub mod space;
pub mod state;
pub mod sync;
pub mod tag;
pub mod thirdparty;
pub mod to_device;
pub mod typing;
pub mod uiaa;
pub mod user_directory;
pub mod voip;
use std::fmt;
pub use error::Error;
// Wrapper around `Box<str>` that cannot be used in a meaningful way outside of
// this crate. Used for string enums because their `_Custom` variant can't be
// truly private (only `#[doc(hidden)]`).
#[doc(hidden)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PrivOwnedStr(Box<str>);
impl fmt::Debug for PrivOwnedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
|
random_line_split
|
|
download.rs
|
use chrono::naive::NaiveDateTime;
use chrono::Local;
use database::Database;
use rutracker::RutrackerForum;
use std::collections::HashMap;
use std::collections::HashSet;
type Result<T> = std::result::Result<T, failure::Error>;
pub struct Downloader<'a> {
db: &'a Database,
forum: &'a RutrackerForum,
ignored_id: Vec<usize>,
}
impl<'a> Downloader<'a> {
pub fn new(db: &'a Database, forum: &'a RutrackerForum, ignored_id: Vec<usize>) -> Self {
Self {
db,
forum,
ignored_id,
}
}
pub fn get_list_for_download(
&self,
forum_id: usize,
download: i16,
) -> Result<HashMap<usize, (String, usize)>> {
/* let date = Local::now().naive_local();
let num_days = |time: NaiveDateTime| date.signed_duration_since(time).num_days();
let check_reg_time_and_status = |status: i16, time: NaiveDateTime| {
([2, 3, 8].contains(&status) && num_days(time) > 30)
|| ([0, 10].contains(&status) && num_days(time) > 90)
};
let keeper_list: HashMap<String, Vec<usize>> =
self.db.get_by_filter(DBName::KeeperList, |_, _| true)?;
let keeper_list: HashSet<usize> = keeper_list.into_iter().flat_map(|(_, v)| v).collect();
let topic_id: HashMap<_, _> = self
.db
.pvc(forum_id, None::<&[usize]>)?
.into_iter()
|
.collect(); */
Ok(HashMap::new())
}
}
|
.filter(|(_, v)| v.seeders <= download)
.filter(|(_, v)| check_reg_time_and_status(v.tor_status, v.reg_time))
.filter(|(id, _)| !self.ignored_id.contains(id) && !keeper_list.contains(id))
|
random_line_split
|
download.rs
|
use chrono::naive::NaiveDateTime;
use chrono::Local;
use database::Database;
use rutracker::RutrackerForum;
use std::collections::HashMap;
use std::collections::HashSet;
type Result<T> = std::result::Result<T, failure::Error>;
pub struct Downloader<'a> {
db: &'a Database,
forum: &'a RutrackerForum,
ignored_id: Vec<usize>,
}
impl<'a> Downloader<'a> {
pub fn new(db: &'a Database, forum: &'a RutrackerForum, ignored_id: Vec<usize>) -> Self {
Self {
db,
forum,
ignored_id,
}
}
pub fn get_list_for_download(
&self,
forum_id: usize,
download: i16,
) -> Result<HashMap<usize, (String, usize)>>
|
}
|
{
/* let date = Local::now().naive_local();
let num_days = |time: NaiveDateTime| date.signed_duration_since(time).num_days();
let check_reg_time_and_status = |status: i16, time: NaiveDateTime| {
([2, 3, 8].contains(&status) && num_days(time) > 30)
|| ([0, 10].contains(&status) && num_days(time) > 90)
};
let keeper_list: HashMap<String, Vec<usize>> =
self.db.get_by_filter(DBName::KeeperList, |_, _| true)?;
let keeper_list: HashSet<usize> = keeper_list.into_iter().flat_map(|(_, v)| v).collect();
let topic_id: HashMap<_, _> = self
.db
.pvc(forum_id, None::<&[usize]>)?
.into_iter()
.filter(|(_, v)| v.seeders <= download)
.filter(|(_, v)| check_reg_time_and_status(v.tor_status, v.reg_time))
.filter(|(id, _)| !self.ignored_id.contains(id) && !keeper_list.contains(id))
.collect(); */
Ok(HashMap::new())
}
|
identifier_body
|
download.rs
|
use chrono::naive::NaiveDateTime;
use chrono::Local;
use database::Database;
use rutracker::RutrackerForum;
use std::collections::HashMap;
use std::collections::HashSet;
type Result<T> = std::result::Result<T, failure::Error>;
pub struct Downloader<'a> {
db: &'a Database,
forum: &'a RutrackerForum,
ignored_id: Vec<usize>,
}
impl<'a> Downloader<'a> {
pub fn
|
(db: &'a Database, forum: &'a RutrackerForum, ignored_id: Vec<usize>) -> Self {
Self {
db,
forum,
ignored_id,
}
}
pub fn get_list_for_download(
&self,
forum_id: usize,
download: i16,
) -> Result<HashMap<usize, (String, usize)>> {
/* let date = Local::now().naive_local();
let num_days = |time: NaiveDateTime| date.signed_duration_since(time).num_days();
let check_reg_time_and_status = |status: i16, time: NaiveDateTime| {
([2, 3, 8].contains(&status) && num_days(time) > 30)
|| ([0, 10].contains(&status) && num_days(time) > 90)
};
let keeper_list: HashMap<String, Vec<usize>> =
self.db.get_by_filter(DBName::KeeperList, |_, _| true)?;
let keeper_list: HashSet<usize> = keeper_list.into_iter().flat_map(|(_, v)| v).collect();
let topic_id: HashMap<_, _> = self
.db
.pvc(forum_id, None::<&[usize]>)?
.into_iter()
.filter(|(_, v)| v.seeders <= download)
.filter(|(_, v)| check_reg_time_and_status(v.tor_status, v.reg_time))
.filter(|(id, _)|!self.ignored_id.contains(id) &&!keeper_list.contains(id))
.collect(); */
Ok(HashMap::new())
}
}
|
new
|
identifier_name
|
error.rs
|
use curl::Error as CurlError;
use std::io::Error as IOError;
use std::fmt::{Formatter,Debug,Display,Error as FormatterError};
use std::error::Error as TraitError;
use std::convert::From;
/// Errors during starting download manager or processing request.
pub enum Error<E> {
/// IO Error
IOError { error: IOError },
/// Curl error - configuring or processing request.
/// First parameter - curl error.
Curl { error: CurlError },
/// User defined error while Initializing
Initialize { error: E },
}
impl <E> Debug for Error<E> {
#[allow(unused)]
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
match self {
&Error::IOError {ref error} => {
write!(f, "IOError: {:?}", error)
},
&Error::Curl {ref error} => {
write!(f, "Curl error: {:?}", error)
},
&Error::Initialize {..} => {
write!(f, "Initialize error")
},
}
}
}
impl <E> Display for Error<E> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
write!(f,"{:?}",self)
}
}
impl <E>TraitError for Error<E> {
#[allow(unused)]
fn description(&self) -> &str
|
fn cause(&self) -> Option<&TraitError> {
match self {
&Error::IOError {ref error} => {
Some(error)
},
&Error::Curl {ref error} => {
Some(error)
},
&Error::Initialize {..} => {
None
},
}
}
}
impl <E>From<IOError> for Error<E> {
fn from(error: IOError) -> Self {
Error::IOError {
error: error
}
}
}
impl <E>From<CurlError> for Error<E> {
fn from(error: CurlError) -> Self {
Error::Curl {
error: error
}
}
}
// impl <E:!CurlError>From<E> for Error<E> where E:!CurlError {
// fn from(error: E) -> Self {
// Error::Initialize {
// error: error
// }
// }
// }
|
{
match self {
&Error::IOError {..} => {
"IOError"
},
&Error::Curl {..} => {
"Curl error"
},
&Error::Initialize {..} => {
"Initialize error"
},
}
}
|
identifier_body
|
error.rs
|
use curl::Error as CurlError;
use std::io::Error as IOError;
use std::fmt::{Formatter,Debug,Display,Error as FormatterError};
use std::error::Error as TraitError;
use std::convert::From;
/// Errors during starting download manager or processing request.
pub enum Error<E> {
/// IO Error
IOError { error: IOError },
/// Curl error - configuring or processing request.
/// First parameter - curl error.
Curl { error: CurlError },
/// User defined error while Initializing
Initialize { error: E },
}
impl <E> Debug for Error<E> {
#[allow(unused)]
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
match self {
&Error::IOError {ref error} => {
write!(f, "IOError: {:?}", error)
},
&Error::Curl {ref error} => {
write!(f, "Curl error: {:?}", error)
},
&Error::Initialize {..} => {
write!(f, "Initialize error")
},
}
}
}
impl <E> Display for Error<E> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
write!(f,"{:?}",self)
}
}
impl <E>TraitError for Error<E> {
#[allow(unused)]
fn
|
(&self) -> &str {
match self {
&Error::IOError {..} => {
"IOError"
},
&Error::Curl {..} => {
"Curl error"
},
&Error::Initialize {..} => {
"Initialize error"
},
}
}
fn cause(&self) -> Option<&TraitError> {
match self {
&Error::IOError {ref error} => {
Some(error)
},
&Error::Curl {ref error} => {
Some(error)
},
&Error::Initialize {..} => {
None
},
}
}
}
impl <E>From<IOError> for Error<E> {
fn from(error: IOError) -> Self {
Error::IOError {
error: error
}
}
}
impl <E>From<CurlError> for Error<E> {
fn from(error: CurlError) -> Self {
Error::Curl {
error: error
}
}
}
// impl <E:!CurlError>From<E> for Error<E> where E:!CurlError {
// fn from(error: E) -> Self {
// Error::Initialize {
// error: error
// }
// }
// }
|
description
|
identifier_name
|
error.rs
|
use curl::Error as CurlError;
use std::io::Error as IOError;
use std::fmt::{Formatter,Debug,Display,Error as FormatterError};
use std::error::Error as TraitError;
use std::convert::From;
/// Errors during starting download manager or processing request.
pub enum Error<E> {
/// IO Error
IOError { error: IOError },
/// Curl error - configuring or processing request.
/// First parameter - curl error.
Curl { error: CurlError },
/// User defined error while Initializing
Initialize { error: E },
}
impl <E> Debug for Error<E> {
#[allow(unused)]
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
match self {
&Error::IOError {ref error} => {
write!(f, "IOError: {:?}", error)
},
&Error::Curl {ref error} => {
write!(f, "Curl error: {:?}", error)
},
&Error::Initialize {..} => {
write!(f, "Initialize error")
},
}
}
}
impl <E> Display for Error<E> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
write!(f,"{:?}",self)
}
}
impl <E>TraitError for Error<E> {
#[allow(unused)]
fn description(&self) -> &str {
match self {
&Error::IOError {..} => {
"IOError"
},
&Error::Curl {..} => {
"Curl error"
},
&Error::Initialize {..} => {
"Initialize error"
},
}
}
fn cause(&self) -> Option<&TraitError> {
match self {
&Error::IOError {ref error} => {
Some(error)
},
&Error::Curl {ref error} => {
Some(error)
|
}
}
}
impl <E>From<IOError> for Error<E> {
fn from(error: IOError) -> Self {
Error::IOError {
error: error
}
}
}
impl <E>From<CurlError> for Error<E> {
fn from(error: CurlError) -> Self {
Error::Curl {
error: error
}
}
}
// impl <E:!CurlError>From<E> for Error<E> where E:!CurlError {
// fn from(error: E) -> Self {
// Error::Initialize {
// error: error
// }
// }
// }
|
},
&Error::Initialize {..} => {
None
},
|
random_line_split
|
extern-generic.rs
|
//
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=eager -Zshare-generics=y
#![allow(dead_code)]
#![crate_type="lib"]
// aux-build:cgu_generic_function.rs
extern crate cgu_generic_function;
//~ MONO_ITEM fn user @@ extern_generic[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::user @@ extern_generic-mod1[Internal]
fn
|
() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::mod1::user @@ extern_generic-mod1-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
}
mod mod2 {
use cgu_generic_function;
//~ MONO_ITEM fn mod2::user @@ extern_generic-mod2[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
mod mod3 {
//~ MONO_ITEM fn mod3::non_user @@ extern_generic-mod3[Internal]
fn non_user() {}
}
// Make sure the two generic functions from the extern crate get instantiated
// once for the current crate
//~ MONO_ITEM fn cgu_generic_function::foo::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
//~ MONO_ITEM fn cgu_generic_function::bar::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
|
user
|
identifier_name
|
extern-generic.rs
|
//
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=eager -Zshare-generics=y
#![allow(dead_code)]
#![crate_type="lib"]
// aux-build:cgu_generic_function.rs
extern crate cgu_generic_function;
//~ MONO_ITEM fn user @@ extern_generic[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::user @@ extern_generic-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::mod1::user @@ extern_generic-mod1-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
}
mod mod2 {
use cgu_generic_function;
//~ MONO_ITEM fn mod2::user @@ extern_generic-mod2[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
mod mod3 {
//~ MONO_ITEM fn mod3::non_user @@ extern_generic-mod3[Internal]
fn non_user()
|
}
// Make sure the two generic functions from the extern crate get instantiated
// once for the current crate
//~ MONO_ITEM fn cgu_generic_function::foo::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
//~ MONO_ITEM fn cgu_generic_function::bar::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
|
{}
|
identifier_body
|
extern-generic.rs
|
//
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=eager -Zshare-generics=y
#![allow(dead_code)]
#![crate_type="lib"]
// aux-build:cgu_generic_function.rs
extern crate cgu_generic_function;
//~ MONO_ITEM fn user @@ extern_generic[Internal]
|
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::user @@ extern_generic-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::mod1::user @@ extern_generic-mod1-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
}
mod mod2 {
use cgu_generic_function;
//~ MONO_ITEM fn mod2::user @@ extern_generic-mod2[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
mod mod3 {
//~ MONO_ITEM fn mod3::non_user @@ extern_generic-mod3[Internal]
fn non_user() {}
}
// Make sure the two generic functions from the extern crate get instantiated
// once for the current crate
//~ MONO_ITEM fn cgu_generic_function::foo::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
//~ MONO_ITEM fn cgu_generic_function::bar::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
|
fn user() {
let _ = cgu_generic_function::foo("abc");
}
|
random_line_split
|
others.rs
|
use super::prelude::*;
use stencila_schema::*;
replaceable_struct!(Date, value);
patchable_struct!(
Organization,
// All properties except `id` (as at 2021-11-18)
// Commented out properties have types that do not yet have a `impl Patchable`.
//address,
alternate_names,
//brands,
//contact_points,
departments,
//description,
//funders,
id,
//identifiers,
//images,
legal_name,
//logo,
//members,
name,
parent_organization,
url
);
patchable_struct!(
Person,
// All properties except `id` (as at 2021-11-18)
// Commented out properties have types that do not yet have a `impl Patchable`.
//address,
affiliations,
alternate_names,
//description,
emails,
family_names,
//funders,
given_names,
honorific_prefix,
honorific_suffix,
id,
//identifiers,
//images,
job_title,
member_of,
|
);
|
name,
telephone_numbers,
url
|
random_line_split
|
foo.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(lang_items, no_core, optin_builtin_traits)]
#![no_core]
#[lang="copy"]
trait Copy { }
#[lang="sized"]
trait Sized { }
#[lang = "freeze"]
auto trait Freeze {}
#[lang="start"]
fn start(_main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { 0 }
extern {
fn _foo() -> [u8; 16];
}
fn _main()
|
{
let _a = unsafe { _foo() };
}
|
identifier_body
|
|
foo.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(lang_items, no_core, optin_builtin_traits)]
#![no_core]
#[lang="copy"]
trait Copy { }
#[lang="sized"]
trait Sized { }
#[lang = "freeze"]
auto trait Freeze {}
#[lang="start"]
fn
|
(_main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { 0 }
extern {
fn _foo() -> [u8; 16];
}
fn _main() {
let _a = unsafe { _foo() };
}
|
start
|
identifier_name
|
foo.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(lang_items, no_core, optin_builtin_traits)]
#![no_core]
#[lang="copy"]
trait Copy { }
|
#[lang="sized"]
trait Sized { }
#[lang = "freeze"]
auto trait Freeze {}
#[lang="start"]
fn start(_main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { 0 }
extern {
fn _foo() -> [u8; 16];
}
fn _main() {
let _a = unsafe { _foo() };
}
|
random_line_split
|
|
x86.rs
|
#[repr(C)]
#[derive(Copy)]
pub struct glob_t {
pub gl_pathc: ::size_t,
pub gl_pathv: *mut *mut ::schar_t,
pub gl_offs: ::size_t,
pub gl_flags: ::int_t,
pub gl_closedir: fn(*mut ::void_t, ),
pub gl_readdir: fn(*mut ::void_t, ) -> *mut ::void_t,
pub gl_opendir: fn(*const ::schar_t, ) -> *mut ::void_t,
pub gl_lstat: fn(*const ::schar_t, *mut ::void_t, ) -> ::int_t,
|
}
new!(glob_t);
pub const GLOB_APPEND: ::int_t = (1 << 5);
pub const GLOB_DOOFFS: ::int_t = (1 << 3);
pub const GLOB_ERR: ::int_t = (1 << 0);
pub const GLOB_MARK: ::int_t = (1 << 1);
pub const GLOB_NOCHECK: ::int_t = (1 << 4);
pub const GLOB_NOESCAPE: ::int_t = (1 << 6);
pub const GLOB_NOSORT: ::int_t = (1 << 2);
pub const GLOB_ABORTED: ::int_t = 2;
pub const GLOB_NOMATCH: ::int_t = 3;
pub const GLOB_NOSPACE: ::int_t = 1;
|
pub gl_stat: fn(*const ::schar_t, *mut ::void_t, ) -> ::int_t,
|
random_line_split
|
x86.rs
|
#[repr(C)]
#[derive(Copy)]
pub struct
|
{
pub gl_pathc: ::size_t,
pub gl_pathv: *mut *mut ::schar_t,
pub gl_offs: ::size_t,
pub gl_flags: ::int_t,
pub gl_closedir: fn(*mut ::void_t, ),
pub gl_readdir: fn(*mut ::void_t, ) -> *mut ::void_t,
pub gl_opendir: fn(*const ::schar_t, ) -> *mut ::void_t,
pub gl_lstat: fn(*const ::schar_t, *mut ::void_t, ) -> ::int_t,
pub gl_stat: fn(*const ::schar_t, *mut ::void_t, ) -> ::int_t,
}
new!(glob_t);
pub const GLOB_APPEND: ::int_t = (1 << 5);
pub const GLOB_DOOFFS: ::int_t = (1 << 3);
pub const GLOB_ERR: ::int_t = (1 << 0);
pub const GLOB_MARK: ::int_t = (1 << 1);
pub const GLOB_NOCHECK: ::int_t = (1 << 4);
pub const GLOB_NOESCAPE: ::int_t = (1 << 6);
pub const GLOB_NOSORT: ::int_t = (1 << 2);
pub const GLOB_ABORTED: ::int_t = 2;
pub const GLOB_NOMATCH: ::int_t = 3;
pub const GLOB_NOSPACE: ::int_t = 1;
|
glob_t
|
identifier_name
|
core-uint-to-str.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::uint;
fn
|
() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!(~"", ~"10000000")
} else if args.len() <= 1u {
vec!(~"", ~"100000")
} else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
let x = i.to_str();
println!("{}", x);
}
}
|
main
|
identifier_name
|
core-uint-to-str.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::uint;
fn main()
|
{
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!(~"", ~"10000000")
} else if args.len() <= 1u {
vec!(~"", ~"100000")
} else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
let x = i.to_str();
println!("{}", x);
}
}
|
identifier_body
|
|
core-uint-to-str.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::uint;
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!(~"", ~"10000000")
|
} else if args.len() <= 1u {
vec!(~"", ~"100000")
} else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
let x = i.to_str();
println!("{}", x);
}
}
|
random_line_split
|
|
core-uint-to-str.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::uint;
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!(~"", ~"10000000")
} else if args.len() <= 1u
|
else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
let x = i.to_str();
println!("{}", x);
}
}
|
{
vec!(~"", ~"100000")
}
|
conditional_block
|
parser.rs
|
peg_file! ply_rustpeg("ply.rustpeg");
pub fn parse(s: &str) -> Result<PLY, String> {
let (f, v, mut counted_elems, data) = try!(ply_rustpeg::parse(s));
let mut counter = 0us;
for &mut (count, ref mut elem) in counted_elems.iter_mut() {
//let (count, ref mut elem) = counted_elems.get_mut(i).unwrap();
if data.len() < count + counter
|
elem.data.push_all(&data[counter.. counter + count]);
counter += count;
}
Ok(PLY {format: f, version: v, elements: counted_elems.into_iter().map(|(_,e)|e).collect()})
}
#[derive(Debug, Copy)]
pub enum Format { Ascii }
#[derive(Debug, Copy)]
pub struct Version (u32, u32);
#[derive(Debug)]
pub struct ElementSpec {
pub name: String,
pub props: Vec<PropertySpec>,
pub data: Vec<Vec<String>>, // individual lines of the data
}
impl ElementSpec {
pub fn get_prop(&self, name: String) -> Option<&PropertySpec> {
self.props.iter().filter(|&e| e.name == name).next()
}
}
#[derive(Debug)]
pub struct PropertySpec {
pub name: String,
pub type_: Type,
}
#[derive(Debug,PartialEq)]
pub enum Type {
Char, UChar, Short, UShort, Int, UInt, Float, Double,
List (Box<Type>),
}
#[derive(Debug)]
pub struct PLY {
pub format: Format,
pub version: Version,
pub elements: Vec<ElementSpec>,
}
impl PLY {
pub fn get_elem(&self, name: String) -> Option<&ElementSpec> {
self.elements.iter().filter(|&e| e.name == name).next()
}
}
|
{
return Err(format!("Data section too short."));
}
|
conditional_block
|
parser.rs
|
peg_file! ply_rustpeg("ply.rustpeg");
pub fn parse(s: &str) -> Result<PLY, String> {
let (f, v, mut counted_elems, data) = try!(ply_rustpeg::parse(s));
let mut counter = 0us;
for &mut (count, ref mut elem) in counted_elems.iter_mut() {
//let (count, ref mut elem) = counted_elems.get_mut(i).unwrap();
if data.len() < count + counter {
return Err(format!("Data section too short."));
}
elem.data.push_all(&data[counter.. counter + count]);
counter += count;
}
Ok(PLY {format: f, version: v, elements: counted_elems.into_iter().map(|(_,e)|e).collect()})
}
#[derive(Debug, Copy)]
pub enum Format { Ascii }
#[derive(Debug, Copy)]
pub struct Version (u32, u32);
#[derive(Debug)]
pub struct ElementSpec {
pub name: String,
pub props: Vec<PropertySpec>,
pub data: Vec<Vec<String>>, // individual lines of the data
}
impl ElementSpec {
pub fn get_prop(&self, name: String) -> Option<&PropertySpec> {
self.props.iter().filter(|&e| e.name == name).next()
}
}
#[derive(Debug)]
pub struct PropertySpec {
pub name: String,
pub type_: Type,
}
#[derive(Debug,PartialEq)]
pub enum Type {
Char, UChar, Short, UShort, Int, UInt, Float, Double,
List (Box<Type>),
}
#[derive(Debug)]
pub struct
|
{
pub format: Format,
pub version: Version,
pub elements: Vec<ElementSpec>,
}
impl PLY {
pub fn get_elem(&self, name: String) -> Option<&ElementSpec> {
self.elements.iter().filter(|&e| e.name == name).next()
}
}
|
PLY
|
identifier_name
|
parser.rs
|
peg_file! ply_rustpeg("ply.rustpeg");
pub fn parse(s: &str) -> Result<PLY, String> {
let (f, v, mut counted_elems, data) = try!(ply_rustpeg::parse(s));
let mut counter = 0us;
for &mut (count, ref mut elem) in counted_elems.iter_mut() {
//let (count, ref mut elem) = counted_elems.get_mut(i).unwrap();
if data.len() < count + counter {
return Err(format!("Data section too short."));
}
elem.data.push_all(&data[counter.. counter + count]);
counter += count;
}
Ok(PLY {format: f, version: v, elements: counted_elems.into_iter().map(|(_,e)|e).collect()})
}
#[derive(Debug, Copy)]
pub enum Format { Ascii }
#[derive(Debug, Copy)]
pub struct Version (u32, u32);
#[derive(Debug)]
pub struct ElementSpec {
pub name: String,
pub props: Vec<PropertySpec>,
pub data: Vec<Vec<String>>, // individual lines of the data
}
impl ElementSpec {
pub fn get_prop(&self, name: String) -> Option<&PropertySpec> {
self.props.iter().filter(|&e| e.name == name).next()
}
}
#[derive(Debug)]
pub struct PropertySpec {
pub name: String,
pub type_: Type,
}
#[derive(Debug,PartialEq)]
pub enum Type {
Char, UChar, Short, UShort, Int, UInt, Float, Double,
List (Box<Type>),
}
#[derive(Debug)]
pub struct PLY {
pub format: Format,
pub version: Version,
pub elements: Vec<ElementSpec>,
|
impl PLY {
pub fn get_elem(&self, name: String) -> Option<&ElementSpec> {
self.elements.iter().filter(|&e| e.name == name).next()
}
}
|
}
|
random_line_split
|
macros.rs
|
macro_rules! non_null {
( $obj:expr, $ctx:expr ) => {
if $obj.is_null() {
return Err($crate::errors::ErrorKind::NullPtr($ctx).into());
} else {
$obj
}
}
}
macro_rules! deref {
( $obj:expr, $ctx:expr ) => {
if $obj.is_null() {
return Err($crate::errors::ErrorKind::NullDeref($ctx).into());
} else {
*$obj
}
};
}
macro_rules! jni_method {
( $jnienv:expr, $name:tt ) => ({
trace!("looking up jni method {}", stringify!($name));
let env = $jnienv;
match deref!(deref!(env, "JNIEnv"), "*JNIEnv").$name {
Some(meth) => {
trace!("found jni method");
meth
},
None => {
trace!("jnienv method not defined, returning error");
return Err($crate::errors::Error::from(
$crate::errors::ErrorKind::JNIEnvMethodNotFound(
stringify!($name))).into())},
}
})
}
macro_rules! check_exception {
( $jnienv:expr ) => {
trace!("checking for exception");
#[allow(unused_unsafe)]
let check = unsafe {
jni_unchecked!($jnienv, ExceptionCheck)
} == $crate::sys::JNI_TRUE;
|
trace!("exception found, returning error");
return Err($crate::errors::Error::from(
$crate::errors::ErrorKind::JavaException).into());
}
trace!("no exception found");
}
}
macro_rules! jni_unchecked {
( $jnienv:expr, $name:tt $(, $args:expr )* ) => ({
trace!("calling unchecked jni method: {}", stringify!($name));
let res = jni_method!($jnienv, $name)($jnienv, $($args),*);
res
})
}
macro_rules! jni_call {
( $jnienv:expr, $name:tt $(, $args:expr )* ) => ({
trace!("calling checked jni method: {}", stringify!($name));
#[allow(unused_unsafe)]
unsafe {
trace!("entering unsafe");
let res = jni_method!($jnienv, $name)($jnienv, $($args),*);
check_exception!($jnienv);
trace!("exiting unsafe");
non_null!(res, concat!(stringify!($name), " result")).into()
}
})
}
macro_rules! catch {
( move $b:block ) => {
(move || $b)()
};
( $b:block ) => {
(|| $b)()
};
}
|
if check {
|
random_line_split
|
token.rs
|
),
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
NtMatchers(..) => f.pad("NtMatchers(..)"),
}
}
}
pub fn binop_to_str(o: BinOp) -> StrBuf {
match o {
PLUS => "+".to_strbuf(),
MINUS => "-".to_strbuf(),
STAR => "*".to_strbuf(),
SLASH => "/".to_strbuf(),
PERCENT => "%".to_strbuf(),
CARET => "^".to_strbuf(),
AND => "&".to_strbuf(),
OR => "|".to_strbuf(),
SHL => "<<".to_strbuf(),
SHR => ">>".to_strbuf()
}
}
pub fn to_str(t: &Token) -> StrBuf {
match *t {
EQ => "=".to_strbuf(),
LT => "<".to_strbuf(),
LE => "<=".to_strbuf(),
EQEQ => "==".to_strbuf(),
NE => "!=".to_strbuf(),
GE => ">=".to_strbuf(),
GT => ">".to_strbuf(),
NOT => "!".to_strbuf(),
TILDE => "~".to_strbuf(),
OROR => "||".to_strbuf(),
ANDAND => "&&".to_strbuf(),
BINOP(op) => binop_to_str(op),
BINOPEQ(op) => {
let mut s = binop_to_str(op);
s.push_str("=");
s
}
/* Structural symbols */
AT => "@".to_strbuf(),
DOT => ".".to_strbuf(),
DOTDOT => "..".to_strbuf(),
DOTDOTDOT => "...".to_strbuf(),
COMMA => ",".to_strbuf(),
SEMI => ";".to_strbuf(),
COLON => ":".to_strbuf(),
MOD_SEP => "::".to_strbuf(),
RARROW => "->".to_strbuf(),
LARROW => "<-".to_strbuf(),
DARROW => "<->".to_strbuf(),
FAT_ARROW => "=>".to_strbuf(),
LPAREN => "(".to_strbuf(),
RPAREN => ")".to_strbuf(),
LBRACKET => "[".to_strbuf(),
RBRACKET => "]".to_strbuf(),
LBRACE => "{".to_strbuf(),
RBRACE => "}".to_strbuf(),
POUND => "#".to_strbuf(),
DOLLAR => "$".to_strbuf(),
/* Literals */
LIT_CHAR(c) => {
let mut res = StrBuf::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { i.to_str().to_strbuf() }
LIT_FLOAT(s, t) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body.push_str(ast_util::float_ty_to_str(t).as_slice());
body
}
LIT_FLOAT_UNSUFFIXED(s) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body
}
LIT_STR(s) => {
(format!("\"{}\"", get_ident(s).get().escape_default())).to_strbuf()
}
LIT_STR_RAW(s, n) => {
(format!("r{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=get_ident(s))).to_strbuf()
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_strbuf(),
LIFETIME(s) => {
(format!("'{}", get_ident(s))).to_strbuf()
}
UNDERSCORE => "_".to_strbuf(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_strbuf(),
EOF => "<eof>".to_strbuf(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(e) => ::print::pprust::expr_to_str(e),
&NtMeta(e) => ::print::pprust::meta_item_to_str(e),
_ => {
let mut s = "an interpolated ".to_strbuf();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
NtStmt(..) => s.push_str("statement"),
NtPat(..) => s.push_str("pattern"),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
NtTy(..) => s.push_str("type"),
NtIdent(..) => s.push_str("identifier"),
NtPath(..) => s.push_str("path"),
NtTT(..) => s.push_str("tt"),
NtMatchers(..) => s.push_str("matcher sequence")
};
s
}
}
}
}
}
pub fn can_begin_expr(t: &Token) -> bool {
match *t {
LPAREN => true,
LBRACE => true,
LBRACKET => true,
IDENT(_, _) => true,
UNDERSCORE => true,
TILDE => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
POUND => true,
AT => true,
NOT => true,
BINOP(MINUS) => true,
BINOP(STAR) => true,
BINOP(AND) => true,
BINOP(OR) => true, // in lambda syntax
OROR => true, // in lambda syntax
MOD_SEP => true,
INTERPOLATED(NtExpr(..))
| INTERPOLATED(NtIdent(..))
| INTERPOLATED(NtBlock(..))
| INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
/// Returns the matching close delimiter if this is an open delimiter,
/// otherwise `None`.
pub fn close_delimiter_for(t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
_ => false
}
}
pub fn is_ident(t: &Token) -> bool {
match *t { IDENT(_, _) => true, _ => false }
}
pub fn is_ident_or_path(t: &Token) -> bool {
match *t {
IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
pub fn is_plain_ident(t: &Token) -> bool {
match *t { IDENT(_, false) => true, _ => false }
}
pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
pub mod special_idents {
use ast::Ident;
$( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast::Ident;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_ident(&self) -> Ident {
match *self {
$( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
$( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_ident(), and in static
// constants below.
|
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME, self_, "self");
(super::STATIC_KEYWORD_NAME, statik, "static");
// for matcher NTs
(3, tt, "tt");
(4, matchers, "matchers");
// outside of libsyntax
(5, clownshoe_abi, "__rust_abi");
(6, opaque, "<opaque>");
(7, unnamed_field, "<unnamed_field>");
(8, type_self, "Self");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(9, As, "as");
(10, Break, "break");
(11, Const, "const");
(12, Crate, "crate");
(13, Else, "else");
(14, Enum, "enum");
(15, Extern, "extern");
(16, False, "false");
(17, Fn, "fn");
(18, For, "for");
(19, If, "if");
(20, Impl, "impl");
(21, In, "in");
(22, Let, "let");
(23, Loop, "loop");
(24, Match, "match");
(25, Mod, "mod");
(26, Mut, "mut");
(27, Once, "once");
(28, Pub, "pub");
(29, Ref, "ref");
(30, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME, Static, "static");
(super::SELF_KEYWORD_NAME, Self, "self");
(31, Struct, "struct");
(32, Super, "super");
(33, True, "true");
(34, Trait, "trait");
(35, Type, "type");
(36, Unsafe, "unsafe");
(37, Use, "use");
(38, Virtual, "virtual");
(39, While, "while");
(40, Continue, "continue");
(41, Proc, "proc");
(42, Box, "box");
'reserved:
(43, Alignof, "alignof");
(44, Be, "be");
(45, Offsetof, "offsetof");
(46, Priv, "priv");
(47, Pure, "pure");
(48, Sizeof, "sizeof");
(49, Typeof, "typeof");
(50, Unsized, "unsized");
(51, Yield, "yield");
(52, Do, "do");
}
}
/**
* Maps a token to a record specifying the corresponding binary
* operator
*/
pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
match *tok {
BINOP(STAR) => Some(ast::BiMul),
BINOP(SLASH) => Some(ast::BiDiv),
BINOP(PERCENT) => Some(ast::BiRem),
BINOP(PLUS) => Some(ast::BiAdd),
BINOP(MINUS) => Some(ast::BiSub),
BINOP(SHL) => Some(ast::BiShl),
BINOP(SHR) => Some(ast::BiShr),
BINOP(AND) => Some(ast::BiBitAnd),
BINOP(CARET) => Some(ast::BiBitXor),
BINOP(OR) => Some(ast::BiBitOr),
LT => Some(ast::BiLt),
LE => Some(ast::BiLe),
GE => Some(ast::BiGe),
GT => Some(ast::BiGt),
EQEQ => Some(ast::BiEq),
NE => Some(ast::BiNe),
ANDAND => Some(ast::BiAnd),
OROR => Some(ast::BiOr),
_ => None
}
}
// looks like we can get rid of this completely...
pub type IdentInterner = StrInterner;
// if an interner exists in TLS, return it. Otherwise, prepare a
// fresh one.
// FIXME(eddyb) #8726 This should probably use a task-local reference.
pub fn get_ident_interner() -> Rc<IdentInterner> {
local_data_key!(key: Rc<::parse::token::IdentInterner>)
match key.get() {
Some(interner) => interner.clone(),
None => {
let interner = Rc::new(mk_fresh_ident_interner());
key.replace(Some(interner.clone()));
interner
}
}
}
/// Represents a string stored in the task-local interner. Because the
/// interner lives for the life of the task, this can be safely treated as an
/// immortal string, as long as it never crosses between tasks.
///
/// FIXME(pcwalton
|
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
|
random_line_split
|
token.rs
|
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
NtMatchers(..) => f.pad("NtMatchers(..)"),
}
}
}
pub fn binop_to_str(o: BinOp) -> StrBuf {
match o {
PLUS => "+".to_strbuf(),
MINUS => "-".to_strbuf(),
STAR => "*".to_strbuf(),
SLASH => "/".to_strbuf(),
PERCENT => "%".to_strbuf(),
CARET => "^".to_strbuf(),
AND => "&".to_strbuf(),
OR => "|".to_strbuf(),
SHL => "<<".to_strbuf(),
SHR => ">>".to_strbuf()
}
}
pub fn to_str(t: &Token) -> StrBuf {
match *t {
EQ => "=".to_strbuf(),
LT => "<".to_strbuf(),
LE => "<=".to_strbuf(),
EQEQ => "==".to_strbuf(),
NE => "!=".to_strbuf(),
GE => ">=".to_strbuf(),
GT => ">".to_strbuf(),
NOT => "!".to_strbuf(),
TILDE => "~".to_strbuf(),
OROR => "||".to_strbuf(),
ANDAND => "&&".to_strbuf(),
BINOP(op) => binop_to_str(op),
BINOPEQ(op) => {
let mut s = binop_to_str(op);
s.push_str("=");
s
}
/* Structural symbols */
AT => "@".to_strbuf(),
DOT => ".".to_strbuf(),
DOTDOT => "..".to_strbuf(),
DOTDOTDOT => "...".to_strbuf(),
COMMA => ",".to_strbuf(),
SEMI => ";".to_strbuf(),
COLON => ":".to_strbuf(),
MOD_SEP => "::".to_strbuf(),
RARROW => "->".to_strbuf(),
LARROW => "<-".to_strbuf(),
DARROW => "<->".to_strbuf(),
FAT_ARROW => "=>".to_strbuf(),
LPAREN => "(".to_strbuf(),
RPAREN => ")".to_strbuf(),
LBRACKET => "[".to_strbuf(),
RBRACKET => "]".to_strbuf(),
LBRACE => "{".to_strbuf(),
RBRACE => "}".to_strbuf(),
POUND => "#".to_strbuf(),
DOLLAR => "$".to_strbuf(),
/* Literals */
LIT_CHAR(c) => {
let mut res = StrBuf::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { i.to_str().to_strbuf() }
LIT_FLOAT(s, t) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body.push_str(ast_util::float_ty_to_str(t).as_slice());
body
}
LIT_FLOAT_UNSUFFIXED(s) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body
}
LIT_STR(s) => {
(format!("\"{}\"", get_ident(s).get().escape_default())).to_strbuf()
}
LIT_STR_RAW(s, n) => {
(format!("r{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=get_ident(s))).to_strbuf()
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_strbuf(),
LIFETIME(s) => {
(format!("'{}", get_ident(s))).to_strbuf()
}
UNDERSCORE => "_".to_strbuf(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_strbuf(),
EOF => "<eof>".to_strbuf(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(e) => ::print::pprust::expr_to_str(e),
&NtMeta(e) => ::print::pprust::meta_item_to_str(e),
_ => {
let mut s = "an interpolated ".to_strbuf();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
NtStmt(..) => s.push_str("statement"),
NtPat(..) => s.push_str("pattern"),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
NtTy(..) => s.push_str("type"),
NtIdent(..) => s.push_str("identifier"),
NtPath(..) => s.push_str("path"),
NtTT(..) => s.push_str("tt"),
NtMatchers(..) => s.push_str("matcher sequence")
};
s
}
}
}
}
}
pub fn can_begin_expr(t: &Token) -> bool {
match *t {
LPAREN => true,
LBRACE => true,
LBRACKET => true,
IDENT(_, _) => true,
UNDERSCORE => true,
TILDE => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
POUND => true,
AT => true,
NOT => true,
BINOP(MINUS) => true,
BINOP(STAR) => true,
BINOP(AND) => true,
BINOP(OR) => true, // in lambda syntax
OROR => true, // in lambda syntax
MOD_SEP => true,
INTERPOLATED(NtExpr(..))
| INTERPOLATED(NtIdent(..))
| INTERPOLATED(NtBlock(..))
| INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
/// Returns the matching close delimiter if this is an open delimiter,
/// otherwise `None`.
pub fn
|
(t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
_ => false
}
}
pub fn is_ident(t: &Token) -> bool {
match *t { IDENT(_, _) => true, _ => false }
}
pub fn is_ident_or_path(t: &Token) -> bool {
match *t {
IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
pub fn is_plain_ident(t: &Token) -> bool {
match *t { IDENT(_, false) => true, _ => false }
}
pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
pub mod special_idents {
use ast::Ident;
$( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast::Ident;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_ident(&self) -> Ident {
match *self {
$( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
$( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_ident(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME, self_, "self");
(super::STATIC_KEYWORD_NAME, statik, "static");
// for matcher NTs
(3, tt, "tt");
(4, matchers, "matchers");
// outside of libsyntax
(5, clownshoe_abi, "__rust_abi");
(6, opaque, "<opaque>");
(7, unnamed_field, "<unnamed_field>");
(8, type_self, "Self");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(9, As, "as");
(10, Break, "break");
(11, Const, "const");
(12, Crate, "crate");
(13, Else, "else");
(14, Enum, "enum");
(15, Extern, "extern");
(16, False, "false");
(17, Fn, "fn");
(18, For, "for");
(19, If, "if");
(20, Impl, "impl");
(21, In, "in");
(22, Let, "let");
(23, Loop, "loop");
(24, Match, "match");
(25, Mod, "mod");
(26, Mut, "mut");
(27, Once, "once");
(28, Pub, "pub");
(29, Ref, "ref");
(30, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME, Static, "static");
(super::SELF_KEYWORD_NAME, Self, "self");
(31, Struct, "struct");
(32, Super, "super");
(33, True, "true");
(34, Trait, "trait");
(35, Type, "type");
(36, Unsafe, "unsafe");
(37, Use, "use");
(38, Virtual, "virtual");
(39, While, "while");
(40, Continue, "continue");
(41, Proc, "proc");
(42, Box, "box");
'reserved:
(43, Alignof, "alignof");
(44, Be, "be");
(45, Offsetof, "offsetof");
(46, Priv, "priv");
(47, Pure, "pure");
(48, Sizeof, "sizeof");
(49, Typeof, "typeof");
(50, Unsized, "unsized");
(51, Yield, "yield");
(52, Do, "do");
}
}
/**
* Maps a token to a record specifying the corresponding binary
* operator
*/
pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
match *tok {
BINOP(STAR) => Some(ast::BiMul),
BINOP(SLASH) => Some(ast::BiDiv),
BINOP(PERCENT) => Some(ast::BiRem),
BINOP(PLUS) => Some(ast::BiAdd),
BINOP(MINUS) => Some(ast::BiSub),
BINOP(SHL) => Some(ast::BiShl),
BINOP(SHR) => Some(ast::BiShr),
BINOP(AND) => Some(ast::BiBitAnd),
BINOP(CARET) => Some(ast::BiBitXor),
BINOP(OR) => Some(ast::BiBitOr),
LT => Some(ast::BiLt),
LE => Some(ast::BiLe),
GE => Some(ast::BiGe),
GT => Some(ast::BiGt),
EQEQ => Some(ast::BiEq),
NE => Some(ast::BiNe),
ANDAND => Some(ast::BiAnd),
OROR => Some(ast::BiOr),
_ => None
}
}
// looks like we can get rid of this completely...
pub type IdentInterner = StrInterner;
// if an interner exists in TLS, return it. Otherwise, prepare a
// fresh one.
// FIXME(eddyb) #8726 This should probably use a task-local reference.
pub fn get_ident_interner() -> Rc<IdentInterner> {
local_data_key!(key: Rc<::parse::token::IdentInterner>)
match key.get() {
Some(interner) => interner.clone(),
None => {
let interner = Rc::new(mk_fresh_ident_interner());
key.replace(Some(interner.clone()));
interner
}
}
}
/// Represents a string stored in the task-local interner. Because the
/// interner lives for the life of the task, this can be safely treated as an
/// immortal string, as long as it never crosses between tasks.
///
/// FIXME(pc
|
close_delimiter_for
|
identifier_name
|
token.rs
|
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
NtMatchers(..) => f.pad("NtMatchers(..)"),
}
}
}
pub fn binop_to_str(o: BinOp) -> StrBuf {
match o {
PLUS => "+".to_strbuf(),
MINUS => "-".to_strbuf(),
STAR => "*".to_strbuf(),
SLASH => "/".to_strbuf(),
PERCENT => "%".to_strbuf(),
CARET => "^".to_strbuf(),
AND => "&".to_strbuf(),
OR => "|".to_strbuf(),
SHL => "<<".to_strbuf(),
SHR => ">>".to_strbuf()
}
}
pub fn to_str(t: &Token) -> StrBuf {
match *t {
EQ => "=".to_strbuf(),
LT => "<".to_strbuf(),
LE => "<=".to_strbuf(),
EQEQ => "==".to_strbuf(),
NE => "!=".to_strbuf(),
GE => ">=".to_strbuf(),
GT => ">".to_strbuf(),
NOT => "!".to_strbuf(),
TILDE => "~".to_strbuf(),
OROR => "||".to_strbuf(),
ANDAND => "&&".to_strbuf(),
BINOP(op) => binop_to_str(op),
BINOPEQ(op) => {
let mut s = binop_to_str(op);
s.push_str("=");
s
}
/* Structural symbols */
AT => "@".to_strbuf(),
DOT => ".".to_strbuf(),
DOTDOT => "..".to_strbuf(),
DOTDOTDOT => "...".to_strbuf(),
COMMA => ",".to_strbuf(),
SEMI => ";".to_strbuf(),
COLON => ":".to_strbuf(),
MOD_SEP => "::".to_strbuf(),
RARROW => "->".to_strbuf(),
LARROW => "<-".to_strbuf(),
DARROW => "<->".to_strbuf(),
FAT_ARROW => "=>".to_strbuf(),
LPAREN => "(".to_strbuf(),
RPAREN => ")".to_strbuf(),
LBRACKET => "[".to_strbuf(),
RBRACKET => "]".to_strbuf(),
LBRACE => "{".to_strbuf(),
RBRACE => "}".to_strbuf(),
POUND => "#".to_strbuf(),
DOLLAR => "$".to_strbuf(),
/* Literals */
LIT_CHAR(c) =>
|
LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { i.to_str().to_strbuf() }
LIT_FLOAT(s, t) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body.push_str(ast_util::float_ty_to_str(t).as_slice());
body
}
LIT_FLOAT_UNSUFFIXED(s) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body
}
LIT_STR(s) => {
(format!("\"{}\"", get_ident(s).get().escape_default())).to_strbuf()
}
LIT_STR_RAW(s, n) => {
(format!("r{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=get_ident(s))).to_strbuf()
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_strbuf(),
LIFETIME(s) => {
(format!("'{}", get_ident(s))).to_strbuf()
}
UNDERSCORE => "_".to_strbuf(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_strbuf(),
EOF => "<eof>".to_strbuf(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(e) => ::print::pprust::expr_to_str(e),
&NtMeta(e) => ::print::pprust::meta_item_to_str(e),
_ => {
let mut s = "an interpolated ".to_strbuf();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
NtStmt(..) => s.push_str("statement"),
NtPat(..) => s.push_str("pattern"),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
NtTy(..) => s.push_str("type"),
NtIdent(..) => s.push_str("identifier"),
NtPath(..) => s.push_str("path"),
NtTT(..) => s.push_str("tt"),
NtMatchers(..) => s.push_str("matcher sequence")
};
s
}
}
}
}
}
pub fn can_begin_expr(t: &Token) -> bool {
match *t {
LPAREN => true,
LBRACE => true,
LBRACKET => true,
IDENT(_, _) => true,
UNDERSCORE => true,
TILDE => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
POUND => true,
AT => true,
NOT => true,
BINOP(MINUS) => true,
BINOP(STAR) => true,
BINOP(AND) => true,
BINOP(OR) => true, // in lambda syntax
OROR => true, // in lambda syntax
MOD_SEP => true,
INTERPOLATED(NtExpr(..))
| INTERPOLATED(NtIdent(..))
| INTERPOLATED(NtBlock(..))
| INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
/// Returns the matching close delimiter if this is an open delimiter,
/// otherwise `None`.
pub fn close_delimiter_for(t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
_ => false
}
}
pub fn is_ident(t: &Token) -> bool {
match *t { IDENT(_, _) => true, _ => false }
}
pub fn is_ident_or_path(t: &Token) -> bool {
match *t {
IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
pub fn is_plain_ident(t: &Token) -> bool {
match *t { IDENT(_, false) => true, _ => false }
}
pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
pub mod special_idents {
use ast::Ident;
$( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast::Ident;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_ident(&self) -> Ident {
match *self {
$( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
$( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_ident(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME, self_, "self");
(super::STATIC_KEYWORD_NAME, statik, "static");
// for matcher NTs
(3, tt, "tt");
(4, matchers, "matchers");
// outside of libsyntax
(5, clownshoe_abi, "__rust_abi");
(6, opaque, "<opaque>");
(7, unnamed_field, "<unnamed_field>");
(8, type_self, "Self");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(9, As, "as");
(10, Break, "break");
(11, Const, "const");
(12, Crate, "crate");
(13, Else, "else");
(14, Enum, "enum");
(15, Extern, "extern");
(16, False, "false");
(17, Fn, "fn");
(18, For, "for");
(19, If, "if");
(20, Impl, "impl");
(21, In, "in");
(22, Let, "let");
(23, Loop, "loop");
(24, Match, "match");
(25, Mod, "mod");
(26, Mut, "mut");
(27, Once, "once");
(28, Pub, "pub");
(29, Ref, "ref");
(30, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME, Static, "static");
(super::SELF_KEYWORD_NAME, Self, "self");
(31, Struct, "struct");
(32, Super, "super");
(33, True, "true");
(34, Trait, "trait");
(35, Type, "type");
(36, Unsafe, "unsafe");
(37, Use, "use");
(38, Virtual, "virtual");
(39, While, "while");
(40, Continue, "continue");
(41, Proc, "proc");
(42, Box, "box");
'reserved:
(43, Alignof, "alignof");
(44, Be, "be");
(45, Offsetof, "offsetof");
(46, Priv, "priv");
(47, Pure, "pure");
(48, Sizeof, "sizeof");
(49, Typeof, "typeof");
(50, Unsized, "unsized");
(51, Yield, "yield");
(52, Do, "do");
}
}
/**
* Maps a token to a record specifying the corresponding binary
* operator
*/
pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
match *tok {
BINOP(STAR) => Some(ast::BiMul),
BINOP(SLASH) => Some(ast::BiDiv),
BINOP(PERCENT) => Some(ast::BiRem),
BINOP(PLUS) => Some(ast::BiAdd),
BINOP(MINUS) => Some(ast::BiSub),
BINOP(SHL) => Some(ast::BiShl),
BINOP(SHR) => Some(ast::BiShr),
BINOP(AND) => Some(ast::BiBitAnd),
BINOP(CARET) => Some(ast::BiBitXor),
BINOP(OR) => Some(ast::BiBitOr),
LT => Some(ast::BiLt),
LE => Some(ast::BiLe),
GE => Some(ast::BiGe),
GT => Some(ast::BiGt),
EQEQ => Some(ast::BiEq),
NE => Some(ast::BiNe),
ANDAND => Some(ast::BiAnd),
OROR => Some(ast::BiOr),
_ => None
}
}
// looks like we can get rid of this completely...
pub type IdentInterner = StrInterner;
// if an interner exists in TLS, return it. Otherwise, prepare a
// fresh one.
// FIXME(eddyb) #8726 This should probably use a task-local reference.
pub fn get_ident_interner() -> Rc<IdentInterner> {
local_data_key!(key: Rc<::parse::token::IdentInterner>)
match key.get() {
Some(interner) => interner.clone(),
None => {
let interner = Rc::new(mk_fresh_ident_interner());
key.replace(Some(interner.clone()));
interner
}
}
}
/// Represents a string stored in the task-local interner. Because the
/// interner lives for the life of the task, this can be safely treated as an
/// immortal string, as long as it never crosses between tasks.
///
/// FIXME(pc
|
{
let mut res = StrBuf::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
|
conditional_block
|
token.rs
|
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
NtMatchers(..) => f.pad("NtMatchers(..)"),
}
}
}
pub fn binop_to_str(o: BinOp) -> StrBuf
|
pub fn to_str(t: &Token) -> StrBuf {
match *t {
EQ => "=".to_strbuf(),
LT => "<".to_strbuf(),
LE => "<=".to_strbuf(),
EQEQ => "==".to_strbuf(),
NE => "!=".to_strbuf(),
GE => ">=".to_strbuf(),
GT => ">".to_strbuf(),
NOT => "!".to_strbuf(),
TILDE => "~".to_strbuf(),
OROR => "||".to_strbuf(),
ANDAND => "&&".to_strbuf(),
BINOP(op) => binop_to_str(op),
BINOPEQ(op) => {
let mut s = binop_to_str(op);
s.push_str("=");
s
}
/* Structural symbols */
AT => "@".to_strbuf(),
DOT => ".".to_strbuf(),
DOTDOT => "..".to_strbuf(),
DOTDOTDOT => "...".to_strbuf(),
COMMA => ",".to_strbuf(),
SEMI => ";".to_strbuf(),
COLON => ":".to_strbuf(),
MOD_SEP => "::".to_strbuf(),
RARROW => "->".to_strbuf(),
LARROW => "<-".to_strbuf(),
DARROW => "<->".to_strbuf(),
FAT_ARROW => "=>".to_strbuf(),
LPAREN => "(".to_strbuf(),
RPAREN => ")".to_strbuf(),
LBRACKET => "[".to_strbuf(),
RBRACKET => "]".to_strbuf(),
LBRACE => "{".to_strbuf(),
RBRACE => "}".to_strbuf(),
POUND => "#".to_strbuf(),
DOLLAR => "$".to_strbuf(),
/* Literals */
LIT_CHAR(c) => {
let mut res = StrBuf::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { i.to_str().to_strbuf() }
LIT_FLOAT(s, t) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body.push_str(ast_util::float_ty_to_str(t).as_slice());
body
}
LIT_FLOAT_UNSUFFIXED(s) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body
}
LIT_STR(s) => {
(format!("\"{}\"", get_ident(s).get().escape_default())).to_strbuf()
}
LIT_STR_RAW(s, n) => {
(format!("r{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=get_ident(s))).to_strbuf()
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_strbuf(),
LIFETIME(s) => {
(format!("'{}", get_ident(s))).to_strbuf()
}
UNDERSCORE => "_".to_strbuf(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_strbuf(),
EOF => "<eof>".to_strbuf(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(e) => ::print::pprust::expr_to_str(e),
&NtMeta(e) => ::print::pprust::meta_item_to_str(e),
_ => {
let mut s = "an interpolated ".to_strbuf();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
NtStmt(..) => s.push_str("statement"),
NtPat(..) => s.push_str("pattern"),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
NtTy(..) => s.push_str("type"),
NtIdent(..) => s.push_str("identifier"),
NtPath(..) => s.push_str("path"),
NtTT(..) => s.push_str("tt"),
NtMatchers(..) => s.push_str("matcher sequence")
};
s
}
}
}
}
}
pub fn can_begin_expr(t: &Token) -> bool {
match *t {
LPAREN => true,
LBRACE => true,
LBRACKET => true,
IDENT(_, _) => true,
UNDERSCORE => true,
TILDE => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
POUND => true,
AT => true,
NOT => true,
BINOP(MINUS) => true,
BINOP(STAR) => true,
BINOP(AND) => true,
BINOP(OR) => true, // in lambda syntax
OROR => true, // in lambda syntax
MOD_SEP => true,
INTERPOLATED(NtExpr(..))
| INTERPOLATED(NtIdent(..))
| INTERPOLATED(NtBlock(..))
| INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
/// Returns the matching close delimiter if this is an open delimiter,
/// otherwise `None`.
pub fn close_delimiter_for(t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
_ => false
}
}
pub fn is_ident(t: &Token) -> bool {
match *t { IDENT(_, _) => true, _ => false }
}
pub fn is_ident_or_path(t: &Token) -> bool {
match *t {
IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
pub fn is_plain_ident(t: &Token) -> bool {
match *t { IDENT(_, false) => true, _ => false }
}
pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
pub mod special_idents {
use ast::Ident;
$( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast::Ident;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_ident(&self) -> Ident {
match *self {
$( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
$( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_ident(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME, self_, "self");
(super::STATIC_KEYWORD_NAME, statik, "static");
// for matcher NTs
(3, tt, "tt");
(4, matchers, "matchers");
// outside of libsyntax
(5, clownshoe_abi, "__rust_abi");
(6, opaque, "<opaque>");
(7, unnamed_field, "<unnamed_field>");
(8, type_self, "Self");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(9, As, "as");
(10, Break, "break");
(11, Const, "const");
(12, Crate, "crate");
(13, Else, "else");
(14, Enum, "enum");
(15, Extern, "extern");
(16, False, "false");
(17, Fn, "fn");
(18, For, "for");
(19, If, "if");
(20, Impl, "impl");
(21, In, "in");
(22, Let, "let");
(23, Loop, "loop");
(24, Match, "match");
(25, Mod, "mod");
(26, Mut, "mut");
(27, Once, "once");
(28, Pub, "pub");
(29, Ref, "ref");
(30, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME, Static, "static");
(super::SELF_KEYWORD_NAME, Self, "self");
(31, Struct, "struct");
(32, Super, "super");
(33, True, "true");
(34, Trait, "trait");
(35, Type, "type");
(36, Unsafe, "unsafe");
(37, Use, "use");
(38, Virtual, "virtual");
(39, While, "while");
(40, Continue, "continue");
(41, Proc, "proc");
(42, Box, "box");
'reserved:
(43, Alignof, "alignof");
(44, Be, "be");
(45, Offsetof, "offsetof");
(46, Priv, "priv");
(47, Pure, "pure");
(48, Sizeof, "sizeof");
(49, Typeof, "typeof");
(50, Unsized, "unsized");
(51, Yield, "yield");
(52, Do, "do");
}
}
/**
* Maps a token to a record specifying the corresponding binary
* operator
*/
pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
match *tok {
BINOP(STAR) => Some(ast::BiMul),
BINOP(SLASH) => Some(ast::BiDiv),
BINOP(PERCENT) => Some(ast::BiRem),
BINOP(PLUS) => Some(ast::BiAdd),
BINOP(MINUS) => Some(ast::BiSub),
BINOP(SHL) => Some(ast::BiShl),
BINOP(SHR) => Some(ast::BiShr),
BINOP(AND) => Some(ast::BiBitAnd),
BINOP(CARET) => Some(ast::BiBitXor),
BINOP(OR) => Some(ast::BiBitOr),
LT => Some(ast::BiLt),
LE => Some(ast::BiLe),
GE => Some(ast::BiGe),
GT => Some(ast::BiGt),
EQEQ => Some(ast::BiEq),
NE => Some(ast::BiNe),
ANDAND => Some(ast::BiAnd),
OROR => Some(ast::BiOr),
_ => None
}
}
// looks like we can get rid of this completely...
pub type IdentInterner = StrInterner;
// if an interner exists in TLS, return it. Otherwise, prepare a
// fresh one.
// FIXME(eddyb) #8726 This should probably use a task-local reference.
pub fn get_ident_interner() -> Rc<IdentInterner> {
local_data_key!(key: Rc<::parse::token::IdentInterner>)
match key.get() {
Some(interner) => interner.clone(),
None => {
let interner = Rc::new(mk_fresh_ident_interner());
key.replace(Some(interner.clone()));
interner
}
}
}
/// Represents a string stored in the task-local interner. Because the
/// interner lives for the life of the task, this can be safely treated as an
/// immortal string, as long as it never crosses between tasks.
///
/// FIXME(pc
|
{
match o {
PLUS => "+".to_strbuf(),
MINUS => "-".to_strbuf(),
STAR => "*".to_strbuf(),
SLASH => "/".to_strbuf(),
PERCENT => "%".to_strbuf(),
CARET => "^".to_strbuf(),
AND => "&".to_strbuf(),
OR => "|".to_strbuf(),
SHL => "<<".to_strbuf(),
SHR => ">>".to_strbuf()
}
}
|
identifier_body
|
tuple-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print no_padding16
// gdb-check:$1 = {10000, -10001}
// gdb-command:print no_padding32
// gdb-check:$2 = {-10002, -10003.5, 10004}
// gdb-command:print no_padding64
// gdb-check:$3 = {-10005.5, 10006, 10007}
// gdb-command:print no_padding163264
// gdb-check:$4 = {-10008, 10009, 10010, 10011}
// gdb-command:print internal_padding
// gdb-check:$5 = {10012, -10013}
// gdb-command:print padding_at_end
// gdb-check:$6 = {-10014, 10015}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print no_padding16
// lldb-check:[...]$0 = NoPadding16(10000, -10001)
// lldb-command:print no_padding32
// lldb-check:[...]$1 = NoPadding32(-10002, -10003.5, 10004)
// lldb-command:print no_padding64
// lldb-check:[...]$2 = NoPadding64(-10005.5, 10006, 10007)
// lldb-command:print no_padding163264
// lldb-check:[...]$3 = NoPadding163264(-10008, 10009, 10010, 10011)
// lldb-command:print internal_padding
// lldb-check:[...]$4 = InternalPadding(10012, -10013)
// lldb-command:print padding_at_end
// lldb-check:[...]$5 = PaddingAtEnd(-10014, 10015)
// This test case mainly makes sure that no field names are generated for tuple structs (as opposed
// to all fields having the name "<unnamed_field>"). Otherwise they are handled the same a normal
// structs.
#![omit_gdb_pretty_printer_section]
struct NoPadding16(u16, i16);
struct NoPadding32(i32, f32, u32);
struct NoPadding64(f64, i64, u64);
struct NoPadding163264(i16, u16, i32, u64);
struct InternalPadding(u16, i64);
struct PaddingAtEnd(i64, u16);
fn
|
() {
let no_padding16 = NoPadding16(10000, -10001);
let no_padding32 = NoPadding32(-10002, -10003.5, 10004);
let no_padding64 = NoPadding64(-10005.5, 10006, 10007);
let no_padding163264 = NoPadding163264(-10008, 10009, 10010, 10011);
let internal_padding = InternalPadding(10012, -10013);
let padding_at_end = PaddingAtEnd(-10014, 10015);
zzz(); // #break
}
fn zzz() {()}
|
main
|
identifier_name
|
tuple-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print no_padding16
// gdb-check:$1 = {10000, -10001}
// gdb-command:print no_padding32
// gdb-check:$2 = {-10002, -10003.5, 10004}
// gdb-command:print no_padding64
// gdb-check:$3 = {-10005.5, 10006, 10007}
// gdb-command:print no_padding163264
// gdb-check:$4 = {-10008, 10009, 10010, 10011}
// gdb-command:print internal_padding
// gdb-check:$5 = {10012, -10013}
// gdb-command:print padding_at_end
// gdb-check:$6 = {-10014, 10015}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print no_padding16
// lldb-check:[...]$0 = NoPadding16(10000, -10001)
// lldb-command:print no_padding32
// lldb-check:[...]$1 = NoPadding32(-10002, -10003.5, 10004)
// lldb-command:print no_padding64
// lldb-check:[...]$2 = NoPadding64(-10005.5, 10006, 10007)
// lldb-command:print no_padding163264
// lldb-check:[...]$3 = NoPadding163264(-10008, 10009, 10010, 10011)
// lldb-command:print internal_padding
// lldb-check:[...]$4 = InternalPadding(10012, -10013)
// lldb-command:print padding_at_end
// lldb-check:[...]$5 = PaddingAtEnd(-10014, 10015)
// This test case mainly makes sure that no field names are generated for tuple structs (as opposed
// to all fields having the name "<unnamed_field>"). Otherwise they are handled the same a normal
// structs.
#![omit_gdb_pretty_printer_section]
struct NoPadding16(u16, i16);
struct NoPadding32(i32, f32, u32);
struct NoPadding64(f64, i64, u64);
struct NoPadding163264(i16, u16, i32, u64);
struct InternalPadding(u16, i64);
struct PaddingAtEnd(i64, u16);
fn main()
|
fn zzz() {()}
|
{
let no_padding16 = NoPadding16(10000, -10001);
let no_padding32 = NoPadding32(-10002, -10003.5, 10004);
let no_padding64 = NoPadding64(-10005.5, 10006, 10007);
let no_padding163264 = NoPadding163264(-10008, 10009, 10010, 10011);
let internal_padding = InternalPadding(10012, -10013);
let padding_at_end = PaddingAtEnd(-10014, 10015);
zzz(); // #break
}
|
identifier_body
|
tuple-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print no_padding16
// gdb-check:$1 = {10000, -10001}
// gdb-command:print no_padding32
// gdb-check:$2 = {-10002, -10003.5, 10004}
// gdb-command:print no_padding64
// gdb-check:$3 = {-10005.5, 10006, 10007}
// gdb-command:print no_padding163264
|
// gdb-check:$5 = {10012, -10013}
// gdb-command:print padding_at_end
// gdb-check:$6 = {-10014, 10015}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print no_padding16
// lldb-check:[...]$0 = NoPadding16(10000, -10001)
// lldb-command:print no_padding32
// lldb-check:[...]$1 = NoPadding32(-10002, -10003.5, 10004)
// lldb-command:print no_padding64
// lldb-check:[...]$2 = NoPadding64(-10005.5, 10006, 10007)
// lldb-command:print no_padding163264
// lldb-check:[...]$3 = NoPadding163264(-10008, 10009, 10010, 10011)
// lldb-command:print internal_padding
// lldb-check:[...]$4 = InternalPadding(10012, -10013)
// lldb-command:print padding_at_end
// lldb-check:[...]$5 = PaddingAtEnd(-10014, 10015)
// This test case mainly makes sure that no field names are generated for tuple structs (as opposed
// to all fields having the name "<unnamed_field>"). Otherwise they are handled the same a normal
// structs.
#![omit_gdb_pretty_printer_section]
struct NoPadding16(u16, i16);
struct NoPadding32(i32, f32, u32);
struct NoPadding64(f64, i64, u64);
struct NoPadding163264(i16, u16, i32, u64);
struct InternalPadding(u16, i64);
struct PaddingAtEnd(i64, u16);
fn main() {
let no_padding16 = NoPadding16(10000, -10001);
let no_padding32 = NoPadding32(-10002, -10003.5, 10004);
let no_padding64 = NoPadding64(-10005.5, 10006, 10007);
let no_padding163264 = NoPadding163264(-10008, 10009, 10010, 10011);
let internal_padding = InternalPadding(10012, -10013);
let padding_at_end = PaddingAtEnd(-10014, 10015);
zzz(); // #break
}
fn zzz() {()}
|
// gdb-check:$4 = {-10008, 10009, 10010, 10011}
// gdb-command:print internal_padding
|
random_line_split
|
smallest-hello-world.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android
// Smallest "hello world" with a libc runtime
#![no_std]
#![feature(intrinsics, lang_items)]
extern crate libc;
extern { fn puts(s: *const u8); }
extern "rust-intrinsic" { fn transmute<T, U>(t: T) -> U; }
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
|
#[no_split_stack]
fn main(_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
|
#[lang = "sized"] pub trait Sized {}
#[start]
|
random_line_split
|
smallest-hello-world.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android
// Smallest "hello world" with a libc runtime
#![no_std]
#![feature(intrinsics, lang_items)]
extern crate libc;
extern { fn puts(s: *const u8); }
extern "rust-intrinsic" { fn transmute<T, U>(t: T) -> U; }
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "sized"] pub trait Sized {}
#[start]
#[no_split_stack]
fn
|
(_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
|
main
|
identifier_name
|
smallest-hello-world.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android
// Smallest "hello world" with a libc runtime
#![no_std]
#![feature(intrinsics, lang_items)]
extern crate libc;
extern { fn puts(s: *const u8); }
extern "rust-intrinsic" { fn transmute<T, U>(t: T) -> U; }
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "sized"] pub trait Sized {}
#[start]
#[no_split_stack]
fn main(_: int, _: *const *const u8) -> int
|
{
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
|
identifier_body
|
|
lib.rs
|
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use chrono::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use anyhow::Result;
use regex::Regex;
#[macro_use]
extern crate lazy_static;
use thiserror::Error;
pub struct Session {
api_key: String,
cache: Cache,
cacheflushdate: String,
cache_path: String,
offline: bool,
}
impl Session {
pub async fn new(api_key: &str) -> Session {
let mut cache_path: PathBuf = dirs::home_dir().unwrap();
cache_path.push(".wsf.cache");
let cache_path = cache_path.display().to_string();
let mut s = Session {
api_key: api_key.to_string(),
cache: Cache::load(&cache_path).unwrap_or_else(|_| Cache::empty()),
cacheflushdate: String::new(),
cache_path,
offline: false,
};
// TODO this is kind of gross, cfd as optional to indicate offline, maybe?
s.offline = match s.get::<String>("/cacheflushdate".to_owned()).await {
Ok(cfd) => {
s.cacheflushdate = cfd;
false
}
Err(_) => true,
};
s
}
pub fn save_cache(&mut self) -> Result<()> {
self.cache.cache_flush_date = self.cacheflushdate.clone();
let mut f = File::create(&self.cache_path)?;
let encoded = serde_json::to_string(&self.cache)?;
f.write_all(encoded.as_bytes())?;
Ok(())
}
async fn get<T: DeserializeOwned>(&self, path: String) -> Result<T> {
let url = &format!(
"http://www.wsdot.wa.gov/ferries/api/schedule/rest{}?apiaccesscode={}",
path, self.api_key
);
let it = reqwest::Client::new().get(url).send().await?.json().await?;
//let mut it = reqwest::get(url).await?.json().await?;
Ok(it)
}
pub async fn find_terminal(&mut self, term: &str) -> Result<Terminal> {
let r = self
.terminals()
.await?
.iter()
.cloned()
.find(|t| t.Description.to_ascii_lowercase().starts_with(&term))
.ok_or_else(|| WsfError::TerminalNotFound(term.to_string()));
Ok(r?)
}
pub async fn terminals(&mut self) -> Result<Vec<Terminal>> {
if self.offline || (self.cache.cache_flush_date == self.cacheflushdate) {
Ok(self.cache.terminals.clone())
} else {
let now = Local::today();
let path = format!("/terminals/{}-{}-{}", now.year(), now.month(), now.day());
let routes: Vec<Terminal> = self.get(path).await?;
self.cache.terminals = routes.clone();
Ok(routes)
}
}
pub async fn schedule(&mut self, from: i32, to: i32) -> Result<TerminalCombo> {
let mut cache_is_stale = true;
let cache_key = format!("{} {}", from, to);
if self.offline || (self.cache.cache_flush_date == self.cacheflushdate) {
if self.cache.sailings.contains_key(&cache_key) {
// cache is up to date and has route!
return Ok(self
.cache
.sailings
.get(&cache_key)
.expect("checked for key in cache then not found")
.clone());
} else {
// cache is up to date, but we don't have this route in it
cache_is_stale = false;
}
}
if cache_is_stale {
self.cache.sailings.clear();
}
let now = Local::now();
let path = format!(
"/schedule/{}-{}-{}/{}/{}",
now.year(),
now.month(),
now.day(),
from,
to
);
let schedule: Schedule = self.get(path).await?;
self.cache
.sailings
.insert(cache_key, schedule.TerminalCombos[0].clone());
Ok(schedule.TerminalCombos[0].clone())
}
}
#[derive(Serialize, Deserialize, Debug)]
struct Cache {
terminals: Vec<Terminal>,
sailings: HashMap<String, TerminalCombo>,
cache_flush_date: String,
}
impl Cache {
fn empty() -> Cache {
Cache {
terminals: vec![],
sailings: HashMap::new(),
cache_flush_date: String::new(),
}
}
fn load(path: &str) -> Result<Cache> {
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
let cache: Cache = serde_json::from_str(&s)?;
Ok(cache)
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Terminal {
pub TerminalID: i32,
pub Description: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SailingTime {
pub DepartingTime: String,
pub ArrivingTime: Option<String>,
pub VesselName: String,
}
impl SailingTime {
// parse date strings of form "/Date(1436318400000-0700)/"
pub fn depart_time(&self) -> Result<DateTime<Local>> {
lazy_static! {
static ref RE: regex::Regex =
Regex::new(r"^/Date\((\d{10})000-(\d{2})(\d{2})\)/$").unwrap();
}
let caps = RE.captures(&self.DepartingTime).unwrap();
let epoch: i64 = caps.get(1).unwrap().as_str().parse()?;
let tz_hours: i32 = caps.get(2).unwrap().as_str().parse()?;
let tz_minutes: i32 = caps.get(3).unwrap().as_str().parse()?;
let nd = NaiveDateTime::from_timestamp(epoch, 0);
let tz = FixedOffset::west((tz_hours * 3600) + (tz_minutes * 60));
let fotz: DateTime<FixedOffset> = DateTime::from_utc(nd, tz);
Ok(fotz.with_timezone(&Local))
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TerminalCombo {
pub Times: Vec<SailingTime>,
pub DepartingTerminalName: String,
pub ArrivingTerminalName: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Schedule {
pub TerminalCombos: Vec<TerminalCombo>,
}
|
#[derive(Debug, Error)]
pub enum WsfError {
#[error("Terminal not found: {0}")]
TerminalNotFound(String),
}
|
random_line_split
|
|
lib.rs
|
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use chrono::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use anyhow::Result;
use regex::Regex;
#[macro_use]
extern crate lazy_static;
use thiserror::Error;
pub struct Session {
api_key: String,
cache: Cache,
cacheflushdate: String,
cache_path: String,
offline: bool,
}
impl Session {
pub async fn new(api_key: &str) -> Session {
let mut cache_path: PathBuf = dirs::home_dir().unwrap();
cache_path.push(".wsf.cache");
let cache_path = cache_path.display().to_string();
let mut s = Session {
api_key: api_key.to_string(),
cache: Cache::load(&cache_path).unwrap_or_else(|_| Cache::empty()),
cacheflushdate: String::new(),
cache_path,
offline: false,
};
// TODO this is kind of gross, cfd as optional to indicate offline, maybe?
s.offline = match s.get::<String>("/cacheflushdate".to_owned()).await {
Ok(cfd) => {
s.cacheflushdate = cfd;
false
}
Err(_) => true,
};
s
}
pub fn save_cache(&mut self) -> Result<()> {
self.cache.cache_flush_date = self.cacheflushdate.clone();
let mut f = File::create(&self.cache_path)?;
let encoded = serde_json::to_string(&self.cache)?;
f.write_all(encoded.as_bytes())?;
Ok(())
}
async fn get<T: DeserializeOwned>(&self, path: String) -> Result<T> {
let url = &format!(
"http://www.wsdot.wa.gov/ferries/api/schedule/rest{}?apiaccesscode={}",
path, self.api_key
);
let it = reqwest::Client::new().get(url).send().await?.json().await?;
//let mut it = reqwest::get(url).await?.json().await?;
Ok(it)
}
pub async fn find_terminal(&mut self, term: &str) -> Result<Terminal> {
let r = self
.terminals()
.await?
.iter()
.cloned()
.find(|t| t.Description.to_ascii_lowercase().starts_with(&term))
.ok_or_else(|| WsfError::TerminalNotFound(term.to_string()));
Ok(r?)
}
pub async fn terminals(&mut self) -> Result<Vec<Terminal>> {
if self.offline || (self.cache.cache_flush_date == self.cacheflushdate) {
Ok(self.cache.terminals.clone())
} else {
let now = Local::today();
let path = format!("/terminals/{}-{}-{}", now.year(), now.month(), now.day());
let routes: Vec<Terminal> = self.get(path).await?;
self.cache.terminals = routes.clone();
Ok(routes)
}
}
pub async fn schedule(&mut self, from: i32, to: i32) -> Result<TerminalCombo> {
let mut cache_is_stale = true;
let cache_key = format!("{} {}", from, to);
if self.offline || (self.cache.cache_flush_date == self.cacheflushdate) {
if self.cache.sailings.contains_key(&cache_key) {
// cache is up to date and has route!
return Ok(self
.cache
.sailings
.get(&cache_key)
.expect("checked for key in cache then not found")
.clone());
} else {
// cache is up to date, but we don't have this route in it
cache_is_stale = false;
}
}
if cache_is_stale
|
let now = Local::now();
let path = format!(
"/schedule/{}-{}-{}/{}/{}",
now.year(),
now.month(),
now.day(),
from,
to
);
let schedule: Schedule = self.get(path).await?;
self.cache
.sailings
.insert(cache_key, schedule.TerminalCombos[0].clone());
Ok(schedule.TerminalCombos[0].clone())
}
}
#[derive(Serialize, Deserialize, Debug)]
struct Cache {
terminals: Vec<Terminal>,
sailings: HashMap<String, TerminalCombo>,
cache_flush_date: String,
}
impl Cache {
fn empty() -> Cache {
Cache {
terminals: vec![],
sailings: HashMap::new(),
cache_flush_date: String::new(),
}
}
fn load(path: &str) -> Result<Cache> {
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
let cache: Cache = serde_json::from_str(&s)?;
Ok(cache)
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Terminal {
pub TerminalID: i32,
pub Description: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SailingTime {
pub DepartingTime: String,
pub ArrivingTime: Option<String>,
pub VesselName: String,
}
impl SailingTime {
// parse date strings of form "/Date(1436318400000-0700)/"
pub fn depart_time(&self) -> Result<DateTime<Local>> {
lazy_static! {
static ref RE: regex::Regex =
Regex::new(r"^/Date\((\d{10})000-(\d{2})(\d{2})\)/$").unwrap();
}
let caps = RE.captures(&self.DepartingTime).unwrap();
let epoch: i64 = caps.get(1).unwrap().as_str().parse()?;
let tz_hours: i32 = caps.get(2).unwrap().as_str().parse()?;
let tz_minutes: i32 = caps.get(3).unwrap().as_str().parse()?;
let nd = NaiveDateTime::from_timestamp(epoch, 0);
let tz = FixedOffset::west((tz_hours * 3600) + (tz_minutes * 60));
let fotz: DateTime<FixedOffset> = DateTime::from_utc(nd, tz);
Ok(fotz.with_timezone(&Local))
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TerminalCombo {
pub Times: Vec<SailingTime>,
pub DepartingTerminalName: String,
pub ArrivingTerminalName: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Schedule {
pub TerminalCombos: Vec<TerminalCombo>,
}
#[derive(Debug, Error)]
pub enum WsfError {
#[error("Terminal not found: {0}")]
TerminalNotFound(String),
}
|
{
self.cache.sailings.clear();
}
|
conditional_block
|
lib.rs
|
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use chrono::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use anyhow::Result;
use regex::Regex;
#[macro_use]
extern crate lazy_static;
use thiserror::Error;
pub struct Session {
api_key: String,
cache: Cache,
cacheflushdate: String,
cache_path: String,
offline: bool,
}
impl Session {
pub async fn new(api_key: &str) -> Session {
let mut cache_path: PathBuf = dirs::home_dir().unwrap();
cache_path.push(".wsf.cache");
let cache_path = cache_path.display().to_string();
let mut s = Session {
api_key: api_key.to_string(),
cache: Cache::load(&cache_path).unwrap_or_else(|_| Cache::empty()),
cacheflushdate: String::new(),
cache_path,
offline: false,
};
// TODO this is kind of gross, cfd as optional to indicate offline, maybe?
s.offline = match s.get::<String>("/cacheflushdate".to_owned()).await {
Ok(cfd) => {
s.cacheflushdate = cfd;
false
}
Err(_) => true,
};
s
}
pub fn save_cache(&mut self) -> Result<()> {
self.cache.cache_flush_date = self.cacheflushdate.clone();
let mut f = File::create(&self.cache_path)?;
let encoded = serde_json::to_string(&self.cache)?;
f.write_all(encoded.as_bytes())?;
Ok(())
}
async fn get<T: DeserializeOwned>(&self, path: String) -> Result<T> {
let url = &format!(
"http://www.wsdot.wa.gov/ferries/api/schedule/rest{}?apiaccesscode={}",
path, self.api_key
);
let it = reqwest::Client::new().get(url).send().await?.json().await?;
//let mut it = reqwest::get(url).await?.json().await?;
Ok(it)
}
pub async fn find_terminal(&mut self, term: &str) -> Result<Terminal> {
let r = self
.terminals()
.await?
.iter()
.cloned()
.find(|t| t.Description.to_ascii_lowercase().starts_with(&term))
.ok_or_else(|| WsfError::TerminalNotFound(term.to_string()));
Ok(r?)
}
pub async fn terminals(&mut self) -> Result<Vec<Terminal>> {
if self.offline || (self.cache.cache_flush_date == self.cacheflushdate) {
Ok(self.cache.terminals.clone())
} else {
let now = Local::today();
let path = format!("/terminals/{}-{}-{}", now.year(), now.month(), now.day());
let routes: Vec<Terminal> = self.get(path).await?;
self.cache.terminals = routes.clone();
Ok(routes)
}
}
pub async fn schedule(&mut self, from: i32, to: i32) -> Result<TerminalCombo> {
let mut cache_is_stale = true;
let cache_key = format!("{} {}", from, to);
if self.offline || (self.cache.cache_flush_date == self.cacheflushdate) {
if self.cache.sailings.contains_key(&cache_key) {
// cache is up to date and has route!
return Ok(self
.cache
.sailings
.get(&cache_key)
.expect("checked for key in cache then not found")
.clone());
} else {
// cache is up to date, but we don't have this route in it
cache_is_stale = false;
}
}
if cache_is_stale {
self.cache.sailings.clear();
}
let now = Local::now();
let path = format!(
"/schedule/{}-{}-{}/{}/{}",
now.year(),
now.month(),
now.day(),
from,
to
);
let schedule: Schedule = self.get(path).await?;
self.cache
.sailings
.insert(cache_key, schedule.TerminalCombos[0].clone());
Ok(schedule.TerminalCombos[0].clone())
}
}
#[derive(Serialize, Deserialize, Debug)]
struct Cache {
terminals: Vec<Terminal>,
sailings: HashMap<String, TerminalCombo>,
cache_flush_date: String,
}
impl Cache {
fn empty() -> Cache {
Cache {
terminals: vec![],
sailings: HashMap::new(),
cache_flush_date: String::new(),
}
}
fn load(path: &str) -> Result<Cache> {
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
let cache: Cache = serde_json::from_str(&s)?;
Ok(cache)
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Terminal {
pub TerminalID: i32,
pub Description: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct
|
{
pub DepartingTime: String,
pub ArrivingTime: Option<String>,
pub VesselName: String,
}
impl SailingTime {
// parse date strings of form "/Date(1436318400000-0700)/"
pub fn depart_time(&self) -> Result<DateTime<Local>> {
lazy_static! {
static ref RE: regex::Regex =
Regex::new(r"^/Date\((\d{10})000-(\d{2})(\d{2})\)/$").unwrap();
}
let caps = RE.captures(&self.DepartingTime).unwrap();
let epoch: i64 = caps.get(1).unwrap().as_str().parse()?;
let tz_hours: i32 = caps.get(2).unwrap().as_str().parse()?;
let tz_minutes: i32 = caps.get(3).unwrap().as_str().parse()?;
let nd = NaiveDateTime::from_timestamp(epoch, 0);
let tz = FixedOffset::west((tz_hours * 3600) + (tz_minutes * 60));
let fotz: DateTime<FixedOffset> = DateTime::from_utc(nd, tz);
Ok(fotz.with_timezone(&Local))
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TerminalCombo {
pub Times: Vec<SailingTime>,
pub DepartingTerminalName: String,
pub ArrivingTerminalName: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Schedule {
pub TerminalCombos: Vec<TerminalCombo>,
}
#[derive(Debug, Error)]
pub enum WsfError {
#[error("Terminal not found: {0}")]
TerminalNotFound(String),
}
|
SailingTime
|
identifier_name
|
advent2.rs
|
// advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read line")) {
// part 1
pos1 = parse_move(pos1, &line);
code1.push_str(&digit_from_pos(pos1).to_string());
// part 2
pos2 = parse_move2(pos2, &line);
code2.push(char_from_pos2(pos2));
}
println!("Part 1: {}", code1);
println!("Part 2: {}", code2);
}
fn digit_from_pos(pos: (i32, i32)) -> i32 {
1 + pos.0 + 3 * pos.1
}
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y > 0 {y -= 1;},
'D' => if y < 2 {y += 1;},
'L' => if x > 0 {x -= 1;},
'R' => if x < 2 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
// ////////
// Part 2
// Same as part 1, except the conditions are less obvious
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move2(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y - (x - 2).abs() > 0 {y -= 1;},
'D' => if y + (x - 2).abs() < 4 {y += 1;},
'L' => if x - (y - 2).abs() > 0 {x -= 1;},
'R' => if x + (y - 2).abs() < 4 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
const KEYPAD2_TABLE: [[char; 5]; 5] = [['*', '*', '1', '*', '*'],
['*', '2', '3', '4', '*'],
['5', '6', '7', '8', '9'],
['*', 'A', 'B', 'C', '*'],
['*', '*', 'D', '*', '*']];
fn char_from_pos2(pos: (i32, i32)) -> char {
KEYPAD2_TABLE[pos.1 as usize][pos.0 as usize]
}
// //////
// Tests
#[test]
fn
|
() {
assert_eq!(1, digit_from_pos((0, 0)));
assert_eq!(2, digit_from_pos((1, 0)));
assert_eq!(3, digit_from_pos((2, 0)));
assert_eq!(4, digit_from_pos((0, 1)));
assert_eq!(5, digit_from_pos((1, 1)));
assert_eq!(6, digit_from_pos((2, 1)));
assert_eq!(7, digit_from_pos((0, 2)));
assert_eq!(8, digit_from_pos((1, 2)));
assert_eq!(9, digit_from_pos((2, 2)));
}
#[test]
fn test_parse_move() {
assert_eq!((0, 0), parse_move((1, 1), "ULL"));
assert_eq!((2, 2), parse_move((0, 0), "RRDDD"));
assert_eq!((1, 2), parse_move((2, 2), "LURDL"));
assert_eq!((1, 1), parse_move((1, 2), "UUUUD"));
}
// part 2
#[test]
fn test_parse_move2() {
assert_eq!((0, 2), parse_move2((0, 2), "ULL"));
assert_eq!((2, 4), parse_move2((0, 2), "RRDDD"));
assert_eq!((2, 3), parse_move2((2, 4), "LURDL"));
assert_eq!((2, 1), parse_move2((2, 3), "UUUUD"));
}
#[test]
fn test_char_from_pos2() {
assert_eq!('5', char_from_pos2((0, 2)));
}
|
test_digit_from_pos
|
identifier_name
|
advent2.rs
|
// advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read line")) {
// part 1
pos1 = parse_move(pos1, &line);
code1.push_str(&digit_from_pos(pos1).to_string());
// part 2
pos2 = parse_move2(pos2, &line);
code2.push(char_from_pos2(pos2));
}
println!("Part 1: {}", code1);
println!("Part 2: {}", code2);
}
fn digit_from_pos(pos: (i32, i32)) -> i32 {
1 + pos.0 + 3 * pos.1
}
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move(pos: (i32, i32), s: &str) -> (i32, i32)
|
// ////////
// Part 2
// Same as part 1, except the conditions are less obvious
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move2(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y - (x - 2).abs() > 0 {y -= 1;},
'D' => if y + (x - 2).abs() < 4 {y += 1;},
'L' => if x - (y - 2).abs() > 0 {x -= 1;},
'R' => if x + (y - 2).abs() < 4 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
const KEYPAD2_TABLE: [[char; 5]; 5] = [['*', '*', '1', '*', '*'],
['*', '2', '3', '4', '*'],
['5', '6', '7', '8', '9'],
['*', 'A', 'B', 'C', '*'],
['*', '*', 'D', '*', '*']];
fn char_from_pos2(pos: (i32, i32)) -> char {
KEYPAD2_TABLE[pos.1 as usize][pos.0 as usize]
}
// //////
// Tests
#[test]
fn test_digit_from_pos() {
assert_eq!(1, digit_from_pos((0, 0)));
assert_eq!(2, digit_from_pos((1, 0)));
assert_eq!(3, digit_from_pos((2, 0)));
assert_eq!(4, digit_from_pos((0, 1)));
assert_eq!(5, digit_from_pos((1, 1)));
assert_eq!(6, digit_from_pos((2, 1)));
assert_eq!(7, digit_from_pos((0, 2)));
assert_eq!(8, digit_from_pos((1, 2)));
assert_eq!(9, digit_from_pos((2, 2)));
}
#[test]
fn test_parse_move() {
assert_eq!((0, 0), parse_move((1, 1), "ULL"));
assert_eq!((2, 2), parse_move((0, 0), "RRDDD"));
assert_eq!((1, 2), parse_move((2, 2), "LURDL"));
assert_eq!((1, 1), parse_move((1, 2), "UUUUD"));
}
// part 2
#[test]
fn test_parse_move2() {
assert_eq!((0, 2), parse_move2((0, 2), "ULL"));
assert_eq!((2, 4), parse_move2((0, 2), "RRDDD"));
assert_eq!((2, 3), parse_move2((2, 4), "LURDL"));
assert_eq!((2, 1), parse_move2((2, 3), "UUUUD"));
}
#[test]
fn test_char_from_pos2() {
assert_eq!('5', char_from_pos2((0, 2)));
}
|
{
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y > 0 {y -= 1;},
'D' => if y < 2 {y += 1;},
'L' => if x > 0 {x -= 1;},
'R' => if x < 2 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
|
identifier_body
|
advent2.rs
|
// advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read line")) {
// part 1
pos1 = parse_move(pos1, &line);
code1.push_str(&digit_from_pos(pos1).to_string());
// part 2
pos2 = parse_move2(pos2, &line);
code2.push(char_from_pos2(pos2));
}
println!("Part 1: {}", code1);
println!("Part 2: {}", code2);
}
fn digit_from_pos(pos: (i32, i32)) -> i32 {
1 + pos.0 + 3 * pos.1
}
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y > 0 {y -= 1;},
'D' => if y < 2
|
,
'L' => if x > 0 {x -= 1;},
'R' => if x < 2 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
// ////////
// Part 2
// Same as part 1, except the conditions are less obvious
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move2(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y - (x - 2).abs() > 0 {y -= 1;},
'D' => if y + (x - 2).abs() < 4 {y += 1;},
'L' => if x - (y - 2).abs() > 0 {x -= 1;},
'R' => if x + (y - 2).abs() < 4 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
const KEYPAD2_TABLE: [[char; 5]; 5] = [['*', '*', '1', '*', '*'],
['*', '2', '3', '4', '*'],
['5', '6', '7', '8', '9'],
['*', 'A', 'B', 'C', '*'],
['*', '*', 'D', '*', '*']];
fn char_from_pos2(pos: (i32, i32)) -> char {
KEYPAD2_TABLE[pos.1 as usize][pos.0 as usize]
}
// //////
// Tests
#[test]
fn test_digit_from_pos() {
assert_eq!(1, digit_from_pos((0, 0)));
assert_eq!(2, digit_from_pos((1, 0)));
assert_eq!(3, digit_from_pos((2, 0)));
assert_eq!(4, digit_from_pos((0, 1)));
assert_eq!(5, digit_from_pos((1, 1)));
assert_eq!(6, digit_from_pos((2, 1)));
assert_eq!(7, digit_from_pos((0, 2)));
assert_eq!(8, digit_from_pos((1, 2)));
assert_eq!(9, digit_from_pos((2, 2)));
}
#[test]
fn test_parse_move() {
assert_eq!((0, 0), parse_move((1, 1), "ULL"));
assert_eq!((2, 2), parse_move((0, 0), "RRDDD"));
assert_eq!((1, 2), parse_move((2, 2), "LURDL"));
assert_eq!((1, 1), parse_move((1, 2), "UUUUD"));
}
// part 2
#[test]
fn test_parse_move2() {
assert_eq!((0, 2), parse_move2((0, 2), "ULL"));
assert_eq!((2, 4), parse_move2((0, 2), "RRDDD"));
assert_eq!((2, 3), parse_move2((2, 4), "LURDL"));
assert_eq!((2, 1), parse_move2((2, 3), "UUUUD"));
}
#[test]
fn test_char_from_pos2() {
assert_eq!('5', char_from_pos2((0, 2)));
}
|
{y += 1;}
|
conditional_block
|
advent2.rs
|
// advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read line")) {
// part 1
pos1 = parse_move(pos1, &line);
code1.push_str(&digit_from_pos(pos1).to_string());
// part 2
pos2 = parse_move2(pos2, &line);
code2.push(char_from_pos2(pos2));
}
println!("Part 1: {}", code1);
println!("Part 2: {}", code2);
}
fn digit_from_pos(pos: (i32, i32)) -> i32 {
1 + pos.0 + 3 * pos.1
}
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y > 0 {y -= 1;},
'D' => if y < 2 {y += 1;},
'L' => if x > 0 {x -= 1;},
'R' => if x < 2 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
// ////////
// Part 2
// Same as part 1, except the conditions are less obvious
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move2(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y - (x - 2).abs() > 0 {y -= 1;},
'D' => if y + (x - 2).abs() < 4 {y += 1;},
'L' => if x - (y - 2).abs() > 0 {x -= 1;},
'R' => if x + (y - 2).abs() < 4 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
const KEYPAD2_TABLE: [[char; 5]; 5] = [['*', '*', '1', '*', '*'],
|
['5', '6', '7', '8', '9'],
['*', 'A', 'B', 'C', '*'],
['*', '*', 'D', '*', '*']];
fn char_from_pos2(pos: (i32, i32)) -> char {
KEYPAD2_TABLE[pos.1 as usize][pos.0 as usize]
}
// //////
// Tests
#[test]
fn test_digit_from_pos() {
assert_eq!(1, digit_from_pos((0, 0)));
assert_eq!(2, digit_from_pos((1, 0)));
assert_eq!(3, digit_from_pos((2, 0)));
assert_eq!(4, digit_from_pos((0, 1)));
assert_eq!(5, digit_from_pos((1, 1)));
assert_eq!(6, digit_from_pos((2, 1)));
assert_eq!(7, digit_from_pos((0, 2)));
assert_eq!(8, digit_from_pos((1, 2)));
assert_eq!(9, digit_from_pos((2, 2)));
}
#[test]
fn test_parse_move() {
assert_eq!((0, 0), parse_move((1, 1), "ULL"));
assert_eq!((2, 2), parse_move((0, 0), "RRDDD"));
assert_eq!((1, 2), parse_move((2, 2), "LURDL"));
assert_eq!((1, 1), parse_move((1, 2), "UUUUD"));
}
// part 2
#[test]
fn test_parse_move2() {
assert_eq!((0, 2), parse_move2((0, 2), "ULL"));
assert_eq!((2, 4), parse_move2((0, 2), "RRDDD"));
assert_eq!((2, 3), parse_move2((2, 4), "LURDL"));
assert_eq!((2, 1), parse_move2((2, 3), "UUUUD"));
}
#[test]
fn test_char_from_pos2() {
assert_eq!('5', char_from_pos2((0, 2)));
}
|
['*', '2', '3', '4', '*'],
|
random_line_split
|
main.rs
|
#[macro_use]
extern crate lazy_static;
extern crate md5;
use md5::compute;
fn next_pair(input: &[u8], pepper: &mut u64) -> Option<(u8, u8)> {
let mut preimage = Vec::new();
// Ignore edge case where maximum pepper yields the digit.
while *pepper!= u64::max_value() {
preimage.clear();
preimage.extend_from_slice(input);
preimage.extend(pepper.to_string().bytes());
let digest = compute(&preimage);
let mut occurrence =
digest.iter().enumerate().skip_while(|&(_, &b)| b == 0);
*pepper = pepper.saturating_add(1);
if let Some((index, byte)) = occurrence.next() {
if (index > 2) || (index == 2 && (byte & 0xf0) == 0)
|
}
}
None
}
fn next_digit(input: &[u8], pepper: &mut u64) -> Option<u8> {
next_pair(input, pepper).map(|(x, _)| x)
}
fn solve_one(input: &[u8]) -> Option<String> {
let mut password = Vec::new();
let mut pepper = 0u64;
for _ in 0..8 {
match next_digit(input, &mut pepper) {
Some(digit) => password.push(format!("{:x}", digit)),
_ => return None,
}
}
Some(password.join(""))
}
fn solve_two(input: &[u8]) -> Option<String> {
let (mut free, mut pepper) = (8, 0u64);
let mut password = [!0u8; 8];
while free!= 0 {
match next_pair(input, &mut pepper) {
Some((position, digit)) => {
let position = position as usize;
if position < 8 && password[position] ==!0u8 {
free -= 1;
password[position] = digit;
}
}
_ => return None,
}
}
Some(password.iter()
.map(|x| format!("{:x}", x))
.collect::<Vec<_>>()
.join(""))
}
fn main() {
lazy_static! {
static ref INPUT: Vec<u8> = "ugkcyxxp".bytes().collect();
}
match solve_one(&INPUT) {
Some(password) => println!("[1] Found the password: {}.", password),
_ => println!("[1] Could not find the password."),
}
match solve_two(&INPUT) {
Some(password) => println!("[2] Found the password: {}.", password),
_ => println!("[2] Could not find the password."),
}
}
|
{
let d6 = digest[2] & 0xf;
let d7 = (digest[3] >> 4) & 0xf;
return Some((d6, d7));
}
|
conditional_block
|
main.rs
|
#[macro_use]
extern crate lazy_static;
extern crate md5;
use md5::compute;
fn next_pair(input: &[u8], pepper: &mut u64) -> Option<(u8, u8)> {
let mut preimage = Vec::new();
// Ignore edge case where maximum pepper yields the digit.
while *pepper!= u64::max_value() {
preimage.clear();
preimage.extend_from_slice(input);
preimage.extend(pepper.to_string().bytes());
let digest = compute(&preimage);
let mut occurrence =
digest.iter().enumerate().skip_while(|&(_, &b)| b == 0);
*pepper = pepper.saturating_add(1);
if let Some((index, byte)) = occurrence.next() {
if (index > 2) || (index == 2 && (byte & 0xf0) == 0) {
let d6 = digest[2] & 0xf;
let d7 = (digest[3] >> 4) & 0xf;
return Some((d6, d7));
}
}
}
None
}
fn next_digit(input: &[u8], pepper: &mut u64) -> Option<u8> {
next_pair(input, pepper).map(|(x, _)| x)
}
fn
|
(input: &[u8]) -> Option<String> {
let mut password = Vec::new();
let mut pepper = 0u64;
for _ in 0..8 {
match next_digit(input, &mut pepper) {
Some(digit) => password.push(format!("{:x}", digit)),
_ => return None,
}
}
Some(password.join(""))
}
fn solve_two(input: &[u8]) -> Option<String> {
let (mut free, mut pepper) = (8, 0u64);
let mut password = [!0u8; 8];
while free!= 0 {
match next_pair(input, &mut pepper) {
Some((position, digit)) => {
let position = position as usize;
if position < 8 && password[position] ==!0u8 {
free -= 1;
password[position] = digit;
}
}
_ => return None,
}
}
Some(password.iter()
.map(|x| format!("{:x}", x))
.collect::<Vec<_>>()
.join(""))
}
fn main() {
lazy_static! {
static ref INPUT: Vec<u8> = "ugkcyxxp".bytes().collect();
}
match solve_one(&INPUT) {
Some(password) => println!("[1] Found the password: {}.", password),
_ => println!("[1] Could not find the password."),
}
match solve_two(&INPUT) {
Some(password) => println!("[2] Found the password: {}.", password),
_ => println!("[2] Could not find the password."),
}
}
|
solve_one
|
identifier_name
|
main.rs
|
#[macro_use]
extern crate lazy_static;
extern crate md5;
use md5::compute;
fn next_pair(input: &[u8], pepper: &mut u64) -> Option<(u8, u8)> {
let mut preimage = Vec::new();
// Ignore edge case where maximum pepper yields the digit.
while *pepper!= u64::max_value() {
preimage.clear();
preimage.extend_from_slice(input);
preimage.extend(pepper.to_string().bytes());
let digest = compute(&preimage);
let mut occurrence =
digest.iter().enumerate().skip_while(|&(_, &b)| b == 0);
*pepper = pepper.saturating_add(1);
if let Some((index, byte)) = occurrence.next() {
if (index > 2) || (index == 2 && (byte & 0xf0) == 0) {
let d6 = digest[2] & 0xf;
let d7 = (digest[3] >> 4) & 0xf;
return Some((d6, d7));
}
}
}
None
}
fn next_digit(input: &[u8], pepper: &mut u64) -> Option<u8> {
next_pair(input, pepper).map(|(x, _)| x)
}
fn solve_one(input: &[u8]) -> Option<String> {
let mut password = Vec::new();
|
match next_digit(input, &mut pepper) {
Some(digit) => password.push(format!("{:x}", digit)),
_ => return None,
}
}
Some(password.join(""))
}
fn solve_two(input: &[u8]) -> Option<String> {
let (mut free, mut pepper) = (8, 0u64);
let mut password = [!0u8; 8];
while free!= 0 {
match next_pair(input, &mut pepper) {
Some((position, digit)) => {
let position = position as usize;
if position < 8 && password[position] ==!0u8 {
free -= 1;
password[position] = digit;
}
}
_ => return None,
}
}
Some(password.iter()
.map(|x| format!("{:x}", x))
.collect::<Vec<_>>()
.join(""))
}
fn main() {
lazy_static! {
static ref INPUT: Vec<u8> = "ugkcyxxp".bytes().collect();
}
match solve_one(&INPUT) {
Some(password) => println!("[1] Found the password: {}.", password),
_ => println!("[1] Could not find the password."),
}
match solve_two(&INPUT) {
Some(password) => println!("[2] Found the password: {}.", password),
_ => println!("[2] Could not find the password."),
}
}
|
let mut pepper = 0u64;
for _ in 0..8 {
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.