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 |
---|---|---|---|---|
trace.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Garbage
//! Collector. A rooted DOM object implementing the interface `Foo` is traced
//! as follows:
//!
//! 1. The GC calls `_trace` defined in `FooBinding` during the marking
//! phase. (This happens through `JSClass.trace` for non-proxy bindings, and
//! through `ProxyTraps.trace` otherwise.)
//! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`).
//! This is typically derived via a `#[dom_struct]` (implies `#[jstraceable]`) annotation.
//! Non-JS-managed types have an empty inline `trace()` method,
//! achieved via `no_jsmanaged_fields!` or similar.
//! 3. For all fields, `Foo::trace()`
//! calls `trace()` on the field.
//! For example, for fields of type `JS<T>`, `JS<T>::trace()` calls
//! `trace_reflector()`.
//! 4. `trace_reflector()` calls `trace_object()` with the `JSObject` for the
//! reflector.
//! 5. `trace_object()` calls `JS_CallTracer()` to notify the GC, which will
//! add the object to the graph, and will trace that object as well.
//! 6. When the GC finishes tracing, it [`finalizes`](../index.html#destruction)
//! any reflectors that were not reachable.
//!
//! The `no_jsmanaged_fields!()` macro adds an empty implementation of `JSTraceable` to
//! a datatype.
use dom::bindings::js::JS;
use dom::bindings::refcounted::Trusted;
use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler};
use script_task::ScriptChan;
use cssparser::RGBA;
use encoding::types::EncodingRef;
use geom::matrix2d::Matrix2D;
use geom::rect::Rect;
use html5ever::tree_builder::QuirksMode;
use hyper::header::Headers;
use hyper::method::Method;
use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSGCTraceKind};
use js::jsval::JSVal;
use js::rust::{Cx, rt};
use layout_interface::{LayoutRPC, LayoutChan};
use libc;
use msg::constellation_msg::{PipelineId, SubpageId, WindowSizeData};
use net::image_cache_task::ImageCacheTask;
use net::storage_task::StorageType;
use script_traits::ScriptControlChan;
use script_traits::UntrustedNodeAddress;
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::ConstellationChan;
use util::smallvec::{SmallVec1, SmallVec};
use util::str::{LengthOrPercentageOrAuto};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::collections::hash_state::HashState;
use std::ffi::CString;
use std::hash::{Hash, Hasher};
use std::old_io::timer::Timer;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender};
use string_cache::{Atom, Namespace};
use style::properties::PropertyDeclarationBlock;
use url::Url;
/// A trait to allow tracing (only) DOM objects.
pub trait JSTraceable {
/// Trace `self`.
fn trace(&self, trc: *mut JSTracer);
}
impl<T: Reflectable> JSTraceable for JS<T> {
fn trace(&self, trc: *mut JSTracer) {
trace_reflector(trc, "", self.reflector());
}
}
no_jsmanaged_fields!(EncodingRef);
no_jsmanaged_fields!(Reflector);
/// Trace a `JSVal`.
pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
if!val.is_markable() {
return;
}
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing value {}", description);
JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind());
}
}
/// Trace the `JSObject` held by `reflector`.
#[allow(unrooted_must_root)]
pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
trace_object(tracer, description, reflector.get_jsobject())
}
/// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
unsafe {
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing {}", description);
JS_CallTracer(tracer, obj as *mut libc::c_void, JSGCTraceKind::JSTRACE_OBJECT);
}
}
impl<T: JSTraceable> JSTraceable for RefCell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.borrow().trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Rc<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for Box<T> {
fn trace(&self, trc: *mut JSTracer) {
(**self).trace(trc)
}
}
impl<T: JSTraceable+Copy> JSTraceable for Cell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.get().trace(trc)
}
}
impl JSTraceable for *mut JSObject {
fn trace(&self, trc: *mut JSTracer) {
trace_object(trc, "object", *self);
}
}
impl JSTraceable for JSVal {
fn trace(&self, trc: *mut JSTracer) {
trace_jsval(trc, "val", *self);
}
}
|
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable> JSTraceable for Vec<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable +'static> JSTraceable for SmallVec1<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
impl<T: JSTraceable> JSTraceable for Option<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
self.as_ref().map(|e| e.trace(trc));
}
}
impl<K,V,S> JSTraceable for HashMap<K, V, S>
where K: Hash + Eq + JSTraceable,
V: JSTraceable,
S: HashState,
<S as HashState>::Hasher: Hasher,
{
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for (k, v) in self.iter() {
k.trace(trc);
v.trace(trc);
}
}
}
impl<A: JSTraceable, B: JSTraceable> JSTraceable for (A, B) {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
let (ref a, ref b) = *self;
a.trace(trc);
b.trace(trc);
}
}
no_jsmanaged_fields!(bool, f32, f64, String, Url);
no_jsmanaged_fields!(usize, u8, u16, u32, u64);
no_jsmanaged_fields!(isize, i8, i16, i32, i64);
no_jsmanaged_fields!(Sender<T>);
no_jsmanaged_fields!(Receiver<T>);
no_jsmanaged_fields!(Rect<T>);
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan);
no_jsmanaged_fields!(Atom, Namespace, Timer);
no_jsmanaged_fields!(Trusted<T>);
no_jsmanaged_fields!(PropertyDeclarationBlock);
// These three are interdependent, if you plan to put jsmanaged data
// in one of these make sure it is propagated properly to containing structs
no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId);
no_jsmanaged_fields!(QuirksMode);
no_jsmanaged_fields!(Cx);
no_jsmanaged_fields!(rt);
no_jsmanaged_fields!(Headers, Method);
no_jsmanaged_fields!(ConstellationChan);
no_jsmanaged_fields!(LayoutChan);
no_jsmanaged_fields!(WindowProxyHandler);
no_jsmanaged_fields!(UntrustedNodeAddress);
no_jsmanaged_fields!(LengthOrPercentageOrAuto);
no_jsmanaged_fields!(RGBA);
no_jsmanaged_fields!(Matrix2D<T>);
no_jsmanaged_fields!(StorageType);
impl JSTraceable for Box<ScriptChan+Send> {
#[inline]
fn trace(&self, _trc: *mut JSTracer) {
// Do nothing
}
}
impl<'a> JSTraceable for &'a str {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl<A,B> JSTraceable for fn(A) -> B {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<ScriptListener+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
impl JSTraceable for Box<LayoutRPC+'static> {
#[inline]
fn trace(&self, _: *mut JSTracer) {
// Do nothing
}
}
|
// XXXManishearth Check if the following three are optimized to no-ops
|
random_line_split
|
debug_view.rs
|
use crate::logger;
use crate::theme;
use crate::view::View;
use crate::Printer;
use crate::Vec2;
use unicode_width::UnicodeWidthStr;
/// View used for debugging, showing logs.
pub struct DebugView {
// TODO: wrap log lines if needed, and save the line splits here.
}
impl DebugView {
/// Creates a new DebugView.
pub fn new() -> Self {
DebugView {}
}
}
impl Default for DebugView {
fn default() -> Self {
Self::new()
}
}
impl View for DebugView {
fn draw(&self, printer: &Printer) {
let logs = logger::LOGS.lock().unwrap();
// Only print the last logs, so skip what doesn't fit
let skipped = logs.len().saturating_sub(printer.size.y);
|
// TODO: customizable time format? (24h/AM-PM)
printer.print(
(0, i),
&format!(
"{} | [ ] {}",
record.time.with_timezone(&chrono::Local).format("%T%.3f"),
record.message
),
);
let color = match record.level {
log::Level::Error => theme::BaseColor::Red.dark(),
log::Level::Warn => theme::BaseColor::Yellow.dark(),
log::Level::Info => theme::BaseColor::Black.light(),
log::Level::Debug => theme::BaseColor::Green.dark(),
log::Level::Trace => theme::BaseColor::Blue.dark(),
};
printer.with_color(color.into(), |printer| {
printer.print((16, i), &format!("{:5}", record.level))
});
}
}
fn required_size(&mut self, _constraint: Vec2) -> Vec2 {
// TODO: read the logs, and compute the required size to print it.
let logs = logger::LOGS.lock().unwrap();
let level_width = 8; // Width of "[ERROR] "
let time_width = 16; // Width of "23:59:59.123 | "
// The longest line sets the width
let w = logs
.iter()
.map(|record| record.message.width() + level_width + time_width)
.max()
.unwrap_or(1);
let h = logs.len();
Vec2::new(w, h)
}
fn layout(&mut self, _size: Vec2) {
// Uh?
}
}
|
for (i, record) in logs.iter().skip(skipped).enumerate() {
// TODO: Apply style to message? (Ex: errors in bold?)
|
random_line_split
|
debug_view.rs
|
use crate::logger;
use crate::theme;
use crate::view::View;
use crate::Printer;
use crate::Vec2;
use unicode_width::UnicodeWidthStr;
/// View used for debugging, showing logs.
pub struct DebugView {
// TODO: wrap log lines if needed, and save the line splits here.
}
impl DebugView {
/// Creates a new DebugView.
pub fn new() -> Self {
DebugView {}
}
}
impl Default for DebugView {
fn default() -> Self {
Self::new()
}
}
impl View for DebugView {
fn draw(&self, printer: &Printer) {
let logs = logger::LOGS.lock().unwrap();
// Only print the last logs, so skip what doesn't fit
let skipped = logs.len().saturating_sub(printer.size.y);
for (i, record) in logs.iter().skip(skipped).enumerate() {
// TODO: Apply style to message? (Ex: errors in bold?)
// TODO: customizable time format? (24h/AM-PM)
printer.print(
(0, i),
&format!(
"{} | [ ] {}",
record.time.with_timezone(&chrono::Local).format("%T%.3f"),
record.message
),
);
let color = match record.level {
log::Level::Error => theme::BaseColor::Red.dark(),
log::Level::Warn => theme::BaseColor::Yellow.dark(),
log::Level::Info => theme::BaseColor::Black.light(),
log::Level::Debug => theme::BaseColor::Green.dark(),
log::Level::Trace => theme::BaseColor::Blue.dark(),
};
printer.with_color(color.into(), |printer| {
printer.print((16, i), &format!("{:5}", record.level))
});
}
}
fn required_size(&mut self, _constraint: Vec2) -> Vec2 {
// TODO: read the logs, and compute the required size to print it.
let logs = logger::LOGS.lock().unwrap();
let level_width = 8; // Width of "[ERROR] "
let time_width = 16; // Width of "23:59:59.123 | "
// The longest line sets the width
let w = logs
.iter()
.map(|record| record.message.width() + level_width + time_width)
.max()
.unwrap_or(1);
let h = logs.len();
Vec2::new(w, h)
}
fn layout(&mut self, _size: Vec2)
|
}
|
{
// Uh?
}
|
identifier_body
|
debug_view.rs
|
use crate::logger;
use crate::theme;
use crate::view::View;
use crate::Printer;
use crate::Vec2;
use unicode_width::UnicodeWidthStr;
/// View used for debugging, showing logs.
pub struct DebugView {
// TODO: wrap log lines if needed, and save the line splits here.
}
impl DebugView {
/// Creates a new DebugView.
pub fn new() -> Self {
DebugView {}
}
}
impl Default for DebugView {
fn default() -> Self {
Self::new()
}
}
impl View for DebugView {
fn
|
(&self, printer: &Printer) {
let logs = logger::LOGS.lock().unwrap();
// Only print the last logs, so skip what doesn't fit
let skipped = logs.len().saturating_sub(printer.size.y);
for (i, record) in logs.iter().skip(skipped).enumerate() {
// TODO: Apply style to message? (Ex: errors in bold?)
// TODO: customizable time format? (24h/AM-PM)
printer.print(
(0, i),
&format!(
"{} | [ ] {}",
record.time.with_timezone(&chrono::Local).format("%T%.3f"),
record.message
),
);
let color = match record.level {
log::Level::Error => theme::BaseColor::Red.dark(),
log::Level::Warn => theme::BaseColor::Yellow.dark(),
log::Level::Info => theme::BaseColor::Black.light(),
log::Level::Debug => theme::BaseColor::Green.dark(),
log::Level::Trace => theme::BaseColor::Blue.dark(),
};
printer.with_color(color.into(), |printer| {
printer.print((16, i), &format!("{:5}", record.level))
});
}
}
fn required_size(&mut self, _constraint: Vec2) -> Vec2 {
// TODO: read the logs, and compute the required size to print it.
let logs = logger::LOGS.lock().unwrap();
let level_width = 8; // Width of "[ERROR] "
let time_width = 16; // Width of "23:59:59.123 | "
// The longest line sets the width
let w = logs
.iter()
.map(|record| record.message.width() + level_width + time_width)
.max()
.unwrap_or(1);
let h = logs.len();
Vec2::new(w, h)
}
fn layout(&mut self, _size: Vec2) {
// Uh?
}
}
|
draw
|
identifier_name
|
poll.rs
|
/// A macro.
#[macro_export]
macro_rules! try_poll {
($e:expr) => (match $e {
$crate::Poll::NotReady => return $crate::Poll::NotReady,
$crate::Poll::Ok(t) => Ok(t),
$crate::Poll::Err(e) => Err(e),
})
}
/// Possible return values from the `Future::poll` method.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Poll<T, E> {
/// Indicates that the future is not ready yet, ask again later.
NotReady,
/// Indicates that the future has completed successfully, and this value is
/// what the future completed with.
Ok(T),
/// Indicates that the future has failed, and this error is what the future
/// failed with.
Err(E),
}
impl<T, E> Poll<T, E> {
/// Change the success type of this `Poll` value with the closure provided
pub fn map<F, U>(self, f: F) -> Poll<U, E>
where F: FnOnce(T) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(f(t)),
Poll::Err(e) => Poll::Err(e),
}
}
/// Change the error type of this `Poll` value with the closure provided
pub fn map_err<F, U>(self, f: F) -> Poll<T, U>
where F: FnOnce(E) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(t),
Poll::Err(e) => Poll::Err(f(e)),
}
}
/// Returns whether this is `Poll::NotReady`
pub fn is_not_ready(&self) -> bool {
match *self {
Poll::NotReady => true,
_ => false,
}
}
/// Returns whether this is either `Poll::Ok` or `Poll::Err`
pub fn is_ready(&self) -> bool {
!self.is_not_ready()
}
/// Unwraps this `Poll` into a `Result`, panicking if it's not ready.
pub fn unwrap(self) -> Result<T, E>
|
}
impl<T, E> From<Result<T, E>> for Poll<T, E> {
fn from(r: Result<T, E>) -> Poll<T, E> {
match r {
Ok(t) => Poll::Ok(t),
Err(t) => Poll::Err(t),
}
}
}
|
{
match self {
Poll::Ok(t) => Ok(t),
Poll::Err(t) => Err(t),
Poll::NotReady => panic!("unwrapping a Poll that wasn't ready"),
}
}
|
identifier_body
|
poll.rs
|
/// A macro.
#[macro_export]
macro_rules! try_poll {
($e:expr) => (match $e {
$crate::Poll::NotReady => return $crate::Poll::NotReady,
$crate::Poll::Ok(t) => Ok(t),
$crate::Poll::Err(e) => Err(e),
})
}
/// Possible return values from the `Future::poll` method.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Poll<T, E> {
/// Indicates that the future is not ready yet, ask again later.
NotReady,
/// Indicates that the future has completed successfully, and this value is
|
Ok(T),
/// Indicates that the future has failed, and this error is what the future
/// failed with.
Err(E),
}
impl<T, E> Poll<T, E> {
/// Change the success type of this `Poll` value with the closure provided
pub fn map<F, U>(self, f: F) -> Poll<U, E>
where F: FnOnce(T) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(f(t)),
Poll::Err(e) => Poll::Err(e),
}
}
/// Change the error type of this `Poll` value with the closure provided
pub fn map_err<F, U>(self, f: F) -> Poll<T, U>
where F: FnOnce(E) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(t),
Poll::Err(e) => Poll::Err(f(e)),
}
}
/// Returns whether this is `Poll::NotReady`
pub fn is_not_ready(&self) -> bool {
match *self {
Poll::NotReady => true,
_ => false,
}
}
/// Returns whether this is either `Poll::Ok` or `Poll::Err`
pub fn is_ready(&self) -> bool {
!self.is_not_ready()
}
/// Unwraps this `Poll` into a `Result`, panicking if it's not ready.
pub fn unwrap(self) -> Result<T, E> {
match self {
Poll::Ok(t) => Ok(t),
Poll::Err(t) => Err(t),
Poll::NotReady => panic!("unwrapping a Poll that wasn't ready"),
}
}
}
impl<T, E> From<Result<T, E>> for Poll<T, E> {
fn from(r: Result<T, E>) -> Poll<T, E> {
match r {
Ok(t) => Poll::Ok(t),
Err(t) => Poll::Err(t),
}
}
}
|
/// what the future completed with.
|
random_line_split
|
poll.rs
|
/// A macro.
#[macro_export]
macro_rules! try_poll {
($e:expr) => (match $e {
$crate::Poll::NotReady => return $crate::Poll::NotReady,
$crate::Poll::Ok(t) => Ok(t),
$crate::Poll::Err(e) => Err(e),
})
}
/// Possible return values from the `Future::poll` method.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Poll<T, E> {
/// Indicates that the future is not ready yet, ask again later.
NotReady,
/// Indicates that the future has completed successfully, and this value is
/// what the future completed with.
Ok(T),
/// Indicates that the future has failed, and this error is what the future
/// failed with.
Err(E),
}
impl<T, E> Poll<T, E> {
/// Change the success type of this `Poll` value with the closure provided
pub fn
|
<F, U>(self, f: F) -> Poll<U, E>
where F: FnOnce(T) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(f(t)),
Poll::Err(e) => Poll::Err(e),
}
}
/// Change the error type of this `Poll` value with the closure provided
pub fn map_err<F, U>(self, f: F) -> Poll<T, U>
where F: FnOnce(E) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(t),
Poll::Err(e) => Poll::Err(f(e)),
}
}
/// Returns whether this is `Poll::NotReady`
pub fn is_not_ready(&self) -> bool {
match *self {
Poll::NotReady => true,
_ => false,
}
}
/// Returns whether this is either `Poll::Ok` or `Poll::Err`
pub fn is_ready(&self) -> bool {
!self.is_not_ready()
}
/// Unwraps this `Poll` into a `Result`, panicking if it's not ready.
pub fn unwrap(self) -> Result<T, E> {
match self {
Poll::Ok(t) => Ok(t),
Poll::Err(t) => Err(t),
Poll::NotReady => panic!("unwrapping a Poll that wasn't ready"),
}
}
}
impl<T, E> From<Result<T, E>> for Poll<T, E> {
fn from(r: Result<T, E>) -> Poll<T, E> {
match r {
Ok(t) => Poll::Ok(t),
Err(t) => Poll::Err(t),
}
}
}
|
map
|
identifier_name
|
lcm.rs
|
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
assert_eq!(x.lcm(y), out);
let mut x = x;
x.lcm_assign(y);
assert_eq!(x, out);
}
test::<u8>(0, 0, 0);
test::<u16>(0, 6, 0);
test::<u32>(6, 0, 0);
test::<u64>(1, 6, 6);
test::<u128>(6, 1, 6);
test::<usize>(8, 12, 24);
test::<u8>(54, 24, 216);
test::<u16>(42, 56, 168);
test::<u32>(48, 18, 144);
test::<u64>(3, 5, 15);
test::<u128>(12, 60, 60);
test::<usize>(12, 90, 180);
}
fn lcm_fail_helper<T: PrimitiveUnsigned>() {
assert_panic!(T::MAX.lcm(T::TWO));
assert_panic!({
let mut x = T::MAX;
x.lcm_assign(T::TWO);
});
|
#[test]
fn lcm_fail() {
apply_fn_to_unsigneds!(lcm_fail_helper);
}
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
test::<u64>(1, 6, Some(6));
test::<u128>(6, 1, Some(6));
test::<usize>(8, 12, Some(24));
test::<u8>(54, 24, Some(216));
test::<u16>(42, 56, Some(168));
test::<u32>(48, 18, Some(144));
test::<u64>(3, 5, Some(15));
test::<u128>(12, 60, Some(60));
test::<usize>(12, 90, Some(180));
test::<usize>(usize::MAX, 2, None);
}
fn lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_34::<T>().test_properties(|(x, y)| {
let lcm = x.lcm(y);
let mut x_mut = x;
x_mut.lcm_assign(y);
assert_eq!(x_mut, lcm);
assert_eq!(y.lcm(x), lcm);
assert!(lcm.divisible_by(x));
assert!(lcm.divisible_by(y));
let gcd = x.gcd(y);
if x!= T::ZERO {
assert_eq!(lcm / x * gcd, y);
}
if y!= T::ZERO {
assert_eq!(lcm / y * gcd, x);
}
if gcd!= T::ZERO {
assert_eq!(x / gcd * y, lcm);
}
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.lcm(x), x);
assert_eq!(x.lcm(T::ONE), x);
assert_eq!(x.lcm(T::ZERO), T::ZERO);
});
}
#[test]
fn lcm_properties() {
apply_fn_to_unsigneds!(lcm_properties_helper);
}
fn checked_lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_33::<T>().test_properties(|(x, y)| {
let lcm = x.checked_lcm(y);
assert_eq!(y.checked_lcm(x), lcm);
if let Some(lcm) = lcm {
assert_eq!(x.lcm(y), lcm);
}
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.checked_lcm(x), Some(x));
assert_eq!(x.checked_lcm(T::ONE), Some(x));
assert_eq!(x.checked_lcm(T::ZERO), Some(T::ZERO));
});
unsigned_triple_gen_var_19::<T>().test_properties(|(x, y, z)| {
if x!= T::ZERO && y!= T::ZERO && z!= T::ZERO {
assert_eq!(
x.checked_lcm(y).and_then(|n| n.checked_lcm(z)),
y.checked_lcm(z).and_then(|n| x.checked_lcm(n))
);
}
});
}
#[test]
fn checked_lcm_properties() {
apply_fn_to_unsigneds!(checked_lcm_properties_helper);
}
|
}
|
random_line_split
|
lcm.rs
|
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn
|
<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
assert_eq!(x.lcm(y), out);
let mut x = x;
x.lcm_assign(y);
assert_eq!(x, out);
}
test::<u8>(0, 0, 0);
test::<u16>(0, 6, 0);
test::<u32>(6, 0, 0);
test::<u64>(1, 6, 6);
test::<u128>(6, 1, 6);
test::<usize>(8, 12, 24);
test::<u8>(54, 24, 216);
test::<u16>(42, 56, 168);
test::<u32>(48, 18, 144);
test::<u64>(3, 5, 15);
test::<u128>(12, 60, 60);
test::<usize>(12, 90, 180);
}
fn lcm_fail_helper<T: PrimitiveUnsigned>() {
assert_panic!(T::MAX.lcm(T::TWO));
assert_panic!({
let mut x = T::MAX;
x.lcm_assign(T::TWO);
});
}
#[test]
fn lcm_fail() {
apply_fn_to_unsigneds!(lcm_fail_helper);
}
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
test::<u64>(1, 6, Some(6));
test::<u128>(6, 1, Some(6));
test::<usize>(8, 12, Some(24));
test::<u8>(54, 24, Some(216));
test::<u16>(42, 56, Some(168));
test::<u32>(48, 18, Some(144));
test::<u64>(3, 5, Some(15));
test::<u128>(12, 60, Some(60));
test::<usize>(12, 90, Some(180));
test::<usize>(usize::MAX, 2, None);
}
fn lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_34::<T>().test_properties(|(x, y)| {
let lcm = x.lcm(y);
let mut x_mut = x;
x_mut.lcm_assign(y);
assert_eq!(x_mut, lcm);
assert_eq!(y.lcm(x), lcm);
assert!(lcm.divisible_by(x));
assert!(lcm.divisible_by(y));
let gcd = x.gcd(y);
if x!= T::ZERO {
assert_eq!(lcm / x * gcd, y);
}
if y!= T::ZERO {
assert_eq!(lcm / y * gcd, x);
}
if gcd!= T::ZERO {
assert_eq!(x / gcd * y, lcm);
}
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.lcm(x), x);
assert_eq!(x.lcm(T::ONE), x);
assert_eq!(x.lcm(T::ZERO), T::ZERO);
});
}
#[test]
fn lcm_properties() {
apply_fn_to_unsigneds!(lcm_properties_helper);
}
fn checked_lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_33::<T>().test_properties(|(x, y)| {
let lcm = x.checked_lcm(y);
assert_eq!(y.checked_lcm(x), lcm);
if let Some(lcm) = lcm {
assert_eq!(x.lcm(y), lcm);
}
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.checked_lcm(x), Some(x));
assert_eq!(x.checked_lcm(T::ONE), Some(x));
assert_eq!(x.checked_lcm(T::ZERO), Some(T::ZERO));
});
unsigned_triple_gen_var_19::<T>().test_properties(|(x, y, z)| {
if x!= T::ZERO && y!= T::ZERO && z!= T::ZERO {
assert_eq!(
x.checked_lcm(y).and_then(|n| n.checked_lcm(z)),
y.checked_lcm(z).and_then(|n| x.checked_lcm(n))
);
}
});
}
#[test]
fn checked_lcm_properties() {
apply_fn_to_unsigneds!(checked_lcm_properties_helper);
}
|
test
|
identifier_name
|
lcm.rs
|
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
assert_eq!(x.lcm(y), out);
let mut x = x;
x.lcm_assign(y);
assert_eq!(x, out);
}
test::<u8>(0, 0, 0);
test::<u16>(0, 6, 0);
test::<u32>(6, 0, 0);
test::<u64>(1, 6, 6);
test::<u128>(6, 1, 6);
test::<usize>(8, 12, 24);
test::<u8>(54, 24, 216);
test::<u16>(42, 56, 168);
test::<u32>(48, 18, 144);
test::<u64>(3, 5, 15);
test::<u128>(12, 60, 60);
test::<usize>(12, 90, 180);
}
fn lcm_fail_helper<T: PrimitiveUnsigned>() {
assert_panic!(T::MAX.lcm(T::TWO));
assert_panic!({
let mut x = T::MAX;
x.lcm_assign(T::TWO);
});
}
#[test]
fn lcm_fail() {
apply_fn_to_unsigneds!(lcm_fail_helper);
}
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
test::<u64>(1, 6, Some(6));
test::<u128>(6, 1, Some(6));
test::<usize>(8, 12, Some(24));
test::<u8>(54, 24, Some(216));
test::<u16>(42, 56, Some(168));
test::<u32>(48, 18, Some(144));
test::<u64>(3, 5, Some(15));
test::<u128>(12, 60, Some(60));
test::<usize>(12, 90, Some(180));
test::<usize>(usize::MAX, 2, None);
}
fn lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_34::<T>().test_properties(|(x, y)| {
let lcm = x.lcm(y);
let mut x_mut = x;
x_mut.lcm_assign(y);
assert_eq!(x_mut, lcm);
assert_eq!(y.lcm(x), lcm);
assert!(lcm.divisible_by(x));
assert!(lcm.divisible_by(y));
let gcd = x.gcd(y);
if x!= T::ZERO {
assert_eq!(lcm / x * gcd, y);
}
if y!= T::ZERO {
assert_eq!(lcm / y * gcd, x);
}
if gcd!= T::ZERO {
assert_eq!(x / gcd * y, lcm);
}
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.lcm(x), x);
assert_eq!(x.lcm(T::ONE), x);
assert_eq!(x.lcm(T::ZERO), T::ZERO);
});
}
#[test]
fn lcm_properties() {
apply_fn_to_unsigneds!(lcm_properties_helper);
}
fn checked_lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_33::<T>().test_properties(|(x, y)| {
let lcm = x.checked_lcm(y);
assert_eq!(y.checked_lcm(x), lcm);
if let Some(lcm) = lcm
|
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.checked_lcm(x), Some(x));
assert_eq!(x.checked_lcm(T::ONE), Some(x));
assert_eq!(x.checked_lcm(T::ZERO), Some(T::ZERO));
});
unsigned_triple_gen_var_19::<T>().test_properties(|(x, y, z)| {
if x!= T::ZERO && y!= T::ZERO && z!= T::ZERO {
assert_eq!(
x.checked_lcm(y).and_then(|n| n.checked_lcm(z)),
y.checked_lcm(z).and_then(|n| x.checked_lcm(n))
);
}
});
}
#[test]
fn checked_lcm_properties() {
apply_fn_to_unsigneds!(checked_lcm_properties_helper);
}
|
{
assert_eq!(x.lcm(y), lcm);
}
|
conditional_block
|
lcm.rs
|
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
assert_eq!(x.lcm(y), out);
let mut x = x;
x.lcm_assign(y);
assert_eq!(x, out);
}
test::<u8>(0, 0, 0);
test::<u16>(0, 6, 0);
test::<u32>(6, 0, 0);
test::<u64>(1, 6, 6);
test::<u128>(6, 1, 6);
test::<usize>(8, 12, 24);
test::<u8>(54, 24, 216);
test::<u16>(42, 56, 168);
test::<u32>(48, 18, 144);
test::<u64>(3, 5, 15);
test::<u128>(12, 60, 60);
test::<usize>(12, 90, 180);
}
fn lcm_fail_helper<T: PrimitiveUnsigned>() {
assert_panic!(T::MAX.lcm(T::TWO));
assert_panic!({
let mut x = T::MAX;
x.lcm_assign(T::TWO);
});
}
#[test]
fn lcm_fail()
|
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
test::<u64>(1, 6, Some(6));
test::<u128>(6, 1, Some(6));
test::<usize>(8, 12, Some(24));
test::<u8>(54, 24, Some(216));
test::<u16>(42, 56, Some(168));
test::<u32>(48, 18, Some(144));
test::<u64>(3, 5, Some(15));
test::<u128>(12, 60, Some(60));
test::<usize>(12, 90, Some(180));
test::<usize>(usize::MAX, 2, None);
}
fn lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_34::<T>().test_properties(|(x, y)| {
let lcm = x.lcm(y);
let mut x_mut = x;
x_mut.lcm_assign(y);
assert_eq!(x_mut, lcm);
assert_eq!(y.lcm(x), lcm);
assert!(lcm.divisible_by(x));
assert!(lcm.divisible_by(y));
let gcd = x.gcd(y);
if x!= T::ZERO {
assert_eq!(lcm / x * gcd, y);
}
if y!= T::ZERO {
assert_eq!(lcm / y * gcd, x);
}
if gcd!= T::ZERO {
assert_eq!(x / gcd * y, lcm);
}
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.lcm(x), x);
assert_eq!(x.lcm(T::ONE), x);
assert_eq!(x.lcm(T::ZERO), T::ZERO);
});
}
#[test]
fn lcm_properties() {
apply_fn_to_unsigneds!(lcm_properties_helper);
}
fn checked_lcm_properties_helper<T: PrimitiveUnsigned>() {
unsigned_pair_gen_var_33::<T>().test_properties(|(x, y)| {
let lcm = x.checked_lcm(y);
assert_eq!(y.checked_lcm(x), lcm);
if let Some(lcm) = lcm {
assert_eq!(x.lcm(y), lcm);
}
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.checked_lcm(x), Some(x));
assert_eq!(x.checked_lcm(T::ONE), Some(x));
assert_eq!(x.checked_lcm(T::ZERO), Some(T::ZERO));
});
unsigned_triple_gen_var_19::<T>().test_properties(|(x, y, z)| {
if x!= T::ZERO && y!= T::ZERO && z!= T::ZERO {
assert_eq!(
x.checked_lcm(y).and_then(|n| n.checked_lcm(z)),
y.checked_lcm(z).and_then(|n| x.checked_lcm(n))
);
}
});
}
#[test]
fn checked_lcm_properties() {
apply_fn_to_unsigneds!(checked_lcm_properties_helper);
}
|
{
apply_fn_to_unsigneds!(lcm_fail_helper);
}
|
identifier_body
|
args.rs
|
// Copyright 2017 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 ffi::OsString;
use marker::PhantomData;
use vec;
use sys::ArgsSysCall;
pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
// On wasm these should always be null, so there's nothing for us to do here
}
pub unsafe fn cleanup() {
}
pub fn args() -> Args {
let v = ArgsSysCall::perform();
Args {
iter: v.into_iter(),
_dont_send_or_sync_me: PhantomData,
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn
|
(&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize {
self.iter.len()
}
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> {
self.iter.next_back()
}
}
|
inner_debug
|
identifier_name
|
args.rs
|
// Copyright 2017 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 ffi::OsString;
use marker::PhantomData;
use vec;
use sys::ArgsSysCall;
pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
// On wasm these should always be null, so there's nothing for us to do here
}
|
Args {
iter: v.into_iter(),
_dont_send_or_sync_me: PhantomData,
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_debug(&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize {
self.iter.len()
}
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> {
self.iter.next_back()
}
}
|
pub unsafe fn cleanup() {
}
pub fn args() -> Args {
let v = ArgsSysCall::perform();
|
random_line_split
|
args.rs
|
// Copyright 2017 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 ffi::OsString;
use marker::PhantomData;
use vec;
use sys::ArgsSysCall;
pub unsafe fn init(_argc: isize, _argv: *const *const u8)
|
pub unsafe fn cleanup() {
}
pub fn args() -> Args {
let v = ArgsSysCall::perform();
Args {
iter: v.into_iter(),
_dont_send_or_sync_me: PhantomData,
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_debug(&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize {
self.iter.len()
}
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> {
self.iter.next_back()
}
}
|
{
// On wasm these should always be null, so there's nothing for us to do here
}
|
identifier_body
|
response.rs
|
use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
hdrs: hdrs,
body: body
}
}
pub fn get_code(&self) -> uint {
self.code
}
pub fn get_headers<'a>(&'a self) -> &'a Headers {
&self.hdrs
}
pub fn get_header<'a>(&'a self, name: &str) -> &'a [String] {
self.hdrs
.find_equiv(name)
.map(|v| v.as_slice())
.unwrap_or(&[])
}
pub fn get_body<'a>(&'a self) -> &'a [u8] {
self.body.as_slice()
}
pub fn move_body(self) -> Vec<u8>
|
}
impl fmt::Show for Response {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::FormatError> {
try!(write!(fmt, "Response {{{}, ", self.code));
for (name, val) in self.hdrs.iter() {
try!(write!(fmt, "{}: {}, ", name, val.connect(", ")));
}
match str::from_utf8(self.body.as_slice()) {
Some(b) => try!(write!(fmt, "{}", b)),
None => try!(write!(fmt, "bytes[{}]", self.body.len()))
}
try!(write!(fmt, "]"));
Ok(())
}
}
|
{
self.body
}
|
identifier_body
|
response.rs
|
use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
hdrs: hdrs,
body: body
}
}
pub fn
|
(&self) -> uint {
self.code
}
pub fn get_headers<'a>(&'a self) -> &'a Headers {
&self.hdrs
}
pub fn get_header<'a>(&'a self, name: &str) -> &'a [String] {
self.hdrs
.find_equiv(name)
.map(|v| v.as_slice())
.unwrap_or(&[])
}
pub fn get_body<'a>(&'a self) -> &'a [u8] {
self.body.as_slice()
}
pub fn move_body(self) -> Vec<u8> {
self.body
}
}
impl fmt::Show for Response {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::FormatError> {
try!(write!(fmt, "Response {{{}, ", self.code));
for (name, val) in self.hdrs.iter() {
try!(write!(fmt, "{}: {}, ", name, val.connect(", ")));
}
match str::from_utf8(self.body.as_slice()) {
Some(b) => try!(write!(fmt, "{}", b)),
None => try!(write!(fmt, "bytes[{}]", self.body.len()))
}
try!(write!(fmt, "]"));
Ok(())
}
}
|
get_code
|
identifier_name
|
response.rs
|
use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
hdrs: hdrs,
body: body
}
}
pub fn get_code(&self) -> uint {
self.code
}
pub fn get_headers<'a>(&'a self) -> &'a Headers {
&self.hdrs
}
pub fn get_header<'a>(&'a self, name: &str) -> &'a [String] {
self.hdrs
.find_equiv(name)
.map(|v| v.as_slice())
.unwrap_or(&[])
}
pub fn get_body<'a>(&'a self) -> &'a [u8] {
self.body.as_slice()
}
pub fn move_body(self) -> Vec<u8> {
self.body
}
}
impl fmt::Show for Response {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::FormatError> {
try!(write!(fmt, "Response {{{}, ", self.code));
for (name, val) in self.hdrs.iter() {
try!(write!(fmt, "{}: {}, ", name, val.connect(", ")));
}
match str::from_utf8(self.body.as_slice()) {
|
Some(b) => try!(write!(fmt, "{}", b)),
None => try!(write!(fmt, "bytes[{}]", self.body.len()))
}
try!(write!(fmt, "]"));
Ok(())
}
}
|
random_line_split
|
|
aarch64_linux_android.rs
|
use crate::spec::{SanitizerSet, Target, TargetOptions};
// See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
// for target ABI requirements.
pub fn target() -> Target {
Target {
llvm_target: "aarch64-linux-android".to_string(),
pointer_width: 64,
|
// As documented in https://developer.android.com/ndk/guides/cpu-features.html
// the neon (ASIMD) and FP must exist on all android aarch64 targets.
features: "+neon,+fp-armv8".to_string(),
supported_sanitizers: SanitizerSet::CFI | SanitizerSet::HWADDRESS,
..super::android_base::opts()
},
}
}
|
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
options: TargetOptions {
max_atomic_width: Some(128),
|
random_line_split
|
aarch64_linux_android.rs
|
use crate::spec::{SanitizerSet, Target, TargetOptions};
// See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
// for target ABI requirements.
pub fn target() -> Target
|
{
Target {
llvm_target: "aarch64-linux-android".to_string(),
pointer_width: 64,
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
options: TargetOptions {
max_atomic_width: Some(128),
// As documented in https://developer.android.com/ndk/guides/cpu-features.html
// the neon (ASIMD) and FP must exist on all android aarch64 targets.
features: "+neon,+fp-armv8".to_string(),
supported_sanitizers: SanitizerSet::CFI | SanitizerSet::HWADDRESS,
..super::android_base::opts()
},
}
}
|
identifier_body
|
|
aarch64_linux_android.rs
|
use crate::spec::{SanitizerSet, Target, TargetOptions};
// See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
// for target ABI requirements.
pub fn
|
() -> Target {
Target {
llvm_target: "aarch64-linux-android".to_string(),
pointer_width: 64,
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
options: TargetOptions {
max_atomic_width: Some(128),
// As documented in https://developer.android.com/ndk/guides/cpu-features.html
// the neon (ASIMD) and FP must exist on all android aarch64 targets.
features: "+neon,+fp-armv8".to_string(),
supported_sanitizers: SanitizerSet::CFI | SanitizerSet::HWADDRESS,
..super::android_base::opts()
},
}
}
|
target
|
identifier_name
|
count_is_at_least.rs
|
use malachite_base::iterators::count_is_at_least;
use std::iter::repeat;
|
assert_eq!(count_is_at_least(xs.iter(), n), result);
assert_eq!(count_is_at_least(xs.iter().rev(), n), result);
}
#[test]
fn test_count_is_at_least() {
count_is_at_least_helper(&[], 0, true);
count_is_at_least_helper(&[], 1, false);
count_is_at_least_helper(&[5], 0, true);
count_is_at_least_helper(&[5], 1, true);
count_is_at_least_helper(&[5], 2, false);
count_is_at_least_helper(&[1, 2, 3, 4], 4, true);
count_is_at_least_helper(&[1, 2, 3, 4], 5, false);
count_is_at_least_helper(&[4; 100], 90, true);
count_is_at_least_helper(&[4; 100], 101, false);
assert_eq!(count_is_at_least(repeat(10), 20), true);
}
|
fn count_is_at_least_helper(xs: &[u8], n: usize, result: bool) {
|
random_line_split
|
count_is_at_least.rs
|
use malachite_base::iterators::count_is_at_least;
use std::iter::repeat;
fn count_is_at_least_helper(xs: &[u8], n: usize, result: bool) {
assert_eq!(count_is_at_least(xs.iter(), n), result);
assert_eq!(count_is_at_least(xs.iter().rev(), n), result);
}
#[test]
fn test_count_is_at_least()
|
{
count_is_at_least_helper(&[], 0, true);
count_is_at_least_helper(&[], 1, false);
count_is_at_least_helper(&[5], 0, true);
count_is_at_least_helper(&[5], 1, true);
count_is_at_least_helper(&[5], 2, false);
count_is_at_least_helper(&[1, 2, 3, 4], 4, true);
count_is_at_least_helper(&[1, 2, 3, 4], 5, false);
count_is_at_least_helper(&[4; 100], 90, true);
count_is_at_least_helper(&[4; 100], 101, false);
assert_eq!(count_is_at_least(repeat(10), 20), true);
}
|
identifier_body
|
|
count_is_at_least.rs
|
use malachite_base::iterators::count_is_at_least;
use std::iter::repeat;
fn
|
(xs: &[u8], n: usize, result: bool) {
assert_eq!(count_is_at_least(xs.iter(), n), result);
assert_eq!(count_is_at_least(xs.iter().rev(), n), result);
}
#[test]
fn test_count_is_at_least() {
count_is_at_least_helper(&[], 0, true);
count_is_at_least_helper(&[], 1, false);
count_is_at_least_helper(&[5], 0, true);
count_is_at_least_helper(&[5], 1, true);
count_is_at_least_helper(&[5], 2, false);
count_is_at_least_helper(&[1, 2, 3, 4], 4, true);
count_is_at_least_helper(&[1, 2, 3, 4], 5, false);
count_is_at_least_helper(&[4; 100], 90, true);
count_is_at_least_helper(&[4; 100], 101, false);
assert_eq!(count_is_at_least(repeat(10), 20), true);
}
|
count_is_at_least_helper
|
identifier_name
|
main.rs
|
#![recursion_limit = "128"]
#![allow(dead_code)]
#[macro_use]
mod util;
mod dispatch;
use anyhow::Result;
use monger_core::os::OS_NAMES;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about, author)]
enum Options {
/// clear the database files for an installed MongoDB version
Clear {
/// the ID of the MongoDB version whose files should be cleared
#[structopt(name = "ID")]
id: String,
},
/// deletes an installed MongoDB version
Delete {
/// the ID of the MongoDB version to delete
#[structopt(name = "ID")]
id: String,
},
/// manages the default arguments used when starting a mongod
Defaults(Defaults),
/// downloads a MongoDB version from a given URL
Download {
/// the URL to download from
#[structopt(name = "URL")]
url: String,
/// specify a unique identifier for the MongoDB version being downloaded
#[structopt(long)]
id: String,
/// download the MongoDB version even if it already is installed
#[structopt(long, short)]
force: bool,
},
/// downloads a MongoDB version
Get {
/// the MongoDB version to download
#[structopt(name = "VERSION")]
version: String,
/// download the MongoDB version even if it already is installed
#[structopt(long, short)]
force: bool,
/// the OS version to download
#[structopt(long, possible_values(&OS_NAMES))]
os: Option<String>,
/// specify a unique identifier for the MongoDB version being downloaded; if not specified,
/// it will default to the version string (i,e, 'x.y.z')
#[structopt(long)]
id: Option<String>,
},
/// lists installed MongoDB versions
List,
/// deletes versions of MongoDB where a newer stable version of the same minor version is
/// installed
Prune,
/// run a binary of a downloaded MongoDB version
Run {
/// the ID of the MongoDB version of the binary being run
#[structopt(name = "ID")]
id: String,
/// the MongoDB binary to run
#[structopt(name = "BIN")]
bin: String,
/// arguments for the MongoDB binary being run
#[structopt(name = "BIN_ARGS", last(true))]
bin_args: Vec<String>,
},
/// updates monger to the latest version
SelfUpdate,
/// start an installed mongod
Start {
/// the ID of the mongod version to start
#[structopt(name = "ID")]
|
#[structopt(name = "MONGODB_ARGS", last(true))]
mongod_args: Vec<String>,
},
}
#[derive(Debug, StructOpt)]
enum Defaults {
/// clears the previously set default arguments
Clear,
/// prints the default arguments used when starting a mongod
Get,
/// sets the default arguments used when starting a mongod
Set {
#[structopt(name = "ARGS", last(true))]
args: Vec<String>,
},
}
fn main() -> Result<()> {
Options::from_args().dispatch()
}
|
id: String,
/// extra arguments for the mongod being run
|
random_line_split
|
main.rs
|
#![recursion_limit = "128"]
#![allow(dead_code)]
#[macro_use]
mod util;
mod dispatch;
use anyhow::Result;
use monger_core::os::OS_NAMES;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about, author)]
enum
|
{
/// clear the database files for an installed MongoDB version
Clear {
/// the ID of the MongoDB version whose files should be cleared
#[structopt(name = "ID")]
id: String,
},
/// deletes an installed MongoDB version
Delete {
/// the ID of the MongoDB version to delete
#[structopt(name = "ID")]
id: String,
},
/// manages the default arguments used when starting a mongod
Defaults(Defaults),
/// downloads a MongoDB version from a given URL
Download {
/// the URL to download from
#[structopt(name = "URL")]
url: String,
/// specify a unique identifier for the MongoDB version being downloaded
#[structopt(long)]
id: String,
/// download the MongoDB version even if it already is installed
#[structopt(long, short)]
force: bool,
},
/// downloads a MongoDB version
Get {
/// the MongoDB version to download
#[structopt(name = "VERSION")]
version: String,
/// download the MongoDB version even if it already is installed
#[structopt(long, short)]
force: bool,
/// the OS version to download
#[structopt(long, possible_values(&OS_NAMES))]
os: Option<String>,
/// specify a unique identifier for the MongoDB version being downloaded; if not specified,
/// it will default to the version string (i,e, 'x.y.z')
#[structopt(long)]
id: Option<String>,
},
/// lists installed MongoDB versions
List,
/// deletes versions of MongoDB where a newer stable version of the same minor version is
/// installed
Prune,
/// run a binary of a downloaded MongoDB version
Run {
/// the ID of the MongoDB version of the binary being run
#[structopt(name = "ID")]
id: String,
/// the MongoDB binary to run
#[structopt(name = "BIN")]
bin: String,
/// arguments for the MongoDB binary being run
#[structopt(name = "BIN_ARGS", last(true))]
bin_args: Vec<String>,
},
/// updates monger to the latest version
SelfUpdate,
/// start an installed mongod
Start {
/// the ID of the mongod version to start
#[structopt(name = "ID")]
id: String,
/// extra arguments for the mongod being run
#[structopt(name = "MONGODB_ARGS", last(true))]
mongod_args: Vec<String>,
},
}
#[derive(Debug, StructOpt)]
enum Defaults {
/// clears the previously set default arguments
Clear,
/// prints the default arguments used when starting a mongod
Get,
/// sets the default arguments used when starting a mongod
Set {
#[structopt(name = "ARGS", last(true))]
args: Vec<String>,
},
}
fn main() -> Result<()> {
Options::from_args().dispatch()
}
|
Options
|
identifier_name
|
main.rs
|
// tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
extern crate itertools;
use std::fs::OpenOptions;
use std::io::BufReader;
use std::io::BufRead;
use std::io::Write;
use std::io::Seek;
use regex::Regex;
use regex::Captures;
use chrono::*;
use std::env;
use std::fmt;
use std::io::SeekFrom::End;
use std::iter::Iterator;
use itertools::Itertools;
// FIXME: This is my first Rust program, so please forgive the current lack of error handling.
// I just wanted to get something which compiled and ran *on my machine*.
// It probably won't compile or run on your box and you won't be told the reason when it panics.
// It also still has a half-dozen warnings, which I don't yet understand.
// But it does *work* (on my machine).
//
// You need rust to build it: https://www.rust-lang.org/downloads.html
// Build it with: cargo build
//
// Run it with: target/debug/tt <activity description>
// TODO: refactor, the whole program is one function
fn main()
|
// but regain exclusive ownership after the scope is exited
// see: https://stackoverflow.com/questions/33831265/how-to-use-a-file-for-reading-and-writing
{
let reader = BufReader::new(&mut file); // "reader" is borrowing *the* mutable reference to file, for "reader"'s lifetime
for wrapped_line in reader.lines() {
let line = wrapped_line.unwrap();
if date_re.is_match(&line) {
let captures = date_re.captures(&line).unwrap();
let year = captures.at(1).unwrap().parse::<i32>().unwrap();
let month = captures.at(2).unwrap().parse::<u32>().unwrap();
let day = captures.at(3).unwrap().parse::<u32>().unwrap();
latest_date = Some(Local.ymd(year, month, day));
latest_datetime = None;
latest_activity = None;
}
if time_activity_re.is_match(&line) && latest_date!= None {
let captures = time_activity_re.captures(&line).unwrap();
let hour = captures.at(1).unwrap().parse::<u32>().unwrap();
let minute = captures.at(2).unwrap().parse::<u32>().unwrap();
let activity = captures.at(3).unwrap();
latest_datetime = Some(latest_date.unwrap().and_hms(hour, minute, 0));
// this shows use of "if" as an expression
latest_activity = if activity.len() > 0 {
// TODO: if latest_activity already constains a string, clear it and reuse it
// as per: https://stackoverflow.com/questions/33781625/how-to-allocate-a-string-before-you-know-how-big-it-needs-to-be
Some(activity.to_string())
} else {
None
};
}
}
}
file.seek(End(0));
let now = Local::now();
if latest_date == None
|| latest_date.unwrap().year()!= now.year()
|| latest_date.unwrap().month()!= now.month()
|| latest_date.unwrap().day()!= now.day() {
// if today isn't the same date as the latest date found in the file (or one wasn't found in the file)
if (latest_date!= None) { // not an empy file, as far as tt is concerned
file.write_all(b"\n\n");
}
file.write_all(format!("{}\n", now.format("%Y-%m-%d")).as_bytes());
file.write_all(b"\n");
}
let activity = env::args().skip(1).join(" "); // use all arguments (apart from the program name) as a description of an activity
if (activity.len() > 0) {
file.write_all(format!("{} {}\n", now.format("%H:%M"), activity).as_bytes());
} else {
// if there was no latest activity *and* there is no activity, then there's no point in writing a second blank line with just a time
if latest_activity == None {
return;
}
file.write_all(format!("{}\n", now.format("%H:%M")).as_bytes());
}
// "file" is automatically flushed and closed as it goes out of scope - very neat
}
|
{
let filename = "tt.txt";
// open a tt.txt file in the local directory
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(filename)
.unwrap();
// now read the whole file to get the latest state
let date_re = Regex::new(r"^(\d{4})-(\d{2})-(\d{2})").unwrap();
let time_activity_re = Regex::new(r"^(\d{2}):(\d{2})\s*(.*)").unwrap();
// not used yet... let time_hashtag_re = Regex::new(r"^(\d{2}):(\d{2}).*(#[^-\s]*).*").unwrap();
let mut latest_date : Option<Date<Local>> = None;
let mut latest_datetime : Option<DateTime<Local>> = None;
let mut latest_activity : Option<String> = None;
// open a new scope so we can mutably lend the file to the reader
|
identifier_body
|
main.rs
|
// tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
extern crate itertools;
use std::fs::OpenOptions;
use std::io::BufReader;
use std::io::BufRead;
use std::io::Write;
use std::io::Seek;
use regex::Regex;
use regex::Captures;
use chrono::*;
use std::env;
use std::fmt;
use std::io::SeekFrom::End;
use std::iter::Iterator;
use itertools::Itertools;
// FIXME: This is my first Rust program, so please forgive the current lack of error handling.
// I just wanted to get something which compiled and ran *on my machine*.
// It probably won't compile or run on your box and you won't be told the reason when it panics.
// It also still has a half-dozen warnings, which I don't yet understand.
// But it does *work* (on my machine).
//
// You need rust to build it: https://www.rust-lang.org/downloads.html
// Build it with: cargo build
//
// Run it with: target/debug/tt <activity description>
// TODO: refactor, the whole program is one function
fn main() {
let filename = "tt.txt";
// open a tt.txt file in the local directory
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(filename)
.unwrap();
// now read the whole file to get the latest state
let date_re = Regex::new(r"^(\d{4})-(\d{2})-(\d{2})").unwrap();
let time_activity_re = Regex::new(r"^(\d{2}):(\d{2})\s*(.*)").unwrap();
// not used yet... let time_hashtag_re = Regex::new(r"^(\d{2}):(\d{2}).*(#[^-\s]*).*").unwrap();
let mut latest_date : Option<Date<Local>> = None;
let mut latest_datetime : Option<DateTime<Local>> = None;
let mut latest_activity : Option<String> = None;
// open a new scope so we can mutably lend the file to the reader
// but regain exclusive ownership after the scope is exited
// see: https://stackoverflow.com/questions/33831265/how-to-use-a-file-for-reading-and-writing
{
let reader = BufReader::new(&mut file); // "reader" is borrowing *the* mutable reference to file, for "reader"'s lifetime
for wrapped_line in reader.lines() {
let line = wrapped_line.unwrap();
if date_re.is_match(&line) {
let captures = date_re.captures(&line).unwrap();
let year = captures.at(1).unwrap().parse::<i32>().unwrap();
let month = captures.at(2).unwrap().parse::<u32>().unwrap();
let day = captures.at(3).unwrap().parse::<u32>().unwrap();
latest_date = Some(Local.ymd(year, month, day));
latest_datetime = None;
latest_activity = None;
}
if time_activity_re.is_match(&line) && latest_date!= None
|
}
}
file.seek(End(0));
let now = Local::now();
if latest_date == None
|| latest_date.unwrap().year()!= now.year()
|| latest_date.unwrap().month()!= now.month()
|| latest_date.unwrap().day()!= now.day() {
// if today isn't the same date as the latest date found in the file (or one wasn't found in the file)
if (latest_date!= None) { // not an empy file, as far as tt is concerned
file.write_all(b"\n\n");
}
file.write_all(format!("{}\n", now.format("%Y-%m-%d")).as_bytes());
file.write_all(b"\n");
}
let activity = env::args().skip(1).join(" "); // use all arguments (apart from the program name) as a description of an activity
if (activity.len() > 0) {
file.write_all(format!("{} {}\n", now.format("%H:%M"), activity).as_bytes());
} else {
// if there was no latest activity *and* there is no activity, then there's no point in writing a second blank line with just a time
if latest_activity == None {
return;
}
file.write_all(format!("{}\n", now.format("%H:%M")).as_bytes());
}
// "file" is automatically flushed and closed as it goes out of scope - very neat
}
|
{
let captures = time_activity_re.captures(&line).unwrap();
let hour = captures.at(1).unwrap().parse::<u32>().unwrap();
let minute = captures.at(2).unwrap().parse::<u32>().unwrap();
let activity = captures.at(3).unwrap();
latest_datetime = Some(latest_date.unwrap().and_hms(hour, minute, 0));
// this shows use of "if" as an expression
latest_activity = if activity.len() > 0 {
// TODO: if latest_activity already constains a string, clear it and reuse it
// as per: https://stackoverflow.com/questions/33781625/how-to-allocate-a-string-before-you-know-how-big-it-needs-to-be
Some(activity.to_string())
} else {
None
};
}
|
conditional_block
|
main.rs
|
// tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
extern crate itertools;
use std::fs::OpenOptions;
use std::io::BufReader;
use std::io::BufRead;
use std::io::Write;
use std::io::Seek;
use regex::Regex;
use regex::Captures;
use chrono::*;
use std::env;
use std::fmt;
use std::io::SeekFrom::End;
use std::iter::Iterator;
use itertools::Itertools;
// FIXME: This is my first Rust program, so please forgive the current lack of error handling.
// I just wanted to get something which compiled and ran *on my machine*.
// It probably won't compile or run on your box and you won't be told the reason when it panics.
// It also still has a half-dozen warnings, which I don't yet understand.
// But it does *work* (on my machine).
//
// You need rust to build it: https://www.rust-lang.org/downloads.html
// Build it with: cargo build
//
// Run it with: target/debug/tt <activity description>
// TODO: refactor, the whole program is one function
fn
|
() {
let filename = "tt.txt";
// open a tt.txt file in the local directory
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(filename)
.unwrap();
// now read the whole file to get the latest state
let date_re = Regex::new(r"^(\d{4})-(\d{2})-(\d{2})").unwrap();
let time_activity_re = Regex::new(r"^(\d{2}):(\d{2})\s*(.*)").unwrap();
// not used yet... let time_hashtag_re = Regex::new(r"^(\d{2}):(\d{2}).*(#[^-\s]*).*").unwrap();
let mut latest_date : Option<Date<Local>> = None;
let mut latest_datetime : Option<DateTime<Local>> = None;
let mut latest_activity : Option<String> = None;
// open a new scope so we can mutably lend the file to the reader
// but regain exclusive ownership after the scope is exited
// see: https://stackoverflow.com/questions/33831265/how-to-use-a-file-for-reading-and-writing
{
let reader = BufReader::new(&mut file); // "reader" is borrowing *the* mutable reference to file, for "reader"'s lifetime
for wrapped_line in reader.lines() {
let line = wrapped_line.unwrap();
if date_re.is_match(&line) {
let captures = date_re.captures(&line).unwrap();
let year = captures.at(1).unwrap().parse::<i32>().unwrap();
let month = captures.at(2).unwrap().parse::<u32>().unwrap();
let day = captures.at(3).unwrap().parse::<u32>().unwrap();
latest_date = Some(Local.ymd(year, month, day));
latest_datetime = None;
latest_activity = None;
}
if time_activity_re.is_match(&line) && latest_date!= None {
let captures = time_activity_re.captures(&line).unwrap();
let hour = captures.at(1).unwrap().parse::<u32>().unwrap();
let minute = captures.at(2).unwrap().parse::<u32>().unwrap();
let activity = captures.at(3).unwrap();
latest_datetime = Some(latest_date.unwrap().and_hms(hour, minute, 0));
// this shows use of "if" as an expression
latest_activity = if activity.len() > 0 {
// TODO: if latest_activity already constains a string, clear it and reuse it
// as per: https://stackoverflow.com/questions/33781625/how-to-allocate-a-string-before-you-know-how-big-it-needs-to-be
Some(activity.to_string())
} else {
None
};
}
}
}
file.seek(End(0));
let now = Local::now();
if latest_date == None
|| latest_date.unwrap().year()!= now.year()
|| latest_date.unwrap().month()!= now.month()
|| latest_date.unwrap().day()!= now.day() {
// if today isn't the same date as the latest date found in the file (or one wasn't found in the file)
if (latest_date!= None) { // not an empy file, as far as tt is concerned
file.write_all(b"\n\n");
}
file.write_all(format!("{}\n", now.format("%Y-%m-%d")).as_bytes());
file.write_all(b"\n");
}
let activity = env::args().skip(1).join(" "); // use all arguments (apart from the program name) as a description of an activity
if (activity.len() > 0) {
file.write_all(format!("{} {}\n", now.format("%H:%M"), activity).as_bytes());
} else {
// if there was no latest activity *and* there is no activity, then there's no point in writing a second blank line with just a time
if latest_activity == None {
return;
}
file.write_all(format!("{}\n", now.format("%H:%M")).as_bytes());
}
// "file" is automatically flushed and closed as it goes out of scope - very neat
}
|
main
|
identifier_name
|
main.rs
|
// tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
extern crate itertools;
use std::fs::OpenOptions;
use std::io::BufReader;
use std::io::BufRead;
use std::io::Write;
use std::io::Seek;
use regex::Regex;
use regex::Captures;
use chrono::*;
use std::env;
use std::fmt;
use std::io::SeekFrom::End;
use std::iter::Iterator;
use itertools::Itertools;
// FIXME: This is my first Rust program, so please forgive the current lack of error handling.
// I just wanted to get something which compiled and ran *on my machine*.
// It probably won't compile or run on your box and you won't be told the reason when it panics.
// It also still has a half-dozen warnings, which I don't yet understand.
// But it does *work* (on my machine).
//
// You need rust to build it: https://www.rust-lang.org/downloads.html
// Build it with: cargo build
//
// Run it with: target/debug/tt <activity description>
// TODO: refactor, the whole program is one function
fn main() {
let filename = "tt.txt";
// open a tt.txt file in the local directory
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(filename)
.unwrap();
// now read the whole file to get the latest state
let date_re = Regex::new(r"^(\d{4})-(\d{2})-(\d{2})").unwrap();
let time_activity_re = Regex::new(r"^(\d{2}):(\d{2})\s*(.*)").unwrap();
// not used yet... let time_hashtag_re = Regex::new(r"^(\d{2}):(\d{2}).*(#[^-\s]*).*").unwrap();
let mut latest_date : Option<Date<Local>> = None;
let mut latest_datetime : Option<DateTime<Local>> = None;
let mut latest_activity : Option<String> = None;
// open a new scope so we can mutably lend the file to the reader
// but regain exclusive ownership after the scope is exited
// see: https://stackoverflow.com/questions/33831265/how-to-use-a-file-for-reading-and-writing
{
let reader = BufReader::new(&mut file); // "reader" is borrowing *the* mutable reference to file, for "reader"'s lifetime
for wrapped_line in reader.lines() {
let line = wrapped_line.unwrap();
if date_re.is_match(&line) {
let captures = date_re.captures(&line).unwrap();
let year = captures.at(1).unwrap().parse::<i32>().unwrap();
let month = captures.at(2).unwrap().parse::<u32>().unwrap();
let day = captures.at(3).unwrap().parse::<u32>().unwrap();
latest_date = Some(Local.ymd(year, month, day));
latest_datetime = None;
latest_activity = None;
}
if time_activity_re.is_match(&line) && latest_date!= None {
let captures = time_activity_re.captures(&line).unwrap();
let hour = captures.at(1).unwrap().parse::<u32>().unwrap();
let minute = captures.at(2).unwrap().parse::<u32>().unwrap();
let activity = captures.at(3).unwrap();
latest_datetime = Some(latest_date.unwrap().and_hms(hour, minute, 0));
// this shows use of "if" as an expression
latest_activity = if activity.len() > 0 {
// TODO: if latest_activity already constains a string, clear it and reuse it
// as per: https://stackoverflow.com/questions/33781625/how-to-allocate-a-string-before-you-know-how-big-it-needs-to-be
Some(activity.to_string())
} else {
None
};
}
}
}
file.seek(End(0));
let now = Local::now();
if latest_date == None
|| latest_date.unwrap().year()!= now.year()
|| latest_date.unwrap().month()!= now.month()
|| latest_date.unwrap().day()!= now.day() {
// if today isn't the same date as the latest date found in the file (or one wasn't found in the file)
if (latest_date!= None) { // not an empy file, as far as tt is concerned
file.write_all(b"\n\n");
}
file.write_all(format!("{}\n", now.format("%Y-%m-%d")).as_bytes());
file.write_all(b"\n");
}
|
// if there was no latest activity *and* there is no activity, then there's no point in writing a second blank line with just a time
if latest_activity == None {
return;
}
file.write_all(format!("{}\n", now.format("%H:%M")).as_bytes());
}
// "file" is automatically flushed and closed as it goes out of scope - very neat
}
|
let activity = env::args().skip(1).join(" "); // use all arguments (apart from the program name) as a description of an activity
if (activity.len() > 0) {
file.write_all(format!("{} {}\n", now.format("%H:%M"), activity).as_bytes());
} else {
|
random_line_split
|
tag-align-shape.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[derive(Debug)]
enum a_tag {
a_tag_var(u64)
}
#[derive(Debug)]
struct t_rec {
c8: u8,
t: a_tag
}
pub fn main()
|
{
let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)};
let y = format!("{:?}", x);
println!("y = {:?}", y);
assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string());
}
|
identifier_body
|
|
tag-align-shape.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[derive(Debug)]
enum a_tag {
a_tag_var(u64)
}
#[derive(Debug)]
struct t_rec {
c8: u8,
t: a_tag
}
pub fn main() {
let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)};
let y = format!("{:?}", x);
println!("y = {:?}", y);
assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string());
}
|
random_line_split
|
|
tag-align-shape.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[derive(Debug)]
enum
|
{
a_tag_var(u64)
}
#[derive(Debug)]
struct t_rec {
c8: u8,
t: a_tag
}
pub fn main() {
let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)};
let y = format!("{:?}", x);
println!("y = {:?}", y);
assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string());
}
|
a_tag
|
identifier_name
|
memorize.rs
|
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Memorizer<I, O> {
store: RefCell<HashMap<I, Rc<O>>>,
func: Box<Fn(&Memorizer<I, O>, &I) -> O>,
}
impl<I: Clone + Hash + Eq, O> Memorizer<I, O> {
pub fn
|
(f: Box<Fn(&Self, &I) -> O>) -> Memorizer<I, O> {
Memorizer {
store: RefCell::new(HashMap::new()),
func: f,
}
}
pub fn lookup(&self, i: I) -> Rc<O> {
if!self.store.borrow().contains_key(&i) {
let ref func = self.func;
let new_val = func(self, &i);
self.store.borrow_mut().insert(i.clone(), Rc::new(new_val));
}
self.store.borrow().get(&i).unwrap().clone()
}
}
|
new
|
identifier_name
|
memorize.rs
|
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Memorizer<I, O> {
store: RefCell<HashMap<I, Rc<O>>>,
func: Box<Fn(&Memorizer<I, O>, &I) -> O>,
}
impl<I: Clone + Hash + Eq, O> Memorizer<I, O> {
pub fn new(f: Box<Fn(&Self, &I) -> O>) -> Memorizer<I, O> {
|
}
}
pub fn lookup(&self, i: I) -> Rc<O> {
if!self.store.borrow().contains_key(&i) {
let ref func = self.func;
let new_val = func(self, &i);
self.store.borrow_mut().insert(i.clone(), Rc::new(new_val));
}
self.store.borrow().get(&i).unwrap().clone()
}
}
|
Memorizer {
store: RefCell::new(HashMap::new()),
func: f,
|
random_line_split
|
memorize.rs
|
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Memorizer<I, O> {
store: RefCell<HashMap<I, Rc<O>>>,
func: Box<Fn(&Memorizer<I, O>, &I) -> O>,
}
impl<I: Clone + Hash + Eq, O> Memorizer<I, O> {
pub fn new(f: Box<Fn(&Self, &I) -> O>) -> Memorizer<I, O> {
Memorizer {
store: RefCell::new(HashMap::new()),
func: f,
}
}
pub fn lookup(&self, i: I) -> Rc<O> {
if!self.store.borrow().contains_key(&i)
|
self.store.borrow().get(&i).unwrap().clone()
}
}
|
{
let ref func = self.func;
let new_val = func(self, &i);
self.store.borrow_mut().insert(i.clone(), Rc::new(new_val));
}
|
conditional_block
|
border.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Border", inherited=False,
additional_methods=[Method("border_" + side + "_has_nonzero_width",
"bool") for side in ["top", "right", "bottom", "left"]]) %>
% for side in ["top", "right", "bottom", "left"]:
${helpers.predefined_type("border-%s-color" % side, "CSSColor", "::cssparser::Color::CurrentColor")}
% endfor
% for side in ["top", "right", "bottom", "left"]:
|
use app_units::Au;
use cssparser::ToCss;
use std::fmt;
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
#[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser)
-> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue)
}
#[derive(Debug, Clone, PartialEq, HeapSizeOf)]
pub struct SpecifiedValue(pub specified::Length);
pub mod computed_value {
use app_units::Au;
pub type T = Au;
}
#[inline] pub fn get_initial_value() -> computed_value::T {
Au::from_px(3) // medium
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T {
self.0.to_computed_value(context)
}
}
</%helpers:longhand>
% endfor
// FIXME(#4126): when gfx supports painting it, make this Size2D<LengthOrPercentage>
% for corner in ["top-left", "top-right", "bottom-right", "bottom-left"]:
${helpers.predefined_type("border-" + corner + "-radius", "BorderRadiusSize",
"computed::BorderRadiusSize::zero()",
"parse")}
% endfor
${helpers.single_keyword("box-decoration-break", "slice clone", products="gecko")}
${helpers.single_keyword("-moz-float-edge",
"content-box margin-box",
gecko_ffi_name="mFloatEdge",
gecko_constant_prefix="NS_STYLE_FLOAT_EDGE",
products="gecko")}
|
${helpers.predefined_type("border-%s-style" % side, "BorderStyle", "specified::BorderStyle::none", need_clone=True)}
% endfor
% for side in ["top", "right", "bottom", "left"]:
<%helpers:longhand name="border-${side}-width">
|
random_line_split
|
border.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Border", inherited=False,
additional_methods=[Method("border_" + side + "_has_nonzero_width",
"bool") for side in ["top", "right", "bottom", "left"]]) %>
% for side in ["top", "right", "bottom", "left"]:
${helpers.predefined_type("border-%s-color" % side, "CSSColor", "::cssparser::Color::CurrentColor")}
% endfor
% for side in ["top", "right", "bottom", "left"]:
${helpers.predefined_type("border-%s-style" % side, "BorderStyle", "specified::BorderStyle::none", need_clone=True)}
% endfor
% for side in ["top", "right", "bottom", "left"]:
<%helpers:longhand name="border-${side}-width">
use app_units::Au;
use cssparser::ToCss;
use std::fmt;
impl ToCss for SpecifiedValue {
fn
|
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
#[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser)
-> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue)
}
#[derive(Debug, Clone, PartialEq, HeapSizeOf)]
pub struct SpecifiedValue(pub specified::Length);
pub mod computed_value {
use app_units::Au;
pub type T = Au;
}
#[inline] pub fn get_initial_value() -> computed_value::T {
Au::from_px(3) // medium
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T {
self.0.to_computed_value(context)
}
}
</%helpers:longhand>
% endfor
// FIXME(#4126): when gfx supports painting it, make this Size2D<LengthOrPercentage>
% for corner in ["top-left", "top-right", "bottom-right", "bottom-left"]:
${helpers.predefined_type("border-" + corner + "-radius", "BorderRadiusSize",
"computed::BorderRadiusSize::zero()",
"parse")}
% endfor
${helpers.single_keyword("box-decoration-break", "slice clone", products="gecko")}
${helpers.single_keyword("-moz-float-edge",
"content-box margin-box",
gecko_ffi_name="mFloatEdge",
gecko_constant_prefix="NS_STYLE_FLOAT_EDGE",
products="gecko")}
|
to_css
|
identifier_name
|
border.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Border", inherited=False,
additional_methods=[Method("border_" + side + "_has_nonzero_width",
"bool") for side in ["top", "right", "bottom", "left"]]) %>
% for side in ["top", "right", "bottom", "left"]:
${helpers.predefined_type("border-%s-color" % side, "CSSColor", "::cssparser::Color::CurrentColor")}
% endfor
% for side in ["top", "right", "bottom", "left"]:
${helpers.predefined_type("border-%s-style" % side, "BorderStyle", "specified::BorderStyle::none", need_clone=True)}
% endfor
% for side in ["top", "right", "bottom", "left"]:
<%helpers:longhand name="border-${side}-width">
use app_units::Au;
use cssparser::ToCss;
use std::fmt;
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write
|
}
#[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser)
-> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue)
}
#[derive(Debug, Clone, PartialEq, HeapSizeOf)]
pub struct SpecifiedValue(pub specified::Length);
pub mod computed_value {
use app_units::Au;
pub type T = Au;
}
#[inline] pub fn get_initial_value() -> computed_value::T {
Au::from_px(3) // medium
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T {
self.0.to_computed_value(context)
}
}
</%helpers:longhand>
% endfor
// FIXME(#4126): when gfx supports painting it, make this Size2D<LengthOrPercentage>
% for corner in ["top-left", "top-right", "bottom-right", "bottom-left"]:
${helpers.predefined_type("border-" + corner + "-radius", "BorderRadiusSize",
"computed::BorderRadiusSize::zero()",
"parse")}
% endfor
${helpers.single_keyword("box-decoration-break", "slice clone", products="gecko")}
${helpers.single_keyword("-moz-float-edge",
"content-box margin-box",
gecko_ffi_name="mFloatEdge",
gecko_constant_prefix="NS_STYLE_FLOAT_EDGE",
products="gecko")}
|
{
self.0.to_css(dest)
}
|
identifier_body
|
stream.rs
|
// This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Represents a token stream.
use std::fmt;
use std::convert::Into;
use std::ops::Deref;
use engine::parser::token::{self, Token, Type};
use template;
use engine::parser::token::TokenError;
use engine::parser::lexer::job::Cursor;
use api::error::{Traced, Dump};
#[derive(Debug, Default, Clone)]
pub struct Position {
pub line: usize,
pub column: usize,
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{line}:{column}", line = self.line, column = self.column)
}
}
#[derive(Debug)]
pub struct Item {
token: Token,
position: Position,
}
impl Item {
pub fn token(&self) -> &Token {
&self.token
}
pub fn position(&self) -> &Position {
&self.position
}
pub fn expect<T>(&self,
pattern: T,
reason: Option<&'static str>)
-> Result<&Item, Traced<TokenError>>
where T: token::Pattern +'static
{
if pattern.matches(self.token()) {
Ok(&self)
} else {
traced_err!(TokenError::UnexpectedTokenAtItem {
reason: reason,
expected: <token::Pattern as Dump>::dump(&pattern),
found: self.dump(),
})
}
}
}
pub type ItemDump = Item; // may change as soon as we use RefTokens
impl Dump for Item {
type Data = ItemDump;
fn dump(&self) -> Self::Data {
ItemDump {
token: self.token.dump(),
position: self.position.clone(),
}
}
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"token {t} at position {p}",
t = self.token,
p = self.position)
}
}
// #[derive(Default)]
pub struct Stream<'a> {
items: Vec<Item>,
template: &'a template::Raw,
}
impl Into<Token> for Item {
fn into(self) -> Token {
self.token
}
}
impl Deref for Item {
type Target = Token;
fn deref(&self) -> &Token {
&self.token
}
}
pub type Iter<'a> = ::std::slice::Iter<'a, Item>;
pub struct DerefIter<'a> {
items: ::std::slice::Iter<'a, Item>,
}
impl<'a> Iterator for DerefIter<'a> {
type Item = &'a Token;
fn next(&mut self) -> Option<&'a Token> {
self.items.next().map(|i| &i.token)
}
}
#[allow(unused_variables)]
impl<'a> Stream<'a> {
/// Constructor
pub fn new(template: &'a template::Raw) -> Stream<'a> {
Stream {
items: Vec::new(),
template: template, // TODO: rename path??
}
}
pub fn push(&mut self, token: Token, cursor: &Cursor) {
self.items.push(Item {
token: token,
position: Position {
line: cursor.line(),
column: cursor.column(),
},
});
}
pub fn template(&self) -> &template::Raw {
self.template
}
pub fn _is_eof(&self) -> bool {
match self.items.last() {
Some(x) => x.token.is_type(Type::Eof),
None => true,
}
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn as_vec(&self) -> &Vec<Item>
|
pub fn iter(&'a self) -> Iter<'a> {
(&self.items).into_iter()
}
pub fn deref_iter(&'a self) -> DerefIter<'a> {
DerefIter { items: (&self.items).into_iter() }
}
}
impl<'a> fmt::Display for Stream<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let v: Vec<String> = self.items.iter().map(|i| format!("{}", i.token)).collect();
write!(f, "[\n\t{}\n]", v.join("\n\t"))
}
}
impl<'a> fmt::Debug for Stream<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let v: Vec<String> = self.items.iter().map(|i| format!("{:?}", i.token)).collect();
write!(f, "[\n\t{}\n]", v.join("\n\t"))
}
}
#[derive(Debug)]
pub struct StreamDump {
pub template_str: String,
pub items_str: String,
}
impl<'a> Dump for Stream<'a> {
type Data = StreamDump;
fn dump(&self) -> Self::Data {
StreamDump {
template_str: self.template().to_string(),
items_str: self.to_string(),
}
}
}
impl fmt::Display for StreamDump {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
" StreamDump{{ template: {template:?}, items: {items:?}}}",
template = self.template_str,
items = self.items_str)
}
}
// TODO: add another token_iter() to the main implementation [using.map(|i| i.into()) as MapIterator]
impl<'a> IntoIterator for Stream<'a> {
type Item = self::Item;
type IntoIter = <Vec<self::Item> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
|
{
&self.items
}
|
identifier_body
|
stream.rs
|
// This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Represents a token stream.
use std::fmt;
use std::convert::Into;
use std::ops::Deref;
use engine::parser::token::{self, Token, Type};
use template;
use engine::parser::token::TokenError;
use engine::parser::lexer::job::Cursor;
use api::error::{Traced, Dump};
#[derive(Debug, Default, Clone)]
pub struct Position {
pub line: usize,
pub column: usize,
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{line}:{column}", line = self.line, column = self.column)
}
}
#[derive(Debug)]
pub struct Item {
token: Token,
position: Position,
}
impl Item {
pub fn token(&self) -> &Token {
&self.token
}
pub fn position(&self) -> &Position {
&self.position
}
pub fn expect<T>(&self,
pattern: T,
reason: Option<&'static str>)
-> Result<&Item, Traced<TokenError>>
where T: token::Pattern +'static
{
if pattern.matches(self.token()) {
Ok(&self)
} else {
traced_err!(TokenError::UnexpectedTokenAtItem {
reason: reason,
expected: <token::Pattern as Dump>::dump(&pattern),
found: self.dump(),
})
}
}
}
pub type ItemDump = Item; // may change as soon as we use RefTokens
impl Dump for Item {
type Data = ItemDump;
fn dump(&self) -> Self::Data {
ItemDump {
token: self.token.dump(),
position: self.position.clone(),
}
}
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"token {t} at position {p}",
t = self.token,
p = self.position)
}
}
// #[derive(Default)]
pub struct Stream<'a> {
items: Vec<Item>,
template: &'a template::Raw,
}
impl Into<Token> for Item {
fn into(self) -> Token {
self.token
}
}
impl Deref for Item {
type Target = Token;
fn deref(&self) -> &Token {
&self.token
}
}
pub type Iter<'a> = ::std::slice::Iter<'a, Item>;
pub struct DerefIter<'a> {
items: ::std::slice::Iter<'a, Item>,
}
impl<'a> Iterator for DerefIter<'a> {
type Item = &'a Token;
fn next(&mut self) -> Option<&'a Token> {
self.items.next().map(|i| &i.token)
}
}
#[allow(unused_variables)]
impl<'a> Stream<'a> {
/// Constructor
pub fn new(template: &'a template::Raw) -> Stream<'a> {
Stream {
items: Vec::new(),
template: template, // TODO: rename path??
}
}
pub fn push(&mut self, token: Token, cursor: &Cursor) {
self.items.push(Item {
token: token,
position: Position {
line: cursor.line(),
column: cursor.column(),
},
});
}
pub fn template(&self) -> &template::Raw {
self.template
}
pub fn _is_eof(&self) -> bool {
match self.items.last() {
Some(x) => x.token.is_type(Type::Eof),
None => true,
}
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn as_vec(&self) -> &Vec<Item> {
&self.items
}
pub fn iter(&'a self) -> Iter<'a> {
(&self.items).into_iter()
}
pub fn deref_iter(&'a self) -> DerefIter<'a> {
DerefIter { items: (&self.items).into_iter() }
}
}
impl<'a> fmt::Display for Stream<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let v: Vec<String> = self.items.iter().map(|i| format!("{}", i.token)).collect();
write!(f, "[\n\t{}\n]", v.join("\n\t"))
}
}
impl<'a> fmt::Debug for Stream<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let v: Vec<String> = self.items.iter().map(|i| format!("{:?}", i.token)).collect();
write!(f, "[\n\t{}\n]", v.join("\n\t"))
}
}
#[derive(Debug)]
pub struct StreamDump {
pub template_str: String,
pub items_str: String,
}
impl<'a> Dump for Stream<'a> {
type Data = StreamDump;
fn dump(&self) -> Self::Data {
StreamDump {
template_str: self.template().to_string(),
items_str: self.to_string(),
}
}
}
impl fmt::Display for StreamDump {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
" StreamDump{{ template: {template:?}, items: {items:?}}}",
template = self.template_str,
items = self.items_str)
}
}
// TODO: add another token_iter() to the main implementation [using.map(|i| i.into()) as MapIterator]
impl<'a> IntoIterator for Stream<'a> {
type Item = self::Item;
type IntoIter = <Vec<self::Item> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
|
fmt
|
identifier_name
|
stream.rs
|
// This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Represents a token stream.
use std::fmt;
use std::convert::Into;
use std::ops::Deref;
use engine::parser::token::{self, Token, Type};
use template;
use engine::parser::token::TokenError;
use engine::parser::lexer::job::Cursor;
use api::error::{Traced, Dump};
#[derive(Debug, Default, Clone)]
pub struct Position {
pub line: usize,
pub column: usize,
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{line}:{column}", line = self.line, column = self.column)
}
}
#[derive(Debug)]
pub struct Item {
token: Token,
position: Position,
}
impl Item {
pub fn token(&self) -> &Token {
&self.token
}
pub fn position(&self) -> &Position {
&self.position
}
pub fn expect<T>(&self,
pattern: T,
reason: Option<&'static str>)
-> Result<&Item, Traced<TokenError>>
|
Ok(&self)
} else {
traced_err!(TokenError::UnexpectedTokenAtItem {
reason: reason,
expected: <token::Pattern as Dump>::dump(&pattern),
found: self.dump(),
})
}
}
}
pub type ItemDump = Item; // may change as soon as we use RefTokens
impl Dump for Item {
type Data = ItemDump;
fn dump(&self) -> Self::Data {
ItemDump {
token: self.token.dump(),
position: self.position.clone(),
}
}
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"token {t} at position {p}",
t = self.token,
p = self.position)
}
}
// #[derive(Default)]
pub struct Stream<'a> {
items: Vec<Item>,
template: &'a template::Raw,
}
impl Into<Token> for Item {
fn into(self) -> Token {
self.token
}
}
impl Deref for Item {
type Target = Token;
fn deref(&self) -> &Token {
&self.token
}
}
pub type Iter<'a> = ::std::slice::Iter<'a, Item>;
pub struct DerefIter<'a> {
items: ::std::slice::Iter<'a, Item>,
}
impl<'a> Iterator for DerefIter<'a> {
type Item = &'a Token;
fn next(&mut self) -> Option<&'a Token> {
self.items.next().map(|i| &i.token)
}
}
#[allow(unused_variables)]
impl<'a> Stream<'a> {
/// Constructor
pub fn new(template: &'a template::Raw) -> Stream<'a> {
Stream {
items: Vec::new(),
template: template, // TODO: rename path??
}
}
pub fn push(&mut self, token: Token, cursor: &Cursor) {
self.items.push(Item {
token: token,
position: Position {
line: cursor.line(),
column: cursor.column(),
},
});
}
pub fn template(&self) -> &template::Raw {
self.template
}
pub fn _is_eof(&self) -> bool {
match self.items.last() {
Some(x) => x.token.is_type(Type::Eof),
None => true,
}
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn as_vec(&self) -> &Vec<Item> {
&self.items
}
pub fn iter(&'a self) -> Iter<'a> {
(&self.items).into_iter()
}
pub fn deref_iter(&'a self) -> DerefIter<'a> {
DerefIter { items: (&self.items).into_iter() }
}
}
impl<'a> fmt::Display for Stream<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let v: Vec<String> = self.items.iter().map(|i| format!("{}", i.token)).collect();
write!(f, "[\n\t{}\n]", v.join("\n\t"))
}
}
impl<'a> fmt::Debug for Stream<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let v: Vec<String> = self.items.iter().map(|i| format!("{:?}", i.token)).collect();
write!(f, "[\n\t{}\n]", v.join("\n\t"))
}
}
#[derive(Debug)]
pub struct StreamDump {
pub template_str: String,
pub items_str: String,
}
impl<'a> Dump for Stream<'a> {
type Data = StreamDump;
fn dump(&self) -> Self::Data {
StreamDump {
template_str: self.template().to_string(),
items_str: self.to_string(),
}
}
}
impl fmt::Display for StreamDump {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
" StreamDump{{ template: {template:?}, items: {items:?}}}",
template = self.template_str,
items = self.items_str)
}
}
// TODO: add another token_iter() to the main implementation [using.map(|i| i.into()) as MapIterator]
impl<'a> IntoIterator for Stream<'a> {
type Item = self::Item;
type IntoIter = <Vec<self::Item> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
|
where T: token::Pattern + 'static
{
if pattern.matches(self.token()) {
|
random_line_split
|
login.rs
|
use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CliResult, CargoResultExt, Config};
#[derive(Deserialize)]
pub struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_frozen: bool,
flag_locked: bool,
#[serde(rename = "flag_Z")]
flag_z: Vec<String>,
flag_registry: Option<String>,
}
pub const USAGE: &'static str = "
Save an api token from the registry locally. If token is not specified, it will be read from stdin.
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token for
-v, --verbose... Use verbose output (-vv very verbose/build.rs output)
-q, --quiet No output printed to stdout
--color WHEN Coloring: auto, always, never
--frozen Require Cargo.lock and cache are up to date
--locked Require Cargo.lock is up to date
-Z FLAG... Unstable (nightly-only) flags to Cargo
--registry REGISTRY Registry to use
";
pub fn execute(options: Options, config: &mut Config) -> CliResult
|
let src = SourceId::crates_io(config)?;
let mut src = RegistrySource::remote(&src, config);
src.update()?;
let config = src.config()?.unwrap();
options.flag_host.clone().unwrap_or(config.api.unwrap())
}
};
println!("please visit {}me and paste the API Token below", host);
let mut line = String::new();
let input = io::stdin();
input.lock().read_line(&mut line).chain_err(|| {
"failed to read stdin"
})?;
line.trim().to_string()
}
};
ops::registry_login(config, token, options.flag_registry)?;
Ok(())
}
|
{
config.configure(options.flag_verbose,
options.flag_quiet,
&options.flag_color,
options.flag_frozen,
options.flag_locked,
&options.flag_z)?;
if options.flag_registry.is_some() && !config.cli_unstable().unstable_options {
return Err(CargoError::from("registry option is an unstable feature and requires -Zunstable-options to use.").into());
}
let token = match options.arg_token {
Some(token) => token,
None => {
let host = match options.flag_registry {
Some(ref _registry) => {
return Err(CargoError::from("token must be provided when --registry is provided.").into());
}
None => {
|
identifier_body
|
login.rs
|
use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CliResult, CargoResultExt, Config};
#[derive(Deserialize)]
pub struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_frozen: bool,
flag_locked: bool,
|
pub const USAGE: &'static str = "
Save an api token from the registry locally. If token is not specified, it will be read from stdin.
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token for
-v, --verbose... Use verbose output (-vv very verbose/build.rs output)
-q, --quiet No output printed to stdout
--color WHEN Coloring: auto, always, never
--frozen Require Cargo.lock and cache are up to date
--locked Require Cargo.lock is up to date
-Z FLAG... Unstable (nightly-only) flags to Cargo
--registry REGISTRY Registry to use
";
pub fn execute(options: Options, config: &mut Config) -> CliResult {
config.configure(options.flag_verbose,
options.flag_quiet,
&options.flag_color,
options.flag_frozen,
options.flag_locked,
&options.flag_z)?;
if options.flag_registry.is_some() &&!config.cli_unstable().unstable_options {
return Err(CargoError::from("registry option is an unstable feature and requires -Zunstable-options to use.").into());
}
let token = match options.arg_token {
Some(token) => token,
None => {
let host = match options.flag_registry {
Some(ref _registry) => {
return Err(CargoError::from("token must be provided when --registry is provided.").into());
}
None => {
let src = SourceId::crates_io(config)?;
let mut src = RegistrySource::remote(&src, config);
src.update()?;
let config = src.config()?.unwrap();
options.flag_host.clone().unwrap_or(config.api.unwrap())
}
};
println!("please visit {}me and paste the API Token below", host);
let mut line = String::new();
let input = io::stdin();
input.lock().read_line(&mut line).chain_err(|| {
"failed to read stdin"
})?;
line.trim().to_string()
}
};
ops::registry_login(config, token, options.flag_registry)?;
Ok(())
}
|
#[serde(rename = "flag_Z")]
flag_z: Vec<String>,
flag_registry: Option<String>,
}
|
random_line_split
|
login.rs
|
use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CliResult, CargoResultExt, Config};
#[derive(Deserialize)]
pub struct
|
{
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_frozen: bool,
flag_locked: bool,
#[serde(rename = "flag_Z")]
flag_z: Vec<String>,
flag_registry: Option<String>,
}
pub const USAGE: &'static str = "
Save an api token from the registry locally. If token is not specified, it will be read from stdin.
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token for
-v, --verbose... Use verbose output (-vv very verbose/build.rs output)
-q, --quiet No output printed to stdout
--color WHEN Coloring: auto, always, never
--frozen Require Cargo.lock and cache are up to date
--locked Require Cargo.lock is up to date
-Z FLAG... Unstable (nightly-only) flags to Cargo
--registry REGISTRY Registry to use
";
pub fn execute(options: Options, config: &mut Config) -> CliResult {
config.configure(options.flag_verbose,
options.flag_quiet,
&options.flag_color,
options.flag_frozen,
options.flag_locked,
&options.flag_z)?;
if options.flag_registry.is_some() &&!config.cli_unstable().unstable_options {
return Err(CargoError::from("registry option is an unstable feature and requires -Zunstable-options to use.").into());
}
let token = match options.arg_token {
Some(token) => token,
None => {
let host = match options.flag_registry {
Some(ref _registry) => {
return Err(CargoError::from("token must be provided when --registry is provided.").into());
}
None => {
let src = SourceId::crates_io(config)?;
let mut src = RegistrySource::remote(&src, config);
src.update()?;
let config = src.config()?.unwrap();
options.flag_host.clone().unwrap_or(config.api.unwrap())
}
};
println!("please visit {}me and paste the API Token below", host);
let mut line = String::new();
let input = io::stdin();
input.lock().read_line(&mut line).chain_err(|| {
"failed to read stdin"
})?;
line.trim().to_string()
}
};
ops::registry_login(config, token, options.flag_registry)?;
Ok(())
}
|
Options
|
identifier_name
|
latest.rs
|
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
// except according to those terms.
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate xkcd;
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio_core::reactor::Core;
fn main() {
let mut core = Core::new().unwrap();
let client = Client::configure()
.connector(HttpsConnector::new(4, &core.handle()).unwrap())
.build(&core.handle());
// Retrieve the latest comic.
let work = xkcd::comics::latest(&client);
let latest_comic = core.run(work).unwrap();
println!("Latest comic: {:?}", latest_comic);
}
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
|
random_line_split
|
latest.rs
|
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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 crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate xkcd;
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio_core::reactor::Core;
fn main()
|
{
let mut core = Core::new().unwrap();
let client = Client::configure()
.connector(HttpsConnector::new(4, &core.handle()).unwrap())
.build(&core.handle());
// Retrieve the latest comic.
let work = xkcd::comics::latest(&client);
let latest_comic = core.run(work).unwrap();
println!("Latest comic: {:?}", latest_comic);
}
|
identifier_body
|
|
latest.rs
|
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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 crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate xkcd;
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio_core::reactor::Core;
fn
|
() {
let mut core = Core::new().unwrap();
let client = Client::configure()
.connector(HttpsConnector::new(4, &core.handle()).unwrap())
.build(&core.handle());
// Retrieve the latest comic.
let work = xkcd::comics::latest(&client);
let latest_comic = core.run(work).unwrap();
println!("Latest comic: {:?}", latest_comic);
}
|
main
|
identifier_name
|
unused-async.rs
|
// edition:2018
// run-pass
#![allow(dead_code)]
#[must_use]
//~^ WARNING `must_use`
async fn test() -> i32 {
1
}
struct Wowee {}
impl Wowee {
#[must_use]
//~^ WARNING `must_use`
async fn test_method() -> i32 {
1
}
}
/* FIXME(guswynn) update this test when async-fn-in-traits works
trait Doer {
#[must_use]
async fn test_trait_method() -> i32;
WARNING must_use
async fn test_other_trait() -> i32;
}
impl Doer for Wowee {
async fn test_trait_method() -> i32 {
1
}
|
#[must_use]
async fn test_other_trait() -> i32 {
WARNING must_use
1
}
}
*/
fn main() {
}
|
random_line_split
|
|
unused-async.rs
|
// edition:2018
// run-pass
#![allow(dead_code)]
#[must_use]
//~^ WARNING `must_use`
async fn test() -> i32 {
1
}
struct Wowee {}
impl Wowee {
#[must_use]
//~^ WARNING `must_use`
async fn test_method() -> i32 {
1
}
}
/* FIXME(guswynn) update this test when async-fn-in-traits works
trait Doer {
#[must_use]
async fn test_trait_method() -> i32;
WARNING must_use
async fn test_other_trait() -> i32;
}
impl Doer for Wowee {
async fn test_trait_method() -> i32 {
1
}
#[must_use]
async fn test_other_trait() -> i32 {
WARNING must_use
1
}
}
*/
fn main()
|
{
}
|
identifier_body
|
|
unused-async.rs
|
// edition:2018
// run-pass
#![allow(dead_code)]
#[must_use]
//~^ WARNING `must_use`
async fn test() -> i32 {
1
}
struct
|
{}
impl Wowee {
#[must_use]
//~^ WARNING `must_use`
async fn test_method() -> i32 {
1
}
}
/* FIXME(guswynn) update this test when async-fn-in-traits works
trait Doer {
#[must_use]
async fn test_trait_method() -> i32;
WARNING must_use
async fn test_other_trait() -> i32;
}
impl Doer for Wowee {
async fn test_trait_method() -> i32 {
1
}
#[must_use]
async fn test_other_trait() -> i32 {
WARNING must_use
1
}
}
*/
fn main() {
}
|
Wowee
|
identifier_name
|
filesearch.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::cell::RefCell;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
impl Copy for FileMatch {}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
/// Functions with type `pick` take a parent directory as well as
/// a file found in that directory.
pub type pick<'a> = |path: &Path|: 'a -> FileMatch;
pub struct
|
<'a> {
pub sysroot: &'a Path,
pub addl_lib_search_paths: &'a RefCell<Vec<Path>>,
pub triple: &'a str,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
let mut visited_dirs = HashSet::new();
let mut found = false;
debug!("filesearch: searching additional lib search paths [{}]",
self.addl_lib_search_paths.borrow().len());
for path in self.addl_lib_search_paths.borrow().iter() {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if!visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if!found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if!visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn search(&self, pick: pick) {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p|!is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display());
rslt = FileMatches;
}
FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
addl_lib_search_paths: &'a RefCell<Vec<Path>>) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
addl_lib_search_paths: addl_lib_search_paths,
triple: triple,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if!env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if!env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if!env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if!env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir!= "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(target_word_size = "64")]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(target_word_size = "32")]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
}
|
FileSearch
|
identifier_name
|
filesearch.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::cell::RefCell;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
impl Copy for FileMatch {}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
/// Functions with type `pick` take a parent directory as well as
/// a file found in that directory.
pub type pick<'a> = |path: &Path|: 'a -> FileMatch;
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub addl_lib_search_paths: &'a RefCell<Vec<Path>>,
pub triple: &'a str,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
let mut visited_dirs = HashSet::new();
let mut found = false;
debug!("filesearch: searching additional lib search paths [{}]",
self.addl_lib_search_paths.borrow().len());
for path in self.addl_lib_search_paths.borrow().iter() {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if!visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if!found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if!visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn search(&self, pick: pick) {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p|!is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display());
rslt = FileMatches;
}
FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
addl_lib_search_paths: &'a RefCell<Vec<Path>>) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
addl_lib_search_paths: addl_lib_search_paths,
triple: triple,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path
|
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if!env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if!env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if!env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if!env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir!= "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(target_word_size = "64")]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(target_word_size = "32")]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
}
|
{
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
|
identifier_body
|
filesearch.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::cell::RefCell;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
impl Copy for FileMatch {}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
/// Functions with type `pick` take a parent directory as well as
/// a file found in that directory.
pub type pick<'a> = |path: &Path|: 'a -> FileMatch;
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub addl_lib_search_paths: &'a RefCell<Vec<Path>>,
pub triple: &'a str,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
let mut visited_dirs = HashSet::new();
let mut found = false;
debug!("filesearch: searching additional lib search paths [{}]",
self.addl_lib_search_paths.borrow().len());
for path in self.addl_lib_search_paths.borrow().iter() {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if!visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if!found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if!visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn search(&self, pick: pick) {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p|!is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display());
rslt = FileMatches;
}
FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
addl_lib_search_paths: &'a RefCell<Vec<Path>>) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
addl_lib_search_paths: addl_lib_search_paths,
triple: triple,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if!env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if!env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if!env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if!env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir!= "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(target_word_size = "64")]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(target_word_size = "32")]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
|
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
}
|
random_line_split
|
|
font_list.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 super::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem};
use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute};
use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString};
use fontconfig::fontconfig::{FcFontSetDestroy, FcMatchPattern, FcPatternCreate, FcPatternDestroy};
use fontconfig::fontconfig::{
FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString,
};
use fontconfig::fontconfig::{FcObjectSetAdd, FcPatternGetInteger};
use libc::{c_char, c_int};
use std::ffi::CString;
use std::ptr;
static FC_FAMILY: &'static [u8] = b"family\0";
static FC_FILE: &'static [u8] = b"file\0";
static FC_INDEX: &'static [u8] = b"index\0";
static FC_FONTFORMAT: &'static [u8] = b"fontformat\0";
pub fn for_each_available_family<F>(mut callback: F)
where
F: FnMut(String),
{
unsafe {
let config = FcConfigGetCurrent();
let font_set = FcConfigGetFonts(config, FcSetSystem);
for i in 0..((*font_set).nfont as isize) {
let font = (*font_set).fonts.offset(i);
let mut family: *mut FcChar8 = ptr::null_mut();
let mut format: *mut FcChar8 = ptr::null_mut();
let mut v: c_int = 0;
if FcPatternGetString(*font, FC_FONTFORMAT.as_ptr() as *mut c_char, v, &mut format)!=
FcResultMatch
{
continue;
}
// Skip bitmap fonts. They aren't supported by FreeType.
let fontformat = c_str_to_string(format as *const c_char);
if fontformat!= "TrueType" && fontformat!= "CFF" && fontformat!= "Type 1" {
continue;
}
while FcPatternGetString(*font, FC_FAMILY.as_ptr() as *mut c_char, v, &mut family) ==
FcResultMatch
{
let family_name = c_str_to_string(family as *const c_char);
callback(family_name);
v += 1;
}
}
}
}
pub fn for_each_variation<F>(family_name: &str, mut callback: F)
where
F: FnMut(String),
{
debug!("getting variations for {}", family_name);
unsafe {
let config = FcConfigGetCurrent();
let mut font_set = FcConfigGetFonts(config, FcSetSystem);
let font_set_array_ptr = &mut font_set;
let pattern = FcPatternCreate();
assert!(!pattern.is_null());
let family_name_c = CString::new(family_name).unwrap();
let family_name = family_name_c.as_ptr();
let ok = FcPatternAddString(
pattern,
FC_FAMILY.as_ptr() as *mut c_char,
family_name as *mut FcChar8,
);
assert_ne!(ok, 0);
let object_set = FcObjectSetCreate();
assert!(!object_set.is_null());
FcObjectSetAdd(object_set, FC_FILE.as_ptr() as *mut c_char);
FcObjectSetAdd(object_set, FC_INDEX.as_ptr() as *mut c_char);
let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set);
debug!("found {} variations", (*matches).nfont);
for i in 0..((*matches).nfont as isize) {
let font = (*matches).fonts.offset(i);
let mut file: *mut FcChar8 = ptr::null_mut();
let result = FcPatternGetString(*font, FC_FILE.as_ptr() as *mut c_char, 0, &mut file);
let file = if result == FcResultMatch
|
else {
panic!();
};
let mut index: libc::c_int = 0;
let result =
FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut c_char, 0, &mut index);
let index = if result == FcResultMatch {
index
} else {
panic!();
};
debug!("variation file: {}", file);
debug!("variation index: {}", index);
callback(file);
}
FcFontSetDestroy(matches);
FcPatternDestroy(pattern);
FcObjectSetDestroy(object_set);
}
}
pub fn system_default_family(generic_name: &str) -> Option<String> {
let generic_name_c = CString::new(generic_name).unwrap();
let generic_name_ptr = generic_name_c.as_ptr();
unsafe {
let pattern = FcNameParse(generic_name_ptr as *mut FcChar8);
FcConfigSubstitute(ptr::null_mut(), pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
let mut result = 0;
let family_match = FcFontMatch(ptr::null_mut(), pattern, &mut result);
let family_name = if result == FcResultMatch {
let mut match_string: *mut FcChar8 = ptr::null_mut();
FcPatternGetString(
family_match,
FC_FAMILY.as_ptr() as *mut c_char,
0,
&mut match_string,
);
let result = c_str_to_string(match_string as *const c_char);
FcPatternDestroy(family_match);
Some(result)
} else {
None
};
FcPatternDestroy(pattern);
family_name
}
}
pub static SANS_SERIF_FONT_FAMILY: &'static str = "DejaVu Sans";
// Based on gfxPlatformGtk::GetCommonFallbackFonts() in Gecko
pub fn fallback_font_families(codepoint: Option<char>) -> Vec<&'static str> {
let mut families = vec!["DejaVu Serif", "FreeSerif", "DejaVu Sans", "FreeSans"];
if let Some(codepoint) = codepoint {
if is_cjk(codepoint) {
families.push("TakaoPGothic");
families.push("Droid Sans Fallback");
families.push("WenQuanYi Micro Hei");
families.push("NanumGothic");
}
}
families
}
|
{
c_str_to_string(file as *const c_char)
}
|
conditional_block
|
font_list.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 super::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem};
use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute};
use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString};
use fontconfig::fontconfig::{FcFontSetDestroy, FcMatchPattern, FcPatternCreate, FcPatternDestroy};
use fontconfig::fontconfig::{
FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString,
};
use fontconfig::fontconfig::{FcObjectSetAdd, FcPatternGetInteger};
use libc::{c_char, c_int};
use std::ffi::CString;
use std::ptr;
static FC_FAMILY: &'static [u8] = b"family\0";
static FC_FILE: &'static [u8] = b"file\0";
static FC_INDEX: &'static [u8] = b"index\0";
static FC_FONTFORMAT: &'static [u8] = b"fontformat\0";
pub fn for_each_available_family<F>(mut callback: F)
where
F: FnMut(String),
{
unsafe {
let config = FcConfigGetCurrent();
let font_set = FcConfigGetFonts(config, FcSetSystem);
for i in 0..((*font_set).nfont as isize) {
let font = (*font_set).fonts.offset(i);
let mut family: *mut FcChar8 = ptr::null_mut();
let mut format: *mut FcChar8 = ptr::null_mut();
let mut v: c_int = 0;
if FcPatternGetString(*font, FC_FONTFORMAT.as_ptr() as *mut c_char, v, &mut format)!=
FcResultMatch
{
continue;
}
// Skip bitmap fonts. They aren't supported by FreeType.
let fontformat = c_str_to_string(format as *const c_char);
if fontformat!= "TrueType" && fontformat!= "CFF" && fontformat!= "Type 1" {
continue;
}
while FcPatternGetString(*font, FC_FAMILY.as_ptr() as *mut c_char, v, &mut family) ==
FcResultMatch
{
let family_name = c_str_to_string(family as *const c_char);
callback(family_name);
v += 1;
}
}
}
}
pub fn for_each_variation<F>(family_name: &str, mut callback: F)
where
F: FnMut(String),
{
debug!("getting variations for {}", family_name);
unsafe {
let config = FcConfigGetCurrent();
let mut font_set = FcConfigGetFonts(config, FcSetSystem);
let font_set_array_ptr = &mut font_set;
let pattern = FcPatternCreate();
assert!(!pattern.is_null());
let family_name_c = CString::new(family_name).unwrap();
let family_name = family_name_c.as_ptr();
let ok = FcPatternAddString(
pattern,
FC_FAMILY.as_ptr() as *mut c_char,
family_name as *mut FcChar8,
);
assert_ne!(ok, 0);
let object_set = FcObjectSetCreate();
assert!(!object_set.is_null());
FcObjectSetAdd(object_set, FC_FILE.as_ptr() as *mut c_char);
FcObjectSetAdd(object_set, FC_INDEX.as_ptr() as *mut c_char);
let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set);
debug!("found {} variations", (*matches).nfont);
for i in 0..((*matches).nfont as isize) {
let font = (*matches).fonts.offset(i);
let mut file: *mut FcChar8 = ptr::null_mut();
let result = FcPatternGetString(*font, FC_FILE.as_ptr() as *mut c_char, 0, &mut file);
let file = if result == FcResultMatch {
c_str_to_string(file as *const c_char)
} else {
panic!();
};
let mut index: libc::c_int = 0;
let result =
FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut c_char, 0, &mut index);
let index = if result == FcResultMatch {
index
} else {
panic!();
};
debug!("variation file: {}", file);
debug!("variation index: {}", index);
callback(file);
}
FcFontSetDestroy(matches);
FcPatternDestroy(pattern);
FcObjectSetDestroy(object_set);
}
}
pub fn system_default_family(generic_name: &str) -> Option<String> {
let generic_name_c = CString::new(generic_name).unwrap();
let generic_name_ptr = generic_name_c.as_ptr();
unsafe {
let pattern = FcNameParse(generic_name_ptr as *mut FcChar8);
FcConfigSubstitute(ptr::null_mut(), pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
let mut result = 0;
let family_match = FcFontMatch(ptr::null_mut(), pattern, &mut result);
let family_name = if result == FcResultMatch {
let mut match_string: *mut FcChar8 = ptr::null_mut();
FcPatternGetString(
family_match,
FC_FAMILY.as_ptr() as *mut c_char,
0,
&mut match_string,
);
let result = c_str_to_string(match_string as *const c_char);
FcPatternDestroy(family_match);
Some(result)
} else {
None
};
FcPatternDestroy(pattern);
family_name
}
}
pub static SANS_SERIF_FONT_FAMILY: &'static str = "DejaVu Sans";
// Based on gfxPlatformGtk::GetCommonFallbackFonts() in Gecko
pub fn fallback_font_families(codepoint: Option<char>) -> Vec<&'static str> {
let mut families = vec!["DejaVu Serif", "FreeSerif", "DejaVu Sans", "FreeSans"];
if let Some(codepoint) = codepoint {
if is_cjk(codepoint) {
families.push("TakaoPGothic");
families.push("Droid Sans Fallback");
families.push("WenQuanYi Micro Hei");
families.push("NanumGothic");
}
}
families
}
|
random_line_split
|
|
font_list.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 super::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem};
use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute};
use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString};
use fontconfig::fontconfig::{FcFontSetDestroy, FcMatchPattern, FcPatternCreate, FcPatternDestroy};
use fontconfig::fontconfig::{
FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString,
};
use fontconfig::fontconfig::{FcObjectSetAdd, FcPatternGetInteger};
use libc::{c_char, c_int};
use std::ffi::CString;
use std::ptr;
static FC_FAMILY: &'static [u8] = b"family\0";
static FC_FILE: &'static [u8] = b"file\0";
static FC_INDEX: &'static [u8] = b"index\0";
static FC_FONTFORMAT: &'static [u8] = b"fontformat\0";
pub fn for_each_available_family<F>(mut callback: F)
where
F: FnMut(String),
{
unsafe {
let config = FcConfigGetCurrent();
let font_set = FcConfigGetFonts(config, FcSetSystem);
for i in 0..((*font_set).nfont as isize) {
let font = (*font_set).fonts.offset(i);
let mut family: *mut FcChar8 = ptr::null_mut();
let mut format: *mut FcChar8 = ptr::null_mut();
let mut v: c_int = 0;
if FcPatternGetString(*font, FC_FONTFORMAT.as_ptr() as *mut c_char, v, &mut format)!=
FcResultMatch
{
continue;
}
// Skip bitmap fonts. They aren't supported by FreeType.
let fontformat = c_str_to_string(format as *const c_char);
if fontformat!= "TrueType" && fontformat!= "CFF" && fontformat!= "Type 1" {
continue;
}
while FcPatternGetString(*font, FC_FAMILY.as_ptr() as *mut c_char, v, &mut family) ==
FcResultMatch
{
let family_name = c_str_to_string(family as *const c_char);
callback(family_name);
v += 1;
}
}
}
}
pub fn for_each_variation<F>(family_name: &str, mut callback: F)
where
F: FnMut(String),
{
debug!("getting variations for {}", family_name);
unsafe {
let config = FcConfigGetCurrent();
let mut font_set = FcConfigGetFonts(config, FcSetSystem);
let font_set_array_ptr = &mut font_set;
let pattern = FcPatternCreate();
assert!(!pattern.is_null());
let family_name_c = CString::new(family_name).unwrap();
let family_name = family_name_c.as_ptr();
let ok = FcPatternAddString(
pattern,
FC_FAMILY.as_ptr() as *mut c_char,
family_name as *mut FcChar8,
);
assert_ne!(ok, 0);
let object_set = FcObjectSetCreate();
assert!(!object_set.is_null());
FcObjectSetAdd(object_set, FC_FILE.as_ptr() as *mut c_char);
FcObjectSetAdd(object_set, FC_INDEX.as_ptr() as *mut c_char);
let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set);
debug!("found {} variations", (*matches).nfont);
for i in 0..((*matches).nfont as isize) {
let font = (*matches).fonts.offset(i);
let mut file: *mut FcChar8 = ptr::null_mut();
let result = FcPatternGetString(*font, FC_FILE.as_ptr() as *mut c_char, 0, &mut file);
let file = if result == FcResultMatch {
c_str_to_string(file as *const c_char)
} else {
panic!();
};
let mut index: libc::c_int = 0;
let result =
FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut c_char, 0, &mut index);
let index = if result == FcResultMatch {
index
} else {
panic!();
};
debug!("variation file: {}", file);
debug!("variation index: {}", index);
callback(file);
}
FcFontSetDestroy(matches);
FcPatternDestroy(pattern);
FcObjectSetDestroy(object_set);
}
}
pub fn system_default_family(generic_name: &str) -> Option<String> {
let generic_name_c = CString::new(generic_name).unwrap();
let generic_name_ptr = generic_name_c.as_ptr();
unsafe {
let pattern = FcNameParse(generic_name_ptr as *mut FcChar8);
FcConfigSubstitute(ptr::null_mut(), pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
let mut result = 0;
let family_match = FcFontMatch(ptr::null_mut(), pattern, &mut result);
let family_name = if result == FcResultMatch {
let mut match_string: *mut FcChar8 = ptr::null_mut();
FcPatternGetString(
family_match,
FC_FAMILY.as_ptr() as *mut c_char,
0,
&mut match_string,
);
let result = c_str_to_string(match_string as *const c_char);
FcPatternDestroy(family_match);
Some(result)
} else {
None
};
FcPatternDestroy(pattern);
family_name
}
}
pub static SANS_SERIF_FONT_FAMILY: &'static str = "DejaVu Sans";
// Based on gfxPlatformGtk::GetCommonFallbackFonts() in Gecko
pub fn fallback_font_families(codepoint: Option<char>) -> Vec<&'static str>
|
{
let mut families = vec!["DejaVu Serif", "FreeSerif", "DejaVu Sans", "FreeSans"];
if let Some(codepoint) = codepoint {
if is_cjk(codepoint) {
families.push("TakaoPGothic");
families.push("Droid Sans Fallback");
families.push("WenQuanYi Micro Hei");
families.push("NanumGothic");
}
}
families
}
|
identifier_body
|
|
font_list.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 super::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem};
use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute};
use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString};
use fontconfig::fontconfig::{FcFontSetDestroy, FcMatchPattern, FcPatternCreate, FcPatternDestroy};
use fontconfig::fontconfig::{
FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString,
};
use fontconfig::fontconfig::{FcObjectSetAdd, FcPatternGetInteger};
use libc::{c_char, c_int};
use std::ffi::CString;
use std::ptr;
static FC_FAMILY: &'static [u8] = b"family\0";
static FC_FILE: &'static [u8] = b"file\0";
static FC_INDEX: &'static [u8] = b"index\0";
static FC_FONTFORMAT: &'static [u8] = b"fontformat\0";
pub fn for_each_available_family<F>(mut callback: F)
where
F: FnMut(String),
{
unsafe {
let config = FcConfigGetCurrent();
let font_set = FcConfigGetFonts(config, FcSetSystem);
for i in 0..((*font_set).nfont as isize) {
let font = (*font_set).fonts.offset(i);
let mut family: *mut FcChar8 = ptr::null_mut();
let mut format: *mut FcChar8 = ptr::null_mut();
let mut v: c_int = 0;
if FcPatternGetString(*font, FC_FONTFORMAT.as_ptr() as *mut c_char, v, &mut format)!=
FcResultMatch
{
continue;
}
// Skip bitmap fonts. They aren't supported by FreeType.
let fontformat = c_str_to_string(format as *const c_char);
if fontformat!= "TrueType" && fontformat!= "CFF" && fontformat!= "Type 1" {
continue;
}
while FcPatternGetString(*font, FC_FAMILY.as_ptr() as *mut c_char, v, &mut family) ==
FcResultMatch
{
let family_name = c_str_to_string(family as *const c_char);
callback(family_name);
v += 1;
}
}
}
}
pub fn
|
<F>(family_name: &str, mut callback: F)
where
F: FnMut(String),
{
debug!("getting variations for {}", family_name);
unsafe {
let config = FcConfigGetCurrent();
let mut font_set = FcConfigGetFonts(config, FcSetSystem);
let font_set_array_ptr = &mut font_set;
let pattern = FcPatternCreate();
assert!(!pattern.is_null());
let family_name_c = CString::new(family_name).unwrap();
let family_name = family_name_c.as_ptr();
let ok = FcPatternAddString(
pattern,
FC_FAMILY.as_ptr() as *mut c_char,
family_name as *mut FcChar8,
);
assert_ne!(ok, 0);
let object_set = FcObjectSetCreate();
assert!(!object_set.is_null());
FcObjectSetAdd(object_set, FC_FILE.as_ptr() as *mut c_char);
FcObjectSetAdd(object_set, FC_INDEX.as_ptr() as *mut c_char);
let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set);
debug!("found {} variations", (*matches).nfont);
for i in 0..((*matches).nfont as isize) {
let font = (*matches).fonts.offset(i);
let mut file: *mut FcChar8 = ptr::null_mut();
let result = FcPatternGetString(*font, FC_FILE.as_ptr() as *mut c_char, 0, &mut file);
let file = if result == FcResultMatch {
c_str_to_string(file as *const c_char)
} else {
panic!();
};
let mut index: libc::c_int = 0;
let result =
FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut c_char, 0, &mut index);
let index = if result == FcResultMatch {
index
} else {
panic!();
};
debug!("variation file: {}", file);
debug!("variation index: {}", index);
callback(file);
}
FcFontSetDestroy(matches);
FcPatternDestroy(pattern);
FcObjectSetDestroy(object_set);
}
}
pub fn system_default_family(generic_name: &str) -> Option<String> {
let generic_name_c = CString::new(generic_name).unwrap();
let generic_name_ptr = generic_name_c.as_ptr();
unsafe {
let pattern = FcNameParse(generic_name_ptr as *mut FcChar8);
FcConfigSubstitute(ptr::null_mut(), pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
let mut result = 0;
let family_match = FcFontMatch(ptr::null_mut(), pattern, &mut result);
let family_name = if result == FcResultMatch {
let mut match_string: *mut FcChar8 = ptr::null_mut();
FcPatternGetString(
family_match,
FC_FAMILY.as_ptr() as *mut c_char,
0,
&mut match_string,
);
let result = c_str_to_string(match_string as *const c_char);
FcPatternDestroy(family_match);
Some(result)
} else {
None
};
FcPatternDestroy(pattern);
family_name
}
}
pub static SANS_SERIF_FONT_FAMILY: &'static str = "DejaVu Sans";
// Based on gfxPlatformGtk::GetCommonFallbackFonts() in Gecko
pub fn fallback_font_families(codepoint: Option<char>) -> Vec<&'static str> {
let mut families = vec!["DejaVu Serif", "FreeSerif", "DejaVu Sans", "FreeSans"];
if let Some(codepoint) = codepoint {
if is_cjk(codepoint) {
families.push("TakaoPGothic");
families.push("Droid Sans Fallback");
families.push("WenQuanYi Micro Hei");
families.push("NanumGothic");
}
}
families
}
|
for_each_variation
|
identifier_name
|
lib.rs
|
//! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier uses global messaging channels, so anyone that can call out to C
//! within an app can send and receive messages to other parts of the app.
//!
//! You could think of Carrier as a poor-(wo)man's nanomsg, however there are
//! some key differences:
//!
//! 1. Carrier is in-memory only (so, inproc://).
//! 2. Carrier only sends a message to one recipient. In other words, if your
//! app simultaneously sends on and is listening to a channel, there's a
//! chance that your app will dequeue and consume the message before the
//! remote gets it. For this reason, you may want to set up an "incoming"
//! channel that you listen to, and a separate "outgoing" channel the
//! remote listens to (and, conversely, the remove would listen to your
//! outgoing and send to your incoming).
//! 3. Channels do not need to be bound/connected before use. By either doing
//! `send()` or `recv()` on a channel, it is created and can start being
//! used. Once a channel has no messages on it and also has no listeners,
//! it is recycled (removed entirely). This allows you to very cheaply make
//! and use new channels that clean themselves up when finished.
extern crate crossbeam;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quick_error;
mod error;
pub mod c;
use ::std::sync::{Arc, RwLock};
use ::std::collections::HashMap;
use ::crossbeam::sync::MsQueue;
pub use ::error::CError;
use ::error::CResult;
lazy_static! {
static ref CONN: Carrier = Carrier::new().expect("carrier -- global static: failed to create");
}
/// The carrier Queue is a quick and simple wrapper around MsQueue that keeps
/// track of a bit more state than MsQueue does.
struct Queue<T> {
internal: MsQueue<T>,
messages: RwLock<i32>,
users: RwLock<i32>,
}
impl<T> Queue<T> {
/// Create a new carrier queue.
fn new() -> Queue<T> {
Queue {
internal: MsQueue::new(),
messages: RwLock::new(0),
users: RwLock::new(0),
}
}
/// Increment the number of messages this queue has by a certain amount (1).
fn inc_messages(&self, val: i32) {
let mut mguard = self.messages.write().expect("Queue.inc_messages() -- failed to grab write lock");
(*mguard) += val;
}
/// Increment the number of users this queue has by a certain amount (1).
fn inc_users(&self, val: i32) {
let mut uguard = self.users.write().expect("Queue.inc_users() -- failed to grab write lock");
(*uguard) += val;
}
/// Get how many messages this queue currently has listening to it.
fn num_messages(&self) -> i32 {
let mguard = self.messages.read().expect("Queue.num_messages() -- failed to grab read lock");
(*mguard).clone()
}
/// Get how many users this queue currently has listening to it.
fn num_users(&self) -> i32 {
let uguard = self.users.read().expect("Queue.num_users() -- failed to grab read lock");
(*uguard).clone()
}
/// MsQueue.push()
fn push(&self, val: T) {
self.internal.push(val);
self.inc_messages(1);
}
/// MsQueue.try_pop()
fn try_pop(&self) -> Option<T> {
let res = self.internal.try_pop();
if res.is_some() {
self.inc_messages(-1);
} else {
*(self.messages.write().expect("Queue.try_pop() -- failed to grab write lock")) = 0;
}
res
}
/// MsQueue.pop()
fn pop(&self) -> T {
self.inc_users(1);
let res = self.internal.pop();
self.inc_users(-1);
self.inc_messages(-1);
res
}
/// Determine if this queue has been "abandoned"...meaning it has no
/// messages in it and there is nobody listening to it.
fn is_abandoned(&self) -> bool {
if self.num_messages() <= 0 && self.num_users() <= 0 {
true
} else {
false
}
}
}
pub struct Carrier {
queues: RwLock<HashMap<String, Arc<Queue<Vec<u8>>>>>,
}
//unsafe impl Send for Carrier {}
//unsafe impl Sync for Carrier {}
impl Carrier {
/// Create a new carrier
pub fn new() -> CResult<Carrier> {
Ok(Carrier {
queues: RwLock::new(HashMap::new()),
})
}
/// Ensure a channel exists
fn ensure(&self, channel: &String) -> Arc<Queue<Vec<u8>>> {
let mut guard = self.queues.write().expect("Carrier.ensure() -- failed to grab write lock");
if (*guard).contains_key(channel) {
(*guard).get(channel).expect("Carrier.ensure() -- failed to grab map item").clone()
} else {
let queue = Arc::new(Queue::new());
(*guard).insert(channel.clone(), queue.clone());
queue
}
}
fn exists(&self, channel: &String) -> bool {
let guard = self.queues.read().expect("Carrier.exists() -- failed to grab read lock");
(*guard).contains_key(channel)
}
/// Count how many active channels there are
fn count(&self) -> u32 {
let guard = self.queues.read().expect("Carrier.count() -- failed to grab read lock");
(*guard).len() as u32
}
/// Remove a channel
fn remove(&self, channel: &String) {
let mut guard = self.queues.write().expect("Carrier.remove() -- failed to grab write lock");
(*guard).remove(channel);
}
fn wipe(&self) {
let mut guard = self.queues.write().expect("Carrier.wipe() -- failed to grab write lock");
guard.clear();
}
}
/// Send a message on a channel
pub fn send(channel: &str, message: Vec<u8>) -> CResult<()> {
let queue = (*CONN).ensure(&String::from(channel));
queue.push(message);
Ok(())
}
/// Send a message on a channel
pub fn send_string(channel: &str, message: String) -> CResult<()> {
let vec = Vec::from(message.as_bytes());
send(channel, vec)
}
/// Blocking receive
pub fn recv(channel: &str) -> CResult<Vec<u8>> {
let queue = (*CONN).ensure(&String::from(channel));
let res = Ok(queue.pop());
if queue.is_abandoned() { (*CONN).remove(&String::from(channel)); }
res
}
/// Non-blocking receive
pub fn recv_nb(channel: &str) -> CResult<Option<Vec<u8>>> {
let channel = String::from(channel);
if!(*CONN).exists(&channel) {
return Ok(None)
}
let queue = (*CONN).ensure(&channel);
let res = Ok(queue.try_pop());
if queue.is_abandoned() { (*CONN).remove(&channel); }
res
}
/// Returns the number of active channels
pub fn count() -> u32
|
/// Wipe out all queues
pub fn wipe() {
(*CONN).wipe();
}
#[cfg(test)]
mod tests {
use ::std::thread;
use super::*;
use ::std::sync::{Arc, RwLock};
#[test]
fn send_recv_simple() {
send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap();
send_string("sendrecv", String::from("this is another test")).unwrap();
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is a test");
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is another test");
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("nope").unwrap();
assert_eq!(next, None);
}
#[test]
fn recv_blocking() {
let handle = thread::spawn(move || {
send_string("core", String::from("hello, there")).unwrap();
});
let msg = String::from_utf8(recv("core").unwrap()).unwrap();
assert_eq!(msg, "hello, there");
handle.join().unwrap();
}
#[test]
fn lock_testing() {
let num_tests = 999;
let mut handles: Vec<thread::JoinHandle<()>> = Vec::with_capacity(num_tests as usize);
let counter = Arc::new(RwLock::new(0));
for _ in 0..num_tests {
let wcounter = counter.clone();
handles.push(thread::spawn(move || {
let msg = recv("threading").unwrap();
assert_eq!(String::from_utf8(msg).unwrap(), "get a job");
*(wcounter.write().unwrap()) += 1;
}));
}
for _ in 0..num_tests {
handles.push(thread::spawn(|| {
send_string("threading", String::from("get a job")).unwrap();
}));
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(*(counter.read().unwrap()), num_tests);
}
// Would love to test wiping, but running in multi-thread mode screws up the
// other tests, so for now it's disabled.
/*
#[test]
fn wiping() {
send_string("wiper", String::from("this is another test")).unwrap();
send_string("wiper", String::from("yoohoo")).unwrap();
wipe();
assert_eq!(recv_nb("wiper").unwrap(), None);
}
*/
}
|
{
(*CONN).count()
}
|
identifier_body
|
lib.rs
|
//! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier uses global messaging channels, so anyone that can call out to C
//! within an app can send and receive messages to other parts of the app.
//!
//! You could think of Carrier as a poor-(wo)man's nanomsg, however there are
//! some key differences:
//!
//! 1. Carrier is in-memory only (so, inproc://).
//! 2. Carrier only sends a message to one recipient. In other words, if your
//! app simultaneously sends on and is listening to a channel, there's a
//! chance that your app will dequeue and consume the message before the
//! remote gets it. For this reason, you may want to set up an "incoming"
//! channel that you listen to, and a separate "outgoing" channel the
//! remote listens to (and, conversely, the remove would listen to your
//! outgoing and send to your incoming).
//! 3. Channels do not need to be bound/connected before use. By either doing
//! `send()` or `recv()` on a channel, it is created and can start being
//! used. Once a channel has no messages on it and also has no listeners,
//! it is recycled (removed entirely). This allows you to very cheaply make
//! and use new channels that clean themselves up when finished.
extern crate crossbeam;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quick_error;
mod error;
pub mod c;
use ::std::sync::{Arc, RwLock};
use ::std::collections::HashMap;
use ::crossbeam::sync::MsQueue;
pub use ::error::CError;
use ::error::CResult;
lazy_static! {
static ref CONN: Carrier = Carrier::new().expect("carrier -- global static: failed to create");
}
/// The carrier Queue is a quick and simple wrapper around MsQueue that keeps
/// track of a bit more state than MsQueue does.
struct Queue<T> {
internal: MsQueue<T>,
messages: RwLock<i32>,
users: RwLock<i32>,
}
impl<T> Queue<T> {
/// Create a new carrier queue.
fn new() -> Queue<T> {
Queue {
internal: MsQueue::new(),
messages: RwLock::new(0),
users: RwLock::new(0),
}
}
/// Increment the number of messages this queue has by a certain amount (1).
fn
|
(&self, val: i32) {
let mut mguard = self.messages.write().expect("Queue.inc_messages() -- failed to grab write lock");
(*mguard) += val;
}
/// Increment the number of users this queue has by a certain amount (1).
fn inc_users(&self, val: i32) {
let mut uguard = self.users.write().expect("Queue.inc_users() -- failed to grab write lock");
(*uguard) += val;
}
/// Get how many messages this queue currently has listening to it.
fn num_messages(&self) -> i32 {
let mguard = self.messages.read().expect("Queue.num_messages() -- failed to grab read lock");
(*mguard).clone()
}
/// Get how many users this queue currently has listening to it.
fn num_users(&self) -> i32 {
let uguard = self.users.read().expect("Queue.num_users() -- failed to grab read lock");
(*uguard).clone()
}
/// MsQueue.push()
fn push(&self, val: T) {
self.internal.push(val);
self.inc_messages(1);
}
/// MsQueue.try_pop()
fn try_pop(&self) -> Option<T> {
let res = self.internal.try_pop();
if res.is_some() {
self.inc_messages(-1);
} else {
*(self.messages.write().expect("Queue.try_pop() -- failed to grab write lock")) = 0;
}
res
}
/// MsQueue.pop()
fn pop(&self) -> T {
self.inc_users(1);
let res = self.internal.pop();
self.inc_users(-1);
self.inc_messages(-1);
res
}
/// Determine if this queue has been "abandoned"...meaning it has no
/// messages in it and there is nobody listening to it.
fn is_abandoned(&self) -> bool {
if self.num_messages() <= 0 && self.num_users() <= 0 {
true
} else {
false
}
}
}
pub struct Carrier {
queues: RwLock<HashMap<String, Arc<Queue<Vec<u8>>>>>,
}
//unsafe impl Send for Carrier {}
//unsafe impl Sync for Carrier {}
impl Carrier {
/// Create a new carrier
pub fn new() -> CResult<Carrier> {
Ok(Carrier {
queues: RwLock::new(HashMap::new()),
})
}
/// Ensure a channel exists
fn ensure(&self, channel: &String) -> Arc<Queue<Vec<u8>>> {
let mut guard = self.queues.write().expect("Carrier.ensure() -- failed to grab write lock");
if (*guard).contains_key(channel) {
(*guard).get(channel).expect("Carrier.ensure() -- failed to grab map item").clone()
} else {
let queue = Arc::new(Queue::new());
(*guard).insert(channel.clone(), queue.clone());
queue
}
}
fn exists(&self, channel: &String) -> bool {
let guard = self.queues.read().expect("Carrier.exists() -- failed to grab read lock");
(*guard).contains_key(channel)
}
/// Count how many active channels there are
fn count(&self) -> u32 {
let guard = self.queues.read().expect("Carrier.count() -- failed to grab read lock");
(*guard).len() as u32
}
/// Remove a channel
fn remove(&self, channel: &String) {
let mut guard = self.queues.write().expect("Carrier.remove() -- failed to grab write lock");
(*guard).remove(channel);
}
fn wipe(&self) {
let mut guard = self.queues.write().expect("Carrier.wipe() -- failed to grab write lock");
guard.clear();
}
}
/// Send a message on a channel
pub fn send(channel: &str, message: Vec<u8>) -> CResult<()> {
let queue = (*CONN).ensure(&String::from(channel));
queue.push(message);
Ok(())
}
/// Send a message on a channel
pub fn send_string(channel: &str, message: String) -> CResult<()> {
let vec = Vec::from(message.as_bytes());
send(channel, vec)
}
/// Blocking receive
pub fn recv(channel: &str) -> CResult<Vec<u8>> {
let queue = (*CONN).ensure(&String::from(channel));
let res = Ok(queue.pop());
if queue.is_abandoned() { (*CONN).remove(&String::from(channel)); }
res
}
/// Non-blocking receive
pub fn recv_nb(channel: &str) -> CResult<Option<Vec<u8>>> {
let channel = String::from(channel);
if!(*CONN).exists(&channel) {
return Ok(None)
}
let queue = (*CONN).ensure(&channel);
let res = Ok(queue.try_pop());
if queue.is_abandoned() { (*CONN).remove(&channel); }
res
}
/// Returns the number of active channels
pub fn count() -> u32 {
(*CONN).count()
}
/// Wipe out all queues
pub fn wipe() {
(*CONN).wipe();
}
#[cfg(test)]
mod tests {
use ::std::thread;
use super::*;
use ::std::sync::{Arc, RwLock};
#[test]
fn send_recv_simple() {
send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap();
send_string("sendrecv", String::from("this is another test")).unwrap();
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is a test");
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is another test");
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("nope").unwrap();
assert_eq!(next, None);
}
#[test]
fn recv_blocking() {
let handle = thread::spawn(move || {
send_string("core", String::from("hello, there")).unwrap();
});
let msg = String::from_utf8(recv("core").unwrap()).unwrap();
assert_eq!(msg, "hello, there");
handle.join().unwrap();
}
#[test]
fn lock_testing() {
let num_tests = 999;
let mut handles: Vec<thread::JoinHandle<()>> = Vec::with_capacity(num_tests as usize);
let counter = Arc::new(RwLock::new(0));
for _ in 0..num_tests {
let wcounter = counter.clone();
handles.push(thread::spawn(move || {
let msg = recv("threading").unwrap();
assert_eq!(String::from_utf8(msg).unwrap(), "get a job");
*(wcounter.write().unwrap()) += 1;
}));
}
for _ in 0..num_tests {
handles.push(thread::spawn(|| {
send_string("threading", String::from("get a job")).unwrap();
}));
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(*(counter.read().unwrap()), num_tests);
}
// Would love to test wiping, but running in multi-thread mode screws up the
// other tests, so for now it's disabled.
/*
#[test]
fn wiping() {
send_string("wiper", String::from("this is another test")).unwrap();
send_string("wiper", String::from("yoohoo")).unwrap();
wipe();
assert_eq!(recv_nb("wiper").unwrap(), None);
}
*/
}
|
inc_messages
|
identifier_name
|
lib.rs
|
//! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier uses global messaging channels, so anyone that can call out to C
//! within an app can send and receive messages to other parts of the app.
//!
//! You could think of Carrier as a poor-(wo)man's nanomsg, however there are
//! some key differences:
//!
//! 1. Carrier is in-memory only (so, inproc://).
//! 2. Carrier only sends a message to one recipient. In other words, if your
//! app simultaneously sends on and is listening to a channel, there's a
//! chance that your app will dequeue and consume the message before the
//! remote gets it. For this reason, you may want to set up an "incoming"
//! channel that you listen to, and a separate "outgoing" channel the
//! remote listens to (and, conversely, the remove would listen to your
//! outgoing and send to your incoming).
//! 3. Channels do not need to be bound/connected before use. By either doing
//! `send()` or `recv()` on a channel, it is created and can start being
//! used. Once a channel has no messages on it and also has no listeners,
//! it is recycled (removed entirely). This allows you to very cheaply make
//! and use new channels that clean themselves up when finished.
extern crate crossbeam;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quick_error;
mod error;
pub mod c;
use ::std::sync::{Arc, RwLock};
use ::std::collections::HashMap;
use ::crossbeam::sync::MsQueue;
pub use ::error::CError;
use ::error::CResult;
lazy_static! {
static ref CONN: Carrier = Carrier::new().expect("carrier -- global static: failed to create");
}
/// The carrier Queue is a quick and simple wrapper around MsQueue that keeps
/// track of a bit more state than MsQueue does.
struct Queue<T> {
internal: MsQueue<T>,
messages: RwLock<i32>,
users: RwLock<i32>,
}
impl<T> Queue<T> {
/// Create a new carrier queue.
fn new() -> Queue<T> {
Queue {
internal: MsQueue::new(),
messages: RwLock::new(0),
users: RwLock::new(0),
}
}
/// Increment the number of messages this queue has by a certain amount (1).
fn inc_messages(&self, val: i32) {
let mut mguard = self.messages.write().expect("Queue.inc_messages() -- failed to grab write lock");
(*mguard) += val;
}
/// Increment the number of users this queue has by a certain amount (1).
fn inc_users(&self, val: i32) {
let mut uguard = self.users.write().expect("Queue.inc_users() -- failed to grab write lock");
(*uguard) += val;
}
/// Get how many messages this queue currently has listening to it.
fn num_messages(&self) -> i32 {
let mguard = self.messages.read().expect("Queue.num_messages() -- failed to grab read lock");
(*mguard).clone()
}
/// Get how many users this queue currently has listening to it.
fn num_users(&self) -> i32 {
let uguard = self.users.read().expect("Queue.num_users() -- failed to grab read lock");
(*uguard).clone()
}
/// MsQueue.push()
fn push(&self, val: T) {
self.internal.push(val);
self.inc_messages(1);
}
/// MsQueue.try_pop()
fn try_pop(&self) -> Option<T> {
let res = self.internal.try_pop();
if res.is_some() {
self.inc_messages(-1);
} else {
*(self.messages.write().expect("Queue.try_pop() -- failed to grab write lock")) = 0;
}
res
}
/// MsQueue.pop()
fn pop(&self) -> T {
self.inc_users(1);
let res = self.internal.pop();
self.inc_users(-1);
self.inc_messages(-1);
res
}
/// Determine if this queue has been "abandoned"...meaning it has no
/// messages in it and there is nobody listening to it.
fn is_abandoned(&self) -> bool {
if self.num_messages() <= 0 && self.num_users() <= 0 {
true
} else {
false
}
}
}
pub struct Carrier {
queues: RwLock<HashMap<String, Arc<Queue<Vec<u8>>>>>,
}
//unsafe impl Send for Carrier {}
//unsafe impl Sync for Carrier {}
impl Carrier {
/// Create a new carrier
pub fn new() -> CResult<Carrier> {
Ok(Carrier {
queues: RwLock::new(HashMap::new()),
})
}
/// Ensure a channel exists
fn ensure(&self, channel: &String) -> Arc<Queue<Vec<u8>>> {
let mut guard = self.queues.write().expect("Carrier.ensure() -- failed to grab write lock");
if (*guard).contains_key(channel)
|
else {
let queue = Arc::new(Queue::new());
(*guard).insert(channel.clone(), queue.clone());
queue
}
}
fn exists(&self, channel: &String) -> bool {
let guard = self.queues.read().expect("Carrier.exists() -- failed to grab read lock");
(*guard).contains_key(channel)
}
/// Count how many active channels there are
fn count(&self) -> u32 {
let guard = self.queues.read().expect("Carrier.count() -- failed to grab read lock");
(*guard).len() as u32
}
/// Remove a channel
fn remove(&self, channel: &String) {
let mut guard = self.queues.write().expect("Carrier.remove() -- failed to grab write lock");
(*guard).remove(channel);
}
fn wipe(&self) {
let mut guard = self.queues.write().expect("Carrier.wipe() -- failed to grab write lock");
guard.clear();
}
}
/// Send a message on a channel
pub fn send(channel: &str, message: Vec<u8>) -> CResult<()> {
let queue = (*CONN).ensure(&String::from(channel));
queue.push(message);
Ok(())
}
/// Send a message on a channel
pub fn send_string(channel: &str, message: String) -> CResult<()> {
let vec = Vec::from(message.as_bytes());
send(channel, vec)
}
/// Blocking receive
pub fn recv(channel: &str) -> CResult<Vec<u8>> {
let queue = (*CONN).ensure(&String::from(channel));
let res = Ok(queue.pop());
if queue.is_abandoned() { (*CONN).remove(&String::from(channel)); }
res
}
/// Non-blocking receive
pub fn recv_nb(channel: &str) -> CResult<Option<Vec<u8>>> {
let channel = String::from(channel);
if!(*CONN).exists(&channel) {
return Ok(None)
}
let queue = (*CONN).ensure(&channel);
let res = Ok(queue.try_pop());
if queue.is_abandoned() { (*CONN).remove(&channel); }
res
}
/// Returns the number of active channels
pub fn count() -> u32 {
(*CONN).count()
}
/// Wipe out all queues
pub fn wipe() {
(*CONN).wipe();
}
#[cfg(test)]
mod tests {
use ::std::thread;
use super::*;
use ::std::sync::{Arc, RwLock};
#[test]
fn send_recv_simple() {
send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap();
send_string("sendrecv", String::from("this is another test")).unwrap();
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is a test");
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is another test");
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("nope").unwrap();
assert_eq!(next, None);
}
#[test]
fn recv_blocking() {
let handle = thread::spawn(move || {
send_string("core", String::from("hello, there")).unwrap();
});
let msg = String::from_utf8(recv("core").unwrap()).unwrap();
assert_eq!(msg, "hello, there");
handle.join().unwrap();
}
#[test]
fn lock_testing() {
let num_tests = 999;
let mut handles: Vec<thread::JoinHandle<()>> = Vec::with_capacity(num_tests as usize);
let counter = Arc::new(RwLock::new(0));
for _ in 0..num_tests {
let wcounter = counter.clone();
handles.push(thread::spawn(move || {
let msg = recv("threading").unwrap();
assert_eq!(String::from_utf8(msg).unwrap(), "get a job");
*(wcounter.write().unwrap()) += 1;
}));
}
for _ in 0..num_tests {
handles.push(thread::spawn(|| {
send_string("threading", String::from("get a job")).unwrap();
}));
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(*(counter.read().unwrap()), num_tests);
}
// Would love to test wiping, but running in multi-thread mode screws up the
// other tests, so for now it's disabled.
/*
#[test]
fn wiping() {
send_string("wiper", String::from("this is another test")).unwrap();
send_string("wiper", String::from("yoohoo")).unwrap();
wipe();
assert_eq!(recv_nb("wiper").unwrap(), None);
}
*/
}
|
{
(*guard).get(channel).expect("Carrier.ensure() -- failed to grab map item").clone()
}
|
conditional_block
|
lib.rs
|
//! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier uses global messaging channels, so anyone that can call out to C
//! within an app can send and receive messages to other parts of the app.
//!
//! You could think of Carrier as a poor-(wo)man's nanomsg, however there are
//! some key differences:
//!
//! 1. Carrier is in-memory only (so, inproc://).
//! 2. Carrier only sends a message to one recipient. In other words, if your
//! app simultaneously sends on and is listening to a channel, there's a
//! chance that your app will dequeue and consume the message before the
//! remote gets it. For this reason, you may want to set up an "incoming"
//! channel that you listen to, and a separate "outgoing" channel the
//! remote listens to (and, conversely, the remove would listen to your
//! outgoing and send to your incoming).
//! 3. Channels do not need to be bound/connected before use. By either doing
//! `send()` or `recv()` on a channel, it is created and can start being
//! used. Once a channel has no messages on it and also has no listeners,
//! it is recycled (removed entirely). This allows you to very cheaply make
//! and use new channels that clean themselves up when finished.
extern crate crossbeam;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quick_error;
mod error;
pub mod c;
use ::std::sync::{Arc, RwLock};
use ::std::collections::HashMap;
use ::crossbeam::sync::MsQueue;
pub use ::error::CError;
use ::error::CResult;
lazy_static! {
static ref CONN: Carrier = Carrier::new().expect("carrier -- global static: failed to create");
}
/// The carrier Queue is a quick and simple wrapper around MsQueue that keeps
/// track of a bit more state than MsQueue does.
struct Queue<T> {
internal: MsQueue<T>,
messages: RwLock<i32>,
users: RwLock<i32>,
}
impl<T> Queue<T> {
/// Create a new carrier queue.
fn new() -> Queue<T> {
Queue {
internal: MsQueue::new(),
messages: RwLock::new(0),
users: RwLock::new(0),
}
}
/// Increment the number of messages this queue has by a certain amount (1).
fn inc_messages(&self, val: i32) {
let mut mguard = self.messages.write().expect("Queue.inc_messages() -- failed to grab write lock");
(*mguard) += val;
}
/// Increment the number of users this queue has by a certain amount (1).
fn inc_users(&self, val: i32) {
let mut uguard = self.users.write().expect("Queue.inc_users() -- failed to grab write lock");
(*uguard) += val;
}
/// Get how many messages this queue currently has listening to it.
fn num_messages(&self) -> i32 {
let mguard = self.messages.read().expect("Queue.num_messages() -- failed to grab read lock");
(*mguard).clone()
}
/// Get how many users this queue currently has listening to it.
fn num_users(&self) -> i32 {
let uguard = self.users.read().expect("Queue.num_users() -- failed to grab read lock");
(*uguard).clone()
}
/// MsQueue.push()
fn push(&self, val: T) {
self.internal.push(val);
self.inc_messages(1);
}
/// MsQueue.try_pop()
fn try_pop(&self) -> Option<T> {
let res = self.internal.try_pop();
if res.is_some() {
self.inc_messages(-1);
} else {
*(self.messages.write().expect("Queue.try_pop() -- failed to grab write lock")) = 0;
}
res
}
/// MsQueue.pop()
fn pop(&self) -> T {
self.inc_users(1);
let res = self.internal.pop();
self.inc_users(-1);
self.inc_messages(-1);
res
}
/// Determine if this queue has been "abandoned"...meaning it has no
/// messages in it and there is nobody listening to it.
fn is_abandoned(&self) -> bool {
if self.num_messages() <= 0 && self.num_users() <= 0 {
true
} else {
false
}
}
}
pub struct Carrier {
queues: RwLock<HashMap<String, Arc<Queue<Vec<u8>>>>>,
}
//unsafe impl Send for Carrier {}
//unsafe impl Sync for Carrier {}
impl Carrier {
/// Create a new carrier
pub fn new() -> CResult<Carrier> {
Ok(Carrier {
queues: RwLock::new(HashMap::new()),
})
}
/// Ensure a channel exists
fn ensure(&self, channel: &String) -> Arc<Queue<Vec<u8>>> {
let mut guard = self.queues.write().expect("Carrier.ensure() -- failed to grab write lock");
if (*guard).contains_key(channel) {
(*guard).get(channel).expect("Carrier.ensure() -- failed to grab map item").clone()
} else {
let queue = Arc::new(Queue::new());
(*guard).insert(channel.clone(), queue.clone());
queue
}
}
fn exists(&self, channel: &String) -> bool {
let guard = self.queues.read().expect("Carrier.exists() -- failed to grab read lock");
(*guard).contains_key(channel)
}
/// Count how many active channels there are
fn count(&self) -> u32 {
let guard = self.queues.read().expect("Carrier.count() -- failed to grab read lock");
(*guard).len() as u32
}
/// Remove a channel
fn remove(&self, channel: &String) {
let mut guard = self.queues.write().expect("Carrier.remove() -- failed to grab write lock");
(*guard).remove(channel);
}
fn wipe(&self) {
let mut guard = self.queues.write().expect("Carrier.wipe() -- failed to grab write lock");
guard.clear();
}
}
/// Send a message on a channel
pub fn send(channel: &str, message: Vec<u8>) -> CResult<()> {
let queue = (*CONN).ensure(&String::from(channel));
queue.push(message);
Ok(())
}
/// Send a message on a channel
pub fn send_string(channel: &str, message: String) -> CResult<()> {
let vec = Vec::from(message.as_bytes());
send(channel, vec)
}
/// Blocking receive
pub fn recv(channel: &str) -> CResult<Vec<u8>> {
let queue = (*CONN).ensure(&String::from(channel));
let res = Ok(queue.pop());
if queue.is_abandoned() { (*CONN).remove(&String::from(channel)); }
res
}
/// Non-blocking receive
pub fn recv_nb(channel: &str) -> CResult<Option<Vec<u8>>> {
let channel = String::from(channel);
if!(*CONN).exists(&channel) {
return Ok(None)
}
let queue = (*CONN).ensure(&channel);
let res = Ok(queue.try_pop());
if queue.is_abandoned() { (*CONN).remove(&channel); }
res
}
/// Returns the number of active channels
pub fn count() -> u32 {
(*CONN).count()
}
/// Wipe out all queues
pub fn wipe() {
(*CONN).wipe();
}
#[cfg(test)]
mod tests {
use ::std::thread;
use super::*;
use ::std::sync::{Arc, RwLock};
|
fn send_recv_simple() {
send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap();
send_string("sendrecv", String::from("this is another test")).unwrap();
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is a test");
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is another test");
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("sendrecv").unwrap();
assert_eq!(next, None);
let next = recv_nb("nope").unwrap();
assert_eq!(next, None);
}
#[test]
fn recv_blocking() {
let handle = thread::spawn(move || {
send_string("core", String::from("hello, there")).unwrap();
});
let msg = String::from_utf8(recv("core").unwrap()).unwrap();
assert_eq!(msg, "hello, there");
handle.join().unwrap();
}
#[test]
fn lock_testing() {
let num_tests = 999;
let mut handles: Vec<thread::JoinHandle<()>> = Vec::with_capacity(num_tests as usize);
let counter = Arc::new(RwLock::new(0));
for _ in 0..num_tests {
let wcounter = counter.clone();
handles.push(thread::spawn(move || {
let msg = recv("threading").unwrap();
assert_eq!(String::from_utf8(msg).unwrap(), "get a job");
*(wcounter.write().unwrap()) += 1;
}));
}
for _ in 0..num_tests {
handles.push(thread::spawn(|| {
send_string("threading", String::from("get a job")).unwrap();
}));
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(*(counter.read().unwrap()), num_tests);
}
// Would love to test wiping, but running in multi-thread mode screws up the
// other tests, so for now it's disabled.
/*
#[test]
fn wiping() {
send_string("wiper", String::from("this is another test")).unwrap();
send_string("wiper", String::from("yoohoo")).unwrap();
wipe();
assert_eq!(recv_nb("wiper").unwrap(), None);
}
*/
}
|
#[test]
|
random_line_split
|
std_vec.rs
|
use std::cmp::Ordering;
impl<T> Collection for Vec<T> {
type Item = T;
}
impl<T> RetainsOrder for Vec<T> {}
impl<T> Sortable for Vec<T> {
fn sort<F>(&mut self, f: F)
where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
self.sort_by(f);
}
}
impl<T, O> SearchableByOrder<O> for Vec<T>
where
O: SortOrder<T>,
{
fn search(&self, a: &T) -> Result<usize, usize> {
self.binary_search_by(|b| O::cmp(b, a))
}
}
impl<T, O> SortedInsert<O> for Vec<T>
where
O: SortOrder<T>,
Self: Collection<Item = T> + SearchableByOrder<O>,
{
fn insert(&mut self, x: T) {
let i = match self.search(&x) {
Ok(i) => i,
Err(i) => i,
};
self.insert(i, x);
}
}
|
use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert};
|
random_line_split
|
|
std_vec.rs
|
use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert};
use std::cmp::Ordering;
impl<T> Collection for Vec<T> {
type Item = T;
}
impl<T> RetainsOrder for Vec<T> {}
impl<T> Sortable for Vec<T> {
fn sort<F>(&mut self, f: F)
where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
self.sort_by(f);
}
}
impl<T, O> SearchableByOrder<O> for Vec<T>
where
O: SortOrder<T>,
{
fn search(&self, a: &T) -> Result<usize, usize> {
self.binary_search_by(|b| O::cmp(b, a))
}
}
impl<T, O> SortedInsert<O> for Vec<T>
where
O: SortOrder<T>,
Self: Collection<Item = T> + SearchableByOrder<O>,
{
fn
|
(&mut self, x: T) {
let i = match self.search(&x) {
Ok(i) => i,
Err(i) => i,
};
self.insert(i, x);
}
}
|
insert
|
identifier_name
|
std_vec.rs
|
use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert};
use std::cmp::Ordering;
impl<T> Collection for Vec<T> {
type Item = T;
}
impl<T> RetainsOrder for Vec<T> {}
impl<T> Sortable for Vec<T> {
fn sort<F>(&mut self, f: F)
where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
self.sort_by(f);
}
}
impl<T, O> SearchableByOrder<O> for Vec<T>
where
O: SortOrder<T>,
{
fn search(&self, a: &T) -> Result<usize, usize> {
self.binary_search_by(|b| O::cmp(b, a))
}
}
impl<T, O> SortedInsert<O> for Vec<T>
where
O: SortOrder<T>,
Self: Collection<Item = T> + SearchableByOrder<O>,
{
fn insert(&mut self, x: T)
|
}
|
{
let i = match self.search(&x) {
Ok(i) => i,
Err(i) => i,
};
self.insert(i, x);
}
|
identifier_body
|
regex_query.rs
|
use crate::error::TantivyError;
use crate::query::{AutomatonWeight, Query, Weight};
use crate::schema::Field;
use crate::Searcher;
use std::clone::Clone;
use std::sync::Arc;
use tantivy_fst::Regex;
/// A Regex Query matches all of the documents
/// containing a specific term that matches
/// a regex pattern.
///
/// Wildcard queries (e.g. ho*se) can be achieved
/// by converting them to their regex counterparts.
///
/// ```rust
/// use tantivy::collector::Count;
/// use tantivy::query::RegexQuery;
/// use tantivy::schema::{Schema, TEXT};
/// use tantivy::{doc, Index, Term};
///
/// # fn test() -> tantivy::Result<()> {
/// let mut schema_builder = Schema::builder();
/// let title = schema_builder.add_text_field("title", TEXT);
/// let schema = schema_builder.build();
/// let index = Index::create_in_ram(schema);
/// {
/// let mut index_writer = index.writer(3_000_000)?;
/// index_writer.add_document(doc!(
/// title => "The Name of the Wind",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "The Diary of Muadib",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "A Dairy Cow",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "The Diary of a Young Girl",
/// ))?;
/// index_writer.commit()?;
/// }
///
/// let reader = index.reader()?;
/// let searcher = reader.searcher();
///
/// let term = Term::from_field_text(title, "Diary");
/// let query = RegexQuery::from_pattern("d[ai]{2}ry", title)?;
/// let count = searcher.search(&query, &Count)?;
/// assert_eq!(count, 3);
/// Ok(())
/// # }
/// # assert!(test().is_ok());
/// ```
#[derive(Debug, Clone)]
pub struct RegexQuery {
regex: Arc<Regex>,
field: Field,
}
impl RegexQuery {
/// Creates a new RegexQuery from a given pattern
pub fn from_pattern(regex_pattern: &str, field: Field) -> crate::Result<Self> {
let regex = Regex::new(regex_pattern)
.map_err(|_| TantivyError::InvalidArgument(regex_pattern.to_string()))?;
Ok(RegexQuery::from_regex(regex, field))
}
/// Creates a new RegexQuery from a fully built Regex
pub fn from_regex<T: Into<Arc<Regex>>>(regex: T, field: Field) -> Self {
RegexQuery {
regex: regex.into(),
field,
}
}
fn specialized_weight(&self) -> AutomatonWeight<Regex> {
AutomatonWeight::new(self.field, self.regex.clone())
}
}
|
) -> crate::Result<Box<dyn Weight>> {
Ok(Box::new(self.specialized_weight()))
}
}
#[cfg(test)]
mod test {
use super::RegexQuery;
use crate::assert_nearly_equals;
use crate::collector::TopDocs;
use crate::schema::TEXT;
use crate::schema::{Field, Schema};
use crate::{Index, IndexReader};
use std::sync::Arc;
use tantivy_fst::Regex;
fn build_test_index() -> crate::Result<(IndexReader, Field)> {
let mut schema_builder = Schema::builder();
let country_field = schema_builder.add_text_field("country", TEXT);
let schema = schema_builder.build();
let index = Index::create_in_ram(schema);
{
let mut index_writer = index.writer_for_tests().unwrap();
index_writer.add_document(doc!(
country_field => "japan",
))?;
index_writer.add_document(doc!(
country_field => "korea",
))?;
index_writer.commit()?;
}
let reader = index.reader()?;
Ok((reader, country_field))
}
fn verify_regex_query(
query_matching_one: RegexQuery,
query_matching_zero: RegexQuery,
reader: IndexReader,
) {
let searcher = reader.searcher();
{
let scored_docs = searcher
.search(&query_matching_one, &TopDocs::with_limit(2))
.unwrap();
assert_eq!(scored_docs.len(), 1, "Expected only 1 document");
let (score, _) = scored_docs[0];
assert_nearly_equals!(1.0, score);
}
let top_docs = searcher
.search(&query_matching_zero, &TopDocs::with_limit(2))
.unwrap();
assert!(top_docs.is_empty(), "Expected ZERO document");
}
#[test]
pub fn test_regex_query() -> crate::Result<()> {
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_pattern("jap[ao]n", field)?;
let matching_zero = RegexQuery::from_pattern("jap[A-Z]n", field)?;
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
#[test]
pub fn test_construct_from_regex() -> crate::Result<()> {
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_regex(Regex::new("jap[ao]n").unwrap(), field);
let matching_zero = RegexQuery::from_regex(Regex::new("jap[A-Z]n").unwrap(), field);
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
#[test]
pub fn test_construct_from_reused_regex() -> crate::Result<()> {
let r1 = Arc::new(Regex::new("jap[ao]n").unwrap());
let r2 = Arc::new(Regex::new("jap[A-Z]n").unwrap());
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_regex(r1.clone(), field);
let matching_zero = RegexQuery::from_regex(r2.clone(), field);
verify_regex_query(matching_one, matching_zero, reader.clone());
let matching_one = RegexQuery::from_regex(r1, field);
let matching_zero = RegexQuery::from_regex(r2, field);
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
}
|
impl Query for RegexQuery {
fn weight(
&self,
_searcher: &Searcher,
_scoring_enabled: bool,
|
random_line_split
|
regex_query.rs
|
use crate::error::TantivyError;
use crate::query::{AutomatonWeight, Query, Weight};
use crate::schema::Field;
use crate::Searcher;
use std::clone::Clone;
use std::sync::Arc;
use tantivy_fst::Regex;
/// A Regex Query matches all of the documents
/// containing a specific term that matches
/// a regex pattern.
///
/// Wildcard queries (e.g. ho*se) can be achieved
/// by converting them to their regex counterparts.
///
/// ```rust
/// use tantivy::collector::Count;
/// use tantivy::query::RegexQuery;
/// use tantivy::schema::{Schema, TEXT};
/// use tantivy::{doc, Index, Term};
///
/// # fn test() -> tantivy::Result<()> {
/// let mut schema_builder = Schema::builder();
/// let title = schema_builder.add_text_field("title", TEXT);
/// let schema = schema_builder.build();
/// let index = Index::create_in_ram(schema);
/// {
/// let mut index_writer = index.writer(3_000_000)?;
/// index_writer.add_document(doc!(
/// title => "The Name of the Wind",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "The Diary of Muadib",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "A Dairy Cow",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "The Diary of a Young Girl",
/// ))?;
/// index_writer.commit()?;
/// }
///
/// let reader = index.reader()?;
/// let searcher = reader.searcher();
///
/// let term = Term::from_field_text(title, "Diary");
/// let query = RegexQuery::from_pattern("d[ai]{2}ry", title)?;
/// let count = searcher.search(&query, &Count)?;
/// assert_eq!(count, 3);
/// Ok(())
/// # }
/// # assert!(test().is_ok());
/// ```
#[derive(Debug, Clone)]
pub struct RegexQuery {
regex: Arc<Regex>,
field: Field,
}
impl RegexQuery {
/// Creates a new RegexQuery from a given pattern
pub fn from_pattern(regex_pattern: &str, field: Field) -> crate::Result<Self> {
let regex = Regex::new(regex_pattern)
.map_err(|_| TantivyError::InvalidArgument(regex_pattern.to_string()))?;
Ok(RegexQuery::from_regex(regex, field))
}
/// Creates a new RegexQuery from a fully built Regex
pub fn
|
<T: Into<Arc<Regex>>>(regex: T, field: Field) -> Self {
RegexQuery {
regex: regex.into(),
field,
}
}
fn specialized_weight(&self) -> AutomatonWeight<Regex> {
AutomatonWeight::new(self.field, self.regex.clone())
}
}
impl Query for RegexQuery {
fn weight(
&self,
_searcher: &Searcher,
_scoring_enabled: bool,
) -> crate::Result<Box<dyn Weight>> {
Ok(Box::new(self.specialized_weight()))
}
}
#[cfg(test)]
mod test {
use super::RegexQuery;
use crate::assert_nearly_equals;
use crate::collector::TopDocs;
use crate::schema::TEXT;
use crate::schema::{Field, Schema};
use crate::{Index, IndexReader};
use std::sync::Arc;
use tantivy_fst::Regex;
fn build_test_index() -> crate::Result<(IndexReader, Field)> {
let mut schema_builder = Schema::builder();
let country_field = schema_builder.add_text_field("country", TEXT);
let schema = schema_builder.build();
let index = Index::create_in_ram(schema);
{
let mut index_writer = index.writer_for_tests().unwrap();
index_writer.add_document(doc!(
country_field => "japan",
))?;
index_writer.add_document(doc!(
country_field => "korea",
))?;
index_writer.commit()?;
}
let reader = index.reader()?;
Ok((reader, country_field))
}
fn verify_regex_query(
query_matching_one: RegexQuery,
query_matching_zero: RegexQuery,
reader: IndexReader,
) {
let searcher = reader.searcher();
{
let scored_docs = searcher
.search(&query_matching_one, &TopDocs::with_limit(2))
.unwrap();
assert_eq!(scored_docs.len(), 1, "Expected only 1 document");
let (score, _) = scored_docs[0];
assert_nearly_equals!(1.0, score);
}
let top_docs = searcher
.search(&query_matching_zero, &TopDocs::with_limit(2))
.unwrap();
assert!(top_docs.is_empty(), "Expected ZERO document");
}
#[test]
pub fn test_regex_query() -> crate::Result<()> {
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_pattern("jap[ao]n", field)?;
let matching_zero = RegexQuery::from_pattern("jap[A-Z]n", field)?;
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
#[test]
pub fn test_construct_from_regex() -> crate::Result<()> {
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_regex(Regex::new("jap[ao]n").unwrap(), field);
let matching_zero = RegexQuery::from_regex(Regex::new("jap[A-Z]n").unwrap(), field);
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
#[test]
pub fn test_construct_from_reused_regex() -> crate::Result<()> {
let r1 = Arc::new(Regex::new("jap[ao]n").unwrap());
let r2 = Arc::new(Regex::new("jap[A-Z]n").unwrap());
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_regex(r1.clone(), field);
let matching_zero = RegexQuery::from_regex(r2.clone(), field);
verify_regex_query(matching_one, matching_zero, reader.clone());
let matching_one = RegexQuery::from_regex(r1, field);
let matching_zero = RegexQuery::from_regex(r2, field);
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
}
|
from_regex
|
identifier_name
|
regex_query.rs
|
use crate::error::TantivyError;
use crate::query::{AutomatonWeight, Query, Weight};
use crate::schema::Field;
use crate::Searcher;
use std::clone::Clone;
use std::sync::Arc;
use tantivy_fst::Regex;
/// A Regex Query matches all of the documents
/// containing a specific term that matches
/// a regex pattern.
///
/// Wildcard queries (e.g. ho*se) can be achieved
/// by converting them to their regex counterparts.
///
/// ```rust
/// use tantivy::collector::Count;
/// use tantivy::query::RegexQuery;
/// use tantivy::schema::{Schema, TEXT};
/// use tantivy::{doc, Index, Term};
///
/// # fn test() -> tantivy::Result<()> {
/// let mut schema_builder = Schema::builder();
/// let title = schema_builder.add_text_field("title", TEXT);
/// let schema = schema_builder.build();
/// let index = Index::create_in_ram(schema);
/// {
/// let mut index_writer = index.writer(3_000_000)?;
/// index_writer.add_document(doc!(
/// title => "The Name of the Wind",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "The Diary of Muadib",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "A Dairy Cow",
/// ))?;
/// index_writer.add_document(doc!(
/// title => "The Diary of a Young Girl",
/// ))?;
/// index_writer.commit()?;
/// }
///
/// let reader = index.reader()?;
/// let searcher = reader.searcher();
///
/// let term = Term::from_field_text(title, "Diary");
/// let query = RegexQuery::from_pattern("d[ai]{2}ry", title)?;
/// let count = searcher.search(&query, &Count)?;
/// assert_eq!(count, 3);
/// Ok(())
/// # }
/// # assert!(test().is_ok());
/// ```
#[derive(Debug, Clone)]
pub struct RegexQuery {
regex: Arc<Regex>,
field: Field,
}
impl RegexQuery {
/// Creates a new RegexQuery from a given pattern
pub fn from_pattern(regex_pattern: &str, field: Field) -> crate::Result<Self> {
let regex = Regex::new(regex_pattern)
.map_err(|_| TantivyError::InvalidArgument(regex_pattern.to_string()))?;
Ok(RegexQuery::from_regex(regex, field))
}
/// Creates a new RegexQuery from a fully built Regex
pub fn from_regex<T: Into<Arc<Regex>>>(regex: T, field: Field) -> Self {
RegexQuery {
regex: regex.into(),
field,
}
}
fn specialized_weight(&self) -> AutomatonWeight<Regex> {
AutomatonWeight::new(self.field, self.regex.clone())
}
}
impl Query for RegexQuery {
fn weight(
&self,
_searcher: &Searcher,
_scoring_enabled: bool,
) -> crate::Result<Box<dyn Weight>> {
Ok(Box::new(self.specialized_weight()))
}
}
#[cfg(test)]
mod test {
use super::RegexQuery;
use crate::assert_nearly_equals;
use crate::collector::TopDocs;
use crate::schema::TEXT;
use crate::schema::{Field, Schema};
use crate::{Index, IndexReader};
use std::sync::Arc;
use tantivy_fst::Regex;
fn build_test_index() -> crate::Result<(IndexReader, Field)> {
let mut schema_builder = Schema::builder();
let country_field = schema_builder.add_text_field("country", TEXT);
let schema = schema_builder.build();
let index = Index::create_in_ram(schema);
{
let mut index_writer = index.writer_for_tests().unwrap();
index_writer.add_document(doc!(
country_field => "japan",
))?;
index_writer.add_document(doc!(
country_field => "korea",
))?;
index_writer.commit()?;
}
let reader = index.reader()?;
Ok((reader, country_field))
}
fn verify_regex_query(
query_matching_one: RegexQuery,
query_matching_zero: RegexQuery,
reader: IndexReader,
)
|
#[test]
pub fn test_regex_query() -> crate::Result<()> {
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_pattern("jap[ao]n", field)?;
let matching_zero = RegexQuery::from_pattern("jap[A-Z]n", field)?;
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
#[test]
pub fn test_construct_from_regex() -> crate::Result<()> {
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_regex(Regex::new("jap[ao]n").unwrap(), field);
let matching_zero = RegexQuery::from_regex(Regex::new("jap[A-Z]n").unwrap(), field);
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
#[test]
pub fn test_construct_from_reused_regex() -> crate::Result<()> {
let r1 = Arc::new(Regex::new("jap[ao]n").unwrap());
let r2 = Arc::new(Regex::new("jap[A-Z]n").unwrap());
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_regex(r1.clone(), field);
let matching_zero = RegexQuery::from_regex(r2.clone(), field);
verify_regex_query(matching_one, matching_zero, reader.clone());
let matching_one = RegexQuery::from_regex(r1, field);
let matching_zero = RegexQuery::from_regex(r2, field);
verify_regex_query(matching_one, matching_zero, reader);
Ok(())
}
}
|
{
let searcher = reader.searcher();
{
let scored_docs = searcher
.search(&query_matching_one, &TopDocs::with_limit(2))
.unwrap();
assert_eq!(scored_docs.len(), 1, "Expected only 1 document");
let (score, _) = scored_docs[0];
assert_nearly_equals!(1.0, score);
}
let top_docs = searcher
.search(&query_matching_zero, &TopDocs::with_limit(2))
.unwrap();
assert!(top_docs.is_empty(), "Expected ZERO document");
}
|
identifier_body
|
day22.rs
|
#[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
players_turn : bool,
turns : u32,
minimum_mana_usage : Arc<AtomicUsize>
}
impl GameState {
fn new(player : Character, boss : Character) -> GameState {
GameState {
player : player,
boss : boss,
players_turn : true,
turns : 0,
minimum_mana_usage : Arc::new(AtomicUsize::new(std::usize::MAX))
}
}
fn apply_boss_damage(&mut self) {
if!self.players_turn {
let damage = std::cmp::max(1, self.boss.damage - self.player.armor);
self.player.hp -= damage as i32;
}
}
fn apply_spells(&mut self) {
self.player.armor = 0; // Init to no shield
for s in &mut self.player.active_spells {
self.player.mana += s.mana_gain;// Recharge
self.player.armor += s.armor;// Shield
s.turns -= 1;
}
self.player.active_spells.retain(|x| x.turns!= 0);
for s in &mut self.boss.active_spells {
self.boss.hp -= s.damage as i32; // Poison
s.turns -= 1;
}
self.boss.active_spells.retain(|x| x.turns!= 0);
}
fn spell_in_effect(&self, spell : &Spell) -> bool {
let mut on = false;
for s in &self.player.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
if!on {
for s in &self.boss.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
}
on
}
fn add_spell(&mut self, spell : Spell) {
self.player.mana -= spell.mana_cost;
self.player.mana_usage += spell.mana_cost;
if spell.turns > 0 {
if spell.name == "Shield" || spell.name == "Recharge" {
self.player.active_spells.push(spell);
} else {
self.boss.active_spells.push(spell);
}
} else {
self.player.hp += spell.heal as i32;
self.boss.hp -= spell.damage as i32;
}
}
}
#[derive(Clone,Debug)]
struct Character {
hp : i32,
damage : u32,
|
active_spells : Vec<Spell>
}
impl Character {
fn new(hp : i32, damage : u32, mana : u32) -> Character {
Character {
hp : hp,
damage : damage,
armor : 0,
mana : mana,
mana_usage : 0,
active_spells : Vec::new()
}
}
}
#[derive(Clone,Debug)]
struct Spell {
name : String,
mana_cost : u32,
damage : u32,
heal : u32,
armor : u32,
mana_gain : u32,
turns : u32, // If turns = 0, instant
}
impl Spell {
fn new(name : &str, cost : u32, damage : u32, heal : u32, armor : u32, gain : u32, turns : u32) -> Spell {
Spell {
name : String::from(name),
mana_cost : cost,
damage : damage,
heal : heal,
armor : armor,
mana_gain : gain,
turns : turns
}
}
}
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let hp = matches.value_of("HP").unwrap_or("50").parse::<i32>().unwrap();
let mana = matches.value_of("MANA").unwrap_or("500").parse::<u32>().unwrap();
let filename = matches.value_of("FILE").unwrap();
let mut file = match File::open(filename) {
Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)),
Ok(_) => println!("Read file {}", filename),
}
let boss = parse_input(s.trim().split('\n').collect());
let player = Character::new(hp, 0, mana);
let spells = build_spell_list();
let easy = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(easy.clone(), &spells, false);
println!("Easy Mode: Min mana used: {}", easy.minimum_mana_usage.load(Ordering::SeqCst));
let hard = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(hard.clone(), &spells, true);
println!("Hard Mode: Min mana used: {}", hard.minimum_mana_usage.load(Ordering::SeqCst));
}
fn find_min_mana_usage(state : GameState, spells : &Vec<Spell>, hard_mode : bool) -> u32 {
let mut mana_usage = std::u32::MAX;
let mut game = state.clone();
game.turns += 1;
if hard_mode && game.players_turn {
game.player.hp -= 1;
}
if game.player.hp > 0 {
game.apply_spells(); //Apply existing spells to player and boss
if game.boss.hp <= 0 {
// Player won
mana_usage = game.player.mana_usage;
} else if game.players_turn {
game.players_turn = false;
for s in spells {
if!game.spell_in_effect(s) && game.player.mana >= s.mana_cost && ((game.player.mana_usage + s.mana_cost) as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
let mut new_game_state = game.clone();
new_game_state.add_spell(s.clone());
let new_mana_usage = find_min_mana_usage(new_game_state, spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
} else {
// Run boss code
game.apply_boss_damage();
if game.player.hp > 0 {
game.players_turn = true;
// If neither player or boss won, start next round
let new_mana_usage = find_min_mana_usage(game.clone(), spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
}
mana_usage
}
fn build_spell_list() -> Vec<Spell> {
let mut spells = Vec::new();
spells.push(Spell::new("Shield", 113, 0, 0, 7, 0, 6));
spells.push(Spell::new("Poison", 173, 3, 0, 0, 0, 6));
spells.push(Spell::new("Magic Missle", 53, 4, 0, 0, 0, 0));
spells.push(Spell::new("Drain", 73, 2, 2, 0, 0, 0));
spells.push(Spell::new("Recharge", 229, 0, 0, 0, 101, 5));
spells
}
fn parse_input(input : Vec<&str>) -> Character {
let mut hp = 0;
let mut damage = 0;
for s in input {
if s.trim().len() > 0 {
let re = Regex::new(r"(.*): (\d+)").unwrap();
for cap in re.captures_iter(s) {
if cap.at(1).unwrap() == "Hit Points" {
hp = cap.at(2).unwrap().parse::<i32>().unwrap();
} else if cap.at(1).unwrap() == "Damage" {
damage = cap.at(2).unwrap().parse::<u32>().unwrap();
}
}
}
}
Character::new(hp, damage, 0)
}
|
armor : u32,
mana : u32,
mana_usage : u32,
|
random_line_split
|
day22.rs
|
#[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
players_turn : bool,
turns : u32,
minimum_mana_usage : Arc<AtomicUsize>
}
impl GameState {
fn new(player : Character, boss : Character) -> GameState {
GameState {
player : player,
boss : boss,
players_turn : true,
turns : 0,
minimum_mana_usage : Arc::new(AtomicUsize::new(std::usize::MAX))
}
}
fn
|
(&mut self) {
if!self.players_turn {
let damage = std::cmp::max(1, self.boss.damage - self.player.armor);
self.player.hp -= damage as i32;
}
}
fn apply_spells(&mut self) {
self.player.armor = 0; // Init to no shield
for s in &mut self.player.active_spells {
self.player.mana += s.mana_gain;// Recharge
self.player.armor += s.armor;// Shield
s.turns -= 1;
}
self.player.active_spells.retain(|x| x.turns!= 0);
for s in &mut self.boss.active_spells {
self.boss.hp -= s.damage as i32; // Poison
s.turns -= 1;
}
self.boss.active_spells.retain(|x| x.turns!= 0);
}
fn spell_in_effect(&self, spell : &Spell) -> bool {
let mut on = false;
for s in &self.player.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
if!on {
for s in &self.boss.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
}
on
}
fn add_spell(&mut self, spell : Spell) {
self.player.mana -= spell.mana_cost;
self.player.mana_usage += spell.mana_cost;
if spell.turns > 0 {
if spell.name == "Shield" || spell.name == "Recharge" {
self.player.active_spells.push(spell);
} else {
self.boss.active_spells.push(spell);
}
} else {
self.player.hp += spell.heal as i32;
self.boss.hp -= spell.damage as i32;
}
}
}
#[derive(Clone,Debug)]
struct Character {
hp : i32,
damage : u32,
armor : u32,
mana : u32,
mana_usage : u32,
active_spells : Vec<Spell>
}
impl Character {
fn new(hp : i32, damage : u32, mana : u32) -> Character {
Character {
hp : hp,
damage : damage,
armor : 0,
mana : mana,
mana_usage : 0,
active_spells : Vec::new()
}
}
}
#[derive(Clone,Debug)]
struct Spell {
name : String,
mana_cost : u32,
damage : u32,
heal : u32,
armor : u32,
mana_gain : u32,
turns : u32, // If turns = 0, instant
}
impl Spell {
fn new(name : &str, cost : u32, damage : u32, heal : u32, armor : u32, gain : u32, turns : u32) -> Spell {
Spell {
name : String::from(name),
mana_cost : cost,
damage : damage,
heal : heal,
armor : armor,
mana_gain : gain,
turns : turns
}
}
}
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let hp = matches.value_of("HP").unwrap_or("50").parse::<i32>().unwrap();
let mana = matches.value_of("MANA").unwrap_or("500").parse::<u32>().unwrap();
let filename = matches.value_of("FILE").unwrap();
let mut file = match File::open(filename) {
Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)),
Ok(_) => println!("Read file {}", filename),
}
let boss = parse_input(s.trim().split('\n').collect());
let player = Character::new(hp, 0, mana);
let spells = build_spell_list();
let easy = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(easy.clone(), &spells, false);
println!("Easy Mode: Min mana used: {}", easy.minimum_mana_usage.load(Ordering::SeqCst));
let hard = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(hard.clone(), &spells, true);
println!("Hard Mode: Min mana used: {}", hard.minimum_mana_usage.load(Ordering::SeqCst));
}
fn find_min_mana_usage(state : GameState, spells : &Vec<Spell>, hard_mode : bool) -> u32 {
let mut mana_usage = std::u32::MAX;
let mut game = state.clone();
game.turns += 1;
if hard_mode && game.players_turn {
game.player.hp -= 1;
}
if game.player.hp > 0 {
game.apply_spells(); //Apply existing spells to player and boss
if game.boss.hp <= 0 {
// Player won
mana_usage = game.player.mana_usage;
} else if game.players_turn {
game.players_turn = false;
for s in spells {
if!game.spell_in_effect(s) && game.player.mana >= s.mana_cost && ((game.player.mana_usage + s.mana_cost) as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
let mut new_game_state = game.clone();
new_game_state.add_spell(s.clone());
let new_mana_usage = find_min_mana_usage(new_game_state, spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
} else {
// Run boss code
game.apply_boss_damage();
if game.player.hp > 0 {
game.players_turn = true;
// If neither player or boss won, start next round
let new_mana_usage = find_min_mana_usage(game.clone(), spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
}
mana_usage
}
fn build_spell_list() -> Vec<Spell> {
let mut spells = Vec::new();
spells.push(Spell::new("Shield", 113, 0, 0, 7, 0, 6));
spells.push(Spell::new("Poison", 173, 3, 0, 0, 0, 6));
spells.push(Spell::new("Magic Missle", 53, 4, 0, 0, 0, 0));
spells.push(Spell::new("Drain", 73, 2, 2, 0, 0, 0));
spells.push(Spell::new("Recharge", 229, 0, 0, 0, 101, 5));
spells
}
fn parse_input(input : Vec<&str>) -> Character {
let mut hp = 0;
let mut damage = 0;
for s in input {
if s.trim().len() > 0 {
let re = Regex::new(r"(.*): (\d+)").unwrap();
for cap in re.captures_iter(s) {
if cap.at(1).unwrap() == "Hit Points" {
hp = cap.at(2).unwrap().parse::<i32>().unwrap();
} else if cap.at(1).unwrap() == "Damage" {
damage = cap.at(2).unwrap().parse::<u32>().unwrap();
}
}
}
}
Character::new(hp, damage, 0)
}
|
apply_boss_damage
|
identifier_name
|
day22.rs
|
#[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
players_turn : bool,
turns : u32,
minimum_mana_usage : Arc<AtomicUsize>
}
impl GameState {
fn new(player : Character, boss : Character) -> GameState {
GameState {
player : player,
boss : boss,
players_turn : true,
turns : 0,
minimum_mana_usage : Arc::new(AtomicUsize::new(std::usize::MAX))
}
}
fn apply_boss_damage(&mut self) {
if!self.players_turn {
let damage = std::cmp::max(1, self.boss.damage - self.player.armor);
self.player.hp -= damage as i32;
}
}
fn apply_spells(&mut self) {
self.player.armor = 0; // Init to no shield
for s in &mut self.player.active_spells {
self.player.mana += s.mana_gain;// Recharge
self.player.armor += s.armor;// Shield
s.turns -= 1;
}
self.player.active_spells.retain(|x| x.turns!= 0);
for s in &mut self.boss.active_spells {
self.boss.hp -= s.damage as i32; // Poison
s.turns -= 1;
}
self.boss.active_spells.retain(|x| x.turns!= 0);
}
fn spell_in_effect(&self, spell : &Spell) -> bool {
let mut on = false;
for s in &self.player.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
if!on {
for s in &self.boss.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
}
on
}
fn add_spell(&mut self, spell : Spell) {
self.player.mana -= spell.mana_cost;
self.player.mana_usage += spell.mana_cost;
if spell.turns > 0 {
if spell.name == "Shield" || spell.name == "Recharge" {
self.player.active_spells.push(spell);
} else {
self.boss.active_spells.push(spell);
}
} else {
self.player.hp += spell.heal as i32;
self.boss.hp -= spell.damage as i32;
}
}
}
#[derive(Clone,Debug)]
struct Character {
hp : i32,
damage : u32,
armor : u32,
mana : u32,
mana_usage : u32,
active_spells : Vec<Spell>
}
impl Character {
fn new(hp : i32, damage : u32, mana : u32) -> Character {
Character {
hp : hp,
damage : damage,
armor : 0,
mana : mana,
mana_usage : 0,
active_spells : Vec::new()
}
}
}
#[derive(Clone,Debug)]
struct Spell {
name : String,
mana_cost : u32,
damage : u32,
heal : u32,
armor : u32,
mana_gain : u32,
turns : u32, // If turns = 0, instant
}
impl Spell {
fn new(name : &str, cost : u32, damage : u32, heal : u32, armor : u32, gain : u32, turns : u32) -> Spell {
Spell {
name : String::from(name),
mana_cost : cost,
damage : damage,
heal : heal,
armor : armor,
mana_gain : gain,
turns : turns
}
}
}
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let hp = matches.value_of("HP").unwrap_or("50").parse::<i32>().unwrap();
let mana = matches.value_of("MANA").unwrap_or("500").parse::<u32>().unwrap();
let filename = matches.value_of("FILE").unwrap();
let mut file = match File::open(filename) {
Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)),
Ok(_) => println!("Read file {}", filename),
}
let boss = parse_input(s.trim().split('\n').collect());
let player = Character::new(hp, 0, mana);
let spells = build_spell_list();
let easy = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(easy.clone(), &spells, false);
println!("Easy Mode: Min mana used: {}", easy.minimum_mana_usage.load(Ordering::SeqCst));
let hard = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(hard.clone(), &spells, true);
println!("Hard Mode: Min mana used: {}", hard.minimum_mana_usage.load(Ordering::SeqCst));
}
fn find_min_mana_usage(state : GameState, spells : &Vec<Spell>, hard_mode : bool) -> u32 {
let mut mana_usage = std::u32::MAX;
let mut game = state.clone();
game.turns += 1;
if hard_mode && game.players_turn {
game.player.hp -= 1;
}
if game.player.hp > 0 {
game.apply_spells(); //Apply existing spells to player and boss
if game.boss.hp <= 0 {
// Player won
mana_usage = game.player.mana_usage;
} else if game.players_turn {
game.players_turn = false;
for s in spells {
if!game.spell_in_effect(s) && game.player.mana >= s.mana_cost && ((game.player.mana_usage + s.mana_cost) as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
let mut new_game_state = game.clone();
new_game_state.add_spell(s.clone());
let new_mana_usage = find_min_mana_usage(new_game_state, spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
} else
|
}
mana_usage
}
fn build_spell_list() -> Vec<Spell> {
let mut spells = Vec::new();
spells.push(Spell::new("Shield", 113, 0, 0, 7, 0, 6));
spells.push(Spell::new("Poison", 173, 3, 0, 0, 0, 6));
spells.push(Spell::new("Magic Missle", 53, 4, 0, 0, 0, 0));
spells.push(Spell::new("Drain", 73, 2, 2, 0, 0, 0));
spells.push(Spell::new("Recharge", 229, 0, 0, 0, 101, 5));
spells
}
fn parse_input(input : Vec<&str>) -> Character {
let mut hp = 0;
let mut damage = 0;
for s in input {
if s.trim().len() > 0 {
let re = Regex::new(r"(.*): (\d+)").unwrap();
for cap in re.captures_iter(s) {
if cap.at(1).unwrap() == "Hit Points" {
hp = cap.at(2).unwrap().parse::<i32>().unwrap();
} else if cap.at(1).unwrap() == "Damage" {
damage = cap.at(2).unwrap().parse::<u32>().unwrap();
}
}
}
}
Character::new(hp, damage, 0)
}
|
{
// Run boss code
game.apply_boss_damage();
if game.player.hp > 0 {
game.players_turn = true;
// If neither player or boss won, start next round
let new_mana_usage = find_min_mana_usage(game.clone(), spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
|
conditional_block
|
day22.rs
|
#[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
players_turn : bool,
turns : u32,
minimum_mana_usage : Arc<AtomicUsize>
}
impl GameState {
fn new(player : Character, boss : Character) -> GameState {
GameState {
player : player,
boss : boss,
players_turn : true,
turns : 0,
minimum_mana_usage : Arc::new(AtomicUsize::new(std::usize::MAX))
}
}
fn apply_boss_damage(&mut self) {
if!self.players_turn {
let damage = std::cmp::max(1, self.boss.damage - self.player.armor);
self.player.hp -= damage as i32;
}
}
fn apply_spells(&mut self) {
self.player.armor = 0; // Init to no shield
for s in &mut self.player.active_spells {
self.player.mana += s.mana_gain;// Recharge
self.player.armor += s.armor;// Shield
s.turns -= 1;
}
self.player.active_spells.retain(|x| x.turns!= 0);
for s in &mut self.boss.active_spells {
self.boss.hp -= s.damage as i32; // Poison
s.turns -= 1;
}
self.boss.active_spells.retain(|x| x.turns!= 0);
}
fn spell_in_effect(&self, spell : &Spell) -> bool
|
fn add_spell(&mut self, spell : Spell) {
self.player.mana -= spell.mana_cost;
self.player.mana_usage += spell.mana_cost;
if spell.turns > 0 {
if spell.name == "Shield" || spell.name == "Recharge" {
self.player.active_spells.push(spell);
} else {
self.boss.active_spells.push(spell);
}
} else {
self.player.hp += spell.heal as i32;
self.boss.hp -= spell.damage as i32;
}
}
}
#[derive(Clone,Debug)]
struct Character {
hp : i32,
damage : u32,
armor : u32,
mana : u32,
mana_usage : u32,
active_spells : Vec<Spell>
}
impl Character {
fn new(hp : i32, damage : u32, mana : u32) -> Character {
Character {
hp : hp,
damage : damage,
armor : 0,
mana : mana,
mana_usage : 0,
active_spells : Vec::new()
}
}
}
#[derive(Clone,Debug)]
struct Spell {
name : String,
mana_cost : u32,
damage : u32,
heal : u32,
armor : u32,
mana_gain : u32,
turns : u32, // If turns = 0, instant
}
impl Spell {
fn new(name : &str, cost : u32, damage : u32, heal : u32, armor : u32, gain : u32, turns : u32) -> Spell {
Spell {
name : String::from(name),
mana_cost : cost,
damage : damage,
heal : heal,
armor : armor,
mana_gain : gain,
turns : turns
}
}
}
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let hp = matches.value_of("HP").unwrap_or("50").parse::<i32>().unwrap();
let mana = matches.value_of("MANA").unwrap_or("500").parse::<u32>().unwrap();
let filename = matches.value_of("FILE").unwrap();
let mut file = match File::open(filename) {
Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)),
Ok(_) => println!("Read file {}", filename),
}
let boss = parse_input(s.trim().split('\n').collect());
let player = Character::new(hp, 0, mana);
let spells = build_spell_list();
let easy = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(easy.clone(), &spells, false);
println!("Easy Mode: Min mana used: {}", easy.minimum_mana_usage.load(Ordering::SeqCst));
let hard = GameState::new(player.clone(), boss.clone());
find_min_mana_usage(hard.clone(), &spells, true);
println!("Hard Mode: Min mana used: {}", hard.minimum_mana_usage.load(Ordering::SeqCst));
}
fn find_min_mana_usage(state : GameState, spells : &Vec<Spell>, hard_mode : bool) -> u32 {
let mut mana_usage = std::u32::MAX;
let mut game = state.clone();
game.turns += 1;
if hard_mode && game.players_turn {
game.player.hp -= 1;
}
if game.player.hp > 0 {
game.apply_spells(); //Apply existing spells to player and boss
if game.boss.hp <= 0 {
// Player won
mana_usage = game.player.mana_usage;
} else if game.players_turn {
game.players_turn = false;
for s in spells {
if!game.spell_in_effect(s) && game.player.mana >= s.mana_cost && ((game.player.mana_usage + s.mana_cost) as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
let mut new_game_state = game.clone();
new_game_state.add_spell(s.clone());
let new_mana_usage = find_min_mana_usage(new_game_state, spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
} else {
// Run boss code
game.apply_boss_damage();
if game.player.hp > 0 {
game.players_turn = true;
// If neither player or boss won, start next round
let new_mana_usage = find_min_mana_usage(game.clone(), spells, hard_mode);
if new_mana_usage < mana_usage && (new_mana_usage as usize) < game.minimum_mana_usage.load(Ordering::SeqCst) {
mana_usage = new_mana_usage;
game.minimum_mana_usage.store(mana_usage as usize, Ordering::SeqCst);
}
}
}
}
mana_usage
}
fn build_spell_list() -> Vec<Spell> {
let mut spells = Vec::new();
spells.push(Spell::new("Shield", 113, 0, 0, 7, 0, 6));
spells.push(Spell::new("Poison", 173, 3, 0, 0, 0, 6));
spells.push(Spell::new("Magic Missle", 53, 4, 0, 0, 0, 0));
spells.push(Spell::new("Drain", 73, 2, 2, 0, 0, 0));
spells.push(Spell::new("Recharge", 229, 0, 0, 0, 101, 5));
spells
}
fn parse_input(input : Vec<&str>) -> Character {
let mut hp = 0;
let mut damage = 0;
for s in input {
if s.trim().len() > 0 {
let re = Regex::new(r"(.*): (\d+)").unwrap();
for cap in re.captures_iter(s) {
if cap.at(1).unwrap() == "Hit Points" {
hp = cap.at(2).unwrap().parse::<i32>().unwrap();
} else if cap.at(1).unwrap() == "Damage" {
damage = cap.at(2).unwrap().parse::<u32>().unwrap();
}
}
}
}
Character::new(hp, damage, 0)
}
|
{
let mut on = false;
for s in &self.player.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
if !on {
for s in &self.boss.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
}
on
}
|
identifier_body
|
htmlfontelement.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 cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding::HTMLFontElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
use servo_atoms::Atom;
use style::attr::AttrValue;
use style::str::{HTML_SPACE_CHARACTERS, read_numbers};
#[dom_struct]
pub struct HTMLFontElement {
htmlelement: HTMLElement,
}
impl HTMLFontElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLFontElement {
HTMLFontElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLFontElement> {
Node::reflect_node(box HTMLFontElement::new_inherited(local_name, prefix, document),
document,
HTMLFontElementBinding::Wrap)
}
}
impl HTMLFontElementMethods for HTMLFontElement {
// https://html.spec.whatwg.org/multipage/#dom-font-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-font-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-font-face
make_getter!(Face, "face");
// https://html.spec.whatwg.org/multipage/#dom-font-face
make_atomic_setter!(SetFace, "face");
// https://html.spec.whatwg.org/multipage/#dom-font-size
make_getter!(Size, "size");
// https://html.spec.whatwg.org/multipage/#dom-font-size
fn SetSize(&self, value: DOMString) {
let element = self.upcast::<Element>();
element.set_attribute(&local_name!("size"), parse_size(&value));
}
}
impl VirtualMethods for HTMLFontElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("face") => AttrValue::from_atomic(value.into()),
&local_name!("color") => AttrValue::from_legacy_color(value.into()),
&local_name!("size") => parse_size(&value),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
pub trait HTMLFontElementLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_face(&self) -> Option<Atom>;
fn get_size(&self) -> Option<u32>;
}
impl HTMLFontElementLayoutHelpers for LayoutJS<HTMLFontElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_face(&self) -> Option<Atom> {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("face"))
.map(AttrValue::as_atom)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_size(&self) -> Option<u32> {
let size = unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("size"))
};
match size {
Some(&AttrValue::UInt(_, s)) => Some(s),
_ => None,
}
}
}
/// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size
fn parse_size(mut input: &str) -> AttrValue {
let original_input = input;
// Steps 1 & 2 are not relevant
// Step 3
input = input.trim_matches(HTML_SPACE_CHARACTERS);
enum
|
{
RelativePlus,
RelativeMinus,
Absolute,
}
let mut input_chars = input.chars().peekable();
let parse_mode = match input_chars.peek() {
// Step 4
None => return AttrValue::String(original_input.into()),
// Step 5
Some(&'+') => {
let _ = input_chars.next(); // consume the '+'
ParseMode::RelativePlus
}
Some(&'-') => {
let _ = input_chars.next(); // consume the '-'
ParseMode::RelativeMinus
}
Some(_) => ParseMode::Absolute,
};
// Steps 6, 7, 8
let mut value = match read_numbers(input_chars) {
(Some(v), _) if v >= 0 => v,
_ => return AttrValue::String(original_input.into()),
};
// Step 9
match parse_mode {
ParseMode::RelativePlus => value = 3 + value,
ParseMode::RelativeMinus => value = 3 - value,
ParseMode::Absolute => (),
}
// Steps 10, 11, 12
AttrValue::UInt(original_input.into(), value as u32)
}
|
ParseMode
|
identifier_name
|
htmlfontelement.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 cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding::HTMLFontElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
use servo_atoms::Atom;
use style::attr::AttrValue;
use style::str::{HTML_SPACE_CHARACTERS, read_numbers};
#[dom_struct]
pub struct HTMLFontElement {
htmlelement: HTMLElement,
}
impl HTMLFontElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLFontElement {
HTMLFontElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLFontElement> {
Node::reflect_node(box HTMLFontElement::new_inherited(local_name, prefix, document),
document,
HTMLFontElementBinding::Wrap)
}
}
impl HTMLFontElementMethods for HTMLFontElement {
// https://html.spec.whatwg.org/multipage/#dom-font-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-font-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-font-face
make_getter!(Face, "face");
// https://html.spec.whatwg.org/multipage/#dom-font-face
make_atomic_setter!(SetFace, "face");
// https://html.spec.whatwg.org/multipage/#dom-font-size
make_getter!(Size, "size");
// https://html.spec.whatwg.org/multipage/#dom-font-size
fn SetSize(&self, value: DOMString) {
let element = self.upcast::<Element>();
element.set_attribute(&local_name!("size"), parse_size(&value));
}
}
impl VirtualMethods for HTMLFontElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("face") => AttrValue::from_atomic(value.into()),
&local_name!("color") => AttrValue::from_legacy_color(value.into()),
&local_name!("size") => parse_size(&value),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
pub trait HTMLFontElementLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_face(&self) -> Option<Atom>;
fn get_size(&self) -> Option<u32>;
}
impl HTMLFontElementLayoutHelpers for LayoutJS<HTMLFontElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_face(&self) -> Option<Atom> {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("face"))
.map(AttrValue::as_atom)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_size(&self) -> Option<u32> {
let size = unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("size"))
};
match size {
Some(&AttrValue::UInt(_, s)) => Some(s),
_ => None,
}
}
}
/// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size
fn parse_size(mut input: &str) -> AttrValue
|
ParseMode::RelativePlus
}
Some(&'-') => {
let _ = input_chars.next(); // consume the '-'
ParseMode::RelativeMinus
}
Some(_) => ParseMode::Absolute,
};
// Steps 6, 7, 8
let mut value = match read_numbers(input_chars) {
(Some(v), _) if v >= 0 => v,
_ => return AttrValue::String(original_input.into()),
};
// Step 9
match parse_mode {
ParseMode::RelativePlus => value = 3 + value,
ParseMode::RelativeMinus => value = 3 - value,
ParseMode::Absolute => (),
}
// Steps 10, 11, 12
AttrValue::UInt(original_input.into(), value as u32)
}
|
{
let original_input = input;
// Steps 1 & 2 are not relevant
// Step 3
input = input.trim_matches(HTML_SPACE_CHARACTERS);
enum ParseMode {
RelativePlus,
RelativeMinus,
Absolute,
}
let mut input_chars = input.chars().peekable();
let parse_mode = match input_chars.peek() {
// Step 4
None => return AttrValue::String(original_input.into()),
// Step 5
Some(&'+') => {
let _ = input_chars.next(); // consume the '+'
|
identifier_body
|
htmlfontelement.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 cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding::HTMLFontElementMethods;
use dom::bindings::inheritance::Castable;
|
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
use servo_atoms::Atom;
use style::attr::AttrValue;
use style::str::{HTML_SPACE_CHARACTERS, read_numbers};
#[dom_struct]
pub struct HTMLFontElement {
htmlelement: HTMLElement,
}
impl HTMLFontElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLFontElement {
HTMLFontElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLFontElement> {
Node::reflect_node(box HTMLFontElement::new_inherited(local_name, prefix, document),
document,
HTMLFontElementBinding::Wrap)
}
}
impl HTMLFontElementMethods for HTMLFontElement {
// https://html.spec.whatwg.org/multipage/#dom-font-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-font-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-font-face
make_getter!(Face, "face");
// https://html.spec.whatwg.org/multipage/#dom-font-face
make_atomic_setter!(SetFace, "face");
// https://html.spec.whatwg.org/multipage/#dom-font-size
make_getter!(Size, "size");
// https://html.spec.whatwg.org/multipage/#dom-font-size
fn SetSize(&self, value: DOMString) {
let element = self.upcast::<Element>();
element.set_attribute(&local_name!("size"), parse_size(&value));
}
}
impl VirtualMethods for HTMLFontElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("face") => AttrValue::from_atomic(value.into()),
&local_name!("color") => AttrValue::from_legacy_color(value.into()),
&local_name!("size") => parse_size(&value),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
pub trait HTMLFontElementLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_face(&self) -> Option<Atom>;
fn get_size(&self) -> Option<u32>;
}
impl HTMLFontElementLayoutHelpers for LayoutJS<HTMLFontElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_face(&self) -> Option<Atom> {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("face"))
.map(AttrValue::as_atom)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_size(&self) -> Option<u32> {
let size = unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("size"))
};
match size {
Some(&AttrValue::UInt(_, s)) => Some(s),
_ => None,
}
}
}
/// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size
fn parse_size(mut input: &str) -> AttrValue {
let original_input = input;
// Steps 1 & 2 are not relevant
// Step 3
input = input.trim_matches(HTML_SPACE_CHARACTERS);
enum ParseMode {
RelativePlus,
RelativeMinus,
Absolute,
}
let mut input_chars = input.chars().peekable();
let parse_mode = match input_chars.peek() {
// Step 4
None => return AttrValue::String(original_input.into()),
// Step 5
Some(&'+') => {
let _ = input_chars.next(); // consume the '+'
ParseMode::RelativePlus
}
Some(&'-') => {
let _ = input_chars.next(); // consume the '-'
ParseMode::RelativeMinus
}
Some(_) => ParseMode::Absolute,
};
// Steps 6, 7, 8
let mut value = match read_numbers(input_chars) {
(Some(v), _) if v >= 0 => v,
_ => return AttrValue::String(original_input.into()),
};
// Step 9
match parse_mode {
ParseMode::RelativePlus => value = 3 + value,
ParseMode::RelativeMinus => value = 3 - value,
ParseMode::Absolute => (),
}
// Steps 10, 11, 12
AttrValue::UInt(original_input.into(), value as u32)
}
|
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
|
random_line_split
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{expr,Generics,ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::mutability), // @[mut]
Borrowed(Option<&'self str>, ast::mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::m_imm)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
pub fn nil_ty() -> Ty<'static>
|
fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) => {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) => {
p.to_path(cx, span, self_ty, self_generics)
}
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: span, name: &str, bounds: &[Path],
self_ident: ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option<PtrTy>)
-> (@expr, ast::explicit_self) {
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
}
}
|
{
Tuple(~[])
}
|
identifier_body
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{expr,Generics,ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::mutability), // @[mut]
Borrowed(Option<&'self str>, ast::mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::m_imm)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
|
Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) => {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) => {
p.to_path(cx, span, self_ty, self_generics)
}
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: span, name: &str, bounds: &[Path],
self_ident: ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option<PtrTy>)
-> (@expr, ast::explicit_self) {
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
}
}
|
pub fn nil_ty() -> Ty<'static> {
|
random_line_split
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{expr,Generics,ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::mutability), // @[mut]
Borrowed(Option<&'self str>, ast::mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::m_imm)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
pub fn nil_ty() -> Ty<'static> {
Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn
|
(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) => {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) => {
p.to_path(cx, span, self_ty, self_generics)
}
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: span, name: &str, bounds: &[Path],
self_ident: ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option<PtrTy>)
-> (@expr, ast::explicit_self) {
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
}
}
|
to_ty
|
identifier_name
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{expr,Generics,ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::mutability), // @[mut]
Borrowed(Option<&'self str>, ast::mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::m_imm)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
pub fn nil_ty() -> Ty<'static> {
Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) =>
|
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) => {
p.to_path(cx, span, self_ty, self_generics)
}
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: span, name: &str, bounds: &[Path],
self_ident: ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option<PtrTy>)
-> (@expr, ast::explicit_self) {
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
}
}
|
{
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
|
conditional_block
|
io.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io::{IoError, IoResult, SeekStyle};
use std::io;
use std::slice;
use std::iter::repeat;
static BUF_CAPACITY: uint = 128;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {
// compute offset as signed and clamp to prevent overflow
let pos = match seek {
io::SeekSet => 0,
io::SeekEnd => end,
io::SeekCur => cur,
} as i64;
if offset + pos < 0 {
Err(IoError {
kind: io::InvalidInput,
desc: "invalid seek to a negative offset",
detail: None
})
} else {
Ok((offset + pos) as u64)
}
}
/// Writes to an owned, growable byte vector that supports seeking.
///
/// # Example
///
/// ```rust
/// # #![allow(unused_must_use)]
/// use rbml::io::SeekableMemWriter;
///
/// let mut w = SeekableMemWriter::new();
/// w.write(&[0, 1, 2]);
///
/// assert_eq!(w.unwrap(), vec!(0, 1, 2));
/// ```
pub struct SeekableMemWriter {
buf: Vec<u8>,
pos: uint,
}
impl SeekableMemWriter {
/// Create a new `SeekableMemWriter`.
#[inline]
pub fn new() -> SeekableMemWriter {
SeekableMemWriter::with_capacity(BUF_CAPACITY)
}
/// Create a new `SeekableMemWriter`, allocating at least `n` bytes for
/// the internal buffer.
#[inline]
pub fn with_capacity(n: uint) -> SeekableMemWriter {
SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 }
}
/// Acquires an immutable reference to the underlying buffer of this
/// `SeekableMemWriter`.
///
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could corrupt the state of this `MemWriter`.
#[inline]
pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
/// Unwraps this `SeekableMemWriter`, returning the underlying buffer
#[inline]
pub fn unwrap(self) -> Vec<u8> { self.buf }
}
impl Writer for SeekableMemWriter {
#[inline]
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
if self.pos == self.buf.len() {
self.buf.push_all(buf)
} else {
// Make sure the internal buffer is as least as big as where we
// currently are
let difference = self.pos as i64 - self.buf.len() as i64;
if difference > 0 {
self.buf.extend(repeat(0).take(difference as uint));
}
// Figure out what bytes will be used to overwrite what's currently
// there (left), and what will be appended on the end (right)
let cap = self.buf.len() - self.pos;
let (left, right) = if cap <= buf.len() {
(&buf[..cap], &buf[cap..])
} else {
let result: (_, &[_]) = (buf, &[]);
result
};
// Do the necessary writes
if left.len() > 0
|
if right.len() > 0 {
self.buf.push_all(right);
}
}
// Bump us forward
self.pos += buf.len();
Ok(())
}
}
impl Seek for SeekableMemWriter {
#[inline]
fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) }
#[inline]
fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
let new = try!(combine(style, self.pos, self.buf.len(), pos));
self.pos = new as uint;
Ok(())
}
}
#[cfg(test)]
mod tests {
extern crate test;
use super::SeekableMemWriter;
use std::io;
use std::iter::repeat;
use test::Bencher;
#[test]
fn test_seekable_mem_writer() {
let mut writer = SeekableMemWriter::new();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[0]).unwrap();
assert_eq!(writer.tell(), Ok(1));
writer.write(&[1, 2, 3]).unwrap();
writer.write(&[4, 5, 6, 7]).unwrap();
assert_eq!(writer.tell(), Ok(8));
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(0, io::SeekSet).unwrap();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[3, 4]).unwrap();
let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekCur).unwrap();
writer.write(&[0, 1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(-1, io::SeekEnd).unwrap();
writer.write(&[1, 2]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekEnd).unwrap();
writer.write(&[1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
assert_eq!(writer.get_ref(), b);
}
#[test]
fn seek_past_end() {
let mut r = SeekableMemWriter::new();
r.seek(10, io::SeekSet).unwrap();
assert!(r.write(&[3]).is_ok());
}
#[test]
fn seek_before_0() {
let mut r = SeekableMemWriter::new();
assert!(r.seek(-1, io::SeekSet).is_err());
}
fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) {
let src: Vec<u8> = repeat(5).take(len).collect();
b.bytes = (times * len) as u64;
b.iter(|| {
let mut wr = SeekableMemWriter::new();
for _ in range(0, times) {
wr.write(src.as_slice()).unwrap();
}
let v = wr.unwrap();
assert_eq!(v.len(), times * len);
assert!(v.iter().all(|x| *x == 5));
});
}
#[bench]
fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 0)
}
#[bench]
fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 10)
}
#[bench]
fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 100)
}
#[bench]
fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 1000)
}
#[bench]
fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 0)
}
#[bench]
fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 10)
}
#[bench]
fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 100)
}
#[bench]
fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 1000)
}
}
|
{
slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), left);
}
|
conditional_block
|
io.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io::{IoError, IoResult, SeekStyle};
use std::io;
use std::slice;
use std::iter::repeat;
static BUF_CAPACITY: uint = 128;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {
// compute offset as signed and clamp to prevent overflow
let pos = match seek {
io::SeekSet => 0,
io::SeekEnd => end,
io::SeekCur => cur,
} as i64;
if offset + pos < 0 {
Err(IoError {
kind: io::InvalidInput,
desc: "invalid seek to a negative offset",
detail: None
})
} else {
Ok((offset + pos) as u64)
}
}
/// Writes to an owned, growable byte vector that supports seeking.
///
/// # Example
///
/// ```rust
/// # #![allow(unused_must_use)]
/// use rbml::io::SeekableMemWriter;
///
/// let mut w = SeekableMemWriter::new();
/// w.write(&[0, 1, 2]);
///
/// assert_eq!(w.unwrap(), vec!(0, 1, 2));
/// ```
pub struct SeekableMemWriter {
buf: Vec<u8>,
pos: uint,
}
impl SeekableMemWriter {
/// Create a new `SeekableMemWriter`.
#[inline]
pub fn new() -> SeekableMemWriter {
SeekableMemWriter::with_capacity(BUF_CAPACITY)
}
/// Create a new `SeekableMemWriter`, allocating at least `n` bytes for
/// the internal buffer.
#[inline]
pub fn
|
(n: uint) -> SeekableMemWriter {
SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 }
}
/// Acquires an immutable reference to the underlying buffer of this
/// `SeekableMemWriter`.
///
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could corrupt the state of this `MemWriter`.
#[inline]
pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
/// Unwraps this `SeekableMemWriter`, returning the underlying buffer
#[inline]
pub fn unwrap(self) -> Vec<u8> { self.buf }
}
impl Writer for SeekableMemWriter {
#[inline]
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
if self.pos == self.buf.len() {
self.buf.push_all(buf)
} else {
// Make sure the internal buffer is as least as big as where we
// currently are
let difference = self.pos as i64 - self.buf.len() as i64;
if difference > 0 {
self.buf.extend(repeat(0).take(difference as uint));
}
// Figure out what bytes will be used to overwrite what's currently
// there (left), and what will be appended on the end (right)
let cap = self.buf.len() - self.pos;
let (left, right) = if cap <= buf.len() {
(&buf[..cap], &buf[cap..])
} else {
let result: (_, &[_]) = (buf, &[]);
result
};
// Do the necessary writes
if left.len() > 0 {
slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), left);
}
if right.len() > 0 {
self.buf.push_all(right);
}
}
// Bump us forward
self.pos += buf.len();
Ok(())
}
}
impl Seek for SeekableMemWriter {
#[inline]
fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) }
#[inline]
fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
let new = try!(combine(style, self.pos, self.buf.len(), pos));
self.pos = new as uint;
Ok(())
}
}
#[cfg(test)]
mod tests {
extern crate test;
use super::SeekableMemWriter;
use std::io;
use std::iter::repeat;
use test::Bencher;
#[test]
fn test_seekable_mem_writer() {
let mut writer = SeekableMemWriter::new();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[0]).unwrap();
assert_eq!(writer.tell(), Ok(1));
writer.write(&[1, 2, 3]).unwrap();
writer.write(&[4, 5, 6, 7]).unwrap();
assert_eq!(writer.tell(), Ok(8));
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(0, io::SeekSet).unwrap();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[3, 4]).unwrap();
let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekCur).unwrap();
writer.write(&[0, 1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(-1, io::SeekEnd).unwrap();
writer.write(&[1, 2]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekEnd).unwrap();
writer.write(&[1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
assert_eq!(writer.get_ref(), b);
}
#[test]
fn seek_past_end() {
let mut r = SeekableMemWriter::new();
r.seek(10, io::SeekSet).unwrap();
assert!(r.write(&[3]).is_ok());
}
#[test]
fn seek_before_0() {
let mut r = SeekableMemWriter::new();
assert!(r.seek(-1, io::SeekSet).is_err());
}
fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) {
let src: Vec<u8> = repeat(5).take(len).collect();
b.bytes = (times * len) as u64;
b.iter(|| {
let mut wr = SeekableMemWriter::new();
for _ in range(0, times) {
wr.write(src.as_slice()).unwrap();
}
let v = wr.unwrap();
assert_eq!(v.len(), times * len);
assert!(v.iter().all(|x| *x == 5));
});
}
#[bench]
fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 0)
}
#[bench]
fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 10)
}
#[bench]
fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 100)
}
#[bench]
fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 1000)
}
#[bench]
fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 0)
}
#[bench]
fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 10)
}
#[bench]
fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 100)
}
#[bench]
fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 1000)
}
}
|
with_capacity
|
identifier_name
|
io.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io::{IoError, IoResult, SeekStyle};
use std::io;
use std::slice;
use std::iter::repeat;
static BUF_CAPACITY: uint = 128;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {
// compute offset as signed and clamp to prevent overflow
let pos = match seek {
io::SeekSet => 0,
io::SeekEnd => end,
io::SeekCur => cur,
} as i64;
if offset + pos < 0 {
Err(IoError {
kind: io::InvalidInput,
desc: "invalid seek to a negative offset",
detail: None
})
} else {
Ok((offset + pos) as u64)
}
}
/// Writes to an owned, growable byte vector that supports seeking.
///
/// # Example
///
/// ```rust
/// # #![allow(unused_must_use)]
/// use rbml::io::SeekableMemWriter;
///
/// let mut w = SeekableMemWriter::new();
/// w.write(&[0, 1, 2]);
///
/// assert_eq!(w.unwrap(), vec!(0, 1, 2));
/// ```
pub struct SeekableMemWriter {
buf: Vec<u8>,
pos: uint,
}
impl SeekableMemWriter {
/// Create a new `SeekableMemWriter`.
#[inline]
pub fn new() -> SeekableMemWriter {
SeekableMemWriter::with_capacity(BUF_CAPACITY)
}
/// Create a new `SeekableMemWriter`, allocating at least `n` bytes for
/// the internal buffer.
#[inline]
pub fn with_capacity(n: uint) -> SeekableMemWriter {
SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 }
}
/// Acquires an immutable reference to the underlying buffer of this
/// `SeekableMemWriter`.
///
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could corrupt the state of this `MemWriter`.
#[inline]
pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
/// Unwraps this `SeekableMemWriter`, returning the underlying buffer
#[inline]
pub fn unwrap(self) -> Vec<u8> { self.buf }
}
impl Writer for SeekableMemWriter {
#[inline]
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
if self.pos == self.buf.len() {
self.buf.push_all(buf)
} else {
// Make sure the internal buffer is as least as big as where we
// currently are
let difference = self.pos as i64 - self.buf.len() as i64;
if difference > 0 {
self.buf.extend(repeat(0).take(difference as uint));
}
// Figure out what bytes will be used to overwrite what's currently
// there (left), and what will be appended on the end (right)
let cap = self.buf.len() - self.pos;
let (left, right) = if cap <= buf.len() {
(&buf[..cap], &buf[cap..])
} else {
let result: (_, &[_]) = (buf, &[]);
result
};
// Do the necessary writes
if left.len() > 0 {
slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), left);
}
if right.len() > 0 {
self.buf.push_all(right);
}
}
// Bump us forward
self.pos += buf.len();
Ok(())
}
}
impl Seek for SeekableMemWriter {
#[inline]
fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) }
#[inline]
fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
let new = try!(combine(style, self.pos, self.buf.len(), pos));
self.pos = new as uint;
Ok(())
}
}
#[cfg(test)]
mod tests {
extern crate test;
use super::SeekableMemWriter;
use std::io;
use std::iter::repeat;
use test::Bencher;
#[test]
fn test_seekable_mem_writer()
|
assert_eq!(writer.get_ref(), b);
writer.seek(-1, io::SeekEnd).unwrap();
writer.write(&[1, 2]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekEnd).unwrap();
writer.write(&[1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
assert_eq!(writer.get_ref(), b);
}
#[test]
fn seek_past_end() {
let mut r = SeekableMemWriter::new();
r.seek(10, io::SeekSet).unwrap();
assert!(r.write(&[3]).is_ok());
}
#[test]
fn seek_before_0() {
let mut r = SeekableMemWriter::new();
assert!(r.seek(-1, io::SeekSet).is_err());
}
fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) {
let src: Vec<u8> = repeat(5).take(len).collect();
b.bytes = (times * len) as u64;
b.iter(|| {
let mut wr = SeekableMemWriter::new();
for _ in range(0, times) {
wr.write(src.as_slice()).unwrap();
}
let v = wr.unwrap();
assert_eq!(v.len(), times * len);
assert!(v.iter().all(|x| *x == 5));
});
}
#[bench]
fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 0)
}
#[bench]
fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 10)
}
#[bench]
fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 100)
}
#[bench]
fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 1000)
}
#[bench]
fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 0)
}
#[bench]
fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 10)
}
#[bench]
fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 100)
}
#[bench]
fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 1000)
}
}
|
{
let mut writer = SeekableMemWriter::new();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[0]).unwrap();
assert_eq!(writer.tell(), Ok(1));
writer.write(&[1, 2, 3]).unwrap();
writer.write(&[4, 5, 6, 7]).unwrap();
assert_eq!(writer.tell(), Ok(8));
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(0, io::SeekSet).unwrap();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[3, 4]).unwrap();
let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekCur).unwrap();
writer.write(&[0, 1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
|
identifier_body
|
io.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io::{IoError, IoResult, SeekStyle};
use std::io;
use std::slice;
use std::iter::repeat;
static BUF_CAPACITY: uint = 128;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {
// compute offset as signed and clamp to prevent overflow
let pos = match seek {
io::SeekSet => 0,
io::SeekEnd => end,
io::SeekCur => cur,
} as i64;
if offset + pos < 0 {
Err(IoError {
kind: io::InvalidInput,
desc: "invalid seek to a negative offset",
detail: None
})
} else {
Ok((offset + pos) as u64)
}
}
/// Writes to an owned, growable byte vector that supports seeking.
///
/// # Example
///
/// ```rust
/// # #![allow(unused_must_use)]
/// use rbml::io::SeekableMemWriter;
///
/// let mut w = SeekableMemWriter::new();
/// w.write(&[0, 1, 2]);
///
/// assert_eq!(w.unwrap(), vec!(0, 1, 2));
/// ```
pub struct SeekableMemWriter {
buf: Vec<u8>,
pos: uint,
}
impl SeekableMemWriter {
/// Create a new `SeekableMemWriter`.
#[inline]
pub fn new() -> SeekableMemWriter {
SeekableMemWriter::with_capacity(BUF_CAPACITY)
}
/// Create a new `SeekableMemWriter`, allocating at least `n` bytes for
/// the internal buffer.
#[inline]
pub fn with_capacity(n: uint) -> SeekableMemWriter {
SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 }
}
/// Acquires an immutable reference to the underlying buffer of this
/// `SeekableMemWriter`.
///
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could corrupt the state of this `MemWriter`.
#[inline]
pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
/// Unwraps this `SeekableMemWriter`, returning the underlying buffer
#[inline]
pub fn unwrap(self) -> Vec<u8> { self.buf }
}
impl Writer for SeekableMemWriter {
#[inline]
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
if self.pos == self.buf.len() {
self.buf.push_all(buf)
} else {
// Make sure the internal buffer is as least as big as where we
// currently are
let difference = self.pos as i64 - self.buf.len() as i64;
if difference > 0 {
self.buf.extend(repeat(0).take(difference as uint));
}
// Figure out what bytes will be used to overwrite what's currently
// there (left), and what will be appended on the end (right)
let cap = self.buf.len() - self.pos;
let (left, right) = if cap <= buf.len() {
(&buf[..cap], &buf[cap..])
} else {
let result: (_, &[_]) = (buf, &[]);
result
};
// Do the necessary writes
if left.len() > 0 {
slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), left);
}
if right.len() > 0 {
self.buf.push_all(right);
}
}
// Bump us forward
self.pos += buf.len();
Ok(())
}
}
impl Seek for SeekableMemWriter {
#[inline]
fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) }
#[inline]
fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
let new = try!(combine(style, self.pos, self.buf.len(), pos));
self.pos = new as uint;
Ok(())
}
}
#[cfg(test)]
mod tests {
extern crate test;
use super::SeekableMemWriter;
use std::io;
use std::iter::repeat;
use test::Bencher;
#[test]
fn test_seekable_mem_writer() {
let mut writer = SeekableMemWriter::new();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[0]).unwrap();
assert_eq!(writer.tell(), Ok(1));
writer.write(&[1, 2, 3]).unwrap();
writer.write(&[4, 5, 6, 7]).unwrap();
assert_eq!(writer.tell(), Ok(8));
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(0, io::SeekSet).unwrap();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[3, 4]).unwrap();
let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
|
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(-1, io::SeekEnd).unwrap();
writer.write(&[1, 2]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekEnd).unwrap();
writer.write(&[1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
assert_eq!(writer.get_ref(), b);
}
#[test]
fn seek_past_end() {
let mut r = SeekableMemWriter::new();
r.seek(10, io::SeekSet).unwrap();
assert!(r.write(&[3]).is_ok());
}
#[test]
fn seek_before_0() {
let mut r = SeekableMemWriter::new();
assert!(r.seek(-1, io::SeekSet).is_err());
}
fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) {
let src: Vec<u8> = repeat(5).take(len).collect();
b.bytes = (times * len) as u64;
b.iter(|| {
let mut wr = SeekableMemWriter::new();
for _ in range(0, times) {
wr.write(src.as_slice()).unwrap();
}
let v = wr.unwrap();
assert_eq!(v.len(), times * len);
assert!(v.iter().all(|x| *x == 5));
});
}
#[bench]
fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 0)
}
#[bench]
fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 10)
}
#[bench]
fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 100)
}
#[bench]
fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 1000)
}
#[bench]
fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 0)
}
#[bench]
fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 10)
}
#[bench]
fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 100)
}
#[bench]
fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 100, 1000)
}
}
|
writer.seek(1, io::SeekCur).unwrap();
writer.write(&[0, 1]).unwrap();
|
random_line_split
|
main.rs
|
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
extern crate env_logger;
extern crate habitat_core as core;
extern crate habitat_launcher as launcher;
use std::env;
use std::process;
use launcher::server;
fn main() {
env_logger::init();
let args: Vec<String> = env::args().skip(1).collect();
// Since we have access to all the arguments passed to the
// Supervisor here, we can simply see if the user requested
// `--no-color` and set our global variable accordingly.
//
// This does, of course, rely on the option name used here staying
// in sync with the name used in the Supervisor.
//
// There is currently no short option to check; just the long
// name.
if args.contains(&String::from("--no-color"))
|
if let Err(err) = server::run(args) {
println!("{}", err);
process::exit(1);
}
}
|
{
core::output::set_no_color(true);
}
|
conditional_block
|
main.rs
|
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
extern crate env_logger;
extern crate habitat_core as core;
extern crate habitat_launcher as launcher;
use std::env;
use std::process;
use launcher::server;
fn main() {
env_logger::init();
let args: Vec<String> = env::args().skip(1).collect();
// Since we have access to all the arguments passed to the
// Supervisor here, we can simply see if the user requested
|
//
// This does, of course, rely on the option name used here staying
// in sync with the name used in the Supervisor.
//
// There is currently no short option to check; just the long
// name.
if args.contains(&String::from("--no-color")) {
core::output::set_no_color(true);
}
if let Err(err) = server::run(args) {
println!("{}", err);
process::exit(1);
}
}
|
// `--no-color` and set our global variable accordingly.
|
random_line_split
|
main.rs
|
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
extern crate env_logger;
extern crate habitat_core as core;
extern crate habitat_launcher as launcher;
use std::env;
use std::process;
use launcher::server;
fn main()
|
process::exit(1);
}
}
|
{
env_logger::init();
let args: Vec<String> = env::args().skip(1).collect();
// Since we have access to all the arguments passed to the
// Supervisor here, we can simply see if the user requested
// `--no-color` and set our global variable accordingly.
//
// This does, of course, rely on the option name used here staying
// in sync with the name used in the Supervisor.
//
// There is currently no short option to check; just the long
// name.
if args.contains(&String::from("--no-color")) {
core::output::set_no_color(true);
}
if let Err(err) = server::run(args) {
println!("{}", err);
|
identifier_body
|
main.rs
|
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
extern crate env_logger;
extern crate habitat_core as core;
extern crate habitat_launcher as launcher;
use std::env;
use std::process;
use launcher::server;
fn
|
() {
env_logger::init();
let args: Vec<String> = env::args().skip(1).collect();
// Since we have access to all the arguments passed to the
// Supervisor here, we can simply see if the user requested
// `--no-color` and set our global variable accordingly.
//
// This does, of course, rely on the option name used here staying
// in sync with the name used in the Supervisor.
//
// There is currently no short option to check; just the long
// name.
if args.contains(&String::from("--no-color")) {
core::output::set_no_color(true);
}
if let Err(err) = server::run(args) {
println!("{}", err);
process::exit(1);
}
}
|
main
|
identifier_name
|
middleware.rs
|
//! Traits to implement middleware types.
//!
//! This module defined the middleware traits for the closures that would be used as handlers and
//! middlewares in the application. This provides nice compile time guarantees of the what each
//! specific middleware can do and return. If anything else is returned then it results in a
//! compile time error.
use std::io;
use hyper::net::Fresh;
use request::Request;
use response::{Response, ShadowResponse};
/// Implements the kind of middleware that is executed when a request has arrived but before it is
/// passed on to the handler for being processed.
///
/// You have access to the request here and can do some pre-processing as required, but you cannot
/// write a response from a `BeforeMiddleware`. You need to implement a `Handler` to do that.
///
/// Typical uses for this middleware is for checking certain header or some form of authentication
/// on the request before it is served by the application.
pub trait BeforeMiddleware: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>);
}
impl<T> BeforeMiddleware for T where T: for <'m, 'r> Fn(&Request<'m, 'r>) + Send + Sync +'static {
fn
|
<'m, 'r>(&'m self, req: &Request<'m, 'r>) {
(*self)(req);
}
}
/// The actual logic for handling the request and writing the response is a part of this
/// middleware.
///
/// Here you have access to both the request and response objects and you need to write the
/// response for a particular request in the Handler type itself. Execution of a `Handler` returns
/// a `ShadowResponse` which is passed on to the `AfterMiddleware`.
pub trait Handler: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: Response<'m, Fresh>) -> io::Result<ShadowResponse>;
}
impl<T> Handler for T where T: for <'m, 'r> Fn(&Request<'m, 'r>, Response<'m>) -> io::Result<ShadowResponse> + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: Response<'m>) -> io::Result<ShadowResponse> {
(*self)(req, res)
}
}
/// Any logic to be executed per request after the response has been sent is a part of this
/// middleware.
///
/// This has access to the `Request` and `ShadowResponse` objects.
///
/// Typical uses for this middleware could be in logging something after the request is served.
pub trait AfterMiddleware: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: &ShadowResponse);
}
impl<T> AfterMiddleware for T where T: for <'m, 'r> Fn(&Request<'m, 'r>, &ShadowResponse) + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: &ShadowResponse) {
(*self)(req, res);
}
}
|
execute
|
identifier_name
|
middleware.rs
|
//! Traits to implement middleware types.
//!
//! This module defined the middleware traits for the closures that would be used as handlers and
//! middlewares in the application. This provides nice compile time guarantees of the what each
//! specific middleware can do and return. If anything else is returned then it results in a
//! compile time error.
use std::io;
use hyper::net::Fresh;
use request::Request;
use response::{Response, ShadowResponse};
/// Implements the kind of middleware that is executed when a request has arrived but before it is
/// passed on to the handler for being processed.
///
/// You have access to the request here and can do some pre-processing as required, but you cannot
/// write a response from a `BeforeMiddleware`. You need to implement a `Handler` to do that.
///
/// Typical uses for this middleware is for checking certain header or some form of authentication
/// on the request before it is served by the application.
pub trait BeforeMiddleware: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>);
}
impl<T> BeforeMiddleware for T where T: for <'m, 'r> Fn(&Request<'m, 'r>) + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>) {
(*self)(req);
}
}
/// The actual logic for handling the request and writing the response is a part of this
/// middleware.
///
/// Here you have access to both the request and response objects and you need to write the
/// response for a particular request in the Handler type itself. Execution of a `Handler` returns
/// a `ShadowResponse` which is passed on to the `AfterMiddleware`.
pub trait Handler: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: Response<'m, Fresh>) -> io::Result<ShadowResponse>;
}
impl<T> Handler for T where T: for <'m, 'r> Fn(&Request<'m, 'r>, Response<'m>) -> io::Result<ShadowResponse> + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: Response<'m>) -> io::Result<ShadowResponse>
|
}
/// Any logic to be executed per request after the response has been sent is a part of this
/// middleware.
///
/// This has access to the `Request` and `ShadowResponse` objects.
///
/// Typical uses for this middleware could be in logging something after the request is served.
pub trait AfterMiddleware: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: &ShadowResponse);
}
impl<T> AfterMiddleware for T where T: for <'m, 'r> Fn(&Request<'m, 'r>, &ShadowResponse) + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: &ShadowResponse) {
(*self)(req, res);
}
}
|
{
(*self)(req, res)
}
|
identifier_body
|
middleware.rs
|
//! Traits to implement middleware types.
//!
//! This module defined the middleware traits for the closures that would be used as handlers and
//! middlewares in the application. This provides nice compile time guarantees of the what each
//! specific middleware can do and return. If anything else is returned then it results in a
//! compile time error.
use std::io;
use hyper::net::Fresh;
use request::Request;
use response::{Response, ShadowResponse};
|
/// write a response from a `BeforeMiddleware`. You need to implement a `Handler` to do that.
///
/// Typical uses for this middleware is for checking certain header or some form of authentication
/// on the request before it is served by the application.
pub trait BeforeMiddleware: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>);
}
impl<T> BeforeMiddleware for T where T: for <'m, 'r> Fn(&Request<'m, 'r>) + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>) {
(*self)(req);
}
}
/// The actual logic for handling the request and writing the response is a part of this
/// middleware.
///
/// Here you have access to both the request and response objects and you need to write the
/// response for a particular request in the Handler type itself. Execution of a `Handler` returns
/// a `ShadowResponse` which is passed on to the `AfterMiddleware`.
pub trait Handler: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: Response<'m, Fresh>) -> io::Result<ShadowResponse>;
}
impl<T> Handler for T where T: for <'m, 'r> Fn(&Request<'m, 'r>, Response<'m>) -> io::Result<ShadowResponse> + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: Response<'m>) -> io::Result<ShadowResponse> {
(*self)(req, res)
}
}
/// Any logic to be executed per request after the response has been sent is a part of this
/// middleware.
///
/// This has access to the `Request` and `ShadowResponse` objects.
///
/// Typical uses for this middleware could be in logging something after the request is served.
pub trait AfterMiddleware: Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: &ShadowResponse);
}
impl<T> AfterMiddleware for T where T: for <'m, 'r> Fn(&Request<'m, 'r>, &ShadowResponse) + Send + Sync +'static {
fn execute<'m, 'r>(&'m self, req: &Request<'m, 'r>, res: &ShadowResponse) {
(*self)(req, res);
}
}
|
/// Implements the kind of middleware that is executed when a request has arrived but before it is
/// passed on to the handler for being processed.
///
/// You have access to the request here and can do some pre-processing as required, but you cannot
|
random_line_split
|
action_plugin.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
action_plugins::{
check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev,
lpurge, ltuer, lustre,
ntp::{action_configure, is_ntp_configured},
ostpool, package, postoffice,
stratagem::{
action_cloudsync, action_filesync, action_mirror, action_purge, action_warning, server,
},
},
lustre::lctl,
};
use iml_util::action_plugins;
use iml_wire_types::ActionName;
use tracing::info;
/// The registry of available actions to the `AgentDaemon`.
/// Add new Actions to the fn body as they are created.
pub fn
|
() -> action_plugins::Actions {
let map = action_plugins::Actions::default()
.add_plugin("start_unit", iml_systemd::start_unit)
.add_plugin("stop_unit", iml_systemd::stop_unit)
.add_plugin("enable_unit", iml_systemd::enable_unit)
.add_plugin("disable_unit", iml_systemd::disable_unit)
.add_plugin("restart_unit", iml_systemd::restart_unit)
.add_plugin("get_unit_run_state", iml_systemd::get_run_state)
.add_plugin("kernel_module_loaded", kernel_module::loaded)
.add_plugin("kernel_module_version", kernel_module::version)
.add_plugin("package_installed", package::installed)
.add_plugin("package_version", package::version)
.add_plugin("start_scan_stratagem", server::trigger_scan)
.add_plugin("stream_fidlists_stratagem", server::stream_fidlists)
.add_plugin("action_check_ha", high_availability::check_ha)
.add_plugin("action_check_stonith", check_stonith::check_stonith)
.add_plugin("get_kernel", check_kernel::get_kernel)
.add_plugin(
"get_ha_resource_list",
high_availability::get_ha_resource_list,
)
.add_plugin("mount", lustre::client::mount)
.add_plugin("mount_many", lustre::client::mount_many)
.add_plugin("unmount", lustre::client::unmount)
.add_plugin("unmount_many", lustre::client::unmount_many)
.add_plugin("ha_resource_start", high_availability::start_resource)
.add_plugin("ha_resource_stop", high_availability::stop_resource)
.add_plugin("crm_attribute", high_availability::crm_attribute)
.add_plugin(
"change_mcast_port",
high_availability::corosync_conf::change_mcast_port,
)
.add_plugin("add_firewall_port", firewall_cmd::add_port)
.add_plugin("remove_firewall_port", firewall_cmd::remove_port)
.add_plugin("pcs", high_availability::pcs)
.add_plugin("lctl", lctl::<Vec<_>, String>)
.add_plugin("ostpool_create", ostpool::action_pool_create)
.add_plugin("ostpool_wait", ostpool::action_pool_wait)
.add_plugin("ostpool_destroy", ostpool::action_pool_destroy)
.add_plugin("ostpool_add", ostpool::action_pool_add)
.add_plugin("ostpool_remove", ostpool::action_pool_remove)
.add_plugin("snapshot_create", lustre::snapshot::create)
.add_plugin("snapshot_destroy", lustre::snapshot::destroy)
.add_plugin("snapshot_mount", lustre::snapshot::mount)
.add_plugin("snapshot_unmount", lustre::snapshot::unmount)
.add_plugin("postoffice_add", postoffice::route_add)
.add_plugin("postoffice_remove", postoffice::route_remove)
.add_plugin("create_lpurge_conf", lpurge::create_lpurge_conf)
.add_plugin("create_lamigo_service", lamigo::create_lamigo_service_unit)
.add_plugin(
"configure_ntp",
action_configure::update_and_write_new_config,
)
.add_plugin("is_ntp_configured", is_ntp_configured::is_ntp_configured)
.add_plugin("create_ltuer_conf", ltuer::create_ltuer_conf)
.add_plugin("create_ldev_conf", ldev::create)
// Task Actions
.add_plugin("action.mirror.extend", action_mirror::process_extend_fids)
.add_plugin("action.mirror.resync", action_mirror::process_resync_fids)
.add_plugin("action.mirror.split", action_mirror::process_split_fids)
.add_plugin("action.stratagem.warning", action_warning::process_fids)
.add_plugin("action.stratagem.purge", action_purge::process_fids)
.add_plugin("action.stratagem.filesync", action_filesync::process_fids)
.add_plugin("action.stratagem.cloudsync", action_cloudsync::process_fids);
info!("Loaded the following ActionPlugins:");
for ActionName(key) in map.keys() {
info!("{}", key)
}
map
}
|
create_registry
|
identifier_name
|
action_plugin.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
|
action_plugins::{
check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev,
lpurge, ltuer, lustre,
ntp::{action_configure, is_ntp_configured},
ostpool, package, postoffice,
stratagem::{
action_cloudsync, action_filesync, action_mirror, action_purge, action_warning, server,
},
},
lustre::lctl,
};
use iml_util::action_plugins;
use iml_wire_types::ActionName;
use tracing::info;
/// The registry of available actions to the `AgentDaemon`.
/// Add new Actions to the fn body as they are created.
pub fn create_registry() -> action_plugins::Actions {
let map = action_plugins::Actions::default()
.add_plugin("start_unit", iml_systemd::start_unit)
.add_plugin("stop_unit", iml_systemd::stop_unit)
.add_plugin("enable_unit", iml_systemd::enable_unit)
.add_plugin("disable_unit", iml_systemd::disable_unit)
.add_plugin("restart_unit", iml_systemd::restart_unit)
.add_plugin("get_unit_run_state", iml_systemd::get_run_state)
.add_plugin("kernel_module_loaded", kernel_module::loaded)
.add_plugin("kernel_module_version", kernel_module::version)
.add_plugin("package_installed", package::installed)
.add_plugin("package_version", package::version)
.add_plugin("start_scan_stratagem", server::trigger_scan)
.add_plugin("stream_fidlists_stratagem", server::stream_fidlists)
.add_plugin("action_check_ha", high_availability::check_ha)
.add_plugin("action_check_stonith", check_stonith::check_stonith)
.add_plugin("get_kernel", check_kernel::get_kernel)
.add_plugin(
"get_ha_resource_list",
high_availability::get_ha_resource_list,
)
.add_plugin("mount", lustre::client::mount)
.add_plugin("mount_many", lustre::client::mount_many)
.add_plugin("unmount", lustre::client::unmount)
.add_plugin("unmount_many", lustre::client::unmount_many)
.add_plugin("ha_resource_start", high_availability::start_resource)
.add_plugin("ha_resource_stop", high_availability::stop_resource)
.add_plugin("crm_attribute", high_availability::crm_attribute)
.add_plugin(
"change_mcast_port",
high_availability::corosync_conf::change_mcast_port,
)
.add_plugin("add_firewall_port", firewall_cmd::add_port)
.add_plugin("remove_firewall_port", firewall_cmd::remove_port)
.add_plugin("pcs", high_availability::pcs)
.add_plugin("lctl", lctl::<Vec<_>, String>)
.add_plugin("ostpool_create", ostpool::action_pool_create)
.add_plugin("ostpool_wait", ostpool::action_pool_wait)
.add_plugin("ostpool_destroy", ostpool::action_pool_destroy)
.add_plugin("ostpool_add", ostpool::action_pool_add)
.add_plugin("ostpool_remove", ostpool::action_pool_remove)
.add_plugin("snapshot_create", lustre::snapshot::create)
.add_plugin("snapshot_destroy", lustre::snapshot::destroy)
.add_plugin("snapshot_mount", lustre::snapshot::mount)
.add_plugin("snapshot_unmount", lustre::snapshot::unmount)
.add_plugin("postoffice_add", postoffice::route_add)
.add_plugin("postoffice_remove", postoffice::route_remove)
.add_plugin("create_lpurge_conf", lpurge::create_lpurge_conf)
.add_plugin("create_lamigo_service", lamigo::create_lamigo_service_unit)
.add_plugin(
"configure_ntp",
action_configure::update_and_write_new_config,
)
.add_plugin("is_ntp_configured", is_ntp_configured::is_ntp_configured)
.add_plugin("create_ltuer_conf", ltuer::create_ltuer_conf)
.add_plugin("create_ldev_conf", ldev::create)
// Task Actions
.add_plugin("action.mirror.extend", action_mirror::process_extend_fids)
.add_plugin("action.mirror.resync", action_mirror::process_resync_fids)
.add_plugin("action.mirror.split", action_mirror::process_split_fids)
.add_plugin("action.stratagem.warning", action_warning::process_fids)
.add_plugin("action.stratagem.purge", action_purge::process_fids)
.add_plugin("action.stratagem.filesync", action_filesync::process_fids)
.add_plugin("action.stratagem.cloudsync", action_cloudsync::process_fids);
info!("Loaded the following ActionPlugins:");
for ActionName(key) in map.keys() {
info!("{}", key)
}
map
}
|
use crate::{
|
random_line_split
|
action_plugin.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
action_plugins::{
check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev,
lpurge, ltuer, lustre,
ntp::{action_configure, is_ntp_configured},
ostpool, package, postoffice,
stratagem::{
action_cloudsync, action_filesync, action_mirror, action_purge, action_warning, server,
},
},
lustre::lctl,
};
use iml_util::action_plugins;
use iml_wire_types::ActionName;
use tracing::info;
/// The registry of available actions to the `AgentDaemon`.
/// Add new Actions to the fn body as they are created.
pub fn create_registry() -> action_plugins::Actions
|
)
.add_plugin("mount", lustre::client::mount)
.add_plugin("mount_many", lustre::client::mount_many)
.add_plugin("unmount", lustre::client::unmount)
.add_plugin("unmount_many", lustre::client::unmount_many)
.add_plugin("ha_resource_start", high_availability::start_resource)
.add_plugin("ha_resource_stop", high_availability::stop_resource)
.add_plugin("crm_attribute", high_availability::crm_attribute)
.add_plugin(
"change_mcast_port",
high_availability::corosync_conf::change_mcast_port,
)
.add_plugin("add_firewall_port", firewall_cmd::add_port)
.add_plugin("remove_firewall_port", firewall_cmd::remove_port)
.add_plugin("pcs", high_availability::pcs)
.add_plugin("lctl", lctl::<Vec<_>, String>)
.add_plugin("ostpool_create", ostpool::action_pool_create)
.add_plugin("ostpool_wait", ostpool::action_pool_wait)
.add_plugin("ostpool_destroy", ostpool::action_pool_destroy)
.add_plugin("ostpool_add", ostpool::action_pool_add)
.add_plugin("ostpool_remove", ostpool::action_pool_remove)
.add_plugin("snapshot_create", lustre::snapshot::create)
.add_plugin("snapshot_destroy", lustre::snapshot::destroy)
.add_plugin("snapshot_mount", lustre::snapshot::mount)
.add_plugin("snapshot_unmount", lustre::snapshot::unmount)
.add_plugin("postoffice_add", postoffice::route_add)
.add_plugin("postoffice_remove", postoffice::route_remove)
.add_plugin("create_lpurge_conf", lpurge::create_lpurge_conf)
.add_plugin("create_lamigo_service", lamigo::create_lamigo_service_unit)
.add_plugin(
"configure_ntp",
action_configure::update_and_write_new_config,
)
.add_plugin("is_ntp_configured", is_ntp_configured::is_ntp_configured)
.add_plugin("create_ltuer_conf", ltuer::create_ltuer_conf)
.add_plugin("create_ldev_conf", ldev::create)
// Task Actions
.add_plugin("action.mirror.extend", action_mirror::process_extend_fids)
.add_plugin("action.mirror.resync", action_mirror::process_resync_fids)
.add_plugin("action.mirror.split", action_mirror::process_split_fids)
.add_plugin("action.stratagem.warning", action_warning::process_fids)
.add_plugin("action.stratagem.purge", action_purge::process_fids)
.add_plugin("action.stratagem.filesync", action_filesync::process_fids)
.add_plugin("action.stratagem.cloudsync", action_cloudsync::process_fids);
info!("Loaded the following ActionPlugins:");
for ActionName(key) in map.keys() {
info!("{}", key)
}
map
}
|
{
let map = action_plugins::Actions::default()
.add_plugin("start_unit", iml_systemd::start_unit)
.add_plugin("stop_unit", iml_systemd::stop_unit)
.add_plugin("enable_unit", iml_systemd::enable_unit)
.add_plugin("disable_unit", iml_systemd::disable_unit)
.add_plugin("restart_unit", iml_systemd::restart_unit)
.add_plugin("get_unit_run_state", iml_systemd::get_run_state)
.add_plugin("kernel_module_loaded", kernel_module::loaded)
.add_plugin("kernel_module_version", kernel_module::version)
.add_plugin("package_installed", package::installed)
.add_plugin("package_version", package::version)
.add_plugin("start_scan_stratagem", server::trigger_scan)
.add_plugin("stream_fidlists_stratagem", server::stream_fidlists)
.add_plugin("action_check_ha", high_availability::check_ha)
.add_plugin("action_check_stonith", check_stonith::check_stonith)
.add_plugin("get_kernel", check_kernel::get_kernel)
.add_plugin(
"get_ha_resource_list",
high_availability::get_ha_resource_list,
|
identifier_body
|
fat.rs
|
use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if 0, then sector_count >= 65536. actual value is large_sector_count
media_type: u8,
sectors_per_fat: u16, // for fat12/fat16 only
sectors_per_track: u16,
head_count: u16,
hidden_sector_count: u32,
large_sector_count: u32,
}
impl BPB {
fn fat_type(&self) -> FatFormat {
let dirent_sectors = (
(self.root_dir_entry_count as u32 * mem::size_of::<DirectoryEntry>() as u32)
.align(self.bytes_per_sector as u32)) / self.bytes_per_sector as u32;
let cluster_count =
(if self.sector_count == 0 { self.large_sector_count } else { self.sector_count as u32 }
- self.resd_sectors as u32 - (self.fat_count as u32 * self.sectors_per_fat as u32)
- dirent_sectors) / self.sectors_per_cluster as u32;
match cluster_count {
n if n < 4085 => FatFormat::Fat12,
n if n < 65525 => FatFormat::Fat16,
_ => FatFormat::Fat32,
}
}
}
#[repr(packed)]
pub struct DirectoryEntry {
name: [u8; 11],
attribute: u8,
_reserved: [u8; 10],
time: u16,
date: u16,
start_cluster: u16,
size: u32,
}
impl DirectoryEntry {
pub const READ_ONLY: u8 = 1 << 0;
pub const HIDDEN: u8 = 1 << 1;
pub const SYSTEM: u8 = 1 << 2;
pub const VOL_LABEL: u8 = 1 << 3;
pub const SUB_DIR: u8 = 1 << 4;
pub const ARCHIVE: u8 = 1 << 5;
// Returns true if the char is to be replaced by an underscore
fn is_replace_char(c: u8) -> bool {
match c {
b'+' | b',' | b';' | b'=' | b'[' | b']' => true,
_ => false
}
}
/* Legal characters are:
* <space>
* Numbers: 0-9
* Upper-case letters: A-Z
* Punctuation:!, #, $, %, & ', (, ), -, @, ^, _, `, {, }, ~
* 0x80-0xff (note that 0xE5 is stored as 0x05 on disk)
0x2E ('.') is reserved for dot entries
*/
fn is_legal_dos_char(c: u8) -> bool {
match c {
b''| b'0'..=b'9' | b'A'..=b'Z' | b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'(' | b')'
| b'-' | b'@' | b'^' | b'_' | b'`' | b'{' | b'}' | b'~' | 0x80..=0xff => true,
_ => false
}
}
fn short_filename(filename: Vec<u8>) -> Option<([u8; 8], Option<[u8; 3]>, bool)> {
let mut parts = filename
.rsplitn(2, |c| *c == b'.');
if let Some(name) = parts.next() {
let mut basename = [b' '; 8];
let mut extension = [b' '; 3];
let mut oversized = false;
let base = if let Some(b) = parts.next() {
// Filename contains extension
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let ext_iter = name
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut ext_i = 0;
for c in ext_iter {
// trim any leading spaces
if c == b''&& ext_i == 0 {
continue;
} else if ext_i == extension.len() {
break;
}
extension[ext_i] = c;
ext_i += 1;
}
b
} else {
// No extension
name
};
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let base_iter = base
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut base_i = 0;
for c in base_iter {
// Trim leading spaces
if c == b''&& base_i == 0 {
continue;
} else if base_i == basename.len() {
// Base name is too long. A tilde and a digit will need to follow the filename,
// but the digit depends on how many other similarly named files exist in the
// directory.
oversized = true;
break;
}
basename[base_i] = c;
base_i += 1;
}
if extension == [b' ', b' ', b' '] {
Some((basename, None, oversized))
} else {
Some((basename, Some(extension), oversized))
}
} else {
None
}
}
}
#[repr(packed)]
pub struct FatBPB {
bpb: BPB,
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 448],
partition_signature: u16, // 0xAA55
}
#[repr(packed)]
pub struct Fat32BPB {
bpb: BPB,
sectors_per_fat: u32,
flags: u16,
fat_version: u16,
root_dir_cluster: u32,
fs_info_sector: u16,
backup_boot_sector: u16,
_reserved: [u8; 12],
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 420],
partition_signature: u16, // 0xAA55
}
pub enum
|
{
Free,
Used,
Bad,
Reserved,
End,
Invalid,
}
pub enum FatFormat {
Fat12,
Fat16,
Fat32,
}
impl FatFormat {
pub fn cluster_type(&self, cluster: u32) -> ClusterType {
match self {
Self::Fat12 => match cluster {
0 => ClusterType::Free,
0xFF8..=0xFFF => ClusterType::End,
2..=0xFEF => ClusterType::Used,
0xFF7 => ClusterType::Bad,
1 | 0xFF0..=0xFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat16 => match cluster {
0 => ClusterType::Free,
0xFFF8..=0xFFFF => ClusterType::End,
2..=0xFFEF => ClusterType::Used,
0xFFF7 => ClusterType::Bad,
1 | 0xFFF0..=0xFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat32 => match cluster {
0 => ClusterType::Free,
0xFFFFFF8..=0xFFFFFFF => ClusterType::End,
2..=0xFFFFFEF => ClusterType::Used,
0xFFFFFF7 => ClusterType::Bad,
1 | 0xFFFFFF0..=0xFFFFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
}
}
}
}
|
ClusterType
|
identifier_name
|
fat.rs
|
use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if 0, then sector_count >= 65536. actual value is large_sector_count
media_type: u8,
sectors_per_fat: u16, // for fat12/fat16 only
sectors_per_track: u16,
head_count: u16,
hidden_sector_count: u32,
large_sector_count: u32,
}
impl BPB {
fn fat_type(&self) -> FatFormat {
let dirent_sectors = (
(self.root_dir_entry_count as u32 * mem::size_of::<DirectoryEntry>() as u32)
.align(self.bytes_per_sector as u32)) / self.bytes_per_sector as u32;
let cluster_count =
(if self.sector_count == 0 { self.large_sector_count } else { self.sector_count as u32 }
- self.resd_sectors as u32 - (self.fat_count as u32 * self.sectors_per_fat as u32)
- dirent_sectors) / self.sectors_per_cluster as u32;
match cluster_count {
n if n < 4085 => FatFormat::Fat12,
n if n < 65525 => FatFormat::Fat16,
_ => FatFormat::Fat32,
}
}
}
#[repr(packed)]
pub struct DirectoryEntry {
name: [u8; 11],
attribute: u8,
_reserved: [u8; 10],
time: u16,
date: u16,
start_cluster: u16,
size: u32,
}
impl DirectoryEntry {
pub const READ_ONLY: u8 = 1 << 0;
pub const HIDDEN: u8 = 1 << 1;
pub const SYSTEM: u8 = 1 << 2;
pub const VOL_LABEL: u8 = 1 << 3;
pub const SUB_DIR: u8 = 1 << 4;
pub const ARCHIVE: u8 = 1 << 5;
// Returns true if the char is to be replaced by an underscore
fn is_replace_char(c: u8) -> bool {
match c {
b'+' | b',' | b';' | b'=' | b'[' | b']' => true,
_ => false
}
}
/* Legal characters are:
* <space>
* Numbers: 0-9
* Upper-case letters: A-Z
* Punctuation:!, #, $, %, & ', (, ), -, @, ^, _, `, {, }, ~
* 0x80-0xff (note that 0xE5 is stored as 0x05 on disk)
0x2E ('.') is reserved for dot entries
*/
fn is_legal_dos_char(c: u8) -> bool {
match c {
b''| b'0'..=b'9' | b'A'..=b'Z' | b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'(' | b')'
| b'-' | b'@' | b'^' | b'_' | b'`' | b'{' | b'}' | b'~' | 0x80..=0xff => true,
_ => false
}
}
fn short_filename(filename: Vec<u8>) -> Option<([u8; 8], Option<[u8; 3]>, bool)> {
let mut parts = filename
.rsplitn(2, |c| *c == b'.');
if let Some(name) = parts.next() {
let mut basename = [b' '; 8];
let mut extension = [b' '; 3];
let mut oversized = false;
let base = if let Some(b) = parts.next() {
// Filename contains extension
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let ext_iter = name
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut ext_i = 0;
for c in ext_iter {
// trim any leading spaces
if c == b''&& ext_i == 0 {
continue;
} else if ext_i == extension.len() {
break;
}
extension[ext_i] = c;
ext_i += 1;
}
b
} else {
// No extension
name
};
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let base_iter = base
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut base_i = 0;
for c in base_iter {
// Trim leading spaces
if c == b''&& base_i == 0 {
continue;
} else if base_i == basename.len() {
// Base name is too long. A tilde and a digit will need to follow the filename,
// but the digit depends on how many other similarly named files exist in the
// directory.
oversized = true;
break;
}
basename[base_i] = c;
base_i += 1;
}
if extension == [b' ', b' ', b' '] {
Some((basename, None, oversized))
} else
|
} else {
None
}
}
}
#[repr(packed)]
pub struct FatBPB {
bpb: BPB,
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 448],
partition_signature: u16, // 0xAA55
}
#[repr(packed)]
pub struct Fat32BPB {
bpb: BPB,
sectors_per_fat: u32,
flags: u16,
fat_version: u16,
root_dir_cluster: u32,
fs_info_sector: u16,
backup_boot_sector: u16,
_reserved: [u8; 12],
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 420],
partition_signature: u16, // 0xAA55
}
pub enum ClusterType {
Free,
Used,
Bad,
Reserved,
End,
Invalid,
}
pub enum FatFormat {
Fat12,
Fat16,
Fat32,
}
impl FatFormat {
pub fn cluster_type(&self, cluster: u32) -> ClusterType {
match self {
Self::Fat12 => match cluster {
0 => ClusterType::Free,
0xFF8..=0xFFF => ClusterType::End,
2..=0xFEF => ClusterType::Used,
0xFF7 => ClusterType::Bad,
1 | 0xFF0..=0xFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat16 => match cluster {
0 => ClusterType::Free,
0xFFF8..=0xFFFF => ClusterType::End,
2..=0xFFEF => ClusterType::Used,
0xFFF7 => ClusterType::Bad,
1 | 0xFFF0..=0xFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat32 => match cluster {
0 => ClusterType::Free,
0xFFFFFF8..=0xFFFFFFF => ClusterType::End,
2..=0xFFFFFEF => ClusterType::Used,
0xFFFFFF7 => ClusterType::Bad,
1 | 0xFFFFFF0..=0xFFFFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
}
}
}
}
|
{
Some((basename, Some(extension), oversized))
}
|
conditional_block
|
fat.rs
|
use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if 0, then sector_count >= 65536. actual value is large_sector_count
media_type: u8,
sectors_per_fat: u16, // for fat12/fat16 only
sectors_per_track: u16,
head_count: u16,
hidden_sector_count: u32,
large_sector_count: u32,
}
impl BPB {
fn fat_type(&self) -> FatFormat {
let dirent_sectors = (
(self.root_dir_entry_count as u32 * mem::size_of::<DirectoryEntry>() as u32)
.align(self.bytes_per_sector as u32)) / self.bytes_per_sector as u32;
let cluster_count =
(if self.sector_count == 0 { self.large_sector_count } else { self.sector_count as u32 }
- self.resd_sectors as u32 - (self.fat_count as u32 * self.sectors_per_fat as u32)
- dirent_sectors) / self.sectors_per_cluster as u32;
match cluster_count {
n if n < 4085 => FatFormat::Fat12,
n if n < 65525 => FatFormat::Fat16,
_ => FatFormat::Fat32,
}
}
}
#[repr(packed)]
pub struct DirectoryEntry {
name: [u8; 11],
attribute: u8,
_reserved: [u8; 10],
time: u16,
date: u16,
start_cluster: u16,
size: u32,
}
impl DirectoryEntry {
pub const READ_ONLY: u8 = 1 << 0;
pub const HIDDEN: u8 = 1 << 1;
pub const SYSTEM: u8 = 1 << 2;
pub const VOL_LABEL: u8 = 1 << 3;
pub const SUB_DIR: u8 = 1 << 4;
pub const ARCHIVE: u8 = 1 << 5;
// Returns true if the char is to be replaced by an underscore
fn is_replace_char(c: u8) -> bool {
match c {
b'+' | b',' | b';' | b'=' | b'[' | b']' => true,
_ => false
}
}
/* Legal characters are:
* <space>
* Numbers: 0-9
* Upper-case letters: A-Z
* Punctuation:!, #, $, %, & ', (, ), -, @, ^, _, `, {, }, ~
* 0x80-0xff (note that 0xE5 is stored as 0x05 on disk)
0x2E ('.') is reserved for dot entries
*/
fn is_legal_dos_char(c: u8) -> bool {
match c {
b''| b'0'..=b'9' | b'A'..=b'Z' | b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'(' | b')'
| b'-' | b'@' | b'^' | b'_' | b'`' | b'{' | b'}' | b'~' | 0x80..=0xff => true,
_ => false
}
}
fn short_filename(filename: Vec<u8>) -> Option<([u8; 8], Option<[u8; 3]>, bool)> {
let mut parts = filename
.rsplitn(2, |c| *c == b'.');
if let Some(name) = parts.next() {
let mut basename = [b' '; 8];
let mut extension = [b' '; 3];
let mut oversized = false;
let base = if let Some(b) = parts.next() {
// Filename contains extension
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let ext_iter = name
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut ext_i = 0;
for c in ext_iter {
// trim any leading spaces
if c == b''&& ext_i == 0 {
continue;
} else if ext_i == extension.len() {
break;
}
extension[ext_i] = c;
ext_i += 1;
}
b
} else {
// No extension
name
};
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let base_iter = base
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut base_i = 0;
for c in base_iter {
// Trim leading spaces
if c == b''&& base_i == 0 {
continue;
} else if base_i == basename.len() {
// Base name is too long. A tilde and a digit will need to follow the filename,
// but the digit depends on how many other similarly named files exist in the
// directory.
oversized = true;
break;
}
|
}
if extension == [b' ', b' ', b' '] {
Some((basename, None, oversized))
} else {
Some((basename, Some(extension), oversized))
}
} else {
None
}
}
}
#[repr(packed)]
pub struct FatBPB {
bpb: BPB,
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 448],
partition_signature: u16, // 0xAA55
}
#[repr(packed)]
pub struct Fat32BPB {
bpb: BPB,
sectors_per_fat: u32,
flags: u16,
fat_version: u16,
root_dir_cluster: u32,
fs_info_sector: u16,
backup_boot_sector: u16,
_reserved: [u8; 12],
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 420],
partition_signature: u16, // 0xAA55
}
pub enum ClusterType {
Free,
Used,
Bad,
Reserved,
End,
Invalid,
}
pub enum FatFormat {
Fat12,
Fat16,
Fat32,
}
impl FatFormat {
pub fn cluster_type(&self, cluster: u32) -> ClusterType {
match self {
Self::Fat12 => match cluster {
0 => ClusterType::Free,
0xFF8..=0xFFF => ClusterType::End,
2..=0xFEF => ClusterType::Used,
0xFF7 => ClusterType::Bad,
1 | 0xFF0..=0xFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat16 => match cluster {
0 => ClusterType::Free,
0xFFF8..=0xFFFF => ClusterType::End,
2..=0xFFEF => ClusterType::Used,
0xFFF7 => ClusterType::Bad,
1 | 0xFFF0..=0xFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat32 => match cluster {
0 => ClusterType::Free,
0xFFFFFF8..=0xFFFFFFF => ClusterType::End,
2..=0xFFFFFEF => ClusterType::Used,
0xFFFFFF7 => ClusterType::Bad,
1 | 0xFFFFFF0..=0xFFFFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
}
}
}
}
|
basename[base_i] = c;
base_i += 1;
|
random_line_split
|
fat.rs
|
use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if 0, then sector_count >= 65536. actual value is large_sector_count
media_type: u8,
sectors_per_fat: u16, // for fat12/fat16 only
sectors_per_track: u16,
head_count: u16,
hidden_sector_count: u32,
large_sector_count: u32,
}
impl BPB {
fn fat_type(&self) -> FatFormat {
let dirent_sectors = (
(self.root_dir_entry_count as u32 * mem::size_of::<DirectoryEntry>() as u32)
.align(self.bytes_per_sector as u32)) / self.bytes_per_sector as u32;
let cluster_count =
(if self.sector_count == 0 { self.large_sector_count } else { self.sector_count as u32 }
- self.resd_sectors as u32 - (self.fat_count as u32 * self.sectors_per_fat as u32)
- dirent_sectors) / self.sectors_per_cluster as u32;
match cluster_count {
n if n < 4085 => FatFormat::Fat12,
n if n < 65525 => FatFormat::Fat16,
_ => FatFormat::Fat32,
}
}
}
#[repr(packed)]
pub struct DirectoryEntry {
name: [u8; 11],
attribute: u8,
_reserved: [u8; 10],
time: u16,
date: u16,
start_cluster: u16,
size: u32,
}
impl DirectoryEntry {
pub const READ_ONLY: u8 = 1 << 0;
pub const HIDDEN: u8 = 1 << 1;
pub const SYSTEM: u8 = 1 << 2;
pub const VOL_LABEL: u8 = 1 << 3;
pub const SUB_DIR: u8 = 1 << 4;
pub const ARCHIVE: u8 = 1 << 5;
// Returns true if the char is to be replaced by an underscore
fn is_replace_char(c: u8) -> bool {
match c {
b'+' | b',' | b';' | b'=' | b'[' | b']' => true,
_ => false
}
}
/* Legal characters are:
* <space>
* Numbers: 0-9
* Upper-case letters: A-Z
* Punctuation:!, #, $, %, & ', (, ), -, @, ^, _, `, {, }, ~
* 0x80-0xff (note that 0xE5 is stored as 0x05 on disk)
0x2E ('.') is reserved for dot entries
*/
fn is_legal_dos_char(c: u8) -> bool {
match c {
b''| b'0'..=b'9' | b'A'..=b'Z' | b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'(' | b')'
| b'-' | b'@' | b'^' | b'_' | b'`' | b'{' | b'}' | b'~' | 0x80..=0xff => true,
_ => false
}
}
fn short_filename(filename: Vec<u8>) -> Option<([u8; 8], Option<[u8; 3]>, bool)>
|
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut ext_i = 0;
for c in ext_iter {
// trim any leading spaces
if c == b''&& ext_i == 0 {
continue;
} else if ext_i == extension.len() {
break;
}
extension[ext_i] = c;
ext_i += 1;
}
b
} else {
// No extension
name
};
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let base_iter = base
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut base_i = 0;
for c in base_iter {
// Trim leading spaces
if c == b''&& base_i == 0 {
continue;
} else if base_i == basename.len() {
// Base name is too long. A tilde and a digit will need to follow the filename,
// but the digit depends on how many other similarly named files exist in the
// directory.
oversized = true;
break;
}
basename[base_i] = c;
base_i += 1;
}
if extension == [b' ', b' ', b' '] {
Some((basename, None, oversized))
} else {
Some((basename, Some(extension), oversized))
}
} else {
None
}
}
}
#[repr(packed)]
pub struct FatBPB {
bpb: BPB,
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 448],
partition_signature: u16, // 0xAA55
}
#[repr(packed)]
pub struct Fat32BPB {
bpb: BPB,
sectors_per_fat: u32,
flags: u16,
fat_version: u16,
root_dir_cluster: u32,
fs_info_sector: u16,
backup_boot_sector: u16,
_reserved: [u8; 12],
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 420],
partition_signature: u16, // 0xAA55
}
pub enum ClusterType {
Free,
Used,
Bad,
Reserved,
End,
Invalid,
}
pub enum FatFormat {
Fat12,
Fat16,
Fat32,
}
impl FatFormat {
pub fn cluster_type(&self, cluster: u32) -> ClusterType {
match self {
Self::Fat12 => match cluster {
0 => ClusterType::Free,
0xFF8..=0xFFF => ClusterType::End,
2..=0xFEF => ClusterType::Used,
0xFF7 => ClusterType::Bad,
1 | 0xFF0..=0xFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat16 => match cluster {
0 => ClusterType::Free,
0xFFF8..=0xFFFF => ClusterType::End,
2..=0xFFEF => ClusterType::Used,
0xFFF7 => ClusterType::Bad,
1 | 0xFFF0..=0xFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
},
Self::Fat32 => match cluster {
0 => ClusterType::Free,
0xFFFFFF8..=0xFFFFFFF => ClusterType::End,
2..=0xFFFFFEF => ClusterType::Used,
0xFFFFFF7 => ClusterType::Bad,
1 | 0xFFFFFF0..=0xFFFFFF6 => ClusterType::Reserved,
_ => ClusterType::Invalid,
}
}
}
}
|
{
let mut parts = filename
.rsplitn(2, |c| *c == b'.');
if let Some(name) = parts.next() {
let mut basename = [b' '; 8];
let mut extension = [b' '; 3];
let mut oversized = false;
let base = if let Some(b) = parts.next() {
// Filename contains extension
// Replace some invalid chars with underscores, convert lowercase to uppercase, and
// remove any remaining invalid characters.
let ext_iter = name
.iter()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
|
identifier_body
|
map.rs
|
use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const FLOOR_HEIGHT: i32 = 30;
pub const ROOM_MAX_SIZE: i32 = 10;
pub const ROOM_MIN_X: i32 = 8;
pub const ROOM_MIN_Y: i32 = 8;
pub const MAX_ROOMS: i32 = 30;
pub const MAX_ROOM_MONSTERS: i32 = 3;
pub const MAX_ROOM_ITEMS:i32 = 4;
#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct Tile {
pub floor: Object,
pub explored: bool,
pub items: Vec<Object>,
}
impl Tile {
pub fn new(floor: &ObjectClass) -> Self {
Tile{
floor: floor.create_object(),
explored: false,
items: vec![],}
}
}
pub fn is_blocked(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all objects in the map location to see if they block
// If only one thing blocks fully we know nothing new can move
// onto that tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub fn blocks_view(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all actors in the map location to see if they block
// If only one thing blocks fully we know nothing can see through that
// tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks_view);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks_view);
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub type Map = Vec<Vec<Tile>>;
#[derive(Clone, Copy, Debug)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
pub fn new(x: i32, y: i32, w: i32, h: i32)
-> Self {
Rect { x1: x, y1: y, x2: x + w, y2: y + h }
}
pub fn center(&self) -> (i32, i32) {
let center_x = (self.x1 + self.x2) / 2;
let center_y = (self.y1 + self.y2) / 2;
(center_x, center_y)
}
pub fn intersects_with(&self, other: &Rect) -> bool {
(self.x1 <= other.x2) && (self.x2 >= other.x1) &&
(self.y1 <= other.y2) && (self.y2 >= other.y1)
}
}
fn create_room(room: &mut Bsp, floor_class: &ObjectClass, map: &mut Map) {
for x in (room.x)..room.x + room.w {
for y in (room.y)..room.y + room.h {
map[x as usize][y as usize] = Tile::new(floor_class);
}
}
}
fn place_objects(floor: usize,
rooms: &Vec<Rect>, map: &mut Map,
items: &object::load::ObjectTypes) {
if floor == 1 {
let mut stairs = (0, 0);
for room in rooms {
let ref mut door_randomizer = items.create_randomizer("door").unwrap();
if room.x1 == 1 && room.y1 == 1 {
make_door(0, room.y2 / 2, door_randomizer, map);
} else if room.y2 == FLOOR_HEIGHT - 1 || room.x2 == FLOOR_WIDTH - 1 {
if stairs == (0, 0) || rand::random()
|
}
}
let (stairs_x, stairs_y) = stairs;
let mut stairs_up = items.get_class("stairs up").create_object();
stairs_up.set_pos(stairs_x, stairs_y);
map[stairs_x as usize][stairs_y as usize].items.push(stairs_up);
}
for _ in 0..rand::thread_rng().gen_range(1,3) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let brick_x = room.x1 + 1;
let brick_y = room.y1 + 2;
if let Some(ref mut brick_random) = items.create_randomizer(
"environmental weapon") {
let brick_class = &mut brick_random.get_class();
let mut brick = brick_class.create_object();
brick.set_pos(brick_x, brick_y);
map[brick_x as usize][brick_y as usize].items.push(brick);
};
}
}
fn place_actors(floor: usize, rooms: &Vec<Rect>, map: &mut Map,
actor_types: &object::load::ObjectTypes,
actors: &mut Vec<Object>) {
for room in rooms {
if room.x1 == 1 && room.y1 == 1 {
actors[consts::PLAYER].set_pos(1, room.y2 / 2);
}
}
for _ in 0..rand::thread_rng().gen_range(1,2) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let x = rand::thread_rng().gen_range(room.x1+1, room.x2);
let y = rand::thread_rng().gen_range(room.y1+1, room.y2);
if let Some(ref mut zombie_random) = actor_types.create_randomizer(
"zombie") {
let zombie_class = &mut zombie_random.get_class();
let mut zombie = zombie_class.create_object();
zombie.set_pos(x, y);
actors.push(zombie);
}
}
}
fn make_door(x: i32, y: i32, door_randomizer: &mut ObjectRandomizer,
map: &mut Map) {
let door_class = door_randomizer.get_class();
let mut door = door_class.create_object();
door.set_pos(x, y);
map[x as usize][y as usize].items[0] = door;
}
fn traverse_node(node: &mut Bsp, rooms: &mut Vec<Rect>,
object_types: &object::load::ObjectTypes,
floor_type: &ObjectClass,
mut map: &mut Map) -> bool {
if node.is_leaf() {
let minx = node.x + 1;
let mut maxx = node.x + node.w - 1;
let mut miny = node.y + 1;
let mut maxy = node.y + node.h - 1;
if maxx == FLOOR_WIDTH - 1 {
maxx -= 1;
}
if maxy == FLOOR_HEIGHT - 1 {
maxy -= 1;
}
node.x = minx;
node.y = miny;
node.w = maxx - minx + 1;
node.h = maxy - miny + 1;
create_room(node, floor_type, map);
rooms.push(Rect::new(node.x, node.y, node.w, node.h));
} else {
if let (Some(left), Some(right)) = (node.left(), node.right()) {
node.x = cmp::min(left.x, right.x);
node.y = cmp::min(left.y, right.y);
node.w = cmp::max(left.x + left.w, right.x + right.w) - node.x;
node.h = cmp::max(left.y + left.h, right.y + right.h) - node.y;
let ref mut door_randomizer = object_types.create_randomizer("door")
.unwrap();
if node.horizontal() {
make_door(left.x, cmp::max(left.y, right.y) - 1,
door_randomizer, &mut map);
} else {
make_door(cmp::max(left.x, right.x) - 1, left.y,
door_randomizer, &mut map);
}
}
}
true
}
pub fn make_map(mut actors: &mut Vec<Object>) -> Map {
let mut map = vec![];
let actor_types = object::load::load_objects(
"data/objects/actors.json").unwrap();
let item_types = object::load::load_objects(
"data/objects/items.json").unwrap();
let wall_class = item_types.get_class("brick wall");
let concrete_floor = item_types.get_class("concrete floor");
for x in 0..FLOOR_WIDTH {
map.push(vec![]);
for y in 0..FLOOR_HEIGHT {
let mut wall_tile: Tile = Tile::new(&concrete_floor);
let mut brick_wall = wall_class.create_object();
brick_wall.set_pos(x, y);
wall_tile.items.push(brick_wall);
map[x as usize].push(wall_tile);
}
}
let mut rooms = vec![];
let mut bsp = Bsp::new_with_size(0, 0, FLOOR_WIDTH, FLOOR_HEIGHT);
bsp.split_recursive(None, 3, ROOM_MIN_X, ROOM_MIN_Y, 1.25, 1.25);
bsp.traverse(TraverseOrder::InvertedLevelOrder, |node| {
traverse_node(node, &mut rooms, &item_types, &concrete_floor, &mut map)
});
place_objects(1, &rooms, &mut map, &item_types);
place_actors(1, &rooms, &mut map, &actor_types, &mut actors);
map
}
|
{
let stairs_x = room.x1 + ((room.x2 - room.x1)/2);
let stairs_y = room.y1 + ((room.y2 - room.y1)/2);
stairs = (stairs_x, stairs_y);
}
|
conditional_block
|
map.rs
|
use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const FLOOR_HEIGHT: i32 = 30;
pub const ROOM_MAX_SIZE: i32 = 10;
pub const ROOM_MIN_X: i32 = 8;
pub const ROOM_MIN_Y: i32 = 8;
pub const MAX_ROOMS: i32 = 30;
pub const MAX_ROOM_MONSTERS: i32 = 3;
pub const MAX_ROOM_ITEMS:i32 = 4;
#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct Tile {
pub floor: Object,
pub explored: bool,
pub items: Vec<Object>,
}
impl Tile {
pub fn new(floor: &ObjectClass) -> Self {
Tile{
floor: floor.create_object(),
explored: false,
items: vec![],}
}
}
pub fn is_blocked(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all objects in the map location to see if they block
// If only one thing blocks fully we know nothing new can move
// onto that tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub fn blocks_view(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks
|
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub type Map = Vec<Vec<Tile>>;
#[derive(Clone, Copy, Debug)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
pub fn new(x: i32, y: i32, w: i32, h: i32)
-> Self {
Rect { x1: x, y1: y, x2: x + w, y2: y + h }
}
pub fn center(&self) -> (i32, i32) {
let center_x = (self.x1 + self.x2) / 2;
let center_y = (self.y1 + self.y2) / 2;
(center_x, center_y)
}
pub fn intersects_with(&self, other: &Rect) -> bool {
(self.x1 <= other.x2) && (self.x2 >= other.x1) &&
(self.y1 <= other.y2) && (self.y2 >= other.y1)
}
}
fn create_room(room: &mut Bsp, floor_class: &ObjectClass, map: &mut Map) {
for x in (room.x)..room.x + room.w {
for y in (room.y)..room.y + room.h {
map[x as usize][y as usize] = Tile::new(floor_class);
}
}
}
fn place_objects(floor: usize,
rooms: &Vec<Rect>, map: &mut Map,
items: &object::load::ObjectTypes) {
if floor == 1 {
let mut stairs = (0, 0);
for room in rooms {
let ref mut door_randomizer = items.create_randomizer("door").unwrap();
if room.x1 == 1 && room.y1 == 1 {
make_door(0, room.y2 / 2, door_randomizer, map);
} else if room.y2 == FLOOR_HEIGHT - 1 || room.x2 == FLOOR_WIDTH - 1 {
if stairs == (0, 0) || rand::random() {
let stairs_x = room.x1 + ((room.x2 - room.x1)/2);
let stairs_y = room.y1 + ((room.y2 - room.y1)/2);
stairs = (stairs_x, stairs_y);
}
}
}
let (stairs_x, stairs_y) = stairs;
let mut stairs_up = items.get_class("stairs up").create_object();
stairs_up.set_pos(stairs_x, stairs_y);
map[stairs_x as usize][stairs_y as usize].items.push(stairs_up);
}
for _ in 0..rand::thread_rng().gen_range(1,3) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let brick_x = room.x1 + 1;
let brick_y = room.y1 + 2;
if let Some(ref mut brick_random) = items.create_randomizer(
"environmental weapon") {
let brick_class = &mut brick_random.get_class();
let mut brick = brick_class.create_object();
brick.set_pos(brick_x, brick_y);
map[brick_x as usize][brick_y as usize].items.push(brick);
};
}
}
fn place_actors(floor: usize, rooms: &Vec<Rect>, map: &mut Map,
actor_types: &object::load::ObjectTypes,
actors: &mut Vec<Object>) {
for room in rooms {
if room.x1 == 1 && room.y1 == 1 {
actors[consts::PLAYER].set_pos(1, room.y2 / 2);
}
}
for _ in 0..rand::thread_rng().gen_range(1,2) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let x = rand::thread_rng().gen_range(room.x1+1, room.x2);
let y = rand::thread_rng().gen_range(room.y1+1, room.y2);
if let Some(ref mut zombie_random) = actor_types.create_randomizer(
"zombie") {
let zombie_class = &mut zombie_random.get_class();
let mut zombie = zombie_class.create_object();
zombie.set_pos(x, y);
actors.push(zombie);
}
}
}
fn make_door(x: i32, y: i32, door_randomizer: &mut ObjectRandomizer,
map: &mut Map) {
let door_class = door_randomizer.get_class();
let mut door = door_class.create_object();
door.set_pos(x, y);
map[x as usize][y as usize].items[0] = door;
}
fn traverse_node(node: &mut Bsp, rooms: &mut Vec<Rect>,
object_types: &object::load::ObjectTypes,
floor_type: &ObjectClass,
mut map: &mut Map) -> bool {
if node.is_leaf() {
let minx = node.x + 1;
let mut maxx = node.x + node.w - 1;
let mut miny = node.y + 1;
let mut maxy = node.y + node.h - 1;
if maxx == FLOOR_WIDTH - 1 {
maxx -= 1;
}
if maxy == FLOOR_HEIGHT - 1 {
maxy -= 1;
}
node.x = minx;
node.y = miny;
node.w = maxx - minx + 1;
node.h = maxy - miny + 1;
create_room(node, floor_type, map);
rooms.push(Rect::new(node.x, node.y, node.w, node.h));
} else {
if let (Some(left), Some(right)) = (node.left(), node.right()) {
node.x = cmp::min(left.x, right.x);
node.y = cmp::min(left.y, right.y);
node.w = cmp::max(left.x + left.w, right.x + right.w) - node.x;
node.h = cmp::max(left.y + left.h, right.y + right.h) - node.y;
let ref mut door_randomizer = object_types.create_randomizer("door")
.unwrap();
if node.horizontal() {
make_door(left.x, cmp::max(left.y, right.y) - 1,
door_randomizer, &mut map);
} else {
make_door(cmp::max(left.x, right.x) - 1, left.y,
door_randomizer, &mut map);
}
}
}
true
}
pub fn make_map(mut actors: &mut Vec<Object>) -> Map {
let mut map = vec![];
let actor_types = object::load::load_objects(
"data/objects/actors.json").unwrap();
let item_types = object::load::load_objects(
"data/objects/items.json").unwrap();
let wall_class = item_types.get_class("brick wall");
let concrete_floor = item_types.get_class("concrete floor");
for x in 0..FLOOR_WIDTH {
map.push(vec![]);
for y in 0..FLOOR_HEIGHT {
let mut wall_tile: Tile = Tile::new(&concrete_floor);
let mut brick_wall = wall_class.create_object();
brick_wall.set_pos(x, y);
wall_tile.items.push(brick_wall);
map[x as usize].push(wall_tile);
}
}
let mut rooms = vec![];
let mut bsp = Bsp::new_with_size(0, 0, FLOOR_WIDTH, FLOOR_HEIGHT);
bsp.split_recursive(None, 3, ROOM_MIN_X, ROOM_MIN_Y, 1.25, 1.25);
bsp.traverse(TraverseOrder::InvertedLevelOrder, |node| {
traverse_node(node, &mut rooms, &item_types, &concrete_floor, &mut map)
});
place_objects(1, &rooms, &mut map, &item_types);
place_actors(1, &rooms, &mut map, &actor_types, &mut actors);
map
}
|
{
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all actors in the map location to see if they block
// If only one thing blocks fully we know nothing can see through that
// tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks_view);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks_view);
|
identifier_body
|
map.rs
|
use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const FLOOR_HEIGHT: i32 = 30;
pub const ROOM_MAX_SIZE: i32 = 10;
pub const ROOM_MIN_X: i32 = 8;
pub const ROOM_MIN_Y: i32 = 8;
pub const MAX_ROOMS: i32 = 30;
pub const MAX_ROOM_MONSTERS: i32 = 3;
pub const MAX_ROOM_ITEMS:i32 = 4;
#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct Tile {
pub floor: Object,
pub explored: bool,
pub items: Vec<Object>,
}
impl Tile {
pub fn new(floor: &ObjectClass) -> Self {
Tile{
floor: floor.create_object(),
explored: false,
items: vec![],}
}
}
pub fn is_blocked(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all objects in the map location to see if they block
// If only one thing blocks fully we know nothing new can move
// onto that tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub fn blocks_view(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all actors in the map location to see if they block
// If only one thing blocks fully we know nothing can see through that
// tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks_view);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks_view);
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub type Map = Vec<Vec<Tile>>;
#[derive(Clone, Copy, Debug)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
pub fn new(x: i32, y: i32, w: i32, h: i32)
-> Self {
Rect { x1: x, y1: y, x2: x + w, y2: y + h }
}
pub fn center(&self) -> (i32, i32) {
let center_x = (self.x1 + self.x2) / 2;
let center_y = (self.y1 + self.y2) / 2;
(center_x, center_y)
}
pub fn intersects_with(&self, other: &Rect) -> bool {
(self.x1 <= other.x2) && (self.x2 >= other.x1) &&
(self.y1 <= other.y2) && (self.y2 >= other.y1)
}
}
fn create_room(room: &mut Bsp, floor_class: &ObjectClass, map: &mut Map) {
for x in (room.x)..room.x + room.w {
for y in (room.y)..room.y + room.h {
map[x as usize][y as usize] = Tile::new(floor_class);
}
}
}
fn place_objects(floor: usize,
rooms: &Vec<Rect>, map: &mut Map,
items: &object::load::ObjectTypes) {
if floor == 1 {
let mut stairs = (0, 0);
for room in rooms {
let ref mut door_randomizer = items.create_randomizer("door").unwrap();
if room.x1 == 1 && room.y1 == 1 {
make_door(0, room.y2 / 2, door_randomizer, map);
} else if room.y2 == FLOOR_HEIGHT - 1 || room.x2 == FLOOR_WIDTH - 1 {
if stairs == (0, 0) || rand::random() {
let stairs_x = room.x1 + ((room.x2 - room.x1)/2);
let stairs_y = room.y1 + ((room.y2 - room.y1)/2);
stairs = (stairs_x, stairs_y);
}
}
}
let (stairs_x, stairs_y) = stairs;
let mut stairs_up = items.get_class("stairs up").create_object();
stairs_up.set_pos(stairs_x, stairs_y);
map[stairs_x as usize][stairs_y as usize].items.push(stairs_up);
}
for _ in 0..rand::thread_rng().gen_range(1,3) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let brick_x = room.x1 + 1;
let brick_y = room.y1 + 2;
if let Some(ref mut brick_random) = items.create_randomizer(
"environmental weapon") {
let brick_class = &mut brick_random.get_class();
let mut brick = brick_class.create_object();
brick.set_pos(brick_x, brick_y);
map[brick_x as usize][brick_y as usize].items.push(brick);
};
}
}
fn place_actors(floor: usize, rooms: &Vec<Rect>, map: &mut Map,
|
actors[consts::PLAYER].set_pos(1, room.y2 / 2);
}
}
for _ in 0..rand::thread_rng().gen_range(1,2) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let x = rand::thread_rng().gen_range(room.x1+1, room.x2);
let y = rand::thread_rng().gen_range(room.y1+1, room.y2);
if let Some(ref mut zombie_random) = actor_types.create_randomizer(
"zombie") {
let zombie_class = &mut zombie_random.get_class();
let mut zombie = zombie_class.create_object();
zombie.set_pos(x, y);
actors.push(zombie);
}
}
}
fn make_door(x: i32, y: i32, door_randomizer: &mut ObjectRandomizer,
map: &mut Map) {
let door_class = door_randomizer.get_class();
let mut door = door_class.create_object();
door.set_pos(x, y);
map[x as usize][y as usize].items[0] = door;
}
fn traverse_node(node: &mut Bsp, rooms: &mut Vec<Rect>,
object_types: &object::load::ObjectTypes,
floor_type: &ObjectClass,
mut map: &mut Map) -> bool {
if node.is_leaf() {
let minx = node.x + 1;
let mut maxx = node.x + node.w - 1;
let mut miny = node.y + 1;
let mut maxy = node.y + node.h - 1;
if maxx == FLOOR_WIDTH - 1 {
maxx -= 1;
}
if maxy == FLOOR_HEIGHT - 1 {
maxy -= 1;
}
node.x = minx;
node.y = miny;
node.w = maxx - minx + 1;
node.h = maxy - miny + 1;
create_room(node, floor_type, map);
rooms.push(Rect::new(node.x, node.y, node.w, node.h));
} else {
if let (Some(left), Some(right)) = (node.left(), node.right()) {
node.x = cmp::min(left.x, right.x);
node.y = cmp::min(left.y, right.y);
node.w = cmp::max(left.x + left.w, right.x + right.w) - node.x;
node.h = cmp::max(left.y + left.h, right.y + right.h) - node.y;
let ref mut door_randomizer = object_types.create_randomizer("door")
.unwrap();
if node.horizontal() {
make_door(left.x, cmp::max(left.y, right.y) - 1,
door_randomizer, &mut map);
} else {
make_door(cmp::max(left.x, right.x) - 1, left.y,
door_randomizer, &mut map);
}
}
}
true
}
pub fn make_map(mut actors: &mut Vec<Object>) -> Map {
let mut map = vec![];
let actor_types = object::load::load_objects(
"data/objects/actors.json").unwrap();
let item_types = object::load::load_objects(
"data/objects/items.json").unwrap();
let wall_class = item_types.get_class("brick wall");
let concrete_floor = item_types.get_class("concrete floor");
for x in 0..FLOOR_WIDTH {
map.push(vec![]);
for y in 0..FLOOR_HEIGHT {
let mut wall_tile: Tile = Tile::new(&concrete_floor);
let mut brick_wall = wall_class.create_object();
brick_wall.set_pos(x, y);
wall_tile.items.push(brick_wall);
map[x as usize].push(wall_tile);
}
}
let mut rooms = vec![];
let mut bsp = Bsp::new_with_size(0, 0, FLOOR_WIDTH, FLOOR_HEIGHT);
bsp.split_recursive(None, 3, ROOM_MIN_X, ROOM_MIN_Y, 1.25, 1.25);
bsp.traverse(TraverseOrder::InvertedLevelOrder, |node| {
traverse_node(node, &mut rooms, &item_types, &concrete_floor, &mut map)
});
place_objects(1, &rooms, &mut map, &item_types);
place_actors(1, &rooms, &mut map, &actor_types, &mut actors);
map
}
|
actor_types: &object::load::ObjectTypes,
actors: &mut Vec<Object>) {
for room in rooms {
if room.x1 == 1 && room.y1 == 1 {
|
random_line_split
|
map.rs
|
use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const FLOOR_HEIGHT: i32 = 30;
pub const ROOM_MAX_SIZE: i32 = 10;
pub const ROOM_MIN_X: i32 = 8;
pub const ROOM_MIN_Y: i32 = 8;
pub const MAX_ROOMS: i32 = 30;
pub const MAX_ROOM_MONSTERS: i32 = 3;
pub const MAX_ROOM_ITEMS:i32 = 4;
#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct Tile {
pub floor: Object,
pub explored: bool,
pub items: Vec<Object>,
}
impl Tile {
pub fn new(floor: &ObjectClass) -> Self {
Tile{
floor: floor.create_object(),
explored: false,
items: vec![],}
}
}
pub fn
|
(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all objects in the map location to see if they block
// If only one thing blocks fully we know nothing new can move
// onto that tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks);
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub fn blocks_view(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all actors in the map location to see if they block
// If only one thing blocks fully we know nothing can see through that
// tile, so we are done. If something only partially blocks, we
// have to keep checking in case there is something fully blocking.
let mut blocks = object::Blocks::No;
for actor in actors {
if actor.x == x && actor.y == y {
blocks = cmp::max(blocks, actor.blocks_view);
if blocks == object::Blocks::Full {
return blocks
}
}
}
for item in &map[x as usize][y as usize].items {
blocks = cmp::max(blocks, item.blocks_view);
if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub type Map = Vec<Vec<Tile>>;
#[derive(Clone, Copy, Debug)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
pub fn new(x: i32, y: i32, w: i32, h: i32)
-> Self {
Rect { x1: x, y1: y, x2: x + w, y2: y + h }
}
pub fn center(&self) -> (i32, i32) {
let center_x = (self.x1 + self.x2) / 2;
let center_y = (self.y1 + self.y2) / 2;
(center_x, center_y)
}
pub fn intersects_with(&self, other: &Rect) -> bool {
(self.x1 <= other.x2) && (self.x2 >= other.x1) &&
(self.y1 <= other.y2) && (self.y2 >= other.y1)
}
}
fn create_room(room: &mut Bsp, floor_class: &ObjectClass, map: &mut Map) {
for x in (room.x)..room.x + room.w {
for y in (room.y)..room.y + room.h {
map[x as usize][y as usize] = Tile::new(floor_class);
}
}
}
fn place_objects(floor: usize,
rooms: &Vec<Rect>, map: &mut Map,
items: &object::load::ObjectTypes) {
if floor == 1 {
let mut stairs = (0, 0);
for room in rooms {
let ref mut door_randomizer = items.create_randomizer("door").unwrap();
if room.x1 == 1 && room.y1 == 1 {
make_door(0, room.y2 / 2, door_randomizer, map);
} else if room.y2 == FLOOR_HEIGHT - 1 || room.x2 == FLOOR_WIDTH - 1 {
if stairs == (0, 0) || rand::random() {
let stairs_x = room.x1 + ((room.x2 - room.x1)/2);
let stairs_y = room.y1 + ((room.y2 - room.y1)/2);
stairs = (stairs_x, stairs_y);
}
}
}
let (stairs_x, stairs_y) = stairs;
let mut stairs_up = items.get_class("stairs up").create_object();
stairs_up.set_pos(stairs_x, stairs_y);
map[stairs_x as usize][stairs_y as usize].items.push(stairs_up);
}
for _ in 0..rand::thread_rng().gen_range(1,3) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let brick_x = room.x1 + 1;
let brick_y = room.y1 + 2;
if let Some(ref mut brick_random) = items.create_randomizer(
"environmental weapon") {
let brick_class = &mut brick_random.get_class();
let mut brick = brick_class.create_object();
brick.set_pos(brick_x, brick_y);
map[brick_x as usize][brick_y as usize].items.push(brick);
};
}
}
fn place_actors(floor: usize, rooms: &Vec<Rect>, map: &mut Map,
actor_types: &object::load::ObjectTypes,
actors: &mut Vec<Object>) {
for room in rooms {
if room.x1 == 1 && room.y1 == 1 {
actors[consts::PLAYER].set_pos(1, room.y2 / 2);
}
}
for _ in 0..rand::thread_rng().gen_range(1,2) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let x = rand::thread_rng().gen_range(room.x1+1, room.x2);
let y = rand::thread_rng().gen_range(room.y1+1, room.y2);
if let Some(ref mut zombie_random) = actor_types.create_randomizer(
"zombie") {
let zombie_class = &mut zombie_random.get_class();
let mut zombie = zombie_class.create_object();
zombie.set_pos(x, y);
actors.push(zombie);
}
}
}
fn make_door(x: i32, y: i32, door_randomizer: &mut ObjectRandomizer,
map: &mut Map) {
let door_class = door_randomizer.get_class();
let mut door = door_class.create_object();
door.set_pos(x, y);
map[x as usize][y as usize].items[0] = door;
}
fn traverse_node(node: &mut Bsp, rooms: &mut Vec<Rect>,
object_types: &object::load::ObjectTypes,
floor_type: &ObjectClass,
mut map: &mut Map) -> bool {
if node.is_leaf() {
let minx = node.x + 1;
let mut maxx = node.x + node.w - 1;
let mut miny = node.y + 1;
let mut maxy = node.y + node.h - 1;
if maxx == FLOOR_WIDTH - 1 {
maxx -= 1;
}
if maxy == FLOOR_HEIGHT - 1 {
maxy -= 1;
}
node.x = minx;
node.y = miny;
node.w = maxx - minx + 1;
node.h = maxy - miny + 1;
create_room(node, floor_type, map);
rooms.push(Rect::new(node.x, node.y, node.w, node.h));
} else {
if let (Some(left), Some(right)) = (node.left(), node.right()) {
node.x = cmp::min(left.x, right.x);
node.y = cmp::min(left.y, right.y);
node.w = cmp::max(left.x + left.w, right.x + right.w) - node.x;
node.h = cmp::max(left.y + left.h, right.y + right.h) - node.y;
let ref mut door_randomizer = object_types.create_randomizer("door")
.unwrap();
if node.horizontal() {
make_door(left.x, cmp::max(left.y, right.y) - 1,
door_randomizer, &mut map);
} else {
make_door(cmp::max(left.x, right.x) - 1, left.y,
door_randomizer, &mut map);
}
}
}
true
}
pub fn make_map(mut actors: &mut Vec<Object>) -> Map {
let mut map = vec![];
let actor_types = object::load::load_objects(
"data/objects/actors.json").unwrap();
let item_types = object::load::load_objects(
"data/objects/items.json").unwrap();
let wall_class = item_types.get_class("brick wall");
let concrete_floor = item_types.get_class("concrete floor");
for x in 0..FLOOR_WIDTH {
map.push(vec![]);
for y in 0..FLOOR_HEIGHT {
let mut wall_tile: Tile = Tile::new(&concrete_floor);
let mut brick_wall = wall_class.create_object();
brick_wall.set_pos(x, y);
wall_tile.items.push(brick_wall);
map[x as usize].push(wall_tile);
}
}
let mut rooms = vec![];
let mut bsp = Bsp::new_with_size(0, 0, FLOOR_WIDTH, FLOOR_HEIGHT);
bsp.split_recursive(None, 3, ROOM_MIN_X, ROOM_MIN_Y, 1.25, 1.25);
bsp.traverse(TraverseOrder::InvertedLevelOrder, |node| {
traverse_node(node, &mut rooms, &item_types, &concrete_floor, &mut map)
});
place_objects(1, &rooms, &mut map, &item_types);
place_actors(1, &rooms, &mut map, &actor_types, &mut actors);
map
}
|
is_blocked
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.