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 |
---|---|---|---|---|
adding_prob_src.rs
|
extern crate rand;
use rand::distributions::{Range, IndependentSample};
use af;
use af::{Array, Dim4, MatProp, DType};
use std::cell::{RefCell, Cell};
use initializations::uniform;
use utils;
use data::{Data, DataSource, DataParams, Normalize, Shuffle};
pub struct AddingProblemSource {
pub params: DataParams,
pub iter: Cell<u64>,
pub offset: Cell<f32>,
pub bptt_unroll : u64,
}
impl AddingProblemSource {
pub fn new(batch_size: u64, bptt_unroll: u64, dtype: DType, max_samples: u64) -> AddingProblemSource
{
assert!(bptt_unroll % 4 == 0, "The number of time steps has to be divisible by 4 for the adding problem");
let input_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let target_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let train_samples = 0.7 * max_samples as f32;
let test_samples = 0.2 * max_samples as f32;
let validation_samples = 0.1 * max_samples as f32;
AddingProblemSource {
params : DataParams {
input_dims: input_dims,
target_dims: target_dims,
dtype: dtype,
normalize: false,
shuffle: false,
current_epoch: Cell::new(0),
num_samples: max_samples,
num_train: train_samples as u64,
num_test: test_samples as u64,
num_validation: Some(validation_samples as u64),
},
iter: Cell::new(0),
offset: Cell::new(0.0f32),
bptt_unroll: bptt_unroll,
}
}
fn generate_input(&self, batch_size: u64, bptt_unroll: u64) -> Array {
let dim1 = Dim4::new(&[batch_size, 1, bptt_unroll/2, 1]);
let ar1 = uniform::<f32>(dim1,-1.0, 1.0);
let between1 = Range::new(0, bptt_unroll/4);
let between2 = Range::new(bptt_unroll/4, bptt_unroll/2);
let mut rng1 = rand::thread_rng();
let mut rng2 = rand::thread_rng();
let mut vec_total = Vec::with_capacity((batch_size*bptt_unroll) as usize);
let vec_zeros = vec!(0f32; (bptt_unroll/2) as usize);
for _ in 0..batch_size {
let index1 = between1.ind_sample(&mut rng1) as usize;
let index2 = between2.ind_sample(&mut rng2) as usize;
let mut vec_temp = vec_zeros.clone();
vec_temp[index1] = 1f32;
vec_temp[index2] = 1f32;
vec_total.extend(vec_temp);
}
let dim2 = Dim4::new(&[bptt_unroll/2, batch_size, 1, 1]);
let ar2 = af::moddims(&af::transpose(&utils::vec_to_array::<f32>(vec_total, dim2), false), dim1);
af::join(2, &ar1, &ar2)
}
fn generate_target(&self, input: &Array, batch_size: u64, bptt_unroll: u64) -> Array {
let first = af::slices(&input, 0, bptt_unroll/2-1);
let second = af::slices(&input, bptt_unroll/2, bptt_unroll-1);
let ar = af::mul(&first, &second, false);
let zeros = af::constant(0f32, Dim4::new(&[batch_size, 1, bptt_unroll, 1]));
af::add(&af::sum(&ar, 2), &zeros, true)
}
}
impl DataSource for AddingProblemSource {
fn get_train_iter(&self, num_batch: u64) -> Data {
let inp = self.generate_input(num_batch
, self.params.input_dims[2]);
let tar = self.generate_target(&inp
, num_batch
, self.params.input_dims[2]);
let batch = Data {
input: RefCell::new(Box::new(inp.clone())),
target: RefCell::new(Box::new(tar.clone())),
};
let current_iter = self.params.current_epoch.get();
if self.iter.get() == self.params.num_samples as u64/ num_batch as u64
|
self.iter.set(self.iter.get() + 1);
batch
}
fn info(&self) -> DataParams {
self.params.clone()
}
fn get_test_iter(&self, num_batch: u64) -> Data {
self.get_train_iter(num_batch)
}
fn get_validation_iter(&self, num_batch: u64) -> Option<Data> {
Some( self.get_train_iter(num_batch))
}
}
|
{
self.params.current_epoch.set(current_iter + 1);
self.iter.set(0);
}
|
conditional_block
|
adding_prob_src.rs
|
extern crate rand;
use rand::distributions::{Range, IndependentSample};
use af;
use af::{Array, Dim4, MatProp, DType};
use std::cell::{RefCell, Cell};
use initializations::uniform;
use utils;
use data::{Data, DataSource, DataParams, Normalize, Shuffle};
pub struct AddingProblemSource {
pub params: DataParams,
pub iter: Cell<u64>,
pub offset: Cell<f32>,
pub bptt_unroll : u64,
}
impl AddingProblemSource {
pub fn new(batch_size: u64, bptt_unroll: u64, dtype: DType, max_samples: u64) -> AddingProblemSource
{
assert!(bptt_unroll % 4 == 0, "The number of time steps has to be divisible by 4 for the adding problem");
let input_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let target_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let train_samples = 0.7 * max_samples as f32;
let test_samples = 0.2 * max_samples as f32;
let validation_samples = 0.1 * max_samples as f32;
AddingProblemSource {
params : DataParams {
input_dims: input_dims,
target_dims: target_dims,
dtype: dtype,
normalize: false,
shuffle: false,
current_epoch: Cell::new(0),
num_samples: max_samples,
num_train: train_samples as u64,
num_test: test_samples as u64,
num_validation: Some(validation_samples as u64),
},
iter: Cell::new(0),
offset: Cell::new(0.0f32),
bptt_unroll: bptt_unroll,
}
}
fn
|
(&self, batch_size: u64, bptt_unroll: u64) -> Array {
let dim1 = Dim4::new(&[batch_size, 1, bptt_unroll/2, 1]);
let ar1 = uniform::<f32>(dim1,-1.0, 1.0);
let between1 = Range::new(0, bptt_unroll/4);
let between2 = Range::new(bptt_unroll/4, bptt_unroll/2);
let mut rng1 = rand::thread_rng();
let mut rng2 = rand::thread_rng();
let mut vec_total = Vec::with_capacity((batch_size*bptt_unroll) as usize);
let vec_zeros = vec!(0f32; (bptt_unroll/2) as usize);
for _ in 0..batch_size {
let index1 = between1.ind_sample(&mut rng1) as usize;
let index2 = between2.ind_sample(&mut rng2) as usize;
let mut vec_temp = vec_zeros.clone();
vec_temp[index1] = 1f32;
vec_temp[index2] = 1f32;
vec_total.extend(vec_temp);
}
let dim2 = Dim4::new(&[bptt_unroll/2, batch_size, 1, 1]);
let ar2 = af::moddims(&af::transpose(&utils::vec_to_array::<f32>(vec_total, dim2), false), dim1);
af::join(2, &ar1, &ar2)
}
fn generate_target(&self, input: &Array, batch_size: u64, bptt_unroll: u64) -> Array {
let first = af::slices(&input, 0, bptt_unroll/2-1);
let second = af::slices(&input, bptt_unroll/2, bptt_unroll-1);
let ar = af::mul(&first, &second, false);
let zeros = af::constant(0f32, Dim4::new(&[batch_size, 1, bptt_unroll, 1]));
af::add(&af::sum(&ar, 2), &zeros, true)
}
}
impl DataSource for AddingProblemSource {
fn get_train_iter(&self, num_batch: u64) -> Data {
let inp = self.generate_input(num_batch
, self.params.input_dims[2]);
let tar = self.generate_target(&inp
, num_batch
, self.params.input_dims[2]);
let batch = Data {
input: RefCell::new(Box::new(inp.clone())),
target: RefCell::new(Box::new(tar.clone())),
};
let current_iter = self.params.current_epoch.get();
if self.iter.get() == self.params.num_samples as u64/ num_batch as u64 {
self.params.current_epoch.set(current_iter + 1);
self.iter.set(0);
}
self.iter.set(self.iter.get() + 1);
batch
}
fn info(&self) -> DataParams {
self.params.clone()
}
fn get_test_iter(&self, num_batch: u64) -> Data {
self.get_train_iter(num_batch)
}
fn get_validation_iter(&self, num_batch: u64) -> Option<Data> {
Some( self.get_train_iter(num_batch))
}
}
|
generate_input
|
identifier_name
|
adding_prob_src.rs
|
extern crate rand;
use rand::distributions::{Range, IndependentSample};
use af;
use af::{Array, Dim4, MatProp, DType};
use std::cell::{RefCell, Cell};
use initializations::uniform;
use utils;
use data::{Data, DataSource, DataParams, Normalize, Shuffle};
pub struct AddingProblemSource {
pub params: DataParams,
pub iter: Cell<u64>,
pub offset: Cell<f32>,
pub bptt_unroll : u64,
}
impl AddingProblemSource {
pub fn new(batch_size: u64, bptt_unroll: u64, dtype: DType, max_samples: u64) -> AddingProblemSource
|
iter: Cell::new(0),
offset: Cell::new(0.0f32),
bptt_unroll: bptt_unroll,
}
}
fn generate_input(&self, batch_size: u64, bptt_unroll: u64) -> Array {
let dim1 = Dim4::new(&[batch_size, 1, bptt_unroll/2, 1]);
let ar1 = uniform::<f32>(dim1,-1.0, 1.0);
let between1 = Range::new(0, bptt_unroll/4);
let between2 = Range::new(bptt_unroll/4, bptt_unroll/2);
let mut rng1 = rand::thread_rng();
let mut rng2 = rand::thread_rng();
let mut vec_total = Vec::with_capacity((batch_size*bptt_unroll) as usize);
let vec_zeros = vec!(0f32; (bptt_unroll/2) as usize);
for _ in 0..batch_size {
let index1 = between1.ind_sample(&mut rng1) as usize;
let index2 = between2.ind_sample(&mut rng2) as usize;
let mut vec_temp = vec_zeros.clone();
vec_temp[index1] = 1f32;
vec_temp[index2] = 1f32;
vec_total.extend(vec_temp);
}
let dim2 = Dim4::new(&[bptt_unroll/2, batch_size, 1, 1]);
let ar2 = af::moddims(&af::transpose(&utils::vec_to_array::<f32>(vec_total, dim2), false), dim1);
af::join(2, &ar1, &ar2)
}
fn generate_target(&self, input: &Array, batch_size: u64, bptt_unroll: u64) -> Array {
let first = af::slices(&input, 0, bptt_unroll/2-1);
let second = af::slices(&input, bptt_unroll/2, bptt_unroll-1);
let ar = af::mul(&first, &second, false);
let zeros = af::constant(0f32, Dim4::new(&[batch_size, 1, bptt_unroll, 1]));
af::add(&af::sum(&ar, 2), &zeros, true)
}
}
impl DataSource for AddingProblemSource {
fn get_train_iter(&self, num_batch: u64) -> Data {
let inp = self.generate_input(num_batch
, self.params.input_dims[2]);
let tar = self.generate_target(&inp
, num_batch
, self.params.input_dims[2]);
let batch = Data {
input: RefCell::new(Box::new(inp.clone())),
target: RefCell::new(Box::new(tar.clone())),
};
let current_iter = self.params.current_epoch.get();
if self.iter.get() == self.params.num_samples as u64/ num_batch as u64 {
self.params.current_epoch.set(current_iter + 1);
self.iter.set(0);
}
self.iter.set(self.iter.get() + 1);
batch
}
fn info(&self) -> DataParams {
self.params.clone()
}
fn get_test_iter(&self, num_batch: u64) -> Data {
self.get_train_iter(num_batch)
}
fn get_validation_iter(&self, num_batch: u64) -> Option<Data> {
Some( self.get_train_iter(num_batch))
}
}
|
{
assert!(bptt_unroll % 4 == 0, "The number of time steps has to be divisible by 4 for the adding problem");
let input_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let target_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let train_samples = 0.7 * max_samples as f32;
let test_samples = 0.2 * max_samples as f32;
let validation_samples = 0.1 * max_samples as f32;
AddingProblemSource {
params : DataParams {
input_dims: input_dims,
target_dims: target_dims,
dtype: dtype,
normalize: false,
shuffle: false,
current_epoch: Cell::new(0),
num_samples: max_samples,
num_train: train_samples as u64,
num_test: test_samples as u64,
num_validation: Some(validation_samples as u64),
},
|
identifier_body
|
lib.rs
|
#![recursion_limit = "256"]
//! This module provides the render environment.
//!
//! OrbTk has choosen the [tinyskia] crate to handle all 2D rendering
//! tasks. Implemented as wrapper functions, it consumes the native
//! rendering functions provided from tinyskia.
//!
//! [tinyskia]: https://docs.rs/tiny-skia
use std::{any::Any, fmt};
/// Pre-selects commonly used OrbTk crates and put them into scope.
pub mod prelude;
/// Handles helper utilities and global methods.
pub use orbtk_utils::prelude as utils;
mod common;
pub use tinyskia::*;
pub mod tinyskia;
pub use self::render_target::*;
mod render_target;
/// Defines the current configuration of the render ctx.
#[derive(Debug, Clone)]
pub struct RenderConfig {
pub fill_style: utils::Brush,
pub stroke_style: utils::Brush,
pub line_width: f64,
pub font_config: FontConfig,
pub alpha: f32,
}
impl Default for RenderConfig {
fn default() -> Self {
RenderConfig {
fill_style: utils::Brush::default(),
stroke_style: utils::Brush::default(),
line_width: 1.,
font_config: FontConfig::default(),
alpha: 1.,
}
}
}
/// The TextMetrics struct represents the dimension of a text.
#[derive(Clone, Copy, Default, Debug)]
pub struct TextMetrics {
pub width: f64,
pub height: f64,
}
/// Internal font helper.
#[derive(Default, Clone, PartialEq, Debug)]
pub struct FontConfig {
pub family: String,
pub font_size: f64,
}
impl ToString for FontConfig {
fn to_string(&self) -> String {
format!("{}px {}", self.font_size, self.family)
}
}
// Handle render pipeline tasks.
pub trait RenderPipeline {
/// Draws the ctx of the pipeline.
fn draw(&self, image: &mut RenderTarget);
}
/// Used to implement a custom render pipeline.
pub trait PipelineTrait: RenderPipeline + Any + Send {
/// Equality for two Pipeline objects.
fn box_eq(&self, other: &dyn Any) -> bool;
/// Converts self to an any reference.
fn as_any(&self) -> &dyn Any;
|
/// Draws the ctx of the pipeline.
fn draw_pipeline(&self, image: &mut RenderTarget) {
self.draw(image);
}
}
impl PartialEq for Box<dyn PipelineTrait> {
fn eq(&self, other: &Box<dyn PipelineTrait>) -> bool {
self.box_eq(other.as_any())
}
}
impl Clone for Box<dyn PipelineTrait> {
fn clone(&self) -> Self {
self.clone_box()
}
}
impl fmt::Debug for Box<dyn PipelineTrait> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Box<dyn PipelineTrait>")
}
}
|
/// Clones self as box.
fn clone_box(&self) -> Box<dyn PipelineTrait>;
|
random_line_split
|
lib.rs
|
#![recursion_limit = "256"]
//! This module provides the render environment.
//!
//! OrbTk has choosen the [tinyskia] crate to handle all 2D rendering
//! tasks. Implemented as wrapper functions, it consumes the native
//! rendering functions provided from tinyskia.
//!
//! [tinyskia]: https://docs.rs/tiny-skia
use std::{any::Any, fmt};
/// Pre-selects commonly used OrbTk crates and put them into scope.
pub mod prelude;
/// Handles helper utilities and global methods.
pub use orbtk_utils::prelude as utils;
mod common;
pub use tinyskia::*;
pub mod tinyskia;
pub use self::render_target::*;
mod render_target;
/// Defines the current configuration of the render ctx.
#[derive(Debug, Clone)]
pub struct RenderConfig {
pub fill_style: utils::Brush,
pub stroke_style: utils::Brush,
pub line_width: f64,
pub font_config: FontConfig,
pub alpha: f32,
}
impl Default for RenderConfig {
fn default() -> Self {
RenderConfig {
fill_style: utils::Brush::default(),
stroke_style: utils::Brush::default(),
line_width: 1.,
font_config: FontConfig::default(),
alpha: 1.,
}
}
}
/// The TextMetrics struct represents the dimension of a text.
#[derive(Clone, Copy, Default, Debug)]
pub struct
|
{
pub width: f64,
pub height: f64,
}
/// Internal font helper.
#[derive(Default, Clone, PartialEq, Debug)]
pub struct FontConfig {
pub family: String,
pub font_size: f64,
}
impl ToString for FontConfig {
fn to_string(&self) -> String {
format!("{}px {}", self.font_size, self.family)
}
}
// Handle render pipeline tasks.
pub trait RenderPipeline {
/// Draws the ctx of the pipeline.
fn draw(&self, image: &mut RenderTarget);
}
/// Used to implement a custom render pipeline.
pub trait PipelineTrait: RenderPipeline + Any + Send {
/// Equality for two Pipeline objects.
fn box_eq(&self, other: &dyn Any) -> bool;
/// Converts self to an any reference.
fn as_any(&self) -> &dyn Any;
/// Clones self as box.
fn clone_box(&self) -> Box<dyn PipelineTrait>;
/// Draws the ctx of the pipeline.
fn draw_pipeline(&self, image: &mut RenderTarget) {
self.draw(image);
}
}
impl PartialEq for Box<dyn PipelineTrait> {
fn eq(&self, other: &Box<dyn PipelineTrait>) -> bool {
self.box_eq(other.as_any())
}
}
impl Clone for Box<dyn PipelineTrait> {
fn clone(&self) -> Self {
self.clone_box()
}
}
impl fmt::Debug for Box<dyn PipelineTrait> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Box<dyn PipelineTrait>")
}
}
|
TextMetrics
|
identifier_name
|
tlb.rs
|
use memory::VAddr;
use super::{Page, VirtualPage};
/// Invalidate the TLB completely by reloading the CR3 register.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
pub unsafe fn flush_all() {
use cpu::control_regs::cr3;
cr3::write(cr3::read());
}
/// Something which may be flushed from the TLB
pub trait Flush {
/// Invalidate this object in the TLB using the `invlpg` instruction.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
unsafe fn invlpg(self);
//
// /// Invalidate this object in the TLB instruction if we are in kernel mode.
// ///
// /// # Returns
// /// + True if the object was flushed
// /// + False if it was not flushed.
// #[inline]
// fn flush(&self) -> bool {
// use cpu::PrivilegeLevel;
//
// if PrivilegeLevel::current_iopl()!= PrivilegeLevel::KernelMode {
// false // can't flush, we are not in kernel mode
// } else {
// // this is safe since we know we are in kernel mode
// unsafe { self.invlpg() };
// true
// }
// }
}
impl Flush for VAddr {
#[inline]
unsafe fn invlpg(self) {
asm!( "invlpg [$0]"
:
: "r" (*self)
: "memory"
: "intel", "volatile" );
}
}
impl Flush for VirtualPage {
#[inline]
unsafe fn
|
(self) {
self.base().invlpg()
}
}
|
invlpg
|
identifier_name
|
tlb.rs
|
use memory::VAddr;
use super::{Page, VirtualPage};
/// Invalidate the TLB completely by reloading the CR3 register.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
pub unsafe fn flush_all() {
use cpu::control_regs::cr3;
cr3::write(cr3::read());
}
/// Something which may be flushed from the TLB
pub trait Flush {
/// Invalidate this object in the TLB using the `invlpg` instruction.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
unsafe fn invlpg(self);
//
// /// Invalidate this object in the TLB instruction if we are in kernel mode.
// ///
// /// # Returns
// /// + True if the object was flushed
// /// + False if it was not flushed.
// #[inline]
// fn flush(&self) -> bool {
// use cpu::PrivilegeLevel;
//
// if PrivilegeLevel::current_iopl()!= PrivilegeLevel::KernelMode {
// false // can't flush, we are not in kernel mode
// } else {
// // this is safe since we know we are in kernel mode
// unsafe { self.invlpg() };
// true
// }
// }
|
}
impl Flush for VAddr {
#[inline]
unsafe fn invlpg(self) {
asm!( "invlpg [$0]"
:
: "r" (*self)
: "memory"
: "intel", "volatile" );
}
}
impl Flush for VirtualPage {
#[inline]
unsafe fn invlpg(self) {
self.base().invlpg()
}
}
|
random_line_split
|
|
tlb.rs
|
use memory::VAddr;
use super::{Page, VirtualPage};
/// Invalidate the TLB completely by reloading the CR3 register.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
pub unsafe fn flush_all() {
use cpu::control_regs::cr3;
cr3::write(cr3::read());
}
/// Something which may be flushed from the TLB
pub trait Flush {
/// Invalidate this object in the TLB using the `invlpg` instruction.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
unsafe fn invlpg(self);
//
// /// Invalidate this object in the TLB instruction if we are in kernel mode.
// ///
// /// # Returns
// /// + True if the object was flushed
// /// + False if it was not flushed.
// #[inline]
// fn flush(&self) -> bool {
// use cpu::PrivilegeLevel;
//
// if PrivilegeLevel::current_iopl()!= PrivilegeLevel::KernelMode {
// false // can't flush, we are not in kernel mode
// } else {
// // this is safe since we know we are in kernel mode
// unsafe { self.invlpg() };
// true
// }
// }
}
impl Flush for VAddr {
#[inline]
unsafe fn invlpg(self)
|
}
impl Flush for VirtualPage {
#[inline]
unsafe fn invlpg(self) {
self.base().invlpg()
}
}
|
{
asm!( "invlpg [$0]"
:
: "r" (*self)
: "memory"
: "intel", "volatile" );
}
|
identifier_body
|
outline.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="outline"
sub_properties="outline-width outline-style outline-color"
derive_serialize="True"
spec="https://drafts.csswg.org/css-ui/#propdef-outline">
use properties::longhands::{outline_color, outline_width, outline_style};
use values::specified;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let _unused = context;
let mut color = None;
let mut style = None;
let mut width = None;
let mut any = false;
loop {
if color.is_none() {
if let Ok(value) = input.try(|i| specified::Color::parse(context, i)) {
color = Some(value);
any = true;
continue
}
}
if style.is_none() {
if let Ok(value) = input.try(|input| outline_style::parse(context, input)) {
style = Some(value);
any = true;
continue
}
}
if width.is_none() {
if let Ok(value) = input.try(|input| outline_width::parse(context, input)) {
width = Some(value);
any = true;
continue
}
}
break
}
if any {
Ok(expanded! {
outline_color: unwrap_or_initial!(outline_color, color),
outline_style: unwrap_or_initial!(outline_style, style),
outline_width: unwrap_or_initial!(outline_width, width),
})
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
</%helpers:shorthand>
// The -moz-outline-radius shorthand is non-standard and not on a standards track.
<%helpers:shorthand name="-moz-outline-radius" sub_properties="${' '.join(
'-moz-outline-radius-%s' % corner
for corner in ['topleft', 'topright', 'bottomright', 'bottomleft']
)}" products="gecko" spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-outline-radius)">
use values::generics::rect::Rect;
use values::specified::border::BorderRadius;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let radii = BorderRadius::parse(context, input)?;
Ok(expanded! {
_moz_outline_radius_topleft: radii.top_left,
_moz_outline_radius_topright: radii.top_right,
_moz_outline_radius_bottomright: radii.bottom_right,
_moz_outline_radius_bottomleft: radii.bottom_left,
})
}
impl<'a> ToCss for LonghandsToSerialize<'a> {
fn
|
<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
use values::generics::border::BorderCornerRadius;
let LonghandsToSerialize {
_moz_outline_radius_topleft: &BorderCornerRadius(ref tl),
_moz_outline_radius_topright: &BorderCornerRadius(ref tr),
_moz_outline_radius_bottomright: &BorderCornerRadius(ref br),
_moz_outline_radius_bottomleft: &BorderCornerRadius(ref bl),
} = *self;
let widths = Rect::new(tl.width(), tr.width(), br.width(), bl.width());
let heights = Rect::new(tl.height(), tr.height(), br.height(), bl.height());
BorderRadius::serialize_rects(widths, heights, dest)
}
}
</%helpers:shorthand>
|
to_css
|
identifier_name
|
outline.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="outline"
sub_properties="outline-width outline-style outline-color"
derive_serialize="True"
spec="https://drafts.csswg.org/css-ui/#propdef-outline">
use properties::longhands::{outline_color, outline_width, outline_style};
use values::specified;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let _unused = context;
let mut color = None;
let mut style = None;
let mut width = None;
let mut any = false;
loop {
if color.is_none() {
if let Ok(value) = input.try(|i| specified::Color::parse(context, i)) {
color = Some(value);
any = true;
continue
}
}
if style.is_none() {
if let Ok(value) = input.try(|input| outline_style::parse(context, input)) {
style = Some(value);
any = true;
continue
}
}
if width.is_none() {
if let Ok(value) = input.try(|input| outline_width::parse(context, input)) {
width = Some(value);
any = true;
continue
}
}
break
}
if any {
Ok(expanded! {
outline_color: unwrap_or_initial!(outline_color, color),
outline_style: unwrap_or_initial!(outline_style, style),
outline_width: unwrap_or_initial!(outline_width, width),
})
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
</%helpers:shorthand>
// The -moz-outline-radius shorthand is non-standard and not on a standards track.
<%helpers:shorthand name="-moz-outline-radius" sub_properties="${' '.join(
'-moz-outline-radius-%s' % corner
for corner in ['topleft', 'topright', 'bottomright', 'bottomleft']
)}" products="gecko" spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-outline-radius)">
use values::generics::rect::Rect;
use values::specified::border::BorderRadius;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let radii = BorderRadius::parse(context, input)?;
Ok(expanded! {
_moz_outline_radius_topleft: radii.top_left,
_moz_outline_radius_topright: radii.top_right,
_moz_outline_radius_bottomright: radii.bottom_right,
_moz_outline_radius_bottomleft: radii.bottom_left,
})
}
impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write
|
}
</%helpers:shorthand>
|
{
use values::generics::border::BorderCornerRadius;
let LonghandsToSerialize {
_moz_outline_radius_topleft: &BorderCornerRadius(ref tl),
_moz_outline_radius_topright: &BorderCornerRadius(ref tr),
_moz_outline_radius_bottomright: &BorderCornerRadius(ref br),
_moz_outline_radius_bottomleft: &BorderCornerRadius(ref bl),
} = *self;
let widths = Rect::new(tl.width(), tr.width(), br.width(), bl.width());
let heights = Rect::new(tl.height(), tr.height(), br.height(), bl.height());
BorderRadius::serialize_rects(widths, heights, dest)
}
|
identifier_body
|
outline.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="outline"
sub_properties="outline-width outline-style outline-color"
derive_serialize="True"
spec="https://drafts.csswg.org/css-ui/#propdef-outline">
use properties::longhands::{outline_color, outline_width, outline_style};
use values::specified;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let _unused = context;
let mut color = None;
let mut style = None;
let mut width = None;
let mut any = false;
loop {
if color.is_none() {
if let Ok(value) = input.try(|i| specified::Color::parse(context, i)) {
color = Some(value);
any = true;
continue
}
}
if style.is_none()
|
if width.is_none() {
if let Ok(value) = input.try(|input| outline_width::parse(context, input)) {
width = Some(value);
any = true;
continue
}
}
break
}
if any {
Ok(expanded! {
outline_color: unwrap_or_initial!(outline_color, color),
outline_style: unwrap_or_initial!(outline_style, style),
outline_width: unwrap_or_initial!(outline_width, width),
})
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
</%helpers:shorthand>
// The -moz-outline-radius shorthand is non-standard and not on a standards track.
<%helpers:shorthand name="-moz-outline-radius" sub_properties="${' '.join(
'-moz-outline-radius-%s' % corner
for corner in ['topleft', 'topright', 'bottomright', 'bottomleft']
)}" products="gecko" spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-outline-radius)">
use values::generics::rect::Rect;
use values::specified::border::BorderRadius;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let radii = BorderRadius::parse(context, input)?;
Ok(expanded! {
_moz_outline_radius_topleft: radii.top_left,
_moz_outline_radius_topright: radii.top_right,
_moz_outline_radius_bottomright: radii.bottom_right,
_moz_outline_radius_bottomleft: radii.bottom_left,
})
}
impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
use values::generics::border::BorderCornerRadius;
let LonghandsToSerialize {
_moz_outline_radius_topleft: &BorderCornerRadius(ref tl),
_moz_outline_radius_topright: &BorderCornerRadius(ref tr),
_moz_outline_radius_bottomright: &BorderCornerRadius(ref br),
_moz_outline_radius_bottomleft: &BorderCornerRadius(ref bl),
} = *self;
let widths = Rect::new(tl.width(), tr.width(), br.width(), bl.width());
let heights = Rect::new(tl.height(), tr.height(), br.height(), bl.height());
BorderRadius::serialize_rects(widths, heights, dest)
}
}
</%helpers:shorthand>
|
{
if let Ok(value) = input.try(|input| outline_style::parse(context, input)) {
style = Some(value);
any = true;
continue
}
}
|
conditional_block
|
outline.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="outline"
sub_properties="outline-width outline-style outline-color"
derive_serialize="True"
spec="https://drafts.csswg.org/css-ui/#propdef-outline">
use properties::longhands::{outline_color, outline_width, outline_style};
use values::specified;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let _unused = context;
let mut color = None;
let mut style = None;
let mut width = None;
let mut any = false;
loop {
if color.is_none() {
if let Ok(value) = input.try(|i| specified::Color::parse(context, i)) {
color = Some(value);
any = true;
continue
}
}
if style.is_none() {
if let Ok(value) = input.try(|input| outline_style::parse(context, input)) {
style = Some(value);
any = true;
continue
}
}
if width.is_none() {
if let Ok(value) = input.try(|input| outline_width::parse(context, input)) {
width = Some(value);
any = true;
continue
}
}
break
}
if any {
Ok(expanded! {
outline_color: unwrap_or_initial!(outline_color, color),
outline_style: unwrap_or_initial!(outline_style, style),
outline_width: unwrap_or_initial!(outline_width, width),
})
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
</%helpers:shorthand>
// The -moz-outline-radius shorthand is non-standard and not on a standards track.
<%helpers:shorthand name="-moz-outline-radius" sub_properties="${' '.join(
'-moz-outline-radius-%s' % corner
for corner in ['topleft', 'topright', 'bottomright', 'bottomleft']
)}" products="gecko" spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-outline-radius)">
use values::generics::rect::Rect;
use values::specified::border::BorderRadius;
use parser::Parse;
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> {
let radii = BorderRadius::parse(context, input)?;
Ok(expanded! {
_moz_outline_radius_topleft: radii.top_left,
_moz_outline_radius_topright: radii.top_right,
_moz_outline_radius_bottomright: radii.bottom_right,
_moz_outline_radius_bottomleft: radii.bottom_left,
})
}
impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
use values::generics::border::BorderCornerRadius;
let LonghandsToSerialize {
_moz_outline_radius_topleft: &BorderCornerRadius(ref tl),
_moz_outline_radius_topright: &BorderCornerRadius(ref tr),
_moz_outline_radius_bottomright: &BorderCornerRadius(ref br),
_moz_outline_radius_bottomleft: &BorderCornerRadius(ref bl),
} = *self;
let widths = Rect::new(tl.width(), tr.width(), br.width(), bl.width());
let heights = Rect::new(tl.height(), tr.height(), br.height(), bl.height());
|
BorderRadius::serialize_rects(widths, heights, dest)
}
}
</%helpers:shorthand>
|
random_line_split
|
|
context.rs
|
use std::io;
use std::error;
use std::fmt;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use ::get_error;
use ::rwops::RWops;
use ::version::Version;
use sys::ttf;
use super::font::{
internal_load_font,
internal_load_font_at_index,
internal_load_font_from_ll,
Font,
};
/// A context manager for `SDL2_TTF` to manage C code initialization and clean-up.
#[must_use]
pub struct Sdl2TtfContext;
// Clean up the context once it goes out of scope
impl Drop for Sdl2TtfContext {
fn drop(&mut self) {
unsafe { ttf::TTF_Quit(); }
}
}
impl Sdl2TtfContext {
/// Loads a font from the given file with the given size in points.
pub fn load_font<'ttf, P: AsRef<Path>>(&'ttf self, path: P, point_size: u16) -> Result<Font<'ttf,'static>, String> {
internal_load_font(path, point_size)
}
/// Loads the font at the given index of the file, with the given
/// size in points.
pub fn load_font_at_index<'ttf, P: AsRef<Path>>(&'ttf self, path: P, index: u32, point_size: u16)
-> Result<Font<'ttf,'static>, String> {
internal_load_font_at_index(path, index, point_size)
}
/// Loads a font from the given SDL2 rwops object with the given size in
/// points.
pub fn load_font_from_rwops<'ttf,'r>(&'ttf self, rwops: RWops<'r>, point_size: u16)
-> Result<Font<'ttf,'r>, String> {
let raw = unsafe {
ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int)
};
if (raw as *mut ()).is_null() {
Err(get_error())
} else {
Ok(internal_load_font_from_ll(raw, Some(rwops)))
}
}
/// Loads the font at the given index of the SDL2 rwops object with
/// the given size in points.
pub fn load_font_at_index_from_rwops<'ttf,'r>(&'ttf self, rwops: RWops<'r>, index: u32,
point_size: u16) -> Result<Font<'ttf,'r>, String> {
let raw = unsafe {
ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int,
index as c_long)
};
if (raw as *mut ()).is_null() {
Err(get_error())
} else {
Ok(internal_load_font_from_ll(raw, Some(rwops)))
}
}
}
/// Returns the version of the dynamically linked `SDL_TTF` library
pub fn get_linked_version() -> Version {
unsafe {
Version::from_ll(*ttf::TTF_Linked_Version())
}
}
/// An error for when `sdl2_ttf` is attempted initialized twice
/// Necessary for context management, unless we find a way to have a singleton
#[derive(Debug)]
pub enum InitError {
InitializationError(io::Error),
AlreadyInitializedError,
}
impl error::Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::AlreadyInitializedError => {
"SDL2_TTF has already been initialized"
},
InitError::InitializationError(ref error) => {
error.description()
},
}
}
fn cause(&self) -> Option<&dyn error::Error> {
match *self {
InitError::AlreadyInitializedError => {
None
},
InitError::InitializationError(ref error) => {
Some(error)
},
}
}
}
impl fmt::Display for InitError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.write_str("SDL2_TTF has already been initialized")
}
}
/// Initializes the truetype font API and returns a context manager which will
/// clean up the library once it goes out of scope.
pub fn init() -> Result<Sdl2TtfContext, InitError>
|
/// Returns whether library has been initialized already.
pub fn has_been_initialized() -> bool {
unsafe {
ttf::TTF_WasInit() == 1
}
}
|
{
unsafe {
if ttf::TTF_WasInit() == 1 {
Err(InitError::AlreadyInitializedError)
} else if ttf::TTF_Init() == 0 {
Ok(Sdl2TtfContext)
} else {
Err(InitError::InitializationError(
io::Error::last_os_error()
))
}
}
}
|
identifier_body
|
context.rs
|
use std::io;
use std::error;
use std::fmt;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use ::get_error;
use ::rwops::RWops;
use ::version::Version;
use sys::ttf;
use super::font::{
internal_load_font,
internal_load_font_at_index,
internal_load_font_from_ll,
Font,
};
/// A context manager for `SDL2_TTF` to manage C code initialization and clean-up.
#[must_use]
pub struct Sdl2TtfContext;
// Clean up the context once it goes out of scope
impl Drop for Sdl2TtfContext {
fn drop(&mut self) {
unsafe { ttf::TTF_Quit(); }
}
}
impl Sdl2TtfContext {
/// Loads a font from the given file with the given size in points.
pub fn load_font<'ttf, P: AsRef<Path>>(&'ttf self, path: P, point_size: u16) -> Result<Font<'ttf,'static>, String> {
internal_load_font(path, point_size)
}
/// Loads the font at the given index of the file, with the given
/// size in points.
pub fn load_font_at_index<'ttf, P: AsRef<Path>>(&'ttf self, path: P, index: u32, point_size: u16)
-> Result<Font<'ttf,'static>, String> {
internal_load_font_at_index(path, index, point_size)
}
/// Loads a font from the given SDL2 rwops object with the given size in
/// points.
pub fn load_font_from_rwops<'ttf,'r>(&'ttf self, rwops: RWops<'r>, point_size: u16)
-> Result<Font<'ttf,'r>, String> {
let raw = unsafe {
ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int)
};
if (raw as *mut ()).is_null() {
Err(get_error())
} else {
Ok(internal_load_font_from_ll(raw, Some(rwops)))
}
}
/// Loads the font at the given index of the SDL2 rwops object with
/// the given size in points.
pub fn
|
<'ttf,'r>(&'ttf self, rwops: RWops<'r>, index: u32,
point_size: u16) -> Result<Font<'ttf,'r>, String> {
let raw = unsafe {
ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int,
index as c_long)
};
if (raw as *mut ()).is_null() {
Err(get_error())
} else {
Ok(internal_load_font_from_ll(raw, Some(rwops)))
}
}
}
/// Returns the version of the dynamically linked `SDL_TTF` library
pub fn get_linked_version() -> Version {
unsafe {
Version::from_ll(*ttf::TTF_Linked_Version())
}
}
/// An error for when `sdl2_ttf` is attempted initialized twice
/// Necessary for context management, unless we find a way to have a singleton
#[derive(Debug)]
pub enum InitError {
InitializationError(io::Error),
AlreadyInitializedError,
}
impl error::Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::AlreadyInitializedError => {
"SDL2_TTF has already been initialized"
},
InitError::InitializationError(ref error) => {
error.description()
},
}
}
fn cause(&self) -> Option<&dyn error::Error> {
match *self {
InitError::AlreadyInitializedError => {
None
},
InitError::InitializationError(ref error) => {
Some(error)
},
}
}
}
impl fmt::Display for InitError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.write_str("SDL2_TTF has already been initialized")
}
}
/// Initializes the truetype font API and returns a context manager which will
/// clean up the library once it goes out of scope.
pub fn init() -> Result<Sdl2TtfContext, InitError> {
unsafe {
if ttf::TTF_WasInit() == 1 {
Err(InitError::AlreadyInitializedError)
} else if ttf::TTF_Init() == 0 {
Ok(Sdl2TtfContext)
} else {
Err(InitError::InitializationError(
io::Error::last_os_error()
))
}
}
}
/// Returns whether library has been initialized already.
pub fn has_been_initialized() -> bool {
unsafe {
ttf::TTF_WasInit() == 1
}
}
|
load_font_at_index_from_rwops
|
identifier_name
|
context.rs
|
use std::io;
use std::error;
use std::fmt;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use ::get_error;
use ::rwops::RWops;
use ::version::Version;
use sys::ttf;
use super::font::{
internal_load_font,
internal_load_font_at_index,
internal_load_font_from_ll,
Font,
};
/// A context manager for `SDL2_TTF` to manage C code initialization and clean-up.
#[must_use]
pub struct Sdl2TtfContext;
// Clean up the context once it goes out of scope
impl Drop for Sdl2TtfContext {
fn drop(&mut self) {
unsafe { ttf::TTF_Quit(); }
}
}
impl Sdl2TtfContext {
/// Loads a font from the given file with the given size in points.
pub fn load_font<'ttf, P: AsRef<Path>>(&'ttf self, path: P, point_size: u16) -> Result<Font<'ttf,'static>, String> {
internal_load_font(path, point_size)
}
/// Loads the font at the given index of the file, with the given
/// size in points.
pub fn load_font_at_index<'ttf, P: AsRef<Path>>(&'ttf self, path: P, index: u32, point_size: u16)
-> Result<Font<'ttf,'static>, String> {
internal_load_font_at_index(path, index, point_size)
}
/// Loads a font from the given SDL2 rwops object with the given size in
/// points.
pub fn load_font_from_rwops<'ttf,'r>(&'ttf self, rwops: RWops<'r>, point_size: u16)
-> Result<Font<'ttf,'r>, String> {
let raw = unsafe {
ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int)
};
if (raw as *mut ()).is_null() {
Err(get_error())
} else {
Ok(internal_load_font_from_ll(raw, Some(rwops)))
}
}
/// Loads the font at the given index of the SDL2 rwops object with
/// the given size in points.
pub fn load_font_at_index_from_rwops<'ttf,'r>(&'ttf self, rwops: RWops<'r>, index: u32,
point_size: u16) -> Result<Font<'ttf,'r>, String> {
let raw = unsafe {
ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int,
index as c_long)
};
if (raw as *mut ()).is_null() {
Err(get_error())
} else {
Ok(internal_load_font_from_ll(raw, Some(rwops)))
}
}
}
/// Returns the version of the dynamically linked `SDL_TTF` library
pub fn get_linked_version() -> Version {
unsafe {
Version::from_ll(*ttf::TTF_Linked_Version())
}
}
/// An error for when `sdl2_ttf` is attempted initialized twice
/// Necessary for context management, unless we find a way to have a singleton
#[derive(Debug)]
pub enum InitError {
InitializationError(io::Error),
AlreadyInitializedError,
}
impl error::Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::AlreadyInitializedError => {
"SDL2_TTF has already been initialized"
},
InitError::InitializationError(ref error) => {
error.description()
},
}
}
fn cause(&self) -> Option<&dyn error::Error> {
match *self {
InitError::AlreadyInitializedError => {
None
},
InitError::InitializationError(ref error) => {
Some(error)
},
}
}
}
impl fmt::Display for InitError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.write_str("SDL2_TTF has already been initialized")
}
}
|
if ttf::TTF_WasInit() == 1 {
Err(InitError::AlreadyInitializedError)
} else if ttf::TTF_Init() == 0 {
Ok(Sdl2TtfContext)
} else {
Err(InitError::InitializationError(
io::Error::last_os_error()
))
}
}
}
/// Returns whether library has been initialized already.
pub fn has_been_initialized() -> bool {
unsafe {
ttf::TTF_WasInit() == 1
}
}
|
/// Initializes the truetype font API and returns a context manager which will
/// clean up the library once it goes out of scope.
pub fn init() -> Result<Sdl2TtfContext, InitError> {
unsafe {
|
random_line_split
|
term-gradient.rs
|
use calx::{term_color, PseudoTermColor};
fn print(t: &mut Box<term::StdoutTerminal>, c: PseudoTermColor) {
t.reset().unwrap();
let fg;
match c {
PseudoTermColor::Mixed { fore, back, mix: _ } => {
fg = u32::from(fore);
t.bg(u32::from(back)).unwrap();
}
PseudoTermColor::Solid(fore) => {
fg = u32::from(fore);
}
}
t.fg(fg).unwrap();
if fg > 8 {
t.attr(term::Attr::Bold).unwrap();
}
print!("{}", c.ch());
}
fn
|
() {
let mut t = term::stdout().unwrap();
for x in 0..80 {
let a = (x as f32) / 80.0;
let c = calx::lerp(term_color::MAROON, term_color::YELLOW, a);
print(&mut t, c);
}
let _ = t.reset();
println!();
let mut path = calx::LerpPath::new((0.0f32, term_color::BLACK), (1.0f32, term_color::YELLOW));
path.add((0.20, term_color::NAVY));
path.add((0.40, term_color::BLUE));
path.add((0.60, term_color::TEAL));
path.add((0.80, term_color::AQUA));
path.add((0.90, term_color::WHITE));
for x in 0..80 {
let a = (x as f32) / 80.0;
print(&mut t, path.sample(a));
}
let _ = t.reset();
println!();
}
|
main
|
identifier_name
|
term-gradient.rs
|
use calx::{term_color, PseudoTermColor};
fn print(t: &mut Box<term::StdoutTerminal>, c: PseudoTermColor) {
t.reset().unwrap();
let fg;
match c {
PseudoTermColor::Mixed { fore, back, mix: _ } => {
fg = u32::from(fore);
t.bg(u32::from(back)).unwrap();
}
PseudoTermColor::Solid(fore) => {
fg = u32::from(fore);
}
}
t.fg(fg).unwrap();
if fg > 8 {
t.attr(term::Attr::Bold).unwrap();
}
print!("{}", c.ch());
}
fn main()
|
}
let _ = t.reset();
println!();
}
|
{
let mut t = term::stdout().unwrap();
for x in 0..80 {
let a = (x as f32) / 80.0;
let c = calx::lerp(term_color::MAROON, term_color::YELLOW, a);
print(&mut t, c);
}
let _ = t.reset();
println!();
let mut path = calx::LerpPath::new((0.0f32, term_color::BLACK), (1.0f32, term_color::YELLOW));
path.add((0.20, term_color::NAVY));
path.add((0.40, term_color::BLUE));
path.add((0.60, term_color::TEAL));
path.add((0.80, term_color::AQUA));
path.add((0.90, term_color::WHITE));
for x in 0..80 {
let a = (x as f32) / 80.0;
print(&mut t, path.sample(a));
|
identifier_body
|
term-gradient.rs
|
use calx::{term_color, PseudoTermColor};
fn print(t: &mut Box<term::StdoutTerminal>, c: PseudoTermColor) {
t.reset().unwrap();
let fg;
match c {
PseudoTermColor::Mixed { fore, back, mix: _ } => {
fg = u32::from(fore);
t.bg(u32::from(back)).unwrap();
}
PseudoTermColor::Solid(fore) => {
fg = u32::from(fore);
}
}
t.fg(fg).unwrap();
if fg > 8 {
t.attr(term::Attr::Bold).unwrap();
}
print!("{}", c.ch());
}
fn main() {
let mut t = term::stdout().unwrap();
for x in 0..80 {
let a = (x as f32) / 80.0;
let c = calx::lerp(term_color::MAROON, term_color::YELLOW, a);
print(&mut t, c);
}
let _ = t.reset();
println!();
|
path.add((0.20, term_color::NAVY));
path.add((0.40, term_color::BLUE));
path.add((0.60, term_color::TEAL));
path.add((0.80, term_color::AQUA));
path.add((0.90, term_color::WHITE));
for x in 0..80 {
let a = (x as f32) / 80.0;
print(&mut t, path.sample(a));
}
let _ = t.reset();
println!();
}
|
let mut path = calx::LerpPath::new((0.0f32, term_color::BLACK), (1.0f32, term_color::YELLOW));
|
random_line_split
|
lib.rs
|
//! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, uint64_t};
use std::ffi::CStr;
use std::ptr;
// Re-export the FFI for the runtime.
pub use weld::runtime::ffi::*;
// These variants should never be constructed: they aren't 0-variant structs to enforce their
// pointer alignment.
#[repr(u64)]
pub enum WeldConf {
_A,
}
#[repr(u64)]
pub enum WeldContext {
_A,
}
#[repr(u64)]
pub enum WeldError {
_A,
}
#[repr(u64)]
pub enum WeldModule {
_A,
}
#[repr(u64)]
pub enum WeldValue {
_A,
}
/// An opaque handle to a Weld configuration.
#[allow(non_camel_case_types)]
pub type weld_conf_t = *mut WeldConf;
/// An opaque handle to a Weld context.
#[allow(non_camel_case_types)]
pub type weld_context_t = *mut WeldContext;
/// An opaque handle to a Weld error.
#[allow(non_camel_case_types)]
pub type weld_error_t = *mut WeldError;
/// An opaque handle to a Weld module.
#[allow(non_camel_case_types)]
pub type weld_module_t = *mut WeldModule;
/// An opaque handle to a Weld data value.
#[allow(non_camel_case_types)]
pub type weld_value_t = *mut WeldValue;
pub use weld::WeldLogLevel;
pub use weld::WeldRuntimeErrno;
#[allow(non_camel_case_types)]
pub type weld_log_level_t = WeldLogLevel;
#[allow(non_camel_case_types)]
pub type weld_errno_t = WeldRuntimeErrno;
trait ToRustStr {
fn to_str(&self) -> &str;
fn to_string(&self) -> String {
self.to_str().to_string()
}
}
impl ToRustStr for *const c_char {
fn to_str(&self) -> &str {
let c_str = unsafe { CStr::from_ptr(*self) };
c_str.to_str().unwrap()
}
}
#[no_mangle]
/// Creates a new context.
///
/// This function is a wrapper for `WeldContext::new`.
pub unsafe extern "C" fn weld_context_new(conf: weld_conf_t) -> weld_context_t {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
if let Ok(context) = weld::WeldContext::new(conf) {
Box::into_raw(Box::new(context)) as _
} else {
// XXX Should this take an error too?
ptr::null_mut()
}
}
#[no_mangle]
/// Gets the memory allocated by a Weld context.
///
/// This includes all live memory allocated in the given context.
pub unsafe extern "C" fn weld_context_memory_usage(context: weld_context_t) -> int64_t {
let context = context as *mut weld::WeldContext;
let context = &*context;
context.memory_usage() as int64_t
}
#[no_mangle]
/// Frees a context.
///
/// All contexts created by the FFI should be freed. This includes contexts obtained from
/// `weld_context_new` and `weld_value_context`.
pub unsafe extern "C" fn weld_context_free(context: weld_context_t) {
let context = context as *mut weld::WeldContext;
if!context.is_null() {
Box::from_raw(context);
}
}
#[no_mangle]
/// Creates a new configuration.
///
/// This function is a wrapper for `WeldConf::new`.
pub extern "C" fn weld_conf_new() -> weld_conf_t {
Box::into_raw(Box::new(weld::WeldConf::new())) as _
}
#[no_mangle]
/// Free a configuration.
///
/// The passsed configuration should have been allocated using `weld_conf_new`.
pub unsafe extern "C" fn weld_conf_free(conf: weld_conf_t) {
let conf = conf as *mut weld::WeldConf;
if!conf.is_null() {
Box::from_raw(conf);
}
}
#[no_mangle]
/// Get a value associated with a key for a configuration.
///
/// This function is a wrapper for `WeldConf::get`.
pub unsafe extern "C" fn weld_conf_get(conf: weld_conf_t, key: *const c_char) -> *const c_char {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
match conf.get(key.to_str()) {
Some(k) => k.as_ptr(),
None => ptr::null_mut(),
}
}
#[no_mangle]
/// Set the value of `key` to `value`.
///
/// This function is a wrapper for `WeldConf::set`.
pub unsafe extern "C" fn weld_conf_set(
conf: weld_conf_t,
key: *const c_char,
value: *const c_char,
) {
let conf = conf as *mut weld::WeldConf;
let conf = &mut *conf;
let key = key.to_string();
let val = CStr::from_ptr(value).to_owned();
conf.set(key, val);
}
#[no_mangle]
/// Returns a new Weld value.
///
/// The value returned by this method is *not* owned by the runtime, so any data this value refers
/// to must be managed by the caller. The created value will always have a NULL context.
///
/// This function is a wrapper for `WeldValue::new_from_data`.
pub extern "C" fn weld_value_new(data: *const c_void) -> weld_value_t {
Box::into_raw(Box::new(weld::WeldValue::new_from_data(data))) as _
}
#[no_mangle]
/// Returns the Run ID of the value.
///
/// If this value was not returned by a Weld program, this function returns `-1`.
pub unsafe extern "C" fn weld_value_run(value: weld_value_t) -> int64_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.run_id().unwrap_or(-1) as int64_t
}
#[no_mangle]
/// Returns the context of a value.
///
/// Since contexts are internally reference-counted, this function increases the reference count of
/// the context. The context must be freed with `weld_context_free` to decrement the internal
/// reference count. Since Weld values owned by a context internally hold a reference to the
/// context, the value is guaranteed to be live until `weld_value_free` is called.
pub unsafe extern "C" fn weld_value_context(value: weld_value_t) -> weld_context_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
if let Some(context) = value.context() {
Box::into_raw(Box::new(context)) as _
} else {
ptr::null_mut() as _
}
}
#[no_mangle]
/// Returns the data pointer for a Weld value.
///
/// This function is a wrapper for `WeldValue::data`. If this value is owned by the runtime, the
/// returned pointer should never be freed -- instead, use `weld_value_free` to free the data.
pub unsafe extern "C" fn weld_value_data(value: weld_value_t) -> *mut c_void {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.data() as _
}
#[no_mangle]
/// Frees a Weld value.
///
/// All Weld values must be freed using this call. Weld values which are owned by the runtime also
/// free the data they contain. Weld values which are not owned by the runtime only free the
/// structure used to wrap the data; the actual data itself is owned by the caller.
pub unsafe extern "C" fn weld_value_free(value: weld_value_t) {
let value = value as *mut weld::WeldValue;
if!value.is_null() {
Box::from_raw(value);
}
}
#[no_mangle]
/// Compiles a Weld program into a runnable module.
///
/// The compilation can be configured using the passed configuration pointer. This function stores
/// an error (which indicates a compilation error or success) in `err`.
///
/// This function is a wrapper for `WeldModule::compile`.
pub unsafe extern "C" fn
|
(
code: *const c_char,
conf: weld_conf_t,
err: weld_error_t,
) -> weld_module_t {
let code = code.to_str();
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match weld::WeldModule::compile(code, conf) {
Ok(module) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(module)) as _
}
Err(compile_err) => {
*err = compile_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Runs a compiled Weld module.
///
/// The module is run with a given configuration and argument list, and returns the result wrapped
/// as a `WeldValue`. If the run raised a runtime error, the method writes the erorr into `err`,
/// and a the method returns `null`. Otherwise, `err` indicates success.
///
/// This function is a wrapper for `WeldModule::run`.
pub unsafe extern "C" fn weld_module_run(
module: weld_module_t,
context: weld_context_t,
arg: weld_value_t,
err: weld_error_t,
) -> weld_value_t {
let module = module as *mut weld::WeldModule;
let module = &mut *module;
let context = context as *mut weld::WeldContext;
let context = &mut *context;
let arg = arg as *mut weld::WeldValue;
let arg = &*arg;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match module.run(context, arg) {
Ok(result) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(result)) as _
}
Err(runtime_err) => {
eprintln!("{:?}", runtime_err);
*err = runtime_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Frees a module.
///
/// Freeing a module does not free the memory it may have allocated. Values returned by the module
/// must be freed explicitly using `weld_value_free`.
pub unsafe extern "C" fn weld_module_free(module: weld_module_t) {
let module = module as *mut weld::WeldModule;
if!module.is_null() {
Box::from_raw(module);
}
}
#[no_mangle]
/// Creates a new Weld error object.
pub extern "C" fn weld_error_new() -> weld_error_t {
Box::into_raw(Box::new(weld::WeldError::default())) as _
}
#[no_mangle]
/// Returns the error code for a Weld error.
///
/// This function is a wrapper for `WeldError::code`.
pub unsafe extern "C" fn weld_error_code(err: weld_error_t) -> uint64_t {
let err = err as *mut weld::WeldError;
let err = &*err;
err.code() as _
}
#[no_mangle]
/// Returns a Weld error message.
///
/// This function is a wrapper for `WeldError::message`.
pub unsafe extern "C" fn weld_error_message(err: weld_error_t) -> *const c_char {
let err = err as *mut weld::WeldError;
let err = &*err;
err.message().as_ptr()
}
#[no_mangle]
/// Frees a Weld error object.
pub unsafe extern "C" fn weld_error_free(err: weld_error_t) {
let err = err as *mut weld::WeldError;
if!err.is_null() {
Box::from_raw(err);
}
}
#[no_mangle]
/// Load a dynamic library that a Weld program can access.
///
/// The dynamic library is a C dynamic library identified by its filename.
/// This function is a wrapper for `load_linked_library`.
pub unsafe extern "C" fn weld_load_library(filename: *const c_char, err: weld_error_t) {
let err = err as *mut weld::WeldError;
let err = &mut *err;
let filename = filename.to_str();
if let Err(e) = weld::load_linked_library(filename) {
*err = e;
} else {
*err = weld::WeldError::new_success();
}
}
#[no_mangle]
/// Enables logging to stderr in Weld with the given log level.
///
/// This function is ignored if it has already been called once, or if some other code in the
/// process has initialized logging using Rust's `log` crate.
pub extern "C" fn weld_set_log_level(level: uint64_t) {
weld::set_log_level(level.into())
}
|
weld_module_compile
|
identifier_name
|
lib.rs
|
//! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, uint64_t};
use std::ffi::CStr;
use std::ptr;
// Re-export the FFI for the runtime.
pub use weld::runtime::ffi::*;
// These variants should never be constructed: they aren't 0-variant structs to enforce their
// pointer alignment.
#[repr(u64)]
pub enum WeldConf {
_A,
}
#[repr(u64)]
pub enum WeldContext {
_A,
}
#[repr(u64)]
pub enum WeldError {
_A,
}
#[repr(u64)]
pub enum WeldModule {
_A,
}
#[repr(u64)]
pub enum WeldValue {
_A,
}
/// An opaque handle to a Weld configuration.
#[allow(non_camel_case_types)]
pub type weld_conf_t = *mut WeldConf;
/// An opaque handle to a Weld context.
#[allow(non_camel_case_types)]
pub type weld_context_t = *mut WeldContext;
/// An opaque handle to a Weld error.
#[allow(non_camel_case_types)]
pub type weld_error_t = *mut WeldError;
/// An opaque handle to a Weld module.
#[allow(non_camel_case_types)]
pub type weld_module_t = *mut WeldModule;
/// An opaque handle to a Weld data value.
#[allow(non_camel_case_types)]
pub type weld_value_t = *mut WeldValue;
pub use weld::WeldLogLevel;
pub use weld::WeldRuntimeErrno;
#[allow(non_camel_case_types)]
pub type weld_log_level_t = WeldLogLevel;
#[allow(non_camel_case_types)]
pub type weld_errno_t = WeldRuntimeErrno;
trait ToRustStr {
fn to_str(&self) -> &str;
fn to_string(&self) -> String {
self.to_str().to_string()
}
}
impl ToRustStr for *const c_char {
fn to_str(&self) -> &str {
let c_str = unsafe { CStr::from_ptr(*self) };
c_str.to_str().unwrap()
}
}
#[no_mangle]
/// Creates a new context.
///
/// This function is a wrapper for `WeldContext::new`.
pub unsafe extern "C" fn weld_context_new(conf: weld_conf_t) -> weld_context_t {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
if let Ok(context) = weld::WeldContext::new(conf) {
Box::into_raw(Box::new(context)) as _
} else {
// XXX Should this take an error too?
ptr::null_mut()
}
}
#[no_mangle]
/// Gets the memory allocated by a Weld context.
///
/// This includes all live memory allocated in the given context.
pub unsafe extern "C" fn weld_context_memory_usage(context: weld_context_t) -> int64_t {
let context = context as *mut weld::WeldContext;
let context = &*context;
context.memory_usage() as int64_t
}
#[no_mangle]
/// Frees a context.
///
/// All contexts created by the FFI should be freed. This includes contexts obtained from
/// `weld_context_new` and `weld_value_context`.
pub unsafe extern "C" fn weld_context_free(context: weld_context_t) {
let context = context as *mut weld::WeldContext;
if!context.is_null()
|
}
#[no_mangle]
/// Creates a new configuration.
///
/// This function is a wrapper for `WeldConf::new`.
pub extern "C" fn weld_conf_new() -> weld_conf_t {
Box::into_raw(Box::new(weld::WeldConf::new())) as _
}
#[no_mangle]
/// Free a configuration.
///
/// The passsed configuration should have been allocated using `weld_conf_new`.
pub unsafe extern "C" fn weld_conf_free(conf: weld_conf_t) {
let conf = conf as *mut weld::WeldConf;
if!conf.is_null() {
Box::from_raw(conf);
}
}
#[no_mangle]
/// Get a value associated with a key for a configuration.
///
/// This function is a wrapper for `WeldConf::get`.
pub unsafe extern "C" fn weld_conf_get(conf: weld_conf_t, key: *const c_char) -> *const c_char {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
match conf.get(key.to_str()) {
Some(k) => k.as_ptr(),
None => ptr::null_mut(),
}
}
#[no_mangle]
/// Set the value of `key` to `value`.
///
/// This function is a wrapper for `WeldConf::set`.
pub unsafe extern "C" fn weld_conf_set(
conf: weld_conf_t,
key: *const c_char,
value: *const c_char,
) {
let conf = conf as *mut weld::WeldConf;
let conf = &mut *conf;
let key = key.to_string();
let val = CStr::from_ptr(value).to_owned();
conf.set(key, val);
}
#[no_mangle]
/// Returns a new Weld value.
///
/// The value returned by this method is *not* owned by the runtime, so any data this value refers
/// to must be managed by the caller. The created value will always have a NULL context.
///
/// This function is a wrapper for `WeldValue::new_from_data`.
pub extern "C" fn weld_value_new(data: *const c_void) -> weld_value_t {
Box::into_raw(Box::new(weld::WeldValue::new_from_data(data))) as _
}
#[no_mangle]
/// Returns the Run ID of the value.
///
/// If this value was not returned by a Weld program, this function returns `-1`.
pub unsafe extern "C" fn weld_value_run(value: weld_value_t) -> int64_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.run_id().unwrap_or(-1) as int64_t
}
#[no_mangle]
/// Returns the context of a value.
///
/// Since contexts are internally reference-counted, this function increases the reference count of
/// the context. The context must be freed with `weld_context_free` to decrement the internal
/// reference count. Since Weld values owned by a context internally hold a reference to the
/// context, the value is guaranteed to be live until `weld_value_free` is called.
pub unsafe extern "C" fn weld_value_context(value: weld_value_t) -> weld_context_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
if let Some(context) = value.context() {
Box::into_raw(Box::new(context)) as _
} else {
ptr::null_mut() as _
}
}
#[no_mangle]
/// Returns the data pointer for a Weld value.
///
/// This function is a wrapper for `WeldValue::data`. If this value is owned by the runtime, the
/// returned pointer should never be freed -- instead, use `weld_value_free` to free the data.
pub unsafe extern "C" fn weld_value_data(value: weld_value_t) -> *mut c_void {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.data() as _
}
#[no_mangle]
/// Frees a Weld value.
///
/// All Weld values must be freed using this call. Weld values which are owned by the runtime also
/// free the data they contain. Weld values which are not owned by the runtime only free the
/// structure used to wrap the data; the actual data itself is owned by the caller.
pub unsafe extern "C" fn weld_value_free(value: weld_value_t) {
let value = value as *mut weld::WeldValue;
if!value.is_null() {
Box::from_raw(value);
}
}
#[no_mangle]
/// Compiles a Weld program into a runnable module.
///
/// The compilation can be configured using the passed configuration pointer. This function stores
/// an error (which indicates a compilation error or success) in `err`.
///
/// This function is a wrapper for `WeldModule::compile`.
pub unsafe extern "C" fn weld_module_compile(
code: *const c_char,
conf: weld_conf_t,
err: weld_error_t,
) -> weld_module_t {
let code = code.to_str();
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match weld::WeldModule::compile(code, conf) {
Ok(module) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(module)) as _
}
Err(compile_err) => {
*err = compile_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Runs a compiled Weld module.
///
/// The module is run with a given configuration and argument list, and returns the result wrapped
/// as a `WeldValue`. If the run raised a runtime error, the method writes the erorr into `err`,
/// and a the method returns `null`. Otherwise, `err` indicates success.
///
/// This function is a wrapper for `WeldModule::run`.
pub unsafe extern "C" fn weld_module_run(
module: weld_module_t,
context: weld_context_t,
arg: weld_value_t,
err: weld_error_t,
) -> weld_value_t {
let module = module as *mut weld::WeldModule;
let module = &mut *module;
let context = context as *mut weld::WeldContext;
let context = &mut *context;
let arg = arg as *mut weld::WeldValue;
let arg = &*arg;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match module.run(context, arg) {
Ok(result) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(result)) as _
}
Err(runtime_err) => {
eprintln!("{:?}", runtime_err);
*err = runtime_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Frees a module.
///
/// Freeing a module does not free the memory it may have allocated. Values returned by the module
/// must be freed explicitly using `weld_value_free`.
pub unsafe extern "C" fn weld_module_free(module: weld_module_t) {
let module = module as *mut weld::WeldModule;
if!module.is_null() {
Box::from_raw(module);
}
}
#[no_mangle]
/// Creates a new Weld error object.
pub extern "C" fn weld_error_new() -> weld_error_t {
Box::into_raw(Box::new(weld::WeldError::default())) as _
}
#[no_mangle]
/// Returns the error code for a Weld error.
///
/// This function is a wrapper for `WeldError::code`.
pub unsafe extern "C" fn weld_error_code(err: weld_error_t) -> uint64_t {
let err = err as *mut weld::WeldError;
let err = &*err;
err.code() as _
}
#[no_mangle]
/// Returns a Weld error message.
///
/// This function is a wrapper for `WeldError::message`.
pub unsafe extern "C" fn weld_error_message(err: weld_error_t) -> *const c_char {
let err = err as *mut weld::WeldError;
let err = &*err;
err.message().as_ptr()
}
#[no_mangle]
/// Frees a Weld error object.
pub unsafe extern "C" fn weld_error_free(err: weld_error_t) {
let err = err as *mut weld::WeldError;
if!err.is_null() {
Box::from_raw(err);
}
}
#[no_mangle]
/// Load a dynamic library that a Weld program can access.
///
/// The dynamic library is a C dynamic library identified by its filename.
/// This function is a wrapper for `load_linked_library`.
pub unsafe extern "C" fn weld_load_library(filename: *const c_char, err: weld_error_t) {
let err = err as *mut weld::WeldError;
let err = &mut *err;
let filename = filename.to_str();
if let Err(e) = weld::load_linked_library(filename) {
*err = e;
} else {
*err = weld::WeldError::new_success();
}
}
#[no_mangle]
/// Enables logging to stderr in Weld with the given log level.
///
/// This function is ignored if it has already been called once, or if some other code in the
/// process has initialized logging using Rust's `log` crate.
pub extern "C" fn weld_set_log_level(level: uint64_t) {
weld::set_log_level(level.into())
}
|
{
Box::from_raw(context);
}
|
conditional_block
|
lib.rs
|
//! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, uint64_t};
use std::ffi::CStr;
use std::ptr;
// Re-export the FFI for the runtime.
pub use weld::runtime::ffi::*;
// These variants should never be constructed: they aren't 0-variant structs to enforce their
// pointer alignment.
#[repr(u64)]
pub enum WeldConf {
_A,
}
#[repr(u64)]
pub enum WeldContext {
_A,
}
#[repr(u64)]
pub enum WeldError {
_A,
}
#[repr(u64)]
pub enum WeldModule {
_A,
}
#[repr(u64)]
pub enum WeldValue {
_A,
}
/// An opaque handle to a Weld configuration.
#[allow(non_camel_case_types)]
pub type weld_conf_t = *mut WeldConf;
/// An opaque handle to a Weld context.
#[allow(non_camel_case_types)]
pub type weld_context_t = *mut WeldContext;
/// An opaque handle to a Weld error.
#[allow(non_camel_case_types)]
pub type weld_error_t = *mut WeldError;
/// An opaque handle to a Weld module.
#[allow(non_camel_case_types)]
pub type weld_module_t = *mut WeldModule;
/// An opaque handle to a Weld data value.
#[allow(non_camel_case_types)]
pub type weld_value_t = *mut WeldValue;
pub use weld::WeldLogLevel;
pub use weld::WeldRuntimeErrno;
#[allow(non_camel_case_types)]
pub type weld_log_level_t = WeldLogLevel;
#[allow(non_camel_case_types)]
pub type weld_errno_t = WeldRuntimeErrno;
trait ToRustStr {
fn to_str(&self) -> &str;
fn to_string(&self) -> String {
self.to_str().to_string()
}
}
impl ToRustStr for *const c_char {
fn to_str(&self) -> &str {
let c_str = unsafe { CStr::from_ptr(*self) };
c_str.to_str().unwrap()
}
}
#[no_mangle]
/// Creates a new context.
///
/// This function is a wrapper for `WeldContext::new`.
pub unsafe extern "C" fn weld_context_new(conf: weld_conf_t) -> weld_context_t {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
if let Ok(context) = weld::WeldContext::new(conf) {
Box::into_raw(Box::new(context)) as _
} else {
// XXX Should this take an error too?
ptr::null_mut()
}
}
#[no_mangle]
/// Gets the memory allocated by a Weld context.
///
/// This includes all live memory allocated in the given context.
pub unsafe extern "C" fn weld_context_memory_usage(context: weld_context_t) -> int64_t {
let context = context as *mut weld::WeldContext;
let context = &*context;
context.memory_usage() as int64_t
}
#[no_mangle]
/// Frees a context.
///
/// All contexts created by the FFI should be freed. This includes contexts obtained from
/// `weld_context_new` and `weld_value_context`.
pub unsafe extern "C" fn weld_context_free(context: weld_context_t) {
let context = context as *mut weld::WeldContext;
if!context.is_null() {
Box::from_raw(context);
}
}
#[no_mangle]
/// Creates a new configuration.
///
/// This function is a wrapper for `WeldConf::new`.
pub extern "C" fn weld_conf_new() -> weld_conf_t {
Box::into_raw(Box::new(weld::WeldConf::new())) as _
}
#[no_mangle]
/// Free a configuration.
///
/// The passsed configuration should have been allocated using `weld_conf_new`.
pub unsafe extern "C" fn weld_conf_free(conf: weld_conf_t) {
let conf = conf as *mut weld::WeldConf;
if!conf.is_null() {
Box::from_raw(conf);
}
}
#[no_mangle]
/// Get a value associated with a key for a configuration.
///
/// This function is a wrapper for `WeldConf::get`.
pub unsafe extern "C" fn weld_conf_get(conf: weld_conf_t, key: *const c_char) -> *const c_char {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
match conf.get(key.to_str()) {
Some(k) => k.as_ptr(),
None => ptr::null_mut(),
}
}
#[no_mangle]
/// Set the value of `key` to `value`.
///
/// This function is a wrapper for `WeldConf::set`.
pub unsafe extern "C" fn weld_conf_set(
conf: weld_conf_t,
key: *const c_char,
value: *const c_char,
) {
let conf = conf as *mut weld::WeldConf;
let conf = &mut *conf;
let key = key.to_string();
let val = CStr::from_ptr(value).to_owned();
conf.set(key, val);
}
#[no_mangle]
/// Returns a new Weld value.
///
/// The value returned by this method is *not* owned by the runtime, so any data this value refers
/// to must be managed by the caller. The created value will always have a NULL context.
///
/// This function is a wrapper for `WeldValue::new_from_data`.
pub extern "C" fn weld_value_new(data: *const c_void) -> weld_value_t {
Box::into_raw(Box::new(weld::WeldValue::new_from_data(data))) as _
}
#[no_mangle]
/// Returns the Run ID of the value.
///
/// If this value was not returned by a Weld program, this function returns `-1`.
pub unsafe extern "C" fn weld_value_run(value: weld_value_t) -> int64_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.run_id().unwrap_or(-1) as int64_t
}
#[no_mangle]
/// Returns the context of a value.
///
/// Since contexts are internally reference-counted, this function increases the reference count of
/// the context. The context must be freed with `weld_context_free` to decrement the internal
/// reference count. Since Weld values owned by a context internally hold a reference to the
/// context, the value is guaranteed to be live until `weld_value_free` is called.
pub unsafe extern "C" fn weld_value_context(value: weld_value_t) -> weld_context_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
if let Some(context) = value.context() {
Box::into_raw(Box::new(context)) as _
} else {
ptr::null_mut() as _
}
}
#[no_mangle]
/// Returns the data pointer for a Weld value.
///
/// This function is a wrapper for `WeldValue::data`. If this value is owned by the runtime, the
/// returned pointer should never be freed -- instead, use `weld_value_free` to free the data.
pub unsafe extern "C" fn weld_value_data(value: weld_value_t) -> *mut c_void {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.data() as _
}
#[no_mangle]
/// Frees a Weld value.
///
/// All Weld values must be freed using this call. Weld values which are owned by the runtime also
/// free the data they contain. Weld values which are not owned by the runtime only free the
/// structure used to wrap the data; the actual data itself is owned by the caller.
pub unsafe extern "C" fn weld_value_free(value: weld_value_t) {
let value = value as *mut weld::WeldValue;
if!value.is_null() {
Box::from_raw(value);
}
}
#[no_mangle]
/// Compiles a Weld program into a runnable module.
///
/// The compilation can be configured using the passed configuration pointer. This function stores
/// an error (which indicates a compilation error or success) in `err`.
///
/// This function is a wrapper for `WeldModule::compile`.
pub unsafe extern "C" fn weld_module_compile(
code: *const c_char,
conf: weld_conf_t,
err: weld_error_t,
) -> weld_module_t {
let code = code.to_str();
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match weld::WeldModule::compile(code, conf) {
Ok(module) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(module)) as _
}
Err(compile_err) => {
*err = compile_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Runs a compiled Weld module.
///
/// The module is run with a given configuration and argument list, and returns the result wrapped
/// as a `WeldValue`. If the run raised a runtime error, the method writes the erorr into `err`,
/// and a the method returns `null`. Otherwise, `err` indicates success.
///
/// This function is a wrapper for `WeldModule::run`.
pub unsafe extern "C" fn weld_module_run(
module: weld_module_t,
context: weld_context_t,
arg: weld_value_t,
err: weld_error_t,
) -> weld_value_t {
let module = module as *mut weld::WeldModule;
let module = &mut *module;
let context = context as *mut weld::WeldContext;
let context = &mut *context;
let arg = arg as *mut weld::WeldValue;
let arg = &*arg;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match module.run(context, arg) {
Ok(result) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(result)) as _
}
Err(runtime_err) => {
eprintln!("{:?}", runtime_err);
*err = runtime_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Frees a module.
///
/// Freeing a module does not free the memory it may have allocated. Values returned by the module
/// must be freed explicitly using `weld_value_free`.
pub unsafe extern "C" fn weld_module_free(module: weld_module_t) {
let module = module as *mut weld::WeldModule;
if!module.is_null() {
Box::from_raw(module);
}
}
#[no_mangle]
/// Creates a new Weld error object.
pub extern "C" fn weld_error_new() -> weld_error_t {
Box::into_raw(Box::new(weld::WeldError::default())) as _
}
#[no_mangle]
/// Returns the error code for a Weld error.
///
/// This function is a wrapper for `WeldError::code`.
pub unsafe extern "C" fn weld_error_code(err: weld_error_t) -> uint64_t
|
#[no_mangle]
/// Returns a Weld error message.
///
/// This function is a wrapper for `WeldError::message`.
pub unsafe extern "C" fn weld_error_message(err: weld_error_t) -> *const c_char {
let err = err as *mut weld::WeldError;
let err = &*err;
err.message().as_ptr()
}
#[no_mangle]
/// Frees a Weld error object.
pub unsafe extern "C" fn weld_error_free(err: weld_error_t) {
let err = err as *mut weld::WeldError;
if!err.is_null() {
Box::from_raw(err);
}
}
#[no_mangle]
/// Load a dynamic library that a Weld program can access.
///
/// The dynamic library is a C dynamic library identified by its filename.
/// This function is a wrapper for `load_linked_library`.
pub unsafe extern "C" fn weld_load_library(filename: *const c_char, err: weld_error_t) {
let err = err as *mut weld::WeldError;
let err = &mut *err;
let filename = filename.to_str();
if let Err(e) = weld::load_linked_library(filename) {
*err = e;
} else {
*err = weld::WeldError::new_success();
}
}
#[no_mangle]
/// Enables logging to stderr in Weld with the given log level.
///
/// This function is ignored if it has already been called once, or if some other code in the
/// process has initialized logging using Rust's `log` crate.
pub extern "C" fn weld_set_log_level(level: uint64_t) {
weld::set_log_level(level.into())
}
|
{
let err = err as *mut weld::WeldError;
let err = &*err;
err.code() as _
}
|
identifier_body
|
lib.rs
|
//! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, uint64_t};
use std::ffi::CStr;
use std::ptr;
// Re-export the FFI for the runtime.
pub use weld::runtime::ffi::*;
// These variants should never be constructed: they aren't 0-variant structs to enforce their
// pointer alignment.
#[repr(u64)]
pub enum WeldConf {
_A,
}
#[repr(u64)]
pub enum WeldContext {
_A,
}
#[repr(u64)]
pub enum WeldError {
_A,
}
#[repr(u64)]
pub enum WeldModule {
_A,
}
#[repr(u64)]
pub enum WeldValue {
_A,
}
/// An opaque handle to a Weld configuration.
#[allow(non_camel_case_types)]
pub type weld_conf_t = *mut WeldConf;
/// An opaque handle to a Weld context.
#[allow(non_camel_case_types)]
pub type weld_context_t = *mut WeldContext;
/// An opaque handle to a Weld error.
#[allow(non_camel_case_types)]
pub type weld_error_t = *mut WeldError;
/// An opaque handle to a Weld module.
#[allow(non_camel_case_types)]
pub type weld_module_t = *mut WeldModule;
/// An opaque handle to a Weld data value.
#[allow(non_camel_case_types)]
pub type weld_value_t = *mut WeldValue;
pub use weld::WeldLogLevel;
pub use weld::WeldRuntimeErrno;
#[allow(non_camel_case_types)]
pub type weld_log_level_t = WeldLogLevel;
#[allow(non_camel_case_types)]
pub type weld_errno_t = WeldRuntimeErrno;
trait ToRustStr {
fn to_str(&self) -> &str;
fn to_string(&self) -> String {
self.to_str().to_string()
}
}
impl ToRustStr for *const c_char {
fn to_str(&self) -> &str {
let c_str = unsafe { CStr::from_ptr(*self) };
c_str.to_str().unwrap()
}
}
#[no_mangle]
/// Creates a new context.
///
/// This function is a wrapper for `WeldContext::new`.
pub unsafe extern "C" fn weld_context_new(conf: weld_conf_t) -> weld_context_t {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
if let Ok(context) = weld::WeldContext::new(conf) {
Box::into_raw(Box::new(context)) as _
} else {
// XXX Should this take an error too?
ptr::null_mut()
}
}
#[no_mangle]
/// Gets the memory allocated by a Weld context.
///
/// This includes all live memory allocated in the given context.
pub unsafe extern "C" fn weld_context_memory_usage(context: weld_context_t) -> int64_t {
let context = context as *mut weld::WeldContext;
let context = &*context;
context.memory_usage() as int64_t
}
#[no_mangle]
/// Frees a context.
///
/// All contexts created by the FFI should be freed. This includes contexts obtained from
/// `weld_context_new` and `weld_value_context`.
pub unsafe extern "C" fn weld_context_free(context: weld_context_t) {
let context = context as *mut weld::WeldContext;
if!context.is_null() {
Box::from_raw(context);
}
}
#[no_mangle]
/// Creates a new configuration.
///
/// This function is a wrapper for `WeldConf::new`.
pub extern "C" fn weld_conf_new() -> weld_conf_t {
Box::into_raw(Box::new(weld::WeldConf::new())) as _
}
#[no_mangle]
/// Free a configuration.
///
/// The passsed configuration should have been allocated using `weld_conf_new`.
pub unsafe extern "C" fn weld_conf_free(conf: weld_conf_t) {
let conf = conf as *mut weld::WeldConf;
if!conf.is_null() {
Box::from_raw(conf);
}
}
#[no_mangle]
/// Get a value associated with a key for a configuration.
///
/// This function is a wrapper for `WeldConf::get`.
pub unsafe extern "C" fn weld_conf_get(conf: weld_conf_t, key: *const c_char) -> *const c_char {
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
match conf.get(key.to_str()) {
Some(k) => k.as_ptr(),
None => ptr::null_mut(),
}
}
#[no_mangle]
/// Set the value of `key` to `value`.
///
/// This function is a wrapper for `WeldConf::set`.
pub unsafe extern "C" fn weld_conf_set(
conf: weld_conf_t,
key: *const c_char,
value: *const c_char,
) {
let conf = conf as *mut weld::WeldConf;
let conf = &mut *conf;
let key = key.to_string();
let val = CStr::from_ptr(value).to_owned();
conf.set(key, val);
}
#[no_mangle]
/// Returns a new Weld value.
///
/// The value returned by this method is *not* owned by the runtime, so any data this value refers
/// to must be managed by the caller. The created value will always have a NULL context.
///
/// This function is a wrapper for `WeldValue::new_from_data`.
pub extern "C" fn weld_value_new(data: *const c_void) -> weld_value_t {
Box::into_raw(Box::new(weld::WeldValue::new_from_data(data))) as _
}
#[no_mangle]
/// Returns the Run ID of the value.
///
/// If this value was not returned by a Weld program, this function returns `-1`.
pub unsafe extern "C" fn weld_value_run(value: weld_value_t) -> int64_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.run_id().unwrap_or(-1) as int64_t
}
#[no_mangle]
/// Returns the context of a value.
///
/// Since contexts are internally reference-counted, this function increases the reference count of
/// the context. The context must be freed with `weld_context_free` to decrement the internal
/// reference count. Since Weld values owned by a context internally hold a reference to the
/// context, the value is guaranteed to be live until `weld_value_free` is called.
pub unsafe extern "C" fn weld_value_context(value: weld_value_t) -> weld_context_t {
let value = value as *mut weld::WeldValue;
let value = &*value;
if let Some(context) = value.context() {
Box::into_raw(Box::new(context)) as _
} else {
ptr::null_mut() as _
}
}
#[no_mangle]
/// Returns the data pointer for a Weld value.
///
/// This function is a wrapper for `WeldValue::data`. If this value is owned by the runtime, the
/// returned pointer should never be freed -- instead, use `weld_value_free` to free the data.
pub unsafe extern "C" fn weld_value_data(value: weld_value_t) -> *mut c_void {
let value = value as *mut weld::WeldValue;
let value = &*value;
value.data() as _
}
#[no_mangle]
/// Frees a Weld value.
///
/// All Weld values must be freed using this call. Weld values which are owned by the runtime also
/// free the data they contain. Weld values which are not owned by the runtime only free the
/// structure used to wrap the data; the actual data itself is owned by the caller.
pub unsafe extern "C" fn weld_value_free(value: weld_value_t) {
let value = value as *mut weld::WeldValue;
if!value.is_null() {
Box::from_raw(value);
}
}
#[no_mangle]
/// Compiles a Weld program into a runnable module.
///
/// The compilation can be configured using the passed configuration pointer. This function stores
/// an error (which indicates a compilation error or success) in `err`.
///
/// This function is a wrapper for `WeldModule::compile`.
pub unsafe extern "C" fn weld_module_compile(
code: *const c_char,
conf: weld_conf_t,
err: weld_error_t,
) -> weld_module_t {
let code = code.to_str();
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match weld::WeldModule::compile(code, conf) {
Ok(module) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(module)) as _
}
Err(compile_err) => {
*err = compile_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Runs a compiled Weld module.
///
/// The module is run with a given configuration and argument list, and returns the result wrapped
/// as a `WeldValue`. If the run raised a runtime error, the method writes the erorr into `err`,
/// and a the method returns `null`. Otherwise, `err` indicates success.
///
/// This function is a wrapper for `WeldModule::run`.
pub unsafe extern "C" fn weld_module_run(
module: weld_module_t,
context: weld_context_t,
arg: weld_value_t,
err: weld_error_t,
) -> weld_value_t {
let module = module as *mut weld::WeldModule;
let module = &mut *module;
let context = context as *mut weld::WeldContext;
let context = &mut *context;
let arg = arg as *mut weld::WeldValue;
let arg = &*arg;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match module.run(context, arg) {
Ok(result) => {
*err = weld::WeldError::new_success();
Box::into_raw(Box::new(result)) as _
}
Err(runtime_err) => {
eprintln!("{:?}", runtime_err);
*err = runtime_err;
ptr::null_mut() as _
}
}
}
#[no_mangle]
/// Frees a module.
///
/// Freeing a module does not free the memory it may have allocated. Values returned by the module
/// must be freed explicitly using `weld_value_free`.
pub unsafe extern "C" fn weld_module_free(module: weld_module_t) {
let module = module as *mut weld::WeldModule;
if!module.is_null() {
Box::from_raw(module);
}
}
#[no_mangle]
/// Creates a new Weld error object.
pub extern "C" fn weld_error_new() -> weld_error_t {
Box::into_raw(Box::new(weld::WeldError::default())) as _
}
#[no_mangle]
/// Returns the error code for a Weld error.
///
/// This function is a wrapper for `WeldError::code`.
pub unsafe extern "C" fn weld_error_code(err: weld_error_t) -> uint64_t {
|
err.code() as _
}
#[no_mangle]
/// Returns a Weld error message.
///
/// This function is a wrapper for `WeldError::message`.
pub unsafe extern "C" fn weld_error_message(err: weld_error_t) -> *const c_char {
let err = err as *mut weld::WeldError;
let err = &*err;
err.message().as_ptr()
}
#[no_mangle]
/// Frees a Weld error object.
pub unsafe extern "C" fn weld_error_free(err: weld_error_t) {
let err = err as *mut weld::WeldError;
if!err.is_null() {
Box::from_raw(err);
}
}
#[no_mangle]
/// Load a dynamic library that a Weld program can access.
///
/// The dynamic library is a C dynamic library identified by its filename.
/// This function is a wrapper for `load_linked_library`.
pub unsafe extern "C" fn weld_load_library(filename: *const c_char, err: weld_error_t) {
let err = err as *mut weld::WeldError;
let err = &mut *err;
let filename = filename.to_str();
if let Err(e) = weld::load_linked_library(filename) {
*err = e;
} else {
*err = weld::WeldError::new_success();
}
}
#[no_mangle]
/// Enables logging to stderr in Weld with the given log level.
///
/// This function is ignored if it has already been called once, or if some other code in the
/// process has initialized logging using Rust's `log` crate.
pub extern "C" fn weld_set_log_level(level: uint64_t) {
weld::set_log_level(level.into())
}
|
let err = err as *mut weld::WeldError;
let err = &*err;
|
random_line_split
|
body.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::str::USVString;
use dom::bindings::trace::RootedTraceableBox;
use dom::blob::{Blob, BlobImpl};
use dom::formdata::FormData;
use dom::globalscope::GlobalScope;
use dom::promise::Promise;
use js::jsapi::Heap;
use js::jsapi::JSContext;
use js::jsapi::JSObject;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_ParseJSON;
use js::jsapi::Value as JSValue;
use js::jsval::UndefinedValue;
use js::typedarray::{ArrayBuffer, CreateWith};
use mime::{Mime, TopLevel, SubLevel};
use std::cell::Ref;
use std::ptr;
use std::rc::Rc;
use std::str;
use url::form_urlencoded;
#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
pub enum BodyType {
Blob,
FormData,
Json,
Text,
ArrayBuffer
}
pub enum FetchedData {
Text(String),
Json(RootedTraceableBox<Heap<JSValue>>),
BlobData(DomRoot<Blob>),
FormData(DomRoot<FormData>),
ArrayBuffer(RootedTraceableBox<Heap<*mut JSObject>>),
}
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(unrooted_must_root)]
pub fn consume_body<T: BodyOperations + DomObject>(object: &T, body_type: BodyType) -> Rc<Promise> {
let promise = Promise::new(&object.global());
// Step 1
if object.get_body_used() || object.is_locked() {
promise.reject_error(Error::Type(
"The response's stream is disturbed or locked".to_string(),
));
return promise;
}
object.set_body_promise(&promise, body_type);
// Steps 2-4
// TODO: Body does not yet have a stream.
consume_body_with_promise(object, body_type, &promise);
promise
}
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(unrooted_must_root)]
pub fn consume_body_with_promise<T: BodyOperations + DomObject>(object: &T,
body_type: BodyType,
promise: &Promise) {
// Step 5
let body = match object.take_body() {
Some(body) => body,
None => return,
};
let pkg_data_results = run_package_data_algorithm(object,
body,
body_type,
object.get_mime_type());
match pkg_data_results {
Ok(results) => {
match results {
FetchedData::Text(s) => promise.resolve_native(&USVString(s)),
FetchedData::Json(j) => promise.resolve_native(&j),
FetchedData::BlobData(b) => promise.resolve_native(&b),
FetchedData::FormData(f) => promise.resolve_native(&f),
FetchedData::ArrayBuffer(a) => promise.resolve_native(&a)
};
},
Err(err) => promise.reject_error(err),
}
}
// https://fetch.spec.whatwg.org/#concept-body-package-data
#[allow(unsafe_code)]
fn run_package_data_algorithm<T: BodyOperations + DomObject>(object: &T,
bytes: Vec<u8>,
body_type: BodyType,
mime_type: Ref<Vec<u8>>)
-> Fallible<FetchedData> {
let global = object.global();
let cx = global.get_cx();
let mime = &*mime_type;
match body_type {
BodyType::Text => run_text_data_algorithm(bytes),
BodyType::Json => run_json_data_algorithm(cx, bytes),
BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime),
BodyType::FormData => run_form_data_algorithm(&global, bytes, mime),
BodyType::ArrayBuffer => unsafe {
run_array_buffer_data_algorithm(cx, bytes)
}
}
}
fn
|
(bytes: Vec<u8>) -> Fallible<FetchedData> {
Ok(FetchedData::Text(String::from_utf8_lossy(&bytes).into_owned()))
}
#[allow(unsafe_code)]
fn run_json_data_algorithm(cx: *mut JSContext,
bytes: Vec<u8>) -> Fallible<FetchedData> {
let json_text = String::from_utf8_lossy(&bytes);
let json_text: Vec<u16> = json_text.encode_utf16().collect();
rooted!(in(cx) let mut rval = UndefinedValue());
unsafe {
if!JS_ParseJSON(cx,
json_text.as_ptr(),
json_text.len() as u32,
rval.handle_mut()) {
JS_ClearPendingException(cx);
// TODO: See issue #13464. Exception should be thrown instead of cleared.
return Err(Error::Type("Failed to parse JSON".to_string()));
}
let rooted_heap = RootedTraceableBox::from_box(Heap::boxed(rval.get()));
Ok(FetchedData::Json(rooted_heap))
}
}
fn run_blob_data_algorithm(root: &GlobalScope,
bytes: Vec<u8>,
mime: &[u8]) -> Fallible<FetchedData> {
let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) {
s
} else {
"".to_string()
};
let blob = Blob::new(root, BlobImpl::new_from_bytes(bytes), mime_string);
Ok(FetchedData::BlobData(blob))
}
fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> {
let mime_str = if let Ok(s) = str::from_utf8(mime) {
s
} else {
""
};
let mime: Mime = mime_str.parse().map_err(
|_| Error::Type("Inappropriate MIME-type for Body".to_string()))?;
match mime {
// TODO
//... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _)
//... is not fully determined yet.
Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) => {
let entries = form_urlencoded::parse(&bytes);
let formdata = FormData::new(None, root);
for (k, e) in entries {
formdata.Append(USVString(k.into_owned()), USVString(e.into_owned()));
}
return Ok(FetchedData::FormData(formdata));
},
_ => return Err(Error::Type("Inappropriate MIME-type for Body".to_string())),
}
}
#[allow(unsafe_code)]
unsafe fn run_array_buffer_data_algorithm(cx: *mut JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> {
rooted!(in(cx) let mut array_buffer_ptr = ptr::null_mut::<JSObject>());
let arraybuffer = ArrayBuffer::create(cx, CreateWith::Slice(&bytes), array_buffer_ptr.handle_mut());
if arraybuffer.is_err() {
return Err(Error::JSFailed);
}
let rooted_heap = RootedTraceableBox::from_box(Heap::boxed(array_buffer_ptr.get()));
Ok(FetchedData::ArrayBuffer(rooted_heap))
}
pub trait BodyOperations {
fn get_body_used(&self) -> bool;
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType);
/// Returns `Some(_)` if the body is complete, `None` if there is more to
/// come.
fn take_body(&self) -> Option<Vec<u8>>;
fn is_locked(&self) -> bool;
fn get_mime_type(&self) -> Ref<Vec<u8>>;
}
|
run_text_data_algorithm
|
identifier_name
|
body.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::str::USVString;
use dom::bindings::trace::RootedTraceableBox;
use dom::blob::{Blob, BlobImpl};
use dom::formdata::FormData;
use dom::globalscope::GlobalScope;
use dom::promise::Promise;
use js::jsapi::Heap;
use js::jsapi::JSContext;
use js::jsapi::JSObject;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_ParseJSON;
use js::jsapi::Value as JSValue;
use js::jsval::UndefinedValue;
use js::typedarray::{ArrayBuffer, CreateWith};
use mime::{Mime, TopLevel, SubLevel};
use std::cell::Ref;
use std::ptr;
use std::rc::Rc;
use std::str;
use url::form_urlencoded;
#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
pub enum BodyType {
Blob,
FormData,
Json,
Text,
ArrayBuffer
}
pub enum FetchedData {
Text(String),
Json(RootedTraceableBox<Heap<JSValue>>),
BlobData(DomRoot<Blob>),
FormData(DomRoot<FormData>),
ArrayBuffer(RootedTraceableBox<Heap<*mut JSObject>>),
}
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(unrooted_must_root)]
pub fn consume_body<T: BodyOperations + DomObject>(object: &T, body_type: BodyType) -> Rc<Promise> {
let promise = Promise::new(&object.global());
// Step 1
if object.get_body_used() || object.is_locked() {
promise.reject_error(Error::Type(
"The response's stream is disturbed or locked".to_string(),
));
return promise;
}
object.set_body_promise(&promise, body_type);
// Steps 2-4
// TODO: Body does not yet have a stream.
consume_body_with_promise(object, body_type, &promise);
promise
}
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(unrooted_must_root)]
pub fn consume_body_with_promise<T: BodyOperations + DomObject>(object: &T,
body_type: BodyType,
promise: &Promise)
|
};
},
Err(err) => promise.reject_error(err),
}
}
// https://fetch.spec.whatwg.org/#concept-body-package-data
#[allow(unsafe_code)]
fn run_package_data_algorithm<T: BodyOperations + DomObject>(object: &T,
bytes: Vec<u8>,
body_type: BodyType,
mime_type: Ref<Vec<u8>>)
-> Fallible<FetchedData> {
let global = object.global();
let cx = global.get_cx();
let mime = &*mime_type;
match body_type {
BodyType::Text => run_text_data_algorithm(bytes),
BodyType::Json => run_json_data_algorithm(cx, bytes),
BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime),
BodyType::FormData => run_form_data_algorithm(&global, bytes, mime),
BodyType::ArrayBuffer => unsafe {
run_array_buffer_data_algorithm(cx, bytes)
}
}
}
fn run_text_data_algorithm(bytes: Vec<u8>) -> Fallible<FetchedData> {
Ok(FetchedData::Text(String::from_utf8_lossy(&bytes).into_owned()))
}
#[allow(unsafe_code)]
fn run_json_data_algorithm(cx: *mut JSContext,
bytes: Vec<u8>) -> Fallible<FetchedData> {
let json_text = String::from_utf8_lossy(&bytes);
let json_text: Vec<u16> = json_text.encode_utf16().collect();
rooted!(in(cx) let mut rval = UndefinedValue());
unsafe {
if!JS_ParseJSON(cx,
json_text.as_ptr(),
json_text.len() as u32,
rval.handle_mut()) {
JS_ClearPendingException(cx);
// TODO: See issue #13464. Exception should be thrown instead of cleared.
return Err(Error::Type("Failed to parse JSON".to_string()));
}
let rooted_heap = RootedTraceableBox::from_box(Heap::boxed(rval.get()));
Ok(FetchedData::Json(rooted_heap))
}
}
fn run_blob_data_algorithm(root: &GlobalScope,
bytes: Vec<u8>,
mime: &[u8]) -> Fallible<FetchedData> {
let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) {
s
} else {
"".to_string()
};
let blob = Blob::new(root, BlobImpl::new_from_bytes(bytes), mime_string);
Ok(FetchedData::BlobData(blob))
}
fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> {
let mime_str = if let Ok(s) = str::from_utf8(mime) {
s
} else {
""
};
let mime: Mime = mime_str.parse().map_err(
|_| Error::Type("Inappropriate MIME-type for Body".to_string()))?;
match mime {
// TODO
//... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _)
//... is not fully determined yet.
Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) => {
let entries = form_urlencoded::parse(&bytes);
let formdata = FormData::new(None, root);
for (k, e) in entries {
formdata.Append(USVString(k.into_owned()), USVString(e.into_owned()));
}
return Ok(FetchedData::FormData(formdata));
},
_ => return Err(Error::Type("Inappropriate MIME-type for Body".to_string())),
}
}
#[allow(unsafe_code)]
unsafe fn run_array_buffer_data_algorithm(cx: *mut JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> {
rooted!(in(cx) let mut array_buffer_ptr = ptr::null_mut::<JSObject>());
let arraybuffer = ArrayBuffer::create(cx, CreateWith::Slice(&bytes), array_buffer_ptr.handle_mut());
if arraybuffer.is_err() {
return Err(Error::JSFailed);
}
let rooted_heap = RootedTraceableBox::from_box(Heap::boxed(array_buffer_ptr.get()));
Ok(FetchedData::ArrayBuffer(rooted_heap))
}
pub trait BodyOperations {
fn get_body_used(&self) -> bool;
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType);
/// Returns `Some(_)` if the body is complete, `None` if there is more to
/// come.
fn take_body(&self) -> Option<Vec<u8>>;
fn is_locked(&self) -> bool;
fn get_mime_type(&self) -> Ref<Vec<u8>>;
}
|
{
// Step 5
let body = match object.take_body() {
Some(body) => body,
None => return,
};
let pkg_data_results = run_package_data_algorithm(object,
body,
body_type,
object.get_mime_type());
match pkg_data_results {
Ok(results) => {
match results {
FetchedData::Text(s) => promise.resolve_native(&USVString(s)),
FetchedData::Json(j) => promise.resolve_native(&j),
FetchedData::BlobData(b) => promise.resolve_native(&b),
FetchedData::FormData(f) => promise.resolve_native(&f),
FetchedData::ArrayBuffer(a) => promise.resolve_native(&a)
|
identifier_body
|
body.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::str::USVString;
use dom::bindings::trace::RootedTraceableBox;
use dom::blob::{Blob, BlobImpl};
use dom::formdata::FormData;
use dom::globalscope::GlobalScope;
use dom::promise::Promise;
use js::jsapi::Heap;
use js::jsapi::JSContext;
use js::jsapi::JSObject;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_ParseJSON;
use js::jsapi::Value as JSValue;
use js::jsval::UndefinedValue;
use js::typedarray::{ArrayBuffer, CreateWith};
use mime::{Mime, TopLevel, SubLevel};
use std::cell::Ref;
use std::ptr;
use std::rc::Rc;
use std::str;
use url::form_urlencoded;
#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
pub enum BodyType {
Blob,
FormData,
Json,
Text,
ArrayBuffer
|
Json(RootedTraceableBox<Heap<JSValue>>),
BlobData(DomRoot<Blob>),
FormData(DomRoot<FormData>),
ArrayBuffer(RootedTraceableBox<Heap<*mut JSObject>>),
}
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(unrooted_must_root)]
pub fn consume_body<T: BodyOperations + DomObject>(object: &T, body_type: BodyType) -> Rc<Promise> {
let promise = Promise::new(&object.global());
// Step 1
if object.get_body_used() || object.is_locked() {
promise.reject_error(Error::Type(
"The response's stream is disturbed or locked".to_string(),
));
return promise;
}
object.set_body_promise(&promise, body_type);
// Steps 2-4
// TODO: Body does not yet have a stream.
consume_body_with_promise(object, body_type, &promise);
promise
}
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(unrooted_must_root)]
pub fn consume_body_with_promise<T: BodyOperations + DomObject>(object: &T,
body_type: BodyType,
promise: &Promise) {
// Step 5
let body = match object.take_body() {
Some(body) => body,
None => return,
};
let pkg_data_results = run_package_data_algorithm(object,
body,
body_type,
object.get_mime_type());
match pkg_data_results {
Ok(results) => {
match results {
FetchedData::Text(s) => promise.resolve_native(&USVString(s)),
FetchedData::Json(j) => promise.resolve_native(&j),
FetchedData::BlobData(b) => promise.resolve_native(&b),
FetchedData::FormData(f) => promise.resolve_native(&f),
FetchedData::ArrayBuffer(a) => promise.resolve_native(&a)
};
},
Err(err) => promise.reject_error(err),
}
}
// https://fetch.spec.whatwg.org/#concept-body-package-data
#[allow(unsafe_code)]
fn run_package_data_algorithm<T: BodyOperations + DomObject>(object: &T,
bytes: Vec<u8>,
body_type: BodyType,
mime_type: Ref<Vec<u8>>)
-> Fallible<FetchedData> {
let global = object.global();
let cx = global.get_cx();
let mime = &*mime_type;
match body_type {
BodyType::Text => run_text_data_algorithm(bytes),
BodyType::Json => run_json_data_algorithm(cx, bytes),
BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime),
BodyType::FormData => run_form_data_algorithm(&global, bytes, mime),
BodyType::ArrayBuffer => unsafe {
run_array_buffer_data_algorithm(cx, bytes)
}
}
}
fn run_text_data_algorithm(bytes: Vec<u8>) -> Fallible<FetchedData> {
Ok(FetchedData::Text(String::from_utf8_lossy(&bytes).into_owned()))
}
#[allow(unsafe_code)]
fn run_json_data_algorithm(cx: *mut JSContext,
bytes: Vec<u8>) -> Fallible<FetchedData> {
let json_text = String::from_utf8_lossy(&bytes);
let json_text: Vec<u16> = json_text.encode_utf16().collect();
rooted!(in(cx) let mut rval = UndefinedValue());
unsafe {
if!JS_ParseJSON(cx,
json_text.as_ptr(),
json_text.len() as u32,
rval.handle_mut()) {
JS_ClearPendingException(cx);
// TODO: See issue #13464. Exception should be thrown instead of cleared.
return Err(Error::Type("Failed to parse JSON".to_string()));
}
let rooted_heap = RootedTraceableBox::from_box(Heap::boxed(rval.get()));
Ok(FetchedData::Json(rooted_heap))
}
}
fn run_blob_data_algorithm(root: &GlobalScope,
bytes: Vec<u8>,
mime: &[u8]) -> Fallible<FetchedData> {
let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) {
s
} else {
"".to_string()
};
let blob = Blob::new(root, BlobImpl::new_from_bytes(bytes), mime_string);
Ok(FetchedData::BlobData(blob))
}
fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> {
let mime_str = if let Ok(s) = str::from_utf8(mime) {
s
} else {
""
};
let mime: Mime = mime_str.parse().map_err(
|_| Error::Type("Inappropriate MIME-type for Body".to_string()))?;
match mime {
// TODO
//... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _)
//... is not fully determined yet.
Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) => {
let entries = form_urlencoded::parse(&bytes);
let formdata = FormData::new(None, root);
for (k, e) in entries {
formdata.Append(USVString(k.into_owned()), USVString(e.into_owned()));
}
return Ok(FetchedData::FormData(formdata));
},
_ => return Err(Error::Type("Inappropriate MIME-type for Body".to_string())),
}
}
#[allow(unsafe_code)]
unsafe fn run_array_buffer_data_algorithm(cx: *mut JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> {
rooted!(in(cx) let mut array_buffer_ptr = ptr::null_mut::<JSObject>());
let arraybuffer = ArrayBuffer::create(cx, CreateWith::Slice(&bytes), array_buffer_ptr.handle_mut());
if arraybuffer.is_err() {
return Err(Error::JSFailed);
}
let rooted_heap = RootedTraceableBox::from_box(Heap::boxed(array_buffer_ptr.get()));
Ok(FetchedData::ArrayBuffer(rooted_heap))
}
pub trait BodyOperations {
fn get_body_used(&self) -> bool;
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType);
/// Returns `Some(_)` if the body is complete, `None` if there is more to
/// come.
fn take_body(&self) -> Option<Vec<u8>>;
fn is_locked(&self) -> bool;
fn get_mime_type(&self) -> Ref<Vec<u8>>;
}
|
}
pub enum FetchedData {
Text(String),
|
random_line_split
|
lib.rs
|
// safesec/safesec-derive/src/lib.rs
// Copyright (C) 2017 authors and contributors (see AUTHORS file)
//
// This file is released under the MIT License.
// ===========================================================================
// Externs
// ===========================================================================
// Stdlib externs
extern crate proc_macro;
// Third-party externs
extern crate num;
extern crate syn;
#[macro_use]
extern crate quote;
// Local externs
// ===========================================================================
// Imports
// ===========================================================================
// Stdlib imports
use proc_macro::TokenStream;
// Third-party imports
use num::ToPrimitive;
// Local imports
// ===========================================================================
//
// ===========================================================================
#[proc_macro_derive(CodeConvert)]
pub fn code_convert(input: TokenStream) -> TokenStream {
// Construct string repr of type definition
let s = input.to_string();
// Parse string
let ast = syn::parse_derive_input(&s).unwrap();
// Build the impl
let gen = impl_code_convert(&ast);
// Return generated impl
gen.parse().unwrap()
}
struct Literal<'a> {
num: &'a syn::Lit
}
impl<'a> From<&'a syn::Lit> for Literal<'a> {
fn from(num: &'a syn::Lit) -> Self {
Self { num: num }
}
}
impl<'a> ToPrimitive for Literal<'a> {
fn to_i64(&self) -> Option<i64> {
match self.num {
&syn::Lit::Int(num, _) => Some(num as i64),
_ => None
}
}
fn
|
(&self) -> Option<u64> {
match self.num {
&syn::Lit::Int(num, _) => Some(num),
_ => None
}
}
}
fn impl_code_convert(ast: &syn::MacroInput) -> quote::Tokens {
if let syn::Body::Enum(ref body) = ast.body {
let name = &ast.ident;
let mut num = 0;
let cases: Vec<_> = body.iter().map(|case| {
// Panic if the variant is a struct or tuple
if let syn::VariantData::Unit = case.data {
// Create variant identifier
let variant = &case.ident;
let ident = quote! { #name::#variant };
// If literal number assigned to variant, assign to num
if let Some(ref d) = case.discriminant {
if let &syn::ConstExpr::Lit(ref l) = d {
let lit = Literal::from(l);
num = match lit.to_u8() {
None => panic!("#[derive(CodeConvert)] only \
supports mapping to u8"),
Some(v) => v
};
} else {
panic!("#[derive(CodeConvert)] only supports literals")
}
}
let ret = quote! { #num => Ok(#ident) };
num += 1;
ret
} else {
panic!("#[derive(CodeConvert)] currently does not support \
tuple or struct variants");
}
}).collect();
quote! {
impl CodeConvert<#name> for #name {
fn from_number(num: u8) -> Result<#name> {
match num {
#(#cases),*,
_ => Err(Error::new(GeneralError::InvalidValue, num.to_string()))
}
}
fn to_number(&self) -> u8 {
self.clone() as u8
}
}
}
} else {
panic!("#[derive(CodeConvert)] is only defined for enums not structs");
}
}
// ===========================================================================
// Tests
// ===========================================================================
// #[cfg(test)]
// mod tests {
// #[test]
// fn it_works() {
// }
// }
// ===========================================================================
//
// ===========================================================================
|
to_u64
|
identifier_name
|
lib.rs
|
// safesec/safesec-derive/src/lib.rs
// Copyright (C) 2017 authors and contributors (see AUTHORS file)
//
// This file is released under the MIT License.
// ===========================================================================
// Externs
// ===========================================================================
// Stdlib externs
extern crate proc_macro;
// Third-party externs
extern crate num;
extern crate syn;
#[macro_use]
extern crate quote;
// Local externs
// ===========================================================================
// Imports
// ===========================================================================
// Stdlib imports
use proc_macro::TokenStream;
// Third-party imports
use num::ToPrimitive;
// Local imports
// ===========================================================================
//
// ===========================================================================
#[proc_macro_derive(CodeConvert)]
pub fn code_convert(input: TokenStream) -> TokenStream {
// Construct string repr of type definition
let s = input.to_string();
// Parse string
let ast = syn::parse_derive_input(&s).unwrap();
// Build the impl
let gen = impl_code_convert(&ast);
// Return generated impl
gen.parse().unwrap()
}
struct Literal<'a> {
num: &'a syn::Lit
}
impl<'a> From<&'a syn::Lit> for Literal<'a> {
fn from(num: &'a syn::Lit) -> Self {
Self { num: num }
}
}
impl<'a> ToPrimitive for Literal<'a> {
fn to_i64(&self) -> Option<i64> {
match self.num {
&syn::Lit::Int(num, _) => Some(num as i64),
_ => None
}
}
fn to_u64(&self) -> Option<u64> {
match self.num {
&syn::Lit::Int(num, _) => Some(num),
_ => None
}
}
}
fn impl_code_convert(ast: &syn::MacroInput) -> quote::Tokens {
if let syn::Body::Enum(ref body) = ast.body {
let name = &ast.ident;
let mut num = 0;
let cases: Vec<_> = body.iter().map(|case| {
// Panic if the variant is a struct or tuple
if let syn::VariantData::Unit = case.data {
// Create variant identifier
let variant = &case.ident;
let ident = quote! { #name::#variant };
// If literal number assigned to variant, assign to num
if let Some(ref d) = case.discriminant {
if let &syn::ConstExpr::Lit(ref l) = d {
let lit = Literal::from(l);
num = match lit.to_u8() {
None => panic!("#[derive(CodeConvert)] only \
supports mapping to u8"),
Some(v) => v
};
} else {
panic!("#[derive(CodeConvert)] only supports literals")
}
}
let ret = quote! { #num => Ok(#ident) };
num += 1;
ret
} else {
panic!("#[derive(CodeConvert)] currently does not support \
tuple or struct variants");
}
}).collect();
quote! {
impl CodeConvert<#name> for #name {
fn from_number(num: u8) -> Result<#name> {
match num {
#(#cases),*,
_ => Err(Error::new(GeneralError::InvalidValue, num.to_string()))
}
}
fn to_number(&self) -> u8 {
|
}
}
}
} else {
panic!("#[derive(CodeConvert)] is only defined for enums not structs");
}
}
// ===========================================================================
// Tests
// ===========================================================================
// #[cfg(test)]
// mod tests {
// #[test]
// fn it_works() {
// }
// }
// ===========================================================================
//
// ===========================================================================
|
self.clone() as u8
|
random_line_split
|
strings.rs
|
//! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MIME_LINE_LENGTH: isize = 76;
/// Return t if OBJECT is a string.
#[lisp_fn]
pub fn stringp(object: LispObject) -> LispObject
|
/// Return the number of bytes in STRING.
/// If STRING is multibyte, this may be greater than the length of STRING.
#[lisp_fn]
pub fn string_bytes(string: LispObject) -> LispObject {
let string = string.as_string_or_error();
LispObject::from_natnum(string.len_bytes() as EmacsInt)
}
/// Return t if two strings have identical contents.
/// Case is significant, but text properties are ignored.
/// Symbols are also allowed; their print names are used instead.
#[lisp_fn]
pub fn string_equal(s1: LispObject, s2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(s1);
let s2 = LispObject::symbol_or_string_as_string(s2);
LispObject::from_bool(
s1.len_chars() == s2.len_chars() && s1.len_bytes() == s2.len_bytes()
&& s1.as_slice() == s2.as_slice(),
)
}
/// Return a multibyte string with the same individual bytes as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an individual 8-bit byte (i.e. not
/// part of a correct utf-8 sequence), it is converted to the corresponding
/// multibyte character of charset `eight-bit'.
/// See also `string-to-multibyte'.
///
/// Beware, this often doesn't really do what you think it does.
/// It is similar to (decode-coding-string STRING \\='utf-8-emacs).
/// If you're not sure, whether to use `string-as-multibyte' or
/// `string-to-multibyte', use `string-to-multibyte'.
#[lisp_fn]
pub fn string_as_multibyte(string: LispObject) -> LispObject {
let s = string.as_string_or_error();
if s.is_multibyte() {
return string;
}
let mut nchars = 0;
let mut nbytes = 0;
multibyte::parse_str_as_multibyte(s.const_data_ptr(), s.len_bytes(), &mut nchars, &mut nbytes);
let new_string = LispObject::from(unsafe {
make_uninit_multibyte_string(nchars as EmacsInt, nbytes as EmacsInt)
});
let mut new_s = new_string.as_string().unwrap();
unsafe {
ptr::copy_nonoverlapping(s.const_data_ptr(), new_s.data_ptr(), s.len_bytes() as usize);
}
if nbytes!= s.len_bytes() {
multibyte::str_as_multibyte(new_s.data_ptr(), nbytes, s.len_bytes(), ptr::null_mut());
}
new_string
}
/// Return a multibyte string with the same individual chars as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an 8-bit byte, it is converted to
/// the corresponding multibyte character of charset `eight-bit'.
///
/// This differs from `string-as-multibyte' by converting each byte of a correct
/// utf-8 sequence to an eight-bit character, not just bytes that don't form a
/// correct sequence.
#[lisp_fn]
pub fn string_to_multibyte(string: LispObject) -> LispObject {
let _ = string.as_string_or_error();
unsafe { LispObject::from(c_string_to_multibyte(string.to_raw())) }
}
/// Return a unibyte string with the same individual chars as STRING.
/// If STRING is unibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties,
/// where each `eight-bit' character is converted to the corresponding byte.
/// If STRING contains a non-ASCII, non-`eight-bit' character,
/// an error is signaled.
#[lisp_fn]
pub fn string_to_unibyte(string: LispObject) -> LispObject {
let lispstr = string.as_string_or_error();
if lispstr.is_multibyte() {
let size = lispstr.len_bytes();
let mut buffer: Vec<libc::c_uchar> = Vec::with_capacity(size as usize);
let converted_size =
multibyte::str_to_unibyte(lispstr.const_data_ptr(), buffer.as_mut_ptr(), size);
if converted_size < size {
error!("Can't convert {}th character to unibyte", converted_size);
}
let raw_ptr = unsafe { make_unibyte_string(buffer.as_ptr() as *const libc::c_char, size) };
LispObject::from(raw_ptr)
} else {
string
}
}
/// Return non-nil if STRING1 is less than STRING2 in lexicographic order.
/// Case is significant.
#[lisp_fn]
pub fn string_lessp(string1: LispObject, string2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(string1);
let s2 = LispObject::symbol_or_string_as_string(string2);
LispObject::from_bool(s1.as_slice() < s2.as_slice())
}
/// Return t if OBJECT is a multibyte string.
/// Return nil if OBJECT is either a unibyte string, or not a string.
#[lisp_fn]
pub fn multibyte_string_p(object: LispObject) -> LispObject {
LispObject::from_bool(object.as_string().map_or(false, |s| s.is_multibyte()))
}
/// Clear the contents of STRING.
/// This makes STRING unibyte and may change its length.
#[lisp_fn]
pub fn clear_string(mut string: LispObject) -> LispObject {
let lisp_string = string.as_string_or_error();
lisp_string.clear_data();
unsafe {
lisp_string.set_num_chars(lisp_string.len_bytes());
}
LispObject::set_string_unibyte(&mut string);
LispObject::constant_nil()
}
include!(concat!(env!("OUT_DIR"), "/strings_exports.rs"));
#[test]
fn test_multibyte_stringp() {
let string = mock_unibyte_string!();
assert_nil!(multibyte_string_p(string));
let flt = mock_float!();
assert_nil!(multibyte_string_p(flt));
let multi = mock_multibyte_string!();
assert_t!(multibyte_string_p(multi));
}
#[test]
fn already_unibyte() {
let single = mock_unibyte_string!();
assert!(string_to_unibyte(single) == single);
}
#[test]
fn str_equality() {
let string1 = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("Hello World");
let string3 = mock_unibyte_string!("Goodbye World");
assert_t!(string_equal(string1, string2));
assert_t!(string_equal(string2, string1));
assert_nil!(string_equal(string1, string3));
assert_nil!(string_equal(string2, string3));
}
#[test]
fn test_stringlessp() {
let string = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("World Hello");
assert_t!(string_lessp(string, string2));
assert_nil!(string_lessp(string2, string));
}
|
{
LispObject::from_bool(object.is_string())
}
|
identifier_body
|
strings.rs
|
//! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MIME_LINE_LENGTH: isize = 76;
/// Return t if OBJECT is a string.
#[lisp_fn]
pub fn stringp(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_string())
}
/// Return the number of bytes in STRING.
/// If STRING is multibyte, this may be greater than the length of STRING.
#[lisp_fn]
pub fn string_bytes(string: LispObject) -> LispObject {
let string = string.as_string_or_error();
LispObject::from_natnum(string.len_bytes() as EmacsInt)
}
/// Return t if two strings have identical contents.
/// Case is significant, but text properties are ignored.
/// Symbols are also allowed; their print names are used instead.
#[lisp_fn]
pub fn string_equal(s1: LispObject, s2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(s1);
let s2 = LispObject::symbol_or_string_as_string(s2);
LispObject::from_bool(
s1.len_chars() == s2.len_chars() && s1.len_bytes() == s2.len_bytes()
&& s1.as_slice() == s2.as_slice(),
)
}
/// Return a multibyte string with the same individual bytes as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an individual 8-bit byte (i.e. not
/// part of a correct utf-8 sequence), it is converted to the corresponding
/// multibyte character of charset `eight-bit'.
/// See also `string-to-multibyte'.
///
/// Beware, this often doesn't really do what you think it does.
/// It is similar to (decode-coding-string STRING \\='utf-8-emacs).
/// If you're not sure, whether to use `string-as-multibyte' or
/// `string-to-multibyte', use `string-to-multibyte'.
#[lisp_fn]
pub fn string_as_multibyte(string: LispObject) -> LispObject {
let s = string.as_string_or_error();
if s.is_multibyte() {
return string;
}
let mut nchars = 0;
let mut nbytes = 0;
multibyte::parse_str_as_multibyte(s.const_data_ptr(), s.len_bytes(), &mut nchars, &mut nbytes);
let new_string = LispObject::from(unsafe {
make_uninit_multibyte_string(nchars as EmacsInt, nbytes as EmacsInt)
});
let mut new_s = new_string.as_string().unwrap();
unsafe {
ptr::copy_nonoverlapping(s.const_data_ptr(), new_s.data_ptr(), s.len_bytes() as usize);
}
if nbytes!= s.len_bytes() {
multibyte::str_as_multibyte(new_s.data_ptr(), nbytes, s.len_bytes(), ptr::null_mut());
}
new_string
}
/// Return a multibyte string with the same individual chars as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an 8-bit byte, it is converted to
/// the corresponding multibyte character of charset `eight-bit'.
///
/// This differs from `string-as-multibyte' by converting each byte of a correct
|
let _ = string.as_string_or_error();
unsafe { LispObject::from(c_string_to_multibyte(string.to_raw())) }
}
/// Return a unibyte string with the same individual chars as STRING.
/// If STRING is unibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties,
/// where each `eight-bit' character is converted to the corresponding byte.
/// If STRING contains a non-ASCII, non-`eight-bit' character,
/// an error is signaled.
#[lisp_fn]
pub fn string_to_unibyte(string: LispObject) -> LispObject {
let lispstr = string.as_string_or_error();
if lispstr.is_multibyte() {
let size = lispstr.len_bytes();
let mut buffer: Vec<libc::c_uchar> = Vec::with_capacity(size as usize);
let converted_size =
multibyte::str_to_unibyte(lispstr.const_data_ptr(), buffer.as_mut_ptr(), size);
if converted_size < size {
error!("Can't convert {}th character to unibyte", converted_size);
}
let raw_ptr = unsafe { make_unibyte_string(buffer.as_ptr() as *const libc::c_char, size) };
LispObject::from(raw_ptr)
} else {
string
}
}
/// Return non-nil if STRING1 is less than STRING2 in lexicographic order.
/// Case is significant.
#[lisp_fn]
pub fn string_lessp(string1: LispObject, string2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(string1);
let s2 = LispObject::symbol_or_string_as_string(string2);
LispObject::from_bool(s1.as_slice() < s2.as_slice())
}
/// Return t if OBJECT is a multibyte string.
/// Return nil if OBJECT is either a unibyte string, or not a string.
#[lisp_fn]
pub fn multibyte_string_p(object: LispObject) -> LispObject {
LispObject::from_bool(object.as_string().map_or(false, |s| s.is_multibyte()))
}
/// Clear the contents of STRING.
/// This makes STRING unibyte and may change its length.
#[lisp_fn]
pub fn clear_string(mut string: LispObject) -> LispObject {
let lisp_string = string.as_string_or_error();
lisp_string.clear_data();
unsafe {
lisp_string.set_num_chars(lisp_string.len_bytes());
}
LispObject::set_string_unibyte(&mut string);
LispObject::constant_nil()
}
include!(concat!(env!("OUT_DIR"), "/strings_exports.rs"));
#[test]
fn test_multibyte_stringp() {
let string = mock_unibyte_string!();
assert_nil!(multibyte_string_p(string));
let flt = mock_float!();
assert_nil!(multibyte_string_p(flt));
let multi = mock_multibyte_string!();
assert_t!(multibyte_string_p(multi));
}
#[test]
fn already_unibyte() {
let single = mock_unibyte_string!();
assert!(string_to_unibyte(single) == single);
}
#[test]
fn str_equality() {
let string1 = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("Hello World");
let string3 = mock_unibyte_string!("Goodbye World");
assert_t!(string_equal(string1, string2));
assert_t!(string_equal(string2, string1));
assert_nil!(string_equal(string1, string3));
assert_nil!(string_equal(string2, string3));
}
#[test]
fn test_stringlessp() {
let string = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("World Hello");
assert_t!(string_lessp(string, string2));
assert_nil!(string_lessp(string2, string));
}
|
/// utf-8 sequence to an eight-bit character, not just bytes that don't form a
/// correct sequence.
#[lisp_fn]
pub fn string_to_multibyte(string: LispObject) -> LispObject {
|
random_line_split
|
strings.rs
|
//! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MIME_LINE_LENGTH: isize = 76;
/// Return t if OBJECT is a string.
#[lisp_fn]
pub fn stringp(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_string())
}
/// Return the number of bytes in STRING.
/// If STRING is multibyte, this may be greater than the length of STRING.
#[lisp_fn]
pub fn string_bytes(string: LispObject) -> LispObject {
let string = string.as_string_or_error();
LispObject::from_natnum(string.len_bytes() as EmacsInt)
}
/// Return t if two strings have identical contents.
/// Case is significant, but text properties are ignored.
/// Symbols are also allowed; their print names are used instead.
#[lisp_fn]
pub fn string_equal(s1: LispObject, s2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(s1);
let s2 = LispObject::symbol_or_string_as_string(s2);
LispObject::from_bool(
s1.len_chars() == s2.len_chars() && s1.len_bytes() == s2.len_bytes()
&& s1.as_slice() == s2.as_slice(),
)
}
/// Return a multibyte string with the same individual bytes as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an individual 8-bit byte (i.e. not
/// part of a correct utf-8 sequence), it is converted to the corresponding
/// multibyte character of charset `eight-bit'.
/// See also `string-to-multibyte'.
///
/// Beware, this often doesn't really do what you think it does.
/// It is similar to (decode-coding-string STRING \\='utf-8-emacs).
/// If you're not sure, whether to use `string-as-multibyte' or
/// `string-to-multibyte', use `string-to-multibyte'.
#[lisp_fn]
pub fn string_as_multibyte(string: LispObject) -> LispObject {
let s = string.as_string_or_error();
if s.is_multibyte() {
return string;
}
let mut nchars = 0;
let mut nbytes = 0;
multibyte::parse_str_as_multibyte(s.const_data_ptr(), s.len_bytes(), &mut nchars, &mut nbytes);
let new_string = LispObject::from(unsafe {
make_uninit_multibyte_string(nchars as EmacsInt, nbytes as EmacsInt)
});
let mut new_s = new_string.as_string().unwrap();
unsafe {
ptr::copy_nonoverlapping(s.const_data_ptr(), new_s.data_ptr(), s.len_bytes() as usize);
}
if nbytes!= s.len_bytes() {
multibyte::str_as_multibyte(new_s.data_ptr(), nbytes, s.len_bytes(), ptr::null_mut());
}
new_string
}
/// Return a multibyte string with the same individual chars as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an 8-bit byte, it is converted to
/// the corresponding multibyte character of charset `eight-bit'.
///
/// This differs from `string-as-multibyte' by converting each byte of a correct
/// utf-8 sequence to an eight-bit character, not just bytes that don't form a
/// correct sequence.
#[lisp_fn]
pub fn string_to_multibyte(string: LispObject) -> LispObject {
let _ = string.as_string_or_error();
unsafe { LispObject::from(c_string_to_multibyte(string.to_raw())) }
}
/// Return a unibyte string with the same individual chars as STRING.
/// If STRING is unibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties,
/// where each `eight-bit' character is converted to the corresponding byte.
/// If STRING contains a non-ASCII, non-`eight-bit' character,
/// an error is signaled.
#[lisp_fn]
pub fn string_to_unibyte(string: LispObject) -> LispObject {
let lispstr = string.as_string_or_error();
if lispstr.is_multibyte() {
let size = lispstr.len_bytes();
let mut buffer: Vec<libc::c_uchar> = Vec::with_capacity(size as usize);
let converted_size =
multibyte::str_to_unibyte(lispstr.const_data_ptr(), buffer.as_mut_ptr(), size);
if converted_size < size {
error!("Can't convert {}th character to unibyte", converted_size);
}
let raw_ptr = unsafe { make_unibyte_string(buffer.as_ptr() as *const libc::c_char, size) };
LispObject::from(raw_ptr)
} else
|
}
/// Return non-nil if STRING1 is less than STRING2 in lexicographic order.
/// Case is significant.
#[lisp_fn]
pub fn string_lessp(string1: LispObject, string2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(string1);
let s2 = LispObject::symbol_or_string_as_string(string2);
LispObject::from_bool(s1.as_slice() < s2.as_slice())
}
/// Return t if OBJECT is a multibyte string.
/// Return nil if OBJECT is either a unibyte string, or not a string.
#[lisp_fn]
pub fn multibyte_string_p(object: LispObject) -> LispObject {
LispObject::from_bool(object.as_string().map_or(false, |s| s.is_multibyte()))
}
/// Clear the contents of STRING.
/// This makes STRING unibyte and may change its length.
#[lisp_fn]
pub fn clear_string(mut string: LispObject) -> LispObject {
let lisp_string = string.as_string_or_error();
lisp_string.clear_data();
unsafe {
lisp_string.set_num_chars(lisp_string.len_bytes());
}
LispObject::set_string_unibyte(&mut string);
LispObject::constant_nil()
}
include!(concat!(env!("OUT_DIR"), "/strings_exports.rs"));
#[test]
fn test_multibyte_stringp() {
let string = mock_unibyte_string!();
assert_nil!(multibyte_string_p(string));
let flt = mock_float!();
assert_nil!(multibyte_string_p(flt));
let multi = mock_multibyte_string!();
assert_t!(multibyte_string_p(multi));
}
#[test]
fn already_unibyte() {
let single = mock_unibyte_string!();
assert!(string_to_unibyte(single) == single);
}
#[test]
fn str_equality() {
let string1 = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("Hello World");
let string3 = mock_unibyte_string!("Goodbye World");
assert_t!(string_equal(string1, string2));
assert_t!(string_equal(string2, string1));
assert_nil!(string_equal(string1, string3));
assert_nil!(string_equal(string2, string3));
}
#[test]
fn test_stringlessp() {
let string = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("World Hello");
assert_t!(string_lessp(string, string2));
assert_nil!(string_lessp(string2, string));
}
|
{
string
}
|
conditional_block
|
strings.rs
|
//! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MIME_LINE_LENGTH: isize = 76;
/// Return t if OBJECT is a string.
#[lisp_fn]
pub fn stringp(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_string())
}
/// Return the number of bytes in STRING.
/// If STRING is multibyte, this may be greater than the length of STRING.
#[lisp_fn]
pub fn string_bytes(string: LispObject) -> LispObject {
let string = string.as_string_or_error();
LispObject::from_natnum(string.len_bytes() as EmacsInt)
}
/// Return t if two strings have identical contents.
/// Case is significant, but text properties are ignored.
/// Symbols are also allowed; their print names are used instead.
#[lisp_fn]
pub fn string_equal(s1: LispObject, s2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(s1);
let s2 = LispObject::symbol_or_string_as_string(s2);
LispObject::from_bool(
s1.len_chars() == s2.len_chars() && s1.len_bytes() == s2.len_bytes()
&& s1.as_slice() == s2.as_slice(),
)
}
/// Return a multibyte string with the same individual bytes as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an individual 8-bit byte (i.e. not
/// part of a correct utf-8 sequence), it is converted to the corresponding
/// multibyte character of charset `eight-bit'.
/// See also `string-to-multibyte'.
///
/// Beware, this often doesn't really do what you think it does.
/// It is similar to (decode-coding-string STRING \\='utf-8-emacs).
/// If you're not sure, whether to use `string-as-multibyte' or
/// `string-to-multibyte', use `string-to-multibyte'.
#[lisp_fn]
pub fn string_as_multibyte(string: LispObject) -> LispObject {
let s = string.as_string_or_error();
if s.is_multibyte() {
return string;
}
let mut nchars = 0;
let mut nbytes = 0;
multibyte::parse_str_as_multibyte(s.const_data_ptr(), s.len_bytes(), &mut nchars, &mut nbytes);
let new_string = LispObject::from(unsafe {
make_uninit_multibyte_string(nchars as EmacsInt, nbytes as EmacsInt)
});
let mut new_s = new_string.as_string().unwrap();
unsafe {
ptr::copy_nonoverlapping(s.const_data_ptr(), new_s.data_ptr(), s.len_bytes() as usize);
}
if nbytes!= s.len_bytes() {
multibyte::str_as_multibyte(new_s.data_ptr(), nbytes, s.len_bytes(), ptr::null_mut());
}
new_string
}
/// Return a multibyte string with the same individual chars as STRING.
/// If STRING is multibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties.
///
/// If STRING is unibyte and contains an 8-bit byte, it is converted to
/// the corresponding multibyte character of charset `eight-bit'.
///
/// This differs from `string-as-multibyte' by converting each byte of a correct
/// utf-8 sequence to an eight-bit character, not just bytes that don't form a
/// correct sequence.
#[lisp_fn]
pub fn string_to_multibyte(string: LispObject) -> LispObject {
let _ = string.as_string_or_error();
unsafe { LispObject::from(c_string_to_multibyte(string.to_raw())) }
}
/// Return a unibyte string with the same individual chars as STRING.
/// If STRING is unibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties,
/// where each `eight-bit' character is converted to the corresponding byte.
/// If STRING contains a non-ASCII, non-`eight-bit' character,
/// an error is signaled.
#[lisp_fn]
pub fn string_to_unibyte(string: LispObject) -> LispObject {
let lispstr = string.as_string_or_error();
if lispstr.is_multibyte() {
let size = lispstr.len_bytes();
let mut buffer: Vec<libc::c_uchar> = Vec::with_capacity(size as usize);
let converted_size =
multibyte::str_to_unibyte(lispstr.const_data_ptr(), buffer.as_mut_ptr(), size);
if converted_size < size {
error!("Can't convert {}th character to unibyte", converted_size);
}
let raw_ptr = unsafe { make_unibyte_string(buffer.as_ptr() as *const libc::c_char, size) };
LispObject::from(raw_ptr)
} else {
string
}
}
/// Return non-nil if STRING1 is less than STRING2 in lexicographic order.
/// Case is significant.
#[lisp_fn]
pub fn string_lessp(string1: LispObject, string2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(string1);
let s2 = LispObject::symbol_or_string_as_string(string2);
LispObject::from_bool(s1.as_slice() < s2.as_slice())
}
/// Return t if OBJECT is a multibyte string.
/// Return nil if OBJECT is either a unibyte string, or not a string.
#[lisp_fn]
pub fn multibyte_string_p(object: LispObject) -> LispObject {
LispObject::from_bool(object.as_string().map_or(false, |s| s.is_multibyte()))
}
/// Clear the contents of STRING.
/// This makes STRING unibyte and may change its length.
#[lisp_fn]
pub fn clear_string(mut string: LispObject) -> LispObject {
let lisp_string = string.as_string_or_error();
lisp_string.clear_data();
unsafe {
lisp_string.set_num_chars(lisp_string.len_bytes());
}
LispObject::set_string_unibyte(&mut string);
LispObject::constant_nil()
}
include!(concat!(env!("OUT_DIR"), "/strings_exports.rs"));
#[test]
fn test_multibyte_stringp() {
let string = mock_unibyte_string!();
assert_nil!(multibyte_string_p(string));
let flt = mock_float!();
assert_nil!(multibyte_string_p(flt));
let multi = mock_multibyte_string!();
assert_t!(multibyte_string_p(multi));
}
#[test]
fn already_unibyte() {
let single = mock_unibyte_string!();
assert!(string_to_unibyte(single) == single);
}
#[test]
fn str_equality() {
let string1 = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("Hello World");
let string3 = mock_unibyte_string!("Goodbye World");
assert_t!(string_equal(string1, string2));
assert_t!(string_equal(string2, string1));
assert_nil!(string_equal(string1, string3));
assert_nil!(string_equal(string2, string3));
}
#[test]
fn
|
() {
let string = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("World Hello");
assert_t!(string_lessp(string, string2));
assert_nil!(string_lessp(string2, string));
}
|
test_stringlessp
|
identifier_name
|
facts.rs
|
use crate::borrow_check::location::{LocationIndex, LocationTable};
use crate::dataflow::indexes::{BorrowIndex, MovePathIndex};
use polonius_engine::AllFacts as PoloniusFacts;
use polonius_engine::Atom;
use rustc_index::vec::Idx;
use rustc_middle::mir::Local;
use rustc_middle::ty::{RegionVid, TyCtxt};
use std::error::Error;
use std::fmt::Debug;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::Path;
#[derive(Copy, Clone, Debug)]
pub struct RustcFacts;
impl polonius_engine::FactTypes for RustcFacts {
type Origin = RegionVid;
type Loan = BorrowIndex;
type Point = LocationIndex;
type Variable = Local;
type Path = MovePathIndex;
}
pub type AllFacts = PoloniusFacts<RustcFacts>;
crate trait AllFactsExt {
/// Returns `true` if there is a need to gather `AllFacts` given the
/// current `-Z` flags.
fn enabled(tcx: TyCtxt<'_>) -> bool;
fn write_to_dir(
&self,
dir: impl AsRef<Path>,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>>;
}
impl AllFactsExt for AllFacts {
/// Return
fn enabled(tcx: TyCtxt<'_>) -> bool {
tcx.sess.opts.debugging_opts.nll_facts || tcx.sess.opts.debugging_opts.polonius
}
fn write_to_dir(
&self,
dir: impl AsRef<Path>,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
let dir: &Path = dir.as_ref();
fs::create_dir_all(dir)?;
let wr = FactWriter { location_table, dir };
macro_rules! write_facts_to_path {
($wr:ident. write_facts_to_path($this:ident. [
$($field:ident,)*
])) => {
$(
$wr.write_facts_to_path(
&$this.$field,
&format!("{}.facts", stringify!($field))
)?;
)*
}
}
write_facts_to_path! {
wr.write_facts_to_path(self.[
loan_issued_at,
universal_region,
cfg_edge,
loan_killed_at,
subset_base,
loan_invalidated_at,
var_used_at,
var_defined_at,
var_dropped_at,
use_of_var_derefs_origin,
drop_of_var_derefs_origin,
child_path,
path_is_var,
path_assigned_at_base,
path_moved_at_base,
path_accessed_at_base,
known_placeholder_subset,
placeholder,
])
}
Ok(())
}
}
impl Atom for BorrowIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
impl Atom for LocationIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
impl Atom for MovePathIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
struct FactWriter<'w> {
location_table: &'w LocationTable,
dir: &'w Path,
}
impl<'w> FactWriter<'w> {
fn
|
<T>(&self, rows: &[T], file_name: &str) -> Result<(), Box<dyn Error>>
where
T: FactRow,
{
let file = &self.dir.join(file_name);
let mut file = BufWriter::new(File::create(file)?);
for row in rows {
row.write(&mut file, self.location_table)?;
}
Ok(())
}
}
trait FactRow {
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>>;
}
impl FactRow for RegionVid {
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[self])
}
}
impl<A, B> FactRow for (A, B)
where
A: FactCell,
B: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1])
}
}
impl<A, B, C> FactRow for (A, B, C)
where
A: FactCell,
B: FactCell,
C: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1, &self.2])
}
}
impl<A, B, C, D> FactRow for (A, B, C, D)
where
A: FactCell,
B: FactCell,
C: FactCell,
D: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1, &self.2, &self.3])
}
}
fn write_row(
out: &mut dyn Write,
location_table: &LocationTable,
columns: &[&dyn FactCell],
) -> Result<(), Box<dyn Error>> {
for (index, c) in columns.iter().enumerate() {
let tail = if index == columns.len() - 1 { "\n" } else { "\t" };
write!(out, "{:?}{}", c.to_string(location_table), tail)?;
}
Ok(())
}
trait FactCell {
fn to_string(&self, location_table: &LocationTable) -> String;
}
impl<A: Debug> FactCell for A {
default fn to_string(&self, _location_table: &LocationTable) -> String {
format!("{:?}", self)
}
}
impl FactCell for LocationIndex {
fn to_string(&self, location_table: &LocationTable) -> String {
format!("{:?}", location_table.to_location(*self))
}
}
|
write_facts_to_path
|
identifier_name
|
facts.rs
|
use crate::borrow_check::location::{LocationIndex, LocationTable};
use crate::dataflow::indexes::{BorrowIndex, MovePathIndex};
use polonius_engine::AllFacts as PoloniusFacts;
use polonius_engine::Atom;
use rustc_index::vec::Idx;
use rustc_middle::mir::Local;
use rustc_middle::ty::{RegionVid, TyCtxt};
use std::error::Error;
use std::fmt::Debug;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::Path;
#[derive(Copy, Clone, Debug)]
pub struct RustcFacts;
impl polonius_engine::FactTypes for RustcFacts {
type Origin = RegionVid;
type Loan = BorrowIndex;
type Point = LocationIndex;
type Variable = Local;
type Path = MovePathIndex;
}
pub type AllFacts = PoloniusFacts<RustcFacts>;
crate trait AllFactsExt {
/// Returns `true` if there is a need to gather `AllFacts` given the
/// current `-Z` flags.
fn enabled(tcx: TyCtxt<'_>) -> bool;
fn write_to_dir(
&self,
dir: impl AsRef<Path>,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>>;
}
impl AllFactsExt for AllFacts {
/// Return
fn enabled(tcx: TyCtxt<'_>) -> bool {
tcx.sess.opts.debugging_opts.nll_facts || tcx.sess.opts.debugging_opts.polonius
}
fn write_to_dir(
&self,
dir: impl AsRef<Path>,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
let dir: &Path = dir.as_ref();
fs::create_dir_all(dir)?;
let wr = FactWriter { location_table, dir };
macro_rules! write_facts_to_path {
($wr:ident. write_facts_to_path($this:ident. [
$($field:ident,)*
])) => {
$(
$wr.write_facts_to_path(
&$this.$field,
&format!("{}.facts", stringify!($field))
)?;
)*
}
}
write_facts_to_path! {
wr.write_facts_to_path(self.[
loan_issued_at,
universal_region,
cfg_edge,
loan_killed_at,
subset_base,
loan_invalidated_at,
var_used_at,
var_defined_at,
var_dropped_at,
use_of_var_derefs_origin,
drop_of_var_derefs_origin,
child_path,
path_is_var,
path_assigned_at_base,
path_moved_at_base,
path_accessed_at_base,
known_placeholder_subset,
placeholder,
])
}
Ok(())
}
}
impl Atom for BorrowIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
impl Atom for LocationIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
impl Atom for MovePathIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
struct FactWriter<'w> {
location_table: &'w LocationTable,
dir: &'w Path,
}
impl<'w> FactWriter<'w> {
fn write_facts_to_path<T>(&self, rows: &[T], file_name: &str) -> Result<(), Box<dyn Error>>
where
T: FactRow,
{
let file = &self.dir.join(file_name);
let mut file = BufWriter::new(File::create(file)?);
for row in rows {
row.write(&mut file, self.location_table)?;
}
Ok(())
}
}
trait FactRow {
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>>;
}
impl FactRow for RegionVid {
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[self])
}
}
impl<A, B> FactRow for (A, B)
where
A: FactCell,
B: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1])
}
}
impl<A, B, C> FactRow for (A, B, C)
where
A: FactCell,
B: FactCell,
C: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1, &self.2])
}
}
impl<A, B, C, D> FactRow for (A, B, C, D)
where
A: FactCell,
B: FactCell,
C: FactCell,
D: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1, &self.2, &self.3])
}
}
fn write_row(
out: &mut dyn Write,
location_table: &LocationTable,
columns: &[&dyn FactCell],
) -> Result<(), Box<dyn Error>> {
for (index, c) in columns.iter().enumerate() {
let tail = if index == columns.len() - 1 { "\n" } else
|
;
write!(out, "{:?}{}", c.to_string(location_table), tail)?;
}
Ok(())
}
trait FactCell {
fn to_string(&self, location_table: &LocationTable) -> String;
}
impl<A: Debug> FactCell for A {
default fn to_string(&self, _location_table: &LocationTable) -> String {
format!("{:?}", self)
}
}
impl FactCell for LocationIndex {
fn to_string(&self, location_table: &LocationTable) -> String {
format!("{:?}", location_table.to_location(*self))
}
}
|
{ "\t" }
|
conditional_block
|
facts.rs
|
use crate::borrow_check::location::{LocationIndex, LocationTable};
use crate::dataflow::indexes::{BorrowIndex, MovePathIndex};
use polonius_engine::AllFacts as PoloniusFacts;
use polonius_engine::Atom;
use rustc_index::vec::Idx;
use rustc_middle::mir::Local;
use rustc_middle::ty::{RegionVid, TyCtxt};
use std::error::Error;
use std::fmt::Debug;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::Path;
#[derive(Copy, Clone, Debug)]
pub struct RustcFacts;
impl polonius_engine::FactTypes for RustcFacts {
type Origin = RegionVid;
type Loan = BorrowIndex;
type Point = LocationIndex;
type Variable = Local;
type Path = MovePathIndex;
}
pub type AllFacts = PoloniusFacts<RustcFacts>;
crate trait AllFactsExt {
/// Returns `true` if there is a need to gather `AllFacts` given the
/// current `-Z` flags.
fn enabled(tcx: TyCtxt<'_>) -> bool;
fn write_to_dir(
&self,
dir: impl AsRef<Path>,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>>;
}
impl AllFactsExt for AllFacts {
/// Return
fn enabled(tcx: TyCtxt<'_>) -> bool {
tcx.sess.opts.debugging_opts.nll_facts || tcx.sess.opts.debugging_opts.polonius
}
fn write_to_dir(
&self,
dir: impl AsRef<Path>,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
let dir: &Path = dir.as_ref();
fs::create_dir_all(dir)?;
let wr = FactWriter { location_table, dir };
macro_rules! write_facts_to_path {
($wr:ident. write_facts_to_path($this:ident. [
$($field:ident,)*
])) => {
$(
$wr.write_facts_to_path(
&$this.$field,
&format!("{}.facts", stringify!($field))
|
wr.write_facts_to_path(self.[
loan_issued_at,
universal_region,
cfg_edge,
loan_killed_at,
subset_base,
loan_invalidated_at,
var_used_at,
var_defined_at,
var_dropped_at,
use_of_var_derefs_origin,
drop_of_var_derefs_origin,
child_path,
path_is_var,
path_assigned_at_base,
path_moved_at_base,
path_accessed_at_base,
known_placeholder_subset,
placeholder,
])
}
Ok(())
}
}
impl Atom for BorrowIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
impl Atom for LocationIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
impl Atom for MovePathIndex {
fn index(self) -> usize {
Idx::index(self)
}
}
struct FactWriter<'w> {
location_table: &'w LocationTable,
dir: &'w Path,
}
impl<'w> FactWriter<'w> {
fn write_facts_to_path<T>(&self, rows: &[T], file_name: &str) -> Result<(), Box<dyn Error>>
where
T: FactRow,
{
let file = &self.dir.join(file_name);
let mut file = BufWriter::new(File::create(file)?);
for row in rows {
row.write(&mut file, self.location_table)?;
}
Ok(())
}
}
trait FactRow {
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>>;
}
impl FactRow for RegionVid {
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[self])
}
}
impl<A, B> FactRow for (A, B)
where
A: FactCell,
B: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1])
}
}
impl<A, B, C> FactRow for (A, B, C)
where
A: FactCell,
B: FactCell,
C: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1, &self.2])
}
}
impl<A, B, C, D> FactRow for (A, B, C, D)
where
A: FactCell,
B: FactCell,
C: FactCell,
D: FactCell,
{
fn write(
&self,
out: &mut dyn Write,
location_table: &LocationTable,
) -> Result<(), Box<dyn Error>> {
write_row(out, location_table, &[&self.0, &self.1, &self.2, &self.3])
}
}
fn write_row(
out: &mut dyn Write,
location_table: &LocationTable,
columns: &[&dyn FactCell],
) -> Result<(), Box<dyn Error>> {
for (index, c) in columns.iter().enumerate() {
let tail = if index == columns.len() - 1 { "\n" } else { "\t" };
write!(out, "{:?}{}", c.to_string(location_table), tail)?;
}
Ok(())
}
trait FactCell {
fn to_string(&self, location_table: &LocationTable) -> String;
}
impl<A: Debug> FactCell for A {
default fn to_string(&self, _location_table: &LocationTable) -> String {
format!("{:?}", self)
}
}
impl FactCell for LocationIndex {
fn to_string(&self, location_table: &LocationTable) -> String {
format!("{:?}", location_table.to_location(*self))
}
}
|
)?;
)*
}
}
write_facts_to_path! {
|
random_line_split
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{ConsoleLogger, FileKey};
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
use graphql_transforms::OSSConnectionInterface;
use relay_compiler::apply_transforms;
use relay_typegen;
use test_schema::test_schema;
pub fn transform_fixture(fixture: &Fixture) -> Result<String, String>
|
.into_iter()
.map(|frag| relay_typegen::generate_operation_type(frag, &schema));
let mut fragments: Vec<_> = programs.typegen.fragments().collect();
fragments.sort_by_key(|frag| frag.name.item);
let fragment_strings = fragments
.into_iter()
.map(|frag| relay_typegen::generate_fragment_type(frag, &schema));
let mut result: Vec<String> = operation_strings.collect();
result.extend(fragment_strings);
Ok(result
.join("-------------------------------------------------------------------------------\n"))
}
|
{
let mut sources = FnvHashMap::default();
sources.insert(FileKey::new(fixture.file_name), fixture.content);
let schema = test_schema();
let ast = parse(fixture.content, FileKey::new(fixture.file_name)).unwrap();
let ir = build(&schema, &ast.definitions).unwrap();
let program = Program::from_definitions(&schema, ir);
let connection_interface = OSSConnectionInterface::default();
let programs = apply_transforms(
"test",
program,
&Default::default(),
&connection_interface,
&ConsoleLogger,
)
.unwrap();
let mut operations: Vec<_> = programs.typegen.operations().collect();
operations.sort_by_key(|op| op.name.item);
let operation_strings = operations
|
identifier_body
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{ConsoleLogger, FileKey};
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
use graphql_transforms::OSSConnectionInterface;
use relay_compiler::apply_transforms;
use relay_typegen;
use test_schema::test_schema;
pub fn
|
(fixture: &Fixture) -> Result<String, String> {
let mut sources = FnvHashMap::default();
sources.insert(FileKey::new(fixture.file_name), fixture.content);
let schema = test_schema();
let ast = parse(fixture.content, FileKey::new(fixture.file_name)).unwrap();
let ir = build(&schema, &ast.definitions).unwrap();
let program = Program::from_definitions(&schema, ir);
let connection_interface = OSSConnectionInterface::default();
let programs = apply_transforms(
"test",
program,
&Default::default(),
&connection_interface,
&ConsoleLogger,
)
.unwrap();
let mut operations: Vec<_> = programs.typegen.operations().collect();
operations.sort_by_key(|op| op.name.item);
let operation_strings = operations
.into_iter()
.map(|frag| relay_typegen::generate_operation_type(frag, &schema));
let mut fragments: Vec<_> = programs.typegen.fragments().collect();
fragments.sort_by_key(|frag| frag.name.item);
let fragment_strings = fragments
.into_iter()
.map(|frag| relay_typegen::generate_fragment_type(frag, &schema));
let mut result: Vec<String> = operation_strings.collect();
result.extend(fragment_strings);
Ok(result
.join("-------------------------------------------------------------------------------\n"))
}
|
transform_fixture
|
identifier_name
|
find.rs
|
use schema::*;
use diesel::*;
#[test]
fn find() {
use schema::users::table as users;
|
let connection = connection();
connection.execute("INSERT INTO users (id, name) VALUES (1, 'Sean'), (2, 'Tess')")
.unwrap();
assert_eq!(Ok(User::new(1, "Sean")), users.find(1).first(&connection));
assert_eq!(Ok(User::new(2, "Tess")), users.find(2).first(&connection));
assert_eq!(Ok(None::<User>), users.find(3).first(&connection).optional());
}
table! {
users_with_name_pk (name) {
name -> VarChar,
}
}
#[test]
fn find_with_non_serial_pk() {
use self::users_with_name_pk::table as users;
let connection = connection();
connection.execute("CREATE TABLE users_with_name_pk (name VARCHAR PRIMARY KEY)")
.unwrap();
connection.execute("INSERT INTO users_with_name_pk (name) VALUES ('Sean'), ('Tess')")
.unwrap();
assert_eq!(Ok("Sean".to_string()), users.find("Sean").first(&connection));
assert_eq!(Ok("Tess".to_string()), users.find("Tess".to_string()).first(&connection));
assert_eq!(Ok(None::<String>), users.find("Wibble").first(&connection).optional());
}
|
random_line_split
|
|
find.rs
|
use schema::*;
use diesel::*;
#[test]
fn find() {
use schema::users::table as users;
let connection = connection();
connection.execute("INSERT INTO users (id, name) VALUES (1, 'Sean'), (2, 'Tess')")
.unwrap();
assert_eq!(Ok(User::new(1, "Sean")), users.find(1).first(&connection));
assert_eq!(Ok(User::new(2, "Tess")), users.find(2).first(&connection));
assert_eq!(Ok(None::<User>), users.find(3).first(&connection).optional());
}
table! {
users_with_name_pk (name) {
name -> VarChar,
}
}
#[test]
fn
|
() {
use self::users_with_name_pk::table as users;
let connection = connection();
connection.execute("CREATE TABLE users_with_name_pk (name VARCHAR PRIMARY KEY)")
.unwrap();
connection.execute("INSERT INTO users_with_name_pk (name) VALUES ('Sean'), ('Tess')")
.unwrap();
assert_eq!(Ok("Sean".to_string()), users.find("Sean").first(&connection));
assert_eq!(Ok("Tess".to_string()), users.find("Tess".to_string()).first(&connection));
assert_eq!(Ok(None::<String>), users.find("Wibble").first(&connection).optional());
}
|
find_with_non_serial_pk
|
identifier_name
|
find.rs
|
use schema::*;
use diesel::*;
#[test]
fn find()
|
table! {
users_with_name_pk (name) {
name -> VarChar,
}
}
#[test]
fn find_with_non_serial_pk() {
use self::users_with_name_pk::table as users;
let connection = connection();
connection.execute("CREATE TABLE users_with_name_pk (name VARCHAR PRIMARY KEY)")
.unwrap();
connection.execute("INSERT INTO users_with_name_pk (name) VALUES ('Sean'), ('Tess')")
.unwrap();
assert_eq!(Ok("Sean".to_string()), users.find("Sean").first(&connection));
assert_eq!(Ok("Tess".to_string()), users.find("Tess".to_string()).first(&connection));
assert_eq!(Ok(None::<String>), users.find("Wibble").first(&connection).optional());
}
|
{
use schema::users::table as users;
let connection = connection();
connection.execute("INSERT INTO users (id, name) VALUES (1, 'Sean'), (2, 'Tess')")
.unwrap();
assert_eq!(Ok(User::new(1, "Sean")), users.find(1).first(&connection));
assert_eq!(Ok(User::new(2, "Tess")), users.find(2).first(&connection));
assert_eq!(Ok(None::<User>), users.find(3).first(&connection).optional());
}
|
identifier_body
|
mod.rs
|
use async_trait::async_trait;
use yaml_rust::Yaml;
mod assert;
mod assign;
mod delay;
mod exec;
mod request;
pub use self::assert::Assert;
pub use self::assign::Assign;
pub use self::delay::Delay;
pub use self::exec::Exec;
pub use self::request::Request;
use crate::benchmark::{Context, Pool, Reports};
use crate::config::Config;
use std::fmt;
#[async_trait]
pub trait Runnable {
async fn execute(&self, context: &mut Context, reports: &mut Reports, pool: &Pool, config: &Config);
}
#[derive(Clone)]
pub struct Report {
pub name: String,
pub duration: f64,
pub status: u16,
}
impl fmt::Debug for Report {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n", self.name, self.duration)
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n status: {}\n", self.name, self.duration, self.status)
}
}
pub fn extract_optional<'a>(item: &'a Yaml, attr: &'a str) -> Option<&'a str> {
if let Some(s) = item[attr].as_str() {
Some(s)
} else {
if item[attr].as_hash().is_some()
|
else {
None
}
}
}
pub fn extract<'a>(item: &'a Yaml, attr: &'a str) -> &'a str {
if let Some(s) = item[attr].as_str() {
s
} else {
if item[attr].as_hash().is_some() {
panic!("`{}` is required needs to be a string. Try adding quotes", attr);
} else {
panic!("Unknown node `{}` => {:?}", attr, item[attr]);
}
}
}
|
{
panic!("`{}` needs to be a string. Try adding quotes", attr);
}
|
conditional_block
|
mod.rs
|
use async_trait::async_trait;
use yaml_rust::Yaml;
mod assert;
mod assign;
mod delay;
mod exec;
mod request;
pub use self::assert::Assert;
pub use self::assign::Assign;
pub use self::delay::Delay;
pub use self::exec::Exec;
pub use self::request::Request;
use crate::benchmark::{Context, Pool, Reports};
use crate::config::Config;
use std::fmt;
#[async_trait]
pub trait Runnable {
async fn execute(&self, context: &mut Context, reports: &mut Reports, pool: &Pool, config: &Config);
}
#[derive(Clone)]
pub struct Report {
pub name: String,
pub duration: f64,
pub status: u16,
}
impl fmt::Debug for Report {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n", self.name, self.duration)
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n status: {}\n", self.name, self.duration, self.status)
}
}
pub fn extract_optional<'a>(item: &'a Yaml, attr: &'a str) -> Option<&'a str> {
if let Some(s) = item[attr].as_str() {
Some(s)
} else {
if item[attr].as_hash().is_some() {
panic!("`{}` needs to be a string. Try adding quotes", attr);
} else {
None
}
}
}
pub fn extract<'a>(item: &'a Yaml, attr: &'a str) -> &'a str {
if let Some(s) = item[attr].as_str() {
s
} else {
if item[attr].as_hash().is_some() {
panic!("`{}` is required needs to be a string. Try adding quotes", attr);
} else {
panic!("Unknown node `{}` => {:?}", attr, item[attr]);
}
}
}
|
fmt
|
identifier_name
|
mod.rs
|
use async_trait::async_trait;
use yaml_rust::Yaml;
mod assert;
mod assign;
mod delay;
mod exec;
|
mod request;
pub use self::assert::Assert;
pub use self::assign::Assign;
pub use self::delay::Delay;
pub use self::exec::Exec;
pub use self::request::Request;
use crate::benchmark::{Context, Pool, Reports};
use crate::config::Config;
use std::fmt;
#[async_trait]
pub trait Runnable {
async fn execute(&self, context: &mut Context, reports: &mut Reports, pool: &Pool, config: &Config);
}
#[derive(Clone)]
pub struct Report {
pub name: String,
pub duration: f64,
pub status: u16,
}
impl fmt::Debug for Report {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n", self.name, self.duration)
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n status: {}\n", self.name, self.duration, self.status)
}
}
pub fn extract_optional<'a>(item: &'a Yaml, attr: &'a str) -> Option<&'a str> {
if let Some(s) = item[attr].as_str() {
Some(s)
} else {
if item[attr].as_hash().is_some() {
panic!("`{}` needs to be a string. Try adding quotes", attr);
} else {
None
}
}
}
pub fn extract<'a>(item: &'a Yaml, attr: &'a str) -> &'a str {
if let Some(s) = item[attr].as_str() {
s
} else {
if item[attr].as_hash().is_some() {
panic!("`{}` is required needs to be a string. Try adding quotes", attr);
} else {
panic!("Unknown node `{}` => {:?}", attr, item[attr]);
}
}
}
|
random_line_split
|
|
try_join_all.rs
|
use futures_util::future::*;
use std::future::Future;
use futures::executor::block_on;
use std::fmt::Debug;
fn assert_done<T, F>(actual_fut: F, expected: T)
where
T: PartialEq + Debug,
F: FnOnce() -> Box<dyn Future<Output = T> + Unpin>,
{
let output = block_on(actual_fut());
assert_eq!(output, expected);
}
#[test]
fn collect_collects() {
assert_done(|| Box::new(try_join_all(vec![ok(1), ok(2)])), Ok::<_, usize>(vec![1, 2]));
assert_done(|| Box::new(try_join_all(vec![ok(1), err(2)])), Err(2));
assert_done(|| Box::new(try_join_all(vec![ok(1)])), Ok::<_, usize>(vec![1]));
// REVIEW: should this be implemented?
// assert_done(|| Box::new(try_join_all(Vec::<i32>::new())), Ok(vec![]));
|
#[test]
fn try_join_all_iter_lifetime() {
// In futures-rs version 0.1, this function would fail to typecheck due to an overly
// conservative type parameterization of `TryJoinAll`.
fn sizes<'a>(bufs: Vec<&'a [u8]>) -> Box<dyn Future<Output = Result<Vec<usize>, ()>> + Unpin> {
let iter = bufs.into_iter().map(|b| ok::<usize, ()>(b.len()));
Box::new(try_join_all(iter))
}
assert_done(|| sizes(vec![&[1,2,3], &[], &[0]]), Ok(vec![3 as usize, 0, 1]));
}
#[test]
fn try_join_all_from_iter() {
assert_done(
|| Box::new(vec![ok(1), ok(2)].into_iter().collect::<TryJoinAll<_>>()),
Ok::<_, usize>(vec![1, 2]),
)
}
|
// TODO: needs more tests
}
|
random_line_split
|
try_join_all.rs
|
use futures_util::future::*;
use std::future::Future;
use futures::executor::block_on;
use std::fmt::Debug;
fn assert_done<T, F>(actual_fut: F, expected: T)
where
T: PartialEq + Debug,
F: FnOnce() -> Box<dyn Future<Output = T> + Unpin>,
{
let output = block_on(actual_fut());
assert_eq!(output, expected);
}
#[test]
fn collect_collects()
|
#[test]
fn try_join_all_iter_lifetime() {
// In futures-rs version 0.1, this function would fail to typecheck due to an overly
// conservative type parameterization of `TryJoinAll`.
fn sizes<'a>(bufs: Vec<&'a [u8]>) -> Box<dyn Future<Output = Result<Vec<usize>, ()>> + Unpin> {
let iter = bufs.into_iter().map(|b| ok::<usize, ()>(b.len()));
Box::new(try_join_all(iter))
}
assert_done(|| sizes(vec![&[1,2,3], &[], &[0]]), Ok(vec![3 as usize, 0, 1]));
}
#[test]
fn try_join_all_from_iter() {
assert_done(
|| Box::new(vec![ok(1), ok(2)].into_iter().collect::<TryJoinAll<_>>()),
Ok::<_, usize>(vec![1, 2]),
)
}
|
{
assert_done(|| Box::new(try_join_all(vec![ok(1), ok(2)])), Ok::<_, usize>(vec![1, 2]));
assert_done(|| Box::new(try_join_all(vec![ok(1), err(2)])), Err(2));
assert_done(|| Box::new(try_join_all(vec![ok(1)])), Ok::<_, usize>(vec![1]));
// REVIEW: should this be implemented?
// assert_done(|| Box::new(try_join_all(Vec::<i32>::new())), Ok(vec![]));
// TODO: needs more tests
}
|
identifier_body
|
try_join_all.rs
|
use futures_util::future::*;
use std::future::Future;
use futures::executor::block_on;
use std::fmt::Debug;
fn assert_done<T, F>(actual_fut: F, expected: T)
where
T: PartialEq + Debug,
F: FnOnce() -> Box<dyn Future<Output = T> + Unpin>,
{
let output = block_on(actual_fut());
assert_eq!(output, expected);
}
#[test]
fn collect_collects() {
assert_done(|| Box::new(try_join_all(vec![ok(1), ok(2)])), Ok::<_, usize>(vec![1, 2]));
assert_done(|| Box::new(try_join_all(vec![ok(1), err(2)])), Err(2));
assert_done(|| Box::new(try_join_all(vec![ok(1)])), Ok::<_, usize>(vec![1]));
// REVIEW: should this be implemented?
// assert_done(|| Box::new(try_join_all(Vec::<i32>::new())), Ok(vec![]));
// TODO: needs more tests
}
#[test]
fn try_join_all_iter_lifetime() {
// In futures-rs version 0.1, this function would fail to typecheck due to an overly
// conservative type parameterization of `TryJoinAll`.
fn
|
<'a>(bufs: Vec<&'a [u8]>) -> Box<dyn Future<Output = Result<Vec<usize>, ()>> + Unpin> {
let iter = bufs.into_iter().map(|b| ok::<usize, ()>(b.len()));
Box::new(try_join_all(iter))
}
assert_done(|| sizes(vec![&[1,2,3], &[], &[0]]), Ok(vec![3 as usize, 0, 1]));
}
#[test]
fn try_join_all_from_iter() {
assert_done(
|| Box::new(vec![ok(1), ok(2)].into_iter().collect::<TryJoinAll<_>>()),
Ok::<_, usize>(vec![1, 2]),
)
}
|
sizes
|
identifier_name
|
pong.rs
|
use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [512, 512];
static PADDLE_SIZE: [f64; 2] = [8.0, 32.0];
static PADDLE_ACCEL: f64 = 4000.0;
static PADDLE_FRICTION: f64 = 0.5;
static PADDLE_MAX_SPEED: f64 = 400.0;
static BALL_SIZE: [f64; 2] = [8.0, 8.0];
static BALL_START_MAX_ANGLE: f64 = 60.0;
static BALL_START_SPEED: f64 = 200.0;
static BALL_SPEED_INCREMENT: f64 = 25.0;
struct Pong {
gl: GlGraphics,
p1: GameObject,
p2: GameObject,
ball: GameObject,
up: bool,
down: bool,
server: Player,
p1_score: u32,
p2_score: u32,
}
enum Player {
Left,
Right
}
impl Pong {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
let objs = [&self.p1, &self.p2, &self.ball];
self.gl.draw(args.viewport(), |c, gl| {
clear(BLACK, gl);
for obj in objs.iter() {
let rect = [0.0, 0.0, obj.size[0], obj.size[1]];
let transform = c.transform.trans(obj.pos[0], obj.pos[1])
.trans(-obj.size[0] / 2.0, -obj.size[1] / 2.0);
rectangle(WHITE, rect, transform, gl);
}
});
}
fn
|
(&mut self, args: &UpdateArgs) {
let (ai_up, ai_down) = self.handle_ai_paddle();
Pong::handle_paddle(&mut self.p1, self.up, self.down, args.dt);
Pong::handle_paddle(&mut self.p2, ai_up, ai_down, args.dt);
Pong::handle_game_object(&mut self.p1, args.dt, false);
Pong::handle_game_object(&mut self.p2, args.dt, false);
Pong::handle_game_object(&mut self.ball, args.dt, true);
self.handle_ball();
}
fn start(&mut self) {
self.p1.pos = [self.p1.size[0] / 2.0 + 4.0, (SIZE[1] / 2) as f64];
self.p2.pos = [SIZE[0] as f64 - self.p2.size[0] / 2.0 - 4.0,
(SIZE[1] / 2) as f64];
self.reset();
}
fn reset(&mut self) {
use std::f64::consts::PI;
use rand;
use rand::Rng;
self.ball.pos = [(SIZE[0] / 2) as f64, (SIZE[1] / 2) as f64];
let mut rng = rand::thread_rng();
let max_angle = 2.0 * BALL_START_MAX_ANGLE * PI / 180.0;
let angle = rng.next_f64() * max_angle - max_angle / 2.0;
self.ball.vel = [
angle.cos() * BALL_START_SPEED * self.serve_direction(),
angle.sin() * BALL_START_SPEED
];
}
fn serve_direction(&mut self) -> f64 {
match self.server {
Player::Left => { -1.0 }
Player::Right => { 1.0 }
}
}
fn key_press(&mut self, key: Key) {
match key {
Key::Up => { self.up = true; }
Key::Down => { self.down = true; }
_ => {}
}
}
fn key_release(&mut self, key: Key) {
match key {
Key::Up => { self.up = false; }
Key::Down => { self.down = false; }
_ => {}
}
}
fn handle_game_object(obj: &mut GameObject, dt: f64, bounce: bool) {
obj.pos[0] += obj.vel[0] * dt;
obj.pos[1] += obj.vel[1] * dt;
if obj.pos[1] + obj.size[1] / 2.0 >= SIZE[1] as f64 {
obj.pos[1] = SIZE[1] as f64 - obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
if obj.pos[1] - obj.size[1] / 2.0 <= 0.0f64 {
obj.pos[1] = obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
}
fn handle_paddle(paddle: &mut GameObject, up: bool, down: bool, dt: f64) {
if up {
paddle.vel[1] -= PADDLE_ACCEL * dt;
} else if down {
paddle.vel[1] += PADDLE_ACCEL * dt;
} else {
let dv = -paddle.vel[1].signum() * PADDLE_ACCEL * dt;
if dv.abs() >= paddle.vel[1].abs() { paddle.vel[1] = 0.0; }
else { paddle.vel[1] += dv; }
}
if paddle.vel[1] > PADDLE_MAX_SPEED {
paddle.vel[1] = PADDLE_MAX_SPEED;
} else if paddle.vel[1] < -PADDLE_MAX_SPEED {
paddle.vel[1] = -PADDLE_MAX_SPEED;
}
}
fn handle_ai_paddle(&self) -> (bool, bool) {
let mut ai_up = false;
let mut ai_down = false;
if self.ball.vel[0] > 0.0 {
let t = (self.p2.pos[0] - self.ball.pos[0]) / self.ball.vel[0];
let target_y = self.ball.pos[1] + self.ball.vel[1] * t;
if target_y > self.p2.pos[1] { ai_down = true; }
else if target_y < self.p2.pos[1] { ai_up = true; }
}
(ai_up, ai_down)
}
fn handle_ball(&mut self) {
for paddle in [&self.p1, &self.p2].iter() {
match self.ball.collision_normal(paddle) {
Some(normal) => {
let dot = self.ball.vel[0] * normal[0] +
self.ball.vel[1] * normal[1];
// reflect ball's velocity off collision normal
self.ball.vel = [
self.ball.vel[0] - 2.0 * normal[0] * dot,
self.ball.vel[1] - 2.0 * normal[1] * dot
];
// apply a bit of paddle y velocity to ball
if normal[0]!= 0.0 {
self.ball.vel[1] += paddle.vel[1] * PADDLE_FRICTION;
}
// increment ball x velocity a bit
self.ball.vel[0] += BALL_SPEED_INCREMENT *
self.ball.vel[0].signum();
Pong::correct_collision(&mut self.ball, paddle, normal);
}
None => {}
}
}
if self.ball.pos[0] > SIZE[0] as f64 { self.score(Player::Left); }
else if self.ball.pos[0] < 0.0 { self.score(Player::Right); }
}
fn correct_collision(a: &mut GameObject, b: &GameObject, normal: [f64; 2]) {
if normal == [1.0, 0.0] {
a.pos[0] = b.pos[0] + b.size[0] / 2.0 + a.size[0] / 2.0;
} else if normal == [-1.0, 0.0] {
a.pos[0] = b.pos[0] - b.size[0] / 2.0 - a.size[0] / 2.0;
} else if normal == [0.0, 1.0] {
a.pos[1] = b.pos[1] + b.size[1] / 2.0 + a.size[1] / 2.0;
} else if normal == [0.0, -1.0] {
a.pos[1] = b.pos[1] - b.size[1] / 2.0 - a.size[1] / 2.0;
}
}
fn score(&mut self, player: Player) {
match player {
Player::Left => {
self.server = Player::Right;
self.p1_score += 1;
println!("Player 1 scored! {}-{}", self.p1_score,
self.p2_score);
}
Player::Right => {
self.server = Player::Left;
self.p2_score += 1;
println!("Player 2 scored! {}-{}", self.p1_score,
self.p2_score);
}
}
self.reset();
}
}
pub fn play() {
let window = Window::new(OPENGL_VERSION,
WindowSettings::new("pong", SIZE)
.exit_on_esc(true));
let mut pong = Pong {
gl: GlGraphics::new(OPENGL_VERSION),
p1: GameObject { size: PADDLE_SIZE,..Default::default() },
p2: GameObject { size: PADDLE_SIZE,..Default::default() },
ball: GameObject { size: BALL_SIZE,..Default::default() },
up: false,
down: false,
server: Player::Left,
p1_score: 0,
p2_score: 0,
};
pong.start();
for e in window.events() {
if let Some(r) = e.render_args() { pong.render(&r); }
if let Some(u) = e.update_args() { pong.update(&u); }
if let Some(Keyboard(key)) = e.press_args() { pong.key_press(key); }
if let Some(Keyboard(key)) = e.release_args() { pong.key_release(key); }
}
}
|
update
|
identifier_name
|
pong.rs
|
use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [512, 512];
static PADDLE_SIZE: [f64; 2] = [8.0, 32.0];
static PADDLE_ACCEL: f64 = 4000.0;
static PADDLE_FRICTION: f64 = 0.5;
static PADDLE_MAX_SPEED: f64 = 400.0;
static BALL_SIZE: [f64; 2] = [8.0, 8.0];
static BALL_START_MAX_ANGLE: f64 = 60.0;
static BALL_START_SPEED: f64 = 200.0;
static BALL_SPEED_INCREMENT: f64 = 25.0;
struct Pong {
gl: GlGraphics,
p1: GameObject,
p2: GameObject,
ball: GameObject,
up: bool,
down: bool,
server: Player,
p1_score: u32,
p2_score: u32,
}
enum Player {
Left,
Right
}
impl Pong {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
let objs = [&self.p1, &self.p2, &self.ball];
self.gl.draw(args.viewport(), |c, gl| {
clear(BLACK, gl);
for obj in objs.iter() {
let rect = [0.0, 0.0, obj.size[0], obj.size[1]];
let transform = c.transform.trans(obj.pos[0], obj.pos[1])
.trans(-obj.size[0] / 2.0, -obj.size[1] / 2.0);
rectangle(WHITE, rect, transform, gl);
}
});
}
fn update(&mut self, args: &UpdateArgs) {
let (ai_up, ai_down) = self.handle_ai_paddle();
Pong::handle_paddle(&mut self.p1, self.up, self.down, args.dt);
Pong::handle_paddle(&mut self.p2, ai_up, ai_down, args.dt);
Pong::handle_game_object(&mut self.p1, args.dt, false);
Pong::handle_game_object(&mut self.p2, args.dt, false);
Pong::handle_game_object(&mut self.ball, args.dt, true);
self.handle_ball();
}
|
fn start(&mut self) {
self.p1.pos = [self.p1.size[0] / 2.0 + 4.0, (SIZE[1] / 2) as f64];
self.p2.pos = [SIZE[0] as f64 - self.p2.size[0] / 2.0 - 4.0,
(SIZE[1] / 2) as f64];
self.reset();
}
fn reset(&mut self) {
use std::f64::consts::PI;
use rand;
use rand::Rng;
self.ball.pos = [(SIZE[0] / 2) as f64, (SIZE[1] / 2) as f64];
let mut rng = rand::thread_rng();
let max_angle = 2.0 * BALL_START_MAX_ANGLE * PI / 180.0;
let angle = rng.next_f64() * max_angle - max_angle / 2.0;
self.ball.vel = [
angle.cos() * BALL_START_SPEED * self.serve_direction(),
angle.sin() * BALL_START_SPEED
];
}
fn serve_direction(&mut self) -> f64 {
match self.server {
Player::Left => { -1.0 }
Player::Right => { 1.0 }
}
}
fn key_press(&mut self, key: Key) {
match key {
Key::Up => { self.up = true; }
Key::Down => { self.down = true; }
_ => {}
}
}
fn key_release(&mut self, key: Key) {
match key {
Key::Up => { self.up = false; }
Key::Down => { self.down = false; }
_ => {}
}
}
fn handle_game_object(obj: &mut GameObject, dt: f64, bounce: bool) {
obj.pos[0] += obj.vel[0] * dt;
obj.pos[1] += obj.vel[1] * dt;
if obj.pos[1] + obj.size[1] / 2.0 >= SIZE[1] as f64 {
obj.pos[1] = SIZE[1] as f64 - obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
if obj.pos[1] - obj.size[1] / 2.0 <= 0.0f64 {
obj.pos[1] = obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
}
fn handle_paddle(paddle: &mut GameObject, up: bool, down: bool, dt: f64) {
if up {
paddle.vel[1] -= PADDLE_ACCEL * dt;
} else if down {
paddle.vel[1] += PADDLE_ACCEL * dt;
} else {
let dv = -paddle.vel[1].signum() * PADDLE_ACCEL * dt;
if dv.abs() >= paddle.vel[1].abs() { paddle.vel[1] = 0.0; }
else { paddle.vel[1] += dv; }
}
if paddle.vel[1] > PADDLE_MAX_SPEED {
paddle.vel[1] = PADDLE_MAX_SPEED;
} else if paddle.vel[1] < -PADDLE_MAX_SPEED {
paddle.vel[1] = -PADDLE_MAX_SPEED;
}
}
fn handle_ai_paddle(&self) -> (bool, bool) {
let mut ai_up = false;
let mut ai_down = false;
if self.ball.vel[0] > 0.0 {
let t = (self.p2.pos[0] - self.ball.pos[0]) / self.ball.vel[0];
let target_y = self.ball.pos[1] + self.ball.vel[1] * t;
if target_y > self.p2.pos[1] { ai_down = true; }
else if target_y < self.p2.pos[1] { ai_up = true; }
}
(ai_up, ai_down)
}
fn handle_ball(&mut self) {
for paddle in [&self.p1, &self.p2].iter() {
match self.ball.collision_normal(paddle) {
Some(normal) => {
let dot = self.ball.vel[0] * normal[0] +
self.ball.vel[1] * normal[1];
// reflect ball's velocity off collision normal
self.ball.vel = [
self.ball.vel[0] - 2.0 * normal[0] * dot,
self.ball.vel[1] - 2.0 * normal[1] * dot
];
// apply a bit of paddle y velocity to ball
if normal[0]!= 0.0 {
self.ball.vel[1] += paddle.vel[1] * PADDLE_FRICTION;
}
// increment ball x velocity a bit
self.ball.vel[0] += BALL_SPEED_INCREMENT *
self.ball.vel[0].signum();
Pong::correct_collision(&mut self.ball, paddle, normal);
}
None => {}
}
}
if self.ball.pos[0] > SIZE[0] as f64 { self.score(Player::Left); }
else if self.ball.pos[0] < 0.0 { self.score(Player::Right); }
}
fn correct_collision(a: &mut GameObject, b: &GameObject, normal: [f64; 2]) {
if normal == [1.0, 0.0] {
a.pos[0] = b.pos[0] + b.size[0] / 2.0 + a.size[0] / 2.0;
} else if normal == [-1.0, 0.0] {
a.pos[0] = b.pos[0] - b.size[0] / 2.0 - a.size[0] / 2.0;
} else if normal == [0.0, 1.0] {
a.pos[1] = b.pos[1] + b.size[1] / 2.0 + a.size[1] / 2.0;
} else if normal == [0.0, -1.0] {
a.pos[1] = b.pos[1] - b.size[1] / 2.0 - a.size[1] / 2.0;
}
}
fn score(&mut self, player: Player) {
match player {
Player::Left => {
self.server = Player::Right;
self.p1_score += 1;
println!("Player 1 scored! {}-{}", self.p1_score,
self.p2_score);
}
Player::Right => {
self.server = Player::Left;
self.p2_score += 1;
println!("Player 2 scored! {}-{}", self.p1_score,
self.p2_score);
}
}
self.reset();
}
}
pub fn play() {
let window = Window::new(OPENGL_VERSION,
WindowSettings::new("pong", SIZE)
.exit_on_esc(true));
let mut pong = Pong {
gl: GlGraphics::new(OPENGL_VERSION),
p1: GameObject { size: PADDLE_SIZE,..Default::default() },
p2: GameObject { size: PADDLE_SIZE,..Default::default() },
ball: GameObject { size: BALL_SIZE,..Default::default() },
up: false,
down: false,
server: Player::Left,
p1_score: 0,
p2_score: 0,
};
pong.start();
for e in window.events() {
if let Some(r) = e.render_args() { pong.render(&r); }
if let Some(u) = e.update_args() { pong.update(&u); }
if let Some(Keyboard(key)) = e.press_args() { pong.key_press(key); }
if let Some(Keyboard(key)) = e.release_args() { pong.key_release(key); }
}
}
|
random_line_split
|
|
pong.rs
|
use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [512, 512];
static PADDLE_SIZE: [f64; 2] = [8.0, 32.0];
static PADDLE_ACCEL: f64 = 4000.0;
static PADDLE_FRICTION: f64 = 0.5;
static PADDLE_MAX_SPEED: f64 = 400.0;
static BALL_SIZE: [f64; 2] = [8.0, 8.0];
static BALL_START_MAX_ANGLE: f64 = 60.0;
static BALL_START_SPEED: f64 = 200.0;
static BALL_SPEED_INCREMENT: f64 = 25.0;
struct Pong {
gl: GlGraphics,
p1: GameObject,
p2: GameObject,
ball: GameObject,
up: bool,
down: bool,
server: Player,
p1_score: u32,
p2_score: u32,
}
enum Player {
Left,
Right
}
impl Pong {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
let objs = [&self.p1, &self.p2, &self.ball];
self.gl.draw(args.viewport(), |c, gl| {
clear(BLACK, gl);
for obj in objs.iter() {
let rect = [0.0, 0.0, obj.size[0], obj.size[1]];
let transform = c.transform.trans(obj.pos[0], obj.pos[1])
.trans(-obj.size[0] / 2.0, -obj.size[1] / 2.0);
rectangle(WHITE, rect, transform, gl);
}
});
}
fn update(&mut self, args: &UpdateArgs) {
let (ai_up, ai_down) = self.handle_ai_paddle();
Pong::handle_paddle(&mut self.p1, self.up, self.down, args.dt);
Pong::handle_paddle(&mut self.p2, ai_up, ai_down, args.dt);
Pong::handle_game_object(&mut self.p1, args.dt, false);
Pong::handle_game_object(&mut self.p2, args.dt, false);
Pong::handle_game_object(&mut self.ball, args.dt, true);
self.handle_ball();
}
fn start(&mut self) {
self.p1.pos = [self.p1.size[0] / 2.0 + 4.0, (SIZE[1] / 2) as f64];
self.p2.pos = [SIZE[0] as f64 - self.p2.size[0] / 2.0 - 4.0,
(SIZE[1] / 2) as f64];
self.reset();
}
fn reset(&mut self) {
use std::f64::consts::PI;
use rand;
use rand::Rng;
self.ball.pos = [(SIZE[0] / 2) as f64, (SIZE[1] / 2) as f64];
let mut rng = rand::thread_rng();
let max_angle = 2.0 * BALL_START_MAX_ANGLE * PI / 180.0;
let angle = rng.next_f64() * max_angle - max_angle / 2.0;
self.ball.vel = [
angle.cos() * BALL_START_SPEED * self.serve_direction(),
angle.sin() * BALL_START_SPEED
];
}
fn serve_direction(&mut self) -> f64 {
match self.server {
Player::Left => { -1.0 }
Player::Right => { 1.0 }
}
}
fn key_press(&mut self, key: Key) {
match key {
Key::Up => { self.up = true; }
Key::Down => { self.down = true; }
_ => {}
}
}
fn key_release(&mut self, key: Key) {
match key {
Key::Up => { self.up = false; }
Key::Down => { self.down = false; }
_ => {}
}
}
fn handle_game_object(obj: &mut GameObject, dt: f64, bounce: bool) {
obj.pos[0] += obj.vel[0] * dt;
obj.pos[1] += obj.vel[1] * dt;
if obj.pos[1] + obj.size[1] / 2.0 >= SIZE[1] as f64 {
obj.pos[1] = SIZE[1] as f64 - obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
if obj.pos[1] - obj.size[1] / 2.0 <= 0.0f64 {
obj.pos[1] = obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
}
fn handle_paddle(paddle: &mut GameObject, up: bool, down: bool, dt: f64) {
if up {
paddle.vel[1] -= PADDLE_ACCEL * dt;
} else if down {
paddle.vel[1] += PADDLE_ACCEL * dt;
} else {
let dv = -paddle.vel[1].signum() * PADDLE_ACCEL * dt;
if dv.abs() >= paddle.vel[1].abs() { paddle.vel[1] = 0.0; }
else { paddle.vel[1] += dv; }
}
if paddle.vel[1] > PADDLE_MAX_SPEED {
paddle.vel[1] = PADDLE_MAX_SPEED;
} else if paddle.vel[1] < -PADDLE_MAX_SPEED {
paddle.vel[1] = -PADDLE_MAX_SPEED;
}
}
fn handle_ai_paddle(&self) -> (bool, bool) {
let mut ai_up = false;
let mut ai_down = false;
if self.ball.vel[0] > 0.0 {
let t = (self.p2.pos[0] - self.ball.pos[0]) / self.ball.vel[0];
let target_y = self.ball.pos[1] + self.ball.vel[1] * t;
if target_y > self.p2.pos[1] { ai_down = true; }
else if target_y < self.p2.pos[1] { ai_up = true; }
}
(ai_up, ai_down)
}
fn handle_ball(&mut self) {
for paddle in [&self.p1, &self.p2].iter() {
match self.ball.collision_normal(paddle) {
Some(normal) => {
let dot = self.ball.vel[0] * normal[0] +
self.ball.vel[1] * normal[1];
// reflect ball's velocity off collision normal
self.ball.vel = [
self.ball.vel[0] - 2.0 * normal[0] * dot,
self.ball.vel[1] - 2.0 * normal[1] * dot
];
// apply a bit of paddle y velocity to ball
if normal[0]!= 0.0 {
self.ball.vel[1] += paddle.vel[1] * PADDLE_FRICTION;
}
// increment ball x velocity a bit
self.ball.vel[0] += BALL_SPEED_INCREMENT *
self.ball.vel[0].signum();
Pong::correct_collision(&mut self.ball, paddle, normal);
}
None => {}
}
}
if self.ball.pos[0] > SIZE[0] as f64 { self.score(Player::Left); }
else if self.ball.pos[0] < 0.0 { self.score(Player::Right); }
}
fn correct_collision(a: &mut GameObject, b: &GameObject, normal: [f64; 2])
|
fn score(&mut self, player: Player) {
match player {
Player::Left => {
self.server = Player::Right;
self.p1_score += 1;
println!("Player 1 scored! {}-{}", self.p1_score,
self.p2_score);
}
Player::Right => {
self.server = Player::Left;
self.p2_score += 1;
println!("Player 2 scored! {}-{}", self.p1_score,
self.p2_score);
}
}
self.reset();
}
}
pub fn play() {
let window = Window::new(OPENGL_VERSION,
WindowSettings::new("pong", SIZE)
.exit_on_esc(true));
let mut pong = Pong {
gl: GlGraphics::new(OPENGL_VERSION),
p1: GameObject { size: PADDLE_SIZE,..Default::default() },
p2: GameObject { size: PADDLE_SIZE,..Default::default() },
ball: GameObject { size: BALL_SIZE,..Default::default() },
up: false,
down: false,
server: Player::Left,
p1_score: 0,
p2_score: 0,
};
pong.start();
for e in window.events() {
if let Some(r) = e.render_args() { pong.render(&r); }
if let Some(u) = e.update_args() { pong.update(&u); }
if let Some(Keyboard(key)) = e.press_args() { pong.key_press(key); }
if let Some(Keyboard(key)) = e.release_args() { pong.key_release(key); }
}
}
|
{
if normal == [1.0, 0.0] {
a.pos[0] = b.pos[0] + b.size[0] / 2.0 + a.size[0] / 2.0;
} else if normal == [-1.0, 0.0] {
a.pos[0] = b.pos[0] - b.size[0] / 2.0 - a.size[0] / 2.0;
} else if normal == [0.0, 1.0] {
a.pos[1] = b.pos[1] + b.size[1] / 2.0 + a.size[1] / 2.0;
} else if normal == [0.0, -1.0] {
a.pos[1] = b.pos[1] - b.size[1] / 2.0 - a.size[1] / 2.0;
}
}
|
identifier_body
|
pong.rs
|
use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [512, 512];
static PADDLE_SIZE: [f64; 2] = [8.0, 32.0];
static PADDLE_ACCEL: f64 = 4000.0;
static PADDLE_FRICTION: f64 = 0.5;
static PADDLE_MAX_SPEED: f64 = 400.0;
static BALL_SIZE: [f64; 2] = [8.0, 8.0];
static BALL_START_MAX_ANGLE: f64 = 60.0;
static BALL_START_SPEED: f64 = 200.0;
static BALL_SPEED_INCREMENT: f64 = 25.0;
struct Pong {
gl: GlGraphics,
p1: GameObject,
p2: GameObject,
ball: GameObject,
up: bool,
down: bool,
server: Player,
p1_score: u32,
p2_score: u32,
}
enum Player {
Left,
Right
}
impl Pong {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
let objs = [&self.p1, &self.p2, &self.ball];
self.gl.draw(args.viewport(), |c, gl| {
clear(BLACK, gl);
for obj in objs.iter() {
let rect = [0.0, 0.0, obj.size[0], obj.size[1]];
let transform = c.transform.trans(obj.pos[0], obj.pos[1])
.trans(-obj.size[0] / 2.0, -obj.size[1] / 2.0);
rectangle(WHITE, rect, transform, gl);
}
});
}
fn update(&mut self, args: &UpdateArgs) {
let (ai_up, ai_down) = self.handle_ai_paddle();
Pong::handle_paddle(&mut self.p1, self.up, self.down, args.dt);
Pong::handle_paddle(&mut self.p2, ai_up, ai_down, args.dt);
Pong::handle_game_object(&mut self.p1, args.dt, false);
Pong::handle_game_object(&mut self.p2, args.dt, false);
Pong::handle_game_object(&mut self.ball, args.dt, true);
self.handle_ball();
}
fn start(&mut self) {
self.p1.pos = [self.p1.size[0] / 2.0 + 4.0, (SIZE[1] / 2) as f64];
self.p2.pos = [SIZE[0] as f64 - self.p2.size[0] / 2.0 - 4.0,
(SIZE[1] / 2) as f64];
self.reset();
}
fn reset(&mut self) {
use std::f64::consts::PI;
use rand;
use rand::Rng;
self.ball.pos = [(SIZE[0] / 2) as f64, (SIZE[1] / 2) as f64];
let mut rng = rand::thread_rng();
let max_angle = 2.0 * BALL_START_MAX_ANGLE * PI / 180.0;
let angle = rng.next_f64() * max_angle - max_angle / 2.0;
self.ball.vel = [
angle.cos() * BALL_START_SPEED * self.serve_direction(),
angle.sin() * BALL_START_SPEED
];
}
fn serve_direction(&mut self) -> f64 {
match self.server {
Player::Left => { -1.0 }
Player::Right => { 1.0 }
}
}
fn key_press(&mut self, key: Key) {
match key {
Key::Up => { self.up = true; }
Key::Down => { self.down = true; }
_ => {}
}
}
fn key_release(&mut self, key: Key) {
match key {
Key::Up => { self.up = false; }
Key::Down => { self.down = false; }
_ => {}
}
}
fn handle_game_object(obj: &mut GameObject, dt: f64, bounce: bool) {
obj.pos[0] += obj.vel[0] * dt;
obj.pos[1] += obj.vel[1] * dt;
if obj.pos[1] + obj.size[1] / 2.0 >= SIZE[1] as f64 {
obj.pos[1] = SIZE[1] as f64 - obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
if obj.pos[1] - obj.size[1] / 2.0 <= 0.0f64 {
obj.pos[1] = obj.size[1] / 2.0;
if bounce { obj.vel[1] *= -1.0; }
else { obj.vel[1] = 0.0; }
}
}
fn handle_paddle(paddle: &mut GameObject, up: bool, down: bool, dt: f64) {
if up {
paddle.vel[1] -= PADDLE_ACCEL * dt;
} else if down {
paddle.vel[1] += PADDLE_ACCEL * dt;
} else {
let dv = -paddle.vel[1].signum() * PADDLE_ACCEL * dt;
if dv.abs() >= paddle.vel[1].abs() { paddle.vel[1] = 0.0; }
else { paddle.vel[1] += dv; }
}
if paddle.vel[1] > PADDLE_MAX_SPEED {
paddle.vel[1] = PADDLE_MAX_SPEED;
} else if paddle.vel[1] < -PADDLE_MAX_SPEED {
paddle.vel[1] = -PADDLE_MAX_SPEED;
}
}
fn handle_ai_paddle(&self) -> (bool, bool) {
let mut ai_up = false;
let mut ai_down = false;
if self.ball.vel[0] > 0.0 {
let t = (self.p2.pos[0] - self.ball.pos[0]) / self.ball.vel[0];
let target_y = self.ball.pos[1] + self.ball.vel[1] * t;
if target_y > self.p2.pos[1] { ai_down = true; }
else if target_y < self.p2.pos[1] { ai_up = true; }
}
(ai_up, ai_down)
}
fn handle_ball(&mut self) {
for paddle in [&self.p1, &self.p2].iter() {
match self.ball.collision_normal(paddle) {
Some(normal) => {
let dot = self.ball.vel[0] * normal[0] +
self.ball.vel[1] * normal[1];
// reflect ball's velocity off collision normal
self.ball.vel = [
self.ball.vel[0] - 2.0 * normal[0] * dot,
self.ball.vel[1] - 2.0 * normal[1] * dot
];
// apply a bit of paddle y velocity to ball
if normal[0]!= 0.0 {
self.ball.vel[1] += paddle.vel[1] * PADDLE_FRICTION;
}
// increment ball x velocity a bit
self.ball.vel[0] += BALL_SPEED_INCREMENT *
self.ball.vel[0].signum();
Pong::correct_collision(&mut self.ball, paddle, normal);
}
None => {}
}
}
if self.ball.pos[0] > SIZE[0] as f64 { self.score(Player::Left); }
else if self.ball.pos[0] < 0.0 { self.score(Player::Right); }
}
fn correct_collision(a: &mut GameObject, b: &GameObject, normal: [f64; 2]) {
if normal == [1.0, 0.0] {
a.pos[0] = b.pos[0] + b.size[0] / 2.0 + a.size[0] / 2.0;
} else if normal == [-1.0, 0.0] {
a.pos[0] = b.pos[0] - b.size[0] / 2.0 - a.size[0] / 2.0;
} else if normal == [0.0, 1.0] {
a.pos[1] = b.pos[1] + b.size[1] / 2.0 + a.size[1] / 2.0;
} else if normal == [0.0, -1.0] {
a.pos[1] = b.pos[1] - b.size[1] / 2.0 - a.size[1] / 2.0;
}
}
fn score(&mut self, player: Player) {
match player {
Player::Left => {
self.server = Player::Right;
self.p1_score += 1;
println!("Player 1 scored! {}-{}", self.p1_score,
self.p2_score);
}
Player::Right => {
self.server = Player::Left;
self.p2_score += 1;
println!("Player 2 scored! {}-{}", self.p1_score,
self.p2_score);
}
}
self.reset();
}
}
pub fn play() {
let window = Window::new(OPENGL_VERSION,
WindowSettings::new("pong", SIZE)
.exit_on_esc(true));
let mut pong = Pong {
gl: GlGraphics::new(OPENGL_VERSION),
p1: GameObject { size: PADDLE_SIZE,..Default::default() },
p2: GameObject { size: PADDLE_SIZE,..Default::default() },
ball: GameObject { size: BALL_SIZE,..Default::default() },
up: false,
down: false,
server: Player::Left,
p1_score: 0,
p2_score: 0,
};
pong.start();
for e in window.events() {
if let Some(r) = e.render_args() { pong.render(&r); }
if let Some(u) = e.update_args() { pong.update(&u); }
if let Some(Keyboard(key)) = e.press_args() { pong.key_press(key); }
if let Some(Keyboard(key)) = e.release_args()
|
}
}
|
{ pong.key_release(key); }
|
conditional_block
|
display_list_builder.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/. */
//! Constructs display lists from render boxes.
use layout::box::RenderBox;
use layout::context::LayoutContext;
use std::cast::transmute;
use script::dom::node::AbstractNode;
use gfx;
use newcss;
/// Display list data is usually an AbstractNode with view () to indicate
/// that nodes in this view shoud not really be touched. The idea is to
/// store the nodes in the display list and have layout transmute them.
pub trait ExtraDisplayListData {
fn new(box: RenderBox) -> Self;
}
pub type Nothing = ();
impl ExtraDisplayListData for AbstractNode<()> {
fn
|
(box: RenderBox) -> AbstractNode<()> {
unsafe {
transmute(box.node())
}
}
}
impl ExtraDisplayListData for Nothing {
fn new(_: RenderBox) -> Nothing {
()
}
}
impl ExtraDisplayListData for RenderBox {
fn new(box: RenderBox) -> RenderBox {
box
}
}
/// A builder object that manages display list builder should mainly hold information about the
/// initial request and desired result--for example, whether the `DisplayList` is to be used for
/// painting or hit testing. This can affect which boxes are created.
///
/// Right now, the builder isn't used for much, but it establishes the pattern we'll need once we
/// support display-list-based hit testing and so forth.
pub struct DisplayListBuilder<'self> {
ctx: &'self LayoutContext,
}
//
// Miscellaneous useful routines
//
/// Allows a CSS color to be converted into a graphics color.
pub trait ToGfxColor {
/// Converts a CSS color to a graphics color.
fn to_gfx_color(&self) -> gfx::color::Color;
}
impl ToGfxColor for newcss::color::Color {
fn to_gfx_color(&self) -> gfx::color::Color {
gfx::color::rgba(self.red, self.green, self.blue, self.alpha)
}
}
|
new
|
identifier_name
|
display_list_builder.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/. */
//! Constructs display lists from render boxes.
use layout::box::RenderBox;
use layout::context::LayoutContext;
use std::cast::transmute;
use script::dom::node::AbstractNode;
use gfx;
use newcss;
/// Display list data is usually an AbstractNode with view () to indicate
/// that nodes in this view shoud not really be touched. The idea is to
|
pub type Nothing = ();
impl ExtraDisplayListData for AbstractNode<()> {
fn new (box: RenderBox) -> AbstractNode<()> {
unsafe {
transmute(box.node())
}
}
}
impl ExtraDisplayListData for Nothing {
fn new(_: RenderBox) -> Nothing {
()
}
}
impl ExtraDisplayListData for RenderBox {
fn new(box: RenderBox) -> RenderBox {
box
}
}
/// A builder object that manages display list builder should mainly hold information about the
/// initial request and desired result--for example, whether the `DisplayList` is to be used for
/// painting or hit testing. This can affect which boxes are created.
///
/// Right now, the builder isn't used for much, but it establishes the pattern we'll need once we
/// support display-list-based hit testing and so forth.
pub struct DisplayListBuilder<'self> {
ctx: &'self LayoutContext,
}
//
// Miscellaneous useful routines
//
/// Allows a CSS color to be converted into a graphics color.
pub trait ToGfxColor {
/// Converts a CSS color to a graphics color.
fn to_gfx_color(&self) -> gfx::color::Color;
}
impl ToGfxColor for newcss::color::Color {
fn to_gfx_color(&self) -> gfx::color::Color {
gfx::color::rgba(self.red, self.green, self.blue, self.alpha)
}
}
|
/// store the nodes in the display list and have layout transmute them.
pub trait ExtraDisplayListData {
fn new(box: RenderBox) -> Self;
}
|
random_line_split
|
randomx_hash.rs
|
extern crate mithril;
|
#[allow(overflowing_literals)]
fn test_gen_program_aes_1rx4() {
//nonce 1000 randomx-codegen
let input0 = m128i::from_i32(0x31903876, 0xbb7a2914, 0xb370f616, 0xd6f7e4f3);
let input1 = m128i::from_i32(0xb5a8ef67, 0x749809c8, 0xf349884a, 0x05c9f5ef);
let input2 = m128i::from_i32(0xa9a93ab0, 0x22e46d0a, 0x1a1fe305, 0xb42708c0);
let input3 = m128i::from_i32(0x68247034, 0xed99ee84, 0x438f563a, 0x138612ff);
let input: [m128i; 4] = [input0, input1, input2, input3];
let (result, new_seed) = gen_program_aes_1rx4(&input, 136);
assert_eq!(result.len(), 136);
assert_eq!(
result[0],
m128i::from_i32(0x27117584, 0x121aeeb3, 0x2f620901, 0xf788e553)
);
assert_eq!(
result[1],
m128i::from_i32(0x7b1951c7, 0x2ca4ef19, 0xf09f9310, 0x248ffc66)
);
assert_eq!(
result[9],
m128i::from_i32(0xf31272c9, 0x187f3e37, 0x9ed29677, 0x9cb3cad8)
);
assert_eq!(
result[29],
m128i::from_i32(0xb979c03b, 0xf3851cd4, 0x8053d5c4, 0xf167e714)
);
assert_eq!(
result[59],
m128i::from_i32(0x9edf9671, 0x351efb59, 0x3cd79767, 0x15624b91)
);
assert_eq!(
result[79],
m128i::from_i32(0x36881166, 0xf619e667, 0xf728102c, 0x103e2d56)
);
assert_eq!(
result[99],
m128i::from_i32(0xdda1adbf, 0xec39dc8a, 0x89884695, 0xc61ff1dd)
);
assert_eq!(
result[135],
m128i::from_i32(0x778d555d, 0x82dfe800, 0xedbe8cae, 0x2fe08b9f)
);
assert_eq!(
new_seed[0].as_i64(),
(0xbc020491ce094c80, 0x3eb2be0994e80b6a)
);
assert_eq!(
new_seed[1].as_i64(),
(0xb5ef741cae93a328, 0x2b0e778ebd40eb43)
);
assert_eq!(
new_seed[2].as_i64(),
(0xd375785cc9d9bb9a, 0x75725136c964ad02)
);
assert_eq!(
new_seed[3].as_i64(),
(0x778d555d82dfe800, 0xedbe8cae2fe08b9f)
);
}
#[test]
#[allow(overflowing_literals)]
fn test_gen_program_aes_4rx4() {
let input0 = m128i::from_i32(0xb53a90c9, 0xf56f1bc9, 0x25a4424b, 0x727ab1b2);
let input1 = m128i::from_i32(0x70152fd1, 0x377f234d, 0xe8027504, 0xfed70bc4);
let input2 = m128i::from_i32(0xae1f977a, 0x841fdb02, 0x85b20930, 0xf22cf15b);
let input3 = m128i::from_i32(0x2fd5f11, 0x28e94c44, 0x8a756cec, 0x33c0d189);
let input: [m128i; 4] = [input0, input1, input2, input3];
let result = gen_program_aes_4rx4(&input, 136);
assert_eq!(result.len(), 136);
assert_eq!(
result[0],
m128i::from_i32(0xf76214a7, 0xcbe6ca8a, 0x71e1f016, 0x44ba2d2d)
);
assert_eq!(
result[1],
m128i::from_i32(0x3c19a6ae, 0x6201dd3a, 0x22dfa1c7, 0x977f13a5)
);
assert_eq!(
result[9],
m128i::from_i32(0xbdf2934c, 0x381a2d03, 0xae553192, 0xb0e5bb9f)
);
assert_eq!(
result[29],
m128i::from_i32(0xcafa93b4, 0xad33c065, 0x980587f5, 0xd1ae0a40)
);
assert_eq!(
result[59],
m128i::from_i32(0x7dc0a58a, 0x77d4f8dc, 0x4eaecb7d, 0x3d052cb5)
);
assert_eq!(
result[79],
m128i::from_i32(0x525b195b, 0x2f51cfca, 0xd948a805, 0xfe9eed66)
);
assert_eq!(
result[99],
m128i::from_i32(0x4ab9f16b, 0xbd648e91, 0xda7d9069, 0x1d9f6716)
);
assert_eq!(
result[135],
m128i::from_i32(0x3f7fdb2f, 0x565cd0c7, 0xbe72f8e3, 0x5da409a1)
);
}
|
use mithril::randomx::hash::{gen_program_aes_1rx4, gen_program_aes_4rx4};
use mithril::randomx::m128::m128i;
#[test]
|
random_line_split
|
randomx_hash.rs
|
extern crate mithril;
use mithril::randomx::hash::{gen_program_aes_1rx4, gen_program_aes_4rx4};
use mithril::randomx::m128::m128i;
#[test]
#[allow(overflowing_literals)]
fn test_gen_program_aes_1rx4() {
//nonce 1000 randomx-codegen
let input0 = m128i::from_i32(0x31903876, 0xbb7a2914, 0xb370f616, 0xd6f7e4f3);
let input1 = m128i::from_i32(0xb5a8ef67, 0x749809c8, 0xf349884a, 0x05c9f5ef);
let input2 = m128i::from_i32(0xa9a93ab0, 0x22e46d0a, 0x1a1fe305, 0xb42708c0);
let input3 = m128i::from_i32(0x68247034, 0xed99ee84, 0x438f563a, 0x138612ff);
let input: [m128i; 4] = [input0, input1, input2, input3];
let (result, new_seed) = gen_program_aes_1rx4(&input, 136);
assert_eq!(result.len(), 136);
assert_eq!(
result[0],
m128i::from_i32(0x27117584, 0x121aeeb3, 0x2f620901, 0xf788e553)
);
assert_eq!(
result[1],
m128i::from_i32(0x7b1951c7, 0x2ca4ef19, 0xf09f9310, 0x248ffc66)
);
assert_eq!(
result[9],
m128i::from_i32(0xf31272c9, 0x187f3e37, 0x9ed29677, 0x9cb3cad8)
);
assert_eq!(
result[29],
m128i::from_i32(0xb979c03b, 0xf3851cd4, 0x8053d5c4, 0xf167e714)
);
assert_eq!(
result[59],
m128i::from_i32(0x9edf9671, 0x351efb59, 0x3cd79767, 0x15624b91)
);
assert_eq!(
result[79],
m128i::from_i32(0x36881166, 0xf619e667, 0xf728102c, 0x103e2d56)
);
assert_eq!(
result[99],
m128i::from_i32(0xdda1adbf, 0xec39dc8a, 0x89884695, 0xc61ff1dd)
);
assert_eq!(
result[135],
m128i::from_i32(0x778d555d, 0x82dfe800, 0xedbe8cae, 0x2fe08b9f)
);
assert_eq!(
new_seed[0].as_i64(),
(0xbc020491ce094c80, 0x3eb2be0994e80b6a)
);
assert_eq!(
new_seed[1].as_i64(),
(0xb5ef741cae93a328, 0x2b0e778ebd40eb43)
);
assert_eq!(
new_seed[2].as_i64(),
(0xd375785cc9d9bb9a, 0x75725136c964ad02)
);
assert_eq!(
new_seed[3].as_i64(),
(0x778d555d82dfe800, 0xedbe8cae2fe08b9f)
);
}
#[test]
#[allow(overflowing_literals)]
fn
|
() {
let input0 = m128i::from_i32(0xb53a90c9, 0xf56f1bc9, 0x25a4424b, 0x727ab1b2);
let input1 = m128i::from_i32(0x70152fd1, 0x377f234d, 0xe8027504, 0xfed70bc4);
let input2 = m128i::from_i32(0xae1f977a, 0x841fdb02, 0x85b20930, 0xf22cf15b);
let input3 = m128i::from_i32(0x2fd5f11, 0x28e94c44, 0x8a756cec, 0x33c0d189);
let input: [m128i; 4] = [input0, input1, input2, input3];
let result = gen_program_aes_4rx4(&input, 136);
assert_eq!(result.len(), 136);
assert_eq!(
result[0],
m128i::from_i32(0xf76214a7, 0xcbe6ca8a, 0x71e1f016, 0x44ba2d2d)
);
assert_eq!(
result[1],
m128i::from_i32(0x3c19a6ae, 0x6201dd3a, 0x22dfa1c7, 0x977f13a5)
);
assert_eq!(
result[9],
m128i::from_i32(0xbdf2934c, 0x381a2d03, 0xae553192, 0xb0e5bb9f)
);
assert_eq!(
result[29],
m128i::from_i32(0xcafa93b4, 0xad33c065, 0x980587f5, 0xd1ae0a40)
);
assert_eq!(
result[59],
m128i::from_i32(0x7dc0a58a, 0x77d4f8dc, 0x4eaecb7d, 0x3d052cb5)
);
assert_eq!(
result[79],
m128i::from_i32(0x525b195b, 0x2f51cfca, 0xd948a805, 0xfe9eed66)
);
assert_eq!(
result[99],
m128i::from_i32(0x4ab9f16b, 0xbd648e91, 0xda7d9069, 0x1d9f6716)
);
assert_eq!(
result[135],
m128i::from_i32(0x3f7fdb2f, 0x565cd0c7, 0xbe72f8e3, 0x5da409a1)
);
}
|
test_gen_program_aes_4rx4
|
identifier_name
|
randomx_hash.rs
|
extern crate mithril;
use mithril::randomx::hash::{gen_program_aes_1rx4, gen_program_aes_4rx4};
use mithril::randomx::m128::m128i;
#[test]
#[allow(overflowing_literals)]
fn test_gen_program_aes_1rx4()
|
m128i::from_i32(0xf31272c9, 0x187f3e37, 0x9ed29677, 0x9cb3cad8)
);
assert_eq!(
result[29],
m128i::from_i32(0xb979c03b, 0xf3851cd4, 0x8053d5c4, 0xf167e714)
);
assert_eq!(
result[59],
m128i::from_i32(0x9edf9671, 0x351efb59, 0x3cd79767, 0x15624b91)
);
assert_eq!(
result[79],
m128i::from_i32(0x36881166, 0xf619e667, 0xf728102c, 0x103e2d56)
);
assert_eq!(
result[99],
m128i::from_i32(0xdda1adbf, 0xec39dc8a, 0x89884695, 0xc61ff1dd)
);
assert_eq!(
result[135],
m128i::from_i32(0x778d555d, 0x82dfe800, 0xedbe8cae, 0x2fe08b9f)
);
assert_eq!(
new_seed[0].as_i64(),
(0xbc020491ce094c80, 0x3eb2be0994e80b6a)
);
assert_eq!(
new_seed[1].as_i64(),
(0xb5ef741cae93a328, 0x2b0e778ebd40eb43)
);
assert_eq!(
new_seed[2].as_i64(),
(0xd375785cc9d9bb9a, 0x75725136c964ad02)
);
assert_eq!(
new_seed[3].as_i64(),
(0x778d555d82dfe800, 0xedbe8cae2fe08b9f)
);
}
#[test]
#[allow(overflowing_literals)]
fn test_gen_program_aes_4rx4() {
let input0 = m128i::from_i32(0xb53a90c9, 0xf56f1bc9, 0x25a4424b, 0x727ab1b2);
let input1 = m128i::from_i32(0x70152fd1, 0x377f234d, 0xe8027504, 0xfed70bc4);
let input2 = m128i::from_i32(0xae1f977a, 0x841fdb02, 0x85b20930, 0xf22cf15b);
let input3 = m128i::from_i32(0x2fd5f11, 0x28e94c44, 0x8a756cec, 0x33c0d189);
let input: [m128i; 4] = [input0, input1, input2, input3];
let result = gen_program_aes_4rx4(&input, 136);
assert_eq!(result.len(), 136);
assert_eq!(
result[0],
m128i::from_i32(0xf76214a7, 0xcbe6ca8a, 0x71e1f016, 0x44ba2d2d)
);
assert_eq!(
result[1],
m128i::from_i32(0x3c19a6ae, 0x6201dd3a, 0x22dfa1c7, 0x977f13a5)
);
assert_eq!(
result[9],
m128i::from_i32(0xbdf2934c, 0x381a2d03, 0xae553192, 0xb0e5bb9f)
);
assert_eq!(
result[29],
m128i::from_i32(0xcafa93b4, 0xad33c065, 0x980587f5, 0xd1ae0a40)
);
assert_eq!(
result[59],
m128i::from_i32(0x7dc0a58a, 0x77d4f8dc, 0x4eaecb7d, 0x3d052cb5)
);
assert_eq!(
result[79],
m128i::from_i32(0x525b195b, 0x2f51cfca, 0xd948a805, 0xfe9eed66)
);
assert_eq!(
result[99],
m128i::from_i32(0x4ab9f16b, 0xbd648e91, 0xda7d9069, 0x1d9f6716)
);
assert_eq!(
result[135],
m128i::from_i32(0x3f7fdb2f, 0x565cd0c7, 0xbe72f8e3, 0x5da409a1)
);
}
|
{
//nonce 1000 randomx-codegen
let input0 = m128i::from_i32(0x31903876, 0xbb7a2914, 0xb370f616, 0xd6f7e4f3);
let input1 = m128i::from_i32(0xb5a8ef67, 0x749809c8, 0xf349884a, 0x05c9f5ef);
let input2 = m128i::from_i32(0xa9a93ab0, 0x22e46d0a, 0x1a1fe305, 0xb42708c0);
let input3 = m128i::from_i32(0x68247034, 0xed99ee84, 0x438f563a, 0x138612ff);
let input: [m128i; 4] = [input0, input1, input2, input3];
let (result, new_seed) = gen_program_aes_1rx4(&input, 136);
assert_eq!(result.len(), 136);
assert_eq!(
result[0],
m128i::from_i32(0x27117584, 0x121aeeb3, 0x2f620901, 0xf788e553)
);
assert_eq!(
result[1],
m128i::from_i32(0x7b1951c7, 0x2ca4ef19, 0xf09f9310, 0x248ffc66)
);
assert_eq!(
result[9],
|
identifier_body
|
time.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.
use libc;
use ops::Sub;
use time::Duration;
use sync::Once;
const NANOS_PER_SEC: u64 = 1_000_000_000;
pub struct SteadyTime {
t: libc::LARGE_INTEGER,
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime { t: 0 };
unsafe { libc::QueryPerformanceCounter(&mut t.t); }
t
}
}
fn frequency() -> libc::LARGE_INTEGER {
static mut FREQUENCY: libc::LARGE_INTEGER = 0;
static ONCE: Once = Once::new();
unsafe {
ONCE.call_once(|| {
libc::QueryPerformanceFrequency(&mut FREQUENCY);
});
FREQUENCY
}
|
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let diff = self.t as u64 - other.t as u64;
let nanos = mul_div_u64(diff, NANOS_PER_SEC, frequency() as u64);
Duration::new(nanos / NANOS_PER_SEC, (nanos % NANOS_PER_SEC) as u32)
}
}
// Computes (value*numer)/denom without overflow, as long as both
// (numer*denom) and the overall result fit into i64 (which is the case
// for our time conversions).
fn mul_div_u64(value: u64, numer: u64, denom: u64) -> u64 {
let q = value / denom;
let r = value % denom;
// Decompose value as (value/denom*denom + value%denom),
// substitute into (value*numer)/denom and simplify.
// r < denom, so (denom*numer) is the upper bound of (r*numer)
q * numer + r * numer / denom
}
#[test]
fn test_muldiv() {
assert_eq!(mul_div_u64( 1_000_000_000_001, 1_000_000_000, 1_000_000),
1_000_000_000_001_000);
}
|
}
impl<'a> Sub for &'a SteadyTime {
|
random_line_split
|
time.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.
use libc;
use ops::Sub;
use time::Duration;
use sync::Once;
const NANOS_PER_SEC: u64 = 1_000_000_000;
pub struct
|
{
t: libc::LARGE_INTEGER,
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime { t: 0 };
unsafe { libc::QueryPerformanceCounter(&mut t.t); }
t
}
}
fn frequency() -> libc::LARGE_INTEGER {
static mut FREQUENCY: libc::LARGE_INTEGER = 0;
static ONCE: Once = Once::new();
unsafe {
ONCE.call_once(|| {
libc::QueryPerformanceFrequency(&mut FREQUENCY);
});
FREQUENCY
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let diff = self.t as u64 - other.t as u64;
let nanos = mul_div_u64(diff, NANOS_PER_SEC, frequency() as u64);
Duration::new(nanos / NANOS_PER_SEC, (nanos % NANOS_PER_SEC) as u32)
}
}
// Computes (value*numer)/denom without overflow, as long as both
// (numer*denom) and the overall result fit into i64 (which is the case
// for our time conversions).
fn mul_div_u64(value: u64, numer: u64, denom: u64) -> u64 {
let q = value / denom;
let r = value % denom;
// Decompose value as (value/denom*denom + value%denom),
// substitute into (value*numer)/denom and simplify.
// r < denom, so (denom*numer) is the upper bound of (r*numer)
q * numer + r * numer / denom
}
#[test]
fn test_muldiv() {
assert_eq!(mul_div_u64( 1_000_000_000_001, 1_000_000_000, 1_000_000),
1_000_000_000_001_000);
}
|
SteadyTime
|
identifier_name
|
time.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.
use libc;
use ops::Sub;
use time::Duration;
use sync::Once;
const NANOS_PER_SEC: u64 = 1_000_000_000;
pub struct SteadyTime {
t: libc::LARGE_INTEGER,
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime { t: 0 };
unsafe { libc::QueryPerformanceCounter(&mut t.t); }
t
}
}
fn frequency() -> libc::LARGE_INTEGER
|
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let diff = self.t as u64 - other.t as u64;
let nanos = mul_div_u64(diff, NANOS_PER_SEC, frequency() as u64);
Duration::new(nanos / NANOS_PER_SEC, (nanos % NANOS_PER_SEC) as u32)
}
}
// Computes (value*numer)/denom without overflow, as long as both
// (numer*denom) and the overall result fit into i64 (which is the case
// for our time conversions).
fn mul_div_u64(value: u64, numer: u64, denom: u64) -> u64 {
let q = value / denom;
let r = value % denom;
// Decompose value as (value/denom*denom + value%denom),
// substitute into (value*numer)/denom and simplify.
// r < denom, so (denom*numer) is the upper bound of (r*numer)
q * numer + r * numer / denom
}
#[test]
fn test_muldiv() {
assert_eq!(mul_div_u64( 1_000_000_000_001, 1_000_000_000, 1_000_000),
1_000_000_000_001_000);
}
|
{
static mut FREQUENCY: libc::LARGE_INTEGER = 0;
static ONCE: Once = Once::new();
unsafe {
ONCE.call_once(|| {
libc::QueryPerformanceFrequency(&mut FREQUENCY);
});
FREQUENCY
}
}
|
identifier_body
|
settings_ui.rs
|
extern crate objc;
use super::consts::*;
use super::cocoa_util::*;
use pref::*;
use core_graphics::*;
use tickeys::Tickeys;
use std::sync::{ONCE_INIT, Once};
use objc::runtime::*;
use cocoa::base::{class,id,nil};
use cocoa::foundation::NSString;
use cocoa::appkit::NSApp;
// naive way of make this a singleton
static mut SHOWING_GUI:bool = false;
#[allow(non_snake_case)]
#[allow(unused_variables)]
pub trait SettingsController //<NSWindowDelegate, NSTableViewDelegate, NSTableViewDataSource>
{
fn get_instance(_: Self, ptr_to_app: *mut Tickeys) -> id
{
Self::__register_objc_class_once();
unsafe
{
if SHOWING_GUI { return nil };
let nib_name = NSString::alloc(nil).init_str("Settings");
let inst: id = msg_send![class(stringify!(SettingsController)), alloc];
let inst: id = msg_send![inst, initWithWindowNibName: nib_name];
inst.retain();
let _:id = msg_send![inst, setUser_data: ptr_to_app];
let _: id = msg_send![inst, showWindow: nil];
SHOWING_GUI = true;
inst
}
}
fn __register_objc_class_once()
{
static REGISTER_APPDELEGATE: Once = ONCE_INIT;
REGISTER_APPDELEGATE.call_once(||
{
println!("SettingsController::__register_objc_class_once");
let superCls = objc::runtime::Class::get("NSWindowController").unwrap();
let mut decl = objc::declare::ClassDecl::new(superCls, stringify!(SettingsController)).unwrap();
decl_prop!(decl, usize, user_data);
decl_prop!(decl, id, popup_audio_scheme);
decl_prop!(decl, id, slide_volume);
decl_prop!(decl, id, slide_pitch);
decl_prop!(decl, id, label_version);
decl_prop!(decl, id, filterListTable);
unsafe
{
//methods
decl.add_method(sel!(quit:), Self::quit_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(value_changed:), Self::value_changed_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(follow_link:), Self::follow_link_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(windowWillClose:), Self::windowWillClose as extern fn(&Object, Sel, id));
decl.add_method(sel!(windowDidLoad), Self::windowDidLoad as extern fn(&mut Object, Sel));
decl.add_method(sel!(tableView:shouldEditTableColumn:row:), Self::tableViewShouldEditTableColumnRow as extern fn(&mut Object, Sel, id, id, i32) -> bool);
decl.add_method(sel!(btnAddClicked:), Self::btnAddClicked as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(btnRemoveClicked:), Self::btnRemoveClicked as extern fn(&mut Object, Sel, id));
//tableViewSource & tableViewDelegate
decl.add_method(sel!(numberOfRowsInTableView:), Self::numberOfRowsInTableView as extern fn(&mut Object, Sel, id)->i32);
decl.add_method(sel!(tableView:objectValueForTableColumn:row:), Self::tableViewObjectValueForTableColumn as extern fn(&mut Object, Sel, id, id, i32)->id);
}
decl.register();
});
}
extern fn windowDidLoad(this: &mut Object, _cmd: Sel)
{
println!("windowDidLoad");
unsafe
{
let window: id = msg_send![this, window];
//hide window btns
let btnMin: id = msg_send![window, standardWindowButton:1];
let _: id = msg_send![btnMin, setHidden: true];
let btnZoom: id = msg_send![window, standardWindowButton:2];
let _: id = msg_send![btnZoom, setHidden: true];
let _: id = msg_send![window, setLevel: CGWindowLevelForKey(CGWindowLevelKey::kCGFloatingWindowLevelKey)];
Self::load_values(this);
}
}
extern fn quit_(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Quit");
app_terminate();
}
extern fn follow_link_(this: &mut Object, _cmd: Sel, sender: id)
{
unsafe
{
let tag:i64 = msg_send![sender, tag];
let url = match tag
{
0 => WEBSITE,
1 => DONATE_URL,
_ => panic!("SettingsController::follow_link_")
};
let workspace: id = msg_send![class("NSWorkspace"), sharedWorkspace];
let url:id = msg_send![class("NSURL"),
URLWithString: NSString::alloc(nil).init_str(url)];
msg_send![workspace, openURL: url]
}
}
extern fn value_changed_(this: &mut Object, _cmd:Sel, sender: id)
{
println!("SettingsController::value_changed_");
const TAG_POPUP_SCHEME: i64 = 0;
const TAG_SLIDE_VOLUME: i64 = 1;
const TAG_SLIDE_PITCH: i64 = 2;
unsafe
{
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let tickeys_ptr:&mut Tickeys = msg_send![this, user_data];
let tag:i64 = msg_send![sender, tag];
match tag
{
TAG_POPUP_SCHEME =>
{
let value:i32 = msg_send![sender, indexOfSelectedItem];
let sch;// = &schemes[value as usize];
{
let schemes = tickeys_ptr.get_schemes();//= load_audio_schemes();
sch = schemes[value as usize].name.clone();
}
let scheme_dir = "data/".to_string() + &sch;//.to_string();
//scheme_dir.push_str(&sch.name);
tickeys_ptr.load_scheme(&get_res_path(&scheme_dir), &sch);
let _:id = msg_send![user_defaults,
setObject: NSString::alloc(nil).init_str(sch.as_ref())
forKey: NSString::alloc(nil).init_str("audio_scheme")];
},
TAG_SLIDE_VOLUME =>
{
let value:f32 = msg_send![sender, floatValue];
tickeys_ptr.set_volume(value);
let _:id = msg_send![user_defaults, setFloat: value
forKey: NSString::alloc(nil).init_str("volume")];
},
TAG_SLIDE_PITCH =>
{
let mut value:f32 = msg_send![sender, floatValue];
if value > 1f32
{
//just map [1, 1.5] -> [1, 2]
value = value * (2.0f32/1.5f32);
}
tickeys_ptr.set_pitch(value);
let _:id = msg_send![user_defaults, setFloat: value
forKey: NSString::alloc(nil).init_str("pitch")];
}
_ => {panic!("WTF");}
}
}
}
extern fn windowWillClose(this: &Object, _cmd: Sel, note: id)
{
println!("SettingsController::windowWillClose");
unsafe
{
let app_ptr: *mut Tickeys = msg_send![this, user_data];
SHOWING_GUI = false;
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _:id = msg_send![user_defaults, synchronize];
let _:id = msg_send![this, release];
}
}
extern fn btnAddClicked(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Add Item");
unsafe
{
let open: id = msg_send![class("NSOpenPanel"), openPanel];
let apps_dir: id = msg_send![class("NSURL"), URLWithString: nsstr("/Applications")];
let allowed_types: id = msg_send![class("NSMutableArray"), arrayWithCapacity:2];
let _: id = msg_send![allowed_types, addObject: nsstr("app")];
let _: id = msg_send![open, setDirectoryURL: apps_dir];
let _: id = msg_send![open, setAllowedFileTypes: allowed_types];
let _: id = msg_send![open, setAllowsMultipleSelection: true];
let ret: i32 = msg_send![open, runModal];
if ret == 1 //Ok
{
let files: id = msg_send![open, URLs];
let n: i32 = msg_send![files, count];
let filterList: id = Self::filterList();
for i in 0..n
{
let appName: id = nsurl_filename(msg_send![files, objectAtIndex: i]);
let contains: bool = msg_send![filterList, containsObject: appName];
if!contains
{
let _: id = msg_send![filterList, addObject: appName];
}
}
//reload table ddata
let filterListTable: id = msg_send![this, filterListTable];
let _: id = msg_send![filterListTable, reloadData];
//save
let ud: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _: id = msg_send![ud, setObject:filterList forKey: nsstr("FilterList")];
}
}
}
extern fn
|
(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Remove Item");
unsafe
{
let filterList = Self::filterList();
let table: id = msg_send![this, filterListTable];
let selectedRow: i32 = msg_send![table, selectedRow];
if selectedRow >= 0
{
let _: id = msg_send![filterList, removeObjectAtIndex:selectedRow];
let _: id = msg_send![table, reloadData];
let ud: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _: id = msg_send![ud, setObject:filterList forKey: nsstr("FilterList")];
}
}
}
unsafe fn load_values(this: id)
{
println!("loadValues");
let app_ptr: &mut Tickeys = msg_send![this, user_data];
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let popup_audio_scheme: id = msg_send![this, popup_audio_scheme];
let _: id = msg_send![popup_audio_scheme, removeAllItems];
let schemes = app_ptr.get_schemes();//load_audio_schemes();
let pref = Pref::load(schemes);
for i in 0..schemes.len()
{
let s = &schemes[i];
let _: id = msg_send![popup_audio_scheme, addItemWithTitle: l10n_str(&s.display_name)];
if *s.name == pref.scheme
{
let _:id = msg_send![popup_audio_scheme, selectItemAtIndex:i];
}
}
let slide_volume: id = msg_send![this, slide_volume];
let _:id = msg_send![slide_volume, setFloatValue: pref.volume];
let slide_pitch: id = msg_send![this, slide_pitch];
let value = if pref.pitch > 1f32
{
pref.pitch * (1.5f32/2.0f32)
} else
{
pref.pitch
};
let _:id = msg_send![slide_pitch, setFloatValue: value];
let label_version: id = msg_send![this, label_version];
let _:id = msg_send![label_version,
setStringValue: NSString::alloc(nil).init_str(format!("{}",CURRENT_VERSION).as_ref())];
//let _:id = msg_send![this, show]
println!("makeKeyAndOrderFront:");
let win:id = msg_send![this, window];
let _:id = msg_send![win, makeKeyAndOrderFront:nil];
let _:id = msg_send![NSApp(), activateIgnoringOtherApps:true];
}
//-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
extern fn numberOfRowsInTableView(this: &mut Object, _cmd: Sel, tableView: id) -> i32
{
unsafe
{
msg_send![Self::filterList(), count]
}
}
fn filterList() -> id
{
unsafe
{
//strong coupling...
let appDelegate: id = msg_send![NSApp(), delegate];
msg_send![appDelegate, filterList]
}
}
//-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
extern fn tableViewObjectValueForTableColumn(this: &mut Object, _cmd: Sel, tableView: id, tableColumn: id, row: i32) -> id
{
unsafe
{
msg_send![Self::filterList(), objectAtIndex: row]
}
}
//-(BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
extern fn tableViewShouldEditTableColumnRow(this: &mut Object, _cmd: Sel, tableView: id, tableColumn: id, row: i32) -> bool
{
false
}
}
impl SettingsController for id
{
}
|
btnRemoveClicked
|
identifier_name
|
settings_ui.rs
|
extern crate objc;
use super::consts::*;
use super::cocoa_util::*;
use pref::*;
use core_graphics::*;
use tickeys::Tickeys;
use std::sync::{ONCE_INIT, Once};
use objc::runtime::*;
use cocoa::base::{class,id,nil};
use cocoa::foundation::NSString;
use cocoa::appkit::NSApp;
// naive way of make this a singleton
static mut SHOWING_GUI:bool = false;
#[allow(non_snake_case)]
#[allow(unused_variables)]
pub trait SettingsController //<NSWindowDelegate, NSTableViewDelegate, NSTableViewDataSource>
{
fn get_instance(_: Self, ptr_to_app: *mut Tickeys) -> id
{
Self::__register_objc_class_once();
unsafe
{
if SHOWING_GUI { return nil };
let nib_name = NSString::alloc(nil).init_str("Settings");
let inst: id = msg_send![class(stringify!(SettingsController)), alloc];
let inst: id = msg_send![inst, initWithWindowNibName: nib_name];
inst.retain();
let _:id = msg_send![inst, setUser_data: ptr_to_app];
let _: id = msg_send![inst, showWindow: nil];
SHOWING_GUI = true;
inst
}
}
fn __register_objc_class_once()
{
static REGISTER_APPDELEGATE: Once = ONCE_INIT;
REGISTER_APPDELEGATE.call_once(||
{
println!("SettingsController::__register_objc_class_once");
let superCls = objc::runtime::Class::get("NSWindowController").unwrap();
let mut decl = objc::declare::ClassDecl::new(superCls, stringify!(SettingsController)).unwrap();
decl_prop!(decl, usize, user_data);
decl_prop!(decl, id, popup_audio_scheme);
decl_prop!(decl, id, slide_volume);
decl_prop!(decl, id, slide_pitch);
decl_prop!(decl, id, label_version);
decl_prop!(decl, id, filterListTable);
unsafe
{
//methods
decl.add_method(sel!(quit:), Self::quit_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(value_changed:), Self::value_changed_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(follow_link:), Self::follow_link_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(windowWillClose:), Self::windowWillClose as extern fn(&Object, Sel, id));
decl.add_method(sel!(windowDidLoad), Self::windowDidLoad as extern fn(&mut Object, Sel));
decl.add_method(sel!(tableView:shouldEditTableColumn:row:), Self::tableViewShouldEditTableColumnRow as extern fn(&mut Object, Sel, id, id, i32) -> bool);
decl.add_method(sel!(btnAddClicked:), Self::btnAddClicked as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(btnRemoveClicked:), Self::btnRemoveClicked as extern fn(&mut Object, Sel, id));
//tableViewSource & tableViewDelegate
decl.add_method(sel!(numberOfRowsInTableView:), Self::numberOfRowsInTableView as extern fn(&mut Object, Sel, id)->i32);
decl.add_method(sel!(tableView:objectValueForTableColumn:row:), Self::tableViewObjectValueForTableColumn as extern fn(&mut Object, Sel, id, id, i32)->id);
}
decl.register();
});
}
extern fn windowDidLoad(this: &mut Object, _cmd: Sel)
{
println!("windowDidLoad");
unsafe
{
let window: id = msg_send![this, window];
//hide window btns
let btnMin: id = msg_send![window, standardWindowButton:1];
let _: id = msg_send![btnMin, setHidden: true];
let btnZoom: id = msg_send![window, standardWindowButton:2];
let _: id = msg_send![btnZoom, setHidden: true];
let _: id = msg_send![window, setLevel: CGWindowLevelForKey(CGWindowLevelKey::kCGFloatingWindowLevelKey)];
Self::load_values(this);
}
}
extern fn quit_(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Quit");
app_terminate();
}
extern fn follow_link_(this: &mut Object, _cmd: Sel, sender: id)
{
unsafe
{
let tag:i64 = msg_send![sender, tag];
let url = match tag
{
0 => WEBSITE,
1 => DONATE_URL,
_ => panic!("SettingsController::follow_link_")
};
let workspace: id = msg_send![class("NSWorkspace"), sharedWorkspace];
let url:id = msg_send![class("NSURL"),
URLWithString: NSString::alloc(nil).init_str(url)];
msg_send![workspace, openURL: url]
}
}
extern fn value_changed_(this: &mut Object, _cmd:Sel, sender: id)
{
println!("SettingsController::value_changed_");
const TAG_POPUP_SCHEME: i64 = 0;
const TAG_SLIDE_VOLUME: i64 = 1;
const TAG_SLIDE_PITCH: i64 = 2;
unsafe
{
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let tickeys_ptr:&mut Tickeys = msg_send![this, user_data];
let tag:i64 = msg_send![sender, tag];
match tag
{
TAG_POPUP_SCHEME =>
{
let value:i32 = msg_send![sender, indexOfSelectedItem];
let sch;// = &schemes[value as usize];
{
let schemes = tickeys_ptr.get_schemes();//= load_audio_schemes();
sch = schemes[value as usize].name.clone();
}
let scheme_dir = "data/".to_string() + &sch;//.to_string();
//scheme_dir.push_str(&sch.name);
tickeys_ptr.load_scheme(&get_res_path(&scheme_dir), &sch);
let _:id = msg_send![user_defaults,
setObject: NSString::alloc(nil).init_str(sch.as_ref())
forKey: NSString::alloc(nil).init_str("audio_scheme")];
},
TAG_SLIDE_VOLUME =>
{
let value:f32 = msg_send![sender, floatValue];
tickeys_ptr.set_volume(value);
let _:id = msg_send![user_defaults, setFloat: value
forKey: NSString::alloc(nil).init_str("volume")];
},
TAG_SLIDE_PITCH =>
{
let mut value:f32 = msg_send![sender, floatValue];
if value > 1f32
{
//just map [1, 1.5] -> [1, 2]
value = value * (2.0f32/1.5f32);
}
tickeys_ptr.set_pitch(value);
let _:id = msg_send![user_defaults, setFloat: value
forKey: NSString::alloc(nil).init_str("pitch")];
}
_ => {panic!("WTF");}
}
}
}
extern fn windowWillClose(this: &Object, _cmd: Sel, note: id)
{
println!("SettingsController::windowWillClose");
unsafe
{
let app_ptr: *mut Tickeys = msg_send![this, user_data];
SHOWING_GUI = false;
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _:id = msg_send![user_defaults, synchronize];
let _:id = msg_send![this, release];
}
}
extern fn btnAddClicked(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Add Item");
unsafe
{
let open: id = msg_send![class("NSOpenPanel"), openPanel];
let apps_dir: id = msg_send![class("NSURL"), URLWithString: nsstr("/Applications")];
let allowed_types: id = msg_send![class("NSMutableArray"), arrayWithCapacity:2];
let _: id = msg_send![allowed_types, addObject: nsstr("app")];
let _: id = msg_send![open, setDirectoryURL: apps_dir];
let _: id = msg_send![open, setAllowedFileTypes: allowed_types];
let _: id = msg_send![open, setAllowsMultipleSelection: true];
let ret: i32 = msg_send![open, runModal];
if ret == 1 //Ok
{
let files: id = msg_send![open, URLs];
let n: i32 = msg_send![files, count];
let filterList: id = Self::filterList();
for i in 0..n
{
let appName: id = nsurl_filename(msg_send![files, objectAtIndex: i]);
let contains: bool = msg_send![filterList, containsObject: appName];
if!contains
{
let _: id = msg_send![filterList, addObject: appName];
}
}
//reload table ddata
let filterListTable: id = msg_send![this, filterListTable];
let _: id = msg_send![filterListTable, reloadData];
//save
let ud: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _: id = msg_send![ud, setObject:filterList forKey: nsstr("FilterList")];
}
}
}
extern fn btnRemoveClicked(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Remove Item");
unsafe
{
let filterList = Self::filterList();
let table: id = msg_send![this, filterListTable];
let selectedRow: i32 = msg_send![table, selectedRow];
if selectedRow >= 0
{
let _: id = msg_send![filterList, removeObjectAtIndex:selectedRow];
let _: id = msg_send![table, reloadData];
let ud: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _: id = msg_send![ud, setObject:filterList forKey: nsstr("FilterList")];
}
}
}
unsafe fn load_values(this: id)
{
println!("loadValues");
let app_ptr: &mut Tickeys = msg_send![this, user_data];
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let popup_audio_scheme: id = msg_send![this, popup_audio_scheme];
let _: id = msg_send![popup_audio_scheme, removeAllItems];
let schemes = app_ptr.get_schemes();//load_audio_schemes();
let pref = Pref::load(schemes);
for i in 0..schemes.len()
{
let s = &schemes[i];
let _: id = msg_send![popup_audio_scheme, addItemWithTitle: l10n_str(&s.display_name)];
if *s.name == pref.scheme
{
let _:id = msg_send![popup_audio_scheme, selectItemAtIndex:i];
}
}
let slide_volume: id = msg_send![this, slide_volume];
let _:id = msg_send![slide_volume, setFloatValue: pref.volume];
let slide_pitch: id = msg_send![this, slide_pitch];
let value = if pref.pitch > 1f32
{
pref.pitch * (1.5f32/2.0f32)
} else
{
pref.pitch
};
let _:id = msg_send![slide_pitch, setFloatValue: value];
let label_version: id = msg_send![this, label_version];
let _:id = msg_send![label_version,
setStringValue: NSString::alloc(nil).init_str(format!("{}",CURRENT_VERSION).as_ref())];
|
let _:id = msg_send![NSApp(), activateIgnoringOtherApps:true];
}
//-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
extern fn numberOfRowsInTableView(this: &mut Object, _cmd: Sel, tableView: id) -> i32
{
unsafe
{
msg_send![Self::filterList(), count]
}
}
fn filterList() -> id
{
unsafe
{
//strong coupling...
let appDelegate: id = msg_send![NSApp(), delegate];
msg_send![appDelegate, filterList]
}
}
//-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
extern fn tableViewObjectValueForTableColumn(this: &mut Object, _cmd: Sel, tableView: id, tableColumn: id, row: i32) -> id
{
unsafe
{
msg_send![Self::filterList(), objectAtIndex: row]
}
}
//-(BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
extern fn tableViewShouldEditTableColumnRow(this: &mut Object, _cmd: Sel, tableView: id, tableColumn: id, row: i32) -> bool
{
false
}
}
impl SettingsController for id
{
}
|
//let _:id = msg_send![this, show]
println!("makeKeyAndOrderFront:");
let win:id = msg_send![this, window];
let _:id = msg_send![win, makeKeyAndOrderFront:nil];
|
random_line_split
|
settings_ui.rs
|
extern crate objc;
use super::consts::*;
use super::cocoa_util::*;
use pref::*;
use core_graphics::*;
use tickeys::Tickeys;
use std::sync::{ONCE_INIT, Once};
use objc::runtime::*;
use cocoa::base::{class,id,nil};
use cocoa::foundation::NSString;
use cocoa::appkit::NSApp;
// naive way of make this a singleton
static mut SHOWING_GUI:bool = false;
#[allow(non_snake_case)]
#[allow(unused_variables)]
pub trait SettingsController //<NSWindowDelegate, NSTableViewDelegate, NSTableViewDataSource>
{
fn get_instance(_: Self, ptr_to_app: *mut Tickeys) -> id
{
Self::__register_objc_class_once();
unsafe
{
if SHOWING_GUI { return nil };
let nib_name = NSString::alloc(nil).init_str("Settings");
let inst: id = msg_send![class(stringify!(SettingsController)), alloc];
let inst: id = msg_send![inst, initWithWindowNibName: nib_name];
inst.retain();
let _:id = msg_send![inst, setUser_data: ptr_to_app];
let _: id = msg_send![inst, showWindow: nil];
SHOWING_GUI = true;
inst
}
}
fn __register_objc_class_once()
{
static REGISTER_APPDELEGATE: Once = ONCE_INIT;
REGISTER_APPDELEGATE.call_once(||
{
println!("SettingsController::__register_objc_class_once");
let superCls = objc::runtime::Class::get("NSWindowController").unwrap();
let mut decl = objc::declare::ClassDecl::new(superCls, stringify!(SettingsController)).unwrap();
decl_prop!(decl, usize, user_data);
decl_prop!(decl, id, popup_audio_scheme);
decl_prop!(decl, id, slide_volume);
decl_prop!(decl, id, slide_pitch);
decl_prop!(decl, id, label_version);
decl_prop!(decl, id, filterListTable);
unsafe
{
//methods
decl.add_method(sel!(quit:), Self::quit_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(value_changed:), Self::value_changed_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(follow_link:), Self::follow_link_ as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(windowWillClose:), Self::windowWillClose as extern fn(&Object, Sel, id));
decl.add_method(sel!(windowDidLoad), Self::windowDidLoad as extern fn(&mut Object, Sel));
decl.add_method(sel!(tableView:shouldEditTableColumn:row:), Self::tableViewShouldEditTableColumnRow as extern fn(&mut Object, Sel, id, id, i32) -> bool);
decl.add_method(sel!(btnAddClicked:), Self::btnAddClicked as extern fn(&mut Object, Sel, id));
decl.add_method(sel!(btnRemoveClicked:), Self::btnRemoveClicked as extern fn(&mut Object, Sel, id));
//tableViewSource & tableViewDelegate
decl.add_method(sel!(numberOfRowsInTableView:), Self::numberOfRowsInTableView as extern fn(&mut Object, Sel, id)->i32);
decl.add_method(sel!(tableView:objectValueForTableColumn:row:), Self::tableViewObjectValueForTableColumn as extern fn(&mut Object, Sel, id, id, i32)->id);
}
decl.register();
});
}
extern fn windowDidLoad(this: &mut Object, _cmd: Sel)
{
println!("windowDidLoad");
unsafe
{
let window: id = msg_send![this, window];
//hide window btns
let btnMin: id = msg_send![window, standardWindowButton:1];
let _: id = msg_send![btnMin, setHidden: true];
let btnZoom: id = msg_send![window, standardWindowButton:2];
let _: id = msg_send![btnZoom, setHidden: true];
let _: id = msg_send![window, setLevel: CGWindowLevelForKey(CGWindowLevelKey::kCGFloatingWindowLevelKey)];
Self::load_values(this);
}
}
extern fn quit_(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Quit");
app_terminate();
}
extern fn follow_link_(this: &mut Object, _cmd: Sel, sender: id)
{
unsafe
{
let tag:i64 = msg_send![sender, tag];
let url = match tag
{
0 => WEBSITE,
1 => DONATE_URL,
_ => panic!("SettingsController::follow_link_")
};
let workspace: id = msg_send![class("NSWorkspace"), sharedWorkspace];
let url:id = msg_send![class("NSURL"),
URLWithString: NSString::alloc(nil).init_str(url)];
msg_send![workspace, openURL: url]
}
}
extern fn value_changed_(this: &mut Object, _cmd:Sel, sender: id)
{
println!("SettingsController::value_changed_");
const TAG_POPUP_SCHEME: i64 = 0;
const TAG_SLIDE_VOLUME: i64 = 1;
const TAG_SLIDE_PITCH: i64 = 2;
unsafe
{
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let tickeys_ptr:&mut Tickeys = msg_send![this, user_data];
let tag:i64 = msg_send![sender, tag];
match tag
{
TAG_POPUP_SCHEME =>
{
let value:i32 = msg_send![sender, indexOfSelectedItem];
let sch;// = &schemes[value as usize];
{
let schemes = tickeys_ptr.get_schemes();//= load_audio_schemes();
sch = schemes[value as usize].name.clone();
}
let scheme_dir = "data/".to_string() + &sch;//.to_string();
//scheme_dir.push_str(&sch.name);
tickeys_ptr.load_scheme(&get_res_path(&scheme_dir), &sch);
let _:id = msg_send![user_defaults,
setObject: NSString::alloc(nil).init_str(sch.as_ref())
forKey: NSString::alloc(nil).init_str("audio_scheme")];
},
TAG_SLIDE_VOLUME =>
{
let value:f32 = msg_send![sender, floatValue];
tickeys_ptr.set_volume(value);
let _:id = msg_send![user_defaults, setFloat: value
forKey: NSString::alloc(nil).init_str("volume")];
},
TAG_SLIDE_PITCH =>
{
let mut value:f32 = msg_send![sender, floatValue];
if value > 1f32
{
//just map [1, 1.5] -> [1, 2]
value = value * (2.0f32/1.5f32);
}
tickeys_ptr.set_pitch(value);
let _:id = msg_send![user_defaults, setFloat: value
forKey: NSString::alloc(nil).init_str("pitch")];
}
_ => {panic!("WTF");}
}
}
}
extern fn windowWillClose(this: &Object, _cmd: Sel, note: id)
{
println!("SettingsController::windowWillClose");
unsafe
{
let app_ptr: *mut Tickeys = msg_send![this, user_data];
SHOWING_GUI = false;
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _:id = msg_send![user_defaults, synchronize];
let _:id = msg_send![this, release];
}
}
extern fn btnAddClicked(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Add Item");
unsafe
{
let open: id = msg_send![class("NSOpenPanel"), openPanel];
let apps_dir: id = msg_send![class("NSURL"), URLWithString: nsstr("/Applications")];
let allowed_types: id = msg_send![class("NSMutableArray"), arrayWithCapacity:2];
let _: id = msg_send![allowed_types, addObject: nsstr("app")];
let _: id = msg_send![open, setDirectoryURL: apps_dir];
let _: id = msg_send![open, setAllowedFileTypes: allowed_types];
let _: id = msg_send![open, setAllowsMultipleSelection: true];
let ret: i32 = msg_send![open, runModal];
if ret == 1 //Ok
{
let files: id = msg_send![open, URLs];
let n: i32 = msg_send![files, count];
let filterList: id = Self::filterList();
for i in 0..n
{
let appName: id = nsurl_filename(msg_send![files, objectAtIndex: i]);
let contains: bool = msg_send![filterList, containsObject: appName];
if!contains
{
let _: id = msg_send![filterList, addObject: appName];
}
}
//reload table ddata
let filterListTable: id = msg_send![this, filterListTable];
let _: id = msg_send![filterListTable, reloadData];
//save
let ud: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _: id = msg_send![ud, setObject:filterList forKey: nsstr("FilterList")];
}
}
}
extern fn btnRemoveClicked(this: &mut Object, _cmd: Sel, sender: id)
{
println!("Remove Item");
unsafe
{
let filterList = Self::filterList();
let table: id = msg_send![this, filterListTable];
let selectedRow: i32 = msg_send![table, selectedRow];
if selectedRow >= 0
{
let _: id = msg_send![filterList, removeObjectAtIndex:selectedRow];
let _: id = msg_send![table, reloadData];
let ud: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let _: id = msg_send![ud, setObject:filterList forKey: nsstr("FilterList")];
}
}
}
unsafe fn load_values(this: id)
{
println!("loadValues");
let app_ptr: &mut Tickeys = msg_send![this, user_data];
let user_defaults: id = msg_send![class("NSUserDefaults"), standardUserDefaults];
let popup_audio_scheme: id = msg_send![this, popup_audio_scheme];
let _: id = msg_send![popup_audio_scheme, removeAllItems];
let schemes = app_ptr.get_schemes();//load_audio_schemes();
let pref = Pref::load(schemes);
for i in 0..schemes.len()
{
let s = &schemes[i];
let _: id = msg_send![popup_audio_scheme, addItemWithTitle: l10n_str(&s.display_name)];
if *s.name == pref.scheme
{
let _:id = msg_send![popup_audio_scheme, selectItemAtIndex:i];
}
}
let slide_volume: id = msg_send![this, slide_volume];
let _:id = msg_send![slide_volume, setFloatValue: pref.volume];
let slide_pitch: id = msg_send![this, slide_pitch];
let value = if pref.pitch > 1f32
{
pref.pitch * (1.5f32/2.0f32)
} else
{
pref.pitch
};
let _:id = msg_send![slide_pitch, setFloatValue: value];
let label_version: id = msg_send![this, label_version];
let _:id = msg_send![label_version,
setStringValue: NSString::alloc(nil).init_str(format!("{}",CURRENT_VERSION).as_ref())];
//let _:id = msg_send![this, show]
println!("makeKeyAndOrderFront:");
let win:id = msg_send![this, window];
let _:id = msg_send![win, makeKeyAndOrderFront:nil];
let _:id = msg_send![NSApp(), activateIgnoringOtherApps:true];
}
//-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
extern fn numberOfRowsInTableView(this: &mut Object, _cmd: Sel, tableView: id) -> i32
{
unsafe
{
msg_send![Self::filterList(), count]
}
}
fn filterList() -> id
{
unsafe
{
//strong coupling...
let appDelegate: id = msg_send![NSApp(), delegate];
msg_send![appDelegate, filterList]
}
}
//-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
extern fn tableViewObjectValueForTableColumn(this: &mut Object, _cmd: Sel, tableView: id, tableColumn: id, row: i32) -> id
{
unsafe
{
msg_send![Self::filterList(), objectAtIndex: row]
}
}
//-(BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
extern fn tableViewShouldEditTableColumnRow(this: &mut Object, _cmd: Sel, tableView: id, tableColumn: id, row: i32) -> bool
|
}
impl SettingsController for id
{
}
|
{
false
}
|
identifier_body
|
lib.rs
|
#![feature(plugin_registrar, macro_rules)]
#![crate_type = "dylib"]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap::{Span};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, DummyResult};
use rustc::plugin::Registry;
use Severity::{Note, Warning, Error, Fatal};
enum Severity {
Note,
Warning,
Error,
Fatal,
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
macro_rules! register_specifics {
($($name: expr => $sev: ident),*) => {
{
$(
reg.register_macro($name, {
fn f(cx: &mut ExtCtxt, sp: Span,
args: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
expand_msg($sev, cx, sp, args)
}
f
});
)*
}
}
}
register_specifics! {
"compile_note" => Note,
"compile_warning" => Warning,
"compile_error" => Error,
"compile_fatal" => Fatal
}
}
fn expand_msg(sev: Severity,
cx: &mut ExtCtxt, sp: Span, args: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
// copied from syntax::ext::concat.
let es = match base::get_exprs_from_tts(cx, sp, args) {
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
let mut accumulator = String::new();
for e in es.into_iter() {
match e.node {
ast::ExprLit(ref lit) => {
match lit.node {
ast::LitStr(ref s, _) |
ast::LitFloat(ref s, _) |
ast::LitFloatUnsuffixed(ref s) => {
accumulator.push_str(s.get());
}
ast::LitChar(c) => {
accumulator.push(c);
}
ast::LitInt(i, ast::UnsignedIntLit(_)) |
|
ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Plus)) => {
accumulator.push_str(format!("{}", i).as_slice());
}
ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => {
accumulator.push_str(format!("-{}", i).as_slice());
}
ast::LitBool(b) => {
accumulator.push_str(format!("{}", b).as_slice());
}
ast::LitByte(..) |
ast::LitBinary(..) => {
cx.span_err(e.span, "cannot concatenate a binary literal");
}
}
}
_ => {
cx.span_err(e.span, "expected a literal");
}
}
}
macro_rules! emit {
($($sev: ident => $method: ident),*) => {
match sev {
$($sev => cx.$method(sp, accumulator.as_slice()),)*
}
}
}
emit! {
Note => span_note,
Warning => span_warn,
Error => span_err,
Fatal => span_fatal
}
DummyResult::any(sp)
}
|
random_line_split
|
|
lib.rs
|
#![feature(plugin_registrar, macro_rules)]
#![crate_type = "dylib"]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap::{Span};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, DummyResult};
use rustc::plugin::Registry;
use Severity::{Note, Warning, Error, Fatal};
enum Severity {
Note,
Warning,
Error,
Fatal,
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
macro_rules! register_specifics {
($($name: expr => $sev: ident),*) => {
{
$(
reg.register_macro($name, {
fn f(cx: &mut ExtCtxt, sp: Span,
args: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
expand_msg($sev, cx, sp, args)
}
f
});
)*
}
}
}
register_specifics! {
"compile_note" => Note,
"compile_warning" => Warning,
"compile_error" => Error,
"compile_fatal" => Fatal
}
}
fn expand_msg(sev: Severity,
cx: &mut ExtCtxt, sp: Span, args: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
// copied from syntax::ext::concat.
let es = match base::get_exprs_from_tts(cx, sp, args) {
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
let mut accumulator = String::new();
for e in es.into_iter() {
match e.node {
ast::ExprLit(ref lit) => {
match lit.node {
ast::LitStr(ref s, _) |
ast::LitFloat(ref s, _) |
ast::LitFloatUnsuffixed(ref s) => {
accumulator.push_str(s.get());
}
ast::LitChar(c) => {
accumulator.push(c);
}
ast::LitInt(i, ast::UnsignedIntLit(_)) |
ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Plus)) =>
|
ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => {
accumulator.push_str(format!("-{}", i).as_slice());
}
ast::LitBool(b) => {
accumulator.push_str(format!("{}", b).as_slice());
}
ast::LitByte(..) |
ast::LitBinary(..) => {
cx.span_err(e.span, "cannot concatenate a binary literal");
}
}
}
_ => {
cx.span_err(e.span, "expected a literal");
}
}
}
macro_rules! emit {
($($sev: ident => $method: ident),*) => {
match sev {
$($sev => cx.$method(sp, accumulator.as_slice()),)*
}
}
}
emit! {
Note => span_note,
Warning => span_warn,
Error => span_err,
Fatal => span_fatal
}
DummyResult::any(sp)
}
|
{
accumulator.push_str(format!("{}", i).as_slice());
}
|
conditional_block
|
lib.rs
|
#![feature(plugin_registrar, macro_rules)]
#![crate_type = "dylib"]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap::{Span};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, DummyResult};
use rustc::plugin::Registry;
use Severity::{Note, Warning, Error, Fatal};
enum Severity {
Note,
Warning,
Error,
Fatal,
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
macro_rules! register_specifics {
($($name: expr => $sev: ident),*) => {
{
$(
reg.register_macro($name, {
fn f(cx: &mut ExtCtxt, sp: Span,
args: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
expand_msg($sev, cx, sp, args)
}
f
});
)*
}
}
}
register_specifics! {
"compile_note" => Note,
"compile_warning" => Warning,
"compile_error" => Error,
"compile_fatal" => Fatal
}
}
fn
|
(sev: Severity,
cx: &mut ExtCtxt, sp: Span, args: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
// copied from syntax::ext::concat.
let es = match base::get_exprs_from_tts(cx, sp, args) {
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
let mut accumulator = String::new();
for e in es.into_iter() {
match e.node {
ast::ExprLit(ref lit) => {
match lit.node {
ast::LitStr(ref s, _) |
ast::LitFloat(ref s, _) |
ast::LitFloatUnsuffixed(ref s) => {
accumulator.push_str(s.get());
}
ast::LitChar(c) => {
accumulator.push(c);
}
ast::LitInt(i, ast::UnsignedIntLit(_)) |
ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Plus)) => {
accumulator.push_str(format!("{}", i).as_slice());
}
ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => {
accumulator.push_str(format!("-{}", i).as_slice());
}
ast::LitBool(b) => {
accumulator.push_str(format!("{}", b).as_slice());
}
ast::LitByte(..) |
ast::LitBinary(..) => {
cx.span_err(e.span, "cannot concatenate a binary literal");
}
}
}
_ => {
cx.span_err(e.span, "expected a literal");
}
}
}
macro_rules! emit {
($($sev: ident => $method: ident),*) => {
match sev {
$($sev => cx.$method(sp, accumulator.as_slice()),)*
}
}
}
emit! {
Note => span_note,
Warning => span_warn,
Error => span_err,
Fatal => span_fatal
}
DummyResult::any(sp)
}
|
expand_msg
|
identifier_name
|
simd-intrinsic-generic-scatter.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.
// ignore-emscripten
// ignore-tidy-linelength
// compile-flags: -C no-prepopulate-passes
#![crate_type = "lib"]
#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vec2<T>(pub T, pub T);
|
extern "platform-intrinsic" {
fn simd_scatter<T, P, M>(value: T, pointers: P, mask: M);
}
// CHECK-LABEL: @scatter_f32x2
#[no_mangle]
pub unsafe fn scatter_f32x2(pointers: Vec2<*mut f32>, mask: Vec2<i32>,
values: Vec2<f32>) {
// CHECK: call void @llvm.masked.scatter.v2f32.v2p0f32(<2 x float> {{.*}}, <2 x float*> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
}
// CHECK-LABEL: @scatter_pf32x2
#[no_mangle]
pub unsafe fn scatter_pf32x2(pointers: Vec2<*mut *const f32>, mask: Vec2<i32>,
values: Vec2<*const f32>) {
// CHECK: call void @llvm.masked.scatter.v2p0f32.v2p0p0f32(<2 x float*> {{.*}}, <2 x float**> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
}
|
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vec4<T>(pub T, pub T, pub T, pub T);
|
random_line_split
|
simd-intrinsic-generic-scatter.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.
// ignore-emscripten
// ignore-tidy-linelength
// compile-flags: -C no-prepopulate-passes
#![crate_type = "lib"]
#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vec2<T>(pub T, pub T);
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vec4<T>(pub T, pub T, pub T, pub T);
extern "platform-intrinsic" {
fn simd_scatter<T, P, M>(value: T, pointers: P, mask: M);
}
// CHECK-LABEL: @scatter_f32x2
#[no_mangle]
pub unsafe fn scatter_f32x2(pointers: Vec2<*mut f32>, mask: Vec2<i32>,
values: Vec2<f32>) {
// CHECK: call void @llvm.masked.scatter.v2f32.v2p0f32(<2 x float> {{.*}}, <2 x float*> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
}
// CHECK-LABEL: @scatter_pf32x2
#[no_mangle]
pub unsafe fn scatter_pf32x2(pointers: Vec2<*mut *const f32>, mask: Vec2<i32>,
values: Vec2<*const f32>)
|
{
// CHECK: call void @llvm.masked.scatter.v2p0f32.v2p0p0f32(<2 x float*> {{.*}}, <2 x float**> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
}
|
identifier_body
|
|
simd-intrinsic-generic-scatter.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.
// ignore-emscripten
// ignore-tidy-linelength
// compile-flags: -C no-prepopulate-passes
#![crate_type = "lib"]
#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vec2<T>(pub T, pub T);
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vec4<T>(pub T, pub T, pub T, pub T);
extern "platform-intrinsic" {
fn simd_scatter<T, P, M>(value: T, pointers: P, mask: M);
}
// CHECK-LABEL: @scatter_f32x2
#[no_mangle]
pub unsafe fn scatter_f32x2(pointers: Vec2<*mut f32>, mask: Vec2<i32>,
values: Vec2<f32>) {
// CHECK: call void @llvm.masked.scatter.v2f32.v2p0f32(<2 x float> {{.*}}, <2 x float*> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
}
// CHECK-LABEL: @scatter_pf32x2
#[no_mangle]
pub unsafe fn
|
(pointers: Vec2<*mut *const f32>, mask: Vec2<i32>,
values: Vec2<*const f32>) {
// CHECK: call void @llvm.masked.scatter.v2p0f32.v2p0p0f32(<2 x float*> {{.*}}, <2 x float**> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
}
|
scatter_pf32x2
|
identifier_name
|
bad.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.
// Check that `<-` and `in` syntax gets a hard error.
// revisions: good bad
//[good] run-pass
#[cfg(bad)]
fn main() {
let (x, y, foo, bar);
x <- y; //[bad]~ ERROR emplacement syntax is obsolete
in(foo) { bar }; //[bad]~ ERROR emplacement syntax is obsolete
}
#[cfg(good)]
fn
|
() {
}
|
main
|
identifier_name
|
bad.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.
// Check that `<-` and `in` syntax gets a hard error.
// revisions: good bad
//[good] run-pass
#[cfg(bad)]
fn main() {
let (x, y, foo, bar);
x <- y; //[bad]~ ERROR emplacement syntax is obsolete
in(foo) { bar }; //[bad]~ ERROR emplacement syntax is obsolete
}
#[cfg(good)]
fn main()
|
{
}
|
identifier_body
|
|
bad.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.
// Check that `<-` and `in` syntax gets a hard error.
// revisions: good bad
//[good] run-pass
#[cfg(bad)]
fn main() {
let (x, y, foo, bar);
x <- y; //[bad]~ ERROR emplacement syntax is obsolete
in(foo) { bar }; //[bad]~ ERROR emplacement syntax is obsolete
}
|
fn main() {
}
|
#[cfg(good)]
|
random_line_split
|
oneshot.rs
|
//! A one-shot, futures-aware channel
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::error::Error;
use std::fmt;
use {Future, Poll, Async};
use lock::Lock;
use task::{self, Task};
/// A future representing the completion of a computation happening elsewhere in
/// memory.
///
/// This is created by the `oneshot::channel` function.
#[must_use = "futures do nothing unless polled"]
pub struct Receiver<T> {
inner: Arc<Inner<T>>,
}
/// Represents the completion half of a oneshot through which the result of a
/// computation is signaled.
///
/// This is created by the `oneshot::channel` function.
pub struct Sender<T> {
inner: Arc<Inner<T>>,
}
/// Internal state of the `Receiver`/`Sender` pair above. This is all used as
/// the internal synchronization between the two for send/recv operations.
struct Inner<T> {
/// Indicates whether this oneshot is complete yet. This is filled in both
/// by `Sender::drop` and by `Receiver::drop`, and both sides iterpret it
/// appropriately.
///
/// For `Receiver`, if this is `true`, then it's guaranteed that `data` is
/// unlocked and ready to be inspected.
///
/// For `Sender` if this is `true` then the oneshot has gone away and it
/// can return ready from `poll_cancel`.
complete: AtomicBool,
/// The actual data being transferred as part of this `Receiver`. This is
/// filled in by `Sender::complete` and read by `Receiver::poll`.
///
/// Note that this is protected by `Lock`, but it is in theory safe to
/// replace with an `UnsafeCell` as it's actually protected by `complete`
/// above. I wouldn't recommend doing this, however, unless someone is
/// supremely confident in the various atomic orderings here and there.
data: Lock<Option<T>>,
/// Field to store the task which is blocked in `Receiver::poll`.
///
/// This is filled in when a oneshot is polled but not ready yet. Note that
/// the `Lock` here, unlike in `data` above, is important to resolve races.
/// Both the `Receiver` and the `Sender` halves understand that if they
/// can't acquire the lock then some important interference is happening.
rx_task: Lock<Option<Task>>,
/// Like `rx_task` above, except for the task blocked in
/// `Sender::poll_cancel`. Additionally, `Lock` cannot be `UnsafeCell`.
tx_task: Lock<Option<Task>>,
|
/// Creates a new futures-aware, one-shot channel.
///
/// This function is similar to Rust's channels found in the standard library.
/// Two halves are returned, the first of which is a `Sender` handle, used to
/// signal the end of a computation and provide its value. The second half is a
/// `Receiver` which implements the `Future` trait, resolving to the value that
/// was given to the `Sender` handle.
///
/// Each half can be separately owned and sent across threads/tasks.
///
/// # Examples
///
/// ```
/// use std::thread;
/// use futures::sync::oneshot;
/// use futures::*;
///
/// let (c, p) = oneshot::channel::<i32>();
///
/// thread::spawn(|| {
/// p.map(|i| {
/// println!("got: {}", i);
/// }).wait();
/// });
///
/// c.complete(3);
/// ```
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let inner = Arc::new(Inner {
complete: AtomicBool::new(false),
data: Lock::new(None),
rx_task: Lock::new(None),
tx_task: Lock::new(None),
});
let receiver = Receiver {
inner: inner.clone(),
};
let sender = Sender {
inner: inner,
};
(sender, receiver)
}
impl<T> Sender<T> {
/// Completes this oneshot with a successful result.
///
/// This function will consume `self` and indicate to the other end, the
/// `Receiver`, that the error provided is the result of the computation this
/// represents.
pub fn complete(self, t: T) {
// First up, flag that this method was called and then store the data.
// Note that this lock acquisition should always succeed as it can only
// interfere with `poll` in `Receiver` which is only called when the
// `complete` flag is true, which we're setting here.
let mut slot = self.inner.data.try_lock().unwrap();
assert!(slot.is_none());
*slot = Some(t);
drop(slot);
}
/// Polls this `Sender` half to detect whether the `Receiver` this has
/// paired with has gone away.
///
/// This function can be used to learn about when the `Receiver` (consumer)
/// half has gone away and nothing will be able to receive a message sent
/// from `complete`.
///
/// Like `Future::poll`, this function will panic if it's not called from
/// within the context of a task. In otherwords, this should only ever be
/// called from inside another future.
///
/// If `Ready` is returned then it means that the `Receiver` has disappeared
/// and the result this `Sender` would otherwise produce should no longer
/// be produced.
///
/// If `NotReady` is returned then the `Receiver` is still alive and may be
/// able to receive a message if sent. The current task, however, is
/// scheduled to receive a notification if the corresponding `Receiver` goes
/// away.
pub fn poll_cancel(&mut self) -> Poll<(), ()> {
// Fast path up first, just read the flag and see if our other half is
// gone. This flag is set both in our destructor and the oneshot
// destructor, but our destructor hasn't run yet so if it's set then the
// oneshot is gone.
if self.inner.complete.load(SeqCst) {
return Ok(Async::Ready(()))
}
// If our other half is not gone then we need to park our current task
// and move it into the `notify_cancel` slot to get notified when it's
// actually gone.
//
// If `try_lock` fails, then the `Receiver` is in the process of using
// it, so we can deduce that it's now in the process of going away and
// hence we're canceled. If it succeeds then we just store our handle.
//
// Crucially we then check `oneshot_gone` *again* before we return.
// While we were storing our handle inside `notify_cancel` the `Receiver`
// may have been dropped. The first thing it does is set the flag, and
// if it fails to acquire the lock it assumes that we'll see the flag
// later on. So... we then try to see the flag later on!
let handle = task::park();
match self.inner.tx_task.try_lock() {
Some(mut p) => *p = Some(handle),
None => return Ok(Async::Ready(())),
}
if self.inner.complete.load(SeqCst) {
Ok(Async::Ready(()))
} else {
Ok(Async::NotReady)
}
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// Flag that we're a completed `Sender` and try to wake up a receiver.
// Whether or not we actually stored any data will get picked up and
// translated to either an item or cancellation.
//
// Note that if we fail to acquire the `rx_task` lock then that means
// we're in one of two situations:
//
// 1. The receiver is trying to block in `poll`
// 2. The receiver is being dropped
//
// In the first case it'll check the `complete` flag after it's done
// blocking to see if it succeeded. In the latter case we don't need to
// wake up anyone anyway. So in both cases it's ok to ignore the `None`
// case of `try_lock` and bail out.
//
// The first case crucially depends on `Lock` using `SeqCst` ordering
// under the hood. If it instead used `Release` / `Acquire` ordering,
// then it would not necessarily synchronize with `inner.complete`
// and deadlock might be possible, as was observed in
// https://github.com/alexcrichton/futures-rs/pull/219.
self.inner.complete.store(true, SeqCst);
if let Some(mut slot) = self.inner.rx_task.try_lock() {
if let Some(task) = slot.take() {
drop(slot);
task.unpark();
}
}
}
}
/// Error returned from a `Receiver<T>` whenever the correponding `Sender<T>`
/// is dropped.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Canceled;
impl fmt::Display for Canceled {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "oneshot canceled")
}
}
impl Error for Canceled {
fn description(&self) -> &str {
"oneshot canceled"
}
}
impl<T> Receiver<T> {
/// Gracefully close this receiver, preventing sending any future messages.
///
/// Any `send` operation which happens after this method returns is
/// guaranteed to fail. Once this method is called the normal `poll` method
/// can be used to determine whether a message was actually sent or not. If
/// `Canceled` is returned from `poll` then no message was sent.
pub fn close(&mut self) {
// Flag our completion and then attempt to wake up the sender if it's
// blocked. See comments in `drop` below for more info
self.inner.complete.store(true, SeqCst);
if let Some(mut handle) = self.inner.tx_task.try_lock() {
if let Some(task) = handle.take() {
drop(handle);
task.unpark()
}
}
}
}
impl<T> Future for Receiver<T> {
type Item = T;
type Error = Canceled;
fn poll(&mut self) -> Poll<T, Canceled> {
let mut done = false;
// Check to see if some data has arrived. If it hasn't then we need to
// block our task.
//
// Note that the acquisition of the `rx_task` lock might fail below, but
// the only situation where this can happen is during `Sender::drop`
// when we are indeed completed already. If that's happening then we
// know we're completed so keep going.
if self.inner.complete.load(SeqCst) {
done = true;
} else {
let task = task::park();
match self.inner.rx_task.try_lock() {
Some(mut slot) => *slot = Some(task),
None => done = true,
}
}
// If we're `done` via one of the paths above, then look at the data and
// figure out what the answer is. If, however, we stored `rx_task`
// successfully above we need to check again if we're completed in case
// a message was sent while `rx_task` was locked and couldn't notify us
// otherwise.
//
// If we're not done, and we're not complete, though, then we've
// successfully blocked our task and we return `NotReady`.
if done || self.inner.complete.load(SeqCst) {
match self.inner.data.try_lock().unwrap().take() {
Some(data) => Ok(data.into()),
None => Err(Canceled),
}
} else {
Ok(Async::NotReady)
}
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
// Indicate to the `Sender` that we're done, so any future calls to
// `poll_cancel` are weeded out.
self.inner.complete.store(true, SeqCst);
// If we've blocked a task then there's no need for it to stick around,
// so we need to drop it. If this lock acquisition fails, though, then
// it's just because our `Sender` is trying to take the task, so we
// let them take care of that.
if let Some(mut slot) = self.inner.rx_task.try_lock() {
let task = slot.take();
drop(slot);
drop(task);
}
// Finally, if our `Sender` wants to get notified of us going away, it
// would have stored something in `tx_task`. Here we try to peel that
// out and unpark it.
//
// Note that the `try_lock` here may fail, but only if the `Sender` is
// in the process of filling in the task. If that happens then we
// already flagged `complete` and they'll pick that up above.
if let Some(mut handle) = self.inner.tx_task.try_lock() {
if let Some(task) = handle.take() {
drop(handle);
task.unpark()
}
}
}
}
|
}
|
random_line_split
|
oneshot.rs
|
//! A one-shot, futures-aware channel
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::error::Error;
use std::fmt;
use {Future, Poll, Async};
use lock::Lock;
use task::{self, Task};
/// A future representing the completion of a computation happening elsewhere in
/// memory.
///
/// This is created by the `oneshot::channel` function.
#[must_use = "futures do nothing unless polled"]
pub struct Receiver<T> {
inner: Arc<Inner<T>>,
}
/// Represents the completion half of a oneshot through which the result of a
/// computation is signaled.
///
/// This is created by the `oneshot::channel` function.
pub struct Sender<T> {
inner: Arc<Inner<T>>,
}
/// Internal state of the `Receiver`/`Sender` pair above. This is all used as
/// the internal synchronization between the two for send/recv operations.
struct Inner<T> {
/// Indicates whether this oneshot is complete yet. This is filled in both
/// by `Sender::drop` and by `Receiver::drop`, and both sides iterpret it
/// appropriately.
///
/// For `Receiver`, if this is `true`, then it's guaranteed that `data` is
/// unlocked and ready to be inspected.
///
/// For `Sender` if this is `true` then the oneshot has gone away and it
/// can return ready from `poll_cancel`.
complete: AtomicBool,
/// The actual data being transferred as part of this `Receiver`. This is
/// filled in by `Sender::complete` and read by `Receiver::poll`.
///
/// Note that this is protected by `Lock`, but it is in theory safe to
/// replace with an `UnsafeCell` as it's actually protected by `complete`
/// above. I wouldn't recommend doing this, however, unless someone is
/// supremely confident in the various atomic orderings here and there.
data: Lock<Option<T>>,
/// Field to store the task which is blocked in `Receiver::poll`.
///
/// This is filled in when a oneshot is polled but not ready yet. Note that
/// the `Lock` here, unlike in `data` above, is important to resolve races.
/// Both the `Receiver` and the `Sender` halves understand that if they
/// can't acquire the lock then some important interference is happening.
rx_task: Lock<Option<Task>>,
/// Like `rx_task` above, except for the task blocked in
/// `Sender::poll_cancel`. Additionally, `Lock` cannot be `UnsafeCell`.
tx_task: Lock<Option<Task>>,
}
/// Creates a new futures-aware, one-shot channel.
///
/// This function is similar to Rust's channels found in the standard library.
/// Two halves are returned, the first of which is a `Sender` handle, used to
/// signal the end of a computation and provide its value. The second half is a
/// `Receiver` which implements the `Future` trait, resolving to the value that
/// was given to the `Sender` handle.
///
/// Each half can be separately owned and sent across threads/tasks.
///
/// # Examples
///
/// ```
/// use std::thread;
/// use futures::sync::oneshot;
/// use futures::*;
///
/// let (c, p) = oneshot::channel::<i32>();
///
/// thread::spawn(|| {
/// p.map(|i| {
/// println!("got: {}", i);
/// }).wait();
/// });
///
/// c.complete(3);
/// ```
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let inner = Arc::new(Inner {
complete: AtomicBool::new(false),
data: Lock::new(None),
rx_task: Lock::new(None),
tx_task: Lock::new(None),
});
let receiver = Receiver {
inner: inner.clone(),
};
let sender = Sender {
inner: inner,
};
(sender, receiver)
}
impl<T> Sender<T> {
/// Completes this oneshot with a successful result.
///
/// This function will consume `self` and indicate to the other end, the
/// `Receiver`, that the error provided is the result of the computation this
/// represents.
pub fn complete(self, t: T) {
// First up, flag that this method was called and then store the data.
// Note that this lock acquisition should always succeed as it can only
// interfere with `poll` in `Receiver` which is only called when the
// `complete` flag is true, which we're setting here.
let mut slot = self.inner.data.try_lock().unwrap();
assert!(slot.is_none());
*slot = Some(t);
drop(slot);
}
/// Polls this `Sender` half to detect whether the `Receiver` this has
/// paired with has gone away.
///
/// This function can be used to learn about when the `Receiver` (consumer)
/// half has gone away and nothing will be able to receive a message sent
/// from `complete`.
///
/// Like `Future::poll`, this function will panic if it's not called from
/// within the context of a task. In otherwords, this should only ever be
/// called from inside another future.
///
/// If `Ready` is returned then it means that the `Receiver` has disappeared
/// and the result this `Sender` would otherwise produce should no longer
/// be produced.
///
/// If `NotReady` is returned then the `Receiver` is still alive and may be
/// able to receive a message if sent. The current task, however, is
/// scheduled to receive a notification if the corresponding `Receiver` goes
/// away.
pub fn poll_cancel(&mut self) -> Poll<(), ()> {
// Fast path up first, just read the flag and see if our other half is
// gone. This flag is set both in our destructor and the oneshot
// destructor, but our destructor hasn't run yet so if it's set then the
// oneshot is gone.
if self.inner.complete.load(SeqCst) {
return Ok(Async::Ready(()))
}
// If our other half is not gone then we need to park our current task
// and move it into the `notify_cancel` slot to get notified when it's
// actually gone.
//
// If `try_lock` fails, then the `Receiver` is in the process of using
// it, so we can deduce that it's now in the process of going away and
// hence we're canceled. If it succeeds then we just store our handle.
//
// Crucially we then check `oneshot_gone` *again* before we return.
// While we were storing our handle inside `notify_cancel` the `Receiver`
// may have been dropped. The first thing it does is set the flag, and
// if it fails to acquire the lock it assumes that we'll see the flag
// later on. So... we then try to see the flag later on!
let handle = task::park();
match self.inner.tx_task.try_lock() {
Some(mut p) => *p = Some(handle),
None => return Ok(Async::Ready(())),
}
if self.inner.complete.load(SeqCst) {
Ok(Async::Ready(()))
} else {
Ok(Async::NotReady)
}
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// Flag that we're a completed `Sender` and try to wake up a receiver.
// Whether or not we actually stored any data will get picked up and
// translated to either an item or cancellation.
//
// Note that if we fail to acquire the `rx_task` lock then that means
// we're in one of two situations:
//
// 1. The receiver is trying to block in `poll`
// 2. The receiver is being dropped
//
// In the first case it'll check the `complete` flag after it's done
// blocking to see if it succeeded. In the latter case we don't need to
// wake up anyone anyway. So in both cases it's ok to ignore the `None`
// case of `try_lock` and bail out.
//
// The first case crucially depends on `Lock` using `SeqCst` ordering
// under the hood. If it instead used `Release` / `Acquire` ordering,
// then it would not necessarily synchronize with `inner.complete`
// and deadlock might be possible, as was observed in
// https://github.com/alexcrichton/futures-rs/pull/219.
self.inner.complete.store(true, SeqCst);
if let Some(mut slot) = self.inner.rx_task.try_lock() {
if let Some(task) = slot.take() {
drop(slot);
task.unpark();
}
}
}
}
/// Error returned from a `Receiver<T>` whenever the correponding `Sender<T>`
/// is dropped.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Canceled;
impl fmt::Display for Canceled {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result
|
}
impl Error for Canceled {
fn description(&self) -> &str {
"oneshot canceled"
}
}
impl<T> Receiver<T> {
/// Gracefully close this receiver, preventing sending any future messages.
///
/// Any `send` operation which happens after this method returns is
/// guaranteed to fail. Once this method is called the normal `poll` method
/// can be used to determine whether a message was actually sent or not. If
/// `Canceled` is returned from `poll` then no message was sent.
pub fn close(&mut self) {
// Flag our completion and then attempt to wake up the sender if it's
// blocked. See comments in `drop` below for more info
self.inner.complete.store(true, SeqCst);
if let Some(mut handle) = self.inner.tx_task.try_lock() {
if let Some(task) = handle.take() {
drop(handle);
task.unpark()
}
}
}
}
impl<T> Future for Receiver<T> {
type Item = T;
type Error = Canceled;
fn poll(&mut self) -> Poll<T, Canceled> {
let mut done = false;
// Check to see if some data has arrived. If it hasn't then we need to
// block our task.
//
// Note that the acquisition of the `rx_task` lock might fail below, but
// the only situation where this can happen is during `Sender::drop`
// when we are indeed completed already. If that's happening then we
// know we're completed so keep going.
if self.inner.complete.load(SeqCst) {
done = true;
} else {
let task = task::park();
match self.inner.rx_task.try_lock() {
Some(mut slot) => *slot = Some(task),
None => done = true,
}
}
// If we're `done` via one of the paths above, then look at the data and
// figure out what the answer is. If, however, we stored `rx_task`
// successfully above we need to check again if we're completed in case
// a message was sent while `rx_task` was locked and couldn't notify us
// otherwise.
//
// If we're not done, and we're not complete, though, then we've
// successfully blocked our task and we return `NotReady`.
if done || self.inner.complete.load(SeqCst) {
match self.inner.data.try_lock().unwrap().take() {
Some(data) => Ok(data.into()),
None => Err(Canceled),
}
} else {
Ok(Async::NotReady)
}
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
// Indicate to the `Sender` that we're done, so any future calls to
// `poll_cancel` are weeded out.
self.inner.complete.store(true, SeqCst);
// If we've blocked a task then there's no need for it to stick around,
// so we need to drop it. If this lock acquisition fails, though, then
// it's just because our `Sender` is trying to take the task, so we
// let them take care of that.
if let Some(mut slot) = self.inner.rx_task.try_lock() {
let task = slot.take();
drop(slot);
drop(task);
}
// Finally, if our `Sender` wants to get notified of us going away, it
// would have stored something in `tx_task`. Here we try to peel that
// out and unpark it.
//
// Note that the `try_lock` here may fail, but only if the `Sender` is
// in the process of filling in the task. If that happens then we
// already flagged `complete` and they'll pick that up above.
if let Some(mut handle) = self.inner.tx_task.try_lock() {
if let Some(task) = handle.take() {
drop(handle);
task.unpark()
}
}
}
}
|
{
write!(fmt, "oneshot canceled")
}
|
identifier_body
|
oneshot.rs
|
//! A one-shot, futures-aware channel
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::error::Error;
use std::fmt;
use {Future, Poll, Async};
use lock::Lock;
use task::{self, Task};
/// A future representing the completion of a computation happening elsewhere in
/// memory.
///
/// This is created by the `oneshot::channel` function.
#[must_use = "futures do nothing unless polled"]
pub struct Receiver<T> {
inner: Arc<Inner<T>>,
}
/// Represents the completion half of a oneshot through which the result of a
/// computation is signaled.
///
/// This is created by the `oneshot::channel` function.
pub struct Sender<T> {
inner: Arc<Inner<T>>,
}
/// Internal state of the `Receiver`/`Sender` pair above. This is all used as
/// the internal synchronization between the two for send/recv operations.
struct Inner<T> {
/// Indicates whether this oneshot is complete yet. This is filled in both
/// by `Sender::drop` and by `Receiver::drop`, and both sides iterpret it
/// appropriately.
///
/// For `Receiver`, if this is `true`, then it's guaranteed that `data` is
/// unlocked and ready to be inspected.
///
/// For `Sender` if this is `true` then the oneshot has gone away and it
/// can return ready from `poll_cancel`.
complete: AtomicBool,
/// The actual data being transferred as part of this `Receiver`. This is
/// filled in by `Sender::complete` and read by `Receiver::poll`.
///
/// Note that this is protected by `Lock`, but it is in theory safe to
/// replace with an `UnsafeCell` as it's actually protected by `complete`
/// above. I wouldn't recommend doing this, however, unless someone is
/// supremely confident in the various atomic orderings here and there.
data: Lock<Option<T>>,
/// Field to store the task which is blocked in `Receiver::poll`.
///
/// This is filled in when a oneshot is polled but not ready yet. Note that
/// the `Lock` here, unlike in `data` above, is important to resolve races.
/// Both the `Receiver` and the `Sender` halves understand that if they
/// can't acquire the lock then some important interference is happening.
rx_task: Lock<Option<Task>>,
/// Like `rx_task` above, except for the task blocked in
/// `Sender::poll_cancel`. Additionally, `Lock` cannot be `UnsafeCell`.
tx_task: Lock<Option<Task>>,
}
/// Creates a new futures-aware, one-shot channel.
///
/// This function is similar to Rust's channels found in the standard library.
/// Two halves are returned, the first of which is a `Sender` handle, used to
/// signal the end of a computation and provide its value. The second half is a
/// `Receiver` which implements the `Future` trait, resolving to the value that
/// was given to the `Sender` handle.
///
/// Each half can be separately owned and sent across threads/tasks.
///
/// # Examples
///
/// ```
/// use std::thread;
/// use futures::sync::oneshot;
/// use futures::*;
///
/// let (c, p) = oneshot::channel::<i32>();
///
/// thread::spawn(|| {
/// p.map(|i| {
/// println!("got: {}", i);
/// }).wait();
/// });
///
/// c.complete(3);
/// ```
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let inner = Arc::new(Inner {
complete: AtomicBool::new(false),
data: Lock::new(None),
rx_task: Lock::new(None),
tx_task: Lock::new(None),
});
let receiver = Receiver {
inner: inner.clone(),
};
let sender = Sender {
inner: inner,
};
(sender, receiver)
}
impl<T> Sender<T> {
/// Completes this oneshot with a successful result.
///
/// This function will consume `self` and indicate to the other end, the
/// `Receiver`, that the error provided is the result of the computation this
/// represents.
pub fn
|
(self, t: T) {
// First up, flag that this method was called and then store the data.
// Note that this lock acquisition should always succeed as it can only
// interfere with `poll` in `Receiver` which is only called when the
// `complete` flag is true, which we're setting here.
let mut slot = self.inner.data.try_lock().unwrap();
assert!(slot.is_none());
*slot = Some(t);
drop(slot);
}
/// Polls this `Sender` half to detect whether the `Receiver` this has
/// paired with has gone away.
///
/// This function can be used to learn about when the `Receiver` (consumer)
/// half has gone away and nothing will be able to receive a message sent
/// from `complete`.
///
/// Like `Future::poll`, this function will panic if it's not called from
/// within the context of a task. In otherwords, this should only ever be
/// called from inside another future.
///
/// If `Ready` is returned then it means that the `Receiver` has disappeared
/// and the result this `Sender` would otherwise produce should no longer
/// be produced.
///
/// If `NotReady` is returned then the `Receiver` is still alive and may be
/// able to receive a message if sent. The current task, however, is
/// scheduled to receive a notification if the corresponding `Receiver` goes
/// away.
pub fn poll_cancel(&mut self) -> Poll<(), ()> {
// Fast path up first, just read the flag and see if our other half is
// gone. This flag is set both in our destructor and the oneshot
// destructor, but our destructor hasn't run yet so if it's set then the
// oneshot is gone.
if self.inner.complete.load(SeqCst) {
return Ok(Async::Ready(()))
}
// If our other half is not gone then we need to park our current task
// and move it into the `notify_cancel` slot to get notified when it's
// actually gone.
//
// If `try_lock` fails, then the `Receiver` is in the process of using
// it, so we can deduce that it's now in the process of going away and
// hence we're canceled. If it succeeds then we just store our handle.
//
// Crucially we then check `oneshot_gone` *again* before we return.
// While we were storing our handle inside `notify_cancel` the `Receiver`
// may have been dropped. The first thing it does is set the flag, and
// if it fails to acquire the lock it assumes that we'll see the flag
// later on. So... we then try to see the flag later on!
let handle = task::park();
match self.inner.tx_task.try_lock() {
Some(mut p) => *p = Some(handle),
None => return Ok(Async::Ready(())),
}
if self.inner.complete.load(SeqCst) {
Ok(Async::Ready(()))
} else {
Ok(Async::NotReady)
}
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// Flag that we're a completed `Sender` and try to wake up a receiver.
// Whether or not we actually stored any data will get picked up and
// translated to either an item or cancellation.
//
// Note that if we fail to acquire the `rx_task` lock then that means
// we're in one of two situations:
//
// 1. The receiver is trying to block in `poll`
// 2. The receiver is being dropped
//
// In the first case it'll check the `complete` flag after it's done
// blocking to see if it succeeded. In the latter case we don't need to
// wake up anyone anyway. So in both cases it's ok to ignore the `None`
// case of `try_lock` and bail out.
//
// The first case crucially depends on `Lock` using `SeqCst` ordering
// under the hood. If it instead used `Release` / `Acquire` ordering,
// then it would not necessarily synchronize with `inner.complete`
// and deadlock might be possible, as was observed in
// https://github.com/alexcrichton/futures-rs/pull/219.
self.inner.complete.store(true, SeqCst);
if let Some(mut slot) = self.inner.rx_task.try_lock() {
if let Some(task) = slot.take() {
drop(slot);
task.unpark();
}
}
}
}
/// Error returned from a `Receiver<T>` whenever the correponding `Sender<T>`
/// is dropped.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Canceled;
impl fmt::Display for Canceled {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "oneshot canceled")
}
}
impl Error for Canceled {
fn description(&self) -> &str {
"oneshot canceled"
}
}
impl<T> Receiver<T> {
/// Gracefully close this receiver, preventing sending any future messages.
///
/// Any `send` operation which happens after this method returns is
/// guaranteed to fail. Once this method is called the normal `poll` method
/// can be used to determine whether a message was actually sent or not. If
/// `Canceled` is returned from `poll` then no message was sent.
pub fn close(&mut self) {
// Flag our completion and then attempt to wake up the sender if it's
// blocked. See comments in `drop` below for more info
self.inner.complete.store(true, SeqCst);
if let Some(mut handle) = self.inner.tx_task.try_lock() {
if let Some(task) = handle.take() {
drop(handle);
task.unpark()
}
}
}
}
impl<T> Future for Receiver<T> {
type Item = T;
type Error = Canceled;
fn poll(&mut self) -> Poll<T, Canceled> {
let mut done = false;
// Check to see if some data has arrived. If it hasn't then we need to
// block our task.
//
// Note that the acquisition of the `rx_task` lock might fail below, but
// the only situation where this can happen is during `Sender::drop`
// when we are indeed completed already. If that's happening then we
// know we're completed so keep going.
if self.inner.complete.load(SeqCst) {
done = true;
} else {
let task = task::park();
match self.inner.rx_task.try_lock() {
Some(mut slot) => *slot = Some(task),
None => done = true,
}
}
// If we're `done` via one of the paths above, then look at the data and
// figure out what the answer is. If, however, we stored `rx_task`
// successfully above we need to check again if we're completed in case
// a message was sent while `rx_task` was locked and couldn't notify us
// otherwise.
//
// If we're not done, and we're not complete, though, then we've
// successfully blocked our task and we return `NotReady`.
if done || self.inner.complete.load(SeqCst) {
match self.inner.data.try_lock().unwrap().take() {
Some(data) => Ok(data.into()),
None => Err(Canceled),
}
} else {
Ok(Async::NotReady)
}
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
// Indicate to the `Sender` that we're done, so any future calls to
// `poll_cancel` are weeded out.
self.inner.complete.store(true, SeqCst);
// If we've blocked a task then there's no need for it to stick around,
// so we need to drop it. If this lock acquisition fails, though, then
// it's just because our `Sender` is trying to take the task, so we
// let them take care of that.
if let Some(mut slot) = self.inner.rx_task.try_lock() {
let task = slot.take();
drop(slot);
drop(task);
}
// Finally, if our `Sender` wants to get notified of us going away, it
// would have stored something in `tx_task`. Here we try to peel that
// out and unpark it.
//
// Note that the `try_lock` here may fail, but only if the `Sender` is
// in the process of filling in the task. If that happens then we
// already flagged `complete` and they'll pick that up above.
if let Some(mut handle) = self.inner.tx_task.try_lock() {
if let Some(task) = handle.take() {
drop(handle);
task.unpark()
}
}
}
}
|
complete
|
identifier_name
|
semaphore.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.
#![unstable(feature = "std_misc",
reason = "the interaction between semaphores and the acquisition/release \
of resources is currently unclear")]
use ops::Drop;
use sync::{Mutex, Condvar};
/// A counting, blocking, semaphore.
///
/// Semaphores are a form of atomic counter where access is only granted if the
/// counter is a positive value. Each acquisition will block the calling thread
/// until the counter is positive, and each release will increment the counter
/// and unblock any threads if necessary.
///
/// # Examples
///
/// ```
/// use std::sync::Semaphore;
///
/// // Create a semaphore that represents 5 resources
/// let sem = Semaphore::new(5);
///
/// // Acquire one of the resources
/// sem.acquire();
///
/// // Acquire one of the resources for a limited period of time
/// {
/// let _guard = sem.access();
/// //...
/// } // resources is released here
///
/// // Release our initially acquired resource
/// sem.release();
/// ```
pub struct Semaphore {
lock: Mutex<int>,
cvar: Condvar,
}
/// An RAII guard which will release a resource acquired from a semaphore when
/// dropped.
pub struct SemaphoreGuard<'a> {
sem: &'a Semaphore,
}
impl Semaphore {
/// Creates a new semaphore with the initial count specified.
///
/// The count specified can be thought of as a number of resources, and a
/// call to `acquire` or `access` will block until at least one resource is
/// available. It is valid to initialize a semaphore with a negative count.
pub fn new(count: int) -> Semaphore {
Semaphore {
lock: Mutex::new(count),
cvar: Condvar::new(),
}
}
/// Acquires a resource of this semaphore, blocking the current thread until
/// it can do so.
///
/// This method will block until the internal count of the semaphore is at
/// least 1.
pub fn acquire(&self) {
let mut count = self.lock.lock().unwrap();
while *count <= 0 {
count = self.cvar.wait(count).unwrap();
}
*count -= 1;
}
/// Release a resource from this semaphore.
///
/// This will increment the number of resources in this semaphore by 1 and
/// will notify any pending waiters in `acquire` or `access` if necessary.
pub fn release(&self) {
*self.lock.lock().unwrap() += 1;
self.cvar.notify_one();
}
/// Acquires a resource of this semaphore, returning an RAII guard to
/// release the semaphore when dropped.
///
/// This function is semantically equivalent to an `acquire` followed by a
/// `release` when the guard returned is dropped.
pub fn access(&self) -> SemaphoreGuard {
self.acquire();
SemaphoreGuard { sem: self }
}
}
#[unsafe_destructor]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Drop for SemaphoreGuard<'a> {
fn drop(&mut self) {
self.sem.release();
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sync::Arc;
use super::Semaphore;
use sync::mpsc::channel;
use thread;
#[test]
fn test_sem_acquire_release() {
let s = Semaphore::new(1);
s.acquire();
s.release();
s.acquire();
}
#[test]
fn test_sem_basic() {
let s = Semaphore::new(1);
let _g = s.access();
}
#[test]
fn test_sem_as_mutex()
|
#[test]
fn test_sem_as_cvar() {
/* Child waits and parent signals */
let (tx, rx) = channel();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
let _t = thread::spawn(move|| {
s2.acquire();
tx.send(()).unwrap();
});
s.release();
let _ = rx.recv();
/* Parent waits and child signals */
let (tx, rx) = channel();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
let _t = thread::spawn(move|| {
s2.release();
let _ = rx.recv();
});
s.acquire();
tx.send(()).unwrap();
}
#[test]
fn test_sem_multi_resource() {
// Parent and child both get in the critical section at the same
// time, and shake hands.
let s = Arc::new(Semaphore::new(2));
let s2 = s.clone();
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
let _t = thread::spawn(move|| {
let _g = s2.access();
let _ = rx2.recv();
tx1.send(()).unwrap();
});
let _g = s.access();
tx2.send(()).unwrap();
rx1.recv().unwrap();
}
#[test]
fn test_sem_runtime_friendly_blocking() {
let s = Arc::new(Semaphore::new(1));
let s2 = s.clone();
let (tx, rx) = channel();
{
let _g = s.access();
thread::spawn(move|| {
tx.send(()).unwrap();
drop(s2.access());
tx.send(()).unwrap();
});
rx.recv().unwrap(); // wait for child to come alive
}
rx.recv().unwrap(); // wait for child to be done
}
}
|
{
let s = Arc::new(Semaphore::new(1));
let s2 = s.clone();
let _t = thread::spawn(move|| {
let _g = s2.access();
});
let _g = s.access();
}
|
identifier_body
|
semaphore.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.
#![unstable(feature = "std_misc",
reason = "the interaction between semaphores and the acquisition/release \
of resources is currently unclear")]
use ops::Drop;
use sync::{Mutex, Condvar};
/// A counting, blocking, semaphore.
///
/// Semaphores are a form of atomic counter where access is only granted if the
/// counter is a positive value. Each acquisition will block the calling thread
/// until the counter is positive, and each release will increment the counter
/// and unblock any threads if necessary.
///
/// # Examples
///
/// ```
/// use std::sync::Semaphore;
///
/// // Create a semaphore that represents 5 resources
/// let sem = Semaphore::new(5);
///
/// // Acquire one of the resources
/// sem.acquire();
///
/// // Acquire one of the resources for a limited period of time
/// {
/// let _guard = sem.access();
/// //...
/// } // resources is released here
///
/// // Release our initially acquired resource
/// sem.release();
/// ```
pub struct Semaphore {
lock: Mutex<int>,
cvar: Condvar,
}
/// An RAII guard which will release a resource acquired from a semaphore when
/// dropped.
pub struct SemaphoreGuard<'a> {
sem: &'a Semaphore,
}
impl Semaphore {
/// Creates a new semaphore with the initial count specified.
///
/// The count specified can be thought of as a number of resources, and a
/// call to `acquire` or `access` will block until at least one resource is
/// available. It is valid to initialize a semaphore with a negative count.
pub fn new(count: int) -> Semaphore {
Semaphore {
lock: Mutex::new(count),
cvar: Condvar::new(),
}
}
/// Acquires a resource of this semaphore, blocking the current thread until
/// it can do so.
///
/// This method will block until the internal count of the semaphore is at
/// least 1.
pub fn acquire(&self) {
let mut count = self.lock.lock().unwrap();
while *count <= 0 {
count = self.cvar.wait(count).unwrap();
}
*count -= 1;
}
/// Release a resource from this semaphore.
///
/// This will increment the number of resources in this semaphore by 1 and
/// will notify any pending waiters in `acquire` or `access` if necessary.
pub fn release(&self) {
*self.lock.lock().unwrap() += 1;
self.cvar.notify_one();
}
/// Acquires a resource of this semaphore, returning an RAII guard to
/// release the semaphore when dropped.
///
/// This function is semantically equivalent to an `acquire` followed by a
/// `release` when the guard returned is dropped.
pub fn access(&self) -> SemaphoreGuard {
self.acquire();
SemaphoreGuard { sem: self }
}
}
#[unsafe_destructor]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Drop for SemaphoreGuard<'a> {
fn drop(&mut self) {
self.sem.release();
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sync::Arc;
use super::Semaphore;
use sync::mpsc::channel;
use thread;
#[test]
fn test_sem_acquire_release() {
let s = Semaphore::new(1);
s.acquire();
s.release();
s.acquire();
}
#[test]
fn test_sem_basic() {
let s = Semaphore::new(1);
let _g = s.access();
}
#[test]
fn test_sem_as_mutex() {
let s = Arc::new(Semaphore::new(1));
let s2 = s.clone();
let _t = thread::spawn(move|| {
let _g = s2.access();
});
let _g = s.access();
}
#[test]
fn test_sem_as_cvar() {
/* Child waits and parent signals */
let (tx, rx) = channel();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
let _t = thread::spawn(move|| {
s2.acquire();
tx.send(()).unwrap();
});
s.release();
let _ = rx.recv();
/* Parent waits and child signals */
let (tx, rx) = channel();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
|
s2.release();
let _ = rx.recv();
});
s.acquire();
tx.send(()).unwrap();
}
#[test]
fn test_sem_multi_resource() {
// Parent and child both get in the critical section at the same
// time, and shake hands.
let s = Arc::new(Semaphore::new(2));
let s2 = s.clone();
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
let _t = thread::spawn(move|| {
let _g = s2.access();
let _ = rx2.recv();
tx1.send(()).unwrap();
});
let _g = s.access();
tx2.send(()).unwrap();
rx1.recv().unwrap();
}
#[test]
fn test_sem_runtime_friendly_blocking() {
let s = Arc::new(Semaphore::new(1));
let s2 = s.clone();
let (tx, rx) = channel();
{
let _g = s.access();
thread::spawn(move|| {
tx.send(()).unwrap();
drop(s2.access());
tx.send(()).unwrap();
});
rx.recv().unwrap(); // wait for child to come alive
}
rx.recv().unwrap(); // wait for child to be done
}
}
|
let _t = thread::spawn(move|| {
|
random_line_split
|
semaphore.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.
#![unstable(feature = "std_misc",
reason = "the interaction between semaphores and the acquisition/release \
of resources is currently unclear")]
use ops::Drop;
use sync::{Mutex, Condvar};
/// A counting, blocking, semaphore.
///
/// Semaphores are a form of atomic counter where access is only granted if the
/// counter is a positive value. Each acquisition will block the calling thread
/// until the counter is positive, and each release will increment the counter
/// and unblock any threads if necessary.
///
/// # Examples
///
/// ```
/// use std::sync::Semaphore;
///
/// // Create a semaphore that represents 5 resources
/// let sem = Semaphore::new(5);
///
/// // Acquire one of the resources
/// sem.acquire();
///
/// // Acquire one of the resources for a limited period of time
/// {
/// let _guard = sem.access();
/// //...
/// } // resources is released here
///
/// // Release our initially acquired resource
/// sem.release();
/// ```
pub struct Semaphore {
lock: Mutex<int>,
cvar: Condvar,
}
/// An RAII guard which will release a resource acquired from a semaphore when
/// dropped.
pub struct SemaphoreGuard<'a> {
sem: &'a Semaphore,
}
impl Semaphore {
/// Creates a new semaphore with the initial count specified.
///
/// The count specified can be thought of as a number of resources, and a
/// call to `acquire` or `access` will block until at least one resource is
/// available. It is valid to initialize a semaphore with a negative count.
pub fn new(count: int) -> Semaphore {
Semaphore {
lock: Mutex::new(count),
cvar: Condvar::new(),
}
}
/// Acquires a resource of this semaphore, blocking the current thread until
/// it can do so.
///
/// This method will block until the internal count of the semaphore is at
/// least 1.
pub fn acquire(&self) {
let mut count = self.lock.lock().unwrap();
while *count <= 0 {
count = self.cvar.wait(count).unwrap();
}
*count -= 1;
}
/// Release a resource from this semaphore.
///
/// This will increment the number of resources in this semaphore by 1 and
/// will notify any pending waiters in `acquire` or `access` if necessary.
pub fn release(&self) {
*self.lock.lock().unwrap() += 1;
self.cvar.notify_one();
}
/// Acquires a resource of this semaphore, returning an RAII guard to
/// release the semaphore when dropped.
///
/// This function is semantically equivalent to an `acquire` followed by a
/// `release` when the guard returned is dropped.
pub fn access(&self) -> SemaphoreGuard {
self.acquire();
SemaphoreGuard { sem: self }
}
}
#[unsafe_destructor]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Drop for SemaphoreGuard<'a> {
fn drop(&mut self) {
self.sem.release();
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sync::Arc;
use super::Semaphore;
use sync::mpsc::channel;
use thread;
#[test]
fn
|
() {
let s = Semaphore::new(1);
s.acquire();
s.release();
s.acquire();
}
#[test]
fn test_sem_basic() {
let s = Semaphore::new(1);
let _g = s.access();
}
#[test]
fn test_sem_as_mutex() {
let s = Arc::new(Semaphore::new(1));
let s2 = s.clone();
let _t = thread::spawn(move|| {
let _g = s2.access();
});
let _g = s.access();
}
#[test]
fn test_sem_as_cvar() {
/* Child waits and parent signals */
let (tx, rx) = channel();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
let _t = thread::spawn(move|| {
s2.acquire();
tx.send(()).unwrap();
});
s.release();
let _ = rx.recv();
/* Parent waits and child signals */
let (tx, rx) = channel();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
let _t = thread::spawn(move|| {
s2.release();
let _ = rx.recv();
});
s.acquire();
tx.send(()).unwrap();
}
#[test]
fn test_sem_multi_resource() {
// Parent and child both get in the critical section at the same
// time, and shake hands.
let s = Arc::new(Semaphore::new(2));
let s2 = s.clone();
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
let _t = thread::spawn(move|| {
let _g = s2.access();
let _ = rx2.recv();
tx1.send(()).unwrap();
});
let _g = s.access();
tx2.send(()).unwrap();
rx1.recv().unwrap();
}
#[test]
fn test_sem_runtime_friendly_blocking() {
let s = Arc::new(Semaphore::new(1));
let s2 = s.clone();
let (tx, rx) = channel();
{
let _g = s.access();
thread::spawn(move|| {
tx.send(()).unwrap();
drop(s2.access());
tx.send(()).unwrap();
});
rx.recv().unwrap(); // wait for child to come alive
}
rx.recv().unwrap(); // wait for child to be done
}
}
|
test_sem_acquire_release
|
identifier_name
|
table.rs
|
//! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256usize;
/// Table cipher
pub struct TableCipher {
table: [u8; TABLE_SIZE],
}
impl TableCipher {
pub fn new(key: &[u8], mode: CryptoMode) -> TableCipher {
let mut md5_digest = digest::with_type(DigestType::Md5);
md5_digest.update(key);
let mut key_digest = BytesMut::with_capacity(md5_digest.digest_len());
md5_digest.digest(&mut key_digest);
let mut bufr = Cursor::new(&key_digest[..]);
let a = bufr.read_u64::<LittleEndian>().unwrap();
let mut table = [0u64; TABLE_SIZE];
for (i, element) in table.iter_mut().enumerate() {
*element = i as u64;
}
for i in 1..1024 {
table.sort_by(|x, y| (a % (*x + i)).cmp(&(a % (*y + i))))
}
TableCipher {
table: match mode {
CryptoMode::Encrypt => {
let mut t = [0u8; TABLE_SIZE];
for i in 0..TABLE_SIZE {
t[i] = table[i] as u8;
}
t
}
CryptoMode::Decrypt => {
let mut t = [0u8; TABLE_SIZE];
for (idx, &item) in table.iter().enumerate() {
t[item as usize] = idx as u8;
}
t
}
},
}
}
fn process<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
let mut buf = BytesMut::with_capacity(self.buffer_size(data));
unsafe {
buf.set_len(self.buffer_size(data)); // Set length
}
for (idx, d) in data.iter().enumerate() {
buf[idx] = self.table[*d as usize];
}
out.put(buf);
Ok(())
}
}
impl StreamCipher for TableCipher {
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
self.process(data, out)
}
fn finalize<B: BufMut>(&mut self, _: &mut B) -> CipherResult<()>
|
fn buffer_size(&self, data: &[u8]) -> usize {
data.len()
}
}
#[test]
fn test_table_cipher() {
let message = "hello world";
let key = "keykeykk";
let mut enc = TableCipher::new(key.as_bytes(), CryptoMode::Encrypt);
let mut dec = TableCipher::new(key.as_bytes(), CryptoMode::Decrypt);
let mut encrypted_msg = Vec::new();
enc.update(message.as_bytes(), &mut encrypted_msg).unwrap();
let mut decrypted_msg = Vec::new();
dec.update(&encrypted_msg[..], &mut decrypted_msg).unwrap();
assert_eq!(&decrypted_msg[..], message.as_bytes());
}
|
{
Ok(())
}
|
identifier_body
|
table.rs
|
//! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256usize;
/// Table cipher
pub struct TableCipher {
table: [u8; TABLE_SIZE],
}
impl TableCipher {
pub fn new(key: &[u8], mode: CryptoMode) -> TableCipher {
let mut md5_digest = digest::with_type(DigestType::Md5);
md5_digest.update(key);
let mut key_digest = BytesMut::with_capacity(md5_digest.digest_len());
md5_digest.digest(&mut key_digest);
let mut bufr = Cursor::new(&key_digest[..]);
let a = bufr.read_u64::<LittleEndian>().unwrap();
let mut table = [0u64; TABLE_SIZE];
for (i, element) in table.iter_mut().enumerate() {
*element = i as u64;
}
for i in 1..1024 {
table.sort_by(|x, y| (a % (*x + i)).cmp(&(a % (*y + i))))
}
TableCipher {
table: match mode {
CryptoMode::Encrypt => {
let mut t = [0u8; TABLE_SIZE];
for i in 0..TABLE_SIZE {
t[i] = table[i] as u8;
}
t
}
CryptoMode::Decrypt => {
let mut t = [0u8; TABLE_SIZE];
for (idx, &item) in table.iter().enumerate() {
t[item as usize] = idx as u8;
}
t
}
},
}
}
fn process<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
let mut buf = BytesMut::with_capacity(self.buffer_size(data));
unsafe {
buf.set_len(self.buffer_size(data)); // Set length
}
for (idx, d) in data.iter().enumerate() {
buf[idx] = self.table[*d as usize];
}
out.put(buf);
Ok(())
}
}
impl StreamCipher for TableCipher {
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
self.process(data, out)
}
fn finalize<B: BufMut>(&mut self, _: &mut B) -> CipherResult<()> {
Ok(())
}
fn buffer_size(&self, data: &[u8]) -> usize {
data.len()
|
let message = "hello world";
let key = "keykeykk";
let mut enc = TableCipher::new(key.as_bytes(), CryptoMode::Encrypt);
let mut dec = TableCipher::new(key.as_bytes(), CryptoMode::Decrypt);
let mut encrypted_msg = Vec::new();
enc.update(message.as_bytes(), &mut encrypted_msg).unwrap();
let mut decrypted_msg = Vec::new();
dec.update(&encrypted_msg[..], &mut decrypted_msg).unwrap();
assert_eq!(&decrypted_msg[..], message.as_bytes());
}
|
}
}
#[test]
fn test_table_cipher() {
|
random_line_split
|
table.rs
|
//! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256usize;
/// Table cipher
pub struct TableCipher {
table: [u8; TABLE_SIZE],
}
impl TableCipher {
pub fn new(key: &[u8], mode: CryptoMode) -> TableCipher {
let mut md5_digest = digest::with_type(DigestType::Md5);
md5_digest.update(key);
let mut key_digest = BytesMut::with_capacity(md5_digest.digest_len());
md5_digest.digest(&mut key_digest);
let mut bufr = Cursor::new(&key_digest[..]);
let a = bufr.read_u64::<LittleEndian>().unwrap();
let mut table = [0u64; TABLE_SIZE];
for (i, element) in table.iter_mut().enumerate() {
*element = i as u64;
}
for i in 1..1024 {
table.sort_by(|x, y| (a % (*x + i)).cmp(&(a % (*y + i))))
}
TableCipher {
table: match mode {
CryptoMode::Encrypt =>
|
CryptoMode::Decrypt => {
let mut t = [0u8; TABLE_SIZE];
for (idx, &item) in table.iter().enumerate() {
t[item as usize] = idx as u8;
}
t
}
},
}
}
fn process<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
let mut buf = BytesMut::with_capacity(self.buffer_size(data));
unsafe {
buf.set_len(self.buffer_size(data)); // Set length
}
for (idx, d) in data.iter().enumerate() {
buf[idx] = self.table[*d as usize];
}
out.put(buf);
Ok(())
}
}
impl StreamCipher for TableCipher {
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
self.process(data, out)
}
fn finalize<B: BufMut>(&mut self, _: &mut B) -> CipherResult<()> {
Ok(())
}
fn buffer_size(&self, data: &[u8]) -> usize {
data.len()
}
}
#[test]
fn test_table_cipher() {
let message = "hello world";
let key = "keykeykk";
let mut enc = TableCipher::new(key.as_bytes(), CryptoMode::Encrypt);
let mut dec = TableCipher::new(key.as_bytes(), CryptoMode::Decrypt);
let mut encrypted_msg = Vec::new();
enc.update(message.as_bytes(), &mut encrypted_msg).unwrap();
let mut decrypted_msg = Vec::new();
dec.update(&encrypted_msg[..], &mut decrypted_msg).unwrap();
assert_eq!(&decrypted_msg[..], message.as_bytes());
}
|
{
let mut t = [0u8; TABLE_SIZE];
for i in 0..TABLE_SIZE {
t[i] = table[i] as u8;
}
t
}
|
conditional_block
|
table.rs
|
//! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256usize;
/// Table cipher
pub struct TableCipher {
table: [u8; TABLE_SIZE],
}
impl TableCipher {
pub fn
|
(key: &[u8], mode: CryptoMode) -> TableCipher {
let mut md5_digest = digest::with_type(DigestType::Md5);
md5_digest.update(key);
let mut key_digest = BytesMut::with_capacity(md5_digest.digest_len());
md5_digest.digest(&mut key_digest);
let mut bufr = Cursor::new(&key_digest[..]);
let a = bufr.read_u64::<LittleEndian>().unwrap();
let mut table = [0u64; TABLE_SIZE];
for (i, element) in table.iter_mut().enumerate() {
*element = i as u64;
}
for i in 1..1024 {
table.sort_by(|x, y| (a % (*x + i)).cmp(&(a % (*y + i))))
}
TableCipher {
table: match mode {
CryptoMode::Encrypt => {
let mut t = [0u8; TABLE_SIZE];
for i in 0..TABLE_SIZE {
t[i] = table[i] as u8;
}
t
}
CryptoMode::Decrypt => {
let mut t = [0u8; TABLE_SIZE];
for (idx, &item) in table.iter().enumerate() {
t[item as usize] = idx as u8;
}
t
}
},
}
}
fn process<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
let mut buf = BytesMut::with_capacity(self.buffer_size(data));
unsafe {
buf.set_len(self.buffer_size(data)); // Set length
}
for (idx, d) in data.iter().enumerate() {
buf[idx] = self.table[*d as usize];
}
out.put(buf);
Ok(())
}
}
impl StreamCipher for TableCipher {
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
self.process(data, out)
}
fn finalize<B: BufMut>(&mut self, _: &mut B) -> CipherResult<()> {
Ok(())
}
fn buffer_size(&self, data: &[u8]) -> usize {
data.len()
}
}
#[test]
fn test_table_cipher() {
let message = "hello world";
let key = "keykeykk";
let mut enc = TableCipher::new(key.as_bytes(), CryptoMode::Encrypt);
let mut dec = TableCipher::new(key.as_bytes(), CryptoMode::Decrypt);
let mut encrypted_msg = Vec::new();
enc.update(message.as_bytes(), &mut encrypted_msg).unwrap();
let mut decrypted_msg = Vec::new();
dec.update(&encrypted_msg[..], &mut decrypted_msg).unwrap();
assert_eq!(&decrypted_msg[..], message.as_bytes());
}
|
new
|
identifier_name
|
util.rs
|
// Copyright 2012-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.
use common::Config;
#[cfg(target_os = "windows")]
use std::env;
/// Conversion table from triple OS name to Rust SYSNAME
static OS_TABLE: &'static [(&'static str, &'static str)] = &[
("mingw32", "windows"),
("win32", "windows"),
("windows", "windows"),
("darwin", "macos"),
("android", "android"),
("linux", "linux"),
("freebsd", "freebsd"),
("dragonfly", "dragonfly"),
("openbsd", "openbsd"),
];
pub fn get_os(triple: &str) -> &'static str {
for &(triple_os, os) in OS_TABLE {
if triple.contains(triple_os)
|
}
panic!("Cannot determine OS from triple");
}
#[cfg(target_os = "windows")]
pub fn make_new_path(path: &str) -> String {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match env::var(lib_path_env_var()) {
Ok(curr) => {
format!("{}{}{}", path, path_div(), curr)
}
Err(..) => path.to_string()
}
}
#[cfg(target_os = "windows")]
pub fn lib_path_env_var() -> &'static str { "PATH" }
#[cfg(target_os = "windows")]
pub fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
|
{
return os
}
|
conditional_block
|
util.rs
|
// 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 common::Config;
#[cfg(target_os = "windows")]
use std::env;
/// Conversion table from triple OS name to Rust SYSNAME
static OS_TABLE: &'static [(&'static str, &'static str)] = &[
("mingw32", "windows"),
("win32", "windows"),
("windows", "windows"),
("darwin", "macos"),
("android", "android"),
("linux", "linux"),
("freebsd", "freebsd"),
("dragonfly", "dragonfly"),
("openbsd", "openbsd"),
];
pub fn get_os(triple: &str) -> &'static str {
for &(triple_os, os) in OS_TABLE {
if triple.contains(triple_os) {
return os
}
}
panic!("Cannot determine OS from triple");
}
#[cfg(target_os = "windows")]
pub fn make_new_path(path: &str) -> String {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match env::var(lib_path_env_var()) {
Ok(curr) => {
format!("{}{}{}", path, path_div(), curr)
}
Err(..) => path.to_string()
}
}
#[cfg(target_os = "windows")]
pub fn lib_path_env_var() -> &'static str { "PATH" }
#[cfg(target_os = "windows")]
pub fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
|
// Copyright 2012-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
|
random_line_split
|
|
util.rs
|
// Copyright 2012-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.
use common::Config;
#[cfg(target_os = "windows")]
use std::env;
/// Conversion table from triple OS name to Rust SYSNAME
static OS_TABLE: &'static [(&'static str, &'static str)] = &[
("mingw32", "windows"),
("win32", "windows"),
("windows", "windows"),
("darwin", "macos"),
("android", "android"),
("linux", "linux"),
("freebsd", "freebsd"),
("dragonfly", "dragonfly"),
("openbsd", "openbsd"),
];
pub fn get_os(triple: &str) -> &'static str {
for &(triple_os, os) in OS_TABLE {
if triple.contains(triple_os) {
return os
}
}
panic!("Cannot determine OS from triple");
}
#[cfg(target_os = "windows")]
pub fn make_new_path(path: &str) -> String
|
#[cfg(target_os = "windows")]
pub fn lib_path_env_var() -> &'static str { "PATH" }
#[cfg(target_os = "windows")]
pub fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
|
{
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match env::var(lib_path_env_var()) {
Ok(curr) => {
format!("{}{}{}", path, path_div(), curr)
}
Err(..) => path.to_string()
}
}
|
identifier_body
|
util.rs
|
// Copyright 2012-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.
use common::Config;
#[cfg(target_os = "windows")]
use std::env;
/// Conversion table from triple OS name to Rust SYSNAME
static OS_TABLE: &'static [(&'static str, &'static str)] = &[
("mingw32", "windows"),
("win32", "windows"),
("windows", "windows"),
("darwin", "macos"),
("android", "android"),
("linux", "linux"),
("freebsd", "freebsd"),
("dragonfly", "dragonfly"),
("openbsd", "openbsd"),
];
pub fn get_os(triple: &str) -> &'static str {
for &(triple_os, os) in OS_TABLE {
if triple.contains(triple_os) {
return os
}
}
panic!("Cannot determine OS from triple");
}
#[cfg(target_os = "windows")]
pub fn make_new_path(path: &str) -> String {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match env::var(lib_path_env_var()) {
Ok(curr) => {
format!("{}{}{}", path, path_div(), curr)
}
Err(..) => path.to_string()
}
}
#[cfg(target_os = "windows")]
pub fn
|
() -> &'static str { "PATH" }
#[cfg(target_os = "windows")]
pub fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
|
lib_path_env_var
|
identifier_name
|
chunking.rs
|
use serde::Deserialize;
use std::{
fmt,
fs::File,
io::{
BufReader,
BufWriter,
Read,
Write,
},
ops::Range,
path::{
Path,
PathBuf,
},
};
use anyhow::{
Context,
Result,
};
use serde::{
de::DeserializeOwned,
ser::Serialize,
};
use csv::Reader;
use itertools::Itertools;
use crate::psql::PsqlJsonIterator;
pub struct SingleChunk {
endpoints: Range<usize>,
filename: String,
}
#[derive(Debug, Deserialize)]
pub struct RawChunk {
filename: String,
start: usize,
stop: usize,
}
pub struct ChunkSpec {
ranges: Vec<SingleChunk>,
}
impl From<RawChunk> for SingleChunk {
fn from(raw: RawChunk) -> SingleChunk {
return Self {
endpoints: Range {
start: raw.start,
end: raw.stop + 1,
},
filename: raw.filename,
};
}
}
impl SingleChunk {
pub fn contains(&self, index: &usize) -> bool {
self.endpoints.contains(index)
}
}
impl ChunkSpec {
pub fn filename_of(&self, index: usize) -> Option<PathBuf> {
self.ranges
.iter()
.find(|r| r.contains(&index))
.map(|c: &SingleChunk| PathBuf::from(&c.filename))
}
}
pub fn load(filename: &Path) -> Result<ChunkSpec> {
let file = File::open(filename)
.with_context(|| format!("Could not open chunk file {:?}", &filename))?;
let reader = BufReader::new(file);
let mut records = Reader::from_reader(reader);
let mut ranges = Vec::new();
for result in records.deserialize() {
let entry: RawChunk = result?;
ranges.push(SingleChunk::from(entry));
}
Ok(ChunkSpec {
ranges,
})
}
pub fn write_splits<R: Read, T: DeserializeOwned + fmt::Debug + Serialize>(
iterator: PsqlJsonIterator<R, T>,
id_getter: fn(&T) -> usize,
chunks: &Path,
output: &Path,
) -> Result<()> {
|
let chunks = load(chunks)?;
let grouped = iterator.group_by(|entry: &T| {
chunks
.filename_of(id_getter(entry))
.ok_or(format!("Could not find filename for {:?}", &entry))
.unwrap()
});
for (filename, items) in &grouped {
let mut path = PathBuf::from(output);
path.push(filename);
let file = File::create(path)?;
let mut writer = BufWriter::new(file);
for item in items {
serde_json::to_writer(&mut writer, &item)?;
writeln!(&mut writer)?;
}
}
Ok(())
}
|
random_line_split
|
|
chunking.rs
|
use serde::Deserialize;
use std::{
fmt,
fs::File,
io::{
BufReader,
BufWriter,
Read,
Write,
},
ops::Range,
path::{
Path,
PathBuf,
},
};
use anyhow::{
Context,
Result,
};
use serde::{
de::DeserializeOwned,
ser::Serialize,
};
use csv::Reader;
use itertools::Itertools;
use crate::psql::PsqlJsonIterator;
pub struct SingleChunk {
endpoints: Range<usize>,
filename: String,
}
#[derive(Debug, Deserialize)]
pub struct RawChunk {
filename: String,
start: usize,
stop: usize,
}
pub struct ChunkSpec {
ranges: Vec<SingleChunk>,
}
impl From<RawChunk> for SingleChunk {
fn from(raw: RawChunk) -> SingleChunk {
return Self {
endpoints: Range {
start: raw.start,
end: raw.stop + 1,
},
filename: raw.filename,
};
}
}
impl SingleChunk {
pub fn contains(&self, index: &usize) -> bool {
self.endpoints.contains(index)
}
}
impl ChunkSpec {
pub fn filename_of(&self, index: usize) -> Option<PathBuf> {
self.ranges
.iter()
.find(|r| r.contains(&index))
.map(|c: &SingleChunk| PathBuf::from(&c.filename))
}
}
pub fn
|
(filename: &Path) -> Result<ChunkSpec> {
let file = File::open(filename)
.with_context(|| format!("Could not open chunk file {:?}", &filename))?;
let reader = BufReader::new(file);
let mut records = Reader::from_reader(reader);
let mut ranges = Vec::new();
for result in records.deserialize() {
let entry: RawChunk = result?;
ranges.push(SingleChunk::from(entry));
}
Ok(ChunkSpec {
ranges,
})
}
pub fn write_splits<R: Read, T: DeserializeOwned + fmt::Debug + Serialize>(
iterator: PsqlJsonIterator<R, T>,
id_getter: fn(&T) -> usize,
chunks: &Path,
output: &Path,
) -> Result<()> {
let chunks = load(chunks)?;
let grouped = iterator.group_by(|entry: &T| {
chunks
.filename_of(id_getter(entry))
.ok_or(format!("Could not find filename for {:?}", &entry))
.unwrap()
});
for (filename, items) in &grouped {
let mut path = PathBuf::from(output);
path.push(filename);
let file = File::create(path)?;
let mut writer = BufWriter::new(file);
for item in items {
serde_json::to_writer(&mut writer, &item)?;
writeln!(&mut writer)?;
}
}
Ok(())
}
|
load
|
identifier_name
|
chunking.rs
|
use serde::Deserialize;
use std::{
fmt,
fs::File,
io::{
BufReader,
BufWriter,
Read,
Write,
},
ops::Range,
path::{
Path,
PathBuf,
},
};
use anyhow::{
Context,
Result,
};
use serde::{
de::DeserializeOwned,
ser::Serialize,
};
use csv::Reader;
use itertools::Itertools;
use crate::psql::PsqlJsonIterator;
pub struct SingleChunk {
endpoints: Range<usize>,
filename: String,
}
#[derive(Debug, Deserialize)]
pub struct RawChunk {
filename: String,
start: usize,
stop: usize,
}
pub struct ChunkSpec {
ranges: Vec<SingleChunk>,
}
impl From<RawChunk> for SingleChunk {
fn from(raw: RawChunk) -> SingleChunk
|
}
impl SingleChunk {
pub fn contains(&self, index: &usize) -> bool {
self.endpoints.contains(index)
}
}
impl ChunkSpec {
pub fn filename_of(&self, index: usize) -> Option<PathBuf> {
self.ranges
.iter()
.find(|r| r.contains(&index))
.map(|c: &SingleChunk| PathBuf::from(&c.filename))
}
}
pub fn load(filename: &Path) -> Result<ChunkSpec> {
let file = File::open(filename)
.with_context(|| format!("Could not open chunk file {:?}", &filename))?;
let reader = BufReader::new(file);
let mut records = Reader::from_reader(reader);
let mut ranges = Vec::new();
for result in records.deserialize() {
let entry: RawChunk = result?;
ranges.push(SingleChunk::from(entry));
}
Ok(ChunkSpec {
ranges,
})
}
pub fn write_splits<R: Read, T: DeserializeOwned + fmt::Debug + Serialize>(
iterator: PsqlJsonIterator<R, T>,
id_getter: fn(&T) -> usize,
chunks: &Path,
output: &Path,
) -> Result<()> {
let chunks = load(chunks)?;
let grouped = iterator.group_by(|entry: &T| {
chunks
.filename_of(id_getter(entry))
.ok_or(format!("Could not find filename for {:?}", &entry))
.unwrap()
});
for (filename, items) in &grouped {
let mut path = PathBuf::from(output);
path.push(filename);
let file = File::create(path)?;
let mut writer = BufWriter::new(file);
for item in items {
serde_json::to_writer(&mut writer, &item)?;
writeln!(&mut writer)?;
}
}
Ok(())
}
|
{
return Self {
endpoints: Range {
start: raw.start,
end: raw.stop + 1,
},
filename: raw.filename,
};
}
|
identifier_body
|
htmlframeelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::htmlelement::HTMLElement;
use dom::windowproxy::WindowProxy;
pub struct HTMLFrameElement {
htmlelement: HTMLElement
}
impl HTMLFrameElement {
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Scrolling(&self) -> DOMString {
None
}
pub fn SetScrolling(&mut self, _scrolling: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Src(&self) -> DOMString {
None
}
pub fn SetSrc(&mut self, _src: &DOMString) -> ErrorResult {
Ok(())
}
pub fn FrameBorder(&self) -> DOMString {
None
}
pub fn SetFrameBorder(&mut self, _frameborder: &DOMString) -> ErrorResult {
Ok(())
}
pub fn LongDesc(&self) -> DOMString {
None
}
pub fn SetLongDesc(&mut self, _longdesc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn NoResize(&self) -> bool {
false
}
pub fn SetNoResize(&mut self, _no_resize: bool) -> ErrorResult {
Ok(())
}
pub fn GetContentDocument(&self) -> Option<AbstractDocument> {
None
}
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy>
|
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
}
|
{
None
}
|
identifier_body
|
htmlframeelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::htmlelement::HTMLElement;
use dom::windowproxy::WindowProxy;
pub struct HTMLFrameElement {
htmlelement: HTMLElement
}
impl HTMLFrameElement {
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Scrolling(&self) -> DOMString {
None
}
pub fn SetScrolling(&mut self, _scrolling: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Src(&self) -> DOMString {
None
}
pub fn SetSrc(&mut self, _src: &DOMString) -> ErrorResult {
Ok(())
}
pub fn FrameBorder(&self) -> DOMString {
None
}
pub fn SetFrameBorder(&mut self, _frameborder: &DOMString) -> ErrorResult {
Ok(())
}
pub fn LongDesc(&self) -> DOMString {
None
}
pub fn SetLongDesc(&mut self, _longdesc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn NoResize(&self) -> bool {
false
}
pub fn SetNoResize(&mut self, _no_resize: bool) -> ErrorResult {
Ok(())
}
pub fn GetContentDocument(&self) -> Option<AbstractDocument> {
None
|
}
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
}
|
}
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> {
None
|
random_line_split
|
htmlframeelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::htmlelement::HTMLElement;
use dom::windowproxy::WindowProxy;
pub struct HTMLFrameElement {
htmlelement: HTMLElement
}
impl HTMLFrameElement {
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Scrolling(&self) -> DOMString {
None
}
pub fn SetScrolling(&mut self, _scrolling: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Src(&self) -> DOMString {
None
}
pub fn SetSrc(&mut self, _src: &DOMString) -> ErrorResult {
Ok(())
}
pub fn FrameBorder(&self) -> DOMString {
None
}
pub fn SetFrameBorder(&mut self, _frameborder: &DOMString) -> ErrorResult {
Ok(())
}
pub fn LongDesc(&self) -> DOMString {
None
}
pub fn SetLongDesc(&mut self, _longdesc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn NoResize(&self) -> bool {
false
}
pub fn SetNoResize(&mut self, _no_resize: bool) -> ErrorResult {
Ok(())
}
pub fn
|
(&self) -> Option<AbstractDocument> {
None
}
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> {
None
}
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
}
|
GetContentDocument
|
identifier_name
|
checked_count_ones.rs
|
use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::integer::Integer;
///
/// assert_eq!(Integer::ZERO.checked_count_ones(), Some(0));
/// // 105 = 1101001b
/// assert_eq!(Integer::from(105).checked_count_ones(), Some(4));
/// assert_eq!(Integer::from(-105).checked_count_ones(), None);
/// // 10^12 = 1110100011010100101001010001000000000000b
/// assert_eq!(Integer::trillion().checked_count_ones(), Some(13));
/// ```
pub fn checked_count_ones(&self) -> Option<u64> {
if self.sign
|
else {
None
}
}
}
|
{
Some(self.abs.count_ones())
}
|
conditional_block
|
checked_count_ones.rs
|
use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::integer::Integer;
///
/// assert_eq!(Integer::ZERO.checked_count_ones(), Some(0));
/// // 105 = 1101001b
/// assert_eq!(Integer::from(105).checked_count_ones(), Some(4));
/// assert_eq!(Integer::from(-105).checked_count_ones(), None);
/// // 10^12 = 1110100011010100101001010001000000000000b
/// assert_eq!(Integer::trillion().checked_count_ones(), Some(13));
/// ```
pub fn
|
(&self) -> Option<u64> {
if self.sign {
Some(self.abs.count_ones())
} else {
None
}
}
}
|
checked_count_ones
|
identifier_name
|
checked_count_ones.rs
|
use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::integer::Integer;
///
/// assert_eq!(Integer::ZERO.checked_count_ones(), Some(0));
|
/// ```
pub fn checked_count_ones(&self) -> Option<u64> {
if self.sign {
Some(self.abs.count_ones())
} else {
None
}
}
}
|
/// // 105 = 1101001b
/// assert_eq!(Integer::from(105).checked_count_ones(), Some(4));
/// assert_eq!(Integer::from(-105).checked_count_ones(), None);
/// // 10^12 = 1110100011010100101001010001000000000000b
/// assert_eq!(Integer::trillion().checked_count_ones(), Some(13));
|
random_line_split
|
checked_count_ones.rs
|
use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use malachite_nz::integer::Integer;
///
/// assert_eq!(Integer::ZERO.checked_count_ones(), Some(0));
/// // 105 = 1101001b
/// assert_eq!(Integer::from(105).checked_count_ones(), Some(4));
/// assert_eq!(Integer::from(-105).checked_count_ones(), None);
/// // 10^12 = 1110100011010100101001010001000000000000b
/// assert_eq!(Integer::trillion().checked_count_ones(), Some(13));
/// ```
pub fn checked_count_ones(&self) -> Option<u64>
|
}
|
{
if self.sign {
Some(self.abs.count_ones())
} else {
None
}
}
|
identifier_body
|
unix_socket.rs
|
mod helper;
#[cfg(not(target_os = "windows"))]
mod tests {
use anyhow::Result;
use pretty_assertions::assert_eq;
use serde_cbor::de::from_slice;
use serde_cbor::ser::to_vec;
use tokio::task;
use pueue_lib::network::message::*;
use pueue_lib::network::protocol::*;
use super::*;
#[tokio::test]
/// This tests whether we can create a listener and client, that communicate via unix sockets.
async fn test_unix_socket() -> Result<()>
|
let mut client = get_client_stream(&shared_settings).await?;
// Create a client that sends a message and instantly receives it
send_message(message, &mut client).await?;
let response_bytes = receive_bytes(&mut client).await?;
let _message: Message = from_slice(&response_bytes)?;
assert_eq!(response_bytes, original_bytes);
Ok(())
}
}
|
{
better_panic::install();
let (shared_settings, _tempdir) = helper::get_shared_settings();
let listener = get_listener(&shared_settings).await?;
let message = create_success_message("This is a test");
let original_bytes = to_vec(&message).expect("Failed to serialize message.");
// Spawn a sub thread that:
// 1. Accepts a new connection
// 2. Reads a message
// 3. Sends the same message back
task::spawn(async move {
let mut stream = listener.accept().await.unwrap();
let message_bytes = receive_bytes(&mut stream).await.unwrap();
let message: Message = from_slice(&message_bytes).unwrap();
send_message(message, &mut stream).await.unwrap();
});
|
identifier_body
|
unix_socket.rs
|
mod helper;
#[cfg(not(target_os = "windows"))]
mod tests {
use anyhow::Result;
use pretty_assertions::assert_eq;
use serde_cbor::de::from_slice;
use serde_cbor::ser::to_vec;
use tokio::task;
use pueue_lib::network::message::*;
use pueue_lib::network::protocol::*;
use super::*;
#[tokio::test]
/// This tests whether we can create a listener and client, that communicate via unix sockets.
async fn
|
() -> Result<()> {
better_panic::install();
let (shared_settings, _tempdir) = helper::get_shared_settings();
let listener = get_listener(&shared_settings).await?;
let message = create_success_message("This is a test");
let original_bytes = to_vec(&message).expect("Failed to serialize message.");
// Spawn a sub thread that:
// 1. Accepts a new connection
// 2. Reads a message
// 3. Sends the same message back
task::spawn(async move {
let mut stream = listener.accept().await.unwrap();
let message_bytes = receive_bytes(&mut stream).await.unwrap();
let message: Message = from_slice(&message_bytes).unwrap();
send_message(message, &mut stream).await.unwrap();
});
let mut client = get_client_stream(&shared_settings).await?;
// Create a client that sends a message and instantly receives it
send_message(message, &mut client).await?;
let response_bytes = receive_bytes(&mut client).await?;
let _message: Message = from_slice(&response_bytes)?;
assert_eq!(response_bytes, original_bytes);
Ok(())
}
}
|
test_unix_socket
|
identifier_name
|
unix_socket.rs
|
mod helper;
#[cfg(not(target_os = "windows"))]
mod tests {
use anyhow::Result;
use pretty_assertions::assert_eq;
use serde_cbor::de::from_slice;
use serde_cbor::ser::to_vec;
use tokio::task;
use pueue_lib::network::message::*;
use pueue_lib::network::protocol::*;
use super::*;
#[tokio::test]
/// This tests whether we can create a listener and client, that communicate via unix sockets.
async fn test_unix_socket() -> Result<()> {
better_panic::install();
let (shared_settings, _tempdir) = helper::get_shared_settings();
let listener = get_listener(&shared_settings).await?;
let message = create_success_message("This is a test");
let original_bytes = to_vec(&message).expect("Failed to serialize message.");
// Spawn a sub thread that:
// 1. Accepts a new connection
// 2. Reads a message
// 3. Sends the same message back
task::spawn(async move {
let mut stream = listener.accept().await.unwrap();
let message_bytes = receive_bytes(&mut stream).await.unwrap();
let message: Message = from_slice(&message_bytes).unwrap();
send_message(message, &mut stream).await.unwrap();
});
let mut client = get_client_stream(&shared_settings).await?;
// Create a client that sends a message and instantly receives it
send_message(message, &mut client).await?;
let response_bytes = receive_bytes(&mut client).await?;
let _message: Message = from_slice(&response_bytes)?;
assert_eq!(response_bytes, original_bytes);
Ok(())
|
}
}
|
random_line_split
|
|
header.rs
|
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use common::ui::{UIWriter, UI};
use hcore::crypto::artifact;
use std::io::{self, Write};
|
use error::Result;
pub fn start(ui: &mut UI, src: &Path) -> Result<()> {
ui.begin(format!("Reading package header for {}", &src.display()))?;
ui.para("")?;
if let Ok(header) = artifact::get_artifact_header(src) {
io::stdout().write(format!("Package : {}\n", &src.display()).as_bytes())?;
io::stdout().write(format!("Format Version : {}\n", header.format_version).as_bytes())?;
io::stdout().write(format!("Key Name : {}\n", header.key_name).as_bytes())?;
io::stdout().write(format!("Hash Type : {}\n", header.hash_type).as_bytes())?;
io::stdout().write(format!("Raw Signature : {}\n", header.signature_raw).as_bytes())?;
} else {
ui.warn("Failed to read package header.")?;
}
Ok(())
}
|
random_line_split
|
|
header.rs
|
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use common::ui::{UIWriter, UI};
use hcore::crypto::artifact;
use std::io::{self, Write};
use error::Result;
pub fn
|
(ui: &mut UI, src: &Path) -> Result<()> {
ui.begin(format!("Reading package header for {}", &src.display()))?;
ui.para("")?;
if let Ok(header) = artifact::get_artifact_header(src) {
io::stdout().write(format!("Package : {}\n", &src.display()).as_bytes())?;
io::stdout().write(format!("Format Version : {}\n", header.format_version).as_bytes())?;
io::stdout().write(format!("Key Name : {}\n", header.key_name).as_bytes())?;
io::stdout().write(format!("Hash Type : {}\n", header.hash_type).as_bytes())?;
io::stdout().write(format!("Raw Signature : {}\n", header.signature_raw).as_bytes())?;
} else {
ui.warn("Failed to read package header.")?;
}
Ok(())
}
|
start
|
identifier_name
|
header.rs
|
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use common::ui::{UIWriter, UI};
use hcore::crypto::artifact;
use std::io::{self, Write};
use error::Result;
pub fn start(ui: &mut UI, src: &Path) -> Result<()> {
ui.begin(format!("Reading package header for {}", &src.display()))?;
ui.para("")?;
if let Ok(header) = artifact::get_artifact_header(src) {
io::stdout().write(format!("Package : {}\n", &src.display()).as_bytes())?;
io::stdout().write(format!("Format Version : {}\n", header.format_version).as_bytes())?;
io::stdout().write(format!("Key Name : {}\n", header.key_name).as_bytes())?;
io::stdout().write(format!("Hash Type : {}\n", header.hash_type).as_bytes())?;
io::stdout().write(format!("Raw Signature : {}\n", header.signature_raw).as_bytes())?;
} else
|
Ok(())
}
|
{
ui.warn("Failed to read package header.")?;
}
|
conditional_block
|
header.rs
|
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use common::ui::{UIWriter, UI};
use hcore::crypto::artifact;
use std::io::{self, Write};
use error::Result;
pub fn start(ui: &mut UI, src: &Path) -> Result<()>
|
{
ui.begin(format!("Reading package header for {}", &src.display()))?;
ui.para("")?;
if let Ok(header) = artifact::get_artifact_header(src) {
io::stdout().write(format!("Package : {}\n", &src.display()).as_bytes())?;
io::stdout().write(format!("Format Version : {}\n", header.format_version).as_bytes())?;
io::stdout().write(format!("Key Name : {}\n", header.key_name).as_bytes())?;
io::stdout().write(format!("Hash Type : {}\n", header.hash_type).as_bytes())?;
io::stdout().write(format!("Raw Signature : {}\n", header.signature_raw).as_bytes())?;
} else {
ui.warn("Failed to read package header.")?;
}
Ok(())
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.