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 |
---|---|---|---|---|
computations.rs
|
// Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
use energy::{Potential, PairPotential};
/// Alternative energy and forces computation.
///
/// The `Computation` trait represent an alternative way to compute a given
/// potential. For example using interpolation on a table or on a grid, from a
/// Fourier decomposition, *etc.*
///
/// # Examples
///
/// ```
/// # use lumol::energy::Potential;
/// use lumol::energy::Computation;
/// use lumol::energy::Harmonic;
///
/// /// This is just a thin wrapper logging every time the `energy/force`
/// /// methods are called.
/// #[derive(Clone)]
/// struct LoggingComputation<T: Potential>(T);
///
/// impl<T: Potential> Computation for LoggingComputation<T> {
/// fn compute_energy(&self, r: f64) -> f64 {
/// println!("Called energy");
/// self.0.energy(r)
/// }
///
/// fn compute_force(&self, r: f64) -> f64 {
/// println!("Called force");
/// self.0.force(r)
/// }
/// }
///
/// let potential = Harmonic{x0: 0.5, k: 4.2};
/// let computation = LoggingComputation(potential.clone());
///
/// assert_eq!(computation.energy(1.0), potential.energy(1.0));
/// assert_eq!(computation.force(2.0), potential.force(2.0));
/// ```
pub trait Computation: Sync + Send {
/// Compute the energy value at `r`
fn compute_energy(&self, r: f64) -> f64;
/// Compute the force value at `r`
fn compute_force(&self, r: f64) -> f64;
}
impl<P: Computation + Clone +'static> Potential for P {
#[inline] fn energy(&self, r:f64) -> f64 {
self.compute_energy(r)
}
#[inline] fn force(&self, r:f64) -> f64 {
self.compute_force(r)
}
}
/// Computation of a potential using tabulated values.
///
/// This can be faster than direct computation for smooth potentials, but will
/// uses more memory and be less precise than direct computation. Values are
/// tabulated in the `[0, max)` range, and a cutoff is applied after `max`.
#[derive(Clone)]
pub struct TableComputation {
/// Step for tabulated value. `energy_table[i]`/`force_table[i]` contains
/// energy/force at `r = i * delta`
delta: f64,
/// Cutoff distance
cutoff: f64,
/// Tabulated potential
energy_table: Vec<f64>,
/// Tabulated compute_force
force_table: Vec<f64>,
/// Initial potential, kept around for tail corrections
potential: Box<PairPotential>,
}
impl TableComputation {
/// Create a new `TableComputation` for `potential`, with `size` points and
/// a maximum value of `max`.
///
/// # Examples
///
/// ```
/// # use lumol::energy::Potential;
/// use lumol::energy::TableComputation;
/// use lumol::energy::Harmonic;
///
/// let potential = Box::new(Harmonic{x0: 0.5, k: 4.2});
/// let table = TableComputation::new(potential, 1000, 2.0);
///
/// assert_eq!(table.energy(1.0), 0.525);
/// assert_eq!(table.energy(3.0), 0.0);
/// ```
pub fn new(potential: Box<PairPotential>, size: usize, max: f64) -> TableComputation {
let delta = max / (size as f64);
let mut energy_table = Vec::with_capacity(size);
let mut force_table = Vec::with_capacity(size);
for i in 0..size {
let r = i as f64 * delta;
energy_table.push(potential.energy(r));
force_table.push(potential.force(r));
}
TableComputation {
delta: delta,
cutoff: max,
energy_table: energy_table,
force_table: force_table,
potential: potential,
}
}
}
impl Computation for TableComputation {
fn compute_energy(&self, r: f64) -> f64 {
debug_assert_eq!(self.energy_table.len(), self.force_table.len());
let bin = f64::floor(r / self.delta) as usize;
if bin < self.energy_table.len() - 1 {
let dx = r - (bin as f64) * self.delta;
let slope = (self.energy_table[bin + 1] - self.energy_table[bin]) / self.delta;
return self.energy_table[bin] + dx * slope;
} else {
return 0.0;
}
}
fn compute_force(&self, r: f64) -> f64 {
debug_assert_eq!(self.energy_table.len(), self.force_table.len());
let bin = f64::floor(r / self.delta) as usize;
if bin < self.force_table.len() - 1 {
let dx = r - (bin as f64) * self.delta;
let slope = (self.force_table[bin + 1] - self.force_table[bin]) / self.delta;
return self.force_table[bin] + dx * slope;
} else {
return 0.0;
}
}
}
impl PairPotential for TableComputation {
fn tail_energy(&self, cutoff: f64) -> f64 {
if cutoff > self.cutoff {
warn_once!("Cutoff in table computation ({}) is smaller than the \
pair interaction cutoff ({}) when computing tail correction. This \
may lead to wrong values for energy.", cutoff, self.cutoff);
}
return self.potential.tail_energy(cutoff);
}
fn tail_virial(&self, cutoff: f64) -> f64 {
if cutoff > self.cutoff {
warn_once!("Cutoff in table computation ({}) is smaller than the \
pair interaction cutoff ({}) when computing tail correction. This \
may lead to wrong values for pressure.", cutoff, self.cutoff);
}
return self.potential.tail_virial(cutoff);
}
}
#[cfg(test)]
mod test {
use super::*;
use energy::{Harmonic, LennardJones};
use energy::PairPotential;
#[test]
fn table() {
|
assert_eq!(table.compute_energy(2.5), 6.25);
assert_eq!(table.compute_force(2.5), -25.0);
// Check that the table is defined up to the cutoff value
let delta = 4.0 / 1000.0;
assert_eq!(table.compute_energy(4.0 - 2.0 * delta), 99.2016);
assert_eq!(table.compute_force(4.0 - 2.0 * delta), -99.6);
assert_eq!(table.compute_energy(4.0 - delta), 0.0);
assert_eq!(table.compute_force(4.0 - delta), 0.0);
assert_eq!(table.compute_energy(4.0), 0.0);
assert_eq!(table.compute_force(4.0), 0.0);
assert_eq!(table.compute_energy(4.1), 0.0);
assert_eq!(table.compute_force(4.1), 0.0);
let lj = LennardJones{epsilon: 50.0, sigma: 2.0};
let table = TableComputation::new(Box::new(lj.clone()), 1000, 4.0);
assert_eq!(table.tail_energy(5.0), lj.tail_energy(5.0));
assert_eq!(table.tail_virial(5.0), lj.tail_virial(5.0));
}
}
|
let table = TableComputation::new(
Box::new(Harmonic{k: 50.0, x0: 2.0}), 1000, 4.0
);
|
random_line_split
|
computations.rs
|
// Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
use energy::{Potential, PairPotential};
/// Alternative energy and forces computation.
///
/// The `Computation` trait represent an alternative way to compute a given
/// potential. For example using interpolation on a table or on a grid, from a
/// Fourier decomposition, *etc.*
///
/// # Examples
///
/// ```
/// # use lumol::energy::Potential;
/// use lumol::energy::Computation;
/// use lumol::energy::Harmonic;
///
/// /// This is just a thin wrapper logging every time the `energy/force`
/// /// methods are called.
/// #[derive(Clone)]
/// struct LoggingComputation<T: Potential>(T);
///
/// impl<T: Potential> Computation for LoggingComputation<T> {
/// fn compute_energy(&self, r: f64) -> f64 {
/// println!("Called energy");
/// self.0.energy(r)
/// }
///
/// fn compute_force(&self, r: f64) -> f64 {
/// println!("Called force");
/// self.0.force(r)
/// }
/// }
///
/// let potential = Harmonic{x0: 0.5, k: 4.2};
/// let computation = LoggingComputation(potential.clone());
///
/// assert_eq!(computation.energy(1.0), potential.energy(1.0));
/// assert_eq!(computation.force(2.0), potential.force(2.0));
/// ```
pub trait Computation: Sync + Send {
/// Compute the energy value at `r`
fn compute_energy(&self, r: f64) -> f64;
/// Compute the force value at `r`
fn compute_force(&self, r: f64) -> f64;
}
impl<P: Computation + Clone +'static> Potential for P {
#[inline] fn energy(&self, r:f64) -> f64 {
self.compute_energy(r)
}
#[inline] fn force(&self, r:f64) -> f64 {
self.compute_force(r)
}
}
/// Computation of a potential using tabulated values.
///
/// This can be faster than direct computation for smooth potentials, but will
/// uses more memory and be less precise than direct computation. Values are
/// tabulated in the `[0, max)` range, and a cutoff is applied after `max`.
#[derive(Clone)]
pub struct TableComputation {
/// Step for tabulated value. `energy_table[i]`/`force_table[i]` contains
/// energy/force at `r = i * delta`
delta: f64,
/// Cutoff distance
cutoff: f64,
/// Tabulated potential
energy_table: Vec<f64>,
/// Tabulated compute_force
force_table: Vec<f64>,
/// Initial potential, kept around for tail corrections
potential: Box<PairPotential>,
}
impl TableComputation {
/// Create a new `TableComputation` for `potential`, with `size` points and
/// a maximum value of `max`.
///
/// # Examples
///
/// ```
/// # use lumol::energy::Potential;
/// use lumol::energy::TableComputation;
/// use lumol::energy::Harmonic;
///
/// let potential = Box::new(Harmonic{x0: 0.5, k: 4.2});
/// let table = TableComputation::new(potential, 1000, 2.0);
///
/// assert_eq!(table.energy(1.0), 0.525);
/// assert_eq!(table.energy(3.0), 0.0);
/// ```
pub fn new(potential: Box<PairPotential>, size: usize, max: f64) -> TableComputation {
let delta = max / (size as f64);
let mut energy_table = Vec::with_capacity(size);
let mut force_table = Vec::with_capacity(size);
for i in 0..size {
let r = i as f64 * delta;
energy_table.push(potential.energy(r));
force_table.push(potential.force(r));
}
TableComputation {
delta: delta,
cutoff: max,
energy_table: energy_table,
force_table: force_table,
potential: potential,
}
}
}
impl Computation for TableComputation {
fn compute_energy(&self, r: f64) -> f64 {
debug_assert_eq!(self.energy_table.len(), self.force_table.len());
let bin = f64::floor(r / self.delta) as usize;
if bin < self.energy_table.len() - 1 {
let dx = r - (bin as f64) * self.delta;
let slope = (self.energy_table[bin + 1] - self.energy_table[bin]) / self.delta;
return self.energy_table[bin] + dx * slope;
} else {
|
}
fn compute_force(&self, r: f64) -> f64 {
debug_assert_eq!(self.energy_table.len(), self.force_table.len());
let bin = f64::floor(r / self.delta) as usize;
if bin < self.force_table.len() - 1 {
let dx = r - (bin as f64) * self.delta;
let slope = (self.force_table[bin + 1] - self.force_table[bin]) / self.delta;
return self.force_table[bin] + dx * slope;
} else {
return 0.0;
}
}
}
impl PairPotential for TableComputation {
fn tail_energy(&self, cutoff: f64) -> f64 {
if cutoff > self.cutoff {
warn_once!("Cutoff in table computation ({}) is smaller than the \
pair interaction cutoff ({}) when computing tail correction. This \
may lead to wrong values for energy.", cutoff, self.cutoff);
}
return self.potential.tail_energy(cutoff);
}
fn tail_virial(&self, cutoff: f64) -> f64 {
if cutoff > self.cutoff {
warn_once!("Cutoff in table computation ({}) is smaller than the \
pair interaction cutoff ({}) when computing tail correction. This \
may lead to wrong values for pressure.", cutoff, self.cutoff);
}
return self.potential.tail_virial(cutoff);
}
}
#[cfg(test)]
mod test {
use super::*;
use energy::{Harmonic, LennardJones};
use energy::PairPotential;
#[test]
fn table() {
let table = TableComputation::new(
Box::new(Harmonic{k: 50.0, x0: 2.0}), 1000, 4.0
);
assert_eq!(table.compute_energy(2.5), 6.25);
assert_eq!(table.compute_force(2.5), -25.0);
// Check that the table is defined up to the cutoff value
let delta = 4.0 / 1000.0;
assert_eq!(table.compute_energy(4.0 - 2.0 * delta), 99.2016);
assert_eq!(table.compute_force(4.0 - 2.0 * delta), -99.6);
assert_eq!(table.compute_energy(4.0 - delta), 0.0);
assert_eq!(table.compute_force(4.0 - delta), 0.0);
assert_eq!(table.compute_energy(4.0), 0.0);
assert_eq!(table.compute_force(4.0), 0.0);
assert_eq!(table.compute_energy(4.1), 0.0);
assert_eq!(table.compute_force(4.1), 0.0);
let lj = LennardJones{epsilon: 50.0, sigma: 2.0};
let table = TableComputation::new(Box::new(lj.clone()), 1000, 4.0);
assert_eq!(table.tail_energy(5.0), lj.tail_energy(5.0));
assert_eq!(table.tail_virial(5.0), lj.tail_virial(5.0));
}
}
|
return 0.0;
}
|
conditional_block
|
packed-struct-generic-layout.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
use std::cast;
#[packed]
struct S<T, S> {
a: T,
b: u8,
c: S
}
fn main() {
unsafe {
let s = S { a: 0xff_ff_ff_ffu32, b: 1, c: 0xaa_aa_aa_aa as i32 };
let transd : [u8,.. 9] = cast::transmute(s);
// Don't worry about endianness, the numbers are palindromic.
assert_eq!(transd,
[0xff, 0xff, 0xff, 0xff,
1,
0xaa, 0xaa, 0xaa, 0xaa]);
let s = S { a: 1u8, b: 2u8, c: 0b10000001_10000001 as i16};
let transd : [u8,.. 4] = cast::transmute(s);
// Again, no endianness problems.
assert_eq!(transd,
[1, 2, 0b10000001, 0b10000001]);
}
}
|
random_line_split
|
|
packed-struct-generic-layout.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
#[packed]
struct
|
<T, S> {
a: T,
b: u8,
c: S
}
fn main() {
unsafe {
let s = S { a: 0xff_ff_ff_ffu32, b: 1, c: 0xaa_aa_aa_aa as i32 };
let transd : [u8,.. 9] = cast::transmute(s);
// Don't worry about endianness, the numbers are palindromic.
assert_eq!(transd,
[0xff, 0xff, 0xff, 0xff,
1,
0xaa, 0xaa, 0xaa, 0xaa]);
let s = S { a: 1u8, b: 2u8, c: 0b10000001_10000001 as i16};
let transd : [u8,.. 4] = cast::transmute(s);
// Again, no endianness problems.
assert_eq!(transd,
[1, 2, 0b10000001, 0b10000001]);
}
}
|
S
|
identifier_name
|
packed-struct-generic-layout.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
#[packed]
struct S<T, S> {
a: T,
b: u8,
c: S
}
fn main()
|
{
unsafe {
let s = S { a: 0xff_ff_ff_ffu32, b: 1, c: 0xaa_aa_aa_aa as i32 };
let transd : [u8, .. 9] = cast::transmute(s);
// Don't worry about endianness, the numbers are palindromic.
assert_eq!(transd,
[0xff, 0xff, 0xff, 0xff,
1,
0xaa, 0xaa, 0xaa, 0xaa]);
let s = S { a: 1u8, b: 2u8, c: 0b10000001_10000001 as i16};
let transd : [u8, .. 4] = cast::transmute(s);
// Again, no endianness problems.
assert_eq!(transd,
[1, 2, 0b10000001, 0b10000001]);
}
}
|
identifier_body
|
|
stores.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Address Book and Dapps Settings Store
use std::{fs, fmt, hash, ops};
use std::collections::HashMap;
use std::path::PathBuf;
use ethstore::ethkey::Address;
use ethjson::misc::{AccountMeta, DappsSettings as JsonSettings};
use account_provider::DappId;
/// Disk-backed map from Address to String. Uses JSON.
pub struct AddressBook {
cache: DiskMap<Address, AccountMeta>,
}
impl AddressBook {
/// Creates new address book at given directory.
pub fn new(path: String) -> Self {
let mut r = AddressBook {
cache: DiskMap::new(path, "address_book.json".into())
};
r.cache.revert(AccountMeta::read_address_map);
r
}
/// Creates transient address book (no changes are saved to disk).
pub fn transient() -> Self {
AddressBook {
cache: DiskMap::transient()
}
}
/// Get the address book.
pub fn get(&self) -> HashMap<Address, AccountMeta> {
self.cache.clone()
}
fn save(&self) {
self.cache.save(AccountMeta::write_address_map)
}
/// Sets new name for given address.
pub fn set_name(&mut self, a: Address, name: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: Default::default(), meta: "{}".to_owned(), uuid: None});
x.name = name;
}
self.save();
}
/// Sets new meta for given address.
pub fn set_meta(&mut self, a: Address, meta: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: "Anonymous".to_owned(), meta: Default::default(), uuid: None});
x.meta = meta;
}
self.save();
}
/// Removes an entry
pub fn remove(&mut self, a: Address) {
self.cache.remove(&a);
self.save();
}
}
/// Dapps user settings
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct DappsSettings {
/// A list of visible accounts
pub accounts: Vec<Address>,
}
impl From<JsonSettings> for DappsSettings {
fn from(s: JsonSettings) -> Self {
DappsSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
impl From<DappsSettings> for JsonSettings {
fn from(s: DappsSettings) -> Self {
JsonSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
/// Disk-backed map from DappId to Settings. Uses JSON.
pub struct DappsSettingsStore {
cache: DiskMap<DappId, DappsSettings>,
}
impl DappsSettingsStore {
/// Creates new store at given directory path.
pub fn new(path: String) -> Self {
let mut r = DappsSettingsStore {
cache: DiskMap::new(path, "dapps_accounts.json".into())
};
r.cache.revert(JsonSettings::read_dapps_settings);
r
}
/// Creates transient store (no changes are saved to disk).
pub fn transient() -> Self {
DappsSettingsStore {
cache: DiskMap::transient()
}
}
/// Get copy of the dapps settings
pub fn get(&self) -> HashMap<DappId, DappsSettings> {
self.cache.clone()
}
fn save(&self) {
self.cache.save(JsonSettings::write_dapps_settings)
}
pub fn set_accounts(&mut self, id: DappId, accounts: Vec<Address>) {
{
let mut settings = self.cache.entry(id).or_insert_with(DappsSettings::default);
settings.accounts = accounts;
}
self.save();
}
|
/// Disk-serializable HashMap
#[derive(Debug)]
struct DiskMap<K: hash::Hash + Eq, V> {
path: PathBuf,
cache: HashMap<K, V>,
transient: bool,
}
impl<K: hash::Hash + Eq, V> ops::Deref for DiskMap<K, V> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.cache
}
}
impl<K: hash::Hash + Eq, V> ops::DerefMut for DiskMap<K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cache
}
}
impl<K: hash::Hash + Eq, V> DiskMap<K, V> {
pub fn new(path: String, file_name: String) -> Self {
trace!(target: "diskmap", "new({})", path);
let mut path: PathBuf = path.into();
path.push(file_name);
trace!(target: "diskmap", "path={:?}", path);
DiskMap {
path: path,
cache: HashMap::new(),
transient: false,
}
}
pub fn transient() -> Self {
let mut map = DiskMap::new(Default::default(), "diskmap.json".into());
map.transient = true;
map
}
fn revert<F, E>(&mut self, read: F) where
F: Fn(fs::File) -> Result<HashMap<K, V>, E>,
E: fmt::Display,
{
if self.transient { return; }
trace!(target: "diskmap", "revert {:?}", self.path);
let _ = fs::File::open(self.path.clone())
.map_err(|e| trace!(target: "diskmap", "Couldn't open disk map: {}", e))
.and_then(|f| read(f).map_err(|e| warn!(target: "diskmap", "Couldn't read disk map: {}", e)))
.and_then(|m| {
self.cache = m;
Ok(())
});
}
fn save<F, E>(&self, write: F) where
F: Fn(&HashMap<K, V>, &mut fs::File) -> Result<(), E>,
E: fmt::Display,
{
if self.transient { return; }
trace!(target: "diskmap", "save {:?}", self.path);
let _ = fs::File::create(self.path.clone())
.map_err(|e| warn!(target: "diskmap", "Couldn't open disk map for writing: {}", e))
.and_then(|mut f| {
write(&self.cache, &mut f).map_err(|e| warn!(target: "diskmap", "Couldn't write to disk map: {}", e))
});
}
}
#[cfg(test)]
mod tests {
use super::{AddressBook, DappsSettingsStore, DappsSettings};
use std::collections::HashMap;
use ethjson::misc::AccountMeta;
use devtools::RandomTempPath;
#[test]
fn should_save_and_reload_address_book() {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_meta(1.into(), "{1:1}".to_owned());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![1.into() => AccountMeta{name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None}]);
}
#[test]
fn should_save_and_reload_dapps_settings() {
// given
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = DappsSettingsStore::new(path.clone());
// when
b.set_accounts("dappOne".into(), vec![1.into(), 2.into()]);
// then
let b = DappsSettingsStore::new(path);
assert_eq!(b.get(), hash_map![
"dappOne".into() => DappsSettings {
accounts: vec![1.into(), 2.into()],
}
]);
}
#[test]
fn should_remove_address() {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_name(2.into(), "Two".to_owned());
b.set_name(3.into(), "Three".to_owned());
b.remove(2.into());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![
1.into() => AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None},
3.into() => AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}
]);
}
}
|
}
|
random_line_split
|
stores.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Address Book and Dapps Settings Store
use std::{fs, fmt, hash, ops};
use std::collections::HashMap;
use std::path::PathBuf;
use ethstore::ethkey::Address;
use ethjson::misc::{AccountMeta, DappsSettings as JsonSettings};
use account_provider::DappId;
/// Disk-backed map from Address to String. Uses JSON.
pub struct AddressBook {
cache: DiskMap<Address, AccountMeta>,
}
impl AddressBook {
/// Creates new address book at given directory.
pub fn new(path: String) -> Self {
let mut r = AddressBook {
cache: DiskMap::new(path, "address_book.json".into())
};
r.cache.revert(AccountMeta::read_address_map);
r
}
/// Creates transient address book (no changes are saved to disk).
pub fn transient() -> Self {
AddressBook {
cache: DiskMap::transient()
}
}
/// Get the address book.
pub fn get(&self) -> HashMap<Address, AccountMeta> {
self.cache.clone()
}
fn
|
(&self) {
self.cache.save(AccountMeta::write_address_map)
}
/// Sets new name for given address.
pub fn set_name(&mut self, a: Address, name: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: Default::default(), meta: "{}".to_owned(), uuid: None});
x.name = name;
}
self.save();
}
/// Sets new meta for given address.
pub fn set_meta(&mut self, a: Address, meta: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: "Anonymous".to_owned(), meta: Default::default(), uuid: None});
x.meta = meta;
}
self.save();
}
/// Removes an entry
pub fn remove(&mut self, a: Address) {
self.cache.remove(&a);
self.save();
}
}
/// Dapps user settings
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct DappsSettings {
/// A list of visible accounts
pub accounts: Vec<Address>,
}
impl From<JsonSettings> for DappsSettings {
fn from(s: JsonSettings) -> Self {
DappsSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
impl From<DappsSettings> for JsonSettings {
fn from(s: DappsSettings) -> Self {
JsonSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
/// Disk-backed map from DappId to Settings. Uses JSON.
pub struct DappsSettingsStore {
cache: DiskMap<DappId, DappsSettings>,
}
impl DappsSettingsStore {
/// Creates new store at given directory path.
pub fn new(path: String) -> Self {
let mut r = DappsSettingsStore {
cache: DiskMap::new(path, "dapps_accounts.json".into())
};
r.cache.revert(JsonSettings::read_dapps_settings);
r
}
/// Creates transient store (no changes are saved to disk).
pub fn transient() -> Self {
DappsSettingsStore {
cache: DiskMap::transient()
}
}
/// Get copy of the dapps settings
pub fn get(&self) -> HashMap<DappId, DappsSettings> {
self.cache.clone()
}
fn save(&self) {
self.cache.save(JsonSettings::write_dapps_settings)
}
pub fn set_accounts(&mut self, id: DappId, accounts: Vec<Address>) {
{
let mut settings = self.cache.entry(id).or_insert_with(DappsSettings::default);
settings.accounts = accounts;
}
self.save();
}
}
/// Disk-serializable HashMap
#[derive(Debug)]
struct DiskMap<K: hash::Hash + Eq, V> {
path: PathBuf,
cache: HashMap<K, V>,
transient: bool,
}
impl<K: hash::Hash + Eq, V> ops::Deref for DiskMap<K, V> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.cache
}
}
impl<K: hash::Hash + Eq, V> ops::DerefMut for DiskMap<K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cache
}
}
impl<K: hash::Hash + Eq, V> DiskMap<K, V> {
pub fn new(path: String, file_name: String) -> Self {
trace!(target: "diskmap", "new({})", path);
let mut path: PathBuf = path.into();
path.push(file_name);
trace!(target: "diskmap", "path={:?}", path);
DiskMap {
path: path,
cache: HashMap::new(),
transient: false,
}
}
pub fn transient() -> Self {
let mut map = DiskMap::new(Default::default(), "diskmap.json".into());
map.transient = true;
map
}
fn revert<F, E>(&mut self, read: F) where
F: Fn(fs::File) -> Result<HashMap<K, V>, E>,
E: fmt::Display,
{
if self.transient { return; }
trace!(target: "diskmap", "revert {:?}", self.path);
let _ = fs::File::open(self.path.clone())
.map_err(|e| trace!(target: "diskmap", "Couldn't open disk map: {}", e))
.and_then(|f| read(f).map_err(|e| warn!(target: "diskmap", "Couldn't read disk map: {}", e)))
.and_then(|m| {
self.cache = m;
Ok(())
});
}
fn save<F, E>(&self, write: F) where
F: Fn(&HashMap<K, V>, &mut fs::File) -> Result<(), E>,
E: fmt::Display,
{
if self.transient { return; }
trace!(target: "diskmap", "save {:?}", self.path);
let _ = fs::File::create(self.path.clone())
.map_err(|e| warn!(target: "diskmap", "Couldn't open disk map for writing: {}", e))
.and_then(|mut f| {
write(&self.cache, &mut f).map_err(|e| warn!(target: "diskmap", "Couldn't write to disk map: {}", e))
});
}
}
#[cfg(test)]
mod tests {
use super::{AddressBook, DappsSettingsStore, DappsSettings};
use std::collections::HashMap;
use ethjson::misc::AccountMeta;
use devtools::RandomTempPath;
#[test]
fn should_save_and_reload_address_book() {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_meta(1.into(), "{1:1}".to_owned());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![1.into() => AccountMeta{name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None}]);
}
#[test]
fn should_save_and_reload_dapps_settings() {
// given
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = DappsSettingsStore::new(path.clone());
// when
b.set_accounts("dappOne".into(), vec![1.into(), 2.into()]);
// then
let b = DappsSettingsStore::new(path);
assert_eq!(b.get(), hash_map![
"dappOne".into() => DappsSettings {
accounts: vec![1.into(), 2.into()],
}
]);
}
#[test]
fn should_remove_address() {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_name(2.into(), "Two".to_owned());
b.set_name(3.into(), "Three".to_owned());
b.remove(2.into());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![
1.into() => AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None},
3.into() => AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}
]);
}
}
|
save
|
identifier_name
|
stores.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Address Book and Dapps Settings Store
use std::{fs, fmt, hash, ops};
use std::collections::HashMap;
use std::path::PathBuf;
use ethstore::ethkey::Address;
use ethjson::misc::{AccountMeta, DappsSettings as JsonSettings};
use account_provider::DappId;
/// Disk-backed map from Address to String. Uses JSON.
pub struct AddressBook {
cache: DiskMap<Address, AccountMeta>,
}
impl AddressBook {
/// Creates new address book at given directory.
pub fn new(path: String) -> Self {
let mut r = AddressBook {
cache: DiskMap::new(path, "address_book.json".into())
};
r.cache.revert(AccountMeta::read_address_map);
r
}
/// Creates transient address book (no changes are saved to disk).
pub fn transient() -> Self {
AddressBook {
cache: DiskMap::transient()
}
}
/// Get the address book.
pub fn get(&self) -> HashMap<Address, AccountMeta> {
self.cache.clone()
}
fn save(&self) {
self.cache.save(AccountMeta::write_address_map)
}
/// Sets new name for given address.
pub fn set_name(&mut self, a: Address, name: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: Default::default(), meta: "{}".to_owned(), uuid: None});
x.name = name;
}
self.save();
}
/// Sets new meta for given address.
pub fn set_meta(&mut self, a: Address, meta: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: "Anonymous".to_owned(), meta: Default::default(), uuid: None});
x.meta = meta;
}
self.save();
}
/// Removes an entry
pub fn remove(&mut self, a: Address) {
self.cache.remove(&a);
self.save();
}
}
/// Dapps user settings
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct DappsSettings {
/// A list of visible accounts
pub accounts: Vec<Address>,
}
impl From<JsonSettings> for DappsSettings {
fn from(s: JsonSettings) -> Self {
DappsSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
impl From<DappsSettings> for JsonSettings {
fn from(s: DappsSettings) -> Self {
JsonSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
/// Disk-backed map from DappId to Settings. Uses JSON.
pub struct DappsSettingsStore {
cache: DiskMap<DappId, DappsSettings>,
}
impl DappsSettingsStore {
/// Creates new store at given directory path.
pub fn new(path: String) -> Self {
let mut r = DappsSettingsStore {
cache: DiskMap::new(path, "dapps_accounts.json".into())
};
r.cache.revert(JsonSettings::read_dapps_settings);
r
}
/// Creates transient store (no changes are saved to disk).
pub fn transient() -> Self {
DappsSettingsStore {
cache: DiskMap::transient()
}
}
/// Get copy of the dapps settings
pub fn get(&self) -> HashMap<DappId, DappsSettings> {
self.cache.clone()
}
fn save(&self) {
self.cache.save(JsonSettings::write_dapps_settings)
}
pub fn set_accounts(&mut self, id: DappId, accounts: Vec<Address>) {
{
let mut settings = self.cache.entry(id).or_insert_with(DappsSettings::default);
settings.accounts = accounts;
}
self.save();
}
}
/// Disk-serializable HashMap
#[derive(Debug)]
struct DiskMap<K: hash::Hash + Eq, V> {
path: PathBuf,
cache: HashMap<K, V>,
transient: bool,
}
impl<K: hash::Hash + Eq, V> ops::Deref for DiskMap<K, V> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.cache
}
}
impl<K: hash::Hash + Eq, V> ops::DerefMut for DiskMap<K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cache
}
}
impl<K: hash::Hash + Eq, V> DiskMap<K, V> {
pub fn new(path: String, file_name: String) -> Self {
trace!(target: "diskmap", "new({})", path);
let mut path: PathBuf = path.into();
path.push(file_name);
trace!(target: "diskmap", "path={:?}", path);
DiskMap {
path: path,
cache: HashMap::new(),
transient: false,
}
}
pub fn transient() -> Self {
let mut map = DiskMap::new(Default::default(), "diskmap.json".into());
map.transient = true;
map
}
fn revert<F, E>(&mut self, read: F) where
F: Fn(fs::File) -> Result<HashMap<K, V>, E>,
E: fmt::Display,
{
if self.transient
|
trace!(target: "diskmap", "revert {:?}", self.path);
let _ = fs::File::open(self.path.clone())
.map_err(|e| trace!(target: "diskmap", "Couldn't open disk map: {}", e))
.and_then(|f| read(f).map_err(|e| warn!(target: "diskmap", "Couldn't read disk map: {}", e)))
.and_then(|m| {
self.cache = m;
Ok(())
});
}
fn save<F, E>(&self, write: F) where
F: Fn(&HashMap<K, V>, &mut fs::File) -> Result<(), E>,
E: fmt::Display,
{
if self.transient { return; }
trace!(target: "diskmap", "save {:?}", self.path);
let _ = fs::File::create(self.path.clone())
.map_err(|e| warn!(target: "diskmap", "Couldn't open disk map for writing: {}", e))
.and_then(|mut f| {
write(&self.cache, &mut f).map_err(|e| warn!(target: "diskmap", "Couldn't write to disk map: {}", e))
});
}
}
#[cfg(test)]
mod tests {
use super::{AddressBook, DappsSettingsStore, DappsSettings};
use std::collections::HashMap;
use ethjson::misc::AccountMeta;
use devtools::RandomTempPath;
#[test]
fn should_save_and_reload_address_book() {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_meta(1.into(), "{1:1}".to_owned());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![1.into() => AccountMeta{name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None}]);
}
#[test]
fn should_save_and_reload_dapps_settings() {
// given
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = DappsSettingsStore::new(path.clone());
// when
b.set_accounts("dappOne".into(), vec![1.into(), 2.into()]);
// then
let b = DappsSettingsStore::new(path);
assert_eq!(b.get(), hash_map![
"dappOne".into() => DappsSettings {
accounts: vec![1.into(), 2.into()],
}
]);
}
#[test]
fn should_remove_address() {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_name(2.into(), "Two".to_owned());
b.set_name(3.into(), "Three".to_owned());
b.remove(2.into());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![
1.into() => AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None},
3.into() => AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}
]);
}
}
|
{ return; }
|
conditional_block
|
stores.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Address Book and Dapps Settings Store
use std::{fs, fmt, hash, ops};
use std::collections::HashMap;
use std::path::PathBuf;
use ethstore::ethkey::Address;
use ethjson::misc::{AccountMeta, DappsSettings as JsonSettings};
use account_provider::DappId;
/// Disk-backed map from Address to String. Uses JSON.
pub struct AddressBook {
cache: DiskMap<Address, AccountMeta>,
}
impl AddressBook {
/// Creates new address book at given directory.
pub fn new(path: String) -> Self {
let mut r = AddressBook {
cache: DiskMap::new(path, "address_book.json".into())
};
r.cache.revert(AccountMeta::read_address_map);
r
}
/// Creates transient address book (no changes are saved to disk).
pub fn transient() -> Self {
AddressBook {
cache: DiskMap::transient()
}
}
/// Get the address book.
pub fn get(&self) -> HashMap<Address, AccountMeta> {
self.cache.clone()
}
fn save(&self) {
self.cache.save(AccountMeta::write_address_map)
}
/// Sets new name for given address.
pub fn set_name(&mut self, a: Address, name: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: Default::default(), meta: "{}".to_owned(), uuid: None});
x.name = name;
}
self.save();
}
/// Sets new meta for given address.
pub fn set_meta(&mut self, a: Address, meta: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: "Anonymous".to_owned(), meta: Default::default(), uuid: None});
x.meta = meta;
}
self.save();
}
/// Removes an entry
pub fn remove(&mut self, a: Address) {
self.cache.remove(&a);
self.save();
}
}
/// Dapps user settings
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct DappsSettings {
/// A list of visible accounts
pub accounts: Vec<Address>,
}
impl From<JsonSettings> for DappsSettings {
fn from(s: JsonSettings) -> Self {
DappsSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
impl From<DappsSettings> for JsonSettings {
fn from(s: DappsSettings) -> Self {
JsonSettings {
accounts: s.accounts.into_iter().map(Into::into).collect(),
}
}
}
/// Disk-backed map from DappId to Settings. Uses JSON.
pub struct DappsSettingsStore {
cache: DiskMap<DappId, DappsSettings>,
}
impl DappsSettingsStore {
/// Creates new store at given directory path.
pub fn new(path: String) -> Self {
let mut r = DappsSettingsStore {
cache: DiskMap::new(path, "dapps_accounts.json".into())
};
r.cache.revert(JsonSettings::read_dapps_settings);
r
}
/// Creates transient store (no changes are saved to disk).
pub fn transient() -> Self {
DappsSettingsStore {
cache: DiskMap::transient()
}
}
/// Get copy of the dapps settings
pub fn get(&self) -> HashMap<DappId, DappsSettings> {
self.cache.clone()
}
fn save(&self) {
self.cache.save(JsonSettings::write_dapps_settings)
}
pub fn set_accounts(&mut self, id: DappId, accounts: Vec<Address>) {
{
let mut settings = self.cache.entry(id).or_insert_with(DappsSettings::default);
settings.accounts = accounts;
}
self.save();
}
}
/// Disk-serializable HashMap
#[derive(Debug)]
struct DiskMap<K: hash::Hash + Eq, V> {
path: PathBuf,
cache: HashMap<K, V>,
transient: bool,
}
impl<K: hash::Hash + Eq, V> ops::Deref for DiskMap<K, V> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.cache
}
}
impl<K: hash::Hash + Eq, V> ops::DerefMut for DiskMap<K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cache
}
}
impl<K: hash::Hash + Eq, V> DiskMap<K, V> {
pub fn new(path: String, file_name: String) -> Self {
trace!(target: "diskmap", "new({})", path);
let mut path: PathBuf = path.into();
path.push(file_name);
trace!(target: "diskmap", "path={:?}", path);
DiskMap {
path: path,
cache: HashMap::new(),
transient: false,
}
}
pub fn transient() -> Self {
let mut map = DiskMap::new(Default::default(), "diskmap.json".into());
map.transient = true;
map
}
fn revert<F, E>(&mut self, read: F) where
F: Fn(fs::File) -> Result<HashMap<K, V>, E>,
E: fmt::Display,
{
if self.transient { return; }
trace!(target: "diskmap", "revert {:?}", self.path);
let _ = fs::File::open(self.path.clone())
.map_err(|e| trace!(target: "diskmap", "Couldn't open disk map: {}", e))
.and_then(|f| read(f).map_err(|e| warn!(target: "diskmap", "Couldn't read disk map: {}", e)))
.and_then(|m| {
self.cache = m;
Ok(())
});
}
fn save<F, E>(&self, write: F) where
F: Fn(&HashMap<K, V>, &mut fs::File) -> Result<(), E>,
E: fmt::Display,
{
if self.transient { return; }
trace!(target: "diskmap", "save {:?}", self.path);
let _ = fs::File::create(self.path.clone())
.map_err(|e| warn!(target: "diskmap", "Couldn't open disk map for writing: {}", e))
.and_then(|mut f| {
write(&self.cache, &mut f).map_err(|e| warn!(target: "diskmap", "Couldn't write to disk map: {}", e))
});
}
}
#[cfg(test)]
mod tests {
use super::{AddressBook, DappsSettingsStore, DappsSettings};
use std::collections::HashMap;
use ethjson::misc::AccountMeta;
use devtools::RandomTempPath;
#[test]
fn should_save_and_reload_address_book() {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_meta(1.into(), "{1:1}".to_owned());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![1.into() => AccountMeta{name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None}]);
}
#[test]
fn should_save_and_reload_dapps_settings() {
// given
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = DappsSettingsStore::new(path.clone());
// when
b.set_accounts("dappOne".into(), vec![1.into(), 2.into()]);
// then
let b = DappsSettingsStore::new(path);
assert_eq!(b.get(), hash_map![
"dappOne".into() => DappsSettings {
accounts: vec![1.into(), 2.into()],
}
]);
}
#[test]
fn should_remove_address()
|
}
|
{
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_name(2.into(), "Two".to_owned());
b.set_name(3.into(), "Three".to_owned());
b.remove(2.into());
let b = AddressBook::new(path);
assert_eq!(b.get(), hash_map![
1.into() => AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None},
3.into() => AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}
]);
}
|
identifier_body
|
dct.rs
|
use rustdct::{DCTplanner, TransformType2And3};
use transpose::transpose;
use std::sync::Arc;
pub const SIZE_MULTIPLIER: u32 = 2;
pub const SIZE_MULTIPLIER_U: usize = SIZE_MULTIPLIER as usize;
pub struct DctCtxt {
row_dct: Arc<dyn TransformType2And3<f32>>,
col_dct: Arc<dyn TransformType2And3<f32>>,
width: usize,
height: usize,
}
impl DctCtxt {
pub fn new(width: u32, height: u32) -> Self
|
pub fn width(&self) -> u32 {
self.width as u32
}
pub fn height(&self) -> u32 {
self.height as u32
}
/// Perform a 2D DCT on a 1D-packed vector with a given `width x height`.
///
/// Assumes `packed_2d` is double-length for scratch space. Returns the vector truncated to
/// `width * height`.
///
/// ### Panics
/// If `self.width * self.height * 2!= packed_2d.len()`
pub fn dct_2d(&self, mut packed_2d: Vec<f32>) -> Vec<f32> {
let Self { ref row_dct, ref col_dct, width, height } = *self;
let trunc_len = width * height;
assert_eq!(trunc_len * 2, packed_2d.len());
{
let (packed_2d, scratch) = packed_2d.split_at_mut(trunc_len);
for (row_in, row_out) in packed_2d.chunks_mut(width)
.zip(scratch.chunks_mut(width)) {
row_dct.process_dct2(row_in, row_out);
}
transpose(scratch, packed_2d, width, height);
for (row_in, row_out) in packed_2d.chunks_mut(height)
.zip(scratch.chunks_mut(height)) {
col_dct.process_dct2(row_in, row_out);
}
transpose(scratch, packed_2d, width, height);
}
packed_2d.truncate(trunc_len);
packed_2d
}
pub fn crop_2d(&self, packed: Vec<f32>) -> Vec<f32> {
crop_2d_dct(packed, self.width)
}
}
/// Crop the values off a 1D-packed 2D DCT.
///
/// Returns `packed` truncated to the premultiplied size, as determined by `rowstride`
///
/// Generic for easier testing
fn crop_2d_dct<T: Copy>(mut packed: Vec<T>, rowstride: usize) -> Vec<T> {
// assert that the rowstride was previously multiplied by SIZE_MULTIPLIER
assert_eq!(rowstride % SIZE_MULTIPLIER_U, 0);
assert!(rowstride / SIZE_MULTIPLIER_U > 0, "rowstride cannot be cropped: {}", rowstride);
let new_rowstride = rowstride / SIZE_MULTIPLIER_U;
for new_row in 0.. packed.len() / (rowstride * SIZE_MULTIPLIER_U) {
let (dest, src) = packed.split_at_mut(new_row * new_rowstride + rowstride);
let dest_start = dest.len() - new_rowstride;
let src_start = new_rowstride * new_row;
let src_end = src_start + new_rowstride;
dest[dest_start..].copy_from_slice(&src[src_start..src_end]);
}
let new_len = packed.len() / (SIZE_MULTIPLIER_U * SIZE_MULTIPLIER_U);
packed.truncate(new_len);
packed
}
#[test]
fn test_crop_2d_dct() {
let packed: Vec<i32> = (0.. 64).collect();
assert_eq!(
crop_2d_dct(packed.clone(), 8),
[
0, 1, 2, 3, // 4, 5, 6, 7
8, 9, 10, 11, // 12, 13, 14, 15
16, 17, 18, 19, // 20, 21, 22, 23,
24, 25, 26, 27, // 28, 29, 30, 31,
// 32.. 64
]
);
}
#[test]
fn test_transpose() {
}
|
{
let mut planner = DCTplanner::new();
let width = width as usize * SIZE_MULTIPLIER_U;
let height = height as usize * SIZE_MULTIPLIER_U;
DctCtxt {
row_dct: planner.plan_dct2(width),
col_dct: planner.plan_dct2(height),
width,
height,
}
}
|
identifier_body
|
dct.rs
|
use rustdct::{DCTplanner, TransformType2And3};
use transpose::transpose;
use std::sync::Arc;
pub const SIZE_MULTIPLIER: u32 = 2;
pub const SIZE_MULTIPLIER_U: usize = SIZE_MULTIPLIER as usize;
pub struct DctCtxt {
row_dct: Arc<dyn TransformType2And3<f32>>,
col_dct: Arc<dyn TransformType2And3<f32>>,
width: usize,
height: usize,
}
impl DctCtxt {
pub fn new(width: u32, height: u32) -> Self {
let mut planner = DCTplanner::new();
let width = width as usize * SIZE_MULTIPLIER_U;
let height = height as usize * SIZE_MULTIPLIER_U;
DctCtxt {
row_dct: planner.plan_dct2(width),
col_dct: planner.plan_dct2(height),
width,
height,
}
}
pub fn width(&self) -> u32 {
self.width as u32
}
pub fn height(&self) -> u32 {
self.height as u32
}
/// Perform a 2D DCT on a 1D-packed vector with a given `width x height`.
///
/// Assumes `packed_2d` is double-length for scratch space. Returns the vector truncated to
/// `width * height`.
///
/// ### Panics
/// If `self.width * self.height * 2!= packed_2d.len()`
pub fn dct_2d(&self, mut packed_2d: Vec<f32>) -> Vec<f32> {
let Self { ref row_dct, ref col_dct, width, height } = *self;
let trunc_len = width * height;
assert_eq!(trunc_len * 2, packed_2d.len());
{
let (packed_2d, scratch) = packed_2d.split_at_mut(trunc_len);
for (row_in, row_out) in packed_2d.chunks_mut(width)
.zip(scratch.chunks_mut(width)) {
row_dct.process_dct2(row_in, row_out);
}
transpose(scratch, packed_2d, width, height);
for (row_in, row_out) in packed_2d.chunks_mut(height)
.zip(scratch.chunks_mut(height)) {
col_dct.process_dct2(row_in, row_out);
}
transpose(scratch, packed_2d, width, height);
}
packed_2d.truncate(trunc_len);
packed_2d
}
|
/// Crop the values off a 1D-packed 2D DCT.
///
/// Returns `packed` truncated to the premultiplied size, as determined by `rowstride`
///
/// Generic for easier testing
fn crop_2d_dct<T: Copy>(mut packed: Vec<T>, rowstride: usize) -> Vec<T> {
// assert that the rowstride was previously multiplied by SIZE_MULTIPLIER
assert_eq!(rowstride % SIZE_MULTIPLIER_U, 0);
assert!(rowstride / SIZE_MULTIPLIER_U > 0, "rowstride cannot be cropped: {}", rowstride);
let new_rowstride = rowstride / SIZE_MULTIPLIER_U;
for new_row in 0.. packed.len() / (rowstride * SIZE_MULTIPLIER_U) {
let (dest, src) = packed.split_at_mut(new_row * new_rowstride + rowstride);
let dest_start = dest.len() - new_rowstride;
let src_start = new_rowstride * new_row;
let src_end = src_start + new_rowstride;
dest[dest_start..].copy_from_slice(&src[src_start..src_end]);
}
let new_len = packed.len() / (SIZE_MULTIPLIER_U * SIZE_MULTIPLIER_U);
packed.truncate(new_len);
packed
}
#[test]
fn test_crop_2d_dct() {
let packed: Vec<i32> = (0.. 64).collect();
assert_eq!(
crop_2d_dct(packed.clone(), 8),
[
0, 1, 2, 3, // 4, 5, 6, 7
8, 9, 10, 11, // 12, 13, 14, 15
16, 17, 18, 19, // 20, 21, 22, 23,
24, 25, 26, 27, // 28, 29, 30, 31,
// 32.. 64
]
);
}
#[test]
fn test_transpose() {
}
|
pub fn crop_2d(&self, packed: Vec<f32>) -> Vec<f32> {
crop_2d_dct(packed, self.width)
}
}
|
random_line_split
|
dct.rs
|
use rustdct::{DCTplanner, TransformType2And3};
use transpose::transpose;
use std::sync::Arc;
pub const SIZE_MULTIPLIER: u32 = 2;
pub const SIZE_MULTIPLIER_U: usize = SIZE_MULTIPLIER as usize;
pub struct
|
{
row_dct: Arc<dyn TransformType2And3<f32>>,
col_dct: Arc<dyn TransformType2And3<f32>>,
width: usize,
height: usize,
}
impl DctCtxt {
pub fn new(width: u32, height: u32) -> Self {
let mut planner = DCTplanner::new();
let width = width as usize * SIZE_MULTIPLIER_U;
let height = height as usize * SIZE_MULTIPLIER_U;
DctCtxt {
row_dct: planner.plan_dct2(width),
col_dct: planner.plan_dct2(height),
width,
height,
}
}
pub fn width(&self) -> u32 {
self.width as u32
}
pub fn height(&self) -> u32 {
self.height as u32
}
/// Perform a 2D DCT on a 1D-packed vector with a given `width x height`.
///
/// Assumes `packed_2d` is double-length for scratch space. Returns the vector truncated to
/// `width * height`.
///
/// ### Panics
/// If `self.width * self.height * 2!= packed_2d.len()`
pub fn dct_2d(&self, mut packed_2d: Vec<f32>) -> Vec<f32> {
let Self { ref row_dct, ref col_dct, width, height } = *self;
let trunc_len = width * height;
assert_eq!(trunc_len * 2, packed_2d.len());
{
let (packed_2d, scratch) = packed_2d.split_at_mut(trunc_len);
for (row_in, row_out) in packed_2d.chunks_mut(width)
.zip(scratch.chunks_mut(width)) {
row_dct.process_dct2(row_in, row_out);
}
transpose(scratch, packed_2d, width, height);
for (row_in, row_out) in packed_2d.chunks_mut(height)
.zip(scratch.chunks_mut(height)) {
col_dct.process_dct2(row_in, row_out);
}
transpose(scratch, packed_2d, width, height);
}
packed_2d.truncate(trunc_len);
packed_2d
}
pub fn crop_2d(&self, packed: Vec<f32>) -> Vec<f32> {
crop_2d_dct(packed, self.width)
}
}
/// Crop the values off a 1D-packed 2D DCT.
///
/// Returns `packed` truncated to the premultiplied size, as determined by `rowstride`
///
/// Generic for easier testing
fn crop_2d_dct<T: Copy>(mut packed: Vec<T>, rowstride: usize) -> Vec<T> {
// assert that the rowstride was previously multiplied by SIZE_MULTIPLIER
assert_eq!(rowstride % SIZE_MULTIPLIER_U, 0);
assert!(rowstride / SIZE_MULTIPLIER_U > 0, "rowstride cannot be cropped: {}", rowstride);
let new_rowstride = rowstride / SIZE_MULTIPLIER_U;
for new_row in 0.. packed.len() / (rowstride * SIZE_MULTIPLIER_U) {
let (dest, src) = packed.split_at_mut(new_row * new_rowstride + rowstride);
let dest_start = dest.len() - new_rowstride;
let src_start = new_rowstride * new_row;
let src_end = src_start + new_rowstride;
dest[dest_start..].copy_from_slice(&src[src_start..src_end]);
}
let new_len = packed.len() / (SIZE_MULTIPLIER_U * SIZE_MULTIPLIER_U);
packed.truncate(new_len);
packed
}
#[test]
fn test_crop_2d_dct() {
let packed: Vec<i32> = (0.. 64).collect();
assert_eq!(
crop_2d_dct(packed.clone(), 8),
[
0, 1, 2, 3, // 4, 5, 6, 7
8, 9, 10, 11, // 12, 13, 14, 15
16, 17, 18, 19, // 20, 21, 22, 23,
24, 25, 26, 27, // 28, 29, 30, 31,
// 32.. 64
]
);
}
#[test]
fn test_transpose() {
}
|
DctCtxt
|
identifier_name
|
util.rs
|
use ::Disruption;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use time::PreciseTime;
use hyper::Client;
pub fn disruption_to_usize(d: &Option<&(Disruption, usize)>) -> usize
|
pub fn send_bulk<T: Encodable>(url: &str, client: &Arc<Client>, bulk: Vec<T>) {
::ACTIVE_THREADS.fetch_add(1, Ordering::SeqCst);
debug!("......");
let mut s = String::new();
let size = bulk.len();
for b in bulk {
s.push_str("{\"index\":{}}\n");
s.push_str(&json::encode(&b).unwrap());
s.push_str("\n");
}
debug!(" >>>>> Bulk: {} mb ({} elements)", s.len() / 1024 / 1024, size);
let start = PreciseTime::now();
let _ = client.post(url)
.body(&s)
.send()
.unwrap();
let end = PreciseTime::now();
let _ = PreciseTime::to(&start, end);
::ACTIVE_THREADS.fetch_sub(1, Ordering::SeqCst);
}
|
{
match *d {
None => 0,
Some(&(Disruption::Node(_), _)) => 1,
Some(&(Disruption::Query(_), _)) => 2,
Some(&(Disruption::Metric(_), _)) => 3
}
}
|
identifier_body
|
util.rs
|
use ::Disruption;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use time::PreciseTime;
use hyper::Client;
pub fn disruption_to_usize(d: &Option<&(Disruption, usize)>) -> usize {
match *d {
None => 0,
Some(&(Disruption::Node(_), _)) => 1,
Some(&(Disruption::Query(_), _)) => 2,
Some(&(Disruption::Metric(_), _)) => 3
}
}
pub fn
|
<T: Encodable>(url: &str, client: &Arc<Client>, bulk: Vec<T>) {
::ACTIVE_THREADS.fetch_add(1, Ordering::SeqCst);
debug!("......");
let mut s = String::new();
let size = bulk.len();
for b in bulk {
s.push_str("{\"index\":{}}\n");
s.push_str(&json::encode(&b).unwrap());
s.push_str("\n");
}
debug!(" >>>>> Bulk: {} mb ({} elements)", s.len() / 1024 / 1024, size);
let start = PreciseTime::now();
let _ = client.post(url)
.body(&s)
.send()
.unwrap();
let end = PreciseTime::now();
let _ = PreciseTime::to(&start, end);
::ACTIVE_THREADS.fetch_sub(1, Ordering::SeqCst);
}
|
send_bulk
|
identifier_name
|
util.rs
|
use ::Disruption;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use time::PreciseTime;
use hyper::Client;
|
pub fn disruption_to_usize(d: &Option<&(Disruption, usize)>) -> usize {
match *d {
None => 0,
Some(&(Disruption::Node(_), _)) => 1,
Some(&(Disruption::Query(_), _)) => 2,
Some(&(Disruption::Metric(_), _)) => 3
}
}
pub fn send_bulk<T: Encodable>(url: &str, client: &Arc<Client>, bulk: Vec<T>) {
::ACTIVE_THREADS.fetch_add(1, Ordering::SeqCst);
debug!("......");
let mut s = String::new();
let size = bulk.len();
for b in bulk {
s.push_str("{\"index\":{}}\n");
s.push_str(&json::encode(&b).unwrap());
s.push_str("\n");
}
debug!(" >>>>> Bulk: {} mb ({} elements)", s.len() / 1024 / 1024, size);
let start = PreciseTime::now();
let _ = client.post(url)
.body(&s)
.send()
.unwrap();
let end = PreciseTime::now();
let _ = PreciseTime::to(&start, end);
::ACTIVE_THREADS.fetch_sub(1, Ordering::SeqCst);
}
|
random_line_split
|
|
errors.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::ast::{SyntaxError, SourceLocation};
pub struct ErrorLoggerIterator<I>(pub I);
impl<T, I: Iterator<Result<T, SyntaxError>>> Iterator<T> for ErrorLoggerIterator<I> {
fn next(&mut self) -> Option<T>
|
}
/// Defaults to a no-op.
/// Set a `RUST_LOG=style::errors` environment variable
/// to log CSS parse errors to stderr.
pub fn log_css_error(location: SourceLocation, message: &str) {
// Check this first as it’s cheaper than local_data.
if log_enabled!(::log::INFO) {
if silence_errors.get().is_none() {
// TODO eventually this will got into a "web console" or something.
info!("{:u}:{:u} {:s}", location.line, location.column, message)
}
}
}
local_data_key!(silence_errors: ())
pub fn with_errors_silenced<T>(f: || -> T) -> T {
silence_errors.replace(Some(()));
let result = f();
silence_errors.replace(None);
result
}
|
{
let ErrorLoggerIterator(ref mut this) = *self;
loop {
match this.next() {
Some(Ok(v)) => return Some(v),
Some(Err(error)) => log_css_error(error.location,
format!("{:?}", error.reason).as_slice()),
None => return None,
}
}
}
|
identifier_body
|
errors.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::ast::{SyntaxError, SourceLocation};
pub struct ErrorLoggerIterator<I>(pub I);
impl<T, I: Iterator<Result<T, SyntaxError>>> Iterator<T> for ErrorLoggerIterator<I> {
fn next(&mut self) -> Option<T> {
let ErrorLoggerIterator(ref mut this) = *self;
loop {
match this.next() {
Some(Ok(v)) => return Some(v),
Some(Err(error)) => log_css_error(error.location,
format!("{:?}", error.reason).as_slice()),
None => return None,
}
}
}
}
/// Defaults to a no-op.
/// Set a `RUST_LOG=style::errors` environment variable
/// to log CSS parse errors to stderr.
pub fn log_css_error(location: SourceLocation, message: &str) {
// Check this first as it’s cheaper than local_data.
if log_enabled!(::log::INFO) {
if silence_errors.get().is_none() {
// TODO eventually this will got into a "web console" or something.
info!("{:u}:{:u} {:s}", location.line, location.column, message)
}
}
}
local_data_key!(silence_errors: ())
pub fn wi
|
>(f: || -> T) -> T {
silence_errors.replace(Some(()));
let result = f();
silence_errors.replace(None);
result
}
|
th_errors_silenced<T
|
identifier_name
|
errors.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::ast::{SyntaxError, SourceLocation};
pub struct ErrorLoggerIterator<I>(pub I);
impl<T, I: Iterator<Result<T, SyntaxError>>> Iterator<T> for ErrorLoggerIterator<I> {
fn next(&mut self) -> Option<T> {
let ErrorLoggerIterator(ref mut this) = *self;
loop {
match this.next() {
Some(Ok(v)) => return Some(v),
Some(Err(error)) => log_css_error(error.location,
format!("{:?}", error.reason).as_slice()),
None => return None,
}
}
}
}
/// Defaults to a no-op.
/// Set a `RUST_LOG=style::errors` environment variable
/// to log CSS parse errors to stderr.
pub fn log_css_error(location: SourceLocation, message: &str) {
// Check this first as it’s cheaper than local_data.
if log_enabled!(::log::INFO) {
if silence_errors.get().is_none() {
// TODO eventually this will got into a "web console" or something.
info!("{:u}:{:u} {:s}", location.line, location.column, message)
|
local_data_key!(silence_errors: ())
pub fn with_errors_silenced<T>(f: || -> T) -> T {
silence_errors.replace(Some(()));
let result = f();
silence_errors.replace(None);
result
}
|
}
}
}
|
random_line_split
|
timeout.rs
|
extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn new(duration: Duration, e: E) -> Timeout<T, E> {
Timeout {
timestamp: Instant::now(),
duration: duration,
phantom: PhantomData,
error: e,
}
}
pub fn is_elapsed(&self) -> bool {
self.timestamp.elapsed() >= self.duration
}
}
impl<T,E> Future for Timeout<T,E>
where E: Fn() -> io::Error
{
type Item = T;
type Error = io::Error;
// Return type of the Future::poll method, indicates whether a future's value is ready or not.
//
// Ok(Async::Ready(t)) means that a future has successfully resolved
// Ok(Async::NotReady) means that a future is not ready to complete yet
// Err(e) means that a future has completed with the given failure
fn
|
(&mut self) -> Poll<Self::Item, Self::Error> {
use futures::{Async, task};
if self.is_elapsed() {
Err((self.error)())
} else {
task::park().unpark(); // this tells the task driving the future to recheck this again
// in the future. Otherwise poll will only be run once.
Ok(Async::NotReady)
}
}
}
|
poll
|
identifier_name
|
timeout.rs
|
extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn new(duration: Duration, e: E) -> Timeout<T, E> {
Timeout {
timestamp: Instant::now(),
duration: duration,
phantom: PhantomData,
error: e,
}
}
pub fn is_elapsed(&self) -> bool {
self.timestamp.elapsed() >= self.duration
}
}
impl<T,E> Future for Timeout<T,E>
where E: Fn() -> io::Error
{
type Item = T;
type Error = io::Error;
// Return type of the Future::poll method, indicates whether a future's value is ready or not.
//
// Ok(Async::Ready(t)) means that a future has successfully resolved
// Ok(Async::NotReady) means that a future is not ready to complete yet
// Err(e) means that a future has completed with the given failure
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
use futures::{Async, task};
if self.is_elapsed()
|
else {
task::park().unpark(); // this tells the task driving the future to recheck this again
// in the future. Otherwise poll will only be run once.
Ok(Async::NotReady)
}
}
}
|
{
Err((self.error)())
}
|
conditional_block
|
timeout.rs
|
extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn new(duration: Duration, e: E) -> Timeout<T, E> {
Timeout {
timestamp: Instant::now(),
duration: duration,
phantom: PhantomData,
error: e,
}
}
pub fn is_elapsed(&self) -> bool {
self.timestamp.elapsed() >= self.duration
}
}
impl<T,E> Future for Timeout<T,E>
where E: Fn() -> io::Error
{
type Item = T;
type Error = io::Error;
// Return type of the Future::poll method, indicates whether a future's value is ready or not.
//
// Ok(Async::Ready(t)) means that a future has successfully resolved
// Ok(Async::NotReady) means that a future is not ready to complete yet
// Err(e) means that a future has completed with the given failure
fn poll(&mut self) -> Poll<Self::Item, Self::Error>
|
}
|
{
use futures::{Async, task};
if self.is_elapsed() {
Err((self.error)())
} else {
task::park().unpark(); // this tells the task driving the future to recheck this again
// in the future. Otherwise poll will only be run once.
Ok(Async::NotReady)
}
}
|
identifier_body
|
timeout.rs
|
extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn new(duration: Duration, e: E) -> Timeout<T, E> {
Timeout {
timestamp: Instant::now(),
duration: duration,
phantom: PhantomData,
error: e,
}
}
pub fn is_elapsed(&self) -> bool {
self.timestamp.elapsed() >= self.duration
}
}
|
impl<T,E> Future for Timeout<T,E>
where E: Fn() -> io::Error
{
type Item = T;
type Error = io::Error;
// Return type of the Future::poll method, indicates whether a future's value is ready or not.
//
// Ok(Async::Ready(t)) means that a future has successfully resolved
// Ok(Async::NotReady) means that a future is not ready to complete yet
// Err(e) means that a future has completed with the given failure
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
use futures::{Async, task};
if self.is_elapsed() {
Err((self.error)())
} else {
task::park().unpark(); // this tells the task driving the future to recheck this again
// in the future. Otherwise poll will only be run once.
Ok(Async::NotReady)
}
}
}
|
random_line_split
|
|
log.rs
|
use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new() -> Self {
MessageLog {
messages: Vec::new(),
last_temporary: false,
}
}
pub fn len(&self) -> usize {
self.messages.len()
}
pub fn tail(&self, count: usize) -> &[MessageLogEntry] {
let mid = cmp::max(0, (self.len() as isize) - (count as isize)) as usize;
&self.messages[mid..]
}
pub fn tail_with_offset(&self, count: usize, offset: usize) -> &[MessageLogEntry] {
let end = cmp::max(0, (self.len() as isize) - (offset as isize)) as usize;
let start = cmp::max(0, (end as isize) - (count as isize)) as usize;
&self.messages[start..end]
}
pub fn add(&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = false;
if let Some(ref mut entry) = self.messages.last_mut() {
if message == entry.message {
entry.repeated += 1;
return;
}
}
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
pub fn add_temporary(&mut self, message: MessageType) {
if self.last_temporary
|
self.last_temporary = true;
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
}
|
{
self.messages.pop();
}
|
conditional_block
|
log.rs
|
use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new() -> Self {
MessageLog {
messages: Vec::new(),
last_temporary: false,
}
}
pub fn len(&self) -> usize {
self.messages.len()
}
pub fn tail(&self, count: usize) -> &[MessageLogEntry]
|
pub fn tail_with_offset(&self, count: usize, offset: usize) -> &[MessageLogEntry] {
let end = cmp::max(0, (self.len() as isize) - (offset as isize)) as usize;
let start = cmp::max(0, (end as isize) - (count as isize)) as usize;
&self.messages[start..end]
}
pub fn add(&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = false;
if let Some(ref mut entry) = self.messages.last_mut() {
if message == entry.message {
entry.repeated += 1;
return;
}
}
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
pub fn add_temporary(&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = true;
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
}
|
{
let mid = cmp::max(0, (self.len() as isize) - (count as isize)) as usize;
&self.messages[mid..]
}
|
identifier_body
|
log.rs
|
use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new() -> Self {
MessageLog {
messages: Vec::new(),
last_temporary: false,
}
}
pub fn len(&self) -> usize {
self.messages.len()
}
pub fn tail(&self, count: usize) -> &[MessageLogEntry] {
let mid = cmp::max(0, (self.len() as isize) - (count as isize)) as usize;
&self.messages[mid..]
}
pub fn tail_with_offset(&self, count: usize, offset: usize) -> &[MessageLogEntry] {
let end = cmp::max(0, (self.len() as isize) - (offset as isize)) as usize;
let start = cmp::max(0, (end as isize) - (count as isize)) as usize;
&self.messages[start..end]
}
pub fn add(&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = false;
if let Some(ref mut entry) = self.messages.last_mut() {
if message == entry.message {
entry.repeated += 1;
return;
}
}
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
pub fn add_temporary(&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = true;
self.messages.push(MessageLogEntry {
message: message,
|
}
}
|
repeated: 1,
});
|
random_line_split
|
log.rs
|
use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new() -> Self {
MessageLog {
messages: Vec::new(),
last_temporary: false,
}
}
pub fn len(&self) -> usize {
self.messages.len()
}
pub fn tail(&self, count: usize) -> &[MessageLogEntry] {
let mid = cmp::max(0, (self.len() as isize) - (count as isize)) as usize;
&self.messages[mid..]
}
pub fn tail_with_offset(&self, count: usize, offset: usize) -> &[MessageLogEntry] {
let end = cmp::max(0, (self.len() as isize) - (offset as isize)) as usize;
let start = cmp::max(0, (end as isize) - (count as isize)) as usize;
&self.messages[start..end]
}
pub fn add(&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = false;
if let Some(ref mut entry) = self.messages.last_mut() {
if message == entry.message {
entry.repeated += 1;
return;
}
}
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
pub fn
|
(&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = true;
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
}
|
add_temporary
|
identifier_name
|
screen.rs
|
use crate::portal::PortalRef;
use alloc::sync::Weak;
use cairo::bindings::{CAIRO_FORMAT_A8, CAIRO_FORMAT_ARGB32, CAIRO_FORMAT_RGB24};
use cairo::{Cairo, Surface};
use core::mem;
use graphics_base::frame_buffer::{AsSurface, AsSurfaceMut, FrameBuffer};
use graphics_base::types::{EventInput, MouseButton, MouseInputInfo, Rect};
use graphics_base::{Error, Result};
|
const CURSOR_HOTSPOT_Y: f64 = 8.0;
pub struct ScreenBuffer {
pub pos: Rect,
pub frame_buffer_size: (u16, u16),
pub frame_buffer: Weak<FrameBuffer>,
pub portal_ref: PortalRef,
}
pub struct InputCapture {
button: MouseButton,
pub pos: Rect,
pub portal_ref: PortalRef,
}
fn to_sprite(hotspot: (u16, u16)) -> (f64, f64) {
(hotspot.0 as f64 - CURSOR_HOTSPOT_X, hotspot.1 as f64 - CURSOR_HOTSPOT_Y)
}
fn surface_from_jpeg_slice(data: &[u8]) -> Result<Surface<'static>> {
let mut decoder = Decoder::new(data);
let data = decoder.decode().map_err(|_| Error::NotSupported)?;
let ImageInfo {
width,
height,
pixel_format,
} = decoder.info().unwrap();
let (data, format) = match pixel_format {
PixelFormat::L8 => (data, CAIRO_FORMAT_A8),
PixelFormat::RGB24 => {
let mut data32 = Vec::with_capacity(width as usize * height as usize * 4);
for chunk in data.chunks_exact(3) {
data32.extend(chunk.iter().rev());
data32.push(0);
}
(data32, CAIRO_FORMAT_RGB24)
}
PixelFormat::CMYK32 => panic!("CMYK not supported"),
};
Ok(Surface::from_vec(data, format, width, height))
}
pub struct Screen<S> {
cursor_hotspot: (u16, u16),
cursor_sprite: (f64, f64),
buttons: [bool; 3],
screen_size: (u16, u16),
lfb: S,
cursor: Surface<'static>,
wallpaper: Surface<'static>,
pub buffers: Vec<ScreenBuffer>,
pub input_capture: Option<InputCapture>,
}
unsafe impl<S> Send for Screen<S> {}
impl<S> Screen<S>
where
S: AsSurfaceMut,
{
pub fn new(screen_size: (u16, u16), lfb: S) -> Self {
static CURSOR_BYTES: &'static [u8] = include_bytes!("icons8-cursor-32.png");
static WALLPAPER_BYTES: &'static [u8] = include_bytes!("wallpaper.jpg");
let cursor = Surface::from_png_slice(CURSOR_BYTES).unwrap();
let cursor_hotspot = (screen_size.0 / 2, screen_size.1 / 2);
let wallpaper = surface_from_jpeg_slice(WALLPAPER_BYTES).unwrap();
Self {
cursor_hotspot,
cursor_sprite: to_sprite(cursor_hotspot),
buttons: [false; 3],
screen_size,
lfb,
cursor,
wallpaper,
buffers: Vec::new(),
input_capture: None,
}
}
fn draw_buffers(cr: &Cairo, screen_size: (u16, u16), wallpaper: &Surface, buffers: &[ScreenBuffer]) {
cr.new_path()
.move_to(0.0, 0.0)
.rel_line_to(0.0, screen_size.1 as f64)
.rel_line_to(screen_size.0 as f64, 0.0)
.rel_line_to(0.0, -(screen_size.1 as f64))
.rel_line_to(-(screen_size.0 as f64), 0.0);
for buffer in buffers {
let ScreenBuffer {
pos: Rect { x, y, width, height },
frame_buffer_size,
ref frame_buffer,
..
} = *buffer;
if let Some(frame_buffer) = frame_buffer.upgrade() {
let surface = frame_buffer.as_surface(CAIRO_FORMAT_RGB24, frame_buffer_size);
cr.set_source_surface(&surface, x, y).paint();
}
cr.new_sub_path()
.rectangle(x, y, width, height)
.close_path()
.clip_preserve();
}
cr.set_source_surface(wallpaper, 0.0, 0.0).paint();
}
fn find_portal(&self) -> Option<(Rect, PortalRef)> {
let pos = self.cursor_hotspot;
let x = pos.0 as f64;
let y = pos.1 as f64;
if let Some(InputCapture {
pos, ref portal_ref,..
}) = self.input_capture
{
Some((pos, portal_ref.clone()))
} else {
for buffer in self.buffers.iter() {
let ScreenBuffer {
pos, ref portal_ref,..
} = *buffer;
if pos.contains(x, y) {
return Some((pos, portal_ref.clone()));
}
}
None
}
}
#[cfg(target_os = "rust_os")]
pub fn update_mouse_state_delta(&mut self, dx: i16, dy: i16, dw: i8, buttons: [bool; 3]) -> Result<()> {
let x = ((self.cursor_hotspot.0 as i32 + dx as i32).max(0) as u16).min(self.screen_size.0 - 1);
let y = ((self.cursor_hotspot.1 as i32 + dy as i32).max(0) as u16).min(self.screen_size.1 - 1);
self.update_mouse_state(x, y, dw, buttons)
}
pub fn update_mouse_state(&mut self, x: u16, y: u16, _dw: i8, buttons: [bool; 3]) -> Result<()> {
let prev_cursor_hotspot = self.cursor_hotspot;
let prev_cursor_sprite = self.cursor_sprite;
let prev_buttons = self.buttons;
self.cursor_hotspot = (x, y);
self.cursor_sprite = to_sprite(self.cursor_hotspot);
self.buttons = buttons;
if let Some((pos, portal_ref)) = self.find_portal() {
let screen_x = x as f64;
let screen_y = y as f64;
let x = screen_x - pos.x;
let y = screen_y - pos.y;
let info = MouseInputInfo {
x,
y,
screen_x,
screen_y,
};
let mut inputs = Vec::new();
if prev_cursor_hotspot!= self.cursor_hotspot {
inputs.push(EventInput::MouseMove { info: info.clone() });
}
for ((&prev_down, &down), &button) in prev_buttons
.iter()
.zip(self.buttons.iter())
.zip([MouseButton::Left, MouseButton::Middle, MouseButton::Right].iter())
{
if!prev_down && down {
inputs.push(EventInput::MouseButtonDown {
info: info.clone(),
button,
});
if self.input_capture.is_none() {
self.input_capture = Some(InputCapture {
button,
pos,
portal_ref: portal_ref.clone(),
});
}
} else if prev_down &&!down {
inputs.push(EventInput::MouseButtonUp {
info: info.clone(),
button,
});
if let Some(InputCapture {
button: prev_button,..
}) = self.input_capture
{
if prev_button == button {
self.input_capture = None;
}
}
}
}
for input in inputs {
portal_ref.send_input(input)?;
}
}
let cr = self
.lfb
.as_surface_mut(CAIRO_FORMAT_ARGB32, self.screen_size)
.into_cairo();
cr.rectangle(prev_cursor_sprite.0, prev_cursor_sprite.1, CURSOR_WIDTH, CURSOR_HEIGHT)
.clip();
Self::draw_buffers(&cr, self.screen_size, &self.wallpaper, &self.buffers);
cr.reset_clip()
.set_source_surface(&self.cursor, self.cursor_sprite.0, self.cursor_sprite.1)
.paint();
Ok(())
}
pub fn update_buffers<I>(&mut self, buffers: I)
where
I: IntoIterator<Item = ScreenBuffer>,
{
let mut prev_input_capture = mem::replace(&mut self.input_capture, None);
self.buffers.clear();
let buffers = buffers.into_iter();
if let (_, Some(capacity)) = buffers.size_hint() {
self.buffers.reserve(capacity);
}
for buffer in buffers {
prev_input_capture = prev_input_capture.and_then(|prev_input_capture| {
if prev_input_capture.portal_ref == buffer.portal_ref {
self.input_capture = Some(InputCapture {
pos: buffer.pos,
..prev_input_capture
});
None
} else {
Some(prev_input_capture)
}
});
self.buffers.push(buffer);
}
let cr = self
.lfb
.as_surface_mut(CAIRO_FORMAT_ARGB32, self.screen_size)
.into_cairo();
Self::draw_buffers(&cr, self.screen_size, &self.wallpaper, &self.buffers);
cr.reset_clip()
.set_source_surface(&self.cursor, self.cursor_sprite.0, self.cursor_sprite.1)
.paint();
}
}
|
use jpeg_decoder::{Decoder, ImageInfo, PixelFormat};
const CURSOR_WIDTH: f64 = 32.0;
const CURSOR_HEIGHT: f64 = 32.0;
const CURSOR_HOTSPOT_X: f64 = 12.0;
|
random_line_split
|
screen.rs
|
use crate::portal::PortalRef;
use alloc::sync::Weak;
use cairo::bindings::{CAIRO_FORMAT_A8, CAIRO_FORMAT_ARGB32, CAIRO_FORMAT_RGB24};
use cairo::{Cairo, Surface};
use core::mem;
use graphics_base::frame_buffer::{AsSurface, AsSurfaceMut, FrameBuffer};
use graphics_base::types::{EventInput, MouseButton, MouseInputInfo, Rect};
use graphics_base::{Error, Result};
use jpeg_decoder::{Decoder, ImageInfo, PixelFormat};
const CURSOR_WIDTH: f64 = 32.0;
const CURSOR_HEIGHT: f64 = 32.0;
const CURSOR_HOTSPOT_X: f64 = 12.0;
const CURSOR_HOTSPOT_Y: f64 = 8.0;
pub struct ScreenBuffer {
pub pos: Rect,
pub frame_buffer_size: (u16, u16),
pub frame_buffer: Weak<FrameBuffer>,
pub portal_ref: PortalRef,
}
pub struct InputCapture {
button: MouseButton,
pub pos: Rect,
pub portal_ref: PortalRef,
}
fn to_sprite(hotspot: (u16, u16)) -> (f64, f64) {
(hotspot.0 as f64 - CURSOR_HOTSPOT_X, hotspot.1 as f64 - CURSOR_HOTSPOT_Y)
}
fn surface_from_jpeg_slice(data: &[u8]) -> Result<Surface<'static>> {
let mut decoder = Decoder::new(data);
let data = decoder.decode().map_err(|_| Error::NotSupported)?;
let ImageInfo {
width,
height,
pixel_format,
} = decoder.info().unwrap();
let (data, format) = match pixel_format {
PixelFormat::L8 => (data, CAIRO_FORMAT_A8),
PixelFormat::RGB24 => {
let mut data32 = Vec::with_capacity(width as usize * height as usize * 4);
for chunk in data.chunks_exact(3) {
data32.extend(chunk.iter().rev());
data32.push(0);
}
(data32, CAIRO_FORMAT_RGB24)
}
PixelFormat::CMYK32 => panic!("CMYK not supported"),
};
Ok(Surface::from_vec(data, format, width, height))
}
pub struct Screen<S> {
cursor_hotspot: (u16, u16),
cursor_sprite: (f64, f64),
buttons: [bool; 3],
screen_size: (u16, u16),
lfb: S,
cursor: Surface<'static>,
wallpaper: Surface<'static>,
pub buffers: Vec<ScreenBuffer>,
pub input_capture: Option<InputCapture>,
}
unsafe impl<S> Send for Screen<S> {}
impl<S> Screen<S>
where
S: AsSurfaceMut,
{
pub fn new(screen_size: (u16, u16), lfb: S) -> Self {
static CURSOR_BYTES: &'static [u8] = include_bytes!("icons8-cursor-32.png");
static WALLPAPER_BYTES: &'static [u8] = include_bytes!("wallpaper.jpg");
let cursor = Surface::from_png_slice(CURSOR_BYTES).unwrap();
let cursor_hotspot = (screen_size.0 / 2, screen_size.1 / 2);
let wallpaper = surface_from_jpeg_slice(WALLPAPER_BYTES).unwrap();
Self {
cursor_hotspot,
cursor_sprite: to_sprite(cursor_hotspot),
buttons: [false; 3],
screen_size,
lfb,
cursor,
wallpaper,
buffers: Vec::new(),
input_capture: None,
}
}
fn draw_buffers(cr: &Cairo, screen_size: (u16, u16), wallpaper: &Surface, buffers: &[ScreenBuffer]) {
cr.new_path()
.move_to(0.0, 0.0)
.rel_line_to(0.0, screen_size.1 as f64)
.rel_line_to(screen_size.0 as f64, 0.0)
.rel_line_to(0.0, -(screen_size.1 as f64))
.rel_line_to(-(screen_size.0 as f64), 0.0);
for buffer in buffers {
let ScreenBuffer {
pos: Rect { x, y, width, height },
frame_buffer_size,
ref frame_buffer,
..
} = *buffer;
if let Some(frame_buffer) = frame_buffer.upgrade() {
let surface = frame_buffer.as_surface(CAIRO_FORMAT_RGB24, frame_buffer_size);
cr.set_source_surface(&surface, x, y).paint();
}
cr.new_sub_path()
.rectangle(x, y, width, height)
.close_path()
.clip_preserve();
}
cr.set_source_surface(wallpaper, 0.0, 0.0).paint();
}
fn find_portal(&self) -> Option<(Rect, PortalRef)> {
let pos = self.cursor_hotspot;
let x = pos.0 as f64;
let y = pos.1 as f64;
if let Some(InputCapture {
pos, ref portal_ref,..
}) = self.input_capture
{
Some((pos, portal_ref.clone()))
} else {
for buffer in self.buffers.iter() {
let ScreenBuffer {
pos, ref portal_ref,..
} = *buffer;
if pos.contains(x, y) {
return Some((pos, portal_ref.clone()));
}
}
None
}
}
#[cfg(target_os = "rust_os")]
pub fn update_mouse_state_delta(&mut self, dx: i16, dy: i16, dw: i8, buttons: [bool; 3]) -> Result<()> {
let x = ((self.cursor_hotspot.0 as i32 + dx as i32).max(0) as u16).min(self.screen_size.0 - 1);
let y = ((self.cursor_hotspot.1 as i32 + dy as i32).max(0) as u16).min(self.screen_size.1 - 1);
self.update_mouse_state(x, y, dw, buttons)
}
pub fn
|
(&mut self, x: u16, y: u16, _dw: i8, buttons: [bool; 3]) -> Result<()> {
let prev_cursor_hotspot = self.cursor_hotspot;
let prev_cursor_sprite = self.cursor_sprite;
let prev_buttons = self.buttons;
self.cursor_hotspot = (x, y);
self.cursor_sprite = to_sprite(self.cursor_hotspot);
self.buttons = buttons;
if let Some((pos, portal_ref)) = self.find_portal() {
let screen_x = x as f64;
let screen_y = y as f64;
let x = screen_x - pos.x;
let y = screen_y - pos.y;
let info = MouseInputInfo {
x,
y,
screen_x,
screen_y,
};
let mut inputs = Vec::new();
if prev_cursor_hotspot!= self.cursor_hotspot {
inputs.push(EventInput::MouseMove { info: info.clone() });
}
for ((&prev_down, &down), &button) in prev_buttons
.iter()
.zip(self.buttons.iter())
.zip([MouseButton::Left, MouseButton::Middle, MouseButton::Right].iter())
{
if!prev_down && down {
inputs.push(EventInput::MouseButtonDown {
info: info.clone(),
button,
});
if self.input_capture.is_none() {
self.input_capture = Some(InputCapture {
button,
pos,
portal_ref: portal_ref.clone(),
});
}
} else if prev_down &&!down {
inputs.push(EventInput::MouseButtonUp {
info: info.clone(),
button,
});
if let Some(InputCapture {
button: prev_button,..
}) = self.input_capture
{
if prev_button == button {
self.input_capture = None;
}
}
}
}
for input in inputs {
portal_ref.send_input(input)?;
}
}
let cr = self
.lfb
.as_surface_mut(CAIRO_FORMAT_ARGB32, self.screen_size)
.into_cairo();
cr.rectangle(prev_cursor_sprite.0, prev_cursor_sprite.1, CURSOR_WIDTH, CURSOR_HEIGHT)
.clip();
Self::draw_buffers(&cr, self.screen_size, &self.wallpaper, &self.buffers);
cr.reset_clip()
.set_source_surface(&self.cursor, self.cursor_sprite.0, self.cursor_sprite.1)
.paint();
Ok(())
}
pub fn update_buffers<I>(&mut self, buffers: I)
where
I: IntoIterator<Item = ScreenBuffer>,
{
let mut prev_input_capture = mem::replace(&mut self.input_capture, None);
self.buffers.clear();
let buffers = buffers.into_iter();
if let (_, Some(capacity)) = buffers.size_hint() {
self.buffers.reserve(capacity);
}
for buffer in buffers {
prev_input_capture = prev_input_capture.and_then(|prev_input_capture| {
if prev_input_capture.portal_ref == buffer.portal_ref {
self.input_capture = Some(InputCapture {
pos: buffer.pos,
..prev_input_capture
});
None
} else {
Some(prev_input_capture)
}
});
self.buffers.push(buffer);
}
let cr = self
.lfb
.as_surface_mut(CAIRO_FORMAT_ARGB32, self.screen_size)
.into_cairo();
Self::draw_buffers(&cr, self.screen_size, &self.wallpaper, &self.buffers);
cr.reset_clip()
.set_source_surface(&self.cursor, self.cursor_sprite.0, self.cursor_sprite.1)
.paint();
}
}
|
update_mouse_state
|
identifier_name
|
screen.rs
|
use crate::portal::PortalRef;
use alloc::sync::Weak;
use cairo::bindings::{CAIRO_FORMAT_A8, CAIRO_FORMAT_ARGB32, CAIRO_FORMAT_RGB24};
use cairo::{Cairo, Surface};
use core::mem;
use graphics_base::frame_buffer::{AsSurface, AsSurfaceMut, FrameBuffer};
use graphics_base::types::{EventInput, MouseButton, MouseInputInfo, Rect};
use graphics_base::{Error, Result};
use jpeg_decoder::{Decoder, ImageInfo, PixelFormat};
const CURSOR_WIDTH: f64 = 32.0;
const CURSOR_HEIGHT: f64 = 32.0;
const CURSOR_HOTSPOT_X: f64 = 12.0;
const CURSOR_HOTSPOT_Y: f64 = 8.0;
pub struct ScreenBuffer {
pub pos: Rect,
pub frame_buffer_size: (u16, u16),
pub frame_buffer: Weak<FrameBuffer>,
pub portal_ref: PortalRef,
}
pub struct InputCapture {
button: MouseButton,
pub pos: Rect,
pub portal_ref: PortalRef,
}
fn to_sprite(hotspot: (u16, u16)) -> (f64, f64) {
(hotspot.0 as f64 - CURSOR_HOTSPOT_X, hotspot.1 as f64 - CURSOR_HOTSPOT_Y)
}
fn surface_from_jpeg_slice(data: &[u8]) -> Result<Surface<'static>> {
let mut decoder = Decoder::new(data);
let data = decoder.decode().map_err(|_| Error::NotSupported)?;
let ImageInfo {
width,
height,
pixel_format,
} = decoder.info().unwrap();
let (data, format) = match pixel_format {
PixelFormat::L8 => (data, CAIRO_FORMAT_A8),
PixelFormat::RGB24 => {
let mut data32 = Vec::with_capacity(width as usize * height as usize * 4);
for chunk in data.chunks_exact(3) {
data32.extend(chunk.iter().rev());
data32.push(0);
}
(data32, CAIRO_FORMAT_RGB24)
}
PixelFormat::CMYK32 => panic!("CMYK not supported"),
};
Ok(Surface::from_vec(data, format, width, height))
}
pub struct Screen<S> {
cursor_hotspot: (u16, u16),
cursor_sprite: (f64, f64),
buttons: [bool; 3],
screen_size: (u16, u16),
lfb: S,
cursor: Surface<'static>,
wallpaper: Surface<'static>,
pub buffers: Vec<ScreenBuffer>,
pub input_capture: Option<InputCapture>,
}
unsafe impl<S> Send for Screen<S> {}
impl<S> Screen<S>
where
S: AsSurfaceMut,
{
pub fn new(screen_size: (u16, u16), lfb: S) -> Self {
static CURSOR_BYTES: &'static [u8] = include_bytes!("icons8-cursor-32.png");
static WALLPAPER_BYTES: &'static [u8] = include_bytes!("wallpaper.jpg");
let cursor = Surface::from_png_slice(CURSOR_BYTES).unwrap();
let cursor_hotspot = (screen_size.0 / 2, screen_size.1 / 2);
let wallpaper = surface_from_jpeg_slice(WALLPAPER_BYTES).unwrap();
Self {
cursor_hotspot,
cursor_sprite: to_sprite(cursor_hotspot),
buttons: [false; 3],
screen_size,
lfb,
cursor,
wallpaper,
buffers: Vec::new(),
input_capture: None,
}
}
fn draw_buffers(cr: &Cairo, screen_size: (u16, u16), wallpaper: &Surface, buffers: &[ScreenBuffer]) {
cr.new_path()
.move_to(0.0, 0.0)
.rel_line_to(0.0, screen_size.1 as f64)
.rel_line_to(screen_size.0 as f64, 0.0)
.rel_line_to(0.0, -(screen_size.1 as f64))
.rel_line_to(-(screen_size.0 as f64), 0.0);
for buffer in buffers {
let ScreenBuffer {
pos: Rect { x, y, width, height },
frame_buffer_size,
ref frame_buffer,
..
} = *buffer;
if let Some(frame_buffer) = frame_buffer.upgrade() {
let surface = frame_buffer.as_surface(CAIRO_FORMAT_RGB24, frame_buffer_size);
cr.set_source_surface(&surface, x, y).paint();
}
cr.new_sub_path()
.rectangle(x, y, width, height)
.close_path()
.clip_preserve();
}
cr.set_source_surface(wallpaper, 0.0, 0.0).paint();
}
fn find_portal(&self) -> Option<(Rect, PortalRef)> {
let pos = self.cursor_hotspot;
let x = pos.0 as f64;
let y = pos.1 as f64;
if let Some(InputCapture {
pos, ref portal_ref,..
}) = self.input_capture
{
Some((pos, portal_ref.clone()))
} else {
for buffer in self.buffers.iter() {
let ScreenBuffer {
pos, ref portal_ref,..
} = *buffer;
if pos.contains(x, y) {
return Some((pos, portal_ref.clone()));
}
}
None
}
}
#[cfg(target_os = "rust_os")]
pub fn update_mouse_state_delta(&mut self, dx: i16, dy: i16, dw: i8, buttons: [bool; 3]) -> Result<()> {
let x = ((self.cursor_hotspot.0 as i32 + dx as i32).max(0) as u16).min(self.screen_size.0 - 1);
let y = ((self.cursor_hotspot.1 as i32 + dy as i32).max(0) as u16).min(self.screen_size.1 - 1);
self.update_mouse_state(x, y, dw, buttons)
}
pub fn update_mouse_state(&mut self, x: u16, y: u16, _dw: i8, buttons: [bool; 3]) -> Result<()> {
let prev_cursor_hotspot = self.cursor_hotspot;
let prev_cursor_sprite = self.cursor_sprite;
let prev_buttons = self.buttons;
self.cursor_hotspot = (x, y);
self.cursor_sprite = to_sprite(self.cursor_hotspot);
self.buttons = buttons;
if let Some((pos, portal_ref)) = self.find_portal() {
let screen_x = x as f64;
let screen_y = y as f64;
let x = screen_x - pos.x;
let y = screen_y - pos.y;
let info = MouseInputInfo {
x,
y,
screen_x,
screen_y,
};
let mut inputs = Vec::new();
if prev_cursor_hotspot!= self.cursor_hotspot {
inputs.push(EventInput::MouseMove { info: info.clone() });
}
for ((&prev_down, &down), &button) in prev_buttons
.iter()
.zip(self.buttons.iter())
.zip([MouseButton::Left, MouseButton::Middle, MouseButton::Right].iter())
{
if!prev_down && down {
inputs.push(EventInput::MouseButtonDown {
info: info.clone(),
button,
});
if self.input_capture.is_none() {
self.input_capture = Some(InputCapture {
button,
pos,
portal_ref: portal_ref.clone(),
});
}
} else if prev_down &&!down {
inputs.push(EventInput::MouseButtonUp {
info: info.clone(),
button,
});
if let Some(InputCapture {
button: prev_button,..
}) = self.input_capture
{
if prev_button == button
|
}
}
}
for input in inputs {
portal_ref.send_input(input)?;
}
}
let cr = self
.lfb
.as_surface_mut(CAIRO_FORMAT_ARGB32, self.screen_size)
.into_cairo();
cr.rectangle(prev_cursor_sprite.0, prev_cursor_sprite.1, CURSOR_WIDTH, CURSOR_HEIGHT)
.clip();
Self::draw_buffers(&cr, self.screen_size, &self.wallpaper, &self.buffers);
cr.reset_clip()
.set_source_surface(&self.cursor, self.cursor_sprite.0, self.cursor_sprite.1)
.paint();
Ok(())
}
pub fn update_buffers<I>(&mut self, buffers: I)
where
I: IntoIterator<Item = ScreenBuffer>,
{
let mut prev_input_capture = mem::replace(&mut self.input_capture, None);
self.buffers.clear();
let buffers = buffers.into_iter();
if let (_, Some(capacity)) = buffers.size_hint() {
self.buffers.reserve(capacity);
}
for buffer in buffers {
prev_input_capture = prev_input_capture.and_then(|prev_input_capture| {
if prev_input_capture.portal_ref == buffer.portal_ref {
self.input_capture = Some(InputCapture {
pos: buffer.pos,
..prev_input_capture
});
None
} else {
Some(prev_input_capture)
}
});
self.buffers.push(buffer);
}
let cr = self
.lfb
.as_surface_mut(CAIRO_FORMAT_ARGB32, self.screen_size)
.into_cairo();
Self::draw_buffers(&cr, self.screen_size, &self.wallpaper, &self.buffers);
cr.reset_clip()
.set_source_surface(&self.cursor, self.cursor_sprite.0, self.cursor_sprite.1)
.paint();
}
}
|
{
self.input_capture = None;
}
|
conditional_block
|
normalization.rs
|
// Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Unicode normalization algorithms.
//!
//! This module implements _Unicode Normalization Forms_ as defined by [Unicode Standard
//! Annex #15][UAX-15]. Unicode normalization is used to ensure that visually equivalent
//! strings have equivalent binary representations.
//!
//! [UAX-15]: http://www.unicode.org/reports/tr15/
use std::iter::{FromIterator, IntoIterator};
use tables::{decomposition_mappings, composition_mappings};
use util::charcc;
//
// Definitions of Normalization Forms
//
/// Normalize a string according to **Normalization Form D** (_D118_).
pub fn nfd(s: &str) -> String {
if already_normalized(s, NormalizationForm::D) {
return s.to_owned();
}
let v = canonical_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KD** (_D119_).
pub fn nfkd(s: &str) -> String {
if already_normalized(s, NormalizationForm::KD) {
return s.to_owned();
}
let v = compatibility_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form C** (_D120_).
pub fn nfc(s: &str) -> String {
if already_normalized(s, NormalizationForm::C) {
return s.to_owned();
}
let mut v = canonical_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KC** (_D121_).
pub fn nfkc(s: &str) -> String {
if already_normalized(s, NormalizationForm::KC) {
return s.to_owned();
}
let mut v = compatibility_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
fn cleaned_up_string(normalized: Vec<charcc>) -> String {
String::from_iter(normalized.iter().map(|cc| cc.to_char()))
}
//
// Quick check
//
enum NormalizationForm { C, D, KC, KD }
/// Check whether a string is already in the specified normalization form.
fn already_normalized(s: &str, form: NormalizationForm) -> bool {
use tables::properties::canonical_combining_class as ccc;
use tables::{quick_check};
let mut last_ccc = 0;
for c in s.chars() {
// ASCII text is always normalized in any form.
if c <= '\u{7F}' {
last_ccc = 0;
continue;
}
let this_ccc = ccc(c);
// The string is not normalized if canonical ordering is not observed.
if (last_ccc > this_ccc) && (this_ccc!= 0) {
return false;
}
// Finally check for explicit exceptions.
let not_allowed = match form {
NormalizationForm::C => quick_check::not_allowed_in_nfc(c),
NormalizationForm::D => quick_check::not_allowed_in_nfd(c),
NormalizationForm::KC => quick_check::not_allowed_in_nfkc(c),
NormalizationForm::KD => quick_check::not_allowed_in_nfkd(c),
};
if not_allowed {
return false;
}
last_ccc = this_ccc;
}
return true;
}
//
// Decomposition
//
/// Produce a Compatibility decomposition (D65) of a character sequence.
fn compatibility_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_compatibility_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Produce a Canonical decomposition (D68) of a character sequence.
fn canonical_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_canonical_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Push a Compatibility decomposition (D65) of a single character into the given buffer.
fn push_compatibility_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::compatibility_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
/// Push a Canonical decomposition (D68) of a single character into the given buffer.
fn push_canonical_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::canonical_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
//
// Conjoining Jamo Behavior
//
const S_BASE: u32 = 0xAC00;
const L_BASE: u32 = 0x1100;
const V_BASE: u32 = 0x1161;
const T_BASE: u32 = 0x11A7;
const L_COUNT: u32 = 19;
const V_COUNT: u32 = 21;
const T_COUNT: u32 = 28;
const N_COUNT: u32 = V_COUNT * T_COUNT;
const S_COUNT: u32 = L_COUNT * N_COUNT;
/// If a character is a Precomposed Hangul syllable (D132) then push its full decomposition into
/// the given buffer and return true. Otherwise do not modify the buffer and return false.
fn push_hangul_decomposition(c: char, vec: &mut Vec<charcc>) -> bool {
use std::char;
if ((c as u32) < S_BASE) || ((S_BASE + S_COUNT) <= (c as u32)) {
return false;
}
let s_index = (c as u32) - S_BASE;
let l_index = s_index / N_COUNT;
let v_index = (s_index % N_COUNT) / T_COUNT;
let t_index = s_index % T_COUNT;
// Computed Hangul syllables are guaranteed to be valid Unicode codepoints (cf. ranges).
// They also have been assigned canonical combining class zero and canonical combining
// class is guaranteed to not change in Unicode, so we can save a table lookup on that.
if t_index > 0 {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
let t = unsafe { char::from_u32_unchecked(T_BASE + t_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
vec.push(charcc::from_char_with_ccc(t, 0));
} else {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
}
return true;
}
/// If a character pair forms a Precomposed Hangul syllable (D132) when it is canonically composed
/// then return this Some composition. Otherwise return None.
fn compose_hangul(c1: char, c2: char) -> Option<charcc> {
use std::char;
// In the same way as with decomposition, arithmetics and character ranges guarantee codepoint
// validity here, and precomposed Hangul syllables also have canonical combining class zero.
// <L, V> pair
if ((L_BASE <= (c1 as u32)) && ((c1 as u32) < L_BASE + L_COUNT)) &&
((V_BASE <= (c2 as u32)) && ((c2 as u32) < V_BASE + V_COUNT))
{
let l_index = (c1 as u32) - L_BASE;
let v_index = (c2 as u32) - V_BASE;
let lv_index = l_index * N_COUNT + v_index * T_COUNT;
// This is safe as the codepoint is guaranteed to have correct value.
let lv = unsafe { char::from_u32_unchecked(S_BASE + lv_index) };
return Some(charcc::from_char_with_ccc(lv, 0));
}
// <LV, T> pair
if ((S_BASE <= (c1 as u32)) && ((c1 as u32) < S_BASE + S_COUNT)) &&
(((c1 as u32) - S_BASE) % T_COUNT == 0) &&
(((T_BASE + 1) <= (c2 as u32)) && ((c2 as u32) < T_BASE + T_COUNT))
{
let t_index = (c2 as u32) - T_BASE;
// This is safe as the codepoint is guaranteed to have correct value.
let lvt = unsafe { char::from_u32_unchecked((c1 as u32) + t_index) };
return Some(charcc::from_char_with_ccc(lvt, 0));
}
// Anything else
return None;
}
//
// Canonical Ordering Algorithm
//
/// Apply the Canonical Ordering Algorithm (D109) to a character slice.
fn reorder_canonically(slice: &mut [charcc]) {
// Actually, this is a bubble sort, but with one important detail: starter characters are never
// reordered. That is, we must sort only the grapheme clusters. Therefore we can replace O(n^2)
// bubble sort of the entire string with an O(n) pass over the clusters. Each grapheme cluster
// still takes O(n^2) time to sort. However, in this case 'n' is the length of the cluster,
// which is a small number in real-world texts (less than 10 in sane texts, usually 2..5).
// And usually the combining marks are almost sorted, so the bubble sort works just fine.
let len = slice.len();
let mut cur = 0;
while cur < len {
// Skip over sequences of starters. We are looking for non-starters.
if slice[cur].ccc() == 0 {
cur += 1;
continue;
}
// Now find the next starter so we know where to stop.
let mut next = cur + 1;
while next < len {
if slice[next].ccc() == 0 {
break;
}
next += 1;
}
// Apply bubble sort to the cluster.
for limit in (cur..next).rev() {
for i in cur..limit {
if slice[i].ccc() > slice[i + 1].ccc() {
slice.swap(i, i + 1);
}
}
}
// We're done with this cluster, move on to the next one.
cur = next;
}
}
//
// Canonical Composition Algorithm
//
/// Apply the Canonical Composition Algorithm (D117) to a character buffer.
fn compose_canonically(buffer: &mut Vec<charcc>) {
let mut ci = 1;
while ci < buffer.len() {
if let Some(li) = find_starter(&buffer[..], ci) {
if!blocked(&buffer[..], li, ci) {
let (l, c) = (buffer[li].to_char(), buffer[ci].to_char());
if let Some(p) = primary_composite(l, c) {
buffer[li] = p;
buffer.remove(ci);
continue;
}
}
}
ci += 1;
}
}
/// Find the last Starter (D107) preceding C in a character slice.
/// This is step R1 of the Canonical Composition Algorithm (D117).
fn find_starter(slice: &[charcc], ci: usize) -> Option<usize> {
for li in (0..ci).rev() {
if slice[li].ccc() == 0 {
return Some(li);
}
}
return None;
}
/// Verify that A is not blocked (D115) from C in a character slice.
/// This is the first part of step R2 of the Canonical Composition Algorithm (D117).
fn blocked(slice: &[charcc], ai: usize, ci: usize) -> bool
|
/// Check for a Primary Composite (D114) equivalent to the given pair of characters.
/// This is the second part of step R2 of the Canonical Composition Algorithm (D117).
fn primary_composite(c1: char, c2: char) -> Option<charcc> {
compose_hangul(c1, c2).or_else(|| composition_mappings::primary(c1, c2))
}
|
{
assert!(ai < ci);
let ccc_a = slice[ai].ccc();
let ccc_c = slice[ci].ccc();
if ccc_a == 0 {
for bi in (ai + 1)..ci {
let ccc_b = slice[bi].ccc();
if (ccc_b == 0) || (ccc_b >= ccc_c) {
return true;
}
}
}
return false;
}
|
identifier_body
|
normalization.rs
|
// Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Unicode normalization algorithms.
//!
//! This module implements _Unicode Normalization Forms_ as defined by [Unicode Standard
//! Annex #15][UAX-15]. Unicode normalization is used to ensure that visually equivalent
//! strings have equivalent binary representations.
//!
//! [UAX-15]: http://www.unicode.org/reports/tr15/
use std::iter::{FromIterator, IntoIterator};
use tables::{decomposition_mappings, composition_mappings};
use util::charcc;
//
// Definitions of Normalization Forms
//
/// Normalize a string according to **Normalization Form D** (_D118_).
pub fn nfd(s: &str) -> String {
if already_normalized(s, NormalizationForm::D) {
return s.to_owned();
}
let v = canonical_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KD** (_D119_).
pub fn nfkd(s: &str) -> String {
if already_normalized(s, NormalizationForm::KD) {
return s.to_owned();
}
let v = compatibility_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form C** (_D120_).
pub fn nfc(s: &str) -> String {
if already_normalized(s, NormalizationForm::C) {
return s.to_owned();
}
let mut v = canonical_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KC** (_D121_).
pub fn nfkc(s: &str) -> String {
if already_normalized(s, NormalizationForm::KC) {
return s.to_owned();
}
let mut v = compatibility_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
fn cleaned_up_string(normalized: Vec<charcc>) -> String {
String::from_iter(normalized.iter().map(|cc| cc.to_char()))
}
//
// Quick check
//
enum NormalizationForm { C, D, KC, KD }
/// Check whether a string is already in the specified normalization form.
fn already_normalized(s: &str, form: NormalizationForm) -> bool {
use tables::properties::canonical_combining_class as ccc;
use tables::{quick_check};
let mut last_ccc = 0;
for c in s.chars() {
// ASCII text is always normalized in any form.
if c <= '\u{7F}' {
last_ccc = 0;
continue;
}
let this_ccc = ccc(c);
// The string is not normalized if canonical ordering is not observed.
if (last_ccc > this_ccc) && (this_ccc!= 0) {
return false;
}
// Finally check for explicit exceptions.
let not_allowed = match form {
NormalizationForm::C => quick_check::not_allowed_in_nfc(c),
NormalizationForm::D => quick_check::not_allowed_in_nfd(c),
NormalizationForm::KC => quick_check::not_allowed_in_nfkc(c),
NormalizationForm::KD => quick_check::not_allowed_in_nfkd(c),
};
if not_allowed {
return false;
}
last_ccc = this_ccc;
}
return true;
}
//
// Decomposition
//
/// Produce a Compatibility decomposition (D65) of a character sequence.
fn compatibility_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_compatibility_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Produce a Canonical decomposition (D68) of a character sequence.
fn canonical_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_canonical_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Push a Compatibility decomposition (D65) of a single character into the given buffer.
fn push_compatibility_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::compatibility_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
/// Push a Canonical decomposition (D68) of a single character into the given buffer.
fn push_canonical_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::canonical_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
//
// Conjoining Jamo Behavior
//
const S_BASE: u32 = 0xAC00;
const L_BASE: u32 = 0x1100;
const V_BASE: u32 = 0x1161;
const T_BASE: u32 = 0x11A7;
const L_COUNT: u32 = 19;
const V_COUNT: u32 = 21;
const T_COUNT: u32 = 28;
const N_COUNT: u32 = V_COUNT * T_COUNT;
const S_COUNT: u32 = L_COUNT * N_COUNT;
/// If a character is a Precomposed Hangul syllable (D132) then push its full decomposition into
/// the given buffer and return true. Otherwise do not modify the buffer and return false.
fn push_hangul_decomposition(c: char, vec: &mut Vec<charcc>) -> bool {
use std::char;
if ((c as u32) < S_BASE) || ((S_BASE + S_COUNT) <= (c as u32)) {
return false;
}
let s_index = (c as u32) - S_BASE;
let l_index = s_index / N_COUNT;
let v_index = (s_index % N_COUNT) / T_COUNT;
let t_index = s_index % T_COUNT;
// Computed Hangul syllables are guaranteed to be valid Unicode codepoints (cf. ranges).
// They also have been assigned canonical combining class zero and canonical combining
// class is guaranteed to not change in Unicode, so we can save a table lookup on that.
if t_index > 0 {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
let t = unsafe { char::from_u32_unchecked(T_BASE + t_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
vec.push(charcc::from_char_with_ccc(t, 0));
} else {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
}
return true;
}
/// If a character pair forms a Precomposed Hangul syllable (D132) when it is canonically composed
/// then return this Some composition. Otherwise return None.
fn compose_hangul(c1: char, c2: char) -> Option<charcc> {
use std::char;
// In the same way as with decomposition, arithmetics and character ranges guarantee codepoint
// validity here, and precomposed Hangul syllables also have canonical combining class zero.
// <L, V> pair
if ((L_BASE <= (c1 as u32)) && ((c1 as u32) < L_BASE + L_COUNT)) &&
((V_BASE <= (c2 as u32)) && ((c2 as u32) < V_BASE + V_COUNT))
{
let l_index = (c1 as u32) - L_BASE;
let v_index = (c2 as u32) - V_BASE;
let lv_index = l_index * N_COUNT + v_index * T_COUNT;
// This is safe as the codepoint is guaranteed to have correct value.
let lv = unsafe { char::from_u32_unchecked(S_BASE + lv_index) };
return Some(charcc::from_char_with_ccc(lv, 0));
}
// <LV, T> pair
if ((S_BASE <= (c1 as u32)) && ((c1 as u32) < S_BASE + S_COUNT)) &&
(((c1 as u32) - S_BASE) % T_COUNT == 0) &&
(((T_BASE + 1) <= (c2 as u32)) && ((c2 as u32) < T_BASE + T_COUNT))
{
let t_index = (c2 as u32) - T_BASE;
// This is safe as the codepoint is guaranteed to have correct value.
let lvt = unsafe { char::from_u32_unchecked((c1 as u32) + t_index) };
return Some(charcc::from_char_with_ccc(lvt, 0));
}
// Anything else
return None;
}
//
// Canonical Ordering Algorithm
//
/// Apply the Canonical Ordering Algorithm (D109) to a character slice.
fn reorder_canonically(slice: &mut [charcc]) {
// Actually, this is a bubble sort, but with one important detail: starter characters are never
// reordered. That is, we must sort only the grapheme clusters. Therefore we can replace O(n^2)
// bubble sort of the entire string with an O(n) pass over the clusters. Each grapheme cluster
// still takes O(n^2) time to sort. However, in this case 'n' is the length of the cluster,
// which is a small number in real-world texts (less than 10 in sane texts, usually 2..5).
// And usually the combining marks are almost sorted, so the bubble sort works just fine.
let len = slice.len();
let mut cur = 0;
while cur < len {
// Skip over sequences of starters. We are looking for non-starters.
if slice[cur].ccc() == 0 {
cur += 1;
continue;
}
// Now find the next starter so we know where to stop.
let mut next = cur + 1;
while next < len {
if slice[next].ccc() == 0 {
break;
}
next += 1;
}
// Apply bubble sort to the cluster.
for limit in (cur..next).rev() {
for i in cur..limit {
if slice[i].ccc() > slice[i + 1].ccc() {
slice.swap(i, i + 1);
}
}
}
// We're done with this cluster, move on to the next one.
cur = next;
}
}
//
// Canonical Composition Algorithm
//
/// Apply the Canonical Composition Algorithm (D117) to a character buffer.
fn compose_canonically(buffer: &mut Vec<charcc>) {
let mut ci = 1;
while ci < buffer.len() {
if let Some(li) = find_starter(&buffer[..], ci) {
if!blocked(&buffer[..], li, ci) {
let (l, c) = (buffer[li].to_char(), buffer[ci].to_char());
if let Some(p) = primary_composite(l, c) {
buffer[li] = p;
buffer.remove(ci);
continue;
}
}
}
ci += 1;
}
}
/// Find the last Starter (D107) preceding C in a character slice.
/// This is step R1 of the Canonical Composition Algorithm (D117).
fn
|
(slice: &[charcc], ci: usize) -> Option<usize> {
for li in (0..ci).rev() {
if slice[li].ccc() == 0 {
return Some(li);
}
}
return None;
}
/// Verify that A is not blocked (D115) from C in a character slice.
/// This is the first part of step R2 of the Canonical Composition Algorithm (D117).
fn blocked(slice: &[charcc], ai: usize, ci: usize) -> bool {
assert!(ai < ci);
let ccc_a = slice[ai].ccc();
let ccc_c = slice[ci].ccc();
if ccc_a == 0 {
for bi in (ai + 1)..ci {
let ccc_b = slice[bi].ccc();
if (ccc_b == 0) || (ccc_b >= ccc_c) {
return true;
}
}
}
return false;
}
/// Check for a Primary Composite (D114) equivalent to the given pair of characters.
/// This is the second part of step R2 of the Canonical Composition Algorithm (D117).
fn primary_composite(c1: char, c2: char) -> Option<charcc> {
compose_hangul(c1, c2).or_else(|| composition_mappings::primary(c1, c2))
}
|
find_starter
|
identifier_name
|
normalization.rs
|
// Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Unicode normalization algorithms.
//!
//! This module implements _Unicode Normalization Forms_ as defined by [Unicode Standard
//! Annex #15][UAX-15]. Unicode normalization is used to ensure that visually equivalent
//! strings have equivalent binary representations.
//!
//! [UAX-15]: http://www.unicode.org/reports/tr15/
use std::iter::{FromIterator, IntoIterator};
use tables::{decomposition_mappings, composition_mappings};
use util::charcc;
//
// Definitions of Normalization Forms
//
/// Normalize a string according to **Normalization Form D** (_D118_).
pub fn nfd(s: &str) -> String {
if already_normalized(s, NormalizationForm::D) {
return s.to_owned();
}
let v = canonical_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KD** (_D119_).
pub fn nfkd(s: &str) -> String {
if already_normalized(s, NormalizationForm::KD) {
return s.to_owned();
}
let v = compatibility_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form C** (_D120_).
pub fn nfc(s: &str) -> String {
if already_normalized(s, NormalizationForm::C) {
return s.to_owned();
}
let mut v = canonical_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KC** (_D121_).
pub fn nfkc(s: &str) -> String {
if already_normalized(s, NormalizationForm::KC) {
return s.to_owned();
}
let mut v = compatibility_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
fn cleaned_up_string(normalized: Vec<charcc>) -> String {
String::from_iter(normalized.iter().map(|cc| cc.to_char()))
}
//
// Quick check
//
enum NormalizationForm { C, D, KC, KD }
/// Check whether a string is already in the specified normalization form.
fn already_normalized(s: &str, form: NormalizationForm) -> bool {
use tables::properties::canonical_combining_class as ccc;
use tables::{quick_check};
let mut last_ccc = 0;
for c in s.chars() {
// ASCII text is always normalized in any form.
if c <= '\u{7F}' {
last_ccc = 0;
continue;
}
let this_ccc = ccc(c);
// The string is not normalized if canonical ordering is not observed.
if (last_ccc > this_ccc) && (this_ccc!= 0) {
return false;
}
// Finally check for explicit exceptions.
let not_allowed = match form {
NormalizationForm::C => quick_check::not_allowed_in_nfc(c),
NormalizationForm::D => quick_check::not_allowed_in_nfd(c),
NormalizationForm::KC => quick_check::not_allowed_in_nfkc(c),
NormalizationForm::KD => quick_check::not_allowed_in_nfkd(c),
};
if not_allowed
|
last_ccc = this_ccc;
}
return true;
}
//
// Decomposition
//
/// Produce a Compatibility decomposition (D65) of a character sequence.
fn compatibility_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_compatibility_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Produce a Canonical decomposition (D68) of a character sequence.
fn canonical_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_canonical_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Push a Compatibility decomposition (D65) of a single character into the given buffer.
fn push_compatibility_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::compatibility_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
/// Push a Canonical decomposition (D68) of a single character into the given buffer.
fn push_canonical_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::canonical_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
//
// Conjoining Jamo Behavior
//
const S_BASE: u32 = 0xAC00;
const L_BASE: u32 = 0x1100;
const V_BASE: u32 = 0x1161;
const T_BASE: u32 = 0x11A7;
const L_COUNT: u32 = 19;
const V_COUNT: u32 = 21;
const T_COUNT: u32 = 28;
const N_COUNT: u32 = V_COUNT * T_COUNT;
const S_COUNT: u32 = L_COUNT * N_COUNT;
/// If a character is a Precomposed Hangul syllable (D132) then push its full decomposition into
/// the given buffer and return true. Otherwise do not modify the buffer and return false.
fn push_hangul_decomposition(c: char, vec: &mut Vec<charcc>) -> bool {
use std::char;
if ((c as u32) < S_BASE) || ((S_BASE + S_COUNT) <= (c as u32)) {
return false;
}
let s_index = (c as u32) - S_BASE;
let l_index = s_index / N_COUNT;
let v_index = (s_index % N_COUNT) / T_COUNT;
let t_index = s_index % T_COUNT;
// Computed Hangul syllables are guaranteed to be valid Unicode codepoints (cf. ranges).
// They also have been assigned canonical combining class zero and canonical combining
// class is guaranteed to not change in Unicode, so we can save a table lookup on that.
if t_index > 0 {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
let t = unsafe { char::from_u32_unchecked(T_BASE + t_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
vec.push(charcc::from_char_with_ccc(t, 0));
} else {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
}
return true;
}
/// If a character pair forms a Precomposed Hangul syllable (D132) when it is canonically composed
/// then return this Some composition. Otherwise return None.
fn compose_hangul(c1: char, c2: char) -> Option<charcc> {
use std::char;
// In the same way as with decomposition, arithmetics and character ranges guarantee codepoint
// validity here, and precomposed Hangul syllables also have canonical combining class zero.
// <L, V> pair
if ((L_BASE <= (c1 as u32)) && ((c1 as u32) < L_BASE + L_COUNT)) &&
((V_BASE <= (c2 as u32)) && ((c2 as u32) < V_BASE + V_COUNT))
{
let l_index = (c1 as u32) - L_BASE;
let v_index = (c2 as u32) - V_BASE;
let lv_index = l_index * N_COUNT + v_index * T_COUNT;
// This is safe as the codepoint is guaranteed to have correct value.
let lv = unsafe { char::from_u32_unchecked(S_BASE + lv_index) };
return Some(charcc::from_char_with_ccc(lv, 0));
}
// <LV, T> pair
if ((S_BASE <= (c1 as u32)) && ((c1 as u32) < S_BASE + S_COUNT)) &&
(((c1 as u32) - S_BASE) % T_COUNT == 0) &&
(((T_BASE + 1) <= (c2 as u32)) && ((c2 as u32) < T_BASE + T_COUNT))
{
let t_index = (c2 as u32) - T_BASE;
// This is safe as the codepoint is guaranteed to have correct value.
let lvt = unsafe { char::from_u32_unchecked((c1 as u32) + t_index) };
return Some(charcc::from_char_with_ccc(lvt, 0));
}
// Anything else
return None;
}
//
// Canonical Ordering Algorithm
//
/// Apply the Canonical Ordering Algorithm (D109) to a character slice.
fn reorder_canonically(slice: &mut [charcc]) {
// Actually, this is a bubble sort, but with one important detail: starter characters are never
// reordered. That is, we must sort only the grapheme clusters. Therefore we can replace O(n^2)
// bubble sort of the entire string with an O(n) pass over the clusters. Each grapheme cluster
// still takes O(n^2) time to sort. However, in this case 'n' is the length of the cluster,
// which is a small number in real-world texts (less than 10 in sane texts, usually 2..5).
// And usually the combining marks are almost sorted, so the bubble sort works just fine.
let len = slice.len();
let mut cur = 0;
while cur < len {
// Skip over sequences of starters. We are looking for non-starters.
if slice[cur].ccc() == 0 {
cur += 1;
continue;
}
// Now find the next starter so we know where to stop.
let mut next = cur + 1;
while next < len {
if slice[next].ccc() == 0 {
break;
}
next += 1;
}
// Apply bubble sort to the cluster.
for limit in (cur..next).rev() {
for i in cur..limit {
if slice[i].ccc() > slice[i + 1].ccc() {
slice.swap(i, i + 1);
}
}
}
// We're done with this cluster, move on to the next one.
cur = next;
}
}
//
// Canonical Composition Algorithm
//
/// Apply the Canonical Composition Algorithm (D117) to a character buffer.
fn compose_canonically(buffer: &mut Vec<charcc>) {
let mut ci = 1;
while ci < buffer.len() {
if let Some(li) = find_starter(&buffer[..], ci) {
if!blocked(&buffer[..], li, ci) {
let (l, c) = (buffer[li].to_char(), buffer[ci].to_char());
if let Some(p) = primary_composite(l, c) {
buffer[li] = p;
buffer.remove(ci);
continue;
}
}
}
ci += 1;
}
}
/// Find the last Starter (D107) preceding C in a character slice.
/// This is step R1 of the Canonical Composition Algorithm (D117).
fn find_starter(slice: &[charcc], ci: usize) -> Option<usize> {
for li in (0..ci).rev() {
if slice[li].ccc() == 0 {
return Some(li);
}
}
return None;
}
/// Verify that A is not blocked (D115) from C in a character slice.
/// This is the first part of step R2 of the Canonical Composition Algorithm (D117).
fn blocked(slice: &[charcc], ai: usize, ci: usize) -> bool {
assert!(ai < ci);
let ccc_a = slice[ai].ccc();
let ccc_c = slice[ci].ccc();
if ccc_a == 0 {
for bi in (ai + 1)..ci {
let ccc_b = slice[bi].ccc();
if (ccc_b == 0) || (ccc_b >= ccc_c) {
return true;
}
}
}
return false;
}
/// Check for a Primary Composite (D114) equivalent to the given pair of characters.
/// This is the second part of step R2 of the Canonical Composition Algorithm (D117).
fn primary_composite(c1: char, c2: char) -> Option<charcc> {
compose_hangul(c1, c2).or_else(|| composition_mappings::primary(c1, c2))
}
|
{
return false;
}
|
conditional_block
|
normalization.rs
|
// Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
|
//! This module implements _Unicode Normalization Forms_ as defined by [Unicode Standard
//! Annex #15][UAX-15]. Unicode normalization is used to ensure that visually equivalent
//! strings have equivalent binary representations.
//!
//! [UAX-15]: http://www.unicode.org/reports/tr15/
use std::iter::{FromIterator, IntoIterator};
use tables::{decomposition_mappings, composition_mappings};
use util::charcc;
//
// Definitions of Normalization Forms
//
/// Normalize a string according to **Normalization Form D** (_D118_).
pub fn nfd(s: &str) -> String {
if already_normalized(s, NormalizationForm::D) {
return s.to_owned();
}
let v = canonical_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KD** (_D119_).
pub fn nfkd(s: &str) -> String {
if already_normalized(s, NormalizationForm::KD) {
return s.to_owned();
}
let v = compatibility_decomposition(s.chars());
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form C** (_D120_).
pub fn nfc(s: &str) -> String {
if already_normalized(s, NormalizationForm::C) {
return s.to_owned();
}
let mut v = canonical_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
/// Normalize a string according to **Normalization Form KC** (_D121_).
pub fn nfkc(s: &str) -> String {
if already_normalized(s, NormalizationForm::KC) {
return s.to_owned();
}
let mut v = compatibility_decomposition(s.chars());
compose_canonically(&mut v);
return cleaned_up_string(v);
}
fn cleaned_up_string(normalized: Vec<charcc>) -> String {
String::from_iter(normalized.iter().map(|cc| cc.to_char()))
}
//
// Quick check
//
enum NormalizationForm { C, D, KC, KD }
/// Check whether a string is already in the specified normalization form.
fn already_normalized(s: &str, form: NormalizationForm) -> bool {
use tables::properties::canonical_combining_class as ccc;
use tables::{quick_check};
let mut last_ccc = 0;
for c in s.chars() {
// ASCII text is always normalized in any form.
if c <= '\u{7F}' {
last_ccc = 0;
continue;
}
let this_ccc = ccc(c);
// The string is not normalized if canonical ordering is not observed.
if (last_ccc > this_ccc) && (this_ccc!= 0) {
return false;
}
// Finally check for explicit exceptions.
let not_allowed = match form {
NormalizationForm::C => quick_check::not_allowed_in_nfc(c),
NormalizationForm::D => quick_check::not_allowed_in_nfd(c),
NormalizationForm::KC => quick_check::not_allowed_in_nfkc(c),
NormalizationForm::KD => quick_check::not_allowed_in_nfkd(c),
};
if not_allowed {
return false;
}
last_ccc = this_ccc;
}
return true;
}
//
// Decomposition
//
/// Produce a Compatibility decomposition (D65) of a character sequence.
fn compatibility_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_compatibility_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Produce a Canonical decomposition (D68) of a character sequence.
fn canonical_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push_canonical_decomposition(c, &mut buffer);
}
reorder_canonically(&mut buffer[..]);
return buffer;
}
/// Push a Compatibility decomposition (D65) of a single character into the given buffer.
fn push_compatibility_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::compatibility_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
/// Push a Canonical decomposition (D68) of a single character into the given buffer.
fn push_canonical_decomposition(c: char, vec: &mut Vec<charcc>) {
if push_hangul_decomposition(c, vec) {
return;
}
match decomposition_mappings::canonical_mapping(c) {
Some(decomposition) => {
vec.extend_from_slice(decomposition);
}
None => {
vec.push(charcc::from_char(c));
}
}
}
//
// Conjoining Jamo Behavior
//
const S_BASE: u32 = 0xAC00;
const L_BASE: u32 = 0x1100;
const V_BASE: u32 = 0x1161;
const T_BASE: u32 = 0x11A7;
const L_COUNT: u32 = 19;
const V_COUNT: u32 = 21;
const T_COUNT: u32 = 28;
const N_COUNT: u32 = V_COUNT * T_COUNT;
const S_COUNT: u32 = L_COUNT * N_COUNT;
/// If a character is a Precomposed Hangul syllable (D132) then push its full decomposition into
/// the given buffer and return true. Otherwise do not modify the buffer and return false.
fn push_hangul_decomposition(c: char, vec: &mut Vec<charcc>) -> bool {
use std::char;
if ((c as u32) < S_BASE) || ((S_BASE + S_COUNT) <= (c as u32)) {
return false;
}
let s_index = (c as u32) - S_BASE;
let l_index = s_index / N_COUNT;
let v_index = (s_index % N_COUNT) / T_COUNT;
let t_index = s_index % T_COUNT;
// Computed Hangul syllables are guaranteed to be valid Unicode codepoints (cf. ranges).
// They also have been assigned canonical combining class zero and canonical combining
// class is guaranteed to not change in Unicode, so we can save a table lookup on that.
if t_index > 0 {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
let t = unsafe { char::from_u32_unchecked(T_BASE + t_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
vec.push(charcc::from_char_with_ccc(t, 0));
} else {
// These are safe as codepoints are guaranteed to have correct values.
let l = unsafe { char::from_u32_unchecked(L_BASE + l_index) };
let v = unsafe { char::from_u32_unchecked(V_BASE + v_index) };
vec.push(charcc::from_char_with_ccc(l, 0));
vec.push(charcc::from_char_with_ccc(v, 0));
}
return true;
}
/// If a character pair forms a Precomposed Hangul syllable (D132) when it is canonically composed
/// then return this Some composition. Otherwise return None.
fn compose_hangul(c1: char, c2: char) -> Option<charcc> {
use std::char;
// In the same way as with decomposition, arithmetics and character ranges guarantee codepoint
// validity here, and precomposed Hangul syllables also have canonical combining class zero.
// <L, V> pair
if ((L_BASE <= (c1 as u32)) && ((c1 as u32) < L_BASE + L_COUNT)) &&
((V_BASE <= (c2 as u32)) && ((c2 as u32) < V_BASE + V_COUNT))
{
let l_index = (c1 as u32) - L_BASE;
let v_index = (c2 as u32) - V_BASE;
let lv_index = l_index * N_COUNT + v_index * T_COUNT;
// This is safe as the codepoint is guaranteed to have correct value.
let lv = unsafe { char::from_u32_unchecked(S_BASE + lv_index) };
return Some(charcc::from_char_with_ccc(lv, 0));
}
// <LV, T> pair
if ((S_BASE <= (c1 as u32)) && ((c1 as u32) < S_BASE + S_COUNT)) &&
(((c1 as u32) - S_BASE) % T_COUNT == 0) &&
(((T_BASE + 1) <= (c2 as u32)) && ((c2 as u32) < T_BASE + T_COUNT))
{
let t_index = (c2 as u32) - T_BASE;
// This is safe as the codepoint is guaranteed to have correct value.
let lvt = unsafe { char::from_u32_unchecked((c1 as u32) + t_index) };
return Some(charcc::from_char_with_ccc(lvt, 0));
}
// Anything else
return None;
}
//
// Canonical Ordering Algorithm
//
/// Apply the Canonical Ordering Algorithm (D109) to a character slice.
fn reorder_canonically(slice: &mut [charcc]) {
// Actually, this is a bubble sort, but with one important detail: starter characters are never
// reordered. That is, we must sort only the grapheme clusters. Therefore we can replace O(n^2)
// bubble sort of the entire string with an O(n) pass over the clusters. Each grapheme cluster
// still takes O(n^2) time to sort. However, in this case 'n' is the length of the cluster,
// which is a small number in real-world texts (less than 10 in sane texts, usually 2..5).
// And usually the combining marks are almost sorted, so the bubble sort works just fine.
let len = slice.len();
let mut cur = 0;
while cur < len {
// Skip over sequences of starters. We are looking for non-starters.
if slice[cur].ccc() == 0 {
cur += 1;
continue;
}
// Now find the next starter so we know where to stop.
let mut next = cur + 1;
while next < len {
if slice[next].ccc() == 0 {
break;
}
next += 1;
}
// Apply bubble sort to the cluster.
for limit in (cur..next).rev() {
for i in cur..limit {
if slice[i].ccc() > slice[i + 1].ccc() {
slice.swap(i, i + 1);
}
}
}
// We're done with this cluster, move on to the next one.
cur = next;
}
}
//
// Canonical Composition Algorithm
//
/// Apply the Canonical Composition Algorithm (D117) to a character buffer.
fn compose_canonically(buffer: &mut Vec<charcc>) {
let mut ci = 1;
while ci < buffer.len() {
if let Some(li) = find_starter(&buffer[..], ci) {
if!blocked(&buffer[..], li, ci) {
let (l, c) = (buffer[li].to_char(), buffer[ci].to_char());
if let Some(p) = primary_composite(l, c) {
buffer[li] = p;
buffer.remove(ci);
continue;
}
}
}
ci += 1;
}
}
/// Find the last Starter (D107) preceding C in a character slice.
/// This is step R1 of the Canonical Composition Algorithm (D117).
fn find_starter(slice: &[charcc], ci: usize) -> Option<usize> {
for li in (0..ci).rev() {
if slice[li].ccc() == 0 {
return Some(li);
}
}
return None;
}
/// Verify that A is not blocked (D115) from C in a character slice.
/// This is the first part of step R2 of the Canonical Composition Algorithm (D117).
fn blocked(slice: &[charcc], ai: usize, ci: usize) -> bool {
assert!(ai < ci);
let ccc_a = slice[ai].ccc();
let ccc_c = slice[ci].ccc();
if ccc_a == 0 {
for bi in (ai + 1)..ci {
let ccc_b = slice[bi].ccc();
if (ccc_b == 0) || (ccc_b >= ccc_c) {
return true;
}
}
}
return false;
}
/// Check for a Primary Composite (D114) equivalent to the given pair of characters.
/// This is the second part of step R2 of the Canonical Composition Algorithm (D117).
fn primary_composite(c1: char, c2: char) -> Option<charcc> {
compose_hangul(c1, c2).or_else(|| composition_mappings::primary(c1, c2))
}
|
//! Unicode normalization algorithms.
//!
|
random_line_split
|
generate_lockfile.rs
|
use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct
|
{
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Generate the lockfile for a project
Usage:
cargo generate-lockfile [options]
Options:
-h, --help Print this message
--manifest-path PATH Path to the manifest to generate a lockfile for
-v, --verbose Use verbose output
-q, --quiet No output printed to stdout
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>());
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
ops::generate_lockfile(&root, config)
.map(|_| None).map_err(|err| CliError::from_boxed(err, 101))
}
|
Options
|
identifier_name
|
generate_lockfile.rs
|
use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Generate the lockfile for a project
Usage:
cargo generate-lockfile [options]
Options:
-h, --help Print this message
--manifest-path PATH Path to the manifest to generate a lockfile for
-v, --verbose Use verbose output
-q, --quiet No output printed to stdout
--color WHEN Coloring: auto, always, never
";
|
debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>());
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
ops::generate_lockfile(&root, config)
.map(|_| None).map_err(|err| CliError::from_boxed(err, 101))
}
|
pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
|
random_line_split
|
generate_lockfile.rs
|
use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Generate the lockfile for a project
Usage:
cargo generate-lockfile [options]
Options:
-h, --help Print this message
--manifest-path PATH Path to the manifest to generate a lockfile for
-v, --verbose Use verbose output
-q, --quiet No output printed to stdout
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>>
|
{
debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>());
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
ops::generate_lockfile(&root, config)
.map(|_| None).map_err(|err| CliError::from_boxed(err, 101))
}
|
identifier_body
|
|
access_control_max_age.rs
|
header! {
/// `Access-Control-Max-Age` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-max-age-response-header)
///
/// The `Access-Control-Max-Age` header indicates how long the results of a
/// preflight request can be cached in a preflight result cache.
///
/// # ABNF
/// ```plain
|
/// Access-Control-Max-Age = \"Access-Control-Max-Age\" \":\" delta-seconds
/// ```
///
/// # Example values
/// * `531`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AccessControlMaxAge};
///
/// let mut headers = Headers::new();
/// headers.set(AccessControlMaxAge(1728000u32));
/// ```
(AccessControlMaxAge, "Access-Control-Max-Age") => [u32]
test_access_control_max_age {
test_header!(test1, vec![b"531"]);
}
}
|
random_line_split
|
|
visible-private-types-generics.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {}
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
pub struct S;
impl S {
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
}
pub struct S1<
|
> {
x: T
}
pub struct S2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
x: T
}
pub enum E1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
V1(T)
}
pub enum E2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
V2(T)
}
fn main() {}
|
T
: Foo //~ ERROR private trait in exported type parameter bound
|
random_line_split
|
visible-private-types-generics.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {}
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
pub struct S;
impl S {
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
}
pub struct
|
<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
x: T
}
pub struct S2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
x: T
}
pub enum E1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
V1(T)
}
pub enum E2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
V2(T)
}
fn main() {}
|
S1
|
identifier_name
|
main.rs
|
// main.rs
// Main entry point for a dining philosophers,
// a concurrency problem.
//
// taken from the rust-lang tutorial:
// https://doc.rust-lang.org/stable/book/dining-philosophers.html
//
// vim: ft=rust sw=4 ts=4
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// a philosopher struct
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left,
right,
}
}
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} has started eating.", self.name);
thread::sleep(Duration::from_millis(1000));
println!("{} has finished eating.", self.name);
}
fn
|
(&self, table: &Table, pause: u32, repeat: u32) {
for x in 0..repeat {
thread::sleep(Duration::from_millis(u64::from(pause)));
println!("{} went to table for {}. time.", self.name, (x + 1));
self.eat(table);
}
}
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Friedich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4), // swap "hands" to prevent deadlock
];
let handles: Vec<_> = philosophers
.into_iter()
.map(|p| {
let table = table.clone();
thread::spawn(move || {
//p.eat(&table);
p.mult_eat(&table, 2000, 3);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
|
mult_eat
|
identifier_name
|
main.rs
|
// main.rs
// Main entry point for a dining philosophers,
// a concurrency problem.
//
// taken from the rust-lang tutorial:
// https://doc.rust-lang.org/stable/book/dining-philosophers.html
//
// vim: ft=rust sw=4 ts=4
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// a philosopher struct
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left,
right,
}
|
let _right = table.forks[self.right].lock().unwrap();
println!("{} has started eating.", self.name);
thread::sleep(Duration::from_millis(1000));
println!("{} has finished eating.", self.name);
}
fn mult_eat(&self, table: &Table, pause: u32, repeat: u32) {
for x in 0..repeat {
thread::sleep(Duration::from_millis(u64::from(pause)));
println!("{} went to table for {}. time.", self.name, (x + 1));
self.eat(table);
}
}
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Friedich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4), // swap "hands" to prevent deadlock
];
let handles: Vec<_> = philosophers
.into_iter()
.map(|p| {
let table = table.clone();
thread::spawn(move || {
//p.eat(&table);
p.mult_eat(&table, 2000, 3);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
|
}
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap();
|
random_line_split
|
main.rs
|
// main.rs
// Main entry point for a dining philosophers,
// a concurrency problem.
//
// taken from the rust-lang tutorial:
// https://doc.rust-lang.org/stable/book/dining-philosophers.html
//
// vim: ft=rust sw=4 ts=4
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// a philosopher struct
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher
|
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} has started eating.", self.name);
thread::sleep(Duration::from_millis(1000));
println!("{} has finished eating.", self.name);
}
fn mult_eat(&self, table: &Table, pause: u32, repeat: u32) {
for x in 0..repeat {
thread::sleep(Duration::from_millis(u64::from(pause)));
println!("{} went to table for {}. time.", self.name, (x + 1));
self.eat(table);
}
}
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Friedich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4), // swap "hands" to prevent deadlock
];
let handles: Vec<_> = philosophers
.into_iter()
.map(|p| {
let table = table.clone();
thread::spawn(move || {
//p.eat(&table);
p.mult_eat(&table, 2000, 3);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
|
{
Philosopher {
name: name.to_string(),
left,
right,
}
}
|
identifier_body
|
font_template.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 style::computed_values::font_weight;
use platform::font_context::FontContextHandle;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use sync::{Arc, Weak};
use font::FontHandleMethods;
/// Describes how to select a font from a given family.
/// This is very basic at the moment and needs to be
/// expanded or refactored when we support more of the
/// font styling parameters.
#[deriving(Clone)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
pub fn new(weight: font_weight::T, italic: bool) -> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
italic: italic,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight.is_bold() == other.weight.is_bold() &&
self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: String,
descriptor: Option<FontTemplateDescriptor>,
data: Option<Weak<FontTemplateData>>,
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: &str) -> FontTemplate {
FontTemplate {
identifier: identifier.to_string(),
descriptor: None,
data: None,
}
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn get_if_matches(&mut self, fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor) -> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) => {
if *requested_desc == actual_desc {
Some(self.get_data())
} else {
None
}
|
},
None => {
let data = self.get_data();
let handle = FontHandleMethods::new_from_template(fctx, data.clone(), None);
let handle: FontHandle = match handle {
Ok(handle) => handle,
Err(()) => fail!("TODO - Handle failure to create a font from template."),
};
let actual_desc = FontTemplateDescriptor::new(handle.boldness(),
handle.is_italic());
let desc_match = actual_desc == *requested_desc;
self.descriptor = Some(actual_desc);
if desc_match {
Some(data)
} else {
None
}
}
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn get_data(&mut self) -> Arc<FontTemplateData> {
let maybe_data = match self.data {
Some(ref data) => data.upgrade(),
None => None,
};
match maybe_data {
Some(data) => data,
None => {
let template_data = Arc::new(FontTemplateData::new(self.identifier.as_slice()));
self.data = Some(template_data.downgrade());
template_data
}
}
}
}
|
random_line_split
|
|
font_template.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 style::computed_values::font_weight;
use platform::font_context::FontContextHandle;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use sync::{Arc, Weak};
use font::FontHandleMethods;
/// Describes how to select a font from a given family.
/// This is very basic at the moment and needs to be
/// expanded or refactored when we support more of the
/// font styling parameters.
#[deriving(Clone)]
pub struct
|
{
pub weight: font_weight::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
pub fn new(weight: font_weight::T, italic: bool) -> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
italic: italic,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight.is_bold() == other.weight.is_bold() &&
self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: String,
descriptor: Option<FontTemplateDescriptor>,
data: Option<Weak<FontTemplateData>>,
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: &str) -> FontTemplate {
FontTemplate {
identifier: identifier.to_string(),
descriptor: None,
data: None,
}
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn get_if_matches(&mut self, fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor) -> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) => {
if *requested_desc == actual_desc {
Some(self.get_data())
} else {
None
}
},
None => {
let data = self.get_data();
let handle = FontHandleMethods::new_from_template(fctx, data.clone(), None);
let handle: FontHandle = match handle {
Ok(handle) => handle,
Err(()) => fail!("TODO - Handle failure to create a font from template."),
};
let actual_desc = FontTemplateDescriptor::new(handle.boldness(),
handle.is_italic());
let desc_match = actual_desc == *requested_desc;
self.descriptor = Some(actual_desc);
if desc_match {
Some(data)
} else {
None
}
}
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn get_data(&mut self) -> Arc<FontTemplateData> {
let maybe_data = match self.data {
Some(ref data) => data.upgrade(),
None => None,
};
match maybe_data {
Some(data) => data,
None => {
let template_data = Arc::new(FontTemplateData::new(self.identifier.as_slice()));
self.data = Some(template_data.downgrade());
template_data
}
}
}
}
|
FontTemplateDescriptor
|
identifier_name
|
advent16.rs
|
// advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
if does_sue_match(&input) {
println!("Found match: {}", input.trim());
}
if does_sue_match2(&input) {
println!("Found match part 2: {}", input.trim());
}
}
}
fn does_sue_match(s: &str) -> bool
|
fn check_match_equal(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x == y)
}
// returns false if it has the property and it doesn't match the value
// returns true if the property doesn't exist or it exists but doesn't match
fn check_match<F>(s: &str, property: &str, value: u32, f: F) -> bool
where F: Fn(u32, u32) -> bool {
let mut re = pcre::Pcre::compile(&format!("{}: (\\d+)", property)).unwrap();
if let Some(m) = re.exec(s) {
assert!(m.string_count() > 1);
f(m.group(1).parse::<u32>().unwrap(), value)
} else {
// property doesn't exist
true
}
}
#[test]
fn test_check_match_equal() {
let s = "junk, foo: 4, bar: 5";
assert!(check_match_equal(s, "foo", 4));
assert!(check_match_equal(s, "bar", 5));
assert!(!check_match_equal(s, "foo", 3));
assert!(check_match_equal(s, "string that isn't even there", 5));
}
// part 2
fn check_match_less(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x < y)
}
fn check_match_greater(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x > y)
}
fn does_sue_match2(s: &str) -> bool {
check_match_equal(s, "children", 3)
&& check_match_greater(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_less(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_less(s, "goldfish", 5)
&& check_match_greater(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
&& check_match_equal(s, "perfumes", 1)
}
|
{
check_match_equal(s, "children", 3)
&& check_match_equal(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_equal(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_equal(s, "goldfish", 5)
&& check_match_equal(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
&& check_match_equal(s, "perfumes", 1)
}
|
identifier_body
|
advent16.rs
|
// advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
if does_sue_match(&input) {
println!("Found match: {}", input.trim());
}
if does_sue_match2(&input) {
println!("Found match part 2: {}", input.trim());
}
}
}
fn does_sue_match(s: &str) -> bool {
check_match_equal(s, "children", 3)
&& check_match_equal(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_equal(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_equal(s, "goldfish", 5)
&& check_match_equal(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
&& check_match_equal(s, "perfumes", 1)
}
fn check_match_equal(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x == y)
}
// returns false if it has the property and it doesn't match the value
// returns true if the property doesn't exist or it exists but doesn't match
fn check_match<F>(s: &str, property: &str, value: u32, f: F) -> bool
where F: Fn(u32, u32) -> bool {
let mut re = pcre::Pcre::compile(&format!("{}: (\\d+)", property)).unwrap();
if let Some(m) = re.exec(s) {
assert!(m.string_count() > 1);
f(m.group(1).parse::<u32>().unwrap(), value)
} else {
// property doesn't exist
true
}
}
#[test]
fn
|
() {
let s = "junk, foo: 4, bar: 5";
assert!(check_match_equal(s, "foo", 4));
assert!(check_match_equal(s, "bar", 5));
assert!(!check_match_equal(s, "foo", 3));
assert!(check_match_equal(s, "string that isn't even there", 5));
}
// part 2
fn check_match_less(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x < y)
}
fn check_match_greater(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x > y)
}
fn does_sue_match2(s: &str) -> bool {
check_match_equal(s, "children", 3)
&& check_match_greater(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_less(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_less(s, "goldfish", 5)
&& check_match_greater(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
&& check_match_equal(s, "perfumes", 1)
}
|
test_check_match_equal
|
identifier_name
|
advent16.rs
|
// advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
if does_sue_match(&input) {
println!("Found match: {}", input.trim());
}
if does_sue_match2(&input) {
println!("Found match part 2: {}", input.trim());
}
}
}
fn does_sue_match(s: &str) -> bool {
check_match_equal(s, "children", 3)
&& check_match_equal(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_equal(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_equal(s, "goldfish", 5)
&& check_match_equal(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
&& check_match_equal(s, "perfumes", 1)
}
fn check_match_equal(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x == y)
}
// returns false if it has the property and it doesn't match the value
// returns true if the property doesn't exist or it exists but doesn't match
fn check_match<F>(s: &str, property: &str, value: u32, f: F) -> bool
where F: Fn(u32, u32) -> bool {
let mut re = pcre::Pcre::compile(&format!("{}: (\\d+)", property)).unwrap();
if let Some(m) = re.exec(s)
|
else {
// property doesn't exist
true
}
}
#[test]
fn test_check_match_equal() {
let s = "junk, foo: 4, bar: 5";
assert!(check_match_equal(s, "foo", 4));
assert!(check_match_equal(s, "bar", 5));
assert!(!check_match_equal(s, "foo", 3));
assert!(check_match_equal(s, "string that isn't even there", 5));
}
// part 2
fn check_match_less(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x < y)
}
fn check_match_greater(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x > y)
}
fn does_sue_match2(s: &str) -> bool {
check_match_equal(s, "children", 3)
&& check_match_greater(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_less(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_less(s, "goldfish", 5)
&& check_match_greater(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
&& check_match_equal(s, "perfumes", 1)
}
|
{
assert!(m.string_count() > 1);
f(m.group(1).parse::<u32>().unwrap(), value)
}
|
conditional_block
|
advent16.rs
|
// advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
if does_sue_match(&input) {
println!("Found match: {}", input.trim());
}
if does_sue_match2(&input) {
println!("Found match part 2: {}", input.trim());
}
}
}
fn does_sue_match(s: &str) -> bool {
check_match_equal(s, "children", 3)
&& check_match_equal(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_equal(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_equal(s, "goldfish", 5)
&& check_match_equal(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
&& check_match_equal(s, "perfumes", 1)
}
fn check_match_equal(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x == y)
}
// returns false if it has the property and it doesn't match the value
// returns true if the property doesn't exist or it exists but doesn't match
fn check_match<F>(s: &str, property: &str, value: u32, f: F) -> bool
where F: Fn(u32, u32) -> bool {
let mut re = pcre::Pcre::compile(&format!("{}: (\\d+)", property)).unwrap();
if let Some(m) = re.exec(s) {
assert!(m.string_count() > 1);
f(m.group(1).parse::<u32>().unwrap(), value)
} else {
// property doesn't exist
true
}
}
#[test]
fn test_check_match_equal() {
let s = "junk, foo: 4, bar: 5";
assert!(check_match_equal(s, "foo", 4));
assert!(check_match_equal(s, "bar", 5));
assert!(!check_match_equal(s, "foo", 3));
assert!(check_match_equal(s, "string that isn't even there", 5));
}
// part 2
fn check_match_less(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x < y)
}
fn check_match_greater(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x > y)
}
fn does_sue_match2(s: &str) -> bool {
check_match_equal(s, "children", 3)
&& check_match_greater(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_less(s, "pomeranians", 3)
|
&& check_match_equal(s, "perfumes", 1)
}
|
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_less(s, "goldfish", 5)
&& check_match_greater(s, "trees", 3)
&& check_match_equal(s, "cars", 2)
|
random_line_split
|
mempty.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use super::{Layout};
use ::platform::Context;
use ::draw::{Drawable, Empty};
pub struct MemptyLayout {}
impl MemptyLayout {
pub fn new() -> MemptyLayout {
MemptyLayout {}
}
}
impl Layout for MemptyLayout {
fn layout<'a>(&'a self, _: &Context) -> Box<Drawable + 'a> {
Box::new(Empty::new())
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any
|
}
|
{
self
}
|
identifier_body
|
mempty.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use super::{Layout};
use ::platform::Context;
use ::draw::{Drawable, Empty};
pub struct MemptyLayout {}
impl MemptyLayout {
pub fn
|
() -> MemptyLayout {
MemptyLayout {}
}
}
impl Layout for MemptyLayout {
fn layout<'a>(&'a self, _: &Context) -> Box<Drawable + 'a> {
Box::new(Empty::new())
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
}
|
new
|
identifier_name
|
mempty.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use super::{Layout};
use ::platform::Context;
use ::draw::{Drawable, Empty};
pub struct MemptyLayout {}
impl MemptyLayout {
pub fn new() -> MemptyLayout {
MemptyLayout {}
}
}
impl Layout for MemptyLayout {
fn layout<'a>(&'a self, _: &Context) -> Box<Drawable + 'a> {
Box::new(Empty::new())
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
}
|
* 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
*
|
random_line_split
|
users.rs
|
#![crate_name = "users"]
#![feature(collections, core, old_io, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// Allow dead code here in order to keep all fields, constants here, for consistency.
#![allow(dead_code, non_camel_case_types)]
extern crate getopts;
extern crate libc;
use std::ffi::{CStr, CString};
use std::old_io::print;
use std::mem;
use std::ptr;
use utmpx::*;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
#[path = "../common/utmpx.rs"]
mod utmpx;
extern {
fn getutxent() -> *const c_utmp;
fn getutxid(ut: *const c_utmp) -> *const c_utmp;
fn getutxline(ut: *const c_utmp) -> *const c_utmp;
fn pututxline(ut: *const c_utmp) -> *const c_utmp;
fn setutxent();
fn endutxent();
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn utmpxname(file: *const libc::c_char) -> libc::c_int;
}
#[cfg(target_os = "freebsd")]
unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
static NAME: &'static str = "users";
pub fn uumain(args: Vec<String>) -> i32 {
let program = args[0].as_slice();
let opts = [
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(f) => panic!("{}", f),
};
if matches.opt_present("help") {
println!("users 1.0.0");
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]", program);
println!("");
print(getopts::usage("Output who is currently logged in according to FILE.", &opts).as_slice());
return 0;
}
if matches.opt_present("version") {
println!("users 1.0.0");
return 0;
}
let mut filename = DEFAULT_FILE;
if matches.free.len() > 0 {
filename = matches.free[0].as_slice();
}
exec(filename);
0
}
fn exec(filename: &str)
|
}
}
endutxent();
}
if users.len() > 0 {
users.sort();
println!("{}", users.connect(" "));
}
}
|
{
unsafe {
utmpxname(CString::new(filename).unwrap().as_ptr());
}
let mut users = vec!();
unsafe {
setutxent();
loop {
let line = getutxent();
if line == ptr::null() {
break;
}
if (*line).ut_type == USER_PROCESS {
let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string();
users.push(user);
|
identifier_body
|
users.rs
|
#![crate_name = "users"]
#![feature(collections, core, old_io, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// Allow dead code here in order to keep all fields, constants here, for consistency.
#![allow(dead_code, non_camel_case_types)]
extern crate getopts;
extern crate libc;
use std::ffi::{CStr, CString};
use std::old_io::print;
use std::mem;
use std::ptr;
use utmpx::*;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
#[path = "../common/utmpx.rs"]
mod utmpx;
extern {
fn getutxent() -> *const c_utmp;
fn getutxid(ut: *const c_utmp) -> *const c_utmp;
fn getutxline(ut: *const c_utmp) -> *const c_utmp;
fn pututxline(ut: *const c_utmp) -> *const c_utmp;
fn setutxent();
fn endutxent();
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn utmpxname(file: *const libc::c_char) -> libc::c_int;
}
#[cfg(target_os = "freebsd")]
unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
static NAME: &'static str = "users";
pub fn
|
(args: Vec<String>) -> i32 {
let program = args[0].as_slice();
let opts = [
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(f) => panic!("{}", f),
};
if matches.opt_present("help") {
println!("users 1.0.0");
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]", program);
println!("");
print(getopts::usage("Output who is currently logged in according to FILE.", &opts).as_slice());
return 0;
}
if matches.opt_present("version") {
println!("users 1.0.0");
return 0;
}
let mut filename = DEFAULT_FILE;
if matches.free.len() > 0 {
filename = matches.free[0].as_slice();
}
exec(filename);
0
}
fn exec(filename: &str) {
unsafe {
utmpxname(CString::new(filename).unwrap().as_ptr());
}
let mut users = vec!();
unsafe {
setutxent();
loop {
let line = getutxent();
if line == ptr::null() {
break;
}
if (*line).ut_type == USER_PROCESS {
let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string();
users.push(user);
}
}
endutxent();
}
if users.len() > 0 {
users.sort();
println!("{}", users.connect(" "));
}
}
|
uumain
|
identifier_name
|
users.rs
|
#![crate_name = "users"]
#![feature(collections, core, old_io, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// Allow dead code here in order to keep all fields, constants here, for consistency.
#![allow(dead_code, non_camel_case_types)]
extern crate getopts;
extern crate libc;
use std::ffi::{CStr, CString};
use std::old_io::print;
use std::mem;
use std::ptr;
use utmpx::*;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
#[path = "../common/utmpx.rs"]
mod utmpx;
extern {
fn getutxent() -> *const c_utmp;
fn getutxid(ut: *const c_utmp) -> *const c_utmp;
fn getutxline(ut: *const c_utmp) -> *const c_utmp;
fn pututxline(ut: *const c_utmp) -> *const c_utmp;
fn setutxent();
fn endutxent();
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn utmpxname(file: *const libc::c_char) -> libc::c_int;
|
unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
static NAME: &'static str = "users";
pub fn uumain(args: Vec<String>) -> i32 {
let program = args[0].as_slice();
let opts = [
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(f) => panic!("{}", f),
};
if matches.opt_present("help") {
println!("users 1.0.0");
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]", program);
println!("");
print(getopts::usage("Output who is currently logged in according to FILE.", &opts).as_slice());
return 0;
}
if matches.opt_present("version") {
println!("users 1.0.0");
return 0;
}
let mut filename = DEFAULT_FILE;
if matches.free.len() > 0 {
filename = matches.free[0].as_slice();
}
exec(filename);
0
}
fn exec(filename: &str) {
unsafe {
utmpxname(CString::new(filename).unwrap().as_ptr());
}
let mut users = vec!();
unsafe {
setutxent();
loop {
let line = getutxent();
if line == ptr::null() {
break;
}
if (*line).ut_type == USER_PROCESS {
let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string();
users.push(user);
}
}
endutxent();
}
if users.len() > 0 {
users.sort();
println!("{}", users.connect(" "));
}
}
|
}
#[cfg(target_os = "freebsd")]
|
random_line_split
|
content_location.rs
|
header! {
/// `Content-Location` header, defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.4.2)
///
/// The header can be used by both the client in requests and the server
/// in resposes with different semantics. Client sets `Content-Location`
/// to refer to the URI where original representation of the body was
/// obtained.
///
/// In responses `Content-Location` represents URI for the representation
/// that was content negotiated, created or for the response payload.
///
/// # ABNF
/// ```plain
/// Content-Location = absolute-URI / partial-URI
/// ```
///
/// # Example values
/// * `/hypertext/Overview.html`
|
/// ```
/// use hyper::header::{Headers, ContentLocation};
///
/// let mut headers = Headers::new();
/// headers.set(ContentLocation("/hypertext/Overview.html".to_owned()));
/// ```
/// ```
/// use hyper::header::{Headers, ContentLocation};
///
/// let mut headers = Headers::new();
/// headers.set(ContentLocation("http://www.example.org/hypertext/Overview.html".to_owned()));
/// ```
// TODO: use URL
(ContentLocation, "Content-Location") => [String]
test_content_location {
test_header!(partial_query, vec![b"/hypertext/Overview.html?q=tim"]);
test_header!(absolute, vec![b"http://www.example.org/hypertext/Overview.html"]);
}
}
|
/// * `http://www.example.org/hypertext/Overview.html`
///
/// # Examples
///
|
random_line_split
|
horiz.rs
|
use ascii_canvas::AsciiView;
use itertools::Itertools;
use super::*;
#[derive(Debug)]
pub struct Horiz {
items: Vec<Box<Content>>,
separate: usize, // 0 => overlapping, 1 => each on its own line, 2 => paragraphs
}
impl Horiz {
pub fn new(items: Vec<Box<Content>>, separate: usize) -> Self {
Horiz {
items: items,
separate: separate,
}
}
}
impl Content for Horiz {
fn min_width(&self) -> usize {
self.items.iter()
.map(|c| c.min_width())
.intersperse(self.separate)
.fold(0, |a,b| a+b)
}
fn emit(&self, view: &mut AsciiView)
|
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
wrap_items.push(self);
}
}
pub fn emit_horiz(view: &mut AsciiView,
items: &[Box<Content>],
separate: usize)
{
let mut column = 0;
for item in items {
let (_, end_column) = item.emit_at(view, 0, column);
column = end_column + separate;
}
}
|
{
emit_horiz(view, &self.items, self.separate);
}
|
identifier_body
|
horiz.rs
|
use ascii_canvas::AsciiView;
|
use itertools::Itertools;
use super::*;
#[derive(Debug)]
pub struct Horiz {
items: Vec<Box<Content>>,
separate: usize, // 0 => overlapping, 1 => each on its own line, 2 => paragraphs
}
impl Horiz {
pub fn new(items: Vec<Box<Content>>, separate: usize) -> Self {
Horiz {
items: items,
separate: separate,
}
}
}
impl Content for Horiz {
fn min_width(&self) -> usize {
self.items.iter()
.map(|c| c.min_width())
.intersperse(self.separate)
.fold(0, |a,b| a+b)
}
fn emit(&self, view: &mut AsciiView) {
emit_horiz(view, &self.items, self.separate);
}
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
wrap_items.push(self);
}
}
pub fn emit_horiz(view: &mut AsciiView,
items: &[Box<Content>],
separate: usize)
{
let mut column = 0;
for item in items {
let (_, end_column) = item.emit_at(view, 0, column);
column = end_column + separate;
}
}
|
random_line_split
|
|
horiz.rs
|
use ascii_canvas::AsciiView;
use itertools::Itertools;
use super::*;
#[derive(Debug)]
pub struct Horiz {
items: Vec<Box<Content>>,
separate: usize, // 0 => overlapping, 1 => each on its own line, 2 => paragraphs
}
impl Horiz {
pub fn new(items: Vec<Box<Content>>, separate: usize) -> Self {
Horiz {
items: items,
separate: separate,
}
}
}
impl Content for Horiz {
fn min_width(&self) -> usize {
self.items.iter()
.map(|c| c.min_width())
.intersperse(self.separate)
.fold(0, |a,b| a+b)
}
fn emit(&self, view: &mut AsciiView) {
emit_horiz(view, &self.items, self.separate);
}
fn
|
(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
wrap_items.push(self);
}
}
pub fn emit_horiz(view: &mut AsciiView,
items: &[Box<Content>],
separate: usize)
{
let mut column = 0;
for item in items {
let (_, end_column) = item.emit_at(view, 0, column);
column = end_column + separate;
}
}
|
into_wrap_items
|
identifier_name
|
htmlhrelement.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::HTMLHRElementBinding::{self, HTMLHRElementMethods};
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 string_cache::Atom;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
}
impl HTMLHRElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
Node::reflect_node(box HTMLHRElement::new_inherited(localName, prefix, document),
document,
HTMLHRElementBinding::Wrap)
}
}
impl HTMLHRElementMethods for HTMLHRElement {
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_atomic_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_getter!(Width, "width");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_dimension_setter!(SetWidth, "width");
}
pub trait HTMLHRLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLHRLayoutHelpers for LayoutJS<HTMLHRElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl VirtualMethods for HTMLHRElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue
|
}
|
{
match name {
&atom!("align") => AttrValue::from_dimension(value.into()),
&atom!("color") => AttrValue::from_legacy_color(value.into()),
&atom!("width") => AttrValue::from_dimension(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
|
identifier_body
|
htmlhrelement.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::HTMLHRElementBinding::{self, HTMLHRElementMethods};
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 string_cache::Atom;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
}
impl HTMLHRElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn
|
(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
Node::reflect_node(box HTMLHRElement::new_inherited(localName, prefix, document),
document,
HTMLHRElementBinding::Wrap)
}
}
impl HTMLHRElementMethods for HTMLHRElement {
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_atomic_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_getter!(Width, "width");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_dimension_setter!(SetWidth, "width");
}
pub trait HTMLHRLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLHRLayoutHelpers for LayoutJS<HTMLHRElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl VirtualMethods for HTMLHRElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("align") => AttrValue::from_dimension(value.into()),
&atom!("color") => AttrValue::from_legacy_color(value.into()),
&atom!("width") => AttrValue::from_dimension(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
|
new
|
identifier_name
|
htmlhrelement.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::HTMLHRElementBinding::{self, HTMLHRElementMethods};
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 string_cache::Atom;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
|
}
impl HTMLHRElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
Node::reflect_node(box HTMLHRElement::new_inherited(localName, prefix, document),
document,
HTMLHRElementBinding::Wrap)
}
}
impl HTMLHRElementMethods for HTMLHRElement {
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_atomic_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_getter!(Color, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_legacy_color_setter!(SetColor, "color");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_getter!(Width, "width");
// https://html.spec.whatwg.org/multipage/#dom-hr-width
make_dimension_setter!(SetWidth, "width");
}
pub trait HTMLHRLayoutHelpers {
fn get_color(&self) -> Option<RGBA>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLHRLayoutHelpers for LayoutJS<HTMLHRElement> {
#[allow(unsafe_code)]
fn get_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("color"))
.and_then(AttrValue::as_color)
.cloned()
}
}
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
}
}
impl VirtualMethods for HTMLHRElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("align") => AttrValue::from_dimension(value.into()),
&atom!("color") => AttrValue::from_legacy_color(value.into()),
&atom!("width") => AttrValue::from_dimension(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
|
random_line_split
|
|
mod.rs
|
//! Platform-specific extensions to `std` for Unix platforms.
//!
//! Provides access to platform-level information on Unix platforms, and
//! exposes Unix-specific functions that would otherwise be inappropriate as
//! part of the core `std` library.
//!
//! It exposes more ways to deal with platform-specific strings ([`OsStr`],
//! [`OsString`]), allows to set permissions more granularly, extract low-level
//! file descriptors from files and sockets, and has platform-specific helpers
//! for spawning processes.
//!
//! # Examples
//!
//! ```no_run
//! use std::fs::File;
//! use std::os::unix::prelude::*;
//!
//! fn main() -> std::io::Result<()> {
//! let f = File::create("foo.txt")?;
//! let fd = f.as_raw_fd();
//!
//! // use fd with native unix bindings
//!
//! Ok(())
//! }
//! ```
//!
//! [`OsStr`]: crate::ffi::OsStr
//! [`OsString`]: crate::ffi::OsString
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(cfg(unix))]
// Use linux as the default platform when documenting on other platforms like Windows
#[cfg(doc)]
use crate::os::linux as platform;
#[cfg(not(doc))]
mod platform {
#[cfg(target_os = "android")]
pub use crate::os::android::*;
#[cfg(target_os = "dragonfly")]
pub use crate::os::dragonfly::*;
#[cfg(target_os = "emscripten")]
pub use crate::os::emscripten::*;
#[cfg(target_os = "espidf")]
pub use crate::os::espidf::*;
#[cfg(target_os = "freebsd")]
pub use crate::os::freebsd::*;
#[cfg(target_os = "fuchsia")]
pub use crate::os::fuchsia::*;
#[cfg(target_os = "haiku")]
pub use crate::os::haiku::*;
#[cfg(target_os = "illumos")]
pub use crate::os::illumos::*;
#[cfg(target_os = "ios")]
pub use crate::os::ios::*;
#[cfg(any(target_os = "linux", target_os = "l4re"))]
pub use crate::os::linux::*;
#[cfg(target_os = "macos")]
pub use crate::os::macos::*;
#[cfg(target_os = "netbsd")]
pub use crate::os::netbsd::*;
#[cfg(target_os = "openbsd")]
pub use crate::os::openbsd::*;
#[cfg(target_os = "redox")]
pub use crate::os::redox::*;
#[cfg(target_os = "solaris")]
pub use crate::os::solaris::*;
#[cfg(target_os = "vxworks")]
pub use crate::os::vxworks::*;
}
pub mod ffi;
pub mod fs;
pub mod io;
pub mod net;
pub mod process;
pub mod raw;
pub mod thread;
#[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")]
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "ios",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd"
))]
pub mod ucred;
|
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::ffi::{OsStrExt, OsStringExt};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::fs::DirEntryExt;
#[doc(no_inline)]
#[stable(feature = "file_offset", since = "1.15.0")]
pub use super::fs::FileExt;
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::process::{CommandExt, ExitStatusExt};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::thread::JoinHandleExt;
}
|
/// A prelude for conveniently writing platform-specific code.
///
/// Includes all extension traits, and some important type definitions.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod prelude {
|
random_line_split
|
shadowroot.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{self, ShadowRootMode};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: Dom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: Dom::from_ref(host),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
ShadowRootBinding::Wrap,
)
}
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
}
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
}
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
|
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
self.host
.upcast::<Node>()
.dirty(NodeDamage::NodeStyleDamaged);
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_named_element(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_named_element(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
},
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
{
elements.push(element);
}
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
DomRoot::from_ref(&self.host)
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers {
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element>;
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument>;
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl LayoutShadowRootHelpers for LayoutDom<ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element> {
(*self.unsafe_get()).host.to_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument> {
(*self.unsafe_get()).author_styles.borrow_for_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
}
|
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
|
random_line_split
|
shadowroot.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{self, ShadowRootMode};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: Dom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: Dom::from_ref(host),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
ShadowRootBinding::Wrap,
)
}
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
}
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
}
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
self.host
.upcast::<Node>()
.dirty(NodeDamage::NodeStyleDamaged);
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_named_element(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_named_element(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
},
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
|
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
DomRoot::from_ref(&self.host)
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers {
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element>;
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument>;
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl LayoutShadowRootHelpers for LayoutDom<ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element> {
(*self.unsafe_get()).host.to_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument> {
(*self.unsafe_get()).author_styles.borrow_for_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
}
|
{
elements.push(element);
}
|
conditional_block
|
shadowroot.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{self, ShadowRootMode};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: Dom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: Dom::from_ref(host),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
ShadowRootBinding::Wrap,
)
}
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
}
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
}
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn
|
(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
self.host
.upcast::<Node>()
.dirty(NodeDamage::NodeStyleDamaged);
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_named_element(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_named_element(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
},
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
{
elements.push(element);
}
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
DomRoot::from_ref(&self.host)
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers {
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element>;
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument>;
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl LayoutShadowRootHelpers for LayoutDom<ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element> {
(*self.unsafe_get()).host.to_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument> {
(*self.unsafe_get()).author_styles.borrow_for_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
}
|
invalidate_stylesheets
|
identifier_name
|
shadowroot.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{self, ShadowRootMode};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: Dom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: Dom::from_ref(host),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
ShadowRootBinding::Wrap,
)
}
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
}
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
}
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
self.host
.upcast::<Node>()
.dirty(NodeDamage::NodeStyleDamaged);
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_named_element(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_named_element(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
},
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
{
elements.push(element);
}
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode
|
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
DomRoot::from_ref(&self.host)
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers {
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element>;
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument>;
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl LayoutShadowRootHelpers for LayoutDom<ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
unsafe fn get_host_for_layout(&self) -> LayoutDom<Element> {
(*self.unsafe_get()).host.to_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn get_style_data_for_layout<'a, E: TElement>(
&self,
) -> &'a AuthorStyles<StyleSheetInDocument> {
(*self.unsafe_get()).author_styles.borrow_for_layout()
}
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
&self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
}
|
{
ShadowRootMode::Closed
}
|
identifier_body
|
connected.rs
|
use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOn {}
/// State used by `Connected`. Means that autocommit is disabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOff {}
/// Marker trait for autocommit mode state types
pub trait AutocommitMode {}
impl AutocommitMode for AutocommitOn {}
impl AutocommitMode for AutocommitOff {}
/// An `HDbc` with the additional invariant of being 'connected'.
#[derive(Debug)]
pub struct Connected<'env, AC: AutocommitMode>(HDbc<'env>, PhantomData<AC>);
impl<'env, AC: AutocommitMode> Drop for Connected<'env, AC> {
fn drop(&mut self) {
match self.0.disconnect() {
Success(()) | Info(()) => (),
Error(()) => if!panicking()
|
,
}
}
}
impl<'env, AC: AutocommitMode> Connected<'env, AC> {
/// Releases inner Connection Handle without calling disconnect.
pub fn into_hdbc(self) -> HDbc<'env> {
unsafe {
let hdbc = ptr::read(&self.0);
forget(self); // do not call drop
hdbc
}
}
}
impl<'env, AC: AutocommitMode> Deref for Connected<'env, AC> {
type Target = HDbc<'env>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'env, AC: AutocommitMode> DerefMut for Connected<'env, AC> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'env, AC: AutocommitMode> HDbcWrapper<'env> for Connected<'env, AC> {
type Handle = Connected<'env, AC>;
fn into_hdbc(self) -> HDbc<'env> {
self.into_hdbc()
}
fn from_hdbc(hdbc: HDbc<'env>) -> Self::Handle {
Connected(hdbc, PhantomData)
}
}
|
{
panic!("SQLDisconnect returned error")
}
|
conditional_block
|
connected.rs
|
use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOn {}
/// State used by `Connected`. Means that autocommit is disabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOff {}
/// Marker trait for autocommit mode state types
pub trait AutocommitMode {}
impl AutocommitMode for AutocommitOn {}
impl AutocommitMode for AutocommitOff {}
/// An `HDbc` with the additional invariant of being 'connected'.
#[derive(Debug)]
pub struct Connected<'env, AC: AutocommitMode>(HDbc<'env>, PhantomData<AC>);
impl<'env, AC: AutocommitMode> Drop for Connected<'env, AC> {
fn drop(&mut self) {
match self.0.disconnect() {
Success(()) | Info(()) => (),
Error(()) => if!panicking() {
|
}
impl<'env, AC: AutocommitMode> Connected<'env, AC> {
/// Releases inner Connection Handle without calling disconnect.
pub fn into_hdbc(self) -> HDbc<'env> {
unsafe {
let hdbc = ptr::read(&self.0);
forget(self); // do not call drop
hdbc
}
}
}
impl<'env, AC: AutocommitMode> Deref for Connected<'env, AC> {
type Target = HDbc<'env>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'env, AC: AutocommitMode> DerefMut for Connected<'env, AC> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'env, AC: AutocommitMode> HDbcWrapper<'env> for Connected<'env, AC> {
type Handle = Connected<'env, AC>;
fn into_hdbc(self) -> HDbc<'env> {
self.into_hdbc()
}
fn from_hdbc(hdbc: HDbc<'env>) -> Self::Handle {
Connected(hdbc, PhantomData)
}
}
|
panic!("SQLDisconnect returned error")
},
}
}
|
random_line_split
|
connected.rs
|
use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOn {}
/// State used by `Connected`. Means that autocommit is disabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOff {}
/// Marker trait for autocommit mode state types
pub trait AutocommitMode {}
impl AutocommitMode for AutocommitOn {}
impl AutocommitMode for AutocommitOff {}
/// An `HDbc` with the additional invariant of being 'connected'.
#[derive(Debug)]
pub struct Connected<'env, AC: AutocommitMode>(HDbc<'env>, PhantomData<AC>);
impl<'env, AC: AutocommitMode> Drop for Connected<'env, AC> {
fn drop(&mut self) {
match self.0.disconnect() {
Success(()) | Info(()) => (),
Error(()) => if!panicking() {
panic!("SQLDisconnect returned error")
},
}
}
}
impl<'env, AC: AutocommitMode> Connected<'env, AC> {
/// Releases inner Connection Handle without calling disconnect.
pub fn into_hdbc(self) -> HDbc<'env> {
unsafe {
let hdbc = ptr::read(&self.0);
forget(self); // do not call drop
hdbc
}
}
}
impl<'env, AC: AutocommitMode> Deref for Connected<'env, AC> {
type Target = HDbc<'env>;
fn deref(&self) -> &Self::Target
|
}
impl<'env, AC: AutocommitMode> DerefMut for Connected<'env, AC> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'env, AC: AutocommitMode> HDbcWrapper<'env> for Connected<'env, AC> {
type Handle = Connected<'env, AC>;
fn into_hdbc(self) -> HDbc<'env> {
self.into_hdbc()
}
fn from_hdbc(hdbc: HDbc<'env>) -> Self::Handle {
Connected(hdbc, PhantomData)
}
}
|
{
&self.0
}
|
identifier_body
|
connected.rs
|
use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum
|
{}
/// State used by `Connected`. Means that autocommit is disabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOff {}
/// Marker trait for autocommit mode state types
pub trait AutocommitMode {}
impl AutocommitMode for AutocommitOn {}
impl AutocommitMode for AutocommitOff {}
/// An `HDbc` with the additional invariant of being 'connected'.
#[derive(Debug)]
pub struct Connected<'env, AC: AutocommitMode>(HDbc<'env>, PhantomData<AC>);
impl<'env, AC: AutocommitMode> Drop for Connected<'env, AC> {
fn drop(&mut self) {
match self.0.disconnect() {
Success(()) | Info(()) => (),
Error(()) => if!panicking() {
panic!("SQLDisconnect returned error")
},
}
}
}
impl<'env, AC: AutocommitMode> Connected<'env, AC> {
/// Releases inner Connection Handle without calling disconnect.
pub fn into_hdbc(self) -> HDbc<'env> {
unsafe {
let hdbc = ptr::read(&self.0);
forget(self); // do not call drop
hdbc
}
}
}
impl<'env, AC: AutocommitMode> Deref for Connected<'env, AC> {
type Target = HDbc<'env>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'env, AC: AutocommitMode> DerefMut for Connected<'env, AC> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'env, AC: AutocommitMode> HDbcWrapper<'env> for Connected<'env, AC> {
type Handle = Connected<'env, AC>;
fn into_hdbc(self) -> HDbc<'env> {
self.into_hdbc()
}
fn from_hdbc(hdbc: HDbc<'env>) -> Self::Handle {
Connected(hdbc, PhantomData)
}
}
|
AutocommitOn
|
identifier_name
|
normal.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.
//! The normal and derived distributions.
use {Rng, Rand, Open01};
use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
/// A wrapper around an `f64` to generate N(0, 1) random numbers
/// (a.k.a. a standard normal, or Gaussian).
///
/// See `Normal` for the general normal distribution.
///
/// Implemented via the ZIGNOR variant[1] of the Ziggurat method.
///
/// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
///
/// # Example
///
/// ```rust
/// use rand::distributions::normal::StandardNormal;
///
/// let StandardNormal(x) = rand::random();
/// println!("{}", x);
/// ```
#[derive(Clone, Copy)]
pub struct StandardNormal(pub f64);
impl Rand for StandardNormal {
fn rand<R:Rng>(rng: &mut R) -> StandardNormal {
#[inline]
fn pdf(x: f64) -> f64 {
(-x*x/2.0).exp()
}
#[inline]
fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 {
// compute a random number in the tail by hand
// strange initial conditions, because the loop is not
// do-while, so the condition should be true on the first
// run, they get overwritten anyway (0 < 1, so these are
// good).
let mut x = 1.0f64;
let mut y = 0.0f64;
while -2.0 * y < x * x {
let Open01(x_) = rng.gen::<Open01<f64>>();
let Open01(y_) = rng.gen::<Open01<f64>>();
x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
y = y_.ln();
}
if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x }
}
StandardNormal(ziggurat(
rng,
true, // this is symmetric
&ziggurat_tables::ZIG_NORM_X,
&ziggurat_tables::ZIG_NORM_F,
pdf, zero_case))
}
}
/// The normal distribution `N(mean, std_dev**2)`.
///
/// This uses the ZIGNOR variant of the Ziggurat method, see
/// `StandardNormal` for more details.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{Normal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0);
/// let v = normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct Normal {
mean: f64,
std_dev: f64,
}
impl Normal {
/// Construct a new `Normal` distribution with the given mean and
/// standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> Normal {
assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
Normal {
mean: mean,
std_dev: std_dev
}
}
}
impl Sample<f64> for Normal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for Normal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
self.mean + self.std_dev * n
}
}
/// The log-normal distribution `ln N(mean, std_dev**2)`.
///
/// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
/// std_dev**2)` distributed.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{LogNormal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0);
/// let v = log_normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct LogNormal {
norm: Normal
}
impl LogNormal {
/// Construct a new `LogNormal` distribution with the given mean
/// and standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> LogNormal {
assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
LogNormal { norm: Normal::new(mean, std_dev) }
}
}
impl Sample<f64> for LogNormal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for LogNormal {
fn
|
<R: Rng>(&self, rng: &mut R) -> f64 {
self.norm.ind_sample(rng).exp()
}
}
#[cfg(test)]
mod tests {
use distributions::{Sample, IndependentSample};
use super::{Normal, LogNormal};
#[test]
fn test_normal() {
let mut norm = Normal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
norm.sample(&mut rng);
norm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_normal_invalid_sd() {
Normal::new(10.0, -1.0);
}
#[test]
fn test_log_normal() {
let mut lnorm = LogNormal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
lnorm.sample(&mut rng);
lnorm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_log_normal_invalid_sd() {
LogNormal::new(10.0, -1.0);
}
}
|
ind_sample
|
identifier_name
|
normal.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.
//! The normal and derived distributions.
use {Rng, Rand, Open01};
use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
/// A wrapper around an `f64` to generate N(0, 1) random numbers
/// (a.k.a. a standard normal, or Gaussian).
///
/// See `Normal` for the general normal distribution.
///
/// Implemented via the ZIGNOR variant[1] of the Ziggurat method.
///
/// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
///
/// # Example
///
/// ```rust
/// use rand::distributions::normal::StandardNormal;
///
/// let StandardNormal(x) = rand::random();
/// println!("{}", x);
/// ```
#[derive(Clone, Copy)]
pub struct StandardNormal(pub f64);
impl Rand for StandardNormal {
fn rand<R:Rng>(rng: &mut R) -> StandardNormal {
#[inline]
fn pdf(x: f64) -> f64 {
(-x*x/2.0).exp()
}
#[inline]
fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 {
// compute a random number in the tail by hand
// strange initial conditions, because the loop is not
// do-while, so the condition should be true on the first
// run, they get overwritten anyway (0 < 1, so these are
// good).
let mut x = 1.0f64;
let mut y = 0.0f64;
while -2.0 * y < x * x {
let Open01(x_) = rng.gen::<Open01<f64>>();
let Open01(y_) = rng.gen::<Open01<f64>>();
x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
y = y_.ln();
}
if u < 0.0
|
else { ziggurat_tables::ZIG_NORM_R - x }
}
StandardNormal(ziggurat(
rng,
true, // this is symmetric
&ziggurat_tables::ZIG_NORM_X,
&ziggurat_tables::ZIG_NORM_F,
pdf, zero_case))
}
}
/// The normal distribution `N(mean, std_dev**2)`.
///
/// This uses the ZIGNOR variant of the Ziggurat method, see
/// `StandardNormal` for more details.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{Normal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0);
/// let v = normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct Normal {
mean: f64,
std_dev: f64,
}
impl Normal {
/// Construct a new `Normal` distribution with the given mean and
/// standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> Normal {
assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
Normal {
mean: mean,
std_dev: std_dev
}
}
}
impl Sample<f64> for Normal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for Normal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
self.mean + self.std_dev * n
}
}
/// The log-normal distribution `ln N(mean, std_dev**2)`.
///
/// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
/// std_dev**2)` distributed.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{LogNormal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0);
/// let v = log_normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct LogNormal {
norm: Normal
}
impl LogNormal {
/// Construct a new `LogNormal` distribution with the given mean
/// and standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> LogNormal {
assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
LogNormal { norm: Normal::new(mean, std_dev) }
}
}
impl Sample<f64> for LogNormal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for LogNormal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
self.norm.ind_sample(rng).exp()
}
}
#[cfg(test)]
mod tests {
use distributions::{Sample, IndependentSample};
use super::{Normal, LogNormal};
#[test]
fn test_normal() {
let mut norm = Normal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
norm.sample(&mut rng);
norm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_normal_invalid_sd() {
Normal::new(10.0, -1.0);
}
#[test]
fn test_log_normal() {
let mut lnorm = LogNormal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
lnorm.sample(&mut rng);
lnorm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_log_normal_invalid_sd() {
LogNormal::new(10.0, -1.0);
}
}
|
{ x - ziggurat_tables::ZIG_NORM_R }
|
conditional_block
|
normal.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.
//! The normal and derived distributions.
use {Rng, Rand, Open01};
use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
/// A wrapper around an `f64` to generate N(0, 1) random numbers
/// (a.k.a. a standard normal, or Gaussian).
///
/// See `Normal` for the general normal distribution.
///
/// Implemented via the ZIGNOR variant[1] of the Ziggurat method.
///
/// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
///
/// # Example
///
/// ```rust
/// use rand::distributions::normal::StandardNormal;
///
/// let StandardNormal(x) = rand::random();
/// println!("{}", x);
/// ```
#[derive(Clone, Copy)]
pub struct StandardNormal(pub f64);
impl Rand for StandardNormal {
fn rand<R:Rng>(rng: &mut R) -> StandardNormal {
#[inline]
fn pdf(x: f64) -> f64 {
(-x*x/2.0).exp()
}
#[inline]
fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 {
// compute a random number in the tail by hand
// strange initial conditions, because the loop is not
// do-while, so the condition should be true on the first
// run, they get overwritten anyway (0 < 1, so these are
// good).
let mut x = 1.0f64;
let mut y = 0.0f64;
while -2.0 * y < x * x {
let Open01(x_) = rng.gen::<Open01<f64>>();
let Open01(y_) = rng.gen::<Open01<f64>>();
x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
y = y_.ln();
}
if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x }
}
StandardNormal(ziggurat(
rng,
true, // this is symmetric
&ziggurat_tables::ZIG_NORM_X,
&ziggurat_tables::ZIG_NORM_F,
pdf, zero_case))
}
}
/// The normal distribution `N(mean, std_dev**2)`.
///
/// This uses the ZIGNOR variant of the Ziggurat method, see
/// `StandardNormal` for more details.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{Normal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0);
/// let v = normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct Normal {
mean: f64,
std_dev: f64,
}
impl Normal {
/// Construct a new `Normal` distribution with the given mean and
/// standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> Normal {
assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
Normal {
mean: mean,
std_dev: std_dev
}
}
}
impl Sample<f64> for Normal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for Normal {
|
}
/// The log-normal distribution `ln N(mean, std_dev**2)`.
///
/// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
/// std_dev**2)` distributed.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{LogNormal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0);
/// let v = log_normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct LogNormal {
norm: Normal
}
impl LogNormal {
/// Construct a new `LogNormal` distribution with the given mean
/// and standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> LogNormal {
assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
LogNormal { norm: Normal::new(mean, std_dev) }
}
}
impl Sample<f64> for LogNormal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for LogNormal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
self.norm.ind_sample(rng).exp()
}
}
#[cfg(test)]
mod tests {
use distributions::{Sample, IndependentSample};
use super::{Normal, LogNormal};
#[test]
fn test_normal() {
let mut norm = Normal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
norm.sample(&mut rng);
norm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_normal_invalid_sd() {
Normal::new(10.0, -1.0);
}
#[test]
fn test_log_normal() {
let mut lnorm = LogNormal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
lnorm.sample(&mut rng);
lnorm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_log_normal_invalid_sd() {
LogNormal::new(10.0, -1.0);
}
}
|
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
self.mean + self.std_dev * n
}
|
random_line_split
|
normal.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.
//! The normal and derived distributions.
use {Rng, Rand, Open01};
use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
/// A wrapper around an `f64` to generate N(0, 1) random numbers
/// (a.k.a. a standard normal, or Gaussian).
///
/// See `Normal` for the general normal distribution.
///
/// Implemented via the ZIGNOR variant[1] of the Ziggurat method.
///
/// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
///
/// # Example
///
/// ```rust
/// use rand::distributions::normal::StandardNormal;
///
/// let StandardNormal(x) = rand::random();
/// println!("{}", x);
/// ```
#[derive(Clone, Copy)]
pub struct StandardNormal(pub f64);
impl Rand for StandardNormal {
fn rand<R:Rng>(rng: &mut R) -> StandardNormal {
#[inline]
fn pdf(x: f64) -> f64 {
(-x*x/2.0).exp()
}
#[inline]
fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 {
// compute a random number in the tail by hand
// strange initial conditions, because the loop is not
// do-while, so the condition should be true on the first
// run, they get overwritten anyway (0 < 1, so these are
// good).
let mut x = 1.0f64;
let mut y = 0.0f64;
while -2.0 * y < x * x {
let Open01(x_) = rng.gen::<Open01<f64>>();
let Open01(y_) = rng.gen::<Open01<f64>>();
x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
y = y_.ln();
}
if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x }
}
StandardNormal(ziggurat(
rng,
true, // this is symmetric
&ziggurat_tables::ZIG_NORM_X,
&ziggurat_tables::ZIG_NORM_F,
pdf, zero_case))
}
}
/// The normal distribution `N(mean, std_dev**2)`.
///
/// This uses the ZIGNOR variant of the Ziggurat method, see
/// `StandardNormal` for more details.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{Normal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0);
/// let v = normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct Normal {
mean: f64,
std_dev: f64,
}
impl Normal {
/// Construct a new `Normal` distribution with the given mean and
/// standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> Normal
|
}
impl Sample<f64> for Normal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for Normal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
self.mean + self.std_dev * n
}
}
/// The log-normal distribution `ln N(mean, std_dev**2)`.
///
/// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
/// std_dev**2)` distributed.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{LogNormal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0);
/// let v = log_normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy)]
pub struct LogNormal {
norm: Normal
}
impl LogNormal {
/// Construct a new `LogNormal` distribution with the given mean
/// and standard deviation.
///
/// # Panics
///
/// Panics if `std_dev < 0`.
#[inline]
pub fn new(mean: f64, std_dev: f64) -> LogNormal {
assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
LogNormal { norm: Normal::new(mean, std_dev) }
}
}
impl Sample<f64> for LogNormal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for LogNormal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
self.norm.ind_sample(rng).exp()
}
}
#[cfg(test)]
mod tests {
use distributions::{Sample, IndependentSample};
use super::{Normal, LogNormal};
#[test]
fn test_normal() {
let mut norm = Normal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
norm.sample(&mut rng);
norm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_normal_invalid_sd() {
Normal::new(10.0, -1.0);
}
#[test]
fn test_log_normal() {
let mut lnorm = LogNormal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in 0..1000 {
lnorm.sample(&mut rng);
lnorm.ind_sample(&mut rng);
}
}
#[test]
#[should_panic]
fn test_log_normal_invalid_sd() {
LogNormal::new(10.0, -1.0);
}
}
|
{
assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
Normal {
mean: mean,
std_dev: std_dev
}
}
|
identifier_body
|
coerce-match.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that coercions are propagated through match and if expressions.
#![allow(unknown_features)]
#![feature(box_syntax)]
pub fn
|
() {
let _: Box<[int]> = if true { box [1i, 2, 3] } else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false => box [1i] };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
|
main
|
identifier_name
|
coerce-match.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that coercions are propagated through match and if expressions.
#![allow(unknown_features)]
#![feature(box_syntax)]
pub fn main()
|
{
let _: Box<[int]> = if true { box [1i, 2, 3] } else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false => box [1i] };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
|
identifier_body
|
|
coerce-match.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
// except according to those terms.
// Check that coercions are propagated through match and if expressions.
#![allow(unknown_features)]
#![feature(box_syntax)]
pub fn main() {
let _: Box<[int]> = if true { box [1i, 2, 3] } else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false => box [1i] };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
|
// 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
|
random_line_split
|
coerce-match.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that coercions are propagated through match and if expressions.
#![allow(unknown_features)]
#![feature(box_syntax)]
pub fn main() {
let _: Box<[int]> = if true
|
else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false => box [1i] };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
|
{ box [1i, 2, 3] }
|
conditional_block
|
lib.rs
|
//! An entity component system based on changesets.
//!
//! # Definition
//!
//! An entity component system is a game architecture pattern where you separate data
//! from logic.
//!
//! In this design, an **entity** is a unique id, **components** are any data
|
//! they directly act on entitie's components to make the world alive.
//!
//! # Design
//!
//! At its heart, Glue is based on immutable **components** and **changesets**.
//! This mean that when you want to modify a component
//! you don't modify the current component.
//! Instead, you push modifications that build up changesets.
//!
//! All the modifications are delayed until you commit the state.
//!
//! ```
//! # use glue::*;
//! #
//! # fn main() {
//! # let mut state = StateBuilder::new().build();
//! let mut update = state.update();
//!
//! update.commit(|state, commit| {
//! // Do state modifications by reading the current state
//! // and producing changesets
//! }); // All changes are then applied in parrallel
//! # }
//! ```
//!
//! This design allows to run independant processes in parrallel without locking components.
//!
#![feature(plugin, custom_derive, pub_restricted, associated_consts, get_type_id)]
#![plugin(serde_macros)]
extern crate vec_map;
extern crate bincode;
extern crate serde;
extern crate serde_json;
#[doc(hidden)]
pub extern crate rayon as extern_rayon;
#[macro_use]
extern crate mopa;
pub mod policy;
pub mod entity;
pub mod component;
pub mod schema;
pub mod state;
pub mod process;
pub mod writer;
pub mod group;
pub mod spawn;
mod utils;
pub use extern_rayon as rayon;
pub use entity::{Accessor, EntityRef};
pub use component::{Component, Storage, StorageSnapshot};
pub use component::modifiers::{Modifier, Insert, Remove};
pub use schema::{Schema, SchemaBuilder};
pub use state::{State, StateBuilder, Update, Commit, StateSnapshot};
pub use process::Scheduler;
pub use writer::{Writer, ModifierWriter, ComponentWriter};
pub use group::{Filter, GroupToken, Group};
pub use spawn::{SpawnRequest, Prototype, PrototypeToken};
pub use component::storages::Packed as PackedStorage;
pub use component::storages::Tag as TagStorage;
|
//! that you want to attach to an entity like a position in the game world.
//! Processes (glue's **systems**), are the logic of the game
|
random_line_split
|
token.rs
|
), string=s.as_slice().to_ascii().as_str_ascii())
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_string(),
LIFETIME(s) => {
format!("{}", get_ident(s))
}
UNDERSCORE => "_".to_string(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_string(),
EOF => "<eof>".to_string(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(ref e) => ::print::pprust::expr_to_str(&**e),
&NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e),
_ => {
let mut s = "an interpolated ".to_string();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
NtStmt(..) => s.push_str("statement"),
NtPat(..) => s.push_str("pattern"),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
NtTy(..) => s.push_str("type"),
NtIdent(..) => s.push_str("identifier"),
NtPath(..) => s.push_str("path"),
NtTT(..) => s.push_str("tt"),
NtMatchers(..) => s.push_str("matcher sequence")
};
s
}
}
}
}
}
pub fn can_begin_expr(t: &Token) -> bool {
match *t {
LPAREN => true,
LBRACE => true,
LBRACKET => true,
IDENT(_, _) => true,
UNDERSCORE => true,
TILDE => true,
LIT_BYTE(_) => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
LIT_BINARY(_) => true,
LIT_BINARY_RAW(_, _) => true,
POUND => true,
AT => true,
NOT => true,
BINOP(MINUS) => true,
BINOP(STAR) => true,
BINOP(AND) => true,
BINOP(OR) => true, // in lambda syntax
OROR => true, // in lambda syntax
MOD_SEP => true,
INTERPOLATED(NtExpr(..))
| INTERPOLATED(NtIdent(..))
| INTERPOLATED(NtBlock(..))
| INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
/// Returns the matching close delimiter if this is an open delimiter,
/// otherwise `None`.
pub fn close_delimiter_for(t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_BYTE(_) => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
LIT_BINARY(_) => true,
LIT_BINARY_RAW(_, _) => true,
_ => false
}
}
pub fn is_ident(t: &Token) -> bool {
match *t { IDENT(_, _) => true, _ => false }
}
pub fn is_ident_or_path(t: &Token) -> bool {
match *t {
IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
pub fn is_plain_ident(t: &Token) -> bool {
match *t { IDENT(_, false) => true, _ => false }
}
pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
pub mod special_idents {
use ast::Ident;
$( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast::Ident;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_ident(&self) -> Ident {
match *self {
$( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
$( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_ident(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME, self_, "self");
(super::STATIC_KEYWORD_NAME, statik, "static");
(3, static_lifetime, "'static");
// for matcher NTs
(4, tt, "tt");
(5, matchers, "matchers");
// outside of libsyntax
(6, clownshoe_abi, "__rust_abi");
(7, opaque, "<opaque>");
(8, unnamed_field, "<unnamed_field>");
(9, type_self, "Self");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(10, As, "as");
(11, Break, "break");
(12, Crate, "crate");
(13, Else, "else");
(14, Enum, "enum");
(15, Extern, "extern");
(16, False, "false");
(17, Fn, "fn");
(18, For, "for");
(19, If, "if");
(20, Impl, "impl");
(21, In, "in");
(22, Let, "let");
(23, Loop, "loop");
(24, Match, "match");
(25, Mod, "mod");
(26, Mut, "mut");
(27, Once, "once");
(28, Pub, "pub");
(29, Ref, "ref");
(30, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME, Static, "static");
(super::SELF_KEYWORD_NAME, Self, "self");
(31, Struct, "struct");
(32, Super, "super");
(33, True, "true");
(34, Trait, "trait");
(35, Type, "type");
(36, Unsafe, "unsafe");
(37, Use, "use");
(38, Virtual, "virtual");
(39, While, "while");
(40, Continue, "continue");
(41, Proc, "proc");
(42, Box, "box");
(43, Const, "const");
'reserved:
(44, Alignof, "alignof");
(45, Be, "be");
(46, Offsetof, "offsetof");
(47, Priv, "priv");
(48, Pure, "pure");
(49, Sizeof, "sizeof");
(50, Typeof, "typeof");
(51, Unsized, "unsized");
(52, Yield, "yield");
(53, Do, "do");
}
}
/**
* Maps a token to a record specifying the corresponding binary
* operator
*/
pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
match *tok {
BINOP(STAR) => Some(ast::BiMul),
BINOP(SLASH) => Some(ast::BiDiv),
BINOP(PERCENT) => Some(ast::BiRem),
BINOP(PLUS) => Some(ast::BiAdd),
BINOP(MINUS) => Some(ast::BiSub),
BINOP(SHL) => Some(ast::BiShl),
BINOP(SHR) => Some(ast::BiShr),
BINOP(AND) => Some(ast::BiBitAnd),
BINOP(CARET) => Some(ast::BiBitXor),
BINOP(OR) => Some(ast::BiBitOr),
LT => Some(ast::BiLt),
LE => Some(ast::BiLe),
GE => Some(ast::BiGe),
GT => Some(ast::BiGt),
EQEQ => Some(ast::BiEq),
NE => Some(ast::BiNe),
ANDAND => Some(ast::BiAnd),
OROR => Some(ast::BiOr),
_ => None
}
}
// looks like we can get rid of this completely...
pub type IdentInterner = StrInterner;
// if an interner exists in TLS, return it. Otherwise, prepare a
// fresh one.
// FIXME(eddyb) #8726 This should probably use a task-local reference.
pub fn get_ident_interner() -> Rc<IdentInterner> {
local_data_key!(key: Rc<::parse::token::IdentInterner>)
match key.get() {
Some(interner) => interner.clone(),
None => {
let interner = Rc::new(mk_fresh_ident_interner());
key.replace(Some(interner.clone()));
interner
}
}
}
/// Represents a string stored in the task-local interner. Because the
/// interner lives for the life of the task, this can be safely treated as an
/// immortal string, as long as it never crosses between tasks.
///
/// FIXME(pcwalton): You must be careful about what you do in the destructors
/// of objects stored in TLS, because they may run after the interner is
/// destroyed. In particular, they must not access string contents. This can
/// be fixed in the future by just leaking all strings until task death
/// somehow.
#[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
string: RcStr,
}
impl InternedString {
#[inline]
pub fn new(string: &'static str) -> InternedString {
InternedString {
string: RcStr::new(string),
}
}
#[inline]
fn new_from_rc_str(string: RcStr) -> InternedString {
InternedString {
string: string,
}
}
#[inline]
pub fn get<'a>(&'a self) -> &'a str {
self.string.as_slice()
}
}
impl BytesContainer for InternedString {
fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
// FIXME(pcwalton): This is a workaround for the incorrect signature
// of `BytesContainer`, which is itself a workaround for the lack of
// DST.
unsafe {
let this = self.get();
mem::transmute(this.container_as_bytes())
}
}
}
impl fmt::Show for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.string.as_slice())
}
}
impl<'a> Equiv<&'a str> for InternedString {
fn equiv(&self, other: & &'a str) -> bool {
(*other) == self.string.as_slice()
}
}
impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
fn decode(d: &mut D) -> Result<InternedString, E> {
Ok(get_name(get_ident_interner().intern(
try!(d.read_str()).as_slice())))
}
}
impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(self.string.as_slice())
}
}
/// Returns the string contents of a name, using the task-local interner.
#[inline]
pub fn get_name(name: Name) -> InternedString {
let interner = get_ident_interner();
InternedString::new_from_rc_str(interner.get(name))
}
/// Returns the string contents of an identifier, using the task-local
/// interner.
#[inline]
pub fn get_ident(ident: Ident) -> InternedString {
get_name(ident.name)
}
/// Interns and returns the string contents of an identifier, using the
/// task-local interner.
#[inline]
pub fn intern_and_get_ident(s: &str) -> InternedString {
get_name(intern(s))
}
/// Maps a string to its interned representation.
#[inline]
pub fn intern(s: &str) -> Name {
get_ident_interner().intern(s)
}
/// gensym's a new uint, using the current interner.
#[inline]
pub fn gensym(s: &str) -> Name {
get_ident_interner().gensym(s)
}
/// Maps a string to an identifier with an empty syntax context.
#[inline]
pub fn str_to_ident(s: &str) -> ast::Ident {
ast::Ident::new(intern(s))
}
/// Maps a string to a gensym'ed identifier.
#[inline]
pub fn gensym_ident(s: &str) -> ast::Ident {
ast::Ident::new(gensym(s))
}
// create a fresh name that maps to the same string as the old one.
// note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
// that is, that the new name and the old one are connected to ptr_eq strings.
pub fn fresh_name(src: &ast::Ident) -> Name {
let interner = get_ident_interner();
interner.gensym_copy(src.name)
// following: debug version. Could work in final except that it's incompatible with
// good error messages and uses of struct names in ambiguous could-be-binding
// locations. Also definitely destroys the guarantee given above about ptr_eq.
/*let num = rand::task_rng().gen_uint_range(0,0xffff);
gensym(format!("{}_{}",ident_to_str(src),num))*/
}
// create a fresh mark.
pub fn fresh_mark() -> Mrk {
gensym("mark")
}
// See the macro above about the types of keywords
pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
match *tok {
token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
_ => { false }
}
}
pub fn is_any_keyword(tok: &Token) -> bool
|
{
match *tok {
token::IDENT(sid, false) => match sid.name {
SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
_ => false,
},
_ => false
}
}
|
identifier_body
|
|
token.rs
|
Box<ast::Path>),
NtTT( Gc<ast::TokenTree>), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
NtMatchers(..) => f.pad("NtMatchers(..)"),
}
}
}
pub fn binop_to_str(o: BinOp) -> &'static str {
match o {
PLUS => "+",
MINUS => "-",
STAR => "*",
SLASH => "/",
PERCENT => "%",
CARET => "^",
AND => "&",
OR => "|",
SHL => "<<",
SHR => ">>"
}
}
pub fn to_str(t: &Token) -> String {
match *t {
EQ => "=".to_string(),
LT => "<".to_string(),
LE => "<=".to_string(),
EQEQ => "==".to_string(),
NE => "!=".to_string(),
GE => ">=".to_string(),
GT => ">".to_string(),
NOT => "!".to_string(),
TILDE => "~".to_string(),
OROR => "||".to_string(),
ANDAND => "&&".to_string(),
BINOP(op) => binop_to_str(op).to_string(),
BINOPEQ(op) => {
let mut s = binop_to_str(op).to_string();
s.push_str("=");
s
}
/* Structural symbols */
AT => "@".to_string(),
DOT => ".".to_string(),
DOTDOT => "..".to_string(),
DOTDOTDOT => "...".to_string(),
COMMA => ",".to_string(),
SEMI => ";".to_string(),
COLON => ":".to_string(),
MOD_SEP => "::".to_string(),
RARROW => "->".to_string(),
LARROW => "<-".to_string(),
FAT_ARROW => "=>".to_string(),
LPAREN => "(".to_string(),
RPAREN => ")".to_string(),
LBRACKET => "[".to_string(),
RBRACKET => "]".to_string(),
LBRACE => "{".to_string(),
RBRACE => "}".to_string(),
POUND => "#".to_string(),
DOLLAR => "$".to_string(),
/* Literals */
LIT_BYTE(b) => {
let mut res = String::from_str("b'");
(b as char).escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
LIT_CHAR(c) => {
let mut res = String::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str() }
LIT_FLOAT(s, t) => {
let mut body = String::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body.push_str(ast_util::float_ty_to_str(t).as_slice());
body
}
LIT_FLOAT_UNSUFFIXED(s) => {
let mut body = String::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body
}
LIT_STR(s) => {
format!("\"{}\"", get_ident(s).get().escape_default())
}
LIT_STR_RAW(s, n) => {
format!("r{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=get_ident(s))
}
LIT_BINARY(ref v) => {
format!(
"b\"{}\"",
v.iter().map(|&b| b as char).collect::<String>().escape_default())
}
LIT_BINARY_RAW(ref s, n) => {
format!("br{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=s.as_slice().to_ascii().as_str_ascii())
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_string(),
LIFETIME(s) => {
format!("{}", get_ident(s))
}
UNDERSCORE => "_".to_string(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_string(),
EOF => "<eof>".to_string(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(ref e) => ::print::pprust::expr_to_str(&**e),
&NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e),
_ => {
let mut s = "an interpolated ".to_string();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
NtStmt(..) => s.push_str("statement"),
NtPat(..) => s.push_str("pattern"),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
NtTy(..) => s.push_str("type"),
NtIdent(..) => s.push_str("identifier"),
NtPath(..) => s.push_str("path"),
NtTT(..) => s.push_str("tt"),
NtMatchers(..) => s.push_str("matcher sequence")
};
s
}
}
}
}
}
pub fn can_begin_expr(t: &Token) -> bool {
match *t {
LPAREN => true,
LBRACE => true,
LBRACKET => true,
IDENT(_, _) => true,
UNDERSCORE => true,
TILDE => true,
LIT_BYTE(_) => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
LIT_BINARY(_) => true,
LIT_BINARY_RAW(_, _) => true,
POUND => true,
AT => true,
NOT => true,
BINOP(MINUS) => true,
BINOP(STAR) => true,
BINOP(AND) => true,
BINOP(OR) => true, // in lambda syntax
OROR => true, // in lambda syntax
MOD_SEP => true,
INTERPOLATED(NtExpr(..))
| INTERPOLATED(NtIdent(..))
| INTERPOLATED(NtBlock(..))
| INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
/// Returns the matching close delimiter if this is an open delimiter,
/// otherwise `None`.
pub fn close_delimiter_for(t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_BYTE(_) => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
LIT_BINARY(_) => true,
LIT_BINARY_RAW(_, _) => true,
_ => false
}
}
pub fn is_ident(t: &Token) -> bool {
match *t { IDENT(_, _) => true, _ => false }
}
pub fn is_ident_or_path(t: &Token) -> bool {
match *t {
IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
pub fn is_plain_ident(t: &Token) -> bool {
match *t { IDENT(_, false) => true, _ => false }
}
pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
pub mod special_idents {
use ast::Ident;
$( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast::Ident;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_ident(&self) -> Ident {
match *self {
$( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
$( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_ident(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME, self_, "self");
(super::STATIC_KEYWORD_NAME, statik, "static");
(3, static_lifetime, "'static");
// for matcher NTs
(4, tt, "tt");
(5, matchers, "matchers");
// outside of libsyntax
(6, clownshoe_abi, "__rust_abi");
(7, opaque, "<opaque>");
(8, unnamed_field, "<unnamed_field>");
(9, type_self, "Self");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(10, As, "as");
(11, Break, "break");
(12, Crate, "crate");
(13, Else, "else");
(14, Enum, "enum");
(15, Extern, "extern");
(16, False, "false");
(17, Fn, "fn");
(18, For, "for");
(19, If, "if");
(20, Impl, "impl");
(21, In, "in");
(22, Let, "let");
(23, Loop, "loop");
(24, Match, "match");
(25, Mod, "mod");
(26, Mut, "mut");
(27, Once, "once");
(28, Pub, "pub");
(29, Ref, "ref");
(30, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME, Static, "static");
(super::SELF_KEYWORD_NAME, Self, "self");
(31, Struct, "struct");
(32, Super, "super");
(33, True, "true");
(34, Trait, "trait");
(35, Type, "type");
(36, Unsafe, "unsafe");
(37, Use, "use");
(38, Virtual, "virtual");
(39, While, "while");
(40, Continue, "continue");
(41, Proc, "proc");
(42, Box, "box");
(43, Const, "const");
'reserved:
(44, Alignof, "alignof");
(45, Be, "be");
(46, Offsetof, "offsetof");
(47, Priv, "priv");
(48, Pure, "pure");
(49, Sizeof, "sizeof");
(50, Typeof, "typeof");
(51, Unsized, "unsized");
(52, Yield, "yield");
(53, Do, "do");
}
}
/**
* Maps a token to a record specifying the corresponding binary
* operator
*/
pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
match *tok {
BINOP(STAR) => Some(ast::BiMul),
BINOP(SLASH) => Some(ast::BiDiv),
BINOP(PERCENT) => Some(ast::BiRem),
BINOP(PLUS) => Some(ast::BiAdd),
BINOP(MINUS) => Some(ast::BiSub),
BINOP(SHL) => Some(ast::BiShl),
BINOP(SHR) => Some(ast::BiShr),
BINOP(AND) => Some(ast::BiBitAnd),
BINOP(CARET) => Some(ast::BiBitXor),
BINOP(OR) => Some(ast::BiBitOr),
LT => Some(ast::BiLt),
LE => Some(ast::BiLe),
GE => Some(ast::BiGe),
GT => Some(ast::BiGt),
EQEQ => Some(ast::BiEq),
NE => Some(ast::BiNe),
ANDAND => Some(ast::BiAnd),
OROR => Some(ast::BiOr),
_ => None
}
}
// looks
|
fmt
|
identifier_name
|
token.rs
|
// except according to those terms.
use ast;
use ast::{P, Ident, Name, Mrk};
use ast_util;
use ext::mtwt;
use parse::token;
use util::interner::{RcStr, StrInterner};
use util::interner;
use serialize::{Decodable, Decoder, Encodable, Encoder};
use std::fmt;
use std::gc::Gc;
use std::mem;
use std::path::BytesContainer;
use std::rc::Rc;
#[allow(non_camel_case_types)]
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
pub enum BinOp {
PLUS,
MINUS,
STAR,
SLASH,
PERCENT,
CARET,
AND,
OR,
SHL,
SHR,
}
#[allow(non_camel_case_types)]
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
pub enum Token {
/* Expression-operator symbols. */
EQ,
LT,
LE,
EQEQ,
NE,
GE,
GT,
ANDAND,
OROR,
NOT,
TILDE,
BINOP(BinOp),
BINOPEQ(BinOp),
/* Structural symbols */
AT,
DOT,
DOTDOT,
DOTDOTDOT,
COMMA,
SEMI,
COLON,
MOD_SEP,
RARROW,
LARROW,
FAT_ARROW,
LPAREN,
RPAREN,
LBRACKET,
RBRACKET,
LBRACE,
RBRACE,
POUND,
DOLLAR,
/* Literals */
LIT_BYTE(u8),
LIT_CHAR(char),
LIT_INT(i64, ast::IntTy),
LIT_UINT(u64, ast::UintTy),
LIT_INT_UNSUFFIXED(i64),
LIT_FLOAT(ast::Ident, ast::FloatTy),
LIT_FLOAT_UNSUFFIXED(ast::Ident),
LIT_STR(ast::Ident),
LIT_STR_RAW(ast::Ident, uint), /* raw str delimited by n hash symbols */
LIT_BINARY(Rc<Vec<u8>>),
LIT_BINARY_RAW(Rc<Vec<u8>>, uint), /* raw binary str delimited by n hash symbols */
/* Name components */
// an identifier contains an "is_mod_name" boolean,
// indicating whether :: follows this token with no
// whitespace in between.
IDENT(ast::Ident, bool),
UNDERSCORE,
LIFETIME(ast::Ident),
/* For interpolation */
INTERPOLATED(Nonterminal),
DOC_COMMENT(ast::Ident),
EOF,
}
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
NtItem(Gc<ast::Item>),
NtBlock(P<ast::Block>),
NtStmt(Gc<ast::Stmt>),
NtPat( Gc<ast::Pat>),
NtExpr(Gc<ast::Expr>),
NtTy( P<ast::Ty>),
// see IDENT, above, for meaning of bool in NtIdent:
NtIdent(Box<ast::Ident>, bool),
NtMeta(Gc<ast::MetaItem>), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( Gc<ast::TokenTree>), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
NtMatchers(..) => f.pad("NtMatchers(..)"),
}
}
}
pub fn binop_to_str(o: BinOp) -> &'static str {
match o {
PLUS => "+",
MINUS => "-",
STAR => "*",
SLASH => "/",
PERCENT => "%",
CARET => "^",
AND => "&",
OR => "|",
SHL => "<<",
SHR => ">>"
}
}
pub fn to_str(t: &Token) -> String {
match *t {
EQ => "=".to_string(),
LT => "<".to_string(),
LE => "<=".to_string(),
EQEQ => "==".to_string(),
NE => "!=".to_string(),
GE => ">=".to_string(),
GT => ">".to_string(),
NOT => "!".to_string(),
TILDE => "~".to_string(),
OROR => "||".to_string(),
ANDAND => "&&".to_string(),
BINOP(op) => binop_to_str(op).to_string(),
BINOPEQ(op) => {
let mut s = binop_to_str(op).to_string();
s.push_str("=");
s
}
/* Structural symbols */
AT => "@".to_string(),
DOT => ".".to_string(),
DOTDOT => "..".to_string(),
DOTDOTDOT => "...".to_string(),
COMMA => ",".to_string(),
SEMI => ";".to_string(),
COLON => ":".to_string(),
MOD_SEP => "::".to_string(),
RARROW => "->".to_string(),
LARROW => "<-".to_string(),
FAT_ARROW => "=>".to_string(),
LPAREN => "(".to_string(),
RPAREN => ")".to_string(),
LBRACKET => "[".to_string(),
RBRACKET => "]".to_string(),
LBRACE => "{".to_string(),
RBRACE => "}".to_string(),
POUND => "#".to_string(),
DOLLAR => "$".to_string(),
/* Literals */
LIT_BYTE(b) => {
let mut res = String::from_str("b'");
(b as char).escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
LIT_CHAR(c) => {
let mut res = String::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
}
LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str() }
LIT_FLOAT(s, t) => {
let mut body = String::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body.push_str(ast_util::float_ty_to_str(t).as_slice());
body
}
LIT_FLOAT_UNSUFFIXED(s) => {
let mut body = String::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body
}
LIT_STR(s) => {
format!("\"{}\"", get_ident(s).get().escape_default())
}
LIT_STR_RAW(s, n) => {
format!("r{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=get_ident(s))
}
LIT_BINARY(ref v) => {
format!(
"b\"{}\"",
v.iter().map(|&b| b as char).collect::<String>().escape_default())
}
LIT_BINARY_RAW(ref s, n) => {
format!("br{delim}\"{string}\"{delim}",
delim="#".repeat(n), string=s.as_slice().to_ascii().as_str_ascii())
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_string(),
LIFETIME(s) => {
format!("{}", get_ident(s))
}
UNDERSCORE => "_".to_string(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_string(),
EOF => "<eof>".to_string(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(ref e) => ::print::pprust::expr_to_str(&**e),
&NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e),
_ => {
let mut s = "an interpolated ".to_string();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
NtStmt(..) => s.push_str("statement"),
NtPat(..) => s.push_str("pattern"),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
NtTy(..) => s.push_str("type"),
NtIdent(..) => s.push_str("identifier"),
NtPath(..) => s.push_str("path"),
NtTT(..) => s.push_str("tt"),
NtMatchers(..) => s.push_str("matcher sequence")
};
s
}
}
}
}
}
pub fn can_begin_expr(t: &Token) -> bool {
match *t {
LPAREN => true,
LBRACE => true,
LBRACKET => true,
IDENT(_, _) => true,
UNDERSCORE => true,
TILDE => true,
LIT_BYTE(_) => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
LIT_BINARY(_) => true,
LIT_BINARY_RAW(_, _) => true,
POUND => true,
AT => true,
NOT => true,
BINOP(MINUS) => true,
BINOP(STAR) => true,
BINOP(AND) => true,
BINOP(OR) => true, // in lambda syntax
OROR => true, // in lambda syntax
MOD_SEP => true,
INTERPOLATED(NtExpr(..))
| INTERPOLATED(NtIdent(..))
| INTERPOLATED(NtBlock(..))
| INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
/// Returns the matching close delimiter if this is an open delimiter,
/// otherwise `None`.
pub fn close_delimiter_for(t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_BYTE(_) => true,
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
LIT_INT_UNSUFFIXED(_) => true,
LIT_FLOAT(_, _) => true,
LIT_FLOAT_UNSUFFIXED(_) => true,
LIT_STR(_) => true,
LIT_STR_RAW(_, _) => true,
LIT_BINARY(_) => true,
LIT_BINARY_RAW(_, _) => true,
_ => false
}
}
pub fn is_ident(t: &Token) -> bool {
match *t { IDENT(_, _) => true, _ => false }
}
pub fn is_ident_or_path(t: &Token) -> bool {
match *t {
IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
_ => false
}
}
pub fn is_plain_ident(t: &Token) -> bool {
match *t { IDENT(_, false) => true, _ => false }
}
pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
pub mod special_idents {
use ast::Ident;
$( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast::Ident;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_ident(&self) -> Ident {
match *self {
$( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
$( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_ident(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME, self_, "self");
(super::STATIC_KEYWORD_NAME, statik, "static");
(3, static_lifetime, "'static");
// for matcher NTs
(4, tt, "tt");
(5, matchers, "matchers");
// outside of libsyntax
(6, clownshoe_abi, "__rust_abi");
(7, opaque, "<opaque>");
(8, unnamed_field, "<unnamed_field>");
(9, type_self, "Self");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(10, As, "as");
(11, Break, "break");
(12, Crate, "crate");
(13, Else, "else");
(14, Enum, "enum");
(15, Extern, "extern");
(16, False, "false");
(17, Fn, "fn");
(18, For, "for");
(19, If, "if");
(20, Impl, "impl");
(21, In, "in");
(22, Let, "let");
(23, Loop, "loop");
(24, Match, "match");
(25, Mod, "mod");
(26, Mut, "mut");
(27, Once, "once");
(28, Pub, "pub");
(29, Ref, "ref");
(30, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME, Static, "static");
(super::SELF_KEYWORD_NAME, Self, "self");
(31, Struct, "struct");
(32, Super, "super");
(33, True, "true");
(34, Trait, "trait");
(35, Type, "type");
(36, Unsafe, "unsafe");
(37, Use, "use");
(38, Virtual, "virtual");
(39, While, "while");
(40, Continue, "continue");
(41, Proc, "proc");
|
//
// 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
|
random_line_split
|
|
grafana_chart.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 seed::{attrs, iframe, prelude::*};
use std::collections::BTreeMap;
pub static IML_METRICS_DASHBOARD_ID: &str = "8Klek6wZz";
pub static IML_METRICS_DASHBOARD_NAME: &str = "iml-metrics";
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct GrafanaChartData<'a> {
pub org_id: u16,
pub refresh: &'a str,
pub panel_id: u16,
#[serde(flatten)]
pub vars: BTreeMap<String, String>,
}
pub(crate) fn
|
(
panel_id: u16,
refresh: &str,
vars: impl IntoIterator<Item = (impl ToString, impl ToString)>,
) -> GrafanaChartData {
let hm: BTreeMap<String, String> = vars
.into_iter()
.map(|(x, y)| {
let var = x.to_string();
let key = match var.as_str() {
"to" | "from" => var.to_string(),
_ => format!("var-{}", var),
};
(key, y.to_string())
})
.collect();
GrafanaChartData {
org_id: 1,
refresh,
panel_id,
vars: hm,
}
}
pub fn no_vars() -> Vec<(String, String)> {
vec![]
}
/// Create an iframe that loads the specified stratagem chart
pub(crate) fn view<'a, T>(
dashboard_id: &str,
dashboard_name: &str,
chart_data: GrafanaChartData<'a>,
height: &str,
) -> Node<T> {
iframe![attrs! {
At::Src => format!("/grafana/d-solo/{}/{}?kiosk&{}", dashboard_id, dashboard_name, serde_urlencoded::to_string(chart_data).unwrap()),
At::Width => "100%",
At::Height => height,
"frameborder" => 0
}]
}
|
create_chart_params
|
identifier_name
|
grafana_chart.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 seed::{attrs, iframe, prelude::*};
use std::collections::BTreeMap;
pub static IML_METRICS_DASHBOARD_ID: &str = "8Klek6wZz";
pub static IML_METRICS_DASHBOARD_NAME: &str = "iml-metrics";
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct GrafanaChartData<'a> {
pub org_id: u16,
pub refresh: &'a str,
pub panel_id: u16,
#[serde(flatten)]
pub vars: BTreeMap<String, String>,
}
pub(crate) fn create_chart_params(
panel_id: u16,
refresh: &str,
vars: impl IntoIterator<Item = (impl ToString, impl ToString)>,
) -> GrafanaChartData {
let hm: BTreeMap<String, String> = vars
.into_iter()
.map(|(x, y)| {
let var = x.to_string();
let key = match var.as_str() {
"to" | "from" => var.to_string(),
_ => format!("var-{}", var),
};
(key, y.to_string())
})
.collect();
GrafanaChartData {
org_id: 1,
refresh,
panel_id,
vars: hm,
}
}
pub fn no_vars() -> Vec<(String, String)> {
vec![]
}
/// Create an iframe that loads the specified stratagem chart
pub(crate) fn view<'a, T>(
dashboard_id: &str,
|
height: &str,
) -> Node<T> {
iframe![attrs! {
At::Src => format!("/grafana/d-solo/{}/{}?kiosk&{}", dashboard_id, dashboard_name, serde_urlencoded::to_string(chart_data).unwrap()),
At::Width => "100%",
At::Height => height,
"frameborder" => 0
}]
}
|
dashboard_name: &str,
chart_data: GrafanaChartData<'a>,
|
random_line_split
|
panic-runtime-unwind2.rs
|
// Copyright 2016 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.
// compile-flags:-C panic=unwind
// no-prefer-dynamic
#![feature(panic_runtime)]
#![crate_type = "rlib"]
#![no_std]
#![panic_runtime]
#[no_mangle]
pub extern fn __rust_maybe_catch_panic() {}
#[no_mangle]
pub extern fn __rust_start_panic()
|
#[no_mangle]
pub extern fn rust_eh_personality() {}
|
{}
|
identifier_body
|
panic-runtime-unwind2.rs
|
// Copyright 2016 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.
// compile-flags:-C panic=unwind
// no-prefer-dynamic
#![feature(panic_runtime)]
#![crate_type = "rlib"]
#![no_std]
#![panic_runtime]
#[no_mangle]
pub extern fn __rust_maybe_catch_panic() {}
#[no_mangle]
pub extern fn __rust_start_panic() {}
#[no_mangle]
pub extern fn
|
() {}
|
rust_eh_personality
|
identifier_name
|
panic-runtime-unwind2.rs
|
// Copyright 2016 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.
// compile-flags:-C panic=unwind
// no-prefer-dynamic
#![feature(panic_runtime)]
#![crate_type = "rlib"]
#![no_std]
#![panic_runtime]
#[no_mangle]
pub extern fn __rust_maybe_catch_panic() {}
#[no_mangle]
pub extern fn __rust_start_panic() {}
#[no_mangle]
pub extern fn rust_eh_personality() {}
|
random_line_split
|
|
indexing.rs
|
use numeric::Tensor;
macro_rules! add_impl {
($t:ty, $m:ident) => (
mod $m {
use numeric::Tensor;
type T = Tensor<$t>;
/*
#[test]
fn indexing() {
let t = T::range(6);
let v = t[2];
assert_eq!(v, 2.0);
}
#[test]
fn indexing_mut() {
let mut t = T::zeros(&[3]);
t[2] = 1.0;
assert!(t == T::new(vec![0.0, 0.0, 1.0]));
}
*/
#[test]
fn indexing_tuple_1() {
let t = T::range(6);
let v = t[(2,)];
assert_eq!(v, 2.0);
}
#[test]
fn indexing_tuple_2() {
let t = T::range(6).reshape(&[2, 3]);
let v = t[(1, 2)];
assert_eq!(v, 5.0);
}
#[test]
fn indexing_tuple_3() {
let t = T::range(100).reshape(&[2, 5, 10]);
let v = t[(1, 2, 3)];
assert_eq!(v, 73.0);
}
}
)
}
add_impl!(f32, float32);
add_impl!(f64, float64);
// Ravelling and unravelling indices
#[test]
fn
|
() {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.ravel_index(&[0, 1, 0, 3]), 33);
assert_eq!(t.ravel_index(&[0, 1, 4, 3]), 57);
assert_eq!(t.ravel_index(&[1, 1, 4, 1]), 175);
assert_eq!(t.ravel_index(&[2, 2, 0, 0]), 300);
}
#[test]
fn unravel_index() {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.unravel_index(33), vec![0, 1, 0, 3]);
assert_eq!(t.unravel_index(57), vec![0, 1, 4, 3]);
assert_eq!(t.unravel_index(175), vec![1, 1, 4, 1]);
assert_eq!(t.unravel_index(300), vec![2, 2, 0, 0]);
}
|
ravel_index
|
identifier_name
|
indexing.rs
|
use numeric::Tensor;
macro_rules! add_impl {
($t:ty, $m:ident) => (
mod $m {
use numeric::Tensor;
type T = Tensor<$t>;
/*
#[test]
fn indexing() {
let t = T::range(6);
let v = t[2];
assert_eq!(v, 2.0);
}
#[test]
fn indexing_mut() {
let mut t = T::zeros(&[3]);
t[2] = 1.0;
assert!(t == T::new(vec![0.0, 0.0, 1.0]));
}
*/
#[test]
fn indexing_tuple_1() {
let t = T::range(6);
let v = t[(2,)];
assert_eq!(v, 2.0);
}
#[test]
fn indexing_tuple_2() {
let t = T::range(6).reshape(&[2, 3]);
let v = t[(1, 2)];
assert_eq!(v, 5.0);
}
#[test]
fn indexing_tuple_3() {
let t = T::range(100).reshape(&[2, 5, 10]);
let v = t[(1, 2, 3)];
assert_eq!(v, 73.0);
}
}
)
}
add_impl!(f32, float32);
add_impl!(f64, float64);
// Ravelling and unravelling indices
#[test]
fn ravel_index()
|
#[test]
fn unravel_index() {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.unravel_index(33), vec![0, 1, 0, 3]);
assert_eq!(t.unravel_index(57), vec![0, 1, 4, 3]);
assert_eq!(t.unravel_index(175), vec![1, 1, 4, 1]);
assert_eq!(t.unravel_index(300), vec![2, 2, 0, 0]);
}
|
{
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.ravel_index(&[0, 1, 0, 3]), 33);
assert_eq!(t.ravel_index(&[0, 1, 4, 3]), 57);
assert_eq!(t.ravel_index(&[1, 1, 4, 1]), 175);
assert_eq!(t.ravel_index(&[2, 2, 0, 0]), 300);
}
|
identifier_body
|
indexing.rs
|
use numeric::Tensor;
macro_rules! add_impl {
($t:ty, $m:ident) => (
mod $m {
use numeric::Tensor;
type T = Tensor<$t>;
/*
#[test]
fn indexing() {
let t = T::range(6);
let v = t[2];
assert_eq!(v, 2.0);
}
#[test]
fn indexing_mut() {
let mut t = T::zeros(&[3]);
t[2] = 1.0;
assert!(t == T::new(vec![0.0, 0.0, 1.0]));
}
*/
#[test]
fn indexing_tuple_1() {
let t = T::range(6);
let v = t[(2,)];
assert_eq!(v, 2.0);
}
#[test]
fn indexing_tuple_2() {
let t = T::range(6).reshape(&[2, 3]);
let v = t[(1, 2)];
assert_eq!(v, 5.0);
}
#[test]
fn indexing_tuple_3() {
let t = T::range(100).reshape(&[2, 5, 10]);
let v = t[(1, 2, 3)];
assert_eq!(v, 73.0);
}
}
)
}
add_impl!(f32, float32);
add_impl!(f64, float64);
|
#[test]
fn ravel_index() {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.ravel_index(&[0, 1, 0, 3]), 33);
assert_eq!(t.ravel_index(&[0, 1, 4, 3]), 57);
assert_eq!(t.ravel_index(&[1, 1, 4, 1]), 175);
assert_eq!(t.ravel_index(&[2, 2, 0, 0]), 300);
}
#[test]
fn unravel_index() {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.unravel_index(33), vec![0, 1, 0, 3]);
assert_eq!(t.unravel_index(57), vec![0, 1, 4, 3]);
assert_eq!(t.unravel_index(175), vec![1, 1, 4, 1]);
assert_eq!(t.unravel_index(300), vec![2, 2, 0, 0]);
}
|
// Ravelling and unravelling indices
|
random_line_split
|
namednodemap.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeHandlers, Element, ElementHelpers};
use dom::window::Window;
use util::namespace;
use util::str::DOMString;
use string_cache::Atom;
#[dom_struct]
pub struct NamedNodeMap {
reflector_: Reflector,
owner: JS<Element>,
}
impl NamedNodeMap {
fn new_inherited(elem: JSRef<Element>) -> NamedNodeMap {
NamedNodeMap {
reflector_: Reflector::new(),
owner: JS::from_rooted(elem),
}
}
pub fn new(window: JSRef<Window>, elem: JSRef<Element>) -> Temporary<NamedNodeMap> {
reflect_dom_object(box NamedNodeMap::new_inherited(elem),
GlobalRef::Window(window), NamedNodeMapBinding::Wrap)
}
}
impl<'a> NamedNodeMapMethods for JSRef<'a, NamedNodeMap> {
// https://dom.spec.whatwg.org/#dom-namednodemap-length
fn Length(self) -> u32 {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let attrs = owner.attrs();
attrs.len() as u32
}
// https://dom.spec.whatwg.org/#dom-namednodemap-item
fn Item(self, index: u32) -> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let attrs = owner.attrs();
attrs.get(index as usize).map(|x| Temporary::new(x.clone()))
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditem
fn
|
(self, name: DOMString) -> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
owner.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns
fn GetNamedItemNS(self, namespace: Option<DOMString>, local_name: DOMString)
-> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let ns = namespace::from_domstring(namespace);
owner.get_attribute(&ns, &Atom::from_slice(&local_name))
}
// https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem
fn RemoveNamedItem(self, name: DOMString) -> Fallible<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let name = owner.parsed_name(name);
owner.remove_attribute_by_name(&Atom::from_slice(&name)).ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns
fn RemoveNamedItemNS(self, namespace: Option<DOMString>, local_name: DOMString)
-> Fallible<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let ns = namespace::from_domstring(namespace);
owner.remove_attribute(&ns, &Atom::from_slice(&local_name)).ok_or(Error::NotFound)
}
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<Attr>> {
let item = self.Item(index);
*found = item.is_some();
item
}
fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<Temporary<Attr>> {
let item = self.GetNamedItem(name);
*found = item.is_some();
item
}
}
|
GetNamedItem
|
identifier_name
|
namednodemap.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeHandlers, Element, ElementHelpers};
use dom::window::Window;
use util::namespace;
use util::str::DOMString;
use string_cache::Atom;
#[dom_struct]
pub struct NamedNodeMap {
reflector_: Reflector,
owner: JS<Element>,
}
impl NamedNodeMap {
fn new_inherited(elem: JSRef<Element>) -> NamedNodeMap {
NamedNodeMap {
reflector_: Reflector::new(),
owner: JS::from_rooted(elem),
}
}
pub fn new(window: JSRef<Window>, elem: JSRef<Element>) -> Temporary<NamedNodeMap> {
reflect_dom_object(box NamedNodeMap::new_inherited(elem),
GlobalRef::Window(window), NamedNodeMapBinding::Wrap)
}
}
impl<'a> NamedNodeMapMethods for JSRef<'a, NamedNodeMap> {
// https://dom.spec.whatwg.org/#dom-namednodemap-length
fn Length(self) -> u32 {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let attrs = owner.attrs();
attrs.len() as u32
}
// https://dom.spec.whatwg.org/#dom-namednodemap-item
fn Item(self, index: u32) -> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let attrs = owner.attrs();
attrs.get(index as usize).map(|x| Temporary::new(x.clone()))
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditem
fn GetNamedItem(self, name: DOMString) -> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
owner.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns
fn GetNamedItemNS(self, namespace: Option<DOMString>, local_name: DOMString)
-> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let ns = namespace::from_domstring(namespace);
owner.get_attribute(&ns, &Atom::from_slice(&local_name))
}
// https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem
fn RemoveNamedItem(self, name: DOMString) -> Fallible<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let name = owner.parsed_name(name);
owner.remove_attribute_by_name(&Atom::from_slice(&name)).ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns
fn RemoveNamedItemNS(self, namespace: Option<DOMString>, local_name: DOMString)
-> Fallible<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let ns = namespace::from_domstring(namespace);
owner.remove_attribute(&ns, &Atom::from_slice(&local_name)).ok_or(Error::NotFound)
}
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<Attr>> {
let item = self.Item(index);
*found = item.is_some();
item
}
fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<Temporary<Attr>>
|
}
|
{
let item = self.GetNamedItem(name);
*found = item.is_some();
item
}
|
identifier_body
|
namednodemap.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods;
use dom::bindings::error::{Error, Fallible};
|
use dom::window::Window;
use util::namespace;
use util::str::DOMString;
use string_cache::Atom;
#[dom_struct]
pub struct NamedNodeMap {
reflector_: Reflector,
owner: JS<Element>,
}
impl NamedNodeMap {
fn new_inherited(elem: JSRef<Element>) -> NamedNodeMap {
NamedNodeMap {
reflector_: Reflector::new(),
owner: JS::from_rooted(elem),
}
}
pub fn new(window: JSRef<Window>, elem: JSRef<Element>) -> Temporary<NamedNodeMap> {
reflect_dom_object(box NamedNodeMap::new_inherited(elem),
GlobalRef::Window(window), NamedNodeMapBinding::Wrap)
}
}
impl<'a> NamedNodeMapMethods for JSRef<'a, NamedNodeMap> {
// https://dom.spec.whatwg.org/#dom-namednodemap-length
fn Length(self) -> u32 {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let attrs = owner.attrs();
attrs.len() as u32
}
// https://dom.spec.whatwg.org/#dom-namednodemap-item
fn Item(self, index: u32) -> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let attrs = owner.attrs();
attrs.get(index as usize).map(|x| Temporary::new(x.clone()))
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditem
fn GetNamedItem(self, name: DOMString) -> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
owner.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns
fn GetNamedItemNS(self, namespace: Option<DOMString>, local_name: DOMString)
-> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let ns = namespace::from_domstring(namespace);
owner.get_attribute(&ns, &Atom::from_slice(&local_name))
}
// https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem
fn RemoveNamedItem(self, name: DOMString) -> Fallible<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let name = owner.parsed_name(name);
owner.remove_attribute_by_name(&Atom::from_slice(&name)).ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns
fn RemoveNamedItemNS(self, namespace: Option<DOMString>, local_name: DOMString)
-> Fallible<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
let ns = namespace::from_domstring(namespace);
owner.remove_attribute(&ns, &Atom::from_slice(&local_name)).ok_or(Error::NotFound)
}
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<Attr>> {
let item = self.Item(index);
*found = item.is_some();
item
}
fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<Temporary<Attr>> {
let item = self.GetNamedItem(name);
*found = item.is_some();
item
}
}
|
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeHandlers, Element, ElementHelpers};
|
random_line_split
|
lib.rs
|
//! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_error;
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive_state;
#[cfg(feature = "serde_state")]
#[macro_use]
extern crate serde_state as serde;
#[cfg(feature = "serde_state")]
extern crate serde_json;
#[cfg(test)]
extern crate env_logger;
#[macro_use]
pub extern crate gluon_base as base;
extern crate gluon_check as check;
#[macro_use]
extern crate gluon_codegen;
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
pub type BoxFuture<'vm, T, E> = futures::future::BoxFuture<'vm, std::result::Result<T, E>>;
macro_rules! alloc {
($context: ident, $data: expr) => {
$crate::thread::alloc($context.gc, $context.thread, &$context.stack.stack(), $data)
};
}
#[macro_use]
#[cfg(feature = "serde")]
pub mod serialization;
#[macro_use]
pub mod gc;
#[macro_use]
pub mod api;
pub mod channel;
pub mod compiler;
pub mod core;
pub mod debug;
pub mod dynamic;
pub mod lazy;
pub mod macros;
pub mod primitives;
pub mod reference;
pub mod stack;
pub mod thread;
pub mod types;
pub mod vm;
mod array;
mod derive;
mod interner;
mod source_map;
mod value;
use std::{self as real_std, fmt, marker::PhantomData};
use crate::base::{metadata::Metadata, source::FileId, symbol::Symbol, types::ArcType};
use crate::{
api::{ValueRef, VmType},
gc::CloneUnrooted,
stack::Stacktrace,
thread::{RootedThread, RootedValue, Thread},
types::{VmIndex, VmInt},
value::{Value, ValueRepr},
};
use codespan_reporting::diagnostic::Diagnostic;
unsafe fn forget_lifetime<'a, 'b, T:?Sized>(x: &'a T) -> &'b T {
::std::mem::transmute(x)
}
#[derive(Debug, PartialEq, Trace)]
#[gluon(gluon_vm)]
#[repr(transparent)]
pub struct Variants<'a>(ValueRepr, PhantomData<&'a Value>);
impl Clone for Variants<'_> {
fn clone(&self) -> Self {
// SAFETY Cloning keeps the same lifetime as `self`
unsafe { Variants(self.0.clone_unrooted(), self.1) }
}
}
impl<'a> Variants<'a> {
/// Creates a new `Variants` value which assumes that `value` is rooted for the lifetime of the
/// value
#[inline]
pub fn new(value: &Value) -> Variants {
// SAFETY The returned value is tied to the lifetime of the `value` root meaning the
// variant is also rooted
unsafe { Variants::with_root(value, value) }
}
#[inline]
pub(crate) unsafe fn with_root<'r, T:?Sized>(value: &Value, _root: &'r T) -> Variants<'r> {
Variants(value.get_repr().clone_unrooted(), PhantomData)
}
#[inline]
pub(crate) fn int(i: VmInt) -> Self {
Variants(ValueRepr::Int(i), PhantomData)
}
#[inline]
pub(crate) fn tag(i: VmIndex) -> Self {
Variants(ValueRepr::Tag(i), PhantomData)
}
#[inline]
pub fn get_value(&self) -> &Value {
Value::from_ref(&self.0)
}
#[inline]
pub(crate) fn get_repr(&self) -> &ValueRepr {
&self.0
}
pub(crate) unsafe fn unrooted(&self) -> Value {
Value::from(self.0.clone_unrooted())
}
/// Returns an instance of `ValueRef` which allows users to safely retrieve the interals of a
/// value
#[inline]
pub fn as_ref(&self) -> ValueRef<'a> {
unsafe { ValueRef::rooted_new(&self.0) }
}
}
/// Type returned from vm functions which may fail
pub type Result<T> = ::std::result::Result<T, Error>;
quick_error! {
/// Representation of all possible errors that can occur when interacting with the `vm` crate
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum Error {
Dead {
display("The gluon thread is dead")
}
UndefinedBinding(symbol: String) {
display("Binding `{}` is not defined", symbol)
}
UndefinedField(typ: ArcType, field: String) {
display("Type `{}` does not have the field `{}`", typ, field)
}
TypeAlreadyExists(symbol: String) {
display("Type `{}` already exists", symbol)
}
GlobalAlreadyExists(symbol: Symbol) {
display("Global `{}` already exists", symbol)
}
MetadataDoesNotExist(symbol: String) {
display("No metadata exists for `{}`", symbol)
}
WrongType(expected: ArcType, actual: ArcType) {
display("Expected a value of type `{}` but the returned type was `{}`",
expected, actual)
}
OutOfMemory { limit: usize, needed: usize } {
display("Thread is out of memory: Limit {}, needed {}", limit, needed)
}
StackOverflow(limit: VmIndex) {
display("The stack has overflowed: Limit `{}`", limit)
}
Message(err: String) {
display("{}", err)
from()
}
Interrupted {
display("Thread was interrupted")
}
Panic(err: String, stacktrace: Option<Stacktrace>) {
display("{}", Panic { err, stacktrace })
}
}
}
impl base::error::AsDiagnostic for Error {
fn as_diagnostic(&self, _map: &base::source::CodeMap) -> Diagnostic<FileId> {
Diagnostic::error().with_message(self.to_string())
}
}
struct Panic<'a> {
err: &'a String,
stacktrace: &'a Option<Stacktrace>,
}
impl<'a> fmt::Display for Panic<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Panic { err, stacktrace } = *self;
write!(f, "{}", err)?;
if let Some(ref stacktrace) = *stacktrace {
write!(f, "\n\n{}", stacktrace)?;
}
Ok(())
}
}
impl fmt::Debug for ExternLoader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ExternLoader")
.field("dependencies", &self.dependencies)
.finish()
}
}
pub struct ExternLoader {
pub load_fn: Box<dyn Fn(&Thread) -> Result<ExternModule> + Send + Sync>,
pub dependencies: Vec<String>,
}
#[derive(Debug)]
pub struct ExternModule {
pub metadata: Metadata,
pub value: RootedValue<RootedThread>,
pub typ: ArcType,
}
impl ExternModule {
pub fn new<'vm, T>(thread: &'vm Thread, value: T) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
ExternModule::with_metadata(thread, value, Metadata::default())
}
pub fn with_metadata<'vm, T>(
thread: &'vm Thread,
value: T,
metadata: Metadata,
) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
Ok(ExternModule {
value: value.marshal(thread)?,
typ: T::make_forall_type(thread),
metadata,
})
|
}
}
/// Internal types and functions exposed to the main `gluon` crate
pub mod internal {
pub use crate::interner::InternedStr;
pub use crate::value::{Cloner, ClosureData, Value, ValuePrinter};
pub use crate::vm::Global;
}
|
random_line_split
|
|
lib.rs
|
//! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_error;
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive_state;
#[cfg(feature = "serde_state")]
#[macro_use]
extern crate serde_state as serde;
#[cfg(feature = "serde_state")]
extern crate serde_json;
#[cfg(test)]
extern crate env_logger;
#[macro_use]
pub extern crate gluon_base as base;
extern crate gluon_check as check;
#[macro_use]
extern crate gluon_codegen;
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
pub type BoxFuture<'vm, T, E> = futures::future::BoxFuture<'vm, std::result::Result<T, E>>;
macro_rules! alloc {
($context: ident, $data: expr) => {
$crate::thread::alloc($context.gc, $context.thread, &$context.stack.stack(), $data)
};
}
#[macro_use]
#[cfg(feature = "serde")]
pub mod serialization;
#[macro_use]
pub mod gc;
#[macro_use]
pub mod api;
pub mod channel;
pub mod compiler;
pub mod core;
pub mod debug;
pub mod dynamic;
pub mod lazy;
pub mod macros;
pub mod primitives;
pub mod reference;
pub mod stack;
pub mod thread;
pub mod types;
pub mod vm;
mod array;
mod derive;
mod interner;
mod source_map;
mod value;
use std::{self as real_std, fmt, marker::PhantomData};
use crate::base::{metadata::Metadata, source::FileId, symbol::Symbol, types::ArcType};
use crate::{
api::{ValueRef, VmType},
gc::CloneUnrooted,
stack::Stacktrace,
thread::{RootedThread, RootedValue, Thread},
types::{VmIndex, VmInt},
value::{Value, ValueRepr},
};
use codespan_reporting::diagnostic::Diagnostic;
unsafe fn forget_lifetime<'a, 'b, T:?Sized>(x: &'a T) -> &'b T {
::std::mem::transmute(x)
}
#[derive(Debug, PartialEq, Trace)]
#[gluon(gluon_vm)]
#[repr(transparent)]
pub struct Variants<'a>(ValueRepr, PhantomData<&'a Value>);
impl Clone for Variants<'_> {
fn clone(&self) -> Self {
// SAFETY Cloning keeps the same lifetime as `self`
unsafe { Variants(self.0.clone_unrooted(), self.1) }
}
}
impl<'a> Variants<'a> {
/// Creates a new `Variants` value which assumes that `value` is rooted for the lifetime of the
/// value
#[inline]
pub fn new(value: &Value) -> Variants {
// SAFETY The returned value is tied to the lifetime of the `value` root meaning the
// variant is also rooted
unsafe { Variants::with_root(value, value) }
}
#[inline]
pub(crate) unsafe fn with_root<'r, T:?Sized>(value: &Value, _root: &'r T) -> Variants<'r> {
Variants(value.get_repr().clone_unrooted(), PhantomData)
}
#[inline]
pub(crate) fn int(i: VmInt) -> Self {
Variants(ValueRepr::Int(i), PhantomData)
}
#[inline]
pub(crate) fn tag(i: VmIndex) -> Self {
Variants(ValueRepr::Tag(i), PhantomData)
}
#[inline]
pub fn get_value(&self) -> &Value {
Value::from_ref(&self.0)
}
#[inline]
pub(crate) fn get_repr(&self) -> &ValueRepr {
&self.0
}
pub(crate) unsafe fn unrooted(&self) -> Value {
Value::from(self.0.clone_unrooted())
}
/// Returns an instance of `ValueRef` which allows users to safely retrieve the interals of a
/// value
#[inline]
pub fn as_ref(&self) -> ValueRef<'a>
|
}
/// Type returned from vm functions which may fail
pub type Result<T> = ::std::result::Result<T, Error>;
quick_error! {
/// Representation of all possible errors that can occur when interacting with the `vm` crate
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum Error {
Dead {
display("The gluon thread is dead")
}
UndefinedBinding(symbol: String) {
display("Binding `{}` is not defined", symbol)
}
UndefinedField(typ: ArcType, field: String) {
display("Type `{}` does not have the field `{}`", typ, field)
}
TypeAlreadyExists(symbol: String) {
display("Type `{}` already exists", symbol)
}
GlobalAlreadyExists(symbol: Symbol) {
display("Global `{}` already exists", symbol)
}
MetadataDoesNotExist(symbol: String) {
display("No metadata exists for `{}`", symbol)
}
WrongType(expected: ArcType, actual: ArcType) {
display("Expected a value of type `{}` but the returned type was `{}`",
expected, actual)
}
OutOfMemory { limit: usize, needed: usize } {
display("Thread is out of memory: Limit {}, needed {}", limit, needed)
}
StackOverflow(limit: VmIndex) {
display("The stack has overflowed: Limit `{}`", limit)
}
Message(err: String) {
display("{}", err)
from()
}
Interrupted {
display("Thread was interrupted")
}
Panic(err: String, stacktrace: Option<Stacktrace>) {
display("{}", Panic { err, stacktrace })
}
}
}
impl base::error::AsDiagnostic for Error {
fn as_diagnostic(&self, _map: &base::source::CodeMap) -> Diagnostic<FileId> {
Diagnostic::error().with_message(self.to_string())
}
}
struct Panic<'a> {
err: &'a String,
stacktrace: &'a Option<Stacktrace>,
}
impl<'a> fmt::Display for Panic<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Panic { err, stacktrace } = *self;
write!(f, "{}", err)?;
if let Some(ref stacktrace) = *stacktrace {
write!(f, "\n\n{}", stacktrace)?;
}
Ok(())
}
}
impl fmt::Debug for ExternLoader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ExternLoader")
.field("dependencies", &self.dependencies)
.finish()
}
}
pub struct ExternLoader {
pub load_fn: Box<dyn Fn(&Thread) -> Result<ExternModule> + Send + Sync>,
pub dependencies: Vec<String>,
}
#[derive(Debug)]
pub struct ExternModule {
pub metadata: Metadata,
pub value: RootedValue<RootedThread>,
pub typ: ArcType,
}
impl ExternModule {
pub fn new<'vm, T>(thread: &'vm Thread, value: T) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
ExternModule::with_metadata(thread, value, Metadata::default())
}
pub fn with_metadata<'vm, T>(
thread: &'vm Thread,
value: T,
metadata: Metadata,
) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
Ok(ExternModule {
value: value.marshal(thread)?,
typ: T::make_forall_type(thread),
metadata,
})
}
}
/// Internal types and functions exposed to the main `gluon` crate
pub mod internal {
pub use crate::interner::InternedStr;
pub use crate::value::{Cloner, ClosureData, Value, ValuePrinter};
pub use crate::vm::Global;
}
|
{
unsafe { ValueRef::rooted_new(&self.0) }
}
|
identifier_body
|
lib.rs
|
//! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_error;
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive_state;
#[cfg(feature = "serde_state")]
#[macro_use]
extern crate serde_state as serde;
#[cfg(feature = "serde_state")]
extern crate serde_json;
#[cfg(test)]
extern crate env_logger;
#[macro_use]
pub extern crate gluon_base as base;
extern crate gluon_check as check;
#[macro_use]
extern crate gluon_codegen;
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
pub type BoxFuture<'vm, T, E> = futures::future::BoxFuture<'vm, std::result::Result<T, E>>;
macro_rules! alloc {
($context: ident, $data: expr) => {
$crate::thread::alloc($context.gc, $context.thread, &$context.stack.stack(), $data)
};
}
#[macro_use]
#[cfg(feature = "serde")]
pub mod serialization;
#[macro_use]
pub mod gc;
#[macro_use]
pub mod api;
pub mod channel;
pub mod compiler;
pub mod core;
pub mod debug;
pub mod dynamic;
pub mod lazy;
pub mod macros;
pub mod primitives;
pub mod reference;
pub mod stack;
pub mod thread;
pub mod types;
pub mod vm;
mod array;
mod derive;
mod interner;
mod source_map;
mod value;
use std::{self as real_std, fmt, marker::PhantomData};
use crate::base::{metadata::Metadata, source::FileId, symbol::Symbol, types::ArcType};
use crate::{
api::{ValueRef, VmType},
gc::CloneUnrooted,
stack::Stacktrace,
thread::{RootedThread, RootedValue, Thread},
types::{VmIndex, VmInt},
value::{Value, ValueRepr},
};
use codespan_reporting::diagnostic::Diagnostic;
unsafe fn forget_lifetime<'a, 'b, T:?Sized>(x: &'a T) -> &'b T {
::std::mem::transmute(x)
}
#[derive(Debug, PartialEq, Trace)]
#[gluon(gluon_vm)]
#[repr(transparent)]
pub struct Variants<'a>(ValueRepr, PhantomData<&'a Value>);
impl Clone for Variants<'_> {
fn clone(&self) -> Self {
// SAFETY Cloning keeps the same lifetime as `self`
unsafe { Variants(self.0.clone_unrooted(), self.1) }
}
}
impl<'a> Variants<'a> {
/// Creates a new `Variants` value which assumes that `value` is rooted for the lifetime of the
/// value
#[inline]
pub fn new(value: &Value) -> Variants {
// SAFETY The returned value is tied to the lifetime of the `value` root meaning the
// variant is also rooted
unsafe { Variants::with_root(value, value) }
}
#[inline]
pub(crate) unsafe fn with_root<'r, T:?Sized>(value: &Value, _root: &'r T) -> Variants<'r> {
Variants(value.get_repr().clone_unrooted(), PhantomData)
}
#[inline]
pub(crate) fn int(i: VmInt) -> Self {
Variants(ValueRepr::Int(i), PhantomData)
}
#[inline]
pub(crate) fn tag(i: VmIndex) -> Self {
Variants(ValueRepr::Tag(i), PhantomData)
}
#[inline]
pub fn get_value(&self) -> &Value {
Value::from_ref(&self.0)
}
#[inline]
pub(crate) fn get_repr(&self) -> &ValueRepr {
&self.0
}
pub(crate) unsafe fn unrooted(&self) -> Value {
Value::from(self.0.clone_unrooted())
}
/// Returns an instance of `ValueRef` which allows users to safely retrieve the interals of a
/// value
#[inline]
pub fn as_ref(&self) -> ValueRef<'a> {
unsafe { ValueRef::rooted_new(&self.0) }
}
}
/// Type returned from vm functions which may fail
pub type Result<T> = ::std::result::Result<T, Error>;
quick_error! {
/// Representation of all possible errors that can occur when interacting with the `vm` crate
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum Error {
Dead {
display("The gluon thread is dead")
}
UndefinedBinding(symbol: String) {
display("Binding `{}` is not defined", symbol)
}
UndefinedField(typ: ArcType, field: String) {
display("Type `{}` does not have the field `{}`", typ, field)
}
TypeAlreadyExists(symbol: String) {
display("Type `{}` already exists", symbol)
}
GlobalAlreadyExists(symbol: Symbol) {
display("Global `{}` already exists", symbol)
}
MetadataDoesNotExist(symbol: String) {
display("No metadata exists for `{}`", symbol)
}
WrongType(expected: ArcType, actual: ArcType) {
display("Expected a value of type `{}` but the returned type was `{}`",
expected, actual)
}
OutOfMemory { limit: usize, needed: usize } {
display("Thread is out of memory: Limit {}, needed {}", limit, needed)
}
StackOverflow(limit: VmIndex) {
display("The stack has overflowed: Limit `{}`", limit)
}
Message(err: String) {
display("{}", err)
from()
}
Interrupted {
display("Thread was interrupted")
}
Panic(err: String, stacktrace: Option<Stacktrace>) {
display("{}", Panic { err, stacktrace })
}
}
}
impl base::error::AsDiagnostic for Error {
fn
|
(&self, _map: &base::source::CodeMap) -> Diagnostic<FileId> {
Diagnostic::error().with_message(self.to_string())
}
}
struct Panic<'a> {
err: &'a String,
stacktrace: &'a Option<Stacktrace>,
}
impl<'a> fmt::Display for Panic<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Panic { err, stacktrace } = *self;
write!(f, "{}", err)?;
if let Some(ref stacktrace) = *stacktrace {
write!(f, "\n\n{}", stacktrace)?;
}
Ok(())
}
}
impl fmt::Debug for ExternLoader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ExternLoader")
.field("dependencies", &self.dependencies)
.finish()
}
}
pub struct ExternLoader {
pub load_fn: Box<dyn Fn(&Thread) -> Result<ExternModule> + Send + Sync>,
pub dependencies: Vec<String>,
}
#[derive(Debug)]
pub struct ExternModule {
pub metadata: Metadata,
pub value: RootedValue<RootedThread>,
pub typ: ArcType,
}
impl ExternModule {
pub fn new<'vm, T>(thread: &'vm Thread, value: T) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
ExternModule::with_metadata(thread, value, Metadata::default())
}
pub fn with_metadata<'vm, T>(
thread: &'vm Thread,
value: T,
metadata: Metadata,
) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
Ok(ExternModule {
value: value.marshal(thread)?,
typ: T::make_forall_type(thread),
metadata,
})
}
}
/// Internal types and functions exposed to the main `gluon` crate
pub mod internal {
pub use crate::interner::InternedStr;
pub use crate::value::{Cloner, ClosureData, Value, ValuePrinter};
pub use crate::vm::Global;
}
|
as_diagnostic
|
identifier_name
|
lib.rs
|
//! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_error;
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive_state;
#[cfg(feature = "serde_state")]
#[macro_use]
extern crate serde_state as serde;
#[cfg(feature = "serde_state")]
extern crate serde_json;
#[cfg(test)]
extern crate env_logger;
#[macro_use]
pub extern crate gluon_base as base;
extern crate gluon_check as check;
#[macro_use]
extern crate gluon_codegen;
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
pub type BoxFuture<'vm, T, E> = futures::future::BoxFuture<'vm, std::result::Result<T, E>>;
macro_rules! alloc {
($context: ident, $data: expr) => {
$crate::thread::alloc($context.gc, $context.thread, &$context.stack.stack(), $data)
};
}
#[macro_use]
#[cfg(feature = "serde")]
pub mod serialization;
#[macro_use]
pub mod gc;
#[macro_use]
pub mod api;
pub mod channel;
pub mod compiler;
pub mod core;
pub mod debug;
pub mod dynamic;
pub mod lazy;
pub mod macros;
pub mod primitives;
pub mod reference;
pub mod stack;
pub mod thread;
pub mod types;
pub mod vm;
mod array;
mod derive;
mod interner;
mod source_map;
mod value;
use std::{self as real_std, fmt, marker::PhantomData};
use crate::base::{metadata::Metadata, source::FileId, symbol::Symbol, types::ArcType};
use crate::{
api::{ValueRef, VmType},
gc::CloneUnrooted,
stack::Stacktrace,
thread::{RootedThread, RootedValue, Thread},
types::{VmIndex, VmInt},
value::{Value, ValueRepr},
};
use codespan_reporting::diagnostic::Diagnostic;
unsafe fn forget_lifetime<'a, 'b, T:?Sized>(x: &'a T) -> &'b T {
::std::mem::transmute(x)
}
#[derive(Debug, PartialEq, Trace)]
#[gluon(gluon_vm)]
#[repr(transparent)]
pub struct Variants<'a>(ValueRepr, PhantomData<&'a Value>);
impl Clone for Variants<'_> {
fn clone(&self) -> Self {
// SAFETY Cloning keeps the same lifetime as `self`
unsafe { Variants(self.0.clone_unrooted(), self.1) }
}
}
impl<'a> Variants<'a> {
/// Creates a new `Variants` value which assumes that `value` is rooted for the lifetime of the
/// value
#[inline]
pub fn new(value: &Value) -> Variants {
// SAFETY The returned value is tied to the lifetime of the `value` root meaning the
// variant is also rooted
unsafe { Variants::with_root(value, value) }
}
#[inline]
pub(crate) unsafe fn with_root<'r, T:?Sized>(value: &Value, _root: &'r T) -> Variants<'r> {
Variants(value.get_repr().clone_unrooted(), PhantomData)
}
#[inline]
pub(crate) fn int(i: VmInt) -> Self {
Variants(ValueRepr::Int(i), PhantomData)
}
#[inline]
pub(crate) fn tag(i: VmIndex) -> Self {
Variants(ValueRepr::Tag(i), PhantomData)
}
#[inline]
pub fn get_value(&self) -> &Value {
Value::from_ref(&self.0)
}
#[inline]
pub(crate) fn get_repr(&self) -> &ValueRepr {
&self.0
}
pub(crate) unsafe fn unrooted(&self) -> Value {
Value::from(self.0.clone_unrooted())
}
/// Returns an instance of `ValueRef` which allows users to safely retrieve the interals of a
/// value
#[inline]
pub fn as_ref(&self) -> ValueRef<'a> {
unsafe { ValueRef::rooted_new(&self.0) }
}
}
/// Type returned from vm functions which may fail
pub type Result<T> = ::std::result::Result<T, Error>;
quick_error! {
/// Representation of all possible errors that can occur when interacting with the `vm` crate
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum Error {
Dead {
display("The gluon thread is dead")
}
UndefinedBinding(symbol: String) {
display("Binding `{}` is not defined", symbol)
}
UndefinedField(typ: ArcType, field: String) {
display("Type `{}` does not have the field `{}`", typ, field)
}
TypeAlreadyExists(symbol: String) {
display("Type `{}` already exists", symbol)
}
GlobalAlreadyExists(symbol: Symbol) {
display("Global `{}` already exists", symbol)
}
MetadataDoesNotExist(symbol: String) {
display("No metadata exists for `{}`", symbol)
}
WrongType(expected: ArcType, actual: ArcType) {
display("Expected a value of type `{}` but the returned type was `{}`",
expected, actual)
}
OutOfMemory { limit: usize, needed: usize } {
display("Thread is out of memory: Limit {}, needed {}", limit, needed)
}
StackOverflow(limit: VmIndex) {
display("The stack has overflowed: Limit `{}`", limit)
}
Message(err: String) {
display("{}", err)
from()
}
Interrupted {
display("Thread was interrupted")
}
Panic(err: String, stacktrace: Option<Stacktrace>) {
display("{}", Panic { err, stacktrace })
}
}
}
impl base::error::AsDiagnostic for Error {
fn as_diagnostic(&self, _map: &base::source::CodeMap) -> Diagnostic<FileId> {
Diagnostic::error().with_message(self.to_string())
}
}
struct Panic<'a> {
err: &'a String,
stacktrace: &'a Option<Stacktrace>,
}
impl<'a> fmt::Display for Panic<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Panic { err, stacktrace } = *self;
write!(f, "{}", err)?;
if let Some(ref stacktrace) = *stacktrace
|
Ok(())
}
}
impl fmt::Debug for ExternLoader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ExternLoader")
.field("dependencies", &self.dependencies)
.finish()
}
}
pub struct ExternLoader {
pub load_fn: Box<dyn Fn(&Thread) -> Result<ExternModule> + Send + Sync>,
pub dependencies: Vec<String>,
}
#[derive(Debug)]
pub struct ExternModule {
pub metadata: Metadata,
pub value: RootedValue<RootedThread>,
pub typ: ArcType,
}
impl ExternModule {
pub fn new<'vm, T>(thread: &'vm Thread, value: T) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
ExternModule::with_metadata(thread, value, Metadata::default())
}
pub fn with_metadata<'vm, T>(
thread: &'vm Thread,
value: T,
metadata: Metadata,
) -> Result<ExternModule>
where
T: VmType + api::Pushable<'vm> + Send + Sync,
{
Ok(ExternModule {
value: value.marshal(thread)?,
typ: T::make_forall_type(thread),
metadata,
})
}
}
/// Internal types and functions exposed to the main `gluon` crate
pub mod internal {
pub use crate::interner::InternedStr;
pub use crate::value::{Cloner, ClosureData, Value, ValuePrinter};
pub use crate::vm::Global;
}
|
{
write!(f, "\n\n{}", stacktrace)?;
}
|
conditional_block
|
associated-types-struct-field-numbered.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we correctly normalize the type of a struct field
// which has an associated type.
pub trait UnifyKey {
type Value;
}
pub struct Node<K:UnifyKey>(K, K::Value);
fn foo<K : UnifyKey<Value=Option<V>>,V : Clone>(node: &Node<K>) -> Option<V> {
node.1.clone()
}
impl UnifyKey for i32 {
type Value = Option<u32>;
}
impl UnifyKey for u32 {
type Value = Option<i32>;
}
pub fn main()
|
{
let node: Node<i32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_u32));
let node: Node<u32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_i32));
}
|
identifier_body
|
|
associated-types-struct-field-numbered.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we correctly normalize the type of a struct field
// which has an associated type.
pub trait UnifyKey {
type Value;
}
pub struct Node<K:UnifyKey>(K, K::Value);
fn
|
<K : UnifyKey<Value=Option<V>>,V : Clone>(node: &Node<K>) -> Option<V> {
node.1.clone()
}
impl UnifyKey for i32 {
type Value = Option<u32>;
}
impl UnifyKey for u32 {
type Value = Option<i32>;
}
pub fn main() {
let node: Node<i32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_u32));
let node: Node<u32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_i32));
}
|
foo
|
identifier_name
|
associated-types-struct-field-numbered.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we correctly normalize the type of a struct field
// which has an associated type.
pub trait UnifyKey {
type Value;
}
pub struct Node<K:UnifyKey>(K, K::Value);
fn foo<K : UnifyKey<Value=Option<V>>,V : Clone>(node: &Node<K>) -> Option<V> {
node.1.clone()
}
impl UnifyKey for i32 {
type Value = Option<u32>;
}
impl UnifyKey for u32 {
type Value = Option<i32>;
}
|
let node: Node<u32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_i32));
}
|
pub fn main() {
let node: Node<i32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_u32));
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.